]> granicus.if.org Git - postgresql/blob - src/backend/parser/gram.y
c19673fc42287e51b2646e69a9592a6f10ac8983
[postgresql] / src / backend / parser / gram.y
1 %{
2
3 /*#define YYDEBUG 1*/
4 /*-------------------------------------------------------------------------
5  *
6  * gram.y
7  *        POSTGRES SQL YACC rules/actions
8  *
9  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $Header: /cvsroot/pgsql/src/backend/parser/gram.y,v 2.389 2002/12/30 15:31:47 momjian Exp $
15  *
16  * HISTORY
17  *        AUTHOR                        DATE                    MAJOR EVENT
18  *        Andrew Yu                     Sept, 1994              POSTQUEL to SQL conversion
19  *        Andrew Yu                     Oct, 1994               lispy code conversion
20  *
21  * NOTES
22  *        CAPITALS are used to represent terminal symbols.
23  *        non-capitals are used to represent non-terminals.
24  *        SQL92-specific syntax is separated from plain SQL/Postgres syntax
25  *        to help isolate the non-extensible portions of the parser.
26  *
27  *        In general, nothing in this file should initiate database accesses
28  *        nor depend on changeable state (such as SET variables).  If you do
29  *        database accesses, your code will fail when we have aborted the
30  *        current transaction and are just parsing commands to find the next
31  *        ROLLBACK or COMMIT.  If you make use of SET variables, then you
32  *        will do the wrong thing in multi-query strings like this:
33  *                      SET SQL_inheritance TO off; SELECT * FROM foo;
34  *        because the entire string is parsed by gram.y before the SET gets
35  *        executed.  Anything that depends on the database or changeable state
36  *        should be handled inside parse_analyze() so that it happens at the
37  *        right time not the wrong time.  The handling of SQL_inheritance is
38  *        a good example.
39  *
40  * WARNINGS
41  *        If you use a list, make sure the datum is a node so that the printing
42  *        routines work.
43  *
44  *        Sometimes we assign constants to makeStrings. Make sure we don't free
45  *        those.
46  *
47  *-------------------------------------------------------------------------
48  */
49 #include "postgres.h"
50
51 #include <ctype.h>
52 #include <limits.h>
53
54 #include "access/htup.h"
55 #include "catalog/index.h"
56 #include "catalog/namespace.h"
57 #include "catalog/pg_type.h"
58 #include "nodes/makefuncs.h"
59 #include "nodes/params.h"
60 #include "nodes/parsenodes.h"
61 #include "parser/gramparse.h"
62 #include "storage/lmgr.h"
63 #include "utils/numeric.h"
64 #include "utils/datetime.h"
65 #include "utils/date.h"
66
67 extern List *parsetree;                 /* final parse result is delivered here */
68
69 static bool QueryIsRule = FALSE;
70
71 /*
72  * If you need access to certain yacc-generated variables and find that
73  * they're static by default, uncomment the next line.  (this is not a
74  * problem, yet.)
75  */
76 /*#define __YYSCLASS*/
77
78 static Node *makeTypeCast(Node *arg, TypeName *typename);
79 static Node *makeStringConst(char *str, TypeName *typename);
80 static Node *makeIntConst(int val);
81 static Node *makeFloatConst(char *str);
82 static Node *makeAConst(Value *v);
83 static Node *makeRowExpr(List *opr, List *largs, List *rargs);
84 static Node *makeDistinctExpr(List *largs, List *rargs);
85 static Node *makeRowNullTest(NullTestType test, List *args);
86 static DefElem *makeDefElem(char *name, Node *arg);
87 static A_Const *makeBoolConst(bool state);
88 static FuncCall *makeOverlaps(List *largs, List *rargs);
89 static SelectStmt *findLeftmostSelect(SelectStmt *node);
90 static void insertSelectOptions(SelectStmt *stmt,
91                                                                 List *sortClause, List *forUpdate,
92                                                                 Node *limitOffset, Node *limitCount);
93 static Node *makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg);
94 static Node *doNegate(Node *n);
95 static void doNegateFloat(Value *v);
96
97 %}
98
99
100 %union
101 {
102         int                                     ival;
103         char                            chr;
104         char                            *str;
105         const char                      *keyword;
106         bool                            boolean;
107         JoinType                        jtype;
108         DropBehavior            dbehavior;
109         OnCommitAction          oncommit;
110         List                            *list;
111         Node                            *node;
112         Value                           *value;
113         ColumnRef                       *columnref;
114
115         TypeName                        *typnam;
116         DefElem                         *defelt;
117         SortGroupBy                     *sortgroupby;
118         JoinExpr                        *jexpr;
119         IndexElem                       *ielem;
120         Alias                           *alias;
121         RangeVar                        *range;
122         A_Indices                       *aind;
123         ResTarget                       *target;
124         PrivTarget                      *privtarget;
125
126         InsertStmt                      *istmt;
127         VariableSetStmt         *vsetstmt;
128 }
129
130 %type <node>    stmt schema_stmt
131                 AlterDatabaseSetStmt AlterDomainStmt AlterGroupStmt
132                 AlterTableStmt AlterUserStmt AlterUserSetStmt
133                 AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt
134                 ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt
135                 CreateDomainStmt CreateGroupStmt CreateOpClassStmt CreatePLangStmt
136                 CreateSchemaStmt CreateSeqStmt CreateStmt
137                 CreateAssertStmt CreateTrigStmt CreateUserStmt
138                 CreatedbStmt CursorStmt DefineStmt DeleteStmt
139                 DropGroupStmt DropOpClassStmt DropPLangStmt DropStmt
140                 DropAssertStmt DropTrigStmt DropRuleStmt DropCastStmt
141                 DropUserStmt DropdbStmt ExplainStmt FetchStmt
142                 GrantStmt IndexStmt InsertStmt ListenStmt LoadStmt
143                 LockStmt NotifyStmt OptimizableStmt
144                 CreateFunctionStmt ReindexStmt RemoveAggrStmt
145                 RemoveFuncStmt RemoveOperStmt RenameStmt RevokeStmt
146                 RuleActionStmt RuleActionStmtOrEmpty RuleStmt
147                 SelectStmt TransactionStmt TruncateStmt
148                 UnlistenStmt UpdateStmt VacuumStmt
149                 VariableResetStmt VariableSetStmt VariableShowStmt
150                 ViewStmt CheckPointStmt CreateConversionStmt
151                 DeallocateStmt PrepareStmt ExecuteStmt
152
153 %type <node>    select_no_parens select_with_parens select_clause
154                                 simple_select
155
156 %type <node>    alter_column_default opclass_item
157 %type <ival>    add_drop
158
159 %type <dbehavior>       opt_drop_behavior
160
161 %type <list>    createdb_opt_list copy_opt_list
162 %type <defelt>  createdb_opt_item copy_opt_item
163
164 %type <ival>    opt_lock lock_type cast_context
165 %type <boolean> opt_force opt_or_replace
166
167 %type <list>    user_list
168
169 %type <list>    OptGroupList
170 %type <defelt>  OptGroupElem
171
172 %type <list>    OptUserList
173 %type <defelt>  OptUserElem
174
175 %type <str>             OptSchemaName
176 %type <list>    OptSchemaEltList
177
178 %type <boolean> TriggerActionTime TriggerForSpec opt_trusted
179 %type <str>             opt_lancompiler
180
181 %type <str>             TriggerEvents
182 %type <value>   TriggerFuncArg
183
184 %type <str>             relation_name copy_file_name
185                                 database_name access_method_clause access_method attr_name
186                                 index_name name function_name file_name
187
188 %type <list>    func_name handler_name qual_Op qual_all_Op OptUseOp
189                                 opt_class opt_validator
190
191 %type <range>   qualified_name OptConstrFromTable
192
193 %type <str>             opt_id  all_Op MathOp opt_name SpecialRuleRelation
194
195 %type <str>             iso_level opt_encoding
196 %type <node>    grantee
197 %type <list>    grantee_list
198 %type <ival>    privilege
199 %type <list>    privileges privilege_list
200 %type <privtarget> privilege_target
201 %type <node>    function_with_argtypes
202 %type <list>    function_with_argtypes_list
203 %type <chr>     TriggerOneEvent
204
205 %type <list>    stmtblock stmtmulti
206                                 OptTableElementList TableElementList OptInherit definition
207                                 opt_distinct opt_definition func_args
208                                 func_args_list func_as createfunc_opt_list
209                                 oper_argtypes RuleActionList RuleActionMulti
210                                 opt_column_list columnList opt_name_list
211                                 sort_clause opt_sort_clause sortby_list index_params
212                                 index_list name_list from_clause from_list opt_array_bounds
213                                 qualified_name_list any_name any_name_list
214                                 any_operator expr_list dotted_name attrs
215                                 target_list update_target_list insert_column_list
216                                 insert_target_list def_list opt_indirection
217                                 group_clause TriggerFuncArgs select_limit
218                                 opt_select_limit opclass_item_list trans_options
219                                 TableFuncElementList
220                                 prep_type_clause prep_type_list
221                                 execute_param_clause
222
223 %type <range>   into_clause OptTempTableName
224
225 %type <defelt>  createfunc_opt_item
226 %type <typnam>  func_arg func_return func_type aggr_argtype
227
228 %type <boolean> opt_arg TriggerForType OptTemp OptWithOids
229 %type <oncommit>        OnCommitOption
230
231 %type <list>    for_update_clause opt_for_update_clause update_list
232 %type <boolean> opt_all
233
234 %type <node>    join_outer join_qual
235 %type <jtype>   join_type
236
237 %type <list>    extract_list overlay_list position_list
238 %type <list>    substr_list trim_list
239 %type <ival>    opt_interval
240 %type <node>    overlay_placing substr_from substr_for
241
242 %type <boolean> opt_instead opt_cursor
243 %type <boolean> index_opt_unique opt_verbose opt_full
244 %type <boolean> opt_freeze opt_default opt_recheck
245 %type <defelt>  opt_binary opt_oids copy_delimiter
246
247 %type <boolean> copy_from
248
249 %type <ival>    direction reindex_type drop_type
250                                 opt_column event comment_type
251
252 %type <ival>    fetch_how_many
253
254 %type <node>    select_limit_value select_offset_value
255
256 %type <list>    OptSeqList
257 %type <defelt>  OptSeqElem
258
259 %type <istmt>   insert_rest
260
261 %type <vsetstmt> set_rest
262
263 %type <node>    TableElement ConstraintElem TableFuncElement
264 %type <node>    columnDef
265 %type <defelt>  def_elem
266 %type <node>    def_arg columnElem where_clause insert_column_item
267                                 a_expr b_expr c_expr r_expr AexprConst
268                                 in_expr having_clause func_table
269 %type <list>    row row_descriptor type_list
270 %type <node>    case_expr case_arg when_clause case_default
271 %type <list>    when_clause_list
272 %type <ival>    sub_type
273 %type <list>    OptCreateAs CreateAsList
274 %type <node>    CreateAsElement
275 %type <value>   NumericOnly FloatOnly IntegerOnly
276 %type <columnref>       columnref
277 %type <alias>   alias_clause
278 %type <sortgroupby>             sortby
279 %type <ielem>   index_elem func_index
280 %type <node>    table_ref
281 %type <jexpr>   joined_table
282 %type <range>   relation_expr
283 %type <target>  target_el insert_target_el update_target_el
284
285 %type <typnam>  Typename SimpleTypename ConstTypename
286                                 GenericType Numeric opt_float
287                                 Character ConstCharacter
288                                 CharacterWithLength CharacterWithoutLength
289                                 ConstDatetime ConstInterval
290                                 Bit ConstBit BitWithLength BitWithoutLength
291 %type <str>             character
292 %type <str>             extract_arg
293 %type <str>             opt_charset opt_collate
294 %type <ival>    opt_numeric opt_decimal
295 %type <boolean> opt_varying opt_timezone
296
297 %type <ival>    Iconst
298 %type <str>             Sconst comment_text
299 %type <str>             UserId opt_boolean ColId_or_Sconst
300 %type <list>    var_list var_list_or_default
301 %type <str>             ColId ColLabel type_name
302 %type <node>    var_value zone_value
303
304 %type <keyword> unreserved_keyword func_name_keyword
305 %type <keyword> col_name_keyword reserved_keyword
306
307 %type <node>    TableConstraint TableLikeClause
308 %type <list>    ColQualList
309 %type <node>    ColConstraint ColConstraintElem ConstraintAttr
310 %type <ival>    key_actions key_delete key_match key_update key_action
311 %type <ival>    ConstraintAttributeSpec ConstraintDeferrabilitySpec
312                                 ConstraintTimeSpec
313
314 %type <list>    constraints_set_list
315 %type <boolean> constraints_set_mode
316
317
318 /*
319  * If you make any token changes, update the keyword table in
320  * parser/keywords.c and add new keywords to the appropriate one of
321  * the reserved-or-not-so-reserved keyword lists, below.
322  */
323
324 /* ordinary key words in alphabetical order */
325 %token <keyword> ABORT_TRANS ABSOLUTE ACCESS ACTION ADD AFTER
326         AGGREGATE ALL ALTER ANALYSE ANALYZE AND ANY AS ASC
327         ASSERTION ASSIGNMENT AT AUTHORIZATION
328
329         BACKWARD BEFORE BEGIN_TRANS BETWEEN BIGINT BINARY BIT
330         BOOLEAN BOTH BY
331
332         CACHE CALLED CASCADE CASE CAST CHAIN CHAR_P
333         CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
334         CLUSTER COALESCE COLLATE COLUMN COMMENT COMMIT
335         COMMITTED CONSTRAINT CONSTRAINTS CONVERSION_P CONVERT COPY CREATE CREATEDB
336         CREATEUSER CROSS CURRENT_DATE CURRENT_TIME
337         CURRENT_TIMESTAMP CURRENT_USER CURSOR CYCLE
338
339         DATABASE DAY_P DEALLOCATE DEC DECIMAL DECLARE DEFAULT
340         DEFERRABLE DEFERRED DEFINER DELETE_P DELIMITER DELIMITERS
341     DESC DISTINCT DO DOMAIN_P DOUBLE DROP
342
343         EACH ELSE ENCODING ENCRYPTED END_TRANS ESCAPE EXCEPT
344         EXCLUSIVE EXECUTE EXISTS EXPLAIN EXTERNAL EXTRACT
345
346         FALSE_P FETCH FLOAT_P FOR FORCE FOREIGN FORWARD
347         FREEZE FROM FULL FUNCTION
348
349         GET GLOBAL GRANT GROUP_P
350
351         HANDLER HAVING HOUR_P
352
353         ILIKE IMMEDIATE IMMUTABLE IMPLICIT_P IN_P INCREMENT
354         INDEX INHERITS INITIALLY INNER_P INOUT INPUT
355         INSENSITIVE INSERT INSTEAD INT INTEGER INTERSECT
356         INTERVAL INTO INVOKER IS ISNULL ISOLATION
357
358         JOIN
359
360         KEY
361
362         LANCOMPILER LANGUAGE LAST LEADING LEFT LEVEL LIKE LIMIT
363         LISTEN LOAD LOCAL LOCALTIME LOCALTIMESTAMP LOCATION
364         LOCK_P
365
366         MATCH MAXVALUE MINUTE_P MINVALUE MODE MONTH_P MOVE
367
368         NAMES NATIONAL NATURAL NCHAR NEW NEXT NO NOCREATEDB
369         NOCREATEUSER NONE NOT NOTHING NOTIFY NOTNULL NULL_P
370         NULLIF NUMERIC
371
372         OF OFF OFFSET OIDS OLD ON ONLY OPERATOR OPTION OR
373         ORDER OUT_P OUTER_P OVERLAPS OVERLAY OWNER
374
375         PARTIAL PASSWORD PATH_P PENDANT PLACING POSITION
376         PRECISION PRESERVE PREPARE PRIMARY PRIOR PRIVILEGES PROCEDURAL
377     PROCEDURE
378
379         READ REAL RECHECK REFERENCES REINDEX RELATIVE RENAME REPLACE
380         RESET RESTRICT RETURNS REVOKE RIGHT ROLLBACK ROW ROWS
381         RULE
382
383         SCHEMA SCROLL SECOND_P SECURITY SELECT SEQUENCE
384         SERIALIZABLE SESSION SESSION_USER SET SETOF SHARE
385         SHOW SIMILAR SIMPLE SMALLINT SOME STABLE START STATEMENT
386         STATISTICS STDIN STDOUT STORAGE STRICT SUBSTRING
387         SYSID
388
389         TABLE TEMP TEMPLATE TEMPORARY THEN TIME TIMESTAMP
390         TO TOAST TRAILING TRANSACTION TREAT TRIGGER TRIM TRUE_P
391         TRUNCATE TRUSTED TYPE_P
392
393         UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNTIL
394         UPDATE USAGE USER USING
395
396         VACUUM VALID VALIDATOR VALUES VARCHAR VARYING
397         VERBOSE VERSION VIEW VOLATILE
398
399         WHEN WHERE WITH WITHOUT WORK WRITE
400
401         YEAR_P
402
403         ZONE
404
405 /* The grammar thinks these are keywords, but they are not in the keywords.c
406  * list and so can never be entered directly.  The filter in parser.c
407  * creates these tokens when required.
408  */
409 %token                  UNIONJOIN
410
411 /* Special keywords, not in the query language - see the "lex" file */
412 %token <str>    IDENT FCONST SCONST NCONST BCONST XCONST Op
413 %token <ival>   ICONST PARAM
414
415 /* these are not real. they are here so that they get generated as #define's*/
416 %token                  OP
417
418 /* precedence: lowest to highest */
419 %left           UNION EXCEPT
420 %left           INTERSECT
421 %left           OR
422 %left           AND
423 %right          NOT
424 %right          '='
425 %nonassoc       '<' '>'
426 %nonassoc       LIKE ILIKE SIMILAR
427 %nonassoc       ESCAPE
428 %nonassoc       OVERLAPS
429 %nonassoc       BETWEEN
430 %nonassoc       IN_P
431 %left           POSTFIXOP               /* dummy for postfix Op rules */
432 %left           Op OPERATOR             /* multi-character ops and user-defined operators */
433 %nonassoc       NOTNULL
434 %nonassoc       ISNULL
435 %nonassoc       IS NULL_P TRUE_P FALSE_P UNKNOWN /* sets precedence for IS NULL, etc */
436 %left           '+' '-'
437 %left           '*' '/' '%'
438 %left           '^'
439 /* Unary Operators */
440 %left           AT ZONE                 /* sets precedence for AT TIME ZONE */
441 %right          UMINUS
442 %left           '[' ']'
443 %left           '(' ')'
444 %left           COLLATE
445 %left           TYPECAST
446 %left           '.'
447 /*
448  * These might seem to be low-precedence, but actually they are not part
449  * of the arithmetic hierarchy at all in their use as JOIN operators.
450  * We make them high-precedence to support their use as function names.
451  * They wouldn't be given a precedence at all, were it not that we need
452  * left-associativity among the JOIN rules themselves.
453  */
454 %left           JOIN UNIONJOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
455 %%
456
457 /*
458  *      Handle comment-only lines, and ;; SELECT * FROM pg_class ;;;
459  *      psql already handles such cases, but other interfaces don't.
460  *      bjm 1999/10/05
461  */
462 stmtblock:      stmtmulti                                                               { parsetree = $1; }
463                 ;
464
465 /* the thrashing around here is to discard "empty" statements... */
466 stmtmulti:      stmtmulti ';' stmt
467                                 { if ($3 != (Node *)NULL)
468                                         $$ = lappend($1, $3);
469                                   else
470                                         $$ = $1;
471                                 }
472                         | stmt
473                                         { if ($1 != (Node *)NULL)
474                                                 $$ = makeList1($1);
475                                           else
476                                                 $$ = NIL;
477                                         }
478                 ;
479
480 stmt :
481                         AlterDatabaseSetStmt
482                         | AlterDomainStmt
483                         | AlterGroupStmt
484                         | AlterTableStmt
485                         | AlterUserStmt
486                         | AlterUserSetStmt
487                         | ClosePortalStmt
488                         | CopyStmt
489                         | CreateStmt
490                         | CreateAsStmt
491                         | CreateCastStmt
492                         | CreateDomainStmt
493                         | CreateFunctionStmt
494                         | CreateSchemaStmt
495                         | CreateGroupStmt
496                         | CreateSeqStmt
497                         | CreateOpClassStmt
498                         | CreatePLangStmt
499                         | CreateAssertStmt
500                         | CreateTrigStmt
501                         | CreateUserStmt
502                         | ClusterStmt
503                         | DeallocateStmt
504                         | DefineStmt
505                         | DropStmt
506                         | TruncateStmt
507                         | CommentStmt
508                         | DropCastStmt
509                         | DropGroupStmt
510                         | DropOpClassStmt
511                         | DropPLangStmt
512                         | DropAssertStmt
513                         | DropTrigStmt
514                         | DropRuleStmt
515                         | DropUserStmt
516                         | ExecuteStmt
517                         | ExplainStmt
518                         | FetchStmt
519                         | GrantStmt
520                         | IndexStmt
521                         | ListenStmt
522                         | UnlistenStmt
523                         | LockStmt
524                         | NotifyStmt
525                         | PrepareStmt
526                         | ReindexStmt
527                         | RemoveAggrStmt
528                         | RemoveOperStmt
529                         | RemoveFuncStmt
530                         | RenameStmt
531                         | RevokeStmt
532                         | OptimizableStmt
533                         | RuleStmt
534                         | TransactionStmt
535                         | ViewStmt
536                         | LoadStmt
537                         | CreatedbStmt
538                         | DropdbStmt
539                         | VacuumStmt
540                         | AnalyzeStmt
541                         | VariableSetStmt
542                         | VariableShowStmt
543                         | VariableResetStmt
544                         | ConstraintsSetStmt
545                         | CheckPointStmt
546                         | CreateConversionStmt
547                         | /*EMPTY*/
548                                 { $$ = (Node *)NULL; }
549                 ;
550
551 /*****************************************************************************
552  *
553  * Create a new Postgres DBMS user
554  *
555  *
556  *****************************************************************************/
557
558 CreateUserStmt:
559                         CREATE USER UserId opt_with OptUserList
560                                 {
561                                         CreateUserStmt *n = makeNode(CreateUserStmt);
562                                         n->user = $3;
563                                         n->options = $5;
564                                         $$ = (Node *)n;
565                                 }
566                 ;
567
568
569 opt_with:       WITH                                                                    {}
570                         | /*EMPTY*/                                                             {}
571                 ;
572
573 /*****************************************************************************
574  *
575  * Alter a postgresql DBMS user
576  *
577  *
578  *****************************************************************************/
579
580 AlterUserStmt:
581                         ALTER USER UserId opt_with OptUserList
582                                  {
583                                         AlterUserStmt *n = makeNode(AlterUserStmt);
584                                         n->user = $3;
585                                         n->options = $5;
586                                         $$ = (Node *)n;
587                                  }
588                 ;
589
590
591 AlterUserSetStmt:
592                         ALTER USER UserId SET set_rest
593                                 {
594                                         AlterUserSetStmt *n = makeNode(AlterUserSetStmt);
595                                         n->user = $3;
596                                         n->variable = $5->name;
597                                         n->value = $5->args;
598                                         $$ = (Node *)n;
599                                 }
600                         | ALTER USER UserId VariableResetStmt
601                                 {
602                                         AlterUserSetStmt *n = makeNode(AlterUserSetStmt);
603                                         n->user = $3;
604                                         n->variable = ((VariableResetStmt *)$4)->name;
605                                         n->value = NIL;
606                                         $$ = (Node *)n;
607                                 }
608                         ;
609
610
611 /*****************************************************************************
612  *
613  * Drop a postgresql DBMS user
614  *
615  * XXX Ideally this would have CASCADE/RESTRICT options, but since a user
616  * might own objects in multiple databases, there is presently no way to
617  * implement either cascading or restricting.  Caveat DBA.
618  *****************************************************************************/
619
620 DropUserStmt:
621                         DROP USER user_list
622                                 {
623                                         DropUserStmt *n = makeNode(DropUserStmt);
624                                         n->users = $3;
625                                         $$ = (Node *)n;
626                                 }
627                         ;
628
629 /*
630  * Options for CREATE USER and ALTER USER
631  */
632 OptUserList:
633                         OptUserList OptUserElem                                 { $$ = lappend($1, $2); }
634                         | /* EMPTY */                                                   { $$ = NIL; }
635                 ;
636
637 OptUserElem:
638                         PASSWORD Sconst
639                                 {
640                                         $$ = makeDefElem("password", (Node *)makeString($2));
641                                 }
642                         | ENCRYPTED PASSWORD Sconst
643                                 {
644                                         $$ = makeDefElem("encryptedPassword", (Node *)makeString($3));
645                                 }
646                         | UNENCRYPTED PASSWORD Sconst
647                                 {
648                                         $$ = makeDefElem("unencryptedPassword", (Node *)makeString($3));
649                                 }
650                         | SYSID Iconst
651                                 {
652                                         $$ = makeDefElem("sysid", (Node *)makeInteger($2));
653                                 }
654                         | CREATEDB
655                                 {
656                                         $$ = makeDefElem("createdb", (Node *)makeInteger(TRUE));
657                                 }
658                         | NOCREATEDB
659                                 {
660                                         $$ = makeDefElem("createdb", (Node *)makeInteger(FALSE));
661                                 }
662                         | CREATEUSER
663                                 {
664                                         $$ = makeDefElem("createuser", (Node *)makeInteger(TRUE));
665                                 }
666                         | NOCREATEUSER
667                                 {
668                                         $$ = makeDefElem("createuser", (Node *)makeInteger(FALSE));
669                                 }
670                         | IN_P GROUP_P user_list
671                                 {
672                                         $$ = makeDefElem("groupElts", (Node *)$3);
673                                 }
674                         | VALID UNTIL Sconst
675                                 {
676                                         $$ = makeDefElem("validUntil", (Node *)makeString($3));
677                                 }
678                 ;
679
680 user_list:      user_list ',' UserId            { $$ = lappend($1, makeString($3)); }
681                         | UserId                                        { $$ = makeList1(makeString($1)); }
682                 ;
683
684
685
686 /*****************************************************************************
687  *
688  * Create a postgresql group
689  *
690  *
691  *****************************************************************************/
692
693 CreateGroupStmt:
694                         CREATE GROUP_P UserId opt_with OptGroupList
695                                 {
696                                         CreateGroupStmt *n = makeNode(CreateGroupStmt);
697                                         n->name = $3;
698                                         n->options = $5;
699                                         $$ = (Node *)n;
700                                 }
701                 ;
702
703 /*
704  * Options for CREATE GROUP
705  */
706 OptGroupList:
707                         OptGroupList OptGroupElem                               { $$ = lappend($1, $2); }
708                         | /* EMPTY */                                                   { $$ = NIL; }
709                 ;
710
711 OptGroupElem:
712                         USER user_list
713                                 {
714                                         $$ = makeDefElem("userElts", (Node *)$2);
715                                 }
716                         | SYSID Iconst
717                                 {
718                                         $$ = makeDefElem("sysid", (Node *)makeInteger($2));
719                                 }
720                 ;
721
722
723 /*****************************************************************************
724  *
725  * Alter a postgresql group
726  *
727  *
728  *****************************************************************************/
729
730 AlterGroupStmt:
731                         ALTER GROUP_P UserId add_drop USER user_list
732                                 {
733                                         AlterGroupStmt *n = makeNode(AlterGroupStmt);
734                                         n->name = $3;
735                                         n->action = $4;
736                                         n->listUsers = $6;
737                                         $$ = (Node *)n;
738                                 }
739                 ;
740
741 add_drop:       ADD                                                                             { $$ = +1; }
742                         | DROP                                                                  { $$ = -1; }
743                 ;
744
745
746 /*****************************************************************************
747  *
748  * Drop a postgresql group
749  *
750  * XXX see above notes about cascading DROP USER; groups have same problem.
751  *****************************************************************************/
752
753 DropGroupStmt:
754                         DROP GROUP_P UserId
755                                 {
756                                         DropGroupStmt *n = makeNode(DropGroupStmt);
757                                         n->name = $3;
758                                         $$ = (Node *)n;
759                                 }
760                 ;
761
762
763 /*****************************************************************************
764  *
765  * Manipulate a schema
766  *
767  *****************************************************************************/
768
769 CreateSchemaStmt:
770                         CREATE SCHEMA OptSchemaName AUTHORIZATION UserId OptSchemaEltList
771                                 {
772                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
773                                         /* One can omit the schema name or the authorization id. */
774                                         if ($3 != NULL)
775                                                 n->schemaname = $3;
776                                         else
777                                                 n->schemaname = $5;
778                                         n->authid = $5;
779                                         n->schemaElts = $6;
780                                         $$ = (Node *)n;
781                                 }
782                         | CREATE SCHEMA ColId OptSchemaEltList
783                                 {
784                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
785                                         /* ...but not both */
786                                         n->schemaname = $3;
787                                         n->authid = NULL;
788                                         n->schemaElts = $4;
789                                         $$ = (Node *)n;
790                                 }
791                 ;
792
793 OptSchemaName:
794                         ColId                                                                   { $$ = $1; }
795                         | /* EMPTY */                                                   { $$ = NULL; }
796                 ;
797
798 OptSchemaEltList:
799                         OptSchemaEltList schema_stmt                    { $$ = lappend($1, $2); }
800                         | /* EMPTY */                                                   { $$ = NIL; }
801                 ;
802
803 /*
804  *      schema_stmt are the ones that can show up inside a CREATE SCHEMA
805  *      statement (in addition to by themselves).
806  */
807 schema_stmt:
808                         CreateStmt
809                         | GrantStmt
810                         | ViewStmt
811                 ;
812
813
814 /*****************************************************************************
815  *
816  * Set PG internal variable
817  *        SET name TO 'var_value'
818  * Include SQL92 syntax (thomas 1997-10-22):
819  *        SET TIME ZONE 'var_value'
820  *
821  *****************************************************************************/
822
823 VariableSetStmt:
824                         SET set_rest
825                                 {
826                                         VariableSetStmt *n = $2;
827                                         n->is_local = false;
828                                         $$ = (Node *) n;
829                                 }
830                         | SET LOCAL set_rest
831                                 {
832                                         VariableSetStmt *n = $3;
833                                         n->is_local = true;
834                                         $$ = (Node *) n;
835                                 }
836                         | SET SESSION set_rest
837                                 {
838                                         VariableSetStmt *n = $3;
839                                         n->is_local = false;
840                                         $$ = (Node *) n;
841                                 }
842                 ;
843
844 set_rest:  ColId TO var_list_or_default
845                                 {
846                                         VariableSetStmt *n = makeNode(VariableSetStmt);
847                                         n->name = $1;
848                                         n->args = $3;
849                                         $$ = n;
850                                 }
851                         | ColId '=' var_list_or_default
852                                 {
853                                         VariableSetStmt *n = makeNode(VariableSetStmt);
854                                         n->name = $1;
855                                         n->args = $3;
856                                         $$ = n;
857                                 }
858                         | TIME ZONE zone_value
859                                 {
860                                         VariableSetStmt *n = makeNode(VariableSetStmt);
861                                         n->name = "timezone";
862                                         if ($3 != NULL)
863                                                 n->args = makeList1($3);
864                                         $$ = n;
865                                 }
866                         | TRANSACTION ISOLATION LEVEL iso_level opt_mode
867                                 {
868                                         VariableSetStmt *n = makeNode(VariableSetStmt);
869                                         n->name = "TRANSACTION ISOLATION LEVEL";
870                                         n->args = makeList1(makeStringConst($4, NULL));
871                                         $$ = n;
872                                 }
873                         | SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL iso_level
874                                 {
875                                         VariableSetStmt *n = makeNode(VariableSetStmt);
876                                         n->name = "default_transaction_isolation";
877                                         n->args = makeList1(makeStringConst($7, NULL));
878                                         $$ = n;
879                                 }
880                         | NAMES opt_encoding
881                                 {
882                                         VariableSetStmt *n = makeNode(VariableSetStmt);
883                                         n->name = "client_encoding";
884                                         if ($2 != NULL)
885                                                 n->args = makeList1(makeStringConst($2, NULL));
886                                         $$ = n;
887                                 }
888                         | SESSION AUTHORIZATION ColId_or_Sconst
889                                 {
890                                         VariableSetStmt *n = makeNode(VariableSetStmt);
891                                         n->name = "session_authorization";
892                                         n->args = makeList1(makeStringConst($3, NULL));
893                                         $$ = n;
894                                 }
895                         | SESSION AUTHORIZATION DEFAULT
896                                 {
897                                         VariableSetStmt *n = makeNode(VariableSetStmt);
898                                         n->name = "session_authorization";
899                                         n->args = NIL;
900                                         $$ = n;
901                                 }
902                 ;
903
904 var_list_or_default:
905                         var_list                                                                { $$ = $1; }
906                         | DEFAULT                                                               { $$ = NIL; }
907                 ;
908
909 var_list:       var_value                                                               { $$ = makeList1($1); }
910                         | var_list ',' var_value                                { $$ = lappend($1, $3); }
911                 ;
912
913 var_value:      opt_boolean
914                                 { $$ = makeStringConst($1, NULL); }
915                         | ColId_or_Sconst
916                                 { $$ = makeStringConst($1, NULL); }
917                         | NumericOnly
918                                 { $$ = makeAConst($1); }
919                 ;
920
921 iso_level:      READ COMMITTED                                                  { $$ = "read committed"; }
922                         | SERIALIZABLE                                                  { $$ = "serializable"; }
923                 ;
924
925 opt_mode:  READ WRITE
926                                 {}
927                 | READ ONLY
928                                 {
929                                         elog(ERROR, "SET TRANSACTION/READ ONLY not yet supported");
930                                 }
931                 | /*EMPTY*/
932                                 {}
933                 ;
934
935 opt_boolean:
936                         TRUE_P                                                                  { $$ = "true"; }
937                         | FALSE_P                                                               { $$ = "false"; }
938                         | ON                                                                    { $$ = "on"; }
939                         | OFF                                                                   { $$ = "off"; }
940                 ;
941
942 /* Timezone values can be:
943  * - a string such as 'pst8pdt'
944  * - an identifier such as "pst8pdt"
945  * - an integer or floating point number
946  * - a time interval per SQL99
947  * ColId gives reduce/reduce errors against ConstInterval and LOCAL,
948  * so use IDENT and reject anything which is a reserved word.
949  */
950 zone_value:
951                         Sconst
952                                 {
953                                         $$ = makeStringConst($1, NULL);
954                                 }
955                         | IDENT
956                                 {
957                                         $$ = makeStringConst($1, NULL);
958                                 }
959                         | ConstInterval Sconst opt_interval
960                                 {
961                                         A_Const *n = (A_Const *) makeStringConst($2, $1);
962                                         if ($3 != INTERVAL_FULL_RANGE)
963                                         {
964                                                 if (($3 & ~(INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE))) != 0)
965                                                         elog(ERROR,
966                                                                  "Time zone interval"
967                                                                  " must be HOUR or HOUR TO MINUTE");
968                                                 n->typename->typmod = INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION, $3);
969                                         }
970                                         $$ = (Node *)n;
971                                 }
972                         | ConstInterval '(' Iconst ')' Sconst opt_interval
973                                 {
974                                         A_Const *n = (A_Const *) makeStringConst($5, $1);
975                                         if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
976                                                 elog(ERROR,
977                                                         "INTERVAL(%d) precision must be between %d and %d",
978                                                         $3, 0, MAX_INTERVAL_PRECISION);
979
980                                         if (($6 != INTERVAL_FULL_RANGE)
981                                                 && (($6 & ~(INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE))) != 0))
982                                                 elog(ERROR,
983                                                          "Time zone interval"
984                                                          " must be HOUR or HOUR TO MINUTE");
985
986                                         n->typename->typmod = INTERVAL_TYPMOD($3, $6);
987
988                                         $$ = (Node *)n;
989                                 }
990                         | NumericOnly                                                   { $$ = makeAConst($1); }
991                         | DEFAULT                                                               { $$ = NULL; }
992                         | LOCAL                                                                 { $$ = NULL; }
993                 ;
994
995 opt_encoding:
996                         Sconst                                                                  { $$ = $1; }
997                         | DEFAULT                                                               { $$ = NULL; }
998                         | /*EMPTY*/                                                             { $$ = NULL; }
999                 ;
1000
1001 ColId_or_Sconst:
1002                         ColId                                                                   { $$ = $1; }
1003                         | SCONST                                                                { $$ = $1; }
1004                 ;
1005
1006
1007 VariableShowStmt:
1008                         SHOW ColId
1009                                 {
1010                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1011                                         n->name = $2;
1012                                         $$ = (Node *) n;
1013                                 }
1014                         | SHOW TIME ZONE
1015                                 {
1016                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1017                                         n->name = "timezone";
1018                                         $$ = (Node *) n;
1019                                 }
1020                         | SHOW TRANSACTION ISOLATION LEVEL
1021                                 {
1022                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1023                                         n->name = "TRANSACTION ISOLATION LEVEL";
1024                                         $$ = (Node *) n;
1025                                 }
1026                         | SHOW SESSION AUTHORIZATION
1027                                 {
1028                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1029                                         n->name = "session_authorization";
1030                                         $$ = (Node *) n;
1031                                 }
1032                         | SHOW ALL
1033                                 {
1034                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1035                                         n->name = "all";
1036                                         $$ = (Node *) n;
1037                                 }
1038                 ;
1039
1040 VariableResetStmt:
1041                         RESET ColId
1042                                 {
1043                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1044                                         n->name = $2;
1045                                         $$ = (Node *) n;
1046                                 }
1047                         | RESET TIME ZONE
1048                                 {
1049                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1050                                         n->name = "timezone";
1051                                         $$ = (Node *) n;
1052                                 }
1053                         | RESET TRANSACTION ISOLATION LEVEL
1054                                 {
1055                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1056                                         n->name = "TRANSACTION ISOLATION LEVEL";
1057                                         $$ = (Node *) n;
1058                                 }
1059                         | RESET SESSION AUTHORIZATION
1060                                 {
1061                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1062                                         n->name = "session_authorization";
1063                                         $$ = (Node *) n;
1064                                 }
1065                         | RESET ALL
1066                                 {
1067                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1068                                         n->name = "all";
1069                                         $$ = (Node *) n;
1070                                 }
1071                 ;
1072
1073
1074 ConstraintsSetStmt:
1075                         SET CONSTRAINTS constraints_set_list constraints_set_mode
1076                                 {
1077                                         ConstraintsSetStmt *n = makeNode(ConstraintsSetStmt);
1078                                         n->constraints = $3;
1079                                         n->deferred    = $4;
1080                                         $$ = (Node *) n;
1081                                 }
1082                 ;
1083
1084 constraints_set_list:
1085                         ALL                                                                             { $$ = NIL; }
1086                         | name_list                                                             { $$ = $1; }
1087                 ;
1088
1089 constraints_set_mode:
1090                         DEFERRED                                                                { $$ = TRUE; }
1091                         | IMMEDIATE                                                             { $$ = FALSE; }
1092                 ;
1093
1094
1095 /*
1096  * Checkpoint statement
1097  */
1098 CheckPointStmt:
1099                         CHECKPOINT
1100                                 {
1101                                         CheckPointStmt *n = makeNode(CheckPointStmt);
1102                                         $$ = (Node *)n;
1103                                 }
1104                 ;
1105
1106
1107 /*****************************************************************************
1108  *
1109  *      ALTER TABLE variations
1110  *
1111  *****************************************************************************/
1112
1113 AlterTableStmt:
1114                         /* ALTER TABLE <relation> ADD [COLUMN] <coldef> */
1115                         ALTER TABLE relation_expr ADD opt_column columnDef
1116                                 {
1117                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1118                                         n->subtype = 'A';
1119                                         n->relation = $3;
1120                                         n->def = $6;
1121                                         $$ = (Node *)n;
1122                                 }
1123                         /* ALTER TABLE <relation> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
1124                         | ALTER TABLE relation_expr ALTER opt_column ColId alter_column_default
1125                                 {
1126                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1127                                         n->subtype = 'T';
1128                                         n->relation = $3;
1129                                         n->name = $6;
1130                                         n->def = $7;
1131                                         $$ = (Node *)n;
1132                                 }
1133                         /* ALTER TABLE <relation> ALTER [COLUMN] <colname> DROP NOT NULL */
1134                         | ALTER TABLE relation_expr ALTER opt_column ColId DROP NOT NULL_P
1135                                 {
1136                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1137                                         n->subtype = 'N';
1138                                         n->relation = $3;
1139                                         n->name = $6;
1140                                         $$ = (Node *)n;
1141                                 }
1142                         /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET NOT NULL */
1143                         | ALTER TABLE relation_expr ALTER opt_column ColId SET NOT NULL_P
1144                                 {
1145                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1146                                         n->subtype = 'O';
1147                                         n->relation = $3;
1148                                         n->name = $6;
1149                                         $$ = (Node *)n;
1150                                 }
1151                         /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STATISTICS <IntegerOnly> */
1152                         | ALTER TABLE relation_expr ALTER opt_column ColId SET STATISTICS IntegerOnly
1153                                 {
1154                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1155                                         n->subtype = 'S';
1156                                         n->relation = $3;
1157                                         n->name = $6;
1158                                         n->def = (Node *) $9;
1159                                         $$ = (Node *)n;
1160                                 }
1161                         /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STORAGE <storagemode> */
1162                         | ALTER TABLE relation_expr ALTER opt_column ColId
1163                         SET STORAGE ColId
1164                                 {
1165                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1166                                         n->subtype = 'M';
1167                                         n->relation = $3;
1168                                         n->name = $6;
1169                                         n->def = (Node *) makeString($9);
1170                                         $$ = (Node *)n;
1171                                 }
1172                         /* ALTER TABLE <relation> DROP [COLUMN] <colname> [RESTRICT|CASCADE] */
1173                         | ALTER TABLE relation_expr DROP opt_column ColId opt_drop_behavior
1174                                 {
1175                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1176                                         n->subtype = 'D';
1177                                         n->relation = $3;
1178                                         n->name = $6;
1179                                         n->behavior = $7;
1180                                         $$ = (Node *)n;
1181                                 }
1182                         /* ALTER TABLE <relation> ADD CONSTRAINT ... */
1183                         | ALTER TABLE relation_expr ADD TableConstraint
1184                                 {
1185                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1186                                         n->subtype = 'C';
1187                                         n->relation = $3;
1188                                         n->def = $5;
1189                                         $$ = (Node *)n;
1190                                 }
1191                         /* ALTER TABLE <relation> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
1192                         | ALTER TABLE relation_expr DROP CONSTRAINT name opt_drop_behavior
1193                                 {
1194                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1195                                         n->subtype = 'X';
1196                                         n->relation = $3;
1197                                         n->name = $6;
1198                                         n->behavior = $7;
1199                                         $$ = (Node *)n;
1200                                 }
1201                         /* ALTER TABLE <name> CREATE TOAST TABLE */
1202                         | ALTER TABLE qualified_name CREATE TOAST TABLE
1203                                 {
1204                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1205                                         n->subtype = 'E';
1206                                         $3->inhOpt = INH_NO;
1207                                         n->relation = $3;
1208                                         $$ = (Node *)n;
1209                                 }
1210                         /* ALTER TABLE <name> OWNER TO UserId */
1211                         | ALTER TABLE qualified_name OWNER TO UserId
1212                                 {
1213                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1214                                         n->subtype = 'U';
1215                                         $3->inhOpt = INH_NO;
1216                                         n->relation = $3;
1217                                         n->name = $6;
1218                                         $$ = (Node *)n;
1219                                 }
1220                 ;
1221
1222 alter_column_default:
1223                         SET DEFAULT a_expr
1224                                 {
1225                                         /* Treat SET DEFAULT NULL the same as DROP DEFAULT */
1226                                         if (exprIsNullConstant($3))
1227                                                 $$ = NULL;
1228                                         else
1229                                                 $$ = $3;
1230                                 }
1231                         | DROP DEFAULT                                  { $$ = NULL; }
1232                 ;
1233
1234 opt_drop_behavior:
1235                         CASCADE                                         { $$ = DROP_CASCADE; }
1236                         | RESTRICT                                      { $$ = DROP_RESTRICT; }
1237                         | /* EMPTY */                           { $$ = DROP_RESTRICT; /* default */ }
1238                 ;
1239
1240
1241
1242 /*****************************************************************************
1243  *
1244  *              QUERY :
1245  *                              close <optname>
1246  *
1247  *****************************************************************************/
1248
1249 ClosePortalStmt:
1250                         CLOSE opt_id
1251                                 {
1252                                         ClosePortalStmt *n = makeNode(ClosePortalStmt);
1253                                         n->portalname = $2;
1254                                         $$ = (Node *)n;
1255                                 }
1256                 ;
1257
1258 opt_id:         ColId                                                                   { $$ = $1; }
1259                         | /*EMPTY*/                                                             { $$ = NULL; }
1260                 ;
1261
1262
1263 /*****************************************************************************
1264  *
1265  *              QUERY :
1266  *                              COPY <relname> ['(' columnList ')'] FROM/TO [WITH options]
1267  *
1268  *                              BINARY, OIDS, and DELIMITERS kept in old locations
1269  *                              for backward compatibility.  2002-06-18
1270  *
1271  *****************************************************************************/
1272
1273 CopyStmt:       COPY opt_binary qualified_name opt_column_list opt_oids
1274                         copy_from copy_file_name copy_delimiter opt_with copy_opt_list
1275                                 {
1276                                         CopyStmt *n = makeNode(CopyStmt);
1277                                         n->relation = $3;
1278                                         n->attlist = $4;
1279                                         n->is_from = $6;
1280                                         n->filename = $7;
1281
1282                                         n->options = NIL;
1283                                         /* Concatenate user-supplied flags */
1284                                         if ($2)
1285                                                 n->options = lappend(n->options, $2);
1286                                         if ($5)
1287                                                 n->options = lappend(n->options, $5);
1288                                         if ($8)
1289                                                 n->options = lappend(n->options, $8);
1290                                         if ($10)
1291                                                 n->options = nconc(n->options, $10);
1292                                         $$ = (Node *)n;
1293                                 }
1294                 ;
1295
1296 copy_from:
1297                         FROM                                                                    { $$ = TRUE; }
1298                         | TO                                                                    { $$ = FALSE; }
1299                 ;
1300
1301 /*
1302  * copy_file_name NULL indicates stdio is used. Whether stdin or stdout is
1303  * used depends on the direction. (It really doesn't make sense to copy from
1304  * stdout. We silently correct the "typo".               - AY 9/94
1305  */
1306 copy_file_name:
1307                         Sconst                                                                  { $$ = $1; }
1308                         | STDIN                                                                 { $$ = NULL; }
1309                         | STDOUT                                                                { $$ = NULL; }
1310                 ;
1311
1312
1313
1314 copy_opt_list:
1315                         copy_opt_list copy_opt_item                             { $$ = lappend($1, $2); }
1316                         | /* EMPTY */                                                   { $$ = NIL; }
1317                 ;
1318
1319
1320 copy_opt_item:
1321                         BINARY
1322                                 {
1323                                         $$ = makeDefElem("binary", (Node *)makeInteger(TRUE));
1324                                 }
1325                         | OIDS
1326                                 {
1327                                         $$ = makeDefElem("oids", (Node *)makeInteger(TRUE));
1328                                 }
1329                         | DELIMITER opt_as Sconst
1330                                 {
1331                                         $$ = makeDefElem("delimiter", (Node *)makeString($3));
1332                                 }
1333                         | NULL_P opt_as Sconst
1334                                 {
1335                                         $$ = makeDefElem("null", (Node *)makeString($3));
1336                                 }
1337                 ;
1338
1339 /* The following exist for backward compatibility */
1340
1341 opt_binary:
1342                         BINARY
1343                                 {
1344                                         $$ = makeDefElem("binary", (Node *)makeInteger(TRUE));
1345                                 }
1346                         | /*EMPTY*/                                                             { $$ = NULL; }
1347                 ;
1348
1349 opt_oids:
1350                         WITH OIDS
1351                                 {
1352                                         $$ = makeDefElem("oids", (Node *)makeInteger(TRUE));
1353                                 }
1354                         | /*EMPTY*/                                                             { $$ = NULL; }
1355                 ;
1356
1357 copy_delimiter:
1358                         /* USING DELIMITERS kept for backward compatibility. 2002-06-15 */
1359                         opt_using DELIMITERS Sconst
1360                                 {
1361                                         $$ = makeDefElem("delimiter", (Node *)makeString($3));
1362                                 }
1363                         | /*EMPTY*/                                                             { $$ = NULL; }
1364                 ;
1365
1366 opt_using:
1367                         USING                                                                   {}
1368                         | /*EMPTY*/                                                             {}
1369                 ;
1370
1371
1372 /*****************************************************************************
1373  *
1374  *              QUERY :
1375  *                              CREATE TABLE relname
1376  *
1377  *****************************************************************************/
1378
1379 CreateStmt:     CREATE OptTemp TABLE qualified_name '(' OptTableElementList ')'
1380                         OptInherit OptWithOids OnCommitOption
1381                                 {
1382                                         CreateStmt *n = makeNode(CreateStmt);
1383                                         $4->istemp = $2;
1384                                         n->relation = $4;
1385                                         n->tableElts = $6;
1386                                         n->inhRelations = $8;
1387                                         n->constraints = NIL;
1388                                         n->hasoids = $9;
1389                                         n->oncommit = $10;
1390                                         $$ = (Node *)n;
1391                                 }
1392                 | CREATE OptTemp TABLE qualified_name OF qualified_name
1393                         '(' OptTableElementList ')' OptWithOids OnCommitOption
1394                                 {
1395                                         /* SQL99 CREATE TABLE OF <UDT> (cols) seems to be satisfied
1396                                          * by our inheritance capabilities. Let's try it...
1397                                          */
1398                                         CreateStmt *n = makeNode(CreateStmt);
1399                                         $4->istemp = $2;
1400                                         n->relation = $4;
1401                                         n->tableElts = $8;
1402                                         n->inhRelations = makeList1($6);
1403                                         n->constraints = NIL;
1404                                         n->hasoids = $10;
1405                                         n->oncommit = $11;
1406                                         $$ = (Node *)n;
1407                                 }
1408                 ;
1409
1410 /*
1411  * Redundancy here is needed to avoid shift/reduce conflicts,
1412  * since TEMP is not a reserved word.  See also OptTempTableName.
1413  */
1414 OptTemp:        TEMPORARY                                               { $$ = TRUE; }
1415                         | TEMP                                                  { $$ = TRUE; }
1416                         | LOCAL TEMPORARY                               { $$ = TRUE; }
1417                         | LOCAL TEMP                                    { $$ = TRUE; }
1418                         | GLOBAL TEMPORARY
1419                                 {
1420                                         elog(ERROR,
1421                                         "GLOBAL TEMPORARY TABLE is not currently supported");
1422                                         $$ = TRUE;
1423                                 }
1424                         | GLOBAL TEMP
1425                                 {
1426                                         elog(ERROR,
1427                                         "GLOBAL TEMPORARY TABLE is not currently supported");
1428                                         $$ = TRUE;
1429                                 }
1430                         | /*EMPTY*/                                             { $$ = FALSE; }
1431                 ;
1432
1433 OptTableElementList:
1434                         TableElementList                                        { $$ = $1; }
1435                         | /*EMPTY*/                                                     { $$ = NIL; }
1436                 ;
1437
1438 TableElementList:
1439                         TableElement
1440                                 {
1441                                         $$ = makeList1($1);
1442                                 }
1443                         | TableElementList ',' TableElement
1444                                 {
1445                                         $$ = lappend($1, $3);
1446                                 }
1447                 ;
1448
1449 TableElement:
1450                         columnDef                                                       { $$ = $1; }
1451                         | TableLikeClause                                       { $$ = $1; }
1452                         | TableConstraint                                       { $$ = $1; }
1453                 ;
1454
1455 columnDef:      ColId Typename ColQualList opt_collate
1456                                 {
1457                                         ColumnDef *n = makeNode(ColumnDef);
1458                                         n->colname = $1;
1459                                         n->typename = $2;
1460                                         n->constraints = $3;
1461                                         n->is_local = true;
1462
1463                                         if ($4 != NULL)
1464                                                 elog(NOTICE,
1465                                                         "CREATE TABLE / COLLATE %s not yet implemented; "
1466                                                         "clause ignored", $4);
1467
1468                                         $$ = (Node *)n;
1469                                 }
1470                 ;
1471
1472 ColQualList:
1473                         ColQualList ColConstraint                               { $$ = lappend($1, $2); }
1474                         | /*EMPTY*/                                                             { $$ = NIL; }
1475                 ;
1476
1477 ColConstraint:
1478                         CONSTRAINT name ColConstraintElem
1479                                 {
1480                                         switch (nodeTag($3))
1481                                         {
1482                                                 case T_Constraint:
1483                                                         {
1484                                                                 Constraint *n = (Constraint *)$3;
1485                                                                 n->name = $2;
1486                                                         }
1487                                                         break;
1488                                                 case T_FkConstraint:
1489                                                         {
1490                                                                 FkConstraint *n = (FkConstraint *)$3;
1491                                                                 n->constr_name = $2;
1492                                                         }
1493                                                         break;
1494                                                 default:
1495                                                         break;
1496                                         }
1497                                         $$ = $3;
1498                                 }
1499                         | ColConstraintElem                                             { $$ = $1; }
1500                         | ConstraintAttr                                                { $$ = $1; }
1501                 ;
1502
1503 /* DEFAULT NULL is already the default for Postgres.
1504  * But define it here and carry it forward into the system
1505  * to make it explicit.
1506  * - thomas 1998-09-13
1507  *
1508  * WITH NULL and NULL are not SQL92-standard syntax elements,
1509  * so leave them out. Use DEFAULT NULL to explicitly indicate
1510  * that a column may have that value. WITH NULL leads to
1511  * shift/reduce conflicts with WITH TIME ZONE anyway.
1512  * - thomas 1999-01-08
1513  *
1514  * DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
1515  * conflict on NOT (since NOT might start a subsequent NOT NULL constraint,
1516  * or be part of a_expr NOT LIKE or similar constructs).
1517  */
1518 ColConstraintElem:
1519                         NOT NULL_P
1520                                 {
1521                                         Constraint *n = makeNode(Constraint);
1522                                         n->contype = CONSTR_NOTNULL;
1523                                         n->name = NULL;
1524                                         n->raw_expr = NULL;
1525                                         n->cooked_expr = NULL;
1526                                         n->keys = NULL;
1527                                         $$ = (Node *)n;
1528                                 }
1529                         | NULL_P
1530                                 {
1531                                         Constraint *n = makeNode(Constraint);
1532                                         n->contype = CONSTR_NULL;
1533                                         n->name = NULL;
1534                                         n->raw_expr = NULL;
1535                                         n->cooked_expr = NULL;
1536                                         n->keys = NULL;
1537                                         $$ = (Node *)n;
1538                                 }
1539                         | UNIQUE
1540                                 {
1541                                         Constraint *n = makeNode(Constraint);
1542                                         n->contype = CONSTR_UNIQUE;
1543                                         n->name = NULL;
1544                                         n->raw_expr = NULL;
1545                                         n->cooked_expr = NULL;
1546                                         n->keys = NULL;
1547                                         $$ = (Node *)n;
1548                                 }
1549                         | PRIMARY KEY
1550                                 {
1551                                         Constraint *n = makeNode(Constraint);
1552                                         n->contype = CONSTR_PRIMARY;
1553                                         n->name = NULL;
1554                                         n->raw_expr = NULL;
1555                                         n->cooked_expr = NULL;
1556                                         n->keys = NULL;
1557                                         $$ = (Node *)n;
1558                                 }
1559                         | CHECK '(' a_expr ')'
1560                                 {
1561                                         Constraint *n = makeNode(Constraint);
1562                                         n->contype = CONSTR_CHECK;
1563                                         n->name = NULL;
1564                                         n->raw_expr = $3;
1565                                         n->cooked_expr = NULL;
1566                                         n->keys = NULL;
1567                                         $$ = (Node *)n;
1568                                 }
1569                         | DEFAULT b_expr
1570                                 {
1571                                         Constraint *n = makeNode(Constraint);
1572                                         n->contype = CONSTR_DEFAULT;
1573                                         n->name = NULL;
1574                                         if (exprIsNullConstant($2))
1575                                         {
1576                                                 /* DEFAULT NULL should be reported as empty expr */
1577                                                 n->raw_expr = NULL;
1578                                         }
1579                                         else
1580                                         {
1581                                                 n->raw_expr = $2;
1582                                         }
1583                                         n->cooked_expr = NULL;
1584                                         n->keys = NULL;
1585                                         $$ = (Node *)n;
1586                                 }
1587                         | REFERENCES qualified_name opt_column_list key_match key_actions
1588                                 {
1589                                         FkConstraint *n = makeNode(FkConstraint);
1590                                         n->constr_name          = NULL;
1591                                         n->pktable                      = $2;
1592                                         n->fk_attrs                     = NIL;
1593                                         n->pk_attrs                     = $3;
1594                                         n->fk_matchtype         = $4;
1595                                         n->fk_upd_action        = (char) ($5 >> 8);
1596                                         n->fk_del_action        = (char) ($5 & 0xFF);
1597                                         n->deferrable           = FALSE;
1598                                         n->initdeferred         = FALSE;
1599                                         $$ = (Node *)n;
1600                                 }
1601                 ;
1602
1603 /*
1604  * ConstraintAttr represents constraint attributes, which we parse as if
1605  * they were independent constraint clauses, in order to avoid shift/reduce
1606  * conflicts (since NOT might start either an independent NOT NULL clause
1607  * or an attribute).  analyze.c is responsible for attaching the attribute
1608  * information to the preceding "real" constraint node, and for complaining
1609  * if attribute clauses appear in the wrong place or wrong combinations.
1610  *
1611  * See also ConstraintAttributeSpec, which can be used in places where
1612  * there is no parsing conflict.
1613  */
1614 ConstraintAttr:
1615                         DEFERRABLE
1616                                 {
1617                                         Constraint *n = makeNode(Constraint);
1618                                         n->contype = CONSTR_ATTR_DEFERRABLE;
1619                                         $$ = (Node *)n;
1620                                 }
1621                         | NOT DEFERRABLE
1622                                 {
1623                                         Constraint *n = makeNode(Constraint);
1624                                         n->contype = CONSTR_ATTR_NOT_DEFERRABLE;
1625                                         $$ = (Node *)n;
1626                                 }
1627                         | INITIALLY DEFERRED
1628                                 {
1629                                         Constraint *n = makeNode(Constraint);
1630                                         n->contype = CONSTR_ATTR_DEFERRED;
1631                                         $$ = (Node *)n;
1632                                 }
1633                         | INITIALLY IMMEDIATE
1634                                 {
1635                                         Constraint *n = makeNode(Constraint);
1636                                         n->contype = CONSTR_ATTR_IMMEDIATE;
1637                                         $$ = (Node *)n;
1638                                 }
1639                 ;
1640
1641
1642 /* SQL99 supports wholesale borrowing of a table definition via the LIKE clause.
1643  * This seems to be a poor man's inheritance capability, with the resulting
1644  * tables completely decoupled except for the original commonality in definitions.
1645  * Seems to have much in common with CREATE TABLE AS. - thomas 2002-06-19
1646  */
1647 TableLikeClause:  LIKE any_name
1648                                 {
1649                                         elog(ERROR, "LIKE in table definitions not yet supported");
1650                                         $$ = NULL;
1651                                 }
1652                 ;
1653
1654
1655 /* ConstraintElem specifies constraint syntax which is not embedded into
1656  *      a column definition. ColConstraintElem specifies the embedded form.
1657  * - thomas 1997-12-03
1658  */
1659 TableConstraint:
1660                         CONSTRAINT name ConstraintElem
1661                                 {
1662                                         switch (nodeTag($3))
1663                                         {
1664                                                 case T_Constraint:
1665                                                         {
1666                                                                 Constraint *n = (Constraint *)$3;
1667                                                                 n->name = $2;
1668                                                         }
1669                                                         break;
1670                                                 case T_FkConstraint:
1671                                                         {
1672                                                                 FkConstraint *n = (FkConstraint *)$3;
1673                                                                 n->constr_name = $2;
1674                                                         }
1675                                                         break;
1676                                                 default:
1677                                                         break;
1678                                         }
1679                                         $$ = $3;
1680                                 }
1681                         | ConstraintElem                                                { $$ = $1; }
1682                 ;
1683
1684 ConstraintElem:
1685                         CHECK '(' a_expr ')'
1686                                 {
1687                                         Constraint *n = makeNode(Constraint);
1688                                         n->contype = CONSTR_CHECK;
1689                                         n->name = NULL;
1690                                         n->raw_expr = $3;
1691                                         n->cooked_expr = NULL;
1692                                         $$ = (Node *)n;
1693                                 }
1694                         | UNIQUE '(' columnList ')'
1695                                 {
1696                                         Constraint *n = makeNode(Constraint);
1697                                         n->contype = CONSTR_UNIQUE;
1698                                         n->name = NULL;
1699                                         n->raw_expr = NULL;
1700                                         n->cooked_expr = NULL;
1701                                         n->keys = $3;
1702                                         $$ = (Node *)n;
1703                                 }
1704                         | PRIMARY KEY '(' columnList ')'
1705                                 {
1706                                         Constraint *n = makeNode(Constraint);
1707                                         n->contype = CONSTR_PRIMARY;
1708                                         n->name = NULL;
1709                                         n->raw_expr = NULL;
1710                                         n->cooked_expr = NULL;
1711                                         n->keys = $4;
1712                                         $$ = (Node *)n;
1713                                 }
1714                         | FOREIGN KEY '(' columnList ')' REFERENCES qualified_name
1715                                 opt_column_list key_match key_actions ConstraintAttributeSpec
1716                                 {
1717                                         FkConstraint *n = makeNode(FkConstraint);
1718                                         n->constr_name          = NULL;
1719                                         n->pktable                      = $7;
1720                                         n->fk_attrs                     = $4;
1721                                         n->pk_attrs                     = $8;
1722                                         n->fk_matchtype         = $9;
1723                                         n->fk_upd_action        = (char) ($10 >> 8);
1724                                         n->fk_del_action        = (char) ($10 & 0xFF);
1725                                         n->deferrable           = ($11 & 1) != 0;
1726                                         n->initdeferred         = ($11 & 2) != 0;
1727                                         $$ = (Node *)n;
1728                                 }
1729                 ;
1730
1731 opt_column_list:
1732                         '(' columnList ')'                                              { $$ = $2; }
1733                         | /*EMPTY*/                                                             { $$ = NIL; }
1734                 ;
1735
1736 columnList:
1737                         columnElem                                                              { $$ = makeList1($1); }
1738                         | columnList ',' columnElem                             { $$ = lappend($1, $3); }
1739                 ;
1740
1741 columnElem: ColId
1742                                 {
1743                                         $$ = (Node *) makeString($1);
1744                                 }
1745                 ;
1746
1747 key_match:  MATCH FULL
1748                         {
1749                                 $$ = FKCONSTR_MATCH_FULL;
1750                         }
1751                 | MATCH PARTIAL
1752                         {
1753                                 elog(ERROR, "FOREIGN KEY/MATCH PARTIAL not yet implemented");
1754                                 $$ = FKCONSTR_MATCH_PARTIAL;
1755                         }
1756                 | MATCH SIMPLE
1757                         {
1758                                 $$ = FKCONSTR_MATCH_UNSPECIFIED;
1759                         }
1760                 | /*EMPTY*/
1761                         {
1762                                 $$ = FKCONSTR_MATCH_UNSPECIFIED;
1763                         }
1764                 ;
1765
1766 /*
1767  * We combine the update and delete actions into one value temporarily
1768  * for simplicity of parsing, and then break them down again in the
1769  * calling production.  update is in the left 8 bits, delete in the right.
1770  * Note that NOACTION is the default.
1771  */
1772 key_actions:
1773                         key_update
1774                                 { $$ = ($1 << 8) | (FKCONSTR_ACTION_NOACTION & 0xFF); }
1775                         | key_delete
1776                                 { $$ = (FKCONSTR_ACTION_NOACTION << 8) | ($1 & 0xFF); }
1777                         | key_update key_delete
1778                                 { $$ = ($1 << 8) | ($2 & 0xFF); }
1779                         | key_delete key_update
1780                                 { $$ = ($2 << 8) | ($1 & 0xFF); }
1781                         | /*EMPTY*/
1782                                 { $$ = (FKCONSTR_ACTION_NOACTION << 8) | (FKCONSTR_ACTION_NOACTION & 0xFF); }
1783                 ;
1784
1785 key_update: ON UPDATE key_action                { $$ = $3; }
1786                 ;
1787
1788 key_delete: ON DELETE_P key_action              { $$ = $3; }
1789                 ;
1790
1791 key_action:
1792                         NO ACTION                                       { $$ = FKCONSTR_ACTION_NOACTION; }
1793                         | RESTRICT                                      { $$ = FKCONSTR_ACTION_RESTRICT; }
1794                         | CASCADE                                       { $$ = FKCONSTR_ACTION_CASCADE; }
1795                         | SET NULL_P                            { $$ = FKCONSTR_ACTION_SETNULL; }
1796                         | SET DEFAULT                           { $$ = FKCONSTR_ACTION_SETDEFAULT; }
1797                 ;
1798
1799 OptInherit: INHERITS '(' qualified_name_list ')'        { $$ = $3; }
1800                         | /*EMPTY*/                                                             { $$ = NIL; }
1801                 ;
1802
1803 OptWithOids:
1804                         WITH OIDS                                                               { $$ = TRUE; }
1805                         | WITHOUT OIDS                                                  { $$ = FALSE; }
1806                         | /*EMPTY*/                                                             { $$ = TRUE; }
1807                 ;
1808
1809 OnCommitOption:  ON COMMIT DROP                         { $$ = ONCOMMIT_DROP; }
1810                         | ON COMMIT DELETE_P ROWS               { $$ = ONCOMMIT_DELETE_ROWS; }
1811                         | ON COMMIT PRESERVE ROWS               { $$ = ONCOMMIT_PRESERVE_ROWS; }
1812                         | /*EMPTY*/                                             { $$ = ONCOMMIT_NOOP; }
1813                 ;
1814
1815
1816 /*
1817  * Note: CREATE TABLE ... AS SELECT ... is just another spelling for
1818  * SELECT ... INTO.
1819  */
1820
1821 CreateAsStmt:
1822                         CREATE OptTemp TABLE qualified_name OptCreateAs AS SelectStmt
1823                                 {
1824                                         /*
1825                                          * When the SelectStmt is a set-operation tree, we must
1826                                          * stuff the INTO information into the leftmost component
1827                                          * Select, because that's where analyze.c will expect
1828                                          * to find it.  Similarly, the output column names must
1829                                          * be attached to that Select's target list.
1830                                          */
1831                                         SelectStmt *n = findLeftmostSelect((SelectStmt *) $7);
1832                                         if (n->into != NULL)
1833                                                 elog(ERROR, "CREATE TABLE AS may not specify INTO");
1834                                         $4->istemp = $2;
1835                                         n->into = $4;
1836                                         n->intoColNames = $5;
1837                                         $$ = $7;
1838                                 }
1839                 ;
1840
1841 OptCreateAs:
1842                         '(' CreateAsList ')'                                    { $$ = $2; }
1843                         | /*EMPTY*/                                                             { $$ = NIL; }
1844                 ;
1845
1846 CreateAsList:
1847                         CreateAsElement                                                 { $$ = makeList1($1); }
1848                         | CreateAsList ',' CreateAsElement              { $$ = lappend($1, $3); }
1849                 ;
1850
1851 CreateAsElement:
1852                         ColId
1853                                 {
1854                                         ColumnDef *n = makeNode(ColumnDef);
1855                                         n->colname = $1;
1856                                         n->typename = NULL;
1857                                         n->inhcount = 0;
1858                                         n->is_local = true;
1859                                         n->is_not_null = false;
1860                                         n->raw_default = NULL;
1861                                         n->cooked_default = NULL;
1862                                         n->constraints = NIL;
1863                                         n->support = NULL;
1864                                         $$ = (Node *)n;
1865                                 }
1866                 ;
1867
1868
1869 /*****************************************************************************
1870  *
1871  *              QUERY :
1872  *                              CREATE SEQUENCE seqname
1873  *
1874  *****************************************************************************/
1875
1876 CreateSeqStmt:
1877                         CREATE OptTemp SEQUENCE qualified_name OptSeqList
1878                                 {
1879                                         CreateSeqStmt *n = makeNode(CreateSeqStmt);
1880                                         $4->istemp = $2;
1881                                         n->sequence = $4;
1882                                         n->options = $5;
1883                                         $$ = (Node *)n;
1884                                 }
1885                 ;
1886
1887 OptSeqList: OptSeqList OptSeqElem                                       { $$ = lappend($1, $2); }
1888                         | /*EMPTY*/                                                             { $$ = NIL; }
1889                 ;
1890
1891 OptSeqElem: CACHE NumericOnly
1892                                 {
1893                                         $$ = makeDefElem("cache", (Node *)$2);
1894                                 }
1895                         | CYCLE
1896                                 {
1897                                         $$ = makeDefElem("cycle", (Node *)true);
1898                                 }
1899                         | NO CYCLE
1900                                 {
1901                                         $$ = makeDefElem("cycle", (Node *)false);
1902                                 }
1903                         | INCREMENT opt_by NumericOnly
1904                                 {
1905                                         $$ = makeDefElem("increment", (Node *)$3);
1906                                 }
1907                         | MAXVALUE NumericOnly
1908                                 {
1909                                         $$ = makeDefElem("maxvalue", (Node *)$2);
1910                                 }
1911                         | MINVALUE NumericOnly
1912                                 {
1913                                         $$ = makeDefElem("minvalue", (Node *)$2);
1914                                 }
1915                         | START opt_with NumericOnly
1916                                 {
1917                                         $$ = makeDefElem("start", (Node *)$3);
1918                                 }
1919                 ;
1920
1921 opt_by:         BY                              {}
1922                         | /* empty */   {}
1923           ;
1924
1925 NumericOnly:
1926                         FloatOnly                                                               { $$ = $1; }
1927                         | IntegerOnly                                                   { $$ = $1; }
1928                 ;
1929
1930 FloatOnly:      FCONST                                                                  { $$ = makeFloat($1); }
1931                         | '-' FCONST
1932                                 {
1933                                         $$ = makeFloat($2);
1934                                         doNegateFloat($$);
1935                                 }
1936                 ;
1937
1938 IntegerOnly:
1939                         Iconst
1940                                 {
1941                                         $$ = makeInteger($1);
1942                                 }
1943                         | '-' Iconst
1944                                 {
1945                                         $$ = makeInteger($2);
1946                                         $$->val.ival = - $$->val.ival;
1947                                 }
1948                 ;
1949
1950 /*****************************************************************************
1951  *
1952  *              QUERIES :
1953  *                              CREATE PROCEDURAL LANGUAGE ...
1954  *                              DROP PROCEDURAL LANGUAGE ...
1955  *
1956  *****************************************************************************/
1957
1958 CreatePLangStmt:
1959                         CREATE opt_trusted opt_procedural LANGUAGE ColId_or_Sconst
1960                         HANDLER handler_name opt_validator opt_lancompiler
1961                         {
1962                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
1963                                 n->plname = $5;
1964                                 n->plhandler = $7;
1965                                 n->plvalidator = $8;
1966                                 n->pltrusted = $2;
1967                                 $$ = (Node *)n;
1968                         }
1969                 ;
1970
1971 opt_trusted:
1972                         TRUSTED                                                                 { $$ = TRUE; }
1973                         | /*EMPTY*/                                                             { $$ = FALSE; }
1974                 ;
1975
1976 /* This ought to be just func_name, but that causes reduce/reduce conflicts
1977  * (CREATE LANGUAGE is the only place where func_name isn't followed by '(').
1978  * Work around by using name and dotted_name separately.
1979  */
1980 handler_name:
1981                         name
1982                                                         { $$ = makeList1(makeString($1)); }
1983                         | dotted_name                                                   { $$ = $1; }
1984                 ;
1985
1986 opt_lancompiler:
1987                         LANCOMPILER Sconst                                              { $$ = $2; }
1988                         | /*EMPTY*/                                                             { $$ = ""; }
1989                 ;
1990
1991 opt_validator:
1992                         VALIDATOR handler_name { $$ = $2; }
1993                         | /*EMPTY*/ { $$ = NULL; }
1994                 ;
1995
1996 DropPLangStmt:
1997                         DROP opt_procedural LANGUAGE ColId_or_Sconst opt_drop_behavior
1998                                 {
1999                                         DropPLangStmt *n = makeNode(DropPLangStmt);
2000                                         n->plname = $4;
2001                                         n->behavior = $5;
2002                                         $$ = (Node *)n;
2003                                 }
2004                 ;
2005
2006 opt_procedural:
2007                         PROCEDURAL                                                              {}
2008                         | /*EMPTY*/                                                             {}
2009                 ;
2010
2011 /*****************************************************************************
2012  *
2013  *              QUERIES :
2014  *                              CREATE TRIGGER ...
2015  *                              DROP TRIGGER ...
2016  *
2017  *****************************************************************************/
2018
2019 CreateTrigStmt:
2020                         CREATE TRIGGER name TriggerActionTime TriggerEvents ON
2021                         qualified_name TriggerForSpec EXECUTE PROCEDURE
2022                         func_name '(' TriggerFuncArgs ')'
2023                                 {
2024                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
2025                                         n->trigname = $3;
2026                                         n->relation = $7;
2027                                         n->funcname = $11;
2028                                         n->args = $13;
2029                                         n->before = $4;
2030                                         n->row = $8;
2031                                         memcpy(n->actions, $5, 4);
2032                                         n->isconstraint  = FALSE;
2033                                         n->deferrable    = FALSE;
2034                                         n->initdeferred  = FALSE;
2035                                         n->constrrel = NULL;
2036                                         $$ = (Node *)n;
2037                                 }
2038                         | CREATE CONSTRAINT TRIGGER name AFTER TriggerEvents ON
2039                         qualified_name OptConstrFromTable
2040                         ConstraintAttributeSpec
2041                         FOR EACH ROW EXECUTE PROCEDURE
2042                         func_name '(' TriggerFuncArgs ')'
2043                                 {
2044                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
2045                                         n->trigname = $4;
2046                                         n->relation = $8;
2047                                         n->funcname = $16;
2048                                         n->args = $18;
2049                                         n->before = FALSE;
2050                                         n->row = TRUE;
2051                                         memcpy(n->actions, $6, 4);
2052                                         n->isconstraint  = TRUE;
2053                                         n->deferrable = ($10 & 1) != 0;
2054                                         n->initdeferred = ($10 & 2) != 0;
2055
2056                                         n->constrrel = $9;
2057                                         $$ = (Node *)n;
2058                                 }
2059                 ;
2060
2061 TriggerActionTime:
2062                         BEFORE                                                                  { $$ = TRUE; }
2063                         | AFTER                                                                 { $$ = FALSE; }
2064                 ;
2065
2066 TriggerEvents:
2067                         TriggerOneEvent
2068                                 {
2069                                         char *e = palloc(4);
2070                                         e[0] = $1; e[1] = '\0';
2071                                         $$ = e;
2072                                 }
2073                         | TriggerOneEvent OR TriggerOneEvent
2074                                 {
2075                                         char *e = palloc(4);
2076                                         e[0] = $1; e[1] = $3; e[2] = '\0';
2077                                         $$ = e;
2078                                 }
2079                         | TriggerOneEvent OR TriggerOneEvent OR TriggerOneEvent
2080                                 {
2081                                         char *e = palloc(4);
2082                                         e[0] = $1; e[1] = $3; e[2] = $5; e[3] = '\0';
2083                                         $$ = e;
2084                                 }
2085                 ;
2086
2087 TriggerOneEvent:
2088                         INSERT                                                                  { $$ = 'i'; }
2089                         | DELETE_P                                                              { $$ = 'd'; }
2090                         | UPDATE                                                                { $$ = 'u'; }
2091                 ;
2092
2093 TriggerForSpec:
2094                         FOR TriggerForOpt TriggerForType
2095                                 {
2096                                         $$ = $3;
2097                                 }
2098                         | /* EMPTY */
2099                                 {
2100                                         /*
2101                                          * If ROW/STATEMENT not specified, default to
2102                                          * STATEMENT, per SQL
2103                                          */
2104                                         $$ = FALSE;
2105                                 }
2106                 ;
2107
2108 TriggerForOpt:
2109                         EACH                                                                    {}
2110                         | /*EMPTY*/                                                             {}
2111                 ;
2112
2113 TriggerForType:
2114                         ROW                                                                             { $$ = TRUE; }
2115                         | STATEMENT                                                             { $$ = FALSE; }
2116                 ;
2117
2118 TriggerFuncArgs:
2119                         TriggerFuncArg                                                  { $$ = makeList1($1); }
2120                         | TriggerFuncArgs ',' TriggerFuncArg    { $$ = lappend($1, $3); }
2121                         | /*EMPTY*/                                                             { $$ = NIL; }
2122                 ;
2123
2124 TriggerFuncArg:
2125                         ICONST
2126                                 {
2127                                         char buf[64];
2128                                         snprintf(buf, sizeof(buf), "%d", $1);
2129                                         $$ = makeString(pstrdup(buf));
2130                                 }
2131                         | FCONST                                                                { $$ = makeString($1); }
2132                         | Sconst                                                                { $$ = makeString($1); }
2133                         | BCONST                                                                { $$ = makeString($1); }
2134                         | XCONST                                                                { $$ = makeString($1); }
2135                         | ColId                                                                 { $$ = makeString($1); }
2136                 ;
2137
2138 OptConstrFromTable:
2139                         FROM qualified_name                                             { $$ = $2; }
2140                         | /*EMPTY*/                                                             { $$ = NULL; }
2141                 ;
2142
2143 ConstraintAttributeSpec:
2144                         ConstraintDeferrabilitySpec
2145                                 { $$ = $1; }
2146                         | ConstraintDeferrabilitySpec ConstraintTimeSpec
2147                                 {
2148                                         if ($1 == 0 && $2 != 0)
2149                                                 elog(ERROR,
2150                                                 "INITIALLY DEFERRED constraint must be DEFERRABLE");
2151                                         $$ = $1 | $2;
2152                                 }
2153                         | ConstraintTimeSpec
2154                                 {
2155                                         if ($1 != 0)
2156                                                 $$ = 3;
2157                                         else
2158                                                 $$ = 0;
2159                                 }
2160                         | ConstraintTimeSpec ConstraintDeferrabilitySpec
2161                                 {
2162                                         if ($2 == 0 && $1 != 0)
2163                                                 elog(ERROR,
2164                                                 "INITIALLY DEFERRED constraint must be DEFERRABLE");
2165                                         $$ = $1 | $2;
2166                                 }
2167                         | /*EMPTY*/
2168                                 { $$ = 0; }
2169                 ;
2170
2171 ConstraintDeferrabilitySpec:
2172                         NOT DEFERRABLE                                                  { $$ = 0; }
2173                         | DEFERRABLE                                                    { $$ = 1; }
2174                 ;
2175
2176 ConstraintTimeSpec:
2177                         INITIALLY IMMEDIATE                                             { $$ = 0; }
2178                         | INITIALLY DEFERRED                                    { $$ = 2; }
2179                 ;
2180
2181
2182 DropTrigStmt:
2183                         DROP TRIGGER name ON qualified_name opt_drop_behavior
2184                                 {
2185                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
2186                                         n->relation = $5;
2187                                         n->property = $3;
2188                                         n->behavior = $6;
2189                                         n->removeType = DROP_TRIGGER;
2190                                         $$ = (Node *) n;
2191                                 }
2192                 ;
2193
2194
2195 /*****************************************************************************
2196  *
2197  *              QUERIES :
2198  *                              CREATE ASSERTION ...
2199  *                              DROP ASSERTION ...
2200  *
2201  *****************************************************************************/
2202
2203 CreateAssertStmt:
2204                         CREATE ASSERTION name CHECK '(' a_expr ')'
2205                         ConstraintAttributeSpec
2206                                 {
2207                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
2208                                         n->trigname = $3;
2209                                         n->args = makeList1($6);
2210                                         n->isconstraint  = TRUE;
2211                                         n->deferrable = ($8 & 1) != 0;
2212                                         n->initdeferred = ($8 & 2) != 0;
2213
2214                                         elog(ERROR, "CREATE ASSERTION is not yet supported");
2215
2216                                         $$ = (Node *)n;
2217                                 }
2218                 ;
2219
2220 DropAssertStmt:
2221                         DROP ASSERTION name opt_drop_behavior
2222                                 {
2223                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
2224                                         n->relation = NULL;
2225                                         n->property = $3;
2226                                         n->behavior = $4;
2227                                         n->removeType = DROP_TRIGGER; /* XXX */
2228                                         elog(ERROR, "DROP ASSERTION is not yet supported");
2229                                         $$ = (Node *) n;
2230                                 }
2231                 ;
2232
2233
2234 /*****************************************************************************
2235  *
2236  *              QUERY :
2237  *                              define (aggregate,operator,type)
2238  *
2239  *****************************************************************************/
2240
2241 DefineStmt:
2242                         CREATE AGGREGATE func_name definition
2243                                 {
2244                                         DefineStmt *n = makeNode(DefineStmt);
2245                                         n->defType = AGGREGATE;
2246                                         n->defnames = $3;
2247                                         n->definition = $4;
2248                                         $$ = (Node *)n;
2249                                 }
2250                         | CREATE OPERATOR any_operator definition
2251                                 {
2252                                         DefineStmt *n = makeNode(DefineStmt);
2253                                         n->defType = OPERATOR;
2254                                         n->defnames = $3;
2255                                         n->definition = $4;
2256                                         $$ = (Node *)n;
2257                                 }
2258                         | CREATE TYPE_P any_name definition
2259                                 {
2260                                         DefineStmt *n = makeNode(DefineStmt);
2261                                         n->defType = TYPE_P;
2262                                         n->defnames = $3;
2263                                         n->definition = $4;
2264                                         $$ = (Node *)n;
2265                                 }
2266                         | CREATE TYPE_P any_name AS '(' TableFuncElementList ')'
2267                                 {
2268                                         CompositeTypeStmt *n = makeNode(CompositeTypeStmt);
2269                                         RangeVar *r = makeNode(RangeVar);
2270
2271                                         /* can't use qualified_name, sigh */
2272                                         switch (length($3))
2273                                         {
2274                                                 case 1:
2275                                                         r->catalogname = NULL;
2276                                                         r->schemaname = NULL;
2277                                                         r->relname = strVal(lfirst($3));
2278                                                         break;
2279                                                 case 2:
2280                                                         r->catalogname = NULL;
2281                                                         r->schemaname = strVal(lfirst($3));
2282                                                         r->relname = strVal(lsecond($3));
2283                                                         break;
2284                                                 case 3:
2285                                                         r->catalogname = strVal(lfirst($3));
2286                                                         r->schemaname = strVal(lsecond($3));
2287                                                         r->relname = strVal(lfirst(lnext(lnext($3))));
2288                                                         break;
2289                                                 default:
2290                                                         elog(ERROR,
2291                                                                  "Improper qualified name (too many dotted names): %s",
2292                                                                  NameListToString($3));
2293                                                         break;
2294                                         }
2295                                         n->typevar = r;
2296                                         n->coldeflist = $6;
2297                                         $$ = (Node *)n;
2298                                 }
2299                         | CREATE CHARACTER SET opt_as any_name GET definition opt_collate
2300                                 {
2301                                         DefineStmt *n = makeNode(DefineStmt);
2302                                         n->defType = CHARACTER;
2303                                         n->defnames = $5;
2304                                         n->definition = $7;
2305                                         $$ = (Node *)n;
2306                                 }
2307                 ;
2308
2309 definition: '(' def_list ')'                                            { $$ = $2; }
2310                 ;
2311
2312 def_list:       def_elem                                                                { $$ = makeList1($1); }
2313                         | def_list ',' def_elem                                 { $$ = lappend($1, $3); }
2314                 ;
2315
2316 def_elem:  ColLabel '=' def_arg
2317                                 {
2318                                         $$ = makeDefElem($1, (Node *)$3);
2319                                 }
2320                         | ColLabel
2321                                 {
2322                                         $$ = makeDefElem($1, (Node *)NULL);
2323                                 }
2324                 ;
2325
2326 /* Note: any simple identifier will be returned as a type name! */
2327 def_arg:        func_return                                             { $$ = (Node *)$1; }
2328                         | qual_all_Op                                   { $$ = (Node *)$1; }
2329                         | NumericOnly                                   { $$ = (Node *)$1; }
2330                         | Sconst                                                { $$ = (Node *)makeString($1); }
2331                 ;
2332
2333
2334 /*****************************************************************************
2335  *
2336  *              QUERIES :
2337  *                              CREATE OPERATOR CLASS ...
2338  *                              DROP OPERATOR CLASS ...
2339  *
2340  *****************************************************************************/
2341
2342 CreateOpClassStmt:
2343                         CREATE OPERATOR CLASS any_name opt_default FOR TYPE_P Typename
2344                         USING access_method AS opclass_item_list
2345                                 {
2346                                         CreateOpClassStmt *n = makeNode(CreateOpClassStmt);
2347                                         n->opclassname = $4;
2348                                         n->isDefault = $5;
2349                                         n->datatype = $8;
2350                                         n->amname = $10;
2351                                         n->items = $12;
2352                                         $$ = (Node *) n;
2353                                 }
2354                 ;
2355
2356 opclass_item_list:
2357                         opclass_item                                                    { $$ = makeList1($1); }
2358                         | opclass_item_list ',' opclass_item    { $$ = lappend($1, $3); }
2359                 ;
2360
2361 opclass_item:
2362                         OPERATOR Iconst any_operator opt_recheck
2363                                 {
2364                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
2365                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
2366                                         n->name = $3;
2367                                         n->args = NIL;
2368                                         n->number = $2;
2369                                         n->recheck = $4;
2370                                         $$ = (Node *) n;
2371                                 }
2372                         | OPERATOR Iconst any_operator '(' oper_argtypes ')' opt_recheck
2373                                 {
2374                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
2375                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
2376                                         n->name = $3;
2377                                         n->args = $5;
2378                                         n->number = $2;
2379                                         n->recheck = $7;
2380                                         $$ = (Node *) n;
2381                                 }
2382                         | FUNCTION Iconst func_name func_args
2383                                 {
2384                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
2385                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
2386                                         n->name = $3;
2387                                         n->args = $4;
2388                                         n->number = $2;
2389                                         $$ = (Node *) n;
2390                                 }
2391                         | STORAGE Typename
2392                                 {
2393                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
2394                                         n->itemtype = OPCLASS_ITEM_STORAGETYPE;
2395                                         n->storedtype = $2;
2396                                         $$ = (Node *) n;
2397                                 }
2398                 ;
2399
2400 opt_default:    DEFAULT { $$ = TRUE; }
2401                         | /*EMPTY*/     { $$ = FALSE; }
2402                 ;
2403
2404 opt_recheck:    RECHECK { $$ = TRUE; }
2405                         | /*EMPTY*/     { $$ = FALSE; }
2406                 ;
2407
2408
2409 DropOpClassStmt:
2410                         DROP OPERATOR CLASS any_name USING access_method opt_drop_behavior
2411                                 {
2412                                         RemoveOpClassStmt *n = makeNode(RemoveOpClassStmt);
2413                                         n->opclassname = $4;
2414                                         n->amname = $6;
2415                                         n->behavior = $7;
2416                                         $$ = (Node *) n;
2417                                 }
2418                 ;
2419
2420
2421 /*****************************************************************************
2422  *
2423  *              QUERY:
2424  *
2425  *              DROP itemtype itemname [, itemname ...] [ RESTRICT | CASCADE ]
2426  *
2427  *****************************************************************************/
2428
2429 DropStmt:       DROP drop_type any_name_list opt_drop_behavior
2430                                 {
2431                                         DropStmt *n = makeNode(DropStmt);
2432                                         n->removeType = $2;
2433                                         n->objects = $3;
2434                                         n->behavior = $4;
2435                                         $$ = (Node *)n;
2436                                 }
2437                 ;
2438
2439 drop_type:      TABLE                                                                   { $$ = DROP_TABLE; }
2440                         | SEQUENCE                                                              { $$ = DROP_SEQUENCE; }
2441                         | VIEW                                                                  { $$ = DROP_VIEW; }
2442                         | INDEX                                                                 { $$ = DROP_INDEX; }
2443                         | TYPE_P                                                                { $$ = DROP_TYPE; }
2444                         | DOMAIN_P                                                              { $$ = DROP_DOMAIN; }
2445                         | CONVERSION_P                                                  { $$ = DROP_CONVERSION; }
2446                         | SCHEMA                                                                { $$ = DROP_SCHEMA; }
2447                 ;
2448
2449 any_name_list:
2450                         any_name                                                                { $$ = makeList1($1); }
2451                         | any_name_list ',' any_name                    { $$ = lappend($1, $3); }
2452                 ;
2453
2454 any_name:       ColId                                           { $$ = makeList1(makeString($1)); }
2455                         | dotted_name                           { $$ = $1; }
2456                 ;
2457
2458 /*****************************************************************************
2459  *
2460  *              QUERY:
2461  *                              truncate table relname
2462  *
2463  *****************************************************************************/
2464
2465 TruncateStmt:
2466                         TRUNCATE opt_table qualified_name
2467                                 {
2468                                         TruncateStmt *n = makeNode(TruncateStmt);
2469                                         n->relation = $3;
2470                                         $$ = (Node *)n;
2471                                 }
2472                 ;
2473
2474 /*****************************************************************************
2475  *
2476  *      The COMMENT ON statement can take different forms based upon the type of
2477  *      the object associated with the comment. The form of the statement is:
2478  *
2479  *      COMMENT ON [ [ DATABASE | DOMAIN | INDEX | SEQUENCE | TABLE | TYPE | VIEW ]
2480  *                               <objname> | AGGREGATE <aggname> (<aggtype>) | FUNCTION
2481  *               <funcname> (arg1, arg2, ...) | OPERATOR <op>
2482  *               (leftoperand_typ rightoperand_typ) | TRIGGER <triggername> ON
2483  *               <relname> | RULE <rulename> ON <relname> ] IS 'text'
2484  *
2485  *****************************************************************************/
2486
2487 CommentStmt:
2488                         COMMENT ON comment_type any_name IS comment_text
2489                                 {
2490                                         CommentStmt *n = makeNode(CommentStmt);
2491                                         n->objtype = $3;
2492                                         n->objname = $4;
2493                                         n->objargs = NIL;
2494                                         n->comment = $6;
2495                                         $$ = (Node *) n;
2496                                 }
2497                         | COMMENT ON AGGREGATE func_name '(' aggr_argtype ')'
2498                         IS comment_text
2499                                 {
2500                                         CommentStmt *n = makeNode(CommentStmt);
2501                                         n->objtype = COMMENT_ON_AGGREGATE;
2502                                         n->objname = $4;
2503                                         n->objargs = makeList1($6);
2504                                         n->comment = $9;
2505                                         $$ = (Node *) n;
2506                                 }
2507                         | COMMENT ON FUNCTION func_name func_args IS comment_text
2508                                 {
2509                                         CommentStmt *n = makeNode(CommentStmt);
2510                                         n->objtype = COMMENT_ON_FUNCTION;
2511                                         n->objname = $4;
2512                                         n->objargs = $5;
2513                                         n->comment = $7;
2514                                         $$ = (Node *) n;
2515                                 }
2516                         | COMMENT ON OPERATOR any_operator '(' oper_argtypes ')'
2517                         IS comment_text
2518                                 {
2519                                         CommentStmt *n = makeNode(CommentStmt);
2520                                         n->objtype = COMMENT_ON_OPERATOR;
2521                                         n->objname = $4;
2522                                         n->objargs = $6;
2523                                         n->comment = $9;
2524                                         $$ = (Node *) n;
2525                                 }
2526                         | COMMENT ON CONSTRAINT name ON any_name IS comment_text
2527                                 {
2528                                         CommentStmt *n = makeNode(CommentStmt);
2529                                         n->objtype = COMMENT_ON_CONSTRAINT;
2530                                         n->objname = lappend($6, makeString($4));
2531                                         n->objargs = NIL;
2532                                         n->comment = $8;
2533                                         $$ = (Node *) n;
2534                                 }
2535                         | COMMENT ON RULE name ON any_name IS comment_text
2536                                 {
2537                                         CommentStmt *n = makeNode(CommentStmt);
2538                                         n->objtype = COMMENT_ON_RULE;
2539                                         n->objname = lappend($6, makeString($4));
2540                                         n->objargs = NIL;
2541                                         n->comment = $8;
2542                                         $$ = (Node *) n;
2543                                 }
2544                         | COMMENT ON RULE name IS comment_text
2545                                 {
2546                                         /* Obsolete syntax supported for awhile for compatibility */
2547                                         CommentStmt *n = makeNode(CommentStmt);
2548                                         n->objtype = COMMENT_ON_RULE;
2549                                         n->objname = makeList1(makeString($4));
2550                                         n->objargs = NIL;
2551                                         n->comment = $6;
2552                                         $$ = (Node *) n;
2553                                 }
2554                         | COMMENT ON TRIGGER name ON any_name IS comment_text
2555                                 {
2556                                         CommentStmt *n = makeNode(CommentStmt);
2557                                         n->objtype = COMMENT_ON_TRIGGER;
2558                                         n->objname = lappend($6, makeString($4));
2559                                         n->objargs = NIL;
2560                                         n->comment = $8;
2561                                         $$ = (Node *) n;
2562                                 }
2563                 ;
2564
2565 comment_type:
2566                         COLUMN                                                          { $$ = COMMENT_ON_COLUMN; }
2567                         | DATABASE                                                      { $$ = COMMENT_ON_DATABASE; }
2568                         | SCHEMA                                                        { $$ = COMMENT_ON_SCHEMA; }
2569                         | INDEX                                                         { $$ = COMMENT_ON_INDEX; }
2570                         | SEQUENCE                                                      { $$ = COMMENT_ON_SEQUENCE; }
2571                         | TABLE                                                         { $$ = COMMENT_ON_TABLE; }
2572                         | DOMAIN_P                                                      { $$ = COMMENT_ON_TYPE; }
2573                         | TYPE_P                                                        { $$ = COMMENT_ON_TYPE; }
2574                         | VIEW                                                          { $$ = COMMENT_ON_VIEW; }
2575                 ;
2576
2577 comment_text:
2578                         Sconst                                                          { $$ = $1; }
2579                         | NULL_P                                                        { $$ = NULL; }
2580                 ;
2581
2582 /*****************************************************************************
2583  *
2584  *              QUERY:
2585  *                      fetch/move [forward | backward] [ # | all ] [ in <portalname> ]
2586  *                      fetch [ forward | backward | absolute | relative ]
2587  *                                [ # | all | next | prior ] [ [ in | from ] <portalname> ]
2588  *
2589  *****************************************************************************/
2590
2591 FetchStmt:      FETCH direction fetch_how_many from_in name
2592                                 {
2593                                         FetchStmt *n = makeNode(FetchStmt);
2594                                         if ($3 < 0)
2595                                         {
2596                                                 $3 = -$3;
2597                                                 $2 = (($2 == FORWARD)? BACKWARD: FORWARD);
2598                                         }
2599                                         n->direction = $2;
2600                                         n->howMany = $3;
2601                                         n->portalname = $5;
2602                                         n->ismove = FALSE;
2603                                         $$ = (Node *)n;
2604                                 }
2605                         | FETCH fetch_how_many from_in name
2606                                 {
2607                                         FetchStmt *n = makeNode(FetchStmt);
2608                                         if ($2 < 0)
2609                                         {
2610                                                 n->howMany = -$2;
2611                                                 n->direction = BACKWARD;
2612                                         }
2613                                         else
2614                                         {
2615                                                 n->direction = FORWARD;
2616                                                 n->howMany = $2;
2617                                         }
2618                                         n->portalname = $4;
2619                                         n->ismove = FALSE;
2620                                         $$ = (Node *)n;
2621                                 }
2622                         | FETCH direction from_in name
2623                                 {
2624                                         FetchStmt *n = makeNode(FetchStmt);
2625                                         n->direction = $2;
2626                                         n->howMany = 1;
2627                                         n->portalname = $4;
2628                                         n->ismove = FALSE;
2629                                         $$ = (Node *)n;
2630                                 }
2631                         | FETCH from_in name
2632                                 {
2633                                         FetchStmt *n = makeNode(FetchStmt);
2634                                         n->direction = FORWARD;
2635                                         n->howMany = 1;
2636                                         n->portalname = $3;
2637                                         n->ismove = FALSE;
2638                                         $$ = (Node *)n;
2639                                 }
2640                         | FETCH name
2641                                 {
2642                                         FetchStmt *n = makeNode(FetchStmt);
2643                                         n->direction = FORWARD;
2644                                         n->howMany = 1;
2645                                         n->portalname = $2;
2646                                         n->ismove = FALSE;
2647                                         $$ = (Node *)n;
2648                                 }
2649                         | MOVE direction fetch_how_many from_in name
2650                                 {
2651                                         FetchStmt *n = makeNode(FetchStmt);
2652                                         if ($3 < 0)
2653                                         {
2654                                                 $3 = -$3;
2655                                                 $2 = (($2 == FORWARD) ? BACKWARD: FORWARD);
2656                                         }
2657                                         n->direction = $2;
2658                                         n->howMany = $3;
2659                                         n->portalname = $5;
2660                                         n->ismove = TRUE;
2661                                         $$ = (Node *)n;
2662                                 }
2663                         | MOVE fetch_how_many from_in name
2664                                 {
2665                                         FetchStmt *n = makeNode(FetchStmt);
2666                                         if ($2 < 0)
2667                                         {
2668                                                 n->howMany = -$2;
2669                                                 n->direction = BACKWARD;
2670                                         }
2671                                         else
2672                                         {
2673                                                 n->direction = FORWARD;
2674                                                 n->howMany = $2;
2675                                         }
2676                                         n->portalname = $4;
2677                                         n->ismove = TRUE;
2678                                         $$ = (Node *)n;
2679                                 }
2680                         | MOVE direction from_in name
2681                                 {
2682                                         FetchStmt *n = makeNode(FetchStmt);
2683                                         n->direction = $2;
2684                                         n->howMany = 1;
2685                                         n->portalname = $4;
2686                                         n->ismove = TRUE;
2687                                         $$ = (Node *)n;
2688                                 }
2689                         | MOVE from_in name
2690                                 {
2691                                         FetchStmt *n = makeNode(FetchStmt);
2692                                         n->direction = FORWARD;
2693                                         n->howMany = 1;
2694                                         n->portalname = $3;
2695                                         n->ismove = TRUE;
2696                                         $$ = (Node *)n;
2697                                 }
2698                         | MOVE name
2699                                 {
2700                                         FetchStmt *n = makeNode(FetchStmt);
2701                                         n->direction = FORWARD;
2702                                         n->howMany = 1;
2703                                         n->portalname = $2;
2704                                         n->ismove = TRUE;
2705                                         $$ = (Node *)n;
2706                                 }
2707                 ;
2708
2709 direction:      FORWARD                                                                 { $$ = FORWARD; }
2710                         | BACKWARD                                                              { $$ = BACKWARD; }
2711                         | RELATIVE                                                              { $$ = FORWARD; }
2712                         | ABSOLUTE
2713                                 {
2714                                         elog(NOTICE,
2715                                         "FETCH / ABSOLUTE not supported, using RELATIVE");
2716                                         $$ = FORWARD;
2717                                 }
2718                 ;
2719
2720 fetch_how_many:
2721                         Iconst                                                                  { $$ = $1; }
2722                         | '-' Iconst                                                    { $$ = - $2; }
2723                         | ALL                                                                   { $$ = LONG_MAX; }
2724                         | LAST                                                                  { $$ = LONG_MAX; }
2725                         | NEXT                                                                  { $$ = 1; }
2726                         | PRIOR                                                                 { $$ = -1; }
2727                 ;
2728
2729 from_in:        IN_P                                                                    {}
2730                         | FROM                                                                  {}
2731                 ;
2732
2733
2734 /*****************************************************************************
2735  *
2736  * GRANT and REVOKE statements
2737  *
2738  *****************************************************************************/
2739
2740 GrantStmt:      GRANT privileges ON privilege_target TO grantee_list
2741                         opt_grant_grant_option
2742                                 {
2743                                         GrantStmt *n = makeNode(GrantStmt);
2744                                         n->is_grant = true;
2745                                         n->privileges = $2;
2746                                         n->objtype = ($4)->objtype;
2747                                         n->objects = ($4)->objs;
2748                                         n->grantees = $6;
2749                                         $$ = (Node*)n;
2750                                 }
2751                 ;
2752
2753 RevokeStmt: REVOKE opt_revoke_grant_option privileges ON privilege_target
2754                         FROM grantee_list
2755                                 {
2756                                         GrantStmt *n = makeNode(GrantStmt);
2757                                         n->is_grant = false;
2758                                         n->privileges = $3;
2759                                         n->objtype = ($5)->objtype;
2760                                         n->objects = ($5)->objs;
2761                                         n->grantees = $7;
2762                                         $$ = (Node *)n;
2763                                 }
2764                 ;
2765
2766
2767 /* either ALL [PRIVILEGES] or a list of individual privileges */
2768 privileges: privilege_list                              { $$ = $1; }
2769                         | ALL                                           { $$ = makeListi1(ACL_ALL_RIGHTS); }
2770                         | ALL PRIVILEGES                        { $$ = makeListi1(ACL_ALL_RIGHTS); }
2771                 ;
2772
2773 privilege_list:
2774                         privilege                                                               { $$ = makeListi1($1); }
2775                         | privilege_list ',' privilege                  { $$ = lappendi($1, $3); }
2776                 ;
2777
2778 /* Not all of these privilege types apply to all objects, but that
2779  * gets sorted out later.
2780  */
2781 privilege:      SELECT                                                                  { $$ = ACL_SELECT; }
2782                         | INSERT                                                                { $$ = ACL_INSERT; }
2783                         | UPDATE                                                                { $$ = ACL_UPDATE; }
2784                         | DELETE_P                                                              { $$ = ACL_DELETE; }
2785                         | RULE                                                                  { $$ = ACL_RULE; }
2786                         | REFERENCES                                                    { $$ = ACL_REFERENCES; }
2787                         | TRIGGER                                                               { $$ = ACL_TRIGGER; }
2788                         | EXECUTE                                                               { $$ = ACL_EXECUTE; }
2789                         | USAGE                                                                 { $$ = ACL_USAGE; }
2790                         | CREATE                                                                { $$ = ACL_CREATE; }
2791                         | TEMPORARY                                                             { $$ = ACL_CREATE_TEMP; }
2792                         | TEMP                                                                  { $$ = ACL_CREATE_TEMP; }
2793                 ;
2794
2795
2796 /* Don't bother trying to fold the first two rules into one using
2797    opt_table.  You're going to get conflicts. */
2798 privilege_target:
2799                         qualified_name_list
2800                                 {
2801                                         PrivTarget *n = makeNode(PrivTarget);
2802                                         n->objtype = ACL_OBJECT_RELATION;
2803                                         n->objs = $1;
2804                                         $$ = n;
2805                                 }
2806                         | TABLE qualified_name_list
2807                                 {
2808                                         PrivTarget *n = makeNode(PrivTarget);
2809                                         n->objtype = ACL_OBJECT_RELATION;
2810                                         n->objs = $2;
2811                                         $$ = n;
2812                                 }
2813                         | FUNCTION function_with_argtypes_list
2814                                 {
2815                                         PrivTarget *n = makeNode(PrivTarget);
2816                                         n->objtype = ACL_OBJECT_FUNCTION;
2817                                         n->objs = $2;
2818                                         $$ = n;
2819                                 }
2820                         | DATABASE name_list
2821                                 {
2822                                         PrivTarget *n = makeNode(PrivTarget);
2823                                         n->objtype = ACL_OBJECT_DATABASE;
2824                                         n->objs = $2;
2825                                         $$ = n;
2826                                 }
2827                         | LANGUAGE name_list
2828                                 {
2829                                         PrivTarget *n = makeNode(PrivTarget);
2830                                         n->objtype = ACL_OBJECT_LANGUAGE;
2831                                         n->objs = $2;
2832                                         $$ = n;
2833                                 }
2834                         | SCHEMA name_list
2835                                 {
2836                                         PrivTarget *n = makeNode(PrivTarget);
2837                                         n->objtype = ACL_OBJECT_NAMESPACE;
2838                                         n->objs = $2;
2839                                         $$ = n;
2840                                 }
2841                 ;
2842
2843
2844 grantee_list:
2845                         grantee                                                                 { $$ = makeList1($1); }
2846                         | grantee_list ',' grantee                              { $$ = lappend($1, $3); }
2847                 ;
2848
2849 grantee:        ColId
2850                                 {
2851                                         PrivGrantee *n = makeNode(PrivGrantee);
2852                                         /* This hack lets us avoid reserving PUBLIC as a keyword*/
2853                                         if (strcmp($1, "public") == 0)
2854                                                 n->username = NULL;
2855                                         else
2856                                                 n->username = $1;
2857                                         n->groupname = NULL;
2858                                         $$ = (Node *)n;
2859                                 }
2860                         | GROUP_P ColId
2861                                 {
2862                                         PrivGrantee *n = makeNode(PrivGrantee);
2863                                         /* Treat GROUP PUBLIC as a synonym for PUBLIC */
2864                                         if (strcmp($2, "public") == 0)
2865                                                 n->groupname = NULL;
2866                                         else
2867                                                 n->groupname = $2;
2868                                         n->username = NULL;
2869                                         $$ = (Node *)n;
2870                                 }
2871                 ;
2872
2873
2874 opt_grant_grant_option:
2875                         WITH GRANT OPTION
2876                                 {
2877                                         elog(ERROR, "grant options are not implemented");
2878                                 }
2879                         | /*EMPTY*/
2880                 ;
2881
2882 opt_revoke_grant_option:
2883                         GRANT OPTION FOR
2884                                 {
2885                                         elog(ERROR, "grant options are not implemented");
2886                                 }
2887                         | /*EMPTY*/
2888                 ;
2889
2890
2891 function_with_argtypes_list:
2892                         function_with_argtypes                                  { $$ = makeList1($1); }
2893                         | function_with_argtypes_list ',' function_with_argtypes
2894                                                                                                         { $$ = lappend($1, $3); }
2895                 ;
2896
2897 function_with_argtypes:
2898                         func_name func_args
2899                                 {
2900                                         FuncWithArgs *n = makeNode(FuncWithArgs);
2901                                         n->funcname = $1;
2902                                         n->funcargs = $2;
2903                                         $$ = (Node *)n;
2904                                 }
2905                 ;
2906
2907
2908 /*****************************************************************************
2909  *
2910  *              QUERY:
2911  *                              create index <indexname> on <relname>
2912  *                                [ using <access> ] "(" (<col> with <op>)+ ")"
2913  *                                [ where <predicate> ]
2914  *
2915  *****************************************************************************/
2916
2917 IndexStmt:      CREATE index_opt_unique INDEX index_name ON qualified_name
2918                         access_method_clause '(' index_params ')' where_clause
2919                                 {
2920                                         IndexStmt *n = makeNode(IndexStmt);
2921                                         n->unique = $2;
2922                                         n->idxname = $4;
2923                                         n->relation = $6;
2924                                         n->accessMethod = $7;
2925                                         n->indexParams = $9;
2926                                         n->whereClause = $11;
2927                                         $$ = (Node *)n;
2928                                 }
2929                 ;
2930
2931 index_opt_unique:
2932                         UNIQUE                                                                  { $$ = TRUE; }
2933                         | /*EMPTY*/                                                             { $$ = FALSE; }
2934                 ;
2935
2936 access_method_clause:
2937                         USING access_method                                             { $$ = $2; }
2938                         /* If btree changes as our default, update pg_get_indexdef() */
2939                         | /*EMPTY*/                                                             { $$ = DEFAULT_INDEX_TYPE; }
2940                 ;
2941
2942 index_params:
2943                         index_list                                                              { $$ = $1; }
2944                         | func_index                                                    { $$ = makeList1($1); }
2945                 ;
2946
2947 index_list:     index_elem                                                              { $$ = makeList1($1); }
2948                         | index_list ',' index_elem                             { $$ = lappend($1, $3); }
2949                 ;
2950
2951 func_index: func_name '(' name_list ')' opt_class
2952                                 {
2953                                         $$ = makeNode(IndexElem);
2954                                         $$->name = NULL;
2955                                         $$->funcname = $1;
2956                                         $$->args = $3;
2957                                         $$->opclass = $5;
2958                                 }
2959                   ;
2960
2961 index_elem: attr_name opt_class
2962                                 {
2963                                         $$ = makeNode(IndexElem);
2964                                         $$->name = $1;
2965                                         $$->funcname = NIL;
2966                                         $$->args = NIL;
2967                                         $$->opclass = $2;
2968                                 }
2969                 ;
2970
2971 opt_class:      any_name
2972                                 {
2973                                         /*
2974                                          * Release 7.0 removed network_ops, timespan_ops, and
2975                                          * datetime_ops, so we suppress it from being passed to
2976                                          * the parser so the default *_ops is used.  This can be
2977                                          * removed in some later release.  bjm 2000/02/07
2978                                          *
2979                                          * Release 7.1 removes lztext_ops, so suppress that too
2980                                          * for a while.  tgl 2000/07/30
2981                                          *
2982                                          * Release 7.2 renames timestamp_ops to timestamptz_ops,
2983                                          * so suppress that too for awhile.  I'm starting to
2984                                          * think we need a better approach.  tgl 2000/10/01
2985                                          */
2986                                         if (length($1) == 1)
2987                                         {
2988                                                 char   *claname = strVal(lfirst($1));
2989
2990                                                 if (strcmp(claname, "network_ops") != 0 &&
2991                                                         strcmp(claname, "timespan_ops") != 0 &&
2992                                                         strcmp(claname, "datetime_ops") != 0 &&
2993                                                         strcmp(claname, "lztext_ops") != 0 &&
2994                                                         strcmp(claname, "timestamp_ops") != 0)
2995                                                         $$ = $1;
2996                                                 else
2997                                                         $$ = NIL;
2998                                         }
2999                                         else
3000                                                 $$ = $1;
3001                                 }
3002                         | USING any_name                                                { $$ = $2; }
3003                         | /*EMPTY*/                                                             { $$ = NIL; }
3004                 ;
3005
3006 /*****************************************************************************
3007  *
3008  *              QUERY:
3009  *                              create [or replace] function <fname>
3010  *                                              [(<type-1> { , <type-n>})]
3011  *                                              returns <type-r>
3012  *                                              as <filename or code in language as appropriate>
3013  *                                              language <lang> [with parameters]
3014  *
3015  *****************************************************************************/
3016
3017 CreateFunctionStmt:
3018                         CREATE opt_or_replace FUNCTION func_name func_args
3019                         RETURNS func_return createfunc_opt_list opt_definition
3020                                 {
3021                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
3022                                         n->replace = $2;
3023                                         n->funcname = $4;
3024                                         n->argTypes = $5;
3025                                         n->returnType = $7;
3026                                         n->options = $8;
3027                                         n->withClause = $9;
3028                                         $$ = (Node *)n;
3029                                 }
3030                 ;
3031
3032 opt_or_replace:
3033                         OR REPLACE                                                              { $$ = TRUE; }
3034                         | /*EMPTY*/                                                             { $$ = FALSE; }
3035                 ;
3036
3037 func_args:      '(' func_args_list ')'                                  { $$ = $2; }
3038                         | '(' ')'                                                               { $$ = NIL; }
3039                 ;
3040
3041 func_args_list:
3042                         func_arg                                                                { $$ = makeList1($1); }
3043                         | func_args_list ',' func_arg                   { $$ = lappend($1, $3); }
3044                 ;
3045
3046 func_arg:       opt_arg func_type
3047                                 {
3048                                         /* We can catch over-specified arguments here if we want to,
3049                                          * but for now better to silently swallow typmod, etc.
3050                                          * - thomas 2000-03-22
3051                                          */
3052                                         $$ = $2;
3053                                 }
3054                         | func_type                                                             { $$ = $1; }
3055                 ;
3056
3057 opt_arg:        IN_P                                                                    { $$ = FALSE; }
3058                         | OUT_P
3059                                 {
3060                                         elog(ERROR,
3061                                         "CREATE FUNCTION / OUT parameters are not supported");
3062                                         $$ = TRUE;
3063                                 }
3064                         | INOUT
3065                                 {
3066                                         elog(ERROR,
3067                                         "CREATE FUNCTION / INOUT parameters are not supported");
3068                                         $$ = FALSE;
3069                                 }
3070                 ;
3071
3072 func_return:
3073                         func_type
3074                                 {
3075                                         /* We can catch over-specified arguments here if we want to,
3076                                          * but for now better to silently swallow typmod, etc.
3077                                          * - thomas 2000-03-22
3078                                          */
3079                                         $$ = $1;
3080                                 }
3081                 ;
3082
3083 /*
3084  * We would like to make the second production here be ColId attrs etc,
3085  * but that causes reduce/reduce conflicts.  type_name is next best choice.
3086  */
3087 func_type:      Typename                                                                { $$ = $1; }
3088                         | type_name attrs '%' TYPE_P
3089                                 {
3090                                         $$ = makeNode(TypeName);
3091                                         $$->names = lcons(makeString($1), $2);
3092                                         $$->pct_type = true;
3093                                         $$->typmod = -1;
3094                                 }
3095                 ;
3096
3097
3098 createfunc_opt_list:
3099                         /* Must be at least one to prevent conflict */
3100                         createfunc_opt_item                     { $$ = makeList1($1); }
3101                         | createfunc_opt_list createfunc_opt_item { $$ = lappend($1, $2); }
3102         ;
3103
3104 createfunc_opt_item:
3105                         AS func_as
3106                                 {
3107                                         $$ = makeDefElem("as", (Node *)$2);
3108                                 }
3109                         | LANGUAGE ColId_or_Sconst
3110                                 {
3111                                         $$ = makeDefElem("language", (Node *)makeString($2));
3112                                 }
3113                         | IMMUTABLE
3114                                 {
3115                                         $$ = makeDefElem("volatility", (Node *)makeString("immutable"));
3116                                 }
3117                         | STABLE
3118                                 {
3119                                         $$ = makeDefElem("volatility", (Node *)makeString("stable"));
3120                                 }
3121                         | VOLATILE
3122                                 {
3123                                         $$ = makeDefElem("volatility", (Node *)makeString("volatile"));
3124                                 }
3125                         | CALLED ON NULL_P INPUT
3126                                 {
3127                                         $$ = makeDefElem("strict", (Node *)makeInteger(FALSE));
3128                                 }
3129                         | RETURNS NULL_P ON NULL_P INPUT
3130                                 {
3131                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
3132                                 }
3133                         | STRICT
3134                                 {
3135                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
3136                                 }
3137                         | EXTERNAL SECURITY DEFINER
3138                                 {
3139                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
3140                                 }
3141                         | EXTERNAL SECURITY INVOKER
3142                                 {
3143                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
3144                                 }
3145                         | SECURITY DEFINER
3146                                 {
3147                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
3148                                 }
3149                         | SECURITY INVOKER
3150                                 {
3151                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
3152                                 }
3153                 ;
3154
3155 func_as:        Sconst                                          { $$ = makeList1(makeString($1)); }
3156                         | Sconst ',' Sconst
3157                                 {
3158                                         $$ = makeList2(makeString($1), makeString($3));
3159                                 }
3160                 ;
3161
3162 opt_definition:
3163                         WITH definition                                                 { $$ = $2; }
3164                         | /*EMPTY*/                                                             { $$ = NIL; }
3165                 ;
3166
3167
3168 /*****************************************************************************
3169  *
3170  *              QUERY:
3171  *
3172  *              DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
3173  *              DROP AGGREGATE aggname (aggtype) [ RESTRICT | CASCADE ]
3174  *              DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
3175  *
3176  *****************************************************************************/
3177
3178 RemoveFuncStmt:
3179                         DROP FUNCTION func_name func_args opt_drop_behavior
3180                                 {
3181                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
3182                                         n->funcname = $3;
3183                                         n->args = $4;
3184                                         n->behavior = $5;
3185                                         $$ = (Node *)n;
3186                                 }
3187                 ;
3188
3189 RemoveAggrStmt:
3190                         DROP AGGREGATE func_name '(' aggr_argtype ')' opt_drop_behavior
3191                                 {
3192                                                 RemoveAggrStmt *n = makeNode(RemoveAggrStmt);
3193                                                 n->aggname = $3;
3194                                                 n->aggtype = $5;
3195                                                 n->behavior = $7;
3196                                                 $$ = (Node *)n;
3197                                 }
3198                 ;
3199
3200 aggr_argtype:
3201                         Typename                                                                { $$ = $1; }
3202                         | '*'                                                                   { $$ = NULL; }
3203                 ;
3204
3205 RemoveOperStmt:
3206                         DROP OPERATOR any_operator '(' oper_argtypes ')' opt_drop_behavior
3207                                 {
3208                                         RemoveOperStmt *n = makeNode(RemoveOperStmt);
3209                                         n->opname = $3;
3210                                         n->args = $5;
3211                                         n->behavior = $7;
3212                                         $$ = (Node *)n;
3213                                 }
3214                 ;
3215
3216 oper_argtypes:
3217                         Typename
3218                                 {
3219                                    elog(ERROR,"parser: argument type missing (use NONE for unary operators)");
3220                                 }
3221                         | Typename ',' Typename
3222                                         { $$ = makeList2($1, $3); }
3223                         | NONE ',' Typename /* left unary */
3224                                         { $$ = makeList2(NULL, $3); }
3225                         | Typename ',' NONE /* right unary */
3226                                         { $$ = makeList2($1, NULL); }
3227                 ;
3228
3229 any_operator:
3230                         all_Op
3231                                         { $$ = makeList1(makeString($1)); }
3232                         | ColId '.' any_operator
3233                                         { $$ = lcons(makeString($1), $3); }
3234                 ;
3235
3236
3237 /*****************************************************************************
3238  *
3239  *              CREATE CAST / DROP CAST
3240  *
3241  *****************************************************************************/
3242
3243 CreateCastStmt: CREATE CAST '(' ConstTypename AS ConstTypename ')'
3244                                         WITH FUNCTION function_with_argtypes cast_context
3245                                 {
3246                                         CreateCastStmt *n = makeNode(CreateCastStmt);
3247                                         n->sourcetype = $4;
3248                                         n->targettype = $6;
3249                                         n->func = (FuncWithArgs *) $10;
3250                                         n->context = (CoercionContext) $11;
3251                                         $$ = (Node *)n;
3252                                 }
3253                         | CREATE CAST '(' ConstTypename AS ConstTypename ')'
3254                                         WITHOUT FUNCTION cast_context
3255                                 {
3256                                         CreateCastStmt *n = makeNode(CreateCastStmt);
3257                                         n->sourcetype = $4;
3258                                         n->targettype = $6;
3259                                         n->func = NULL;
3260                                         n->context = (CoercionContext) $10;
3261                                         $$ = (Node *)n;
3262                                 }
3263                 ;
3264
3265 cast_context:  AS IMPLICIT_P                                    { $$ = COERCION_IMPLICIT; }
3266                 | AS ASSIGNMENT                                                 { $$ = COERCION_ASSIGNMENT; }
3267                 | /*EMPTY*/                                                             { $$ = COERCION_EXPLICIT; }
3268                 ;
3269
3270
3271 DropCastStmt: DROP CAST '(' ConstTypename AS ConstTypename ')' opt_drop_behavior
3272                                 {
3273                                         DropCastStmt *n = makeNode(DropCastStmt);
3274                                         n->sourcetype = $4;
3275                                         n->targettype = $6;
3276                                         n->behavior = $8;
3277                                         $$ = (Node *)n;
3278                                 }
3279                 ;
3280
3281
3282
3283 /*****************************************************************************
3284  *
3285  *              QUERY:
3286  *
3287  *              REINDEX type <typename> [FORCE] [ALL]
3288  *
3289  *****************************************************************************/
3290
3291 ReindexStmt:
3292                         REINDEX reindex_type qualified_name opt_force
3293                                 {
3294                                         ReindexStmt *n = makeNode(ReindexStmt);
3295                                         n->reindexType = $2;
3296                                         n->relation = $3;
3297                                         n->name = NULL;
3298                                         n->force = $4;
3299                                         $$ = (Node *)n;
3300                                 }
3301                         | REINDEX DATABASE name opt_force
3302                                 {
3303                                         ReindexStmt *n = makeNode(ReindexStmt);
3304                                         n->reindexType = DATABASE;
3305                                         n->name = $3;
3306                                         n->relation = NULL;
3307                                         n->force = $4;
3308                                         $$ = (Node *)n;
3309                                 }
3310                 ;
3311
3312 reindex_type:
3313                         INDEX                                                                   { $$ = INDEX; }
3314                         | TABLE                                                                 { $$ = TABLE; }
3315                 ;
3316
3317 opt_force:      FORCE                                                                   {  $$ = TRUE; }
3318                         | /* EMPTY */                                                   {  $$ = FALSE; }
3319                 ;
3320
3321
3322 /*****************************************************************************
3323  *
3324  *              QUERY:
3325  *                              rename <attrname1> in <relname> [*] to <attrname2>
3326  *                              rename <relname1> to <relname2>
3327  *
3328  *****************************************************************************/
3329
3330 RenameStmt: ALTER TABLE relation_expr RENAME opt_column opt_name TO name
3331                                 {
3332                                         RenameStmt *n = makeNode(RenameStmt);
3333                                         n->relation = $3;
3334                                         n->oldname = $6;
3335                                         n->newname = $8;
3336                                         if ($6 == NULL)
3337                                                 n->renameType = RENAME_TABLE;
3338                                         else
3339                                                 n->renameType = RENAME_COLUMN;
3340                                         $$ = (Node *)n;
3341                                 }
3342                         | ALTER TRIGGER name ON relation_expr RENAME TO name
3343                                 {
3344                                         RenameStmt *n = makeNode(RenameStmt);
3345                                         n->relation = $5;
3346                                         n->oldname = $3;
3347                                         n->newname = $8;
3348                                         n->renameType = RENAME_TRIGGER;
3349                                         $$ = (Node *)n;
3350                                 }
3351                 ;
3352
3353 opt_name:       name                                                                    { $$ = $1; }
3354                         | /*EMPTY*/                                                             { $$ = NULL; }
3355                 ;
3356
3357 opt_column: COLUMN                                                                      { $$ = COLUMN; }
3358                         | /*EMPTY*/                                                             { $$ = 0; }
3359                 ;
3360
3361
3362 /*****************************************************************************
3363  *
3364  *              QUERY:  Define Rewrite Rule
3365  *
3366  *****************************************************************************/
3367
3368 RuleStmt:       CREATE opt_or_replace RULE name AS
3369                         { QueryIsRule=TRUE; }
3370                         ON event TO qualified_name where_clause
3371                         DO opt_instead RuleActionList
3372                                 {
3373                                         RuleStmt *n = makeNode(RuleStmt);
3374                                         n->replace = $2;
3375                                         n->relation = $10;
3376                                         n->rulename = $4;
3377                                         n->whereClause = $11;
3378                                         n->event = $8;
3379                                         n->instead = $13;
3380                                         n->actions = $14;
3381                                         $$ = (Node *)n;
3382                                         QueryIsRule=FALSE;
3383                                 }
3384                 ;
3385
3386 RuleActionList:
3387                         NOTHING                                                                 { $$ = NIL; }
3388                         | RuleActionStmt                                                { $$ = makeList1($1); }
3389                         | '(' RuleActionMulti ')'                               { $$ = $2; }
3390                 ;
3391
3392 /* the thrashing around here is to discard "empty" statements... */
3393 RuleActionMulti:
3394                         RuleActionMulti ';' RuleActionStmtOrEmpty
3395                                 { if ($3 != (Node *) NULL)
3396                                         $$ = lappend($1, $3);
3397                                   else
3398                                         $$ = $1;
3399                                 }
3400                         | RuleActionStmtOrEmpty
3401                                 { if ($1 != (Node *) NULL)
3402                                         $$ = makeList1($1);
3403                                   else
3404                                         $$ = NIL;
3405                                 }
3406                 ;
3407
3408 RuleActionStmt:
3409                         SelectStmt
3410                         | InsertStmt
3411                         | UpdateStmt
3412                         | DeleteStmt
3413                         | NotifyStmt
3414                 ;
3415
3416 RuleActionStmtOrEmpty:
3417                         RuleActionStmt                                                  { $$ = $1; }
3418                         |       /*EMPTY*/                                                       { $$ = (Node *)NULL; }
3419                 ;
3420
3421 /* change me to select, update, etc. some day */
3422 event:          SELECT                                                                  { $$ = CMD_SELECT; }
3423                         | UPDATE                                                                { $$ = CMD_UPDATE; }
3424                         | DELETE_P                                                              { $$ = CMD_DELETE; }
3425                         | INSERT                                                                { $$ = CMD_INSERT; }
3426                  ;
3427
3428 opt_instead:
3429                         INSTEAD                                                                 { $$ = TRUE; }
3430                         | /*EMPTY*/                                                             { $$ = FALSE; }
3431                 ;
3432
3433
3434 DropRuleStmt:
3435                         DROP RULE name ON qualified_name opt_drop_behavior
3436                                 {
3437                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
3438                                         n->relation = $5;
3439                                         n->property = $3;
3440                                         n->behavior = $6;
3441                                         n->removeType = DROP_RULE;
3442                                         $$ = (Node *) n;
3443                                 }
3444                 ;
3445
3446
3447 /*****************************************************************************
3448  *
3449  *              QUERY:
3450  *                              NOTIFY <qualified_name> can appear both in rule bodies and
3451  *                              as a query-level command
3452  *
3453  *****************************************************************************/
3454
3455 NotifyStmt: NOTIFY qualified_name
3456                                 {
3457                                         NotifyStmt *n = makeNode(NotifyStmt);
3458                                         n->relation = $2;
3459                                         $$ = (Node *)n;
3460                                 }
3461                 ;
3462
3463 ListenStmt: LISTEN qualified_name
3464                                 {
3465                                         ListenStmt *n = makeNode(ListenStmt);
3466                                         n->relation = $2;
3467                                         $$ = (Node *)n;
3468                                 }
3469                 ;
3470
3471 UnlistenStmt:
3472                         UNLISTEN qualified_name
3473                                 {
3474                                         UnlistenStmt *n = makeNode(UnlistenStmt);
3475                                         n->relation = $2;
3476                                         $$ = (Node *)n;
3477                                 }
3478                         | UNLISTEN '*'
3479                                 {
3480                                         UnlistenStmt *n = makeNode(UnlistenStmt);
3481                                         n->relation = makeNode(RangeVar);
3482                                         n->relation->relname = "*";
3483                                         n->relation->schemaname = NULL;
3484                                         $$ = (Node *)n;
3485                                 }
3486                 ;
3487
3488
3489 /*****************************************************************************
3490  *
3491  *              Transactions:
3492  *
3493  *              BEGIN / COMMIT / ROLLBACK
3494  *              (also older versions END / ABORT)
3495  *
3496  *****************************************************************************/
3497
3498 TransactionStmt:
3499                         ABORT_TRANS opt_trans
3500                                 {
3501                                         TransactionStmt *n = makeNode(TransactionStmt);
3502                                         n->command = ROLLBACK;
3503                                         n->options = NIL;
3504                                         $$ = (Node *)n;
3505                                 }
3506                         | BEGIN_TRANS opt_trans
3507                                 {
3508                                         TransactionStmt *n = makeNode(TransactionStmt);
3509                                         n->command = BEGIN_TRANS;
3510                                         n->options = NIL;
3511                                         $$ = (Node *)n;
3512                                 }
3513                         | START TRANSACTION trans_options
3514                                 {
3515                                         TransactionStmt *n = makeNode(TransactionStmt);
3516                                         n->command = START;
3517                                         n->options = $3;
3518                                         $$ = (Node *)n;
3519                                 }
3520                         | COMMIT opt_trans
3521                                 {
3522                                         TransactionStmt *n = makeNode(TransactionStmt);
3523                                         n->command = COMMIT;
3524                                         n->options = NIL;
3525                                         $$ = (Node *)n;
3526                                 }
3527                         | END_TRANS opt_trans
3528                                 {
3529                                         TransactionStmt *n = makeNode(TransactionStmt);
3530                                         n->command = COMMIT;
3531                                         n->options = NIL;
3532                                         $$ = (Node *)n;
3533                                 }
3534                         | ROLLBACK opt_trans
3535                                 {
3536                                         TransactionStmt *n = makeNode(TransactionStmt);
3537                                         n->command = ROLLBACK;
3538                                         n->options = NIL;
3539                                         $$ = (Node *)n;
3540                                 }
3541                 ;
3542
3543 trans_options:  ISOLATION LEVEL iso_level
3544                                                                         { $$ = makeList1(makeStringConst($3, NULL)); }
3545                          |      /* EMPTY */                     { $$ = NIL; }
3546                          ;
3547
3548 opt_trans:      WORK                                                                    {}
3549                         | TRANSACTION                                                   {}
3550                         | /*EMPTY*/                                                             {}
3551                 ;
3552
3553 /*****************************************************************************
3554  *
3555  *              QUERY:
3556  *                              create view <viewname> '('target-list ')' AS <query>
3557  *
3558  *****************************************************************************/
3559
3560 ViewStmt:       CREATE opt_or_replace VIEW qualified_name opt_column_list
3561                                 AS SelectStmt
3562                                 {
3563                                         ViewStmt *n = makeNode(ViewStmt);
3564                                         n->replace = $2;
3565                                         n->view = $4;
3566                                         n->aliases = $5;
3567                                         n->query = (Query *) $7;
3568                                         $$ = (Node *)n;
3569                                 }
3570                 ;
3571
3572
3573 /*****************************************************************************
3574  *
3575  *              QUERY:
3576  *                              load "filename"
3577  *
3578  *****************************************************************************/
3579
3580 LoadStmt:       LOAD file_name
3581                                 {
3582                                         LoadStmt *n = makeNode(LoadStmt);
3583                                         n->filename = $2;
3584                                         $$ = (Node *)n;
3585                                 }
3586                 ;
3587
3588
3589 /*****************************************************************************
3590  *
3591  *              CREATE DATABASE
3592  *
3593  *****************************************************************************/
3594
3595 CreatedbStmt:
3596                         CREATE DATABASE database_name opt_with createdb_opt_list
3597                                 {
3598                                         CreatedbStmt *n = makeNode(CreatedbStmt);
3599                                         n->dbname = $3;
3600                                         n->options = $5;
3601                                         $$ = (Node *)n;
3602                                 }
3603                 ;
3604
3605 createdb_opt_list:
3606                         createdb_opt_list createdb_opt_item             { $$ = lappend($1, $2); }
3607                         | /* EMPTY */                                                   { $$ = NIL; }
3608                 ;
3609
3610 createdb_opt_item:
3611                         LOCATION opt_equal Sconst
3612                                 {
3613                                         $$ = makeDefElem("location", (Node *)makeString($3));
3614                                 }
3615                         | LOCATION opt_equal DEFAULT
3616                                 {
3617                                         $$ = makeDefElem("location", NULL);
3618                                 }
3619                         | TEMPLATE opt_equal name
3620                                 {
3621                                         $$ = makeDefElem("template", (Node *)makeString($3));
3622                                 }
3623                         | TEMPLATE opt_equal DEFAULT
3624                                 {
3625                                         $$ = makeDefElem("template", NULL);
3626                                 }
3627                         | ENCODING opt_equal Sconst
3628                                 {
3629                                         $$ = makeDefElem("encoding", (Node *)makeString($3));
3630                                 }
3631                         | ENCODING opt_equal Iconst
3632                                 {
3633                                         $$ = makeDefElem("encoding", (Node *)makeInteger($3));
3634                                 }
3635                         | ENCODING opt_equal DEFAULT
3636                                 {
3637                                         $$ = makeDefElem("encoding", NULL);
3638                                 }
3639                         | OWNER opt_equal name
3640                                 {
3641                                         $$ = makeDefElem("owner", (Node *)makeString($3));
3642                                 }
3643                         | OWNER opt_equal DEFAULT
3644                                 {
3645                                         $$ = makeDefElem("owner", NULL);
3646                                 }
3647                 ;
3648
3649 /*
3650  *      Though the equals sign doesn't match other WITH options, pg_dump uses
3651  *      equals for backward compability, and it doesn't seem worth removing it.
3652  *      2002-02-25
3653  */
3654 opt_equal:      '='                                                                             {}
3655                         | /*EMPTY*/                                                             {}
3656                 ;
3657
3658
3659 /*****************************************************************************
3660  *
3661  *              ALTER DATABASE
3662  *
3663  *****************************************************************************/
3664
3665 AlterDatabaseSetStmt:
3666                         ALTER DATABASE database_name SET set_rest
3667                                 {
3668                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
3669                                         n->dbname = $3;
3670                                         n->variable = $5->name;
3671                                         n->value = $5->args;
3672                                         $$ = (Node *)n;
3673                                 }
3674                         | ALTER DATABASE database_name VariableResetStmt
3675                                 {
3676                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
3677                                         n->dbname = $3;
3678                                         n->variable = ((VariableResetStmt *)$4)->name;
3679                                         n->value = NIL;
3680                                         $$ = (Node *)n;
3681                                 }
3682                 ;
3683
3684
3685 /*****************************************************************************
3686  *
3687  *              DROP DATABASE
3688  *
3689  * This is implicitly CASCADE, no need for drop behavior
3690  *****************************************************************************/
3691
3692 DropdbStmt: DROP DATABASE database_name
3693                                 {
3694                                         DropdbStmt *n = makeNode(DropdbStmt);
3695                                         n->dbname = $3;
3696                                         $$ = (Node *)n;
3697                                 }
3698                 ;
3699
3700
3701 /*****************************************************************************
3702  *
3703  * Manipulate a domain
3704  *
3705  *****************************************************************************/
3706
3707 CreateDomainStmt:
3708                         CREATE DOMAIN_P any_name opt_as Typename ColQualList opt_collate
3709                                 {
3710                                         CreateDomainStmt *n = makeNode(CreateDomainStmt);
3711                                         n->domainname = $3;
3712                                         n->typename = $5;
3713                                         n->constraints = $6;
3714
3715                                         if ($7 != NULL)
3716                                                 elog(NOTICE,"CREATE DOMAIN / COLLATE %s not yet "
3717                                                         "implemented; clause ignored", $7);
3718                                         $$ = (Node *)n;
3719                                 }
3720                 ;
3721
3722 AlterDomainStmt:
3723                         /* ALTER DOMAIN <domain> {SET DEFAULT <expr>|DROP DEFAULT} */
3724                         ALTER DOMAIN_P any_name alter_column_default
3725                                 {
3726                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
3727                                         n->subtype = 'T';
3728                                         n->typename = $3;
3729                                         n->def = $4;
3730                                         $$ = (Node *)n;
3731                                 }
3732                         /* ALTER DOMAIN <domain> DROP NOT NULL */
3733                         | ALTER DOMAIN_P any_name DROP NOT NULL_P
3734                                 {
3735                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
3736                                         n->subtype = 'N';
3737                                         n->typename = $3;
3738                                         $$ = (Node *)n;
3739                                 }
3740                         /* ALTER DOMAIN <domain> SET NOT NULL */
3741                         | ALTER DOMAIN_P any_name SET NOT NULL_P
3742                                 {
3743                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
3744                                         n->subtype = 'O';
3745                                         n->typename = $3;
3746                                         $$ = (Node *)n;
3747                                 }
3748                         /* ALTER DOMAIN <domain> ADD CONSTRAINT ... */
3749                         | ALTER DOMAIN_P any_name ADD TableConstraint
3750                                 {
3751                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
3752                                         n->subtype = 'C';
3753                                         n->typename = $3;
3754                                         n->def = $5;
3755                                         $$ = (Node *)n;
3756                                 }
3757                         /* ALTER DOMAIN <domain> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
3758                         | ALTER DOMAIN_P any_name DROP CONSTRAINT name opt_drop_behavior
3759                                 {
3760                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
3761                                         n->subtype = 'X';
3762                                         n->typename = $3;
3763                                         n->name = $6;
3764                                         n->behavior = $7;
3765                                         $$ = (Node *)n;
3766                                 }
3767                         ;
3768
3769 opt_as:         AS                                                                              {}
3770                         | /* EMPTY */                                                   {}
3771                 ;
3772
3773
3774 /*****************************************************************************
3775  *
3776  * Manipulate a conversion
3777  *
3778  *              CREATE [DEFAULT] CONVERSION <conversion_name>
3779  *              FOR <encoding_name> TO <encoding_name> FROM <func_name>
3780  *
3781  *****************************************************************************/
3782
3783 CreateConversionStmt:
3784                         CREATE opt_default CONVERSION_P any_name FOR Sconst
3785                         TO Sconst FROM any_name
3786                         {
3787                           CreateConversionStmt *n = makeNode(CreateConversionStmt);
3788                           n->conversion_name = $4;
3789                           n->for_encoding_name = $6;
3790                           n->to_encoding_name = $8;
3791                           n->func_name = $10;
3792                           n->def = $2;
3793                           $$ = (Node *)n;
3794                         }
3795                 ;
3796
3797 /*****************************************************************************
3798  *
3799  *              QUERY:
3800  *                              cluster <index_name> on <qualified_name>
3801  *                              cluster <qualified_name>
3802  *                              cluster
3803  *
3804  *****************************************************************************/
3805
3806 ClusterStmt:
3807                         CLUSTER index_name ON qualified_name
3808                                 {
3809                                    ClusterStmt *n = makeNode(ClusterStmt);
3810                                    n->relation = $4;
3811                                    n->indexname = $2;
3812                                    $$ = (Node*)n;
3813                                 }
3814                         | CLUSTER qualified_name
3815                                 {
3816                                ClusterStmt *n = makeNode(ClusterStmt);
3817                                    n->relation = $2;
3818                                    n->indexname = NULL;
3819                                    $$ = (Node*)n;
3820                                 }
3821                         | CLUSTER
3822                             {
3823                                    ClusterStmt *n = makeNode(ClusterStmt);
3824                                    n->relation = NULL;
3825                                    n->indexname = NULL;
3826                                    $$ = (Node*)n;
3827                                 }
3828                 ;
3829
3830 /*****************************************************************************
3831  *
3832  *              QUERY:
3833  *                              vacuum
3834  *                              analyze
3835  *
3836  *****************************************************************************/
3837
3838 VacuumStmt: VACUUM opt_full opt_freeze opt_verbose
3839                                 {
3840                                         VacuumStmt *n = makeNode(VacuumStmt);
3841                                         n->vacuum = true;
3842                                         n->analyze = false;
3843                                         n->full = $2;
3844                                         n->freeze = $3;
3845                                         n->verbose = $4;
3846                                         n->relation = NULL;
3847                                         n->va_cols = NIL;
3848                                         $$ = (Node *)n;
3849                                 }
3850                         | VACUUM opt_full opt_freeze opt_verbose qualified_name
3851                                 {
3852                                         VacuumStmt *n = makeNode(VacuumStmt);
3853                                         n->vacuum = true;
3854                                         n->analyze = false;
3855                                         n->full = $2;
3856                                         n->freeze = $3;
3857                                         n->verbose = $4;
3858                                         n->relation = $5;
3859                                         n->va_cols = NIL;
3860                                         $$ = (Node *)n;
3861                                 }
3862                         | VACUUM opt_full opt_freeze opt_verbose AnalyzeStmt
3863                                 {
3864                                         VacuumStmt *n = (VacuumStmt *) $5;
3865                                         n->vacuum = true;
3866                                         n->full = $2;
3867                                         n->freeze = $3;
3868                                         n->verbose |= $4;
3869                                         $$ = (Node *)n;
3870                                 }
3871                 ;
3872
3873 AnalyzeStmt:
3874                         analyze_keyword opt_verbose
3875                                 {
3876                                         VacuumStmt *n = makeNode(VacuumStmt);
3877                                         n->vacuum = false;
3878                                         n->analyze = true;
3879                                         n->full = false;
3880                                         n->freeze = false;
3881                                         n->verbose = $2;
3882                                         n->relation = NULL;
3883                                         n->va_cols = NIL;
3884                                         $$ = (Node *)n;
3885                                 }
3886                         | analyze_keyword opt_verbose qualified_name opt_name_list
3887                                 {
3888                                         VacuumStmt *n = makeNode(VacuumStmt);
3889                                         n->vacuum = false;
3890                                         n->analyze = true;
3891                                         n->full = false;
3892                                         n->freeze = false;
3893                                         n->verbose = $2;
3894                                         n->relation = $3;
3895                                         n->va_cols = $4;
3896                                         $$ = (Node *)n;
3897                                 }
3898                 ;
3899
3900 analyze_keyword:
3901                         ANALYZE                                                                 {}
3902                         | ANALYSE /* British */                                 {}
3903                 ;
3904
3905 opt_verbose:
3906                         VERBOSE                                                                 { $$ = TRUE; }
3907                         | /*EMPTY*/                                                             { $$ = FALSE; }
3908                 ;
3909
3910 opt_full:       FULL                                                                    { $$ = TRUE; }
3911                         | /*EMPTY*/                                                             { $$ = FALSE; }
3912                 ;
3913
3914 opt_freeze: FREEZE                                                                      { $$ = TRUE; }
3915                         | /*EMPTY*/                                                             { $$ = FALSE; }
3916                 ;
3917
3918 opt_name_list:
3919                         '(' name_list ')'                                               { $$ = $2; }
3920                         | /*EMPTY*/                                                             { $$ = NIL; }
3921                 ;
3922
3923
3924 /*****************************************************************************
3925  *
3926  *              QUERY:
3927  *                              EXPLAIN query
3928  *                              EXPLAIN ANALYZE query
3929  *
3930  *****************************************************************************/
3931
3932 ExplainStmt:
3933                         EXPLAIN opt_verbose OptimizableStmt
3934                                 {
3935                                         ExplainStmt *n = makeNode(ExplainStmt);
3936                                         n->verbose = $2;
3937                                         n->analyze = FALSE;
3938                                         n->query = (Query*)$3;
3939                                         $$ = (Node *)n;
3940                                 }
3941                         | EXPLAIN analyze_keyword opt_verbose OptimizableStmt
3942                                 {
3943                                         ExplainStmt *n = makeNode(ExplainStmt);
3944                                         n->verbose = $3;
3945                                         n->analyze = TRUE;
3946                                         n->query = (Query*)$4;
3947                                         $$ = (Node *)n;
3948                                 }
3949                 ;
3950
3951 /*****************************************************************************
3952  *
3953  *              QUERY:
3954  *                              PREPARE <plan_name> [(args, ...)] AS <query>
3955  *
3956  *****************************************************************************/
3957
3958 PrepareStmt: PREPARE name prep_type_clause AS OptimizableStmt
3959                                 {
3960                                         PrepareStmt *n = makeNode(PrepareStmt);
3961                                         n->name = $2;
3962                                         n->argtypes = $3;
3963                                         n->query = (Query *) $5;
3964                                         $$ = (Node *) n;
3965                                 }
3966                 ;
3967
3968 prep_type_clause: '(' prep_type_list ')'        { $$ = $2; }
3969                                 | /* EMPTY */                           { $$ = NIL; }
3970                 ;
3971
3972 prep_type_list: Typename                        { $$ = makeList1($1); }
3973                           | prep_type_list ',' Typename
3974                                                                         { $$ = lappend($1, $3); }
3975                 ;
3976
3977 /*****************************************************************************
3978  *
3979  *              QUERY:
3980  *                              EXECUTE <plan_name> [(params, ...)] [INTO ...]
3981  *
3982  *****************************************************************************/
3983
3984 ExecuteStmt: EXECUTE name execute_param_clause into_clause
3985                                 {
3986                                         ExecuteStmt *n = makeNode(ExecuteStmt);
3987                                         n->name = $2;
3988                                         n->params = $3;
3989                                         n->into = $4;
3990                                         $$ = (Node *) n;
3991                                 }
3992                 ;
3993
3994 execute_param_clause: '(' expr_list ')'                         { $$ = $2; }
3995                                         | /* EMPTY */                                   { $$ = NIL; }
3996                                         ;
3997
3998 /*****************************************************************************
3999  *
4000  *              QUERY:
4001  *                              DEALLOCATE [PREPARE] <plan_name>
4002  *
4003  *****************************************************************************/
4004
4005 DeallocateStmt: DEALLOCATE name
4006                                         {
4007                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
4008                                                 n->name = $2;
4009                                                 $$ = (Node *) n;
4010                                         }
4011                                 | DEALLOCATE PREPARE name
4012                                         {
4013                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
4014                                                 n->name = $3;
4015                                                 $$ = (Node *) n;
4016                                         }
4017                 ;
4018
4019 /*****************************************************************************
4020  *                                                                                                                                                       *
4021  *              Optimizable Stmts:                                                                                                       *
4022  *                                                                                                                                                       *
4023  *              one of the five queries processed by the planner                                         *
4024  *                                                                                                                                                       *
4025  *              [ultimately] produces query-trees as specified                                           *
4026  *              in the query-spec document in ~postgres/ref                                                      *
4027  *                                                                                                                                                       *
4028  *****************************************************************************/
4029
4030 OptimizableStmt:
4031                         SelectStmt
4032                         | CursorStmt
4033                         | UpdateStmt
4034                         | InsertStmt
4035                         | DeleteStmt                                    /* by default all are $$=$1 */
4036                 ;
4037
4038
4039 /*****************************************************************************
4040  *
4041  *              QUERY:
4042  *                              INSERT STATEMENTS
4043  *
4044  *****************************************************************************/
4045
4046 InsertStmt:
4047                         INSERT INTO qualified_name insert_rest
4048                                 {
4049                                         $4->relation = $3;
4050                                         $$ = (Node *) $4;
4051                                 }
4052                 ;
4053
4054 insert_rest:
4055                         VALUES '(' insert_target_list ')'
4056                                 {
4057                                         $$ = makeNode(InsertStmt);
4058                                         $$->cols = NIL;
4059                                         $$->targetList = $3;
4060                                         $$->selectStmt = NULL;
4061                                 }
4062                         | DEFAULT VALUES
4063                                 {
4064                                         $$ = makeNode(InsertStmt);
4065                                         $$->cols = NIL;
4066                                         $$->targetList = NIL;
4067                                         $$->selectStmt = NULL;
4068                                 }
4069                         | SelectStmt
4070                                 {
4071                                         $$ = makeNode(InsertStmt);
4072                                         $$->cols = NIL;
4073                                         $$->targetList = NIL;
4074                                         $$->selectStmt = $1;
4075                                 }
4076                         | '(' insert_column_list ')' VALUES '(' insert_target_list ')'
4077                                 {
4078                                         $$ = makeNode(InsertStmt);
4079                                         $$->cols = $2;
4080                                         $$->targetList = $6;
4081                                         $$->selectStmt = NULL;
4082                                 }
4083                         | '(' insert_column_list ')' SelectStmt
4084                                 {
4085                                         $$ = makeNode(InsertStmt);
4086                                         $$->cols = $2;
4087                                         $$->targetList = NIL;
4088                                         $$->selectStmt = $4;
4089                                 }
4090                 ;
4091
4092 insert_column_list:
4093                         insert_column_item                                              { $$ = makeList1($1); }
4094                         | insert_column_list ',' insert_column_item
4095                                         { $$ = lappend($1, $3); }
4096                 ;
4097
4098 insert_column_item:
4099                         ColId opt_indirection
4100                                 {
4101                                         ResTarget *n = makeNode(ResTarget);
4102                                         n->name = $1;
4103                                         n->indirection = $2;
4104                                         n->val = NULL;
4105                                         $$ = (Node *)n;
4106                                 }
4107                 ;
4108
4109
4110 /*****************************************************************************
4111  *
4112  *              QUERY:
4113  *                              DELETE STATEMENTS
4114  *
4115  *****************************************************************************/
4116
4117 DeleteStmt: DELETE_P FROM relation_expr where_clause
4118                                 {
4119                                         DeleteStmt *n = makeNode(DeleteStmt);
4120                                         n->relation = $3;
4121                                         n->whereClause = $4;
4122                                         $$ = (Node *)n;
4123                                 }
4124                 ;
4125
4126 LockStmt:       LOCK_P opt_table qualified_name_list opt_lock
4127                                 {
4128                                         LockStmt *n = makeNode(LockStmt);
4129
4130                                         n->relations = $3;
4131                                         n->mode = $4;
4132                                         $$ = (Node *)n;
4133                                 }
4134                 ;
4135
4136 opt_lock:       IN_P lock_type MODE                     { $$ = $2; }
4137                         | /*EMPTY*/                                             { $$ = AccessExclusiveLock; }
4138                 ;
4139
4140 lock_type:      ACCESS SHARE                                    { $$ = AccessShareLock; }
4141                         | ROW SHARE                                             { $$ = RowShareLock; }
4142                         | ROW EXCLUSIVE                                 { $$ = RowExclusiveLock; }
4143                         | SHARE UPDATE EXCLUSIVE                { $$ = ShareUpdateExclusiveLock; }
4144                         | SHARE                                                 { $$ = ShareLock; }
4145                         | SHARE ROW EXCLUSIVE                   { $$ = ShareRowExclusiveLock; }
4146                         | EXCLUSIVE                                             { $$ = ExclusiveLock; }
4147                         | ACCESS EXCLUSIVE                              { $$ = AccessExclusiveLock; }
4148                 ;
4149
4150
4151 /*****************************************************************************
4152  *
4153  *              QUERY:
4154  *                              UpdateStmt (UPDATE)
4155  *
4156  *****************************************************************************/
4157
4158 UpdateStmt: UPDATE relation_expr
4159                         SET update_target_list
4160                         from_clause
4161                         where_clause
4162                                 {
4163                                         UpdateStmt *n = makeNode(UpdateStmt);
4164                                         n->relation = $2;
4165                                         n->targetList = $4;
4166                                         n->fromClause = $5;
4167                                         n->whereClause = $6;
4168                                         $$ = (Node *)n;
4169                                 }
4170                 ;
4171
4172
4173 /*****************************************************************************
4174  *
4175  *              QUERY:
4176  *                              CURSOR STATEMENTS
4177  *
4178  *****************************************************************************/
4179 CursorStmt: DECLARE name opt_cursor CURSOR FOR SelectStmt
4180                                 {
4181                                         SelectStmt *n = (SelectStmt *)$6;
4182                                         n->portalname = $2;
4183                                         n->binary = $3;
4184                                         $$ = $6;
4185                                 }
4186                 ;
4187
4188 opt_cursor: BINARY                                                                      { $$ = TRUE; }
4189                         | INSENSITIVE                                                   { $$ = FALSE; }
4190                         | SCROLL                                                                { $$ = FALSE; }
4191                         | INSENSITIVE SCROLL                                    { $$ = FALSE; }
4192                         | /*EMPTY*/                                                             { $$ = FALSE; }
4193                 ;
4194
4195 /*****************************************************************************
4196  *
4197  *              QUERY:
4198  *                              SELECT STATEMENTS
4199  *
4200  *****************************************************************************/
4201
4202 /* A complete SELECT statement looks like this.
4203  *
4204  * The rule returns either a single SelectStmt node or a tree of them,
4205  * representing a set-operation tree.
4206  *
4207  * There is an ambiguity when a sub-SELECT is within an a_expr and there
4208  * are excess parentheses: do the parentheses belong to the sub-SELECT or
4209  * to the surrounding a_expr?  We don't really care, but yacc wants to know.
4210  * To resolve the ambiguity, we are careful to define the grammar so that
4211  * the decision is staved off as long as possible: as long as we can keep
4212  * absorbing parentheses into the sub-SELECT, we will do so, and only when
4213  * it's no longer possible to do that will we decide that parens belong to
4214  * the expression.      For example, in "SELECT (((SELECT 2)) + 3)" the extra
4215  * parentheses are treated as part of the sub-select.  The necessity of doing
4216  * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)".      Had we
4217  * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
4218  * SELECT viewpoint when we see the UNION.
4219  *
4220  * This approach is implemented by defining a nonterminal select_with_parens,
4221  * which represents a SELECT with at least one outer layer of parentheses,
4222  * and being careful to use select_with_parens, never '(' SelectStmt ')',
4223  * in the expression grammar.  We will then have shift-reduce conflicts
4224  * which we can resolve in favor of always treating '(' <select> ')' as
4225  * a select_with_parens.  To resolve the conflicts, the productions that
4226  * conflict with the select_with_parens productions are manually given
4227  * precedences lower than the precedence of ')', thereby ensuring that we
4228  * shift ')' (and then reduce to select_with_parens) rather than trying to
4229  * reduce the inner <select> nonterminal to something else.  We use UMINUS
4230  * precedence for this, which is a fairly arbitrary choice.
4231  *
4232  * To be able to define select_with_parens itself without ambiguity, we need
4233  * a nonterminal select_no_parens that represents a SELECT structure with no
4234  * outermost parentheses.  This is a little bit tedious, but it works.
4235  *
4236  * In non-expression contexts, we use SelectStmt which can represent a SELECT
4237  * with or without outer parentheses.
4238  */
4239
4240 SelectStmt: select_no_parens                    %prec UMINUS
4241                         | select_with_parens            %prec UMINUS
4242                 ;
4243
4244 select_with_parens:
4245                         '(' select_no_parens ')'                                { $$ = $2; }
4246                         | '(' select_with_parens ')'                    { $$ = $2; }
4247                 ;
4248
4249 /*
4250  *      FOR UPDATE may be before or after LIMIT/OFFSET.
4251  *      In <=7.2.X, LIMIT/OFFSET had to be after FOR UPDATE
4252  *      We now support both orderings, but prefer LIMIT/OFFSET before FOR UPDATE
4253  *      2002-08-28 bjm
4254  */
4255 select_no_parens:
4256                         simple_select                                           { $$ = $1; }
4257                         | select_clause sort_clause
4258                                 {
4259                                         insertSelectOptions((SelectStmt *) $1, $2, NIL,
4260                                                                                 NULL, NULL);
4261                                         $$ = $1;
4262                                 }
4263                         | select_clause opt_sort_clause for_update_clause opt_select_limit
4264                                 {
4265                                         insertSelectOptions((SelectStmt *) $1, $2, $3,
4266                                                                                 nth(0, $4), nth(1, $4));
4267                                         $$ = $1;
4268                                 }
4269                         | select_clause opt_sort_clause select_limit opt_for_update_clause
4270                                 {
4271                                         insertSelectOptions((SelectStmt *) $1, $2, $4,
4272                                                                                 nth(0, $3), nth(1, $3));
4273                                         $$ = $1;
4274                                 }
4275                 ;
4276
4277 select_clause:
4278                         simple_select                                                   { $$ = $1; }
4279                         | select_with_parens                                    { $$ = $1; }
4280                 ;
4281
4282 /*
4283  * This rule parses SELECT statements that can appear within set operations,
4284  * including UNION, INTERSECT and EXCEPT.  '(' and ')' can be used to specify
4285  * the ordering of the set operations.  Without '(' and ')' we want the
4286  * operations to be ordered per the precedence specs at the head of this file.
4287  *
4288  * As with select_no_parens, simple_select cannot have outer parentheses,
4289  * but can have parenthesized subclauses.
4290  *
4291  * Note that sort clauses cannot be included at this level --- SQL92 requires
4292  *              SELECT foo UNION SELECT bar ORDER BY baz
4293  * to be parsed as
4294  *              (SELECT foo UNION SELECT bar) ORDER BY baz
4295  * not
4296  *              SELECT foo UNION (SELECT bar ORDER BY baz)
4297  * Likewise FOR UPDATE and LIMIT.  Therefore, those clauses are described
4298  * as part of the select_no_parens production, not simple_select.
4299  * This does not limit functionality, because you can reintroduce sort and
4300  * limit clauses inside parentheses.
4301  *
4302  * NOTE: only the leftmost component SelectStmt should have INTO.
4303  * However, this is not checked by the grammar; parse analysis must check it.
4304  */
4305 simple_select:
4306                         SELECT opt_distinct target_list
4307                         into_clause from_clause where_clause
4308                         group_clause having_clause
4309                                 {
4310                                         SelectStmt *n = makeNode(SelectStmt);
4311                                         n->distinctClause = $2;
4312                                         n->targetList = $3;
4313                                         n->into = $4;
4314                                         n->intoColNames = NIL;
4315                                         n->fromClause = $5;
4316                                         n->whereClause = $6;
4317                                         n->groupClause = $7;
4318                                         n->havingClause = $8;
4319                                         $$ = (Node *)n;
4320                                 }
4321                         | select_clause UNION opt_all select_clause
4322                                 {
4323                                         $$ = makeSetOp(SETOP_UNION, $3, $1, $4);
4324                                 }
4325                         | select_clause INTERSECT opt_all select_clause
4326                                 {
4327                                         $$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
4328                                 }
4329                         | select_clause EXCEPT opt_all select_clause
4330                                 {
4331                                         $$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
4332                                 }
4333                 ;
4334
4335 into_clause:
4336                         INTO OptTempTableName                                   { $$ = $2; }
4337                         | /*EMPTY*/                                                             { $$ = NULL; }
4338                 ;
4339
4340 /*
4341  * Redundancy here is needed to avoid shift/reduce conflicts,
4342  * since TEMP is not a reserved word.  See also OptTemp.
4343  */
4344 OptTempTableName:
4345                         TEMPORARY opt_table qualified_name
4346                                 {
4347                                         $$ = $3;
4348                                         $$->istemp = true;
4349                                 }
4350                         | TEMP opt_table qualified_name
4351                                 {
4352                                         $$ = $3;
4353                                         $$->istemp = true;
4354                                 }
4355                         | LOCAL TEMPORARY opt_table qualified_name
4356                                 {
4357                                         $$ = $4;
4358                                         $$->istemp = true;
4359                                 }
4360                         | LOCAL TEMP opt_table qualified_name
4361                                 {
4362                                         $$ = $4;
4363                                         $$->istemp = true;
4364                                 }
4365                         | GLOBAL TEMPORARY opt_table qualified_name
4366                                 {
4367                                         elog(ERROR,
4368                                                 "GLOBAL TEMPORARY TABLE is not currently supported");
4369                                         $$ = $4;
4370                                         $$->istemp = true;
4371                                 }
4372                         | GLOBAL TEMP opt_table qualified_name
4373                                 {
4374                                         elog(ERROR,
4375                                                 "GLOBAL TEMPORARY TABLE is not currently supported");
4376                                         $$ = $4;
4377                                         $$->istemp = true;
4378                                 }
4379                         | TABLE qualified_name
4380                                 {
4381                                         $$ = $2;
4382                                         $$->istemp = false;
4383                                 }
4384                         | qualified_name
4385                                 {
4386                                         $$ = $1;
4387                                         $$->istemp = false;
4388                                 }
4389                 ;
4390
4391 opt_table:      TABLE                                                                   {}
4392                         | /*EMPTY*/                                                             {}
4393                 ;
4394
4395 opt_all:        ALL                                                                             { $$ = TRUE; }
4396                         | DISTINCT                                                              { $$ = FALSE; }
4397                         | /*EMPTY*/                                                             { $$ = FALSE; }
4398                 ;
4399
4400 /* We use (NIL) as a placeholder to indicate that all target expressions
4401  * should be placed in the DISTINCT list during parsetree analysis.
4402  */
4403 opt_distinct:
4404                         DISTINCT                                                                { $$ = makeList1(NIL); }
4405                         | DISTINCT ON '(' expr_list ')'                 { $$ = $4; }
4406                         | ALL                                                                   { $$ = NIL; }
4407                         | /*EMPTY*/                                                             { $$ = NIL; }
4408                 ;
4409
4410 opt_sort_clause:
4411                         sort_clause                                                             { $$ = $1;}
4412                         | /*EMPTY*/                                                             { $$ = NIL; }
4413                 ;
4414
4415 sort_clause:
4416                         ORDER BY sortby_list                                    { $$ = $3; }
4417                 ;
4418
4419 sortby_list:
4420                         sortby                                                                  { $$ = makeList1($1); }
4421                         | sortby_list ',' sortby                                { $$ = lappend($1, $3); }
4422                 ;
4423
4424 sortby:         a_expr OptUseOp
4425                                 {
4426                                         $$ = makeNode(SortGroupBy);
4427                                         $$->node = $1;
4428                                         $$->useOp = $2;
4429                                 }
4430                 ;
4431
4432 OptUseOp:       USING qual_all_Op                                               { $$ = $2; }
4433                         | ASC
4434                                                         { $$ = makeList1(makeString("<")); }
4435                         | DESC
4436                                                         { $$ = makeList1(makeString(">")); }
4437                         | /*EMPTY*/
4438                                                         { $$ = makeList1(makeString("<"));      /*default*/ }
4439                 ;
4440
4441
4442 select_limit:
4443                         LIMIT select_limit_value OFFSET select_offset_value
4444                                 { $$ = makeList2($4, $2); }
4445                         | OFFSET select_offset_value LIMIT select_limit_value
4446                                 { $$ = makeList2($2, $4); }
4447                         | LIMIT select_limit_value
4448                                 { $$ = makeList2(NULL, $2); }
4449                         | OFFSET select_offset_value
4450                                 { $$ = makeList2($2, NULL); }
4451                         | LIMIT select_limit_value ',' select_offset_value
4452                                 /* Disabled because it was too confusing, bjm 2002-02-18 */
4453                                 { elog(ERROR,
4454                                         "LIMIT #,# syntax not supported.\n\tUse separate LIMIT and OFFSET clauses."); }
4455                 ;
4456
4457
4458 opt_select_limit:
4459                         select_limit                                                    { $$ = $1; }
4460                         | /* EMPTY */
4461                                         { $$ = makeList2(NULL,NULL); }
4462                 ;
4463
4464 select_limit_value:
4465                         Iconst
4466                                 {
4467                                         Const   *n = makeNode(Const);
4468
4469                                         if ($1 < 0)
4470                                                 elog(ERROR, "LIMIT must not be negative");
4471
4472                                         n->consttype    = INT4OID;
4473                                         n->constlen             = sizeof(int4);
4474                                         n->constvalue   = Int32GetDatum($1);
4475                                         n->constisnull  = FALSE;
4476                                         n->constbyval   = TRUE;
4477                                         $$ = (Node *)n;
4478                                 }
4479                         | ALL
4480                                 {
4481                                         /* LIMIT ALL is represented as a NULL constant */
4482                                         Const   *n = makeNode(Const);
4483
4484                                         n->consttype    = INT4OID;
4485                                         n->constlen             = sizeof(int4);
4486                                         n->constvalue   = (Datum) 0;
4487                                         n->constisnull  = TRUE;
4488                                         n->constbyval   = TRUE;
4489                                         $$ = (Node *)n;
4490                                 }
4491                         | PARAM
4492                                 {
4493                                         Param   *n = makeNode(Param);
4494
4495                                         n->paramkind    = PARAM_NUM;
4496                                         n->paramid              = $1;
4497                                         n->paramtype    = INT4OID;
4498                                         $$ = (Node *)n;
4499                                 }
4500                 ;
4501
4502 select_offset_value:
4503                         Iconst
4504                                 {
4505                                         Const   *n = makeNode(Const);
4506
4507                                         if ($1 < 0)
4508                                                 elog(ERROR, "OFFSET must not be negative");
4509
4510                                         n->consttype    = INT4OID;
4511                                         n->constlen             = sizeof(int4);
4512                                         n->constvalue   = Int32GetDatum($1);
4513                                         n->constisnull  = FALSE;
4514                                         n->constbyval   = TRUE;
4515                                         $$ = (Node *)n;
4516                                 }
4517                         | PARAM
4518                                 {
4519                                         Param   *n = makeNode(Param);
4520
4521                                         n->paramkind    = PARAM_NUM;
4522                                         n->paramid              = $1;
4523                                         n->paramtype    = INT4OID;
4524                                         $$ = (Node *)n;
4525                                 }
4526                 ;
4527
4528 /*
4529  *      jimmy bell-style recursive queries aren't supported in the
4530  *      current system.
4531  *
4532  *      ...however, recursive addattr and rename supported.  make special
4533  *      cases for these.
4534  */
4535
4536 group_clause:
4537                         GROUP_P BY expr_list                                    { $$ = $3; }
4538                         | /*EMPTY*/                                                             { $$ = NIL; }
4539                 ;
4540
4541 having_clause:
4542                         HAVING a_expr                                                   { $$ = $2; }
4543                         | /*EMPTY*/                                                             { $$ = NULL; }
4544                 ;
4545
4546 for_update_clause:
4547                         FOR UPDATE update_list                                  { $$ = $3; }
4548                         | FOR READ ONLY                                                 { $$ = NULL; }
4549                 ;
4550
4551 opt_for_update_clause:
4552                         for_update_clause                                               { $$ = $1; }
4553                         | /* EMPTY */                                                   { $$ = NULL; }
4554                 ;
4555
4556 update_list:
4557                         OF name_list                                                    { $$ = $2; }
4558                         | /* EMPTY */                                                   { $$ = makeList1(NULL); }
4559                 ;
4560
4561 /*****************************************************************************
4562  *
4563  *      clauses common to all Optimizable Stmts:
4564  *              from_clause             - allow list of both JOIN expressions and table names
4565  *              where_clause    - qualifications for joins or restrictions
4566  *
4567  *****************************************************************************/
4568
4569 from_clause:
4570                         FROM from_list                                                  { $$ = $2; }
4571                         | /*EMPTY*/                                                             { $$ = NIL; }
4572                 ;
4573
4574 from_list:
4575                         table_ref                                                               { $$ = makeList1($1); }
4576                         | from_list ',' table_ref                               { $$ = lappend($1, $3); }
4577                 ;
4578
4579 /*
4580  * table_ref is where an alias clause can be attached.  Note we cannot make
4581  * alias_clause have an empty production because that causes parse conflicts
4582  * between table_ref := '(' joined_table ')' alias_clause
4583  * and joined_table := '(' joined_table ')'.  So, we must have the
4584  * redundant-looking productions here instead.
4585  */
4586 table_ref:      relation_expr
4587                                 {
4588                                         $$ = (Node *) $1;
4589                                 }
4590                         | relation_expr alias_clause
4591                                 {
4592                                         $1->alias = $2;
4593                                         $$ = (Node *) $1;
4594                                 }
4595                         | func_table
4596                                 {
4597                                         RangeFunction *n = makeNode(RangeFunction);
4598                                         n->funccallnode = $1;
4599                                         n->coldeflist = NIL;
4600                                         $$ = (Node *) n;
4601                                 }
4602                         | func_table alias_clause
4603                                 {
4604                                         RangeFunction *n = makeNode(RangeFunction);
4605                                         n->funccallnode = $1;
4606                                         n->alias = $2;
4607                                         n->coldeflist = NIL;
4608                                         $$ = (Node *) n;
4609                                 }
4610                         | func_table AS '(' TableFuncElementList ')'
4611                                 {
4612                                         RangeFunction *n = makeNode(RangeFunction);
4613                                         n->funccallnode = $1;
4614                                         n->coldeflist = $4;
4615                                         $$ = (Node *) n;
4616                                 }
4617                         | func_table AS ColId '(' TableFuncElementList ')'
4618                                 {
4619                                         RangeFunction *n = makeNode(RangeFunction);
4620                                         Alias *a = makeNode(Alias);
4621                                         n->funccallnode = $1;
4622                                         a->aliasname = $3;
4623                                         n->alias = a;
4624                                         n->coldeflist = $5;
4625                                         $$ = (Node *) n;
4626                                 }
4627                         | func_table ColId '(' TableFuncElementList ')'
4628                                 {
4629                                         RangeFunction *n = makeNode(RangeFunction);
4630                                         Alias *a = makeNode(Alias);
4631                                         n->funccallnode = $1;
4632                                         a->aliasname = $2;
4633                                         n->alias = a;
4634                                         n->coldeflist = $4;
4635                                         $$ = (Node *) n;
4636                                 }
4637                         | select_with_parens
4638                                 {
4639                                         /*
4640                                          * The SQL spec does not permit a subselect
4641                                          * (<derived_table>) without an alias clause,
4642                                          * so we don't either.  This avoids the problem
4643                                          * of needing to invent a unique refname for it.
4644                                          * That could be surmounted if there's sufficient
4645                                          * popular demand, but for now let's just implement
4646                                          * the spec and see if anyone complains.
4647                                          * However, it does seem like a good idea to emit
4648                                          * an error message that's better than "parse error".
4649                                          */
4650                                         elog(ERROR, "sub-SELECT in FROM must have an alias"
4651                                                  "\n\tFor example, FROM (SELECT ...) [AS] foo");
4652                                         $$ = NULL;
4653                                 }
4654                         | select_with_parens alias_clause
4655                                 {
4656                                         RangeSubselect *n = makeNode(RangeSubselect);
4657                                         n->subquery = $1;
4658                                         n->alias = $2;
4659                                         $$ = (Node *) n;
4660                                 }
4661                         | joined_table
4662                                 {
4663                                         $$ = (Node *) $1;
4664                                 }
4665                         | '(' joined_table ')' alias_clause
4666                                 {
4667                                         $2->alias = $4;
4668                                         $$ = (Node *) $2;
4669                                 }
4670                 ;
4671
4672
4673 /*
4674  * It may seem silly to separate joined_table from table_ref, but there is
4675  * method in SQL92's madness: if you don't do it this way you get reduce-
4676  * reduce conflicts, because it's not clear to the parser generator whether
4677  * to expect alias_clause after ')' or not.  For the same reason we must
4678  * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
4679  * join_type to expand to empty; if we try it, the parser generator can't
4680  * figure out when to reduce an empty join_type right after table_ref.
4681  *
4682  * Note that a CROSS JOIN is the same as an unqualified
4683  * INNER JOIN, and an INNER JOIN/ON has the same shape
4684  * but a qualification expression to limit membership.
4685  * A NATURAL JOIN implicitly matches column names between
4686  * tables and the shape is determined by which columns are
4687  * in common. We'll collect columns during the later transformations.
4688  */
4689
4690 joined_table:
4691                         '(' joined_table ')'
4692                                 {
4693                                         $$ = $2;
4694                                 }
4695                         | table_ref CROSS JOIN table_ref
4696                                 {
4697                                         /* CROSS JOIN is same as unqualified inner join */
4698                                         JoinExpr *n = makeNode(JoinExpr);
4699                                         n->jointype = JOIN_INNER;
4700                                         n->isNatural = FALSE;
4701                                         n->larg = $1;
4702                                         n->rarg = $4;
4703                                         n->using = NIL;
4704                                         n->quals = NULL;
4705                                         $$ = n;
4706                                 }
4707                         | table_ref UNIONJOIN table_ref
4708                                 {
4709                                         /* UNION JOIN is made into 1 token to avoid shift/reduce
4710                                          * conflict against regular UNION keyword.
4711                                          */
4712                                         JoinExpr *n = makeNode(JoinExpr);
4713                                         n->jointype = JOIN_UNION;
4714                                         n->isNatural = FALSE;
4715                                         n->larg = $1;
4716                                         n->rarg = $3;
4717                                         n->using = NIL;
4718                                         n->quals = NULL;
4719                                         $$ = n;
4720                                 }
4721                         | table_ref join_type JOIN table_ref join_qual
4722                                 {
4723                                         JoinExpr *n = makeNode(JoinExpr);
4724                                         n->jointype = $2;
4725                                         n->isNatural = FALSE;
4726                                         n->larg = $1;
4727                                         n->rarg = $4;
4728                                         if ($5 != NULL && IsA($5, List))
4729                                                 n->using = (List *) $5; /* USING clause */
4730                                         else
4731                                                 n->quals = $5; /* ON clause */
4732                                         $$ = n;
4733                                 }
4734                         | table_ref JOIN table_ref join_qual
4735                                 {
4736                                         /* letting join_type reduce to empty doesn't work */
4737                                         JoinExpr *n = makeNode(JoinExpr);
4738                                         n->jointype = JOIN_INNER;
4739                                         n->isNatural = FALSE;
4740                                         n->larg = $1;
4741                                         n->rarg = $3;
4742                                         if ($4 != NULL && IsA($4, List))
4743                                                 n->using = (List *) $4; /* USING clause */
4744                                         else
4745                                                 n->quals = $4; /* ON clause */
4746                                         $$ = n;
4747                                 }
4748                         | table_ref NATURAL join_type JOIN table_ref
4749                                 {
4750                                         JoinExpr *n = makeNode(JoinExpr);
4751                                         n->jointype = $3;
4752                                         n->isNatural = TRUE;
4753                                         n->larg = $1;
4754                                         n->rarg = $5;
4755                                         n->using = NIL; /* figure out which columns later... */
4756                                         n->quals = NULL; /* fill later */
4757                                         $$ = n;
4758                                 }
4759                         | table_ref NATURAL JOIN table_ref
4760                                 {
4761                                         /* letting join_type reduce to empty doesn't work */
4762                                         JoinExpr *n = makeNode(JoinExpr);
4763                                         n->jointype = JOIN_INNER;
4764                                         n->isNatural = TRUE;
4765                                         n->larg = $1;
4766                                         n->rarg = $4;
4767                                         n->using = NIL; /* figure out which columns later... */
4768                                         n->quals = NULL; /* fill later */
4769                                         $$ = n;
4770                                 }
4771                 ;
4772
4773 alias_clause:
4774                         AS ColId '(' name_list ')'
4775                                 {
4776                                         $$ = makeNode(Alias);
4777                                         $$->aliasname = $2;
4778                                         $$->colnames = $4;
4779                                 }
4780                         | AS ColId
4781                                 {
4782                                         $$ = makeNode(Alias);
4783                                         $$->aliasname = $2;
4784                                 }
4785                         | ColId '(' name_list ')'
4786                                 {
4787                                         $$ = makeNode(Alias);
4788                                         $$->aliasname = $1;
4789                                         $$->colnames = $3;
4790                                 }
4791                         | ColId
4792                                 {
4793                                         $$ = makeNode(Alias);
4794                                         $$->aliasname = $1;
4795                                 }
4796                 ;
4797
4798 join_type:      FULL join_outer                                                 { $$ = JOIN_FULL; }
4799                         | LEFT join_outer                                               { $$ = JOIN_LEFT; }
4800                         | RIGHT join_outer                                              { $$ = JOIN_RIGHT; }
4801                         | INNER_P                                                               { $$ = JOIN_INNER; }
4802                 ;
4803
4804 /* OUTER is just noise... */
4805 join_outer: OUTER_P                                                                     { $$ = NULL; }
4806                         | /*EMPTY*/                                                             { $$ = NULL; }
4807                 ;
4808
4809 /* JOIN qualification clauses
4810  * Possibilities are:
4811  *      USING ( column list ) allows only unqualified column names,
4812  *                                                which must match between tables.
4813  *      ON expr allows more general qualifications.
4814  *
4815  * We return USING as a List node, while an ON-expr will not be a List.
4816  */
4817
4818 join_qual:      USING '(' name_list ')'                                 { $$ = (Node *) $3; }
4819                         | ON a_expr                                                             { $$ = $2; }
4820                 ;
4821
4822
4823 relation_expr:
4824                         qualified_name
4825                                 {
4826                                         /* default inheritance */
4827                                         $$ = $1;
4828                                         $$->inhOpt = INH_DEFAULT;
4829                                         $$->alias = NULL;
4830                                 }
4831                         | qualified_name '*'
4832                                 {
4833                                         /* inheritance query */
4834                                         $$ = $1;
4835                                         $$->inhOpt = INH_YES;
4836                                         $$->alias = NULL;
4837                                 }
4838                         | ONLY qualified_name
4839                                 {
4840                                         /* no inheritance */
4841                                         $$ = $2;
4842                                         $$->inhOpt = INH_NO;
4843                                         $$->alias = NULL;
4844                                 }
4845                         | ONLY '(' qualified_name ')'
4846                                 {
4847                                         /* no inheritance, SQL99-style syntax */
4848                                         $$ = $3;
4849                                         $$->inhOpt = INH_NO;
4850                                         $$->alias = NULL;
4851                                 }
4852                 ;
4853
4854
4855 func_table: func_name '(' ')'
4856                                 {
4857                                         FuncCall *n = makeNode(FuncCall);
4858                                         n->funcname = $1;
4859                                         n->args = NIL;
4860                                         n->agg_star = FALSE;
4861                                         n->agg_distinct = FALSE;
4862                                         $$ = (Node *)n;
4863                                 }
4864                         | func_name '(' expr_list ')'
4865                                 {
4866                                         FuncCall *n = makeNode(FuncCall);
4867                                         n->funcname = $1;
4868                                         n->args = $3;
4869                                         n->agg_star = FALSE;
4870                                         n->agg_distinct = FALSE;
4871                                         $$ = (Node *)n;
4872                                 }
4873                 ;
4874
4875
4876 where_clause:
4877                         WHERE a_expr                                                    { $$ = $2; }
4878                         | /*EMPTY*/                                                             { $$ = NULL; }
4879                 ;
4880
4881
4882 TableFuncElementList:
4883                         TableFuncElement
4884                                 {
4885                                         $$ = makeList1($1);
4886                                 }
4887                         | TableFuncElementList ',' TableFuncElement
4888                                 {
4889                                         $$ = lappend($1, $3);
4890                                 }
4891                 ;
4892
4893 TableFuncElement:       ColId Typename
4894                                 {
4895                                         ColumnDef *n = makeNode(ColumnDef);
4896                                         n->colname = $1;
4897                                         n->typename = $2;
4898                                         n->constraints = NIL;
4899                                         n->is_local = true;
4900                                         $$ = (Node *)n;
4901                                 }
4902                 ;
4903
4904 /*****************************************************************************
4905  *
4906  *      Type syntax
4907  *              SQL92 introduces a large amount of type-specific syntax.
4908  *              Define individual clauses to handle these cases, and use
4909  *               the generic case to handle regular type-extensible Postgres syntax.
4910  *              - thomas 1997-10-10
4911  *
4912  *****************************************************************************/
4913
4914 Typename:       SimpleTypename opt_array_bounds
4915                                 {
4916                                         $$ = $1;
4917                                         $$->arrayBounds = $2;
4918                                 }
4919                         | SETOF SimpleTypename
4920                                 {
4921                                         $$ = $2;
4922                                         $$->setof = TRUE;
4923                                 }
4924                 ;
4925
4926 opt_array_bounds:
4927                         opt_array_bounds '[' ']'
4928                                         {  $$ = lappend($1, makeInteger(-1)); }
4929                         | opt_array_bounds '[' Iconst ']'
4930                                         {  $$ = lappend($1, makeInteger($3)); }
4931                         | /*EMPTY*/
4932                                         {  $$ = NIL; }
4933                 ;
4934
4935 /*
4936  * XXX ideally, the production for a qualified typename should be ColId attrs
4937  * (there's no obvious reason why the first name should need to be restricted)
4938  * and should be an alternative of GenericType (so that it can be used to
4939  * specify a type for a literal in AExprConst).  However doing either causes
4940  * reduce/reduce conflicts that I haven't been able to find a workaround
4941  * for.  FIXME later.
4942  */
4943 SimpleTypename:
4944                         GenericType                                                             { $$ = $1; }
4945                         | Numeric                                                               { $$ = $1; }
4946                         | Bit                                                                   { $$ = $1; }
4947                         | Character                                                             { $$ = $1; }
4948                         | ConstDatetime                                                 { $$ = $1; }
4949                         | ConstInterval opt_interval
4950                                 {
4951                                         $$ = $1;
4952                                         if ($2 != INTERVAL_FULL_RANGE)
4953                                                 $$->typmod = INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION, $2);
4954                                 }
4955                         | ConstInterval '(' Iconst ')' opt_interval
4956                                 {
4957                                         $$ = $1;
4958                                         if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
4959                                                 elog(ERROR,
4960                                                 "INTERVAL(%d) precision must be between %d and %d",
4961                                                          $3, 0, MAX_INTERVAL_PRECISION);
4962                                         $$->typmod = INTERVAL_TYPMOD($3, $5);
4963                                 }
4964                         | type_name attrs
4965                                 {
4966                                         $$ = makeNode(TypeName);
4967                                         $$->names = lcons(makeString($1), $2);
4968                                         $$->typmod = -1;
4969                                 }
4970                 ;
4971
4972 /* We have a separate ConstTypename to allow defaulting fixed-length
4973  * types such as CHAR() and BIT() to an unspecified length.
4974  * SQL9x requires that these default to a length of one, but this
4975  * makes no sense for constructs like CHAR 'hi' and BIT '0101',
4976  * where there is an obvious better choice to make.
4977  * Note that ConstInterval is not included here since it must
4978  * be pushed up higher in the rules to accomodate the postfix
4979  * options (e.g. INTERVAL '1' YEAR).
4980  */
4981 ConstTypename:
4982                         GenericType                                                             { $$ = $1; }
4983                         | Numeric                                                               { $$ = $1; }
4984                         | ConstBit                                                              { $$ = $1; }
4985                         | ConstCharacter                                                { $$ = $1; }
4986                         | ConstDatetime                                                 { $$ = $1; }
4987                 ;
4988
4989 GenericType:
4990                         type_name
4991                                 {
4992                                         $$ = makeTypeName($1);
4993                                 }
4994                 ;
4995
4996 /* SQL92 numeric data types
4997  * Check FLOAT() precision limits assuming IEEE floating types.
4998  * Provide real DECIMAL() and NUMERIC() implementations now - Jan 1998-12-30
4999  * - thomas 1997-09-18
5000  */
5001 Numeric:        INT
5002                                 {
5003                                         $$ = SystemTypeName("int4");
5004                                 }
5005                         | INTEGER
5006                                 {
5007                                         $$ = SystemTypeName("int4");
5008                                 }
5009                         | SMALLINT
5010                                 {
5011                                         $$ = SystemTypeName("int2");
5012                                 }
5013                         | BIGINT
5014                                 {
5015                                         $$ = SystemTypeName("int8");
5016                                 }
5017                         | REAL
5018                                 {
5019                                         $$ = SystemTypeName("float4");
5020                                 }
5021                         | FLOAT_P opt_float
5022                                 {
5023                                         $$ = $2;
5024                                 }
5025                         | DOUBLE PRECISION
5026                                 {
5027                                         $$ = SystemTypeName("float8");
5028                                 }
5029                         | DECIMAL opt_decimal
5030                                 {
5031                                         $$ = SystemTypeName("numeric");
5032                                         $$->typmod = $2;
5033                                 }
5034                         | DEC opt_decimal
5035                                 {
5036                                         $$ = SystemTypeName("numeric");
5037                                         $$->typmod = $2;
5038                                 }
5039                         | NUMERIC opt_numeric
5040                                 {
5041                                         $$ = SystemTypeName("numeric");
5042                                         $$->typmod = $2;
5043                                 }
5044                         | BOOLEAN
5045                                 {
5046                                         $$ = SystemTypeName("bool");
5047                                 }
5048                 ;
5049
5050 opt_float:      '(' Iconst ')'
5051                                 {
5052                                         if ($2 < 1)
5053                                                 elog(ERROR,
5054                                                         "precision for FLOAT must be at least 1");
5055                                         else if ($2 < 7)
5056                                                 $$ = SystemTypeName("float4");
5057                                         else if ($2 < 16)
5058                                                 $$ = SystemTypeName("float8");
5059                                         else
5060                                                 elog(ERROR,
5061                                                         "precision for FLOAT must be less than 16");
5062                                 }
5063                         | /*EMPTY*/
5064                                 {
5065                                         $$ = SystemTypeName("float8");
5066                                 }
5067                 ;
5068
5069 opt_numeric:
5070                         '(' Iconst ',' Iconst ')'
5071                                 {
5072                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
5073                                                 elog(ERROR,
5074                                                         "NUMERIC precision %d must be between 1 and %d",
5075                                                          $2, NUMERIC_MAX_PRECISION);
5076                                         if ($4 < 0 || $4 > $2)
5077                                                 elog(ERROR,
5078                                                 "NUMERIC scale %d must be between 0 and precision %d",
5079                                                          $4,$2);
5080
5081                                         $$ = (($2 << 16) | $4) + VARHDRSZ;
5082                                 }
5083                         | '(' Iconst ')'
5084                                 {
5085                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
5086                                                 elog(ERROR,
5087                                                         "NUMERIC precision %d must be between 1 and %d",
5088                                                          $2, NUMERIC_MAX_PRECISION);
5089
5090                                         $$ = ($2 << 16) + VARHDRSZ;
5091                                 }
5092                         | /*EMPTY*/
5093                                 {
5094                                         /* Insert "-1" meaning "no limit" */
5095                                         $$ = -1;
5096                                 }
5097                 ;
5098
5099 opt_decimal:
5100                         '(' Iconst ',' Iconst ')'
5101                                 {
5102                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
5103                                                 elog(ERROR,
5104                                                         "DECIMAL precision %d must be between 1 and %d",
5105                                                                         $2, NUMERIC_MAX_PRECISION);
5106                                         if ($4 < 0 || $4 > $2)
5107                                                 elog(ERROR,
5108                                                         "DECIMAL scale %d must be between 0 and precision %d",
5109                                                                         $4,$2);
5110
5111                                         $$ = (($2 << 16) | $4) + VARHDRSZ;
5112                                 }
5113                         | '(' Iconst ')'
5114                                 {
5115                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
5116                                                 elog(ERROR,
5117                                                         "DECIMAL precision %d must be between 1 and %d",
5118                                                                         $2, NUMERIC_MAX_PRECISION);
5119
5120                                         $$ = ($2 << 16) + VARHDRSZ;
5121                                 }
5122                         | /*EMPTY*/
5123                                 {
5124                                         /* Insert "-1" meaning "no limit" */
5125                                         $$ = -1;
5126                                 }
5127                 ;
5128
5129
5130 /*
5131  * SQL92 bit-field data types
5132  * The following implements BIT() and BIT VARYING().
5133  */
5134 Bit:            BitWithLength
5135                                 {
5136                                         $$ = $1;
5137                                 }
5138                         | BitWithoutLength
5139                                 {
5140                                         $$ = $1;
5141                                 }
5142                 ;
5143
5144 ConstBit:       BitWithLength
5145                                 {
5146                                         $$ = $1;
5147                                 }
5148                         | BitWithoutLength
5149                                 {
5150                                         $$->typmod = -1;
5151                                         $$ = $1;
5152                                 }
5153                 ;
5154
5155 BitWithLength:
5156                         BIT opt_varying '(' Iconst ')'
5157                                 {
5158                                         char *typname;
5159
5160                                         typname = $2 ? "varbit" : "bit";
5161                                         $$ = SystemTypeName(typname);
5162                                         if ($4 < 1)
5163                                                 elog(ERROR, "length for type '%s' must be at least 1",
5164                                                          typname);
5165                                         else if ($4 > (MaxAttrSize * BITS_PER_BYTE))
5166                                                 elog(ERROR, "length for type '%s' cannot exceed %d",
5167                                                          typname, (MaxAttrSize * BITS_PER_BYTE));
5168                                         $$->typmod = $4;
5169                                 }
5170                 ;
5171
5172 BitWithoutLength:
5173                         BIT opt_varying
5174                                 {
5175                                         /* bit defaults to bit(1), varbit to no limit */
5176                                         if ($2)
5177                                         {
5178                                                 $$ = SystemTypeName("varbit");
5179                                                 $$->typmod = -1;
5180                                         }
5181                                         else
5182                                         {
5183                                                 $$ = SystemTypeName("bit");
5184                                                 $$->typmod = 1;
5185                                         }
5186                                 }
5187                 ;
5188
5189
5190 /*
5191  * SQL92 character data types
5192  * The following implements CHAR() and VARCHAR().
5193  */
5194 Character:  CharacterWithLength
5195                                 {
5196                                         $$ = $1;
5197                                 }
5198                         | CharacterWithoutLength
5199                                 {
5200                                         $$ = $1;
5201                                 }
5202                 ;
5203
5204 ConstCharacter:  CharacterWithLength
5205                                 {
5206                                         $$ = $1;
5207                                 }
5208                         | CharacterWithoutLength
5209                                 {
5210                                         /* Length was not specified so allow to be unrestricted.
5211                                          * This handles problems with fixed-length (bpchar) strings
5212                                          * which in column definitions must default to a length
5213                                          * of one, but should not be constrained if the length
5214                                          * was not specified.
5215                                          */
5216                                         $1->typmod = -1;
5217                                         $$ = $1;
5218                                 }
5219                 ;
5220
5221 CharacterWithLength:  character '(' Iconst ')' opt_charset
5222                                 {
5223                                         if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
5224                                         {
5225                                                 char *type;
5226
5227                                                 type = palloc(strlen($1) + 1 + strlen($5) + 1);
5228                                                 strcpy(type, $1);
5229                                                 strcat(type, "_");
5230                                                 strcat(type, $5);
5231                                                 $1 = type;
5232                                         }
5233
5234                                         $$ = SystemTypeName($1);
5235
5236                                         if ($3 < 1)
5237                                                 elog(ERROR, "length for type '%s' must be at least 1",
5238                                                          $1);
5239                                         else if ($3 > MaxAttrSize)
5240                                                 elog(ERROR, "length for type '%s' cannot exceed %d",
5241                                                          $1, MaxAttrSize);
5242
5243                                         /* we actually implement these like a varlen, so
5244                                          * the first 4 bytes is the length. (the difference
5245                                          * between these and "text" is that we blank-pad and
5246                                          * truncate where necessary)
5247                                          */
5248                                         $$->typmod = VARHDRSZ + $3;
5249                                 }
5250                 ;
5251
5252 CharacterWithoutLength:  character opt_charset
5253                                 {
5254                                         if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
5255                                         {
5256                                                 char *type;
5257
5258                                                 type = palloc(strlen($1) + 1 + strlen($2) + 1);
5259                                                 strcpy(type, $1);
5260                                                 strcat(type, "_");
5261                                                 strcat(type, $2);
5262                                                 $1 = type;
5263                                         }
5264
5265                                         $$ = SystemTypeName($1);
5266
5267                                         /* char defaults to char(1), varchar to no limit */
5268                                         if (strcmp($1, "bpchar") == 0)
5269                                                 $$->typmod = VARHDRSZ + 1;
5270                                         else
5271                                                 $$->typmod = -1;
5272                                 }
5273                 ;
5274
5275 character:      CHARACTER opt_varying
5276                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
5277                         | CHAR_P opt_varying
5278                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
5279                         | VARCHAR
5280                                                                                 { $$ = "varchar"; }
5281                         | NATIONAL CHARACTER opt_varying
5282                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
5283                         | NATIONAL CHAR_P opt_varying
5284                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
5285                         | NCHAR opt_varying
5286                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
5287                 ;
5288
5289 opt_varying:
5290                         VARYING                                                                 { $$ = TRUE; }
5291                         | /*EMPTY*/                                                             { $$ = FALSE; }
5292                 ;
5293
5294 opt_charset:
5295                         CHARACTER SET ColId                                             { $$ = $3; }
5296                         | /*EMPTY*/                                                             { $$ = NULL; }
5297                 ;
5298
5299 opt_collate:
5300                         COLLATE ColId                                                   { $$ = $2; }
5301                         | /*EMPTY*/                                                             { $$ = NULL; }
5302                 ;
5303
5304 ConstDatetime:
5305                         TIMESTAMP '(' Iconst ')' opt_timezone
5306                                 {
5307                                         if ($5)
5308                                                 $$ = SystemTypeName("timestamptz");
5309                                         else
5310                                                 $$ = SystemTypeName("timestamp");
5311                                         /* XXX the timezone field seems to be unused
5312                                          * - thomas 2001-09-06
5313                                          */
5314                                         $$->timezone = $5;
5315                                         if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
5316                                                 elog(ERROR,
5317                                                 "TIMESTAMP(%d)%s precision must be between %d and %d",
5318                                                          $3, ($5 ? " WITH TIME ZONE": ""), 0,
5319                                                          MAX_TIMESTAMP_PRECISION);
5320                                         $$->typmod = $3;
5321                                 }
5322                         | TIMESTAMP opt_timezone
5323                                 {
5324                                         if ($2)
5325                                                 $$ = SystemTypeName("timestamptz");
5326                                         else
5327                                                 $$ = SystemTypeName("timestamp");
5328                                         /* XXX the timezone field seems to be unused
5329                                          * - thomas 2001-09-06
5330                                          */
5331                                         $$->timezone = $2;
5332                                         /* SQL99 specified a default precision of six
5333                                          * for schema definitions. But for timestamp
5334                                          * literals we don't want to throw away precision
5335                                          * so leave this as unspecified for now.
5336                                          * Later, we may want a different production
5337                                          * for schemas. - thomas 2001-12-07
5338                                          */
5339                                         $$->typmod = -1;
5340                                 }
5341                         | TIME '(' Iconst ')' opt_timezone
5342                                 {
5343                                         if ($5)
5344                                                 $$ = SystemTypeName("timetz");
5345                                         else
5346                                                 $$ = SystemTypeName("time");
5347                                         if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
5348                                                 elog(ERROR,
5349                                                 "TIME(%d)%s precision must be between %d and %d",
5350                                                          $3, ($5 ? " WITH TIME ZONE": ""), 0,
5351                                                          MAX_TIME_PRECISION);
5352                                         $$->typmod = $3;
5353                                 }
5354                         | TIME opt_timezone
5355                                 {
5356                                         if ($2)
5357                                                 $$ = SystemTypeName("timetz");
5358                                         else
5359                                                 $$ = SystemTypeName("time");
5360                                         /* SQL99 specified a default precision of zero.
5361                                          * See comments for timestamp above on why we will
5362                                          * leave this unspecified for now. - thomas 2001-12-07
5363                                          */
5364                                         $$->typmod = -1;
5365                                 }
5366                 ;
5367
5368 ConstInterval:
5369                         INTERVAL                                                                { $$ = SystemTypeName("interval"); }
5370                 ;
5371
5372 opt_timezone:
5373                         WITH TIME ZONE                                                  { $$ = TRUE; }
5374                         | WITHOUT TIME ZONE                                             { $$ = FALSE; }
5375                         | /*EMPTY*/                                                             { $$ = FALSE; }
5376                 ;
5377
5378 opt_interval:
5379                         YEAR_P                                                                  { $$ = INTERVAL_MASK(YEAR); }
5380                         | MONTH_P                                                               { $$ = INTERVAL_MASK(MONTH); }
5381                         | DAY_P                                                                 { $$ = INTERVAL_MASK(DAY); }
5382                         | HOUR_P                                                                { $$ = INTERVAL_MASK(HOUR); }
5383                         | MINUTE_P                                                              { $$ = INTERVAL_MASK(MINUTE); }
5384                         | SECOND_P                                                              { $$ = INTERVAL_MASK(SECOND); }
5385                         | YEAR_P TO MONTH_P
5386                                         { $$ = INTERVAL_MASK(YEAR) | INTERVAL_MASK(MONTH); }
5387                         | DAY_P TO HOUR_P
5388                                         { $$ = INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR); }
5389                         | DAY_P TO MINUTE_P
5390                                         { $$ = INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR)
5391                                                 | INTERVAL_MASK(MINUTE); }
5392                         | DAY_P TO SECOND_P
5393                                         { $$ = INTERVAL_MASK(DAY) | INTERVAL_MASK(HOUR)
5394                                                 | INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND); }
5395                         | HOUR_P TO MINUTE_P
5396                                         { $$ = INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE); }
5397                         | HOUR_P TO SECOND_P
5398                                         { $$ = INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE)
5399                                                 | INTERVAL_MASK(SECOND); }
5400                         | MINUTE_P TO SECOND_P
5401                                         { $$ = INTERVAL_MASK(MINUTE) | INTERVAL_MASK(SECOND); }
5402                         | /*EMPTY*/                                                             { $$ = INTERVAL_FULL_RANGE; }
5403                 ;
5404
5405
5406 /*****************************************************************************
5407  *
5408  *      expression grammar
5409  *
5410  *****************************************************************************/
5411
5412 /* Expressions using row descriptors
5413  * Define row_descriptor to allow yacc to break the reduce/reduce conflict
5414  *      with singleton expressions. Use SQL99's ROW keyword to allow rows of
5415  *  one element.
5416  */
5417 r_expr:  row IN_P select_with_parens
5418                                 {
5419                                         SubLink *n = makeNode(SubLink);
5420                                         n->lefthand = $1;
5421                                         n->oper = (List *) makeSimpleA_Expr(OP, "=", NULL, NULL);
5422                                         n->useor = FALSE;
5423                                         n->subLinkType = ANY_SUBLINK;
5424                                         n->subselect = $3;
5425                                         $$ = (Node *)n;
5426                                 }
5427                         | row NOT IN_P select_with_parens
5428                                 {
5429                                         SubLink *n = makeNode(SubLink);
5430                                         n->lefthand = $1;
5431                                         n->oper = (List *) makeSimpleA_Expr(OP, "<>", NULL, NULL);
5432                                         n->useor = TRUE;
5433                                         n->subLinkType = ALL_SUBLINK;
5434                                         n->subselect = $4;
5435                                         $$ = (Node *)n;
5436                                 }
5437                         | row qual_all_Op sub_type select_with_parens
5438                         %prec Op
5439                                 {
5440                                         SubLink *n = makeNode(SubLink);
5441                                         n->lefthand = $1;
5442                                         n->oper = (List *) makeA_Expr(OP, $2, NULL, NULL);
5443                                         if (strcmp(strVal(llast($2)), "<>") == 0)
5444                                                 n->useor = TRUE;
5445                                         else
5446                                                 n->useor = FALSE;
5447                                         n->subLinkType = $3;
5448                                         n->subselect = $4;
5449                                         $$ = (Node *)n;
5450                                 }
5451                         | row qual_all_Op select_with_parens
5452                         %prec Op
5453                                 {
5454                                         SubLink *n = makeNode(SubLink);
5455                                         n->lefthand = $1;
5456                                         n->oper = (List *) makeA_Expr(OP, $2, NULL, NULL);
5457                                         if (strcmp(strVal(llast($2)), "<>") == 0)
5458                                                 n->useor = TRUE;
5459                                         else
5460                                                 n->useor = FALSE;
5461                                         n->subLinkType = MULTIEXPR_SUBLINK;
5462                                         n->subselect = $3;
5463                                         $$ = (Node *)n;
5464                                 }
5465                         | row qual_all_Op row
5466                         %prec Op
5467                                 {
5468                                         $$ = makeRowExpr($2, $1, $3);
5469                                 }
5470                         | row IS NULL_P
5471                                 {
5472                                         $$ = makeRowNullTest(IS_NULL, $1);
5473                                 }
5474                         | row IS NOT NULL_P
5475                                 {
5476                                         $$ = makeRowNullTest(IS_NOT_NULL, $1);
5477                                 }
5478                         | row OVERLAPS row
5479                                 {
5480                                         $$ = (Node *)makeOverlaps($1, $3);
5481                                 }
5482                         | row IS DISTINCT FROM row
5483                         %prec IS
5484                                 {
5485                                         /* IS DISTINCT FROM has the following rules for non-array types:
5486                                          * a) the row lengths must be equal
5487                                          * b) if both rows are zero-length, then they are not distinct
5488                                          * c) if any element is distinct, the rows are distinct
5489                                          * The rules for an element being distinct:
5490                                          * a) if the elements are both NULL, then they are not distinct
5491                                          * b) if the elements compare to be equal, then they are not distinct
5492                                          * c) otherwise, they are distinct
5493                                          */
5494                                         List *largs = $1;
5495                                         List *rargs = $5;
5496                                         /* lengths don't match? then complain */
5497                                         if (length(largs) != length(rargs))
5498                                         {
5499                                                 elog(ERROR, "Unequal number of entries in row expression");
5500                                         }
5501                                         /* both are zero-length rows? then they are not distinct */
5502                                         else if (length(largs) <= 0)
5503                                         {
5504                                                 $$ = (Node *)makeBoolConst(FALSE);
5505                                         }
5506                                         /* otherwise, we need to compare each element */
5507                                         else
5508                                         {
5509                                                 $$ = (Node *)makeDistinctExpr(largs, rargs);
5510                                         }
5511                                 }
5512                 ;
5513
5514 /* Explicit row production.
5515  * SQL99 allows an optional ROW keyword, so we can now do single-element productions
5516  * without conflicting with the parenthesized a_expr production.
5517  */
5518 row:  ROW '(' row_descriptor ')'                                        { $$ = $3; }
5519                         | ROW '(' a_expr ')'                                    { $$ = makeList1($3); }
5520                         | ROW '(' ')'                                                   { $$ = NULL; }
5521                         | '(' row_descriptor ')'                                { $$ = $2; }
5522                 ;
5523
5524 row_descriptor:  expr_list ',' a_expr                           { $$ = lappend($1, $3); }
5525                 ;
5526
5527 sub_type:       ANY                                                                             { $$ = ANY_SUBLINK; }
5528                         | SOME                                                                  { $$ = ANY_SUBLINK; }
5529                         | ALL                                                                   { $$ = ALL_SUBLINK; }
5530                 ;
5531
5532 all_Op:         Op                                                                              { $$ = $1; }
5533                         | MathOp                                                                { $$ = $1; }
5534                 ;
5535
5536 MathOp:          '+'                                                                    { $$ = "+"; }
5537                         | '-'                                                                   { $$ = "-"; }
5538                         | '*'                                                                   { $$ = "*"; }
5539                         | '/'                                                                   { $$ = "/"; }
5540                         | '%'                                                                   { $$ = "%"; }
5541                         | '^'                                                                   { $$ = "^"; }
5542                         | '<'                                                                   { $$ = "<"; }
5543                         | '>'                                                                   { $$ = ">"; }
5544                         | '='                                                                   { $$ = "="; }
5545                 ;
5546
5547 qual_Op:        Op
5548                                         { $$ = makeList1(makeString($1)); }
5549                         | OPERATOR '(' any_operator ')'                 { $$ = $3; }
5550                 ;
5551
5552 qual_all_Op:
5553                         all_Op
5554                                         { $$ = makeList1(makeString($1)); }
5555                         | OPERATOR '(' any_operator ')'                 { $$ = $3; }
5556                 ;
5557
5558 /*
5559  * General expressions
5560  * This is the heart of the expression syntax.
5561  *
5562  * We have two expression types: a_expr is the unrestricted kind, and
5563  * b_expr is a subset that must be used in some places to avoid shift/reduce
5564  * conflicts.  For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
5565  * because that use of AND conflicts with AND as a boolean operator.  So,
5566  * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
5567  *
5568  * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
5569  * always be used by surrounding it with parens.
5570  *
5571  * c_expr is all the productions that are common to a_expr and b_expr;
5572  * it's factored out just to eliminate redundant coding.
5573  */
5574 a_expr:         c_expr                                                                  { $$ = $1; }
5575                         | a_expr TYPECAST Typename
5576                                         { $$ = makeTypeCast($1, $3); }
5577                         | a_expr COLLATE ColId
5578                                 {
5579                                         FuncCall *n = makeNode(FuncCall);
5580                                         n->funcname = SystemFuncName($3);
5581                                         n->args = makeList1($1);
5582                                         n->agg_star = FALSE;
5583                                         n->agg_distinct = FALSE;
5584                                         $$ = (Node *) n;
5585                                 }
5586                         | a_expr AT TIME ZONE c_expr
5587                                 {
5588                                         FuncCall *n = makeNode(FuncCall);
5589                                         n->funcname = SystemFuncName("timezone");
5590                                         n->args = makeList2($5, $1);
5591                                         n->agg_star = FALSE;
5592                                         n->agg_distinct = FALSE;
5593                                         $$ = (Node *) n;
5594                                 }
5595                 /*
5596                  * These operators must be called out explicitly in order to make use
5597                  * of yacc/bison's automatic operator-precedence handling.  All other
5598                  * operator names are handled by the generic productions using "Op",
5599                  * below; and all those operators will have the same precedence.
5600                  *
5601                  * If you add more explicitly-known operators, be sure to add them
5602                  * also to b_expr and to the MathOp list above.
5603                  */
5604                         | '+' a_expr                                    %prec UMINUS
5605                                 { $$ = (Node *) makeSimpleA_Expr(OP, "+", NULL, $2); }
5606                         | '-' a_expr                                    %prec UMINUS
5607                                 { $$ = doNegate($2); }
5608                         | '%' a_expr
5609                                 { $$ = (Node *) makeSimpleA_Expr(OP, "%", NULL, $2); }
5610                         | '^' a_expr
5611                                 { $$ = (Node *) makeSimpleA_Expr(OP, "^", NULL, $2); }
5612                         | a_expr '%'
5613                                 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, NULL); }
5614                         | a_expr '^'
5615                                 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, NULL); }
5616                         | a_expr '+' a_expr
5617                                 { $$ = (Node *) makeSimpleA_Expr(OP, "+", $1, $3); }
5618                         | a_expr '-' a_expr
5619                                 { $$ = (Node *) makeSimpleA_Expr(OP, "-", $1, $3); }
5620                         | a_expr '*' a_expr
5621                                 { $$ = (Node *) makeSimpleA_Expr(OP, "*", $1, $3); }
5622                         | a_expr '/' a_expr
5623                                 { $$ = (Node *) makeSimpleA_Expr(OP, "/", $1, $3); }
5624                         | a_expr '%' a_expr
5625                                 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, $3); }
5626                         | a_expr '^' a_expr
5627                                 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, $3); }
5628                         | a_expr '<' a_expr
5629                                 { $$ = (Node *) makeSimpleA_Expr(OP, "<", $1, $3); }
5630                         | a_expr '>' a_expr
5631                                 { $$ = (Node *) makeSimpleA_Expr(OP, ">", $1, $3); }
5632                         | a_expr '=' a_expr
5633                                 { $$ = (Node *) makeSimpleA_Expr(OP, "=", $1, $3); }
5634
5635                         | a_expr qual_Op a_expr                         %prec Op
5636                                 { $$ = (Node *) makeA_Expr(OP, $2, $1, $3); }
5637                         | qual_Op a_expr                                        %prec Op
5638                                 { $$ = (Node *) makeA_Expr(OP, $1, NULL, $2); }
5639                         | a_expr qual_Op                                        %prec POSTFIXOP
5640                                 { $$ = (Node *) makeA_Expr(OP, $2, $1, NULL); }
5641
5642                         | a_expr AND a_expr
5643                                 { $$ = (Node *) makeA_Expr(AND, NIL, $1, $3); }
5644                         | a_expr OR a_expr
5645                                 { $$ = (Node *) makeA_Expr(OR, NIL, $1, $3); }
5646                         | NOT a_expr
5647                                 { $$ = (Node *) makeA_Expr(NOT, NIL, NULL, $2); }
5648
5649                         | a_expr LIKE a_expr
5650                                 { $$ = (Node *) makeSimpleA_Expr(OP, "~~", $1, $3); }
5651                         | a_expr LIKE a_expr ESCAPE a_expr
5652                                 {
5653                                         FuncCall *n = makeNode(FuncCall);
5654                                         n->funcname = SystemFuncName("like_escape");
5655                                         n->args = makeList2($3, $5);
5656                                         n->agg_star = FALSE;
5657                                         n->agg_distinct = FALSE;
5658                                         $$ = (Node *) makeSimpleA_Expr(OP, "~~", $1, (Node *) n);
5659                                 }
5660                         | a_expr NOT LIKE a_expr
5661                                 { $$ = (Node *) makeSimpleA_Expr(OP, "!~~", $1, $4); }
5662                         | a_expr NOT LIKE a_expr ESCAPE a_expr
5663                                 {
5664                                         FuncCall *n = makeNode(FuncCall);
5665                                         n->funcname = SystemFuncName("like_escape");
5666                                         n->args = makeList2($4, $6);
5667                                         n->agg_star = FALSE;
5668                                         n->agg_distinct = FALSE;
5669                                         $$ = (Node *) makeSimpleA_Expr(OP, "!~~", $1, (Node *) n);
5670                                 }
5671                         | a_expr ILIKE a_expr
5672                                 { $$ = (Node *) makeSimpleA_Expr(OP, "~~*", $1, $3); }
5673                         | a_expr ILIKE a_expr ESCAPE a_expr
5674                                 {
5675                                         FuncCall *n = makeNode(FuncCall);
5676                                         n->funcname = SystemFuncName("like_escape");
5677                                         n->args = makeList2($3, $5);
5678                                         n->agg_star = FALSE;
5679                                         n->agg_distinct = FALSE;
5680                                         $$ = (Node *) makeSimpleA_Expr(OP, "~~*", $1, (Node *) n);
5681                                 }
5682                         | a_expr NOT ILIKE a_expr
5683                                 { $$ = (Node *) makeSimpleA_Expr(OP, "!~~*", $1, $4); }
5684                         | a_expr NOT ILIKE a_expr ESCAPE a_expr
5685                                 {
5686                                         FuncCall *n = makeNode(FuncCall);
5687                                         n->funcname = SystemFuncName("like_escape");
5688                                         n->args = makeList2($4, $6);
5689                                         n->agg_star = FALSE;
5690                                         n->agg_distinct = FALSE;
5691                                         $$ = (Node *) makeSimpleA_Expr(OP, "!~~*", $1, (Node *) n);
5692                                 }
5693
5694                         | a_expr SIMILAR TO a_expr                              %prec SIMILAR
5695                                 {
5696                                         A_Const *c = makeNode(A_Const);
5697                                         FuncCall *n = makeNode(FuncCall);
5698                                         c->val.type = T_Null;
5699                                         n->funcname = SystemFuncName("similar_escape");
5700                                         n->args = makeList2($4, (Node *) c);
5701                                         n->agg_star = FALSE;
5702                                         n->agg_distinct = FALSE;
5703                                         $$ = (Node *) makeSimpleA_Expr(OP, "~", $1, (Node *) n);
5704                                 }
5705                         | a_expr SIMILAR TO a_expr ESCAPE a_expr
5706                                 {
5707                                         FuncCall *n = makeNode(FuncCall);
5708                                         n->funcname = SystemFuncName("similar_escape");
5709                                         n->args = makeList2($4, $6);
5710                                         n->agg_star = FALSE;
5711                                         n->agg_distinct = FALSE;
5712                                         $$ = (Node *) makeSimpleA_Expr(OP, "~", $1, (Node *) n);
5713                                 }
5714                         | a_expr NOT SIMILAR TO a_expr                  %prec SIMILAR
5715                                 {
5716                                         A_Const *c = makeNode(A_Const);
5717                                         FuncCall *n = makeNode(FuncCall);
5718                                         c->val.type = T_Null;
5719                                         n->funcname = SystemFuncName("similar_escape");
5720                                         n->args = makeList2($5, (Node *) c);
5721                                         n->agg_star = FALSE;
5722                                         n->agg_distinct = FALSE;
5723                                         $$ = (Node *) makeSimpleA_Expr(OP, "!~", $1, (Node *) n);
5724                                 }
5725                         | a_expr NOT SIMILAR TO a_expr ESCAPE a_expr
5726                                 {
5727                                         FuncCall *n = makeNode(FuncCall);
5728                                         n->funcname = SystemFuncName("similar_escape");
5729                                         n->args = makeList2($5, $7);
5730                                         n->agg_star = FALSE;
5731                                         n->agg_distinct = FALSE;
5732                                         $$ = (Node *) makeSimpleA_Expr(OP, "!~", $1, (Node *) n);
5733                                 }
5734
5735                         /* NullTest clause
5736                          * Define SQL92-style Null test clause.
5737                          * Allow two forms described in the standard:
5738                          *      a IS NULL
5739                          *      a IS NOT NULL
5740                          * Allow two SQL extensions
5741                          *      a ISNULL
5742                          *      a NOTNULL
5743                          */
5744                         | a_expr ISNULL
5745                                 {
5746                                         NullTest *n = makeNode(NullTest);
5747                                         n->arg = (Expr *) $1;
5748                                         n->nulltesttype = IS_NULL;
5749                                         $$ = (Node *)n;
5750                                 }
5751                         | a_expr IS NULL_P
5752                                 {
5753                                         NullTest *n = makeNode(NullTest);
5754                                         n->arg = (Expr *) $1;
5755                                         n->nulltesttype = IS_NULL;
5756                                         $$ = (Node *)n;
5757                                 }
5758                         | a_expr NOTNULL
5759                                 {
5760                                         NullTest *n = makeNode(NullTest);
5761                                         n->arg = (Expr *) $1;
5762                                         n->nulltesttype = IS_NOT_NULL;
5763                                         $$ = (Node *)n;
5764                                 }
5765                         | a_expr IS NOT NULL_P
5766                                 {
5767                                         NullTest *n = makeNode(NullTest);
5768                                         n->arg = (Expr *) $1;
5769                                         n->nulltesttype = IS_NOT_NULL;
5770                                         $$ = (Node *)n;
5771                                 }
5772                         | a_expr IS TRUE_P
5773                                 {
5774                                         BooleanTest *b = makeNode(BooleanTest);
5775                                         b->arg = (Expr *) $1;
5776                                         b->booltesttype = IS_TRUE;
5777                                         $$ = (Node *)b;
5778                                 }
5779                         | a_expr IS NOT TRUE_P
5780                                 {
5781                                         BooleanTest *b = makeNode(BooleanTest);
5782                                         b->arg = (Expr *) $1;
5783                                         b->booltesttype = IS_NOT_TRUE;
5784                                         $$ = (Node *)b;
5785                                 }
5786                         | a_expr IS FALSE_P
5787                                 {
5788                                         BooleanTest *b = makeNode(BooleanTest);
5789                                         b->arg = (Expr *) $1;
5790                                         b->booltesttype = IS_FALSE;
5791                                         $$ = (Node *)b;
5792                                 }
5793                         | a_expr IS NOT FALSE_P
5794                                 {
5795                                         BooleanTest *b = makeNode(BooleanTest);
5796                                         b->arg = (Expr *) $1;
5797                                         b->booltesttype = IS_NOT_FALSE;
5798                                         $$ = (Node *)b;
5799                                 }
5800                         | a_expr IS UNKNOWN
5801                                 {
5802                                         BooleanTest *b = makeNode(BooleanTest);
5803                                         b->arg = (Expr *) $1;
5804                                         b->booltesttype = IS_UNKNOWN;
5805                                         $$ = (Node *)b;
5806                                 }
5807                         | a_expr IS NOT UNKNOWN
5808                                 {
5809                                         BooleanTest *b = makeNode(BooleanTest);
5810                                         b->arg = (Expr *) $1;
5811                                         b->booltesttype = IS_NOT_UNKNOWN;
5812                                         $$ = (Node *)b;
5813                                 }
5814                         | a_expr IS DISTINCT FROM a_expr                        %prec IS
5815                                 { $$ = (Node *) makeSimpleA_Expr(DISTINCT, "=", $1, $5); }
5816                         | a_expr IS OF '(' type_list ')'                        %prec IS
5817                                 {
5818                                         $$ = (Node *) makeSimpleA_Expr(OF, "=", $1, (Node *) $5);
5819                                 }
5820                         | a_expr IS NOT OF '(' type_list ')'            %prec IS
5821                                 {
5822                                         $$ = (Node *) makeSimpleA_Expr(OF, "!=", $1, (Node *) $6);
5823                                 }
5824                         | a_expr BETWEEN b_expr AND b_expr                      %prec BETWEEN
5825                                 {
5826                                         $$ = (Node *) makeA_Expr(AND, NIL,
5827                                                 (Node *) makeSimpleA_Expr(OP, ">=", $1, $3),
5828                                                 (Node *) makeSimpleA_Expr(OP, "<=", $1, $5));
5829                                 }
5830                         | a_expr NOT BETWEEN b_expr AND b_expr          %prec BETWEEN
5831                                 {
5832                                         $$ = (Node *) makeA_Expr(OR, NIL,
5833                                                 (Node *) makeSimpleA_Expr(OP, "<", $1, $4),
5834                                                 (Node *) makeSimpleA_Expr(OP, ">", $1, $6));
5835                                 }
5836                         | a_expr IN_P in_expr
5837                                 {
5838                                         /* in_expr returns a SubLink or a list of a_exprs */
5839                                         if (IsA($3, SubLink))
5840                                         {
5841                                                         SubLink *n = (SubLink *)$3;
5842                                                         n->lefthand = makeList1($1);
5843                                                         n->oper = (List *) makeSimpleA_Expr(OP, "=", NULL, NULL);
5844                                                         n->useor = FALSE;
5845                                                         n->subLinkType = ANY_SUBLINK;
5846                                                         $$ = (Node *)n;
5847                                         }
5848                                         else
5849                                         {
5850                                                 Node *n = NULL;
5851                                                 List *l;
5852                                                 foreach(l, (List *) $3)
5853                                                 {
5854                                                         Node *cmp;
5855                                                         cmp = (Node *) makeSimpleA_Expr(OP, "=", $1, lfirst(l));
5856                                                         if (n == NULL)
5857                                                                 n = cmp;
5858                                                         else
5859                                                                 n = (Node *) makeA_Expr(OR, NIL, n, cmp);
5860                                                 }
5861                                                 $$ = n;
5862                                         }
5863                                 }
5864                         | a_expr NOT IN_P in_expr
5865                                 {
5866                                         /* in_expr returns a SubLink or a list of a_exprs */
5867                                         if (IsA($4, SubLink))
5868                                         {
5869                                                 SubLink *n = (SubLink *)$4;
5870                                                 n->lefthand = makeList1($1);
5871                                                 n->oper = (List *) makeSimpleA_Expr(OP, "<>", NULL, NULL);
5872                                                 n->useor = FALSE;
5873                                                 n->subLinkType = ALL_SUBLINK;
5874                                                 $$ = (Node *)n;
5875                                         }
5876                                         else
5877                                         {
5878                                                 Node *n = NULL;
5879                                                 List *l;
5880                                                 foreach(l, (List *) $4)
5881                                                 {
5882                                                         Node *cmp;
5883                                                         cmp = (Node *) makeSimpleA_Expr(OP, "<>", $1, lfirst(l));
5884                                                         if (n == NULL)
5885                                                                 n = cmp;
5886                                                         else
5887                                                                 n = (Node *) makeA_Expr(AND, NIL, n, cmp);
5888                                                 }
5889                                                 $$ = n;
5890                                         }
5891                                 }
5892                         | a_expr qual_all_Op sub_type select_with_parens %prec Op
5893                                 {
5894                                         SubLink *n = makeNode(SubLink);
5895                                         n->lefthand = makeList1($1);
5896                                         n->oper = (List *) makeA_Expr(OP, $2, NULL, NULL);
5897                                         n->useor = FALSE; /* doesn't matter since only one col */
5898                                         n->subLinkType = $3;
5899                                         n->subselect = $4;
5900                                         $$ = (Node *)n;
5901                                 }
5902                         | UNIQUE select_with_parens %prec Op
5903                                 {
5904                                         /* Not sure how to get rid of the parentheses
5905                                          * but there are lots of shift/reduce errors without them.
5906                                          *
5907                                          * Should be able to implement this by plopping the entire
5908                                          * select into a node, then transforming the target expressions
5909                                          * from whatever they are into count(*), and testing the
5910                                          * entire result equal to one.
5911                                          * But, will probably implement a separate node in the executor.
5912                                          */
5913                                         elog(ERROR, "UNIQUE predicate is not yet implemented");
5914                                 }
5915                         | r_expr
5916                                 { $$ = $1; }
5917                 ;
5918
5919 /*
5920  * Restricted expressions
5921  *
5922  * b_expr is a subset of the complete expression syntax defined by a_expr.
5923  *
5924  * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
5925  * cause trouble in the places where b_expr is used.  For simplicity, we
5926  * just eliminate all the boolean-keyword-operator productions from b_expr.
5927  */
5928 b_expr:         c_expr
5929                                 { $$ = $1; }
5930                         | b_expr TYPECAST Typename
5931                                 { $$ = makeTypeCast($1, $3); }
5932                         | '+' b_expr                                    %prec UMINUS
5933                                 { $$ = (Node *) makeSimpleA_Expr(OP, "+", NULL, $2); }
5934                         | '-' b_expr                                    %prec UMINUS
5935                                 { $$ = doNegate($2); }
5936                         | '%' b_expr
5937                                 { $$ = (Node *) makeSimpleA_Expr(OP, "%", NULL, $2); }
5938                         | '^' b_expr
5939                                 { $$ = (Node *) makeSimpleA_Expr(OP, "^", NULL, $2); }
5940                         | b_expr '%'
5941                                 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, NULL); }
5942                         | b_expr '^'
5943                                 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, NULL); }
5944                         | b_expr '+' b_expr
5945                                 { $$ = (Node *) makeSimpleA_Expr(OP, "+", $1, $3); }
5946                         | b_expr '-' b_expr
5947                                 { $$ = (Node *) makeSimpleA_Expr(OP, "-", $1, $3); }
5948                         | b_expr '*' b_expr
5949                                 { $$ = (Node *) makeSimpleA_Expr(OP, "*", $1, $3); }
5950                         | b_expr '/' b_expr
5951                                 { $$ = (Node *) makeSimpleA_Expr(OP, "/", $1, $3); }
5952                         | b_expr '%' b_expr
5953                                 { $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, $3); }
5954                         | b_expr '^' b_expr
5955                                 { $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, $3); }
5956                         | b_expr '<' b_expr
5957                                 { $$ = (Node *) makeSimpleA_Expr(OP, "<", $1, $3); }
5958                         | b_expr '>' b_expr
5959                                 { $$ = (Node *) makeSimpleA_Expr(OP, ">", $1, $3); }
5960                         | b_expr '=' b_expr
5961                                 { $$ = (Node *) makeSimpleA_Expr(OP, "=", $1, $3); }
5962                         | b_expr qual_Op b_expr                         %prec Op
5963                                 { $$ = (Node *) makeA_Expr(OP, $2, $1, $3); }
5964                         | qual_Op b_expr                                        %prec Op
5965                                 { $$ = (Node *) makeA_Expr(OP, $1, NULL, $2); }
5966                         | b_expr qual_Op                                        %prec POSTFIXOP
5967                                 { $$ = (Node *) makeA_Expr(OP, $2, $1, NULL); }
5968                         | b_expr IS DISTINCT FROM b_expr        %prec IS
5969                                 { $$ = (Node *) makeSimpleA_Expr(DISTINCT, "=", $1, $5); }
5970                         | b_expr IS OF '(' type_list ')'        %prec IS
5971                                 {
5972                                         $$ = (Node *) makeSimpleA_Expr(OF, "=", $1, (Node *) $5);
5973                                 }
5974                         | b_expr IS NOT OF '(' type_list ')'    %prec IS
5975                                 {
5976                                         $$ = (Node *) makeSimpleA_Expr(OF, "!=", $1, (Node *) $6);
5977                                 }
5978                 ;
5979
5980 /*
5981  * Productions that can be used in both a_expr and b_expr.
5982  *
5983  * Note: productions that refer recursively to a_expr or b_expr mostly
5984  * cannot appear here.  However, it's OK to refer to a_exprs that occur
5985  * inside parentheses, such as function arguments; that cannot introduce
5986  * ambiguity to the b_expr syntax.
5987  */
5988 c_expr:         columnref                                                               { $$ = (Node *) $1; }
5989                         | AexprConst                                                    { $$ = $1; }
5990                         | PARAM attrs opt_indirection
5991                                 {
5992                                         /*
5993                                          * PARAM without field names is considered a constant,
5994                                          * but with 'em, it is not.  Not very consistent ...
5995                                          */
5996                                         ParamRef *n = makeNode(ParamRef);
5997                                         n->number = $1;
5998                                         n->fields = $2;
5999                                         n->indirection = $3;
6000                                         $$ = (Node *)n;
6001                                 }
6002                         | '(' a_expr ')'                                                { $$ = $2; }
6003                         | '(' a_expr ')' attrs opt_indirection
6004                                 {
6005                                         ExprFieldSelect *n = makeNode(ExprFieldSelect);
6006                                         n->arg = $2;
6007                                         n->fields = $4;
6008                                         n->indirection = $5;
6009                                         $$ = (Node *)n;
6010                                 }
6011                         | case_expr
6012                                 { $$ = $1; }
6013                         | func_name '(' ')'
6014                                 {
6015                                         FuncCall *n = makeNode(FuncCall);
6016                                         n->funcname = $1;
6017                                         n->args = NIL;
6018                                         n->agg_star = FALSE;
6019                                         n->agg_distinct = FALSE;
6020                                         $$ = (Node *)n;
6021                                 }
6022                         | func_name '(' expr_list ')'
6023                                 {
6024                                         FuncCall *n = makeNode(FuncCall);
6025                                         n->funcname = $1;
6026                                         n->args = $3;
6027                                         n->agg_star = FALSE;
6028                                         n->agg_distinct = FALSE;
6029                                         $$ = (Node *)n;
6030                                 }
6031                         | func_name '(' ALL expr_list ')'
6032                                 {
6033                                         FuncCall *n = makeNode(FuncCall);
6034                                         n->funcname = $1;
6035                                         n->args = $4;
6036                                         n->agg_star = FALSE;
6037                                         n->agg_distinct = FALSE;
6038                                         /* Ideally we'd mark the FuncCall node to indicate
6039                                          * "must be an aggregate", but there's no provision
6040                                          * for that in FuncCall at the moment.
6041                                          */
6042                                         $$ = (Node *)n;
6043                                 }
6044                         | func_name '(' DISTINCT expr_list ')'
6045                                 {
6046                                         FuncCall *n = makeNode(FuncCall);
6047                                         n->funcname = $1;
6048                                         n->args = $4;
6049                                         n->agg_star = FALSE;
6050                                         n->agg_distinct = TRUE;
6051                                         $$ = (Node *)n;
6052                                 }
6053                         | func_name '(' '*' ')'
6054                                 {
6055                                         /*
6056                                          * For now, we transform AGGREGATE(*) into AGGREGATE(1).
6057                                          *
6058                                          * This does the right thing for COUNT(*) (in fact,
6059                                          * any certainly-non-null expression would do for COUNT),
6060                                          * and there are no other aggregates in SQL92 that accept
6061                                          * '*' as parameter.
6062                                          *
6063                                          * The FuncCall node is also marked agg_star = true,
6064                                          * so that later processing can detect what the argument
6065                                          * really was.
6066                                          */
6067                                         FuncCall *n = makeNode(FuncCall);
6068                                         A_Const *star = makeNode(A_Const);
6069
6070                                         star->val.type = T_Integer;
6071                                         star->val.val.ival = 1;
6072                                         n->funcname = $1;
6073                                         n->args = makeList1(star);
6074                                         n->agg_star = TRUE;
6075                                         n->agg_distinct = FALSE;
6076                                         $$ = (Node *)n;
6077                                 }
6078                         | CURRENT_DATE
6079                                 {
6080                                         /*
6081                                          * Translate as "'now'::text::date".
6082                                          *
6083                                          * We cannot use "'now'::date" because coerce_type() will
6084                                          * immediately reduce that to a constant representing
6085                                          * today's date.  We need to delay the conversion until
6086                                          * runtime, else the wrong things will happen when
6087                                          * CURRENT_DATE is used in a column default value or rule.
6088                                          *
6089                                          * This could be simplified if we had a way to generate
6090                                          * an expression tree representing runtime application
6091                                          * of type-input conversion functions...
6092                                          */
6093                                         A_Const *s = makeNode(A_Const);
6094                                         TypeName *d;
6095
6096                                         s->val.type = T_String;
6097                                         s->val.val.str = "now";
6098                                         s->typename = SystemTypeName("text");
6099
6100                                         d = SystemTypeName("date");
6101
6102                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6103                                 }
6104                         | CURRENT_TIME
6105                                 {
6106                                         /*
6107                                          * Translate as "'now'::text::timetz".
6108                                          * See comments for CURRENT_DATE.
6109                                          */
6110                                         A_Const *s = makeNode(A_Const);
6111                                         TypeName *d;
6112
6113                                         s->val.type = T_String;
6114                                         s->val.val.str = "now";
6115                                         s->typename = SystemTypeName("text");
6116
6117                                         d = SystemTypeName("timetz");
6118                                         /* SQL99 mandates a default precision of zero for TIME
6119                                          * fields in schemas. However, for CURRENT_TIME
6120                                          * let's preserve the microsecond precision we
6121                                          * might see from the system clock. - thomas 2001-12-07
6122                                          */
6123                                         d->typmod = 6;
6124
6125                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6126                                 }
6127                         | CURRENT_TIME '(' Iconst ')'
6128                                 {
6129                                         /*
6130                                          * Translate as "'now'::text::timetz(n)".
6131                                          * See comments for CURRENT_DATE.
6132                                          */
6133                                         A_Const *s = makeNode(A_Const);
6134                                         TypeName *d;
6135
6136                                         s->val.type = T_String;
6137                                         s->val.val.str = "now";
6138                                         s->typename = SystemTypeName("text");
6139                                         d = SystemTypeName("timetz");
6140                                         if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
6141                                                 elog(ERROR,
6142                                                 "CURRENT_TIME(%d) precision must be between %d and %d",
6143                                                          $3, 0, MAX_TIME_PRECISION);
6144                                         d->typmod = $3;
6145
6146                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6147                                 }
6148                         | CURRENT_TIMESTAMP
6149                                 {
6150                                         /*
6151                                          * Translate as "'now'::text::timestamptz".
6152                                          * See comments for CURRENT_DATE.
6153                                          */
6154                                         A_Const *s = makeNode(A_Const);
6155                                         TypeName *d;
6156
6157                                         s->val.type = T_String;
6158                                         s->val.val.str = "now";
6159                                         s->typename = SystemTypeName("text");
6160
6161                                         d = SystemTypeName("timestamptz");
6162                                         /* SQL99 mandates a default precision of 6 for timestamp.
6163                                          * Also, that is about as precise as we will get since
6164                                          * we are using a microsecond time interface.
6165                                          * - thomas 2001-12-07
6166                                          */
6167                                         d->typmod = 6;
6168
6169                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6170                                 }
6171                         | CURRENT_TIMESTAMP '(' Iconst ')'
6172                                 {
6173                                         /*
6174                                          * Translate as "'now'::text::timestamptz(n)".
6175                                          * See comments for CURRENT_DATE.
6176                                          */
6177                                         A_Const *s = makeNode(A_Const);
6178                                         TypeName *d;
6179
6180                                         s->val.type = T_String;
6181                                         s->val.val.str = "now";
6182                                         s->typename = SystemTypeName("text");
6183
6184                                         d = SystemTypeName("timestamptz");
6185                                         if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
6186                                                 elog(ERROR,
6187                                                 "CURRENT_TIMESTAMP(%d) precision "
6188                                                 "must be between %d and %d",
6189                                                          $3, 0, MAX_TIMESTAMP_PRECISION);
6190                                         d->typmod = $3;
6191
6192                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6193                                 }
6194                         | LOCALTIME
6195                                 {
6196                                         /*
6197                                          * Translate as "'now'::text::time".
6198                                          * See comments for CURRENT_DATE.
6199                                          */
6200                                         A_Const *s = makeNode(A_Const);
6201                                         TypeName *d;
6202
6203                                         s->val.type = T_String;
6204                                         s->val.val.str = "now";
6205                                         s->typename = SystemTypeName("text");
6206
6207                                         d = SystemTypeName("time");
6208                                         /* SQL99 mandates a default precision of zero for TIME
6209                                          * fields in schemas. However, for LOCALTIME
6210                                          * let's preserve the microsecond precision we
6211                                          * might see from the system clock. - thomas 2001-12-07
6212                                          */
6213                                         d->typmod = 6;
6214
6215                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6216                                 }
6217                         | LOCALTIME '(' Iconst ')'
6218                                 {
6219                                         /*
6220                                          * Translate as "'now'::text::time(n)".
6221                                          * See comments for CURRENT_DATE.
6222                                          */
6223                                         A_Const *s = makeNode(A_Const);
6224                                         TypeName *d;
6225
6226                                         s->val.type = T_String;
6227                                         s->val.val.str = "now";
6228                                         s->typename = SystemTypeName("text");
6229                                         d = SystemTypeName("time");
6230                                         if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
6231                                                 elog(ERROR,
6232                                                 "LOCALTIME(%d) precision must be between %d and %d",
6233                                                          $3, 0, MAX_TIME_PRECISION);
6234                                         d->typmod = $3;
6235
6236                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6237                                 }
6238                         | LOCALTIMESTAMP
6239                                 {
6240                                         /*
6241                                          * Translate as "'now'::text::timestamp".
6242                                          * See comments for CURRENT_DATE.
6243                                          */
6244                                         A_Const *s = makeNode(A_Const);
6245                                         TypeName *d;
6246
6247                                         s->val.type = T_String;
6248                                         s->val.val.str = "now";
6249                                         s->typename = SystemTypeName("text");
6250
6251                                         d = SystemTypeName("timestamp");
6252                                         /* SQL99 mandates a default precision of 6 for timestamp.
6253                                          * Also, that is about as precise as we will get since
6254                                          * we are using a microsecond time interface.
6255                                          * - thomas 2001-12-07
6256                                          */
6257                                         d->typmod = 6;
6258
6259                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6260                                 }
6261                         | LOCALTIMESTAMP '(' Iconst ')'
6262                                 {
6263                                         /*
6264                                          * Translate as "'now'::text::timestamp(n)".
6265                                          * See comments for CURRENT_DATE.
6266                                          */
6267                                         A_Const *s = makeNode(A_Const);
6268                                         TypeName *d;
6269
6270                                         s->val.type = T_String;
6271                                         s->val.val.str = "now";
6272                                         s->typename = SystemTypeName("text");
6273
6274                                         d = SystemTypeName("timestamp");
6275                                         if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
6276                                                 elog(ERROR,
6277                                                 "LOCALTIMESTAMP(%d) precision must be "
6278                                                 "between %d and %d",
6279                                                          $3, 0, MAX_TIMESTAMP_PRECISION);
6280                                         d->typmod = $3;
6281
6282                                         $$ = (Node *)makeTypeCast((Node *)s, d);
6283                                 }
6284                         | CURRENT_USER
6285                                 {
6286                                         FuncCall *n = makeNode(FuncCall);
6287                                         n->funcname = SystemFuncName("current_user");
6288                                         n->args = NIL;
6289                                         n->agg_star = FALSE;
6290                                         n->agg_distinct = FALSE;
6291                                         $$ = (Node *)n;
6292                                 }
6293                         | SESSION_USER
6294                                 {
6295                                         FuncCall *n = makeNode(FuncCall);
6296                                         n->funcname = SystemFuncName("session_user");
6297                                         n->args = NIL;
6298                                         n->agg_star = FALSE;
6299                                         n->agg_distinct = FALSE;
6300                                         $$ = (Node *)n;
6301                                 }
6302                         | USER
6303                                 {
6304                                         FuncCall *n = makeNode(FuncCall);
6305                                         n->funcname = SystemFuncName("current_user");
6306                                         n->args = NIL;
6307                                         n->agg_star = FALSE;
6308                                         n->agg_distinct = FALSE;
6309                                         $$ = (Node *)n;
6310                                 }
6311                         | CAST '(' a_expr AS Typename ')'
6312                                 { $$ = makeTypeCast($3, $5); }
6313                         | EXTRACT '(' extract_list ')'
6314                                 {
6315                                         FuncCall *n = makeNode(FuncCall);
6316                                         n->funcname = SystemFuncName("date_part");
6317                                         n->args = $3;
6318                                         n->agg_star = FALSE;
6319                                         n->agg_distinct = FALSE;
6320                                         $$ = (Node *)n;
6321                                 }
6322                         | OVERLAY '(' overlay_list ')'
6323                                 {
6324                                         /* overlay(A PLACING B FROM C FOR D) is converted to
6325                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+D)
6326                                          * overlay(A PLACING B FROM C) is converted to
6327                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+char_length(B))
6328                                          */
6329                                         FuncCall *n = makeNode(FuncCall);
6330                                         n->funcname = SystemFuncName("overlay");
6331                                         n->args = $3;
6332                                         n->agg_star = FALSE;
6333                                         n->agg_distinct = FALSE;
6334                                         $$ = (Node *)n;
6335                                 }
6336                         | POSITION '(' position_list ')'
6337                                 {
6338                                         /* position(A in B) is converted to position(B, A) */
6339                                         FuncCall *n = makeNode(FuncCall);
6340                                         n->funcname = SystemFuncName("position");
6341                                         n->args = $3;
6342                                         n->agg_star = FALSE;
6343                                         n->agg_distinct = FALSE;
6344                                         $$ = (Node *)n;
6345                                 }
6346                         | SUBSTRING '(' substr_list ')'
6347                                 {
6348                                         /* substring(A from B for C) is converted to
6349                                          * substring(A, B, C) - thomas 2000-11-28
6350                                          */
6351                                         FuncCall *n = makeNode(FuncCall);
6352                                         n->funcname = SystemFuncName("substring");
6353                                         n->args = $3;
6354                                         n->agg_star = FALSE;
6355                                         n->agg_distinct = FALSE;
6356                                         $$ = (Node *)n;
6357                                 }
6358                         | TREAT '(' a_expr AS Typename ')'
6359                                 {
6360                                         /* TREAT(expr AS target) converts expr of a particular type to target,
6361                                          * which is defined to be a subtype of the original expression.
6362                                          * In SQL99, this is intended for use with structured UDTs,
6363                                          * but let's make this a generally useful form allowing stronger
6364                                          * coersions than are handled by implicit casting.
6365                                          */
6366                                         FuncCall *n = makeNode(FuncCall);
6367                                         /* Convert SystemTypeName() to SystemFuncName() even though
6368                                          * at the moment they result in the same thing.
6369                                          */
6370                                         n->funcname = SystemFuncName(((Value *)llast($5->names))->val.str);
6371                                         n->args = makeList1($3);
6372                                         $$ = (Node *)n;
6373                                 }
6374                         | TRIM '(' BOTH trim_list ')'
6375                                 {
6376                                         /* various trim expressions are defined in SQL92
6377                                          * - thomas 1997-07-19
6378                                          */
6379                                         FuncCall *n = makeNode(FuncCall);
6380                                         n->funcname = SystemFuncName("btrim");
6381                                         n->args = $4;
6382                                         n->agg_star = FALSE;
6383                                         n->agg_distinct = FALSE;
6384                                         $$ = (Node *)n;
6385                                 }
6386                         | TRIM '(' LEADING trim_list ')'
6387                                 {
6388                                         FuncCall *n = makeNode(FuncCall);
6389                                         n->funcname = SystemFuncName("ltrim");
6390                                         n->args = $4;
6391                                         n->agg_star = FALSE;
6392                                         n->agg_distinct = FALSE;
6393                                         $$ = (Node *)n;
6394                                 }
6395                         | TRIM '(' TRAILING trim_list ')'
6396                                 {
6397                                         FuncCall *n = makeNode(FuncCall);
6398                                         n->funcname = SystemFuncName("rtrim");
6399                                         n->args = $4;
6400                                         n->agg_star = FALSE;
6401                                         n->agg_distinct = FALSE;
6402                                         $$ = (Node *)n;
6403                                 }
6404                         | TRIM '(' trim_list ')'
6405                                 {
6406                                         FuncCall *n = makeNode(FuncCall);
6407                                         n->funcname = SystemFuncName("btrim");
6408                                         n->args = $3;
6409                                         n->agg_star = FALSE;
6410                                         n->agg_distinct = FALSE;
6411                                         $$ = (Node *)n;
6412                                 }
6413                         | CONVERT '(' a_expr USING any_name ')'
6414                                 {
6415                                         FuncCall *n = makeNode(FuncCall);
6416                                         A_Const *c = makeNode(A_Const);
6417
6418                                         c->val.type = T_String;
6419                                         c->val.val.str = NameListToQuotedString($5);
6420
6421                                         n->funcname = SystemFuncName("convert_using");
6422                                         n->args = makeList2($3, c);
6423                                         n->agg_star = FALSE;
6424                                         n->agg_distinct = FALSE;
6425                                         $$ = (Node *)n;
6426                                 }
6427                         | CONVERT '(' expr_list ')'
6428                                 {
6429                                         FuncCall *n = makeNode(FuncCall);
6430                                         n->funcname = SystemFuncName("convert");
6431                                         n->args = $3;
6432                                         n->agg_star = FALSE;
6433                                         n->agg_distinct = FALSE;
6434                                         $$ = (Node *)n;
6435                                 }
6436                         | select_with_parens                    %prec UMINUS
6437                                 {
6438                                         SubLink *n = makeNode(SubLink);
6439                                         n->lefthand = NIL;
6440                                         n->oper = NIL;
6441                                         n->useor = FALSE;
6442                                         n->subLinkType = EXPR_SUBLINK;
6443                                         n->subselect = $1;
6444                                         $$ = (Node *)n;
6445                                 }
6446                         | EXISTS select_with_parens
6447                                 {
6448                                         SubLink *n = makeNode(SubLink);
6449                                         n->lefthand = NIL;
6450                                         n->oper = NIL;
6451                                         n->useor = FALSE;
6452                                         n->subLinkType = EXISTS_SUBLINK;
6453                                         n->subselect = $2;
6454                                         $$ = (Node *)n;
6455                                 }
6456                 ;
6457
6458 /*
6459  * Supporting nonterminals for expressions.
6460  */
6461
6462 opt_indirection:
6463                         opt_indirection '[' a_expr ']'
6464                                 {
6465                                         A_Indices *ai = makeNode(A_Indices);
6466                                         ai->lidx = NULL;
6467                                         ai->uidx = $3;
6468                                         $$ = lappend($1, ai);
6469                                 }
6470                         | opt_indirection '[' a_expr ':' a_expr ']'
6471                                 {
6472                                         A_Indices *ai = makeNode(A_Indices);
6473                                         ai->lidx = $3;
6474                                         ai->uidx = $5;
6475                                         $$ = lappend($1, ai);
6476                                 }
6477                         | /*EMPTY*/
6478                                 { $$ = NIL; }
6479                 ;
6480
6481 expr_list:      a_expr                                                                  { $$ = makeList1($1); }
6482                         | expr_list ',' a_expr                                  { $$ = lappend($1, $3); }
6483                 ;
6484
6485 extract_list:
6486                         extract_arg FROM a_expr
6487                                 {
6488                                         A_Const *n = makeNode(A_Const);
6489                                         n->val.type = T_String;
6490                                         n->val.val.str = $1;
6491                                         $$ = makeList2((Node *) n, $3);
6492                                 }
6493                         | /*EMPTY*/                                                             { $$ = NIL; }
6494                 ;
6495
6496 type_list:  type_list ',' Typename
6497                                 {
6498                                         $$ = lappend($1, $3);
6499                                 }
6500                         | Typename
6501                                 {
6502                                         $$ = makeList1($1);
6503                                 }
6504                 ;
6505
6506 /* Allow delimited string SCONST in extract_arg as an SQL extension.
6507  * - thomas 2001-04-12
6508  */
6509
6510 extract_arg:
6511                         IDENT                                                                   { $$ = $1; }
6512                         | YEAR_P                                                                { $$ = "year"; }
6513                         | MONTH_P                                                               { $$ = "month"; }
6514                         | DAY_P                                                                 { $$ = "day"; }
6515                         | HOUR_P                                                                { $$ = "hour"; }
6516                         | MINUTE_P                                                              { $$ = "minute"; }
6517                         | SECOND_P                                                              { $$ = "second"; }
6518                         | SCONST                                                                { $$ = $1; }
6519                 ;
6520
6521 /* OVERLAY() arguments
6522  * SQL99 defines the OVERLAY() function:
6523  * o overlay(text placing text from int for int)
6524  * o overlay(text placing text from int)
6525  */
6526 overlay_list:
6527                         a_expr overlay_placing substr_from substr_for
6528                                 {
6529                                         $$ = makeList4($1, $2, $3, $4);
6530                                 }
6531                         | a_expr overlay_placing substr_from
6532                                 {
6533                                         $$ = makeList3($1, $2, $3);
6534                                 }
6535                 ;
6536
6537 overlay_placing:
6538                         PLACING a_expr
6539                                 { $$ = $2; }
6540                 ;
6541
6542 /* position_list uses b_expr not a_expr to avoid conflict with general IN */
6543
6544 position_list:
6545                         b_expr IN_P b_expr                                              { $$ = makeList2($3, $1); }
6546                         | /*EMPTY*/                                                             { $$ = NIL; }
6547                 ;
6548
6549 /* SUBSTRING() arguments
6550  * SQL9x defines a specific syntax for arguments to SUBSTRING():
6551  * o substring(text from int for int)
6552  * o substring(text from int) get entire string from starting point "int"
6553  * o substring(text from pattern) get entire string matching pattern
6554  * o substring(text for int) get first "int" characters of string
6555  * We also want to implement generic substring functions which accept
6556  * the usual generic list of arguments. So we will accept both styles
6557  * here, and convert the SQL9x style to the generic list for further
6558  * processing. - thomas 2000-11-28
6559  */
6560 substr_list:
6561                         a_expr substr_from substr_for
6562                                 {
6563                                         $$ = makeList3($1, $2, $3);
6564                                 }
6565                         | a_expr substr_for substr_from
6566                                 {
6567                                         $$ = makeList3($1, $3, $2);
6568                                 }
6569                         | a_expr substr_from
6570                                 {
6571                                         $$ = makeList2($1, $2);
6572                                 }
6573                         | a_expr substr_for
6574                                 {
6575                                         A_Const *n = makeNode(A_Const);
6576                                         n->val.type = T_Integer;
6577                                         n->val.val.ival = 1;
6578                                         $$ = makeList3($1, (Node *)n, $2);
6579                                 }
6580                         | expr_list
6581                                 {
6582                                         $$ = $1;
6583                                 }
6584                         | /*EMPTY*/
6585                                 { $$ = NIL; }
6586                 ;
6587
6588 substr_from:
6589                         FROM a_expr                                                             { $$ = $2; }
6590                 ;
6591
6592 substr_for: FOR a_expr                                                          { $$ = $2; }
6593                 ;
6594
6595 trim_list:      a_expr FROM expr_list                                   { $$ = lappend($3, $1); }
6596                         | FROM expr_list                                                { $$ = $2; }
6597                         | expr_list                                                             { $$ = $1; }
6598                 ;
6599
6600 in_expr:        select_with_parens
6601                                 {
6602                                         SubLink *n = makeNode(SubLink);
6603                                         n->subselect = $1;
6604                                         $$ = (Node *)n;
6605                                 }
6606                         | '(' expr_list ')'                                             { $$ = (Node *)$2; }
6607                 ;
6608
6609 /* Case clause
6610  * Define SQL92-style case clause.
6611  * Allow all four forms described in the standard:
6612  * - Full specification
6613  *      CASE WHEN a = b THEN c ... ELSE d END
6614  * - Implicit argument
6615  *      CASE a WHEN b THEN c ... ELSE d END
6616  * - Conditional NULL
6617  *      NULLIF(x,y)
6618  *      same as CASE WHEN x = y THEN NULL ELSE x END
6619  * - Conditional substitution from list, use first non-null argument
6620  *      COALESCE(a,b,...)
6621  * same as CASE WHEN a IS NOT NULL THEN a WHEN b IS NOT NULL THEN b ... END
6622  * - thomas 1998-11-09
6623  */
6624 case_expr:      CASE case_arg when_clause_list case_default END_TRANS
6625                                 {
6626                                         CaseExpr *c = makeNode(CaseExpr);
6627                                         c->arg = (Expr *) $2;
6628                                         c->args = $3;
6629                                         c->defresult = (Expr *) $4;
6630                                         $$ = (Node *)c;
6631                                 }
6632                         | NULLIF '(' a_expr ',' a_expr ')'
6633                                 {
6634                                         CaseExpr *c = makeNode(CaseExpr);
6635                                         CaseWhen *w = makeNode(CaseWhen);
6636
6637                                         w->expr = (Expr *) makeSimpleA_Expr(OP, "=", $3, $5);
6638                                         /* w->result is left NULL */
6639                                         c->args = makeList1(w);
6640                                         c->defresult = (Expr *) $3;
6641                                         $$ = (Node *)c;
6642                                 }
6643                         | COALESCE '(' expr_list ')'
6644                                 {
6645                                         CaseExpr *c = makeNode(CaseExpr);
6646                                         List *l;
6647                                         foreach (l,$3)
6648                                         {
6649                                                 CaseWhen *w = makeNode(CaseWhen);
6650                                                 NullTest *n = makeNode(NullTest);
6651                                                 n->arg = lfirst(l);
6652                                                 n->nulltesttype = IS_NOT_NULL;
6653                                                 w->expr = (Expr *) n;
6654                                                 w->result = lfirst(l);
6655                                                 c->args = lappend(c->args, w);
6656                                         }
6657                                         $$ = (Node *)c;
6658                                 }
6659                 ;
6660
6661 when_clause_list:
6662                         /* There must be at least one */
6663                         when_clause                                                             { $$ = makeList1($1); }
6664                         | when_clause_list when_clause                  { $$ = lappend($1, $2); }
6665                 ;
6666
6667 when_clause:
6668                         WHEN a_expr THEN a_expr
6669                                 {
6670                                         CaseWhen *w = makeNode(CaseWhen);
6671                                         w->expr = (Expr *) $2;
6672                                         w->result = (Expr *) $4;
6673                                         $$ = (Node *)w;
6674                                 }
6675                 ;
6676
6677 case_default:
6678                         ELSE a_expr                                                             { $$ = $2; }
6679                         | /*EMPTY*/                                                             { $$ = NULL; }
6680                 ;
6681
6682 case_arg:       a_expr                                                                  { $$ = $1; }
6683                         | /*EMPTY*/                                                             { $$ = NULL; }
6684                 ;
6685
6686 /*
6687  * columnref starts with relation_name not ColId, so that OLD and NEW
6688  * references can be accepted.  Note that when there are more than two
6689  * dotted names, the first name is not actually a relation name...
6690  */
6691 columnref:      relation_name opt_indirection
6692                                 {
6693                                         $$ = makeNode(ColumnRef);
6694                                         $$->fields = makeList1(makeString($1));
6695                                         $$->indirection = $2;
6696                                 }
6697                         | dotted_name opt_indirection
6698                                 {
6699                                         $$ = makeNode(ColumnRef);
6700                                         $$->fields = $1;
6701                                         $$->indirection = $2;
6702                                 }
6703                 ;
6704
6705 dotted_name:
6706                         relation_name attrs
6707                                         { $$ = lcons(makeString($1), $2); }
6708                 ;
6709
6710 attrs:          '.' attr_name
6711                                         { $$ = makeList1(makeString($2)); }
6712                         | '.' '*'
6713                                         { $$ = makeList1(makeString("*")); }
6714                         | '.' attr_name attrs
6715                                         { $$ = lcons(makeString($2), $3); }
6716                 ;
6717
6718
6719 /*****************************************************************************
6720  *
6721  *      target lists
6722  *
6723  *****************************************************************************/
6724
6725 /* Target lists as found in SELECT ... and INSERT VALUES ( ... ) */
6726
6727 target_list:
6728                         target_el                                                               { $$ = makeList1($1); }
6729                         | target_list ',' target_el                             { $$ = lappend($1, $3); }
6730                 ;
6731
6732 /* AS is not optional because shift/red conflict with unary ops */
6733 target_el:      a_expr AS ColLabel
6734                                 {
6735                                         $$ = makeNode(ResTarget);
6736                                         $$->name = $3;
6737                                         $$->indirection = NIL;
6738                                         $$->val = (Node *)$1;
6739                                 }
6740                         | a_expr
6741                                 {
6742                                         $$ = makeNode(ResTarget);
6743                                         $$->name = NULL;
6744                                         $$->indirection = NIL;
6745                                         $$->val = (Node *)$1;
6746                                 }
6747                         | '*'
6748                                 {
6749                                         ColumnRef *n = makeNode(ColumnRef);
6750                                         n->fields = makeList1(makeString("*"));
6751                                         n->indirection = NIL;
6752                                         $$ = makeNode(ResTarget);
6753                                         $$->name = NULL;
6754                                         $$->indirection = NIL;
6755                                         $$->val = (Node *)n;
6756                                 }
6757                 ;
6758
6759 /* Target list as found in UPDATE table SET ...
6760 | '(' row_ ')' = '(' row_ ')'
6761 {
6762         $$ = NULL;
6763 }
6764  */
6765 update_target_list:
6766                         update_target_el                                                { $$ = makeList1($1); }
6767                         | update_target_list ',' update_target_el { $$ = lappend($1,$3); }
6768                 ;
6769
6770 update_target_el:
6771                         ColId opt_indirection '=' a_expr
6772                                 {
6773                                         $$ = makeNode(ResTarget);
6774                                         $$->name = $1;
6775                                         $$->indirection = $2;
6776                                         $$->val = (Node *)$4;
6777                                 }
6778                 ;
6779
6780 insert_target_list:
6781                         insert_target_el                                                { $$ = makeList1($1); }
6782                         | insert_target_list ',' insert_target_el { $$ = lappend($1, $3); }
6783                 ;
6784
6785 insert_target_el:
6786                         target_el                                                               { $$ = $1; }
6787                         | DEFAULT
6788                                 {
6789                                         InsertDefault *def = makeNode(InsertDefault);
6790                                         $$ = makeNode(ResTarget);
6791                                         $$->name = NULL;
6792                                         $$->indirection = NULL;
6793                                         $$->val = (Node *)def;
6794                                 }
6795                 ;
6796
6797
6798 /*****************************************************************************
6799  *
6800  *      Names and constants
6801  *
6802  *****************************************************************************/
6803
6804 relation_name:
6805                         SpecialRuleRelation                                             { $$ = $1; }
6806                         | ColId                                                                 { $$ = $1; }
6807                 ;
6808
6809 qualified_name_list:
6810                         qualified_name                                                  { $$ = makeList1($1); }
6811                         | qualified_name_list ',' qualified_name { $$ = lappend($1, $3); }
6812                 ;
6813
6814 qualified_name:
6815                         relation_name
6816                                 {
6817                                         $$ = makeNode(RangeVar);
6818                                         $$->catalogname = NULL;
6819                                         $$->schemaname = NULL;
6820                                         $$->relname = $1;
6821                                 }
6822                         | dotted_name
6823                                 {
6824                                         $$ = makeNode(RangeVar);
6825                                         switch (length($1))
6826                                         {
6827                                                 case 2:
6828                                                         $$->catalogname = NULL;
6829                                                         $$->schemaname = strVal(lfirst($1));
6830                                                         $$->relname = strVal(lsecond($1));
6831                                                         break;
6832                                                 case 3:
6833                                                         $$->catalogname = strVal(lfirst($1));
6834                                                         $$->schemaname = strVal(lsecond($1));
6835                                                         $$->relname = strVal(lfirst(lnext(lnext($1))));
6836                                                         break;
6837                                                 default:
6838                                                         elog(ERROR,
6839                                                         "Improper qualified name "
6840                                                         "(too many dotted names): %s",
6841                                                                  NameListToString($1));
6842                                                         break;
6843                                         }
6844                                 }
6845                 ;
6846
6847 name_list:      name
6848                                         { $$ = makeList1(makeString($1)); }
6849                         | name_list ',' name
6850                                         { $$ = lappend($1, makeString($3)); }
6851                 ;
6852
6853
6854 name:           ColId                                                                   { $$ = $1; };
6855
6856 database_name:
6857                         ColId                                                                   { $$ = $1; };
6858
6859 access_method:
6860                         ColId                                                                   { $$ = $1; };
6861
6862 attr_name:      ColId                                                                   { $$ = $1; };
6863
6864 index_name: ColId                                                                       { $$ = $1; };
6865
6866 file_name:      Sconst                                                                  { $$ = $1; };
6867
6868 func_name:      function_name
6869                                         { $$ = makeList1(makeString($1)); }
6870                         | dotted_name                                                   { $$ = $1; }
6871                 ;
6872
6873
6874 /*
6875  * Constants
6876  */
6877 AexprConst: Iconst
6878                                 {
6879                                         A_Const *n = makeNode(A_Const);
6880                                         n->val.type = T_Integer;
6881                                         n->val.val.ival = $1;
6882                                         $$ = (Node *)n;
6883                                 }
6884                         | FCONST
6885                                 {
6886                                         A_Const *n = makeNode(A_Const);
6887                                         n->val.type = T_Float;
6888                                         n->val.val.str = $1;
6889                                         $$ = (Node *)n;
6890                                 }
6891                         | Sconst
6892                                 {
6893                                         A_Const *n = makeNode(A_Const);
6894                                         n->val.type = T_String;
6895                                         n->val.val.str = $1;
6896                                         $$ = (Node *)n;
6897                                 }
6898                         | BCONST
6899                                 {
6900                                         A_Const *n = makeNode(A_Const);
6901                                         n->val.type = T_BitString;
6902                                         n->val.val.str = $1;
6903                                         $$ = (Node *)n;
6904                                 }
6905                         | XCONST
6906                                 {
6907                                         /* This is a bit constant per SQL99:
6908                                          * Without Feature F511, "BIT data type",
6909                                          * a <general literal> shall not be a
6910                                          * <bit string literal> or a <hex string literal>.
6911                                          */
6912                                         A_Const *n = makeNode(A_Const);
6913                                         n->val.type = T_BitString;
6914                                         n->val.val.str = $1;
6915                                         $$ = (Node *)n;
6916                                 }
6917                         | ConstTypename Sconst
6918                                 {
6919                                         A_Const *n = makeNode(A_Const);
6920                                         n->typename = $1;
6921                                         n->val.type = T_String;
6922                                         n->val.val.str = $2;
6923                                         $$ = (Node *)n;
6924                                 }
6925                         | ConstInterval Sconst opt_interval
6926                                 {
6927                                         A_Const *n = makeNode(A_Const);
6928                                         n->typename = $1;
6929                                         n->val.type = T_String;
6930                                         n->val.val.str = $2;
6931                                         /* precision is not specified, but fields may be... */
6932                                         if ($3 != INTERVAL_FULL_RANGE)
6933                                                 n->typename->typmod = INTERVAL_TYPMOD(INTERVAL_FULL_PRECISION, $3);
6934                                         $$ = (Node *)n;
6935                                 }
6936                         | ConstInterval '(' Iconst ')' Sconst opt_interval
6937                                 {
6938                                         A_Const *n = makeNode(A_Const);
6939                                         n->typename = $1;
6940                                         n->val.type = T_String;
6941                                         n->val.val.str = $5;
6942                                         /* precision specified, and fields may be... */
6943                                         if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
6944                                                 elog(ERROR,
6945                                                 "INTERVAL(%d) precision must be between %d and %d",
6946                                                          $3, 0, MAX_INTERVAL_PRECISION);
6947                                         n->typename->typmod = INTERVAL_TYPMOD($3, $6);
6948                                         $$ = (Node *)n;
6949                                 }
6950                         | PARAM opt_indirection
6951                                 {
6952                                         ParamRef *n = makeNode(ParamRef);
6953                                         n->number = $1;
6954                                         n->fields = NIL;
6955                                         n->indirection = $2;
6956                                         $$ = (Node *)n;
6957                                 }
6958                         | TRUE_P
6959                                 {
6960                                         $$ = (Node *)makeBoolConst(TRUE);
6961                                 }
6962                         | FALSE_P
6963                                 {
6964                                         $$ = (Node *)makeBoolConst(FALSE);
6965                                 }
6966                         | NULL_P
6967                                 {
6968                                         A_Const *n = makeNode(A_Const);
6969                                         n->val.type = T_Null;
6970                                         $$ = (Node *)n;
6971                                 }
6972                 ;
6973
6974 Iconst:         ICONST                                                                  { $$ = $1; };
6975 Sconst:         SCONST                                                                  { $$ = $1; };
6976 UserId:         ColId                                                                   { $$ = $1; };
6977
6978 /*
6979  * Name classification hierarchy.
6980  *
6981  * IDENT is the lexeme returned by the lexer for identifiers that match
6982  * no known keyword.  In most cases, we can accept certain keywords as
6983  * names, not only IDENTs.      We prefer to accept as many such keywords
6984  * as possible to minimize the impact of "reserved words" on programmers.
6985  * So, we divide names into several possible classes.  The classification
6986  * is chosen in part to make keywords acceptable as names wherever possible.
6987  */
6988
6989 /* Column identifier --- names that can be column, table, etc names.
6990  */
6991 ColId:          IDENT                                                                   { $$ = $1; }
6992                         | unreserved_keyword                                    { $$ = pstrdup($1); }
6993                         | col_name_keyword                                              { $$ = pstrdup($1); }
6994                 ;
6995
6996 /* Type identifier --- names that can be type names.
6997  */
6998 type_name:      IDENT                                                                   { $$ = $1; }
6999                         | unreserved_keyword                                    { $$ = pstrdup($1); }
7000                 ;
7001
7002 /* Function identifier --- names that can be function names.
7003  */
7004 function_name:
7005                         IDENT                                                                   { $$ = $1; }
7006                         | unreserved_keyword                                    { $$ = pstrdup($1); }
7007                         | func_name_keyword                                             { $$ = pstrdup($1); }
7008                 ;
7009
7010 /* Column label --- allowed labels in "AS" clauses.
7011  * This presently includes *all* Postgres keywords.
7012  */
7013 ColLabel:       IDENT                                                                   { $$ = $1; }
7014                         | unreserved_keyword                                    { $$ = pstrdup($1); }
7015                         | col_name_keyword                                              { $$ = pstrdup($1); }
7016                         | func_name_keyword                                             { $$ = pstrdup($1); }
7017                         | reserved_keyword                                              { $$ = pstrdup($1); }
7018                 ;
7019
7020
7021 /*
7022  * Keyword classification lists.  Generally, every keyword present in
7023  * the Postgres grammar should appear in exactly one of these lists.
7024  *
7025  * Put a new keyword into the first list that it can go into without causing
7026  * shift or reduce conflicts.  The earlier lists define "less reserved"
7027  * categories of keywords.
7028  */
7029
7030 /* "Unreserved" keywords --- available for use as any kind of name.
7031  */
7032 unreserved_keyword:
7033                           ABORT_TRANS
7034                         | ABSOLUTE
7035                         | ACCESS
7036                         | ACTION
7037                         | ADD
7038                         | AFTER
7039                         | AGGREGATE
7040                         | ALTER
7041                         | ASSERTION
7042                         | ASSIGNMENT
7043                         | AT
7044                         | BACKWARD
7045                         | BEFORE
7046                         | BEGIN_TRANS
7047                         | BY
7048                         | CACHE
7049                         | CALLED
7050                         | CASCADE
7051                         | CHAIN
7052                         | CHARACTERISTICS
7053                         | CHECKPOINT
7054                         | CLASS
7055                         | CLOSE
7056                         | CLUSTER
7057                         | COMMENT
7058                         | COMMIT
7059                         | COMMITTED
7060                         | CONSTRAINTS
7061                         | CONVERSION_P
7062                         | COPY
7063                         | CREATEDB
7064                         | CREATEUSER
7065                         | CURSOR
7066                         | CYCLE
7067                         | DATABASE
7068                         | DAY_P
7069                         | DEALLOCATE
7070                         | DECLARE
7071                         | DEFERRED
7072                         | DEFINER
7073                         | DELETE_P
7074                         | DELIMITER
7075                         | DELIMITERS
7076                         | DOMAIN_P
7077                         | DOUBLE
7078                         | DROP
7079                         | EACH
7080                         | ENCODING
7081                         | ENCRYPTED
7082                         | ESCAPE
7083                         | EXCLUSIVE
7084                         | EXECUTE
7085                         | EXPLAIN
7086                         | EXTERNAL
7087                         | FETCH
7088                         | FORCE
7089                         | FORWARD
7090                         | FUNCTION
7091                         | GET
7092                         | GLOBAL
7093                         | HANDLER
7094                         | HOUR_P
7095                         | IMMEDIATE
7096                         | IMMUTABLE
7097                         | IMPLICIT_P
7098                         | INCREMENT
7099                         | INDEX
7100                         | INHERITS
7101                         | INOUT
7102                         | INPUT
7103                         | INSENSITIVE
7104                         | INSERT
7105                         | INSTEAD
7106                         | INVOKER
7107                         | ISOLATION
7108                         | KEY
7109                         | LANGUAGE
7110                         | LANCOMPILER
7111                         | LAST
7112                         | LEVEL
7113                         | LISTEN
7114                         | LOAD
7115                         | LOCAL
7116                         | LOCATION
7117                         | LOCK_P
7118                         | MATCH
7119                         | MAXVALUE
7120                         | MINUTE_P
7121                         | MINVALUE
7122                         | MODE
7123                         | MONTH_P
7124                         | MOVE
7125                         | NAMES
7126                         | NATIONAL
7127                         | NEXT
7128                         | NO
7129                         | NOCREATEDB
7130                         | NOCREATEUSER
7131                         | NOTHING
7132                         | NOTIFY
7133                         | OF
7134                         | OIDS
7135                         | OPERATOR
7136                         | OPTION
7137                         | OUT_P
7138                         | OWNER
7139                         | PARTIAL
7140                         | PASSWORD
7141                         | PATH_P
7142                         | PENDANT
7143                         | PRECISION
7144                         | PREPARE
7145                         | PRESERVE
7146                         | PRIOR
7147                         | PRIVILEGES
7148                         | PROCEDURAL
7149                         | PROCEDURE
7150                         | READ
7151                         | RECHECK
7152                         | REINDEX
7153                         | RELATIVE
7154                         | RENAME
7155                         | REPLACE
7156                         | RESET
7157                         | RESTRICT
7158                         | RETURNS
7159                         | REVOKE
7160                         | ROLLBACK
7161                         | ROWS
7162                         | RULE
7163                         | SCHEMA
7164                         | SCROLL
7165                         | SECOND_P
7166                         | SECURITY
7167                         | SESSION
7168                         | SEQUENCE
7169                         | SERIALIZABLE
7170                         | SET
7171                         | SHARE
7172                         | SHOW
7173                         | SIMPLE
7174                         | STABLE
7175                         | START
7176                         | STATEMENT
7177                         | STATISTICS
7178                         | STDIN
7179                         | STDOUT
7180                         | STORAGE
7181                         | STRICT
7182                         | SYSID
7183                         | TEMP
7184                         | TEMPLATE
7185                         | TEMPORARY
7186                         | TOAST
7187                         | TRANSACTION
7188                         | TRIGGER
7189                         | TRUNCATE
7190                         | TRUSTED
7191                         | TYPE_P
7192                         | UNENCRYPTED
7193                         | UNKNOWN
7194                         | UNLISTEN
7195                         | UNTIL
7196                         | UPDATE
7197                         | USAGE
7198                         | VACUUM
7199                         | VALID
7200                         | VALIDATOR
7201                         | VALUES
7202                         | VARYING
7203                         | VERSION
7204                         | VIEW
7205                         | VOLATILE
7206                         | WITH
7207                         | WITHOUT
7208                         | WRITE
7209                         | WORK
7210                         | YEAR_P
7211                         | ZONE
7212                 ;
7213
7214 /* Column identifier --- keywords that can be column, table, etc names.
7215  *
7216  * Many of these keywords will in fact be recognized as type or function
7217  * names too; but they have special productions for the purpose, and so
7218  * can't be treated as "generic" type or function names.
7219  *
7220  * The type names appearing here are not usable as function names
7221  * because they can be followed by '(' in typename productions, which
7222  * looks too much like a function call for an LR(1) parser.
7223  */
7224 col_name_keyword:
7225                           BIGINT
7226                         | BIT
7227                         | BOOLEAN
7228                         | CHAR_P
7229                         | CHARACTER
7230                         | COALESCE
7231                         | CONVERT
7232                         | DEC
7233                         | DECIMAL
7234                         | EXISTS
7235                         | EXTRACT
7236                         | FLOAT_P
7237                         | INT
7238                         | INTEGER
7239                         | INTERVAL
7240                         | NCHAR
7241                         | NONE
7242                         | NULLIF
7243                         | NUMERIC
7244                         | OVERLAY
7245                         | POSITION
7246                         | REAL
7247                         | ROW
7248                         | SETOF
7249                         | SMALLINT
7250                         | SUBSTRING
7251                         | TIME
7252                         | TIMESTAMP
7253                         | TREAT
7254                         | TRIM
7255                         | VARCHAR
7256                 ;
7257
7258 /* Function identifier --- keywords that can be function names.
7259  *
7260  * Most of these are keywords that are used as operators in expressions;
7261  * in general such keywords can't be column names because they would be
7262  * ambiguous with variables, but they are unambiguous as function identifiers.
7263  *
7264  * Do not include POSITION, SUBSTRING, etc here since they have explicit
7265  * productions in a_expr to support the goofy SQL9x argument syntax.
7266  * - thomas 2000-11-28
7267  */
7268 func_name_keyword:
7269                           AUTHORIZATION
7270                         | BETWEEN
7271                         | BINARY
7272                         | CROSS
7273                         | FREEZE
7274                         | FULL
7275                         | ILIKE
7276                         | IN_P
7277                         | INNER_P
7278                         | IS
7279                         | ISNULL
7280                         | JOIN
7281                         | LEFT
7282                         | LIKE
7283                         | NATURAL
7284                         | NOTNULL
7285                         | OUTER_P
7286                         | OVERLAPS
7287                         | RIGHT
7288                         | SIMILAR
7289                         | VERBOSE
7290                 ;
7291
7292 /* Reserved keyword --- these keywords are usable only as a ColLabel.
7293  *
7294  * Keywords appear here if they could not be distinguished from variable,
7295  * type, or function names in some contexts.  Don't put things here unless
7296  * forced to.
7297  */
7298 reserved_keyword:
7299                           ALL
7300                         | ANALYSE
7301                         | ANALYZE
7302                         | AND
7303                         | ANY
7304                         | AS
7305                         | ASC
7306                         | BOTH
7307                         | CASE
7308                         | CAST
7309                         | CHECK
7310                         | COLLATE
7311                         | COLUMN
7312                         | CONSTRAINT
7313                         | CREATE
7314                         | CURRENT_DATE
7315                         | CURRENT_TIME
7316                         | CURRENT_TIMESTAMP
7317                         | CURRENT_USER
7318                         | DEFAULT
7319                         | DEFERRABLE
7320                         | DESC
7321                         | DISTINCT
7322                         | DO
7323                         | ELSE
7324                         | END_TRANS
7325                         | EXCEPT
7326                         | FALSE_P
7327                         | FOR
7328                         | FOREIGN
7329                         | FROM
7330                         | GRANT
7331                         | GROUP_P
7332                         | HAVING
7333                         | INITIALLY
7334                         | INTERSECT
7335                         | INTO
7336                         | LEADING
7337                         | LIMIT
7338                         | LOCALTIME
7339                         | LOCALTIMESTAMP
7340                         | NEW
7341                         | NOT
7342                         | NULL_P
7343                         | OFF
7344                         | OFFSET
7345                         | OLD
7346                         | ON
7347                         | ONLY
7348                         | OR
7349                         | ORDER
7350                         | PLACING
7351                         | PRIMARY
7352                         | REFERENCES
7353                         | SELECT
7354                         | SESSION_USER
7355                         | SOME
7356                         | TABLE
7357                         | THEN
7358                         | TO
7359                         | TRAILING
7360                         | TRUE_P
7361                         | UNION
7362                         | UNIQUE
7363                         | USER
7364                         | USING
7365                         | WHEN
7366                         | WHERE
7367                 ;
7368
7369
7370 SpecialRuleRelation:
7371                         OLD
7372                                 {
7373                                         if (QueryIsRule)
7374                                                 $$ = "*OLD*";
7375                                         else
7376                                                 elog(ERROR, "OLD used in non-rule query");
7377                                 }
7378                         | NEW
7379                                 {
7380                                         if (QueryIsRule)
7381                                                 $$ = "*NEW*";
7382                                         else
7383                                                 elog(ERROR, "NEW used in non-rule query");
7384                                 }
7385                 ;
7386
7387 %%
7388
7389 static Node *
7390 makeTypeCast(Node *arg, TypeName *typename)
7391 {
7392         /*
7393          * Simply generate a TypeCast node.
7394          *
7395          * Earlier we would determine whether an A_Const would
7396          * be acceptable, however Domains require coerce_type()
7397          * to process them -- applying constraints as required.
7398          */
7399         TypeCast *n = makeNode(TypeCast);
7400         n->arg = arg;
7401         n->typename = typename;
7402         return (Node *) n;
7403 }
7404
7405 static Node *
7406 makeStringConst(char *str, TypeName *typename)
7407 {
7408         A_Const *n = makeNode(A_Const);
7409
7410         n->val.type = T_String;
7411         n->val.val.str = str;
7412         n->typename = typename;
7413
7414         return (Node *)n;
7415 }
7416
7417 static Node *
7418 makeIntConst(int val)
7419 {
7420         A_Const *n = makeNode(A_Const);
7421         n->val.type = T_Integer;
7422         n->val.val.ival = val;
7423         n->typename = SystemTypeName("int4");
7424
7425         return (Node *)n;
7426 }
7427
7428 static Node *
7429 makeFloatConst(char *str)
7430 {
7431         A_Const *n = makeNode(A_Const);
7432
7433         n->val.type = T_Float;
7434         n->val.val.str = str;
7435         n->typename = SystemTypeName("float8");
7436
7437         return (Node *)n;
7438 }
7439
7440 static Node *
7441 makeAConst(Value *v)
7442 {
7443         Node *n;
7444
7445         switch (v->type)
7446         {
7447                 case T_Float:
7448                         n = makeFloatConst(v->val.str);
7449                         break;
7450
7451                 case T_Integer:
7452                         n = makeIntConst(v->val.ival);
7453                         break;
7454
7455                 case T_String:
7456                 default:
7457                         n = makeStringConst(v->val.str, NULL);
7458                         break;
7459         }
7460
7461         return n;
7462 }
7463
7464 /* makeDefElem()
7465  * Create a DefElem node and set contents.
7466  * Could be moved to nodes/makefuncs.c if this is useful elsewhere.
7467  */
7468 static DefElem *
7469 makeDefElem(char *name, Node *arg)
7470 {
7471         DefElem *f = makeNode(DefElem);
7472         f->defname = name;
7473         f->arg = arg;
7474         return f;
7475 }
7476
7477 /* makeBoolConst()
7478  * Create an A_Const node and initialize to a boolean constant.
7479  */
7480 static A_Const *
7481 makeBoolConst(bool state)
7482 {
7483         A_Const *n = makeNode(A_Const);
7484         n->val.type = T_String;
7485         n->val.val.str = (state? "t": "f");
7486         n->typename = SystemTypeName("bool");
7487         return n;
7488 }
7489
7490 /* makeRowExpr()
7491  * Generate separate operator nodes for a single row descriptor expression.
7492  * Perhaps this should go deeper in the parser someday...
7493  * - thomas 1997-12-22
7494  */
7495 static Node *
7496 makeRowExpr(List *opr, List *largs, List *rargs)
7497 {
7498         Node *expr = NULL;
7499         Node *larg, *rarg;
7500         char *oprname;
7501
7502         if (length(largs) != length(rargs))
7503                 elog(ERROR, "Unequal number of entries in row expression");
7504
7505         if (lnext(largs) != NIL)
7506                 expr = makeRowExpr(opr, lnext(largs), lnext(rargs));
7507
7508         larg = lfirst(largs);
7509         rarg = lfirst(rargs);
7510
7511         oprname = strVal(llast(opr));
7512
7513         if ((strcmp(oprname, "=") == 0) ||
7514                 (strcmp(oprname, "<") == 0) ||
7515                 (strcmp(oprname, "<=") == 0) ||
7516                 (strcmp(oprname, ">") == 0) ||
7517                 (strcmp(oprname, ">=") == 0))
7518         {
7519                 if (expr == NULL)
7520                         expr = (Node *) makeA_Expr(OP, opr, larg, rarg);
7521                 else
7522                         expr = (Node *) makeA_Expr(AND, NIL, expr,
7523                                                                            (Node *) makeA_Expr(OP, opr,
7524                                                                                                                    larg, rarg));
7525         }
7526         else if (strcmp(oprname, "<>") == 0)
7527         {
7528                 if (expr == NULL)
7529                         expr = (Node *) makeA_Expr(OP, opr, larg, rarg);
7530                 else
7531                         expr = (Node *) makeA_Expr(OR, NIL, expr,
7532                                                                            (Node *) makeA_Expr(OP, opr,
7533                                                                                                                    larg, rarg));
7534         }
7535         else
7536         {
7537                 elog(ERROR, "Operator '%s' not implemented for row expressions",
7538                          oprname);
7539         }
7540
7541         return expr;
7542 }
7543
7544 /* makeDistinctExpr()
7545  * Generate separate operator nodes for a single row descriptor expression.
7546  * Same comments as for makeRowExpr().
7547  */
7548 static Node *
7549 makeDistinctExpr(List *largs, List *rargs)
7550 {
7551         Node *expr = NULL;
7552         Node *larg, *rarg;
7553
7554         if (length(largs) != length(rargs))
7555                 elog(ERROR, "Unequal number of entries in row expression");
7556
7557         if (lnext(largs) != NIL)
7558                 expr = makeDistinctExpr(lnext(largs), lnext(rargs));
7559
7560         larg = lfirst(largs);
7561         rarg = lfirst(rargs);
7562
7563         if (expr == NULL)
7564                 expr = (Node *) makeSimpleA_Expr(DISTINCT, "=", larg, rarg);
7565         else
7566                 expr = (Node *) makeA_Expr(OR, NIL, expr,
7567                                                                    (Node *) makeSimpleA_Expr(DISTINCT, "=",
7568                                                                                                                          larg, rarg));
7569
7570         return expr;
7571 }
7572
7573 /* makeRowNullTest()
7574  * Generate separate operator nodes for a single row descriptor test.
7575  */
7576 static Node *
7577 makeRowNullTest(NullTestType test, List *args)
7578 {
7579         Node *expr = NULL;
7580         NullTest *n;
7581
7582         if (lnext(args) != NIL)
7583                 expr = makeRowNullTest(test, lnext(args));
7584
7585         n = makeNode(NullTest);
7586         n->arg = (Expr *) lfirst(args);
7587         n->nulltesttype = test;
7588
7589         if (expr == NULL)
7590                 expr = (Node *) n;
7591         else if (test == IS_NOT_NULL)
7592                 expr = (Node *) makeA_Expr(OR, NIL, expr, (Node *)n);
7593         else
7594                 expr = (Node *) makeA_Expr(AND, NIL, expr, (Node *)n);
7595
7596         return expr;
7597 }
7598
7599 /* makeOverlaps()
7600  * Create and populate a FuncCall node to support the OVERLAPS operator.
7601  */
7602 static FuncCall *
7603 makeOverlaps(List *largs, List *rargs)
7604 {
7605         FuncCall *n = makeNode(FuncCall);
7606         n->funcname = SystemFuncName("overlaps");
7607         if (length(largs) == 1)
7608                 largs = lappend(largs, largs);
7609         else if (length(largs) != 2)
7610                 elog(ERROR, "Wrong number of parameters"
7611                          " on left side of OVERLAPS expression");
7612         if (length(rargs) == 1)
7613                 rargs = lappend(rargs, rargs);
7614         else if (length(rargs) != 2)
7615                 elog(ERROR, "Wrong number of parameters"
7616                          " on right side of OVERLAPS expression");
7617         n->args = nconc(largs, rargs);
7618         n->agg_star = FALSE;
7619         n->agg_distinct = FALSE;
7620         return n;
7621 }
7622
7623 /* findLeftmostSelect()
7624  * Find the leftmost component SelectStmt in a set-operation parsetree.
7625  */
7626 static SelectStmt *
7627 findLeftmostSelect(SelectStmt *node)
7628 {
7629         while (node && node->op != SETOP_NONE)
7630                 node = node->larg;
7631         Assert(node && IsA(node, SelectStmt) && node->larg == NULL);
7632         return node;
7633 }
7634
7635 /* insertSelectOptions()
7636  * Insert ORDER BY, etc into an already-constructed SelectStmt.
7637  *
7638  * This routine is just to avoid duplicating code in SelectStmt productions.
7639  */
7640 static void
7641 insertSelectOptions(SelectStmt *stmt,
7642                                         List *sortClause, List *forUpdate,
7643                                         Node *limitOffset, Node *limitCount)
7644 {
7645         /*
7646          * Tests here are to reject constructs like
7647          *      (SELECT foo ORDER BY bar) ORDER BY baz
7648          */
7649         if (sortClause)
7650         {
7651                 if (stmt->sortClause)
7652                         elog(ERROR, "Multiple ORDER BY clauses not allowed");
7653                 stmt->sortClause = sortClause;
7654         }
7655         if (forUpdate)
7656         {
7657                 if (stmt->forUpdate)
7658                         elog(ERROR, "Multiple FOR UPDATE clauses not allowed");
7659                 stmt->forUpdate = forUpdate;
7660         }
7661         if (limitOffset)
7662         {
7663                 if (stmt->limitOffset)
7664                         elog(ERROR, "Multiple OFFSET clauses not allowed");
7665                 stmt->limitOffset = limitOffset;
7666         }
7667         if (limitCount)
7668         {
7669                 if (stmt->limitCount)
7670                         elog(ERROR, "Multiple LIMIT clauses not allowed");
7671                 stmt->limitCount = limitCount;
7672         }
7673 }
7674
7675 static Node *
7676 makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
7677 {
7678         SelectStmt *n = makeNode(SelectStmt);
7679
7680         n->op = op;
7681         n->all = all;
7682         n->larg = (SelectStmt *) larg;
7683         n->rarg = (SelectStmt *) rarg;
7684         return (Node *) n;
7685 }
7686
7687 /* SystemFuncName()
7688  * Build a properly-qualified reference to a built-in function.
7689  */
7690 List *
7691 SystemFuncName(char *name)
7692 {
7693         return makeList2(makeString("pg_catalog"), makeString(name));
7694 }
7695
7696 /* SystemTypeName()
7697  * Build a properly-qualified reference to a built-in type.
7698  *
7699  * typmod is defaulted, but may be changed afterwards by caller.
7700  */
7701 TypeName *
7702 SystemTypeName(char *name)
7703 {
7704         TypeName   *n = makeNode(TypeName);
7705
7706         n->names = makeList2(makeString("pg_catalog"), makeString(name));
7707         n->typmod = -1;
7708         return n;
7709 }
7710
7711 /* parser_init()
7712  * Initialize to parse one query string
7713  */
7714 void
7715 parser_init(void)
7716 {
7717         QueryIsRule = FALSE;
7718 }
7719
7720 /* exprIsNullConstant()
7721  * Test whether an a_expr is a plain NULL constant or not.
7722  */
7723 bool
7724 exprIsNullConstant(Node *arg)
7725 {
7726         if (arg && IsA(arg, A_Const))
7727         {
7728                 A_Const *con = (A_Const *) arg;
7729
7730                 if (con->val.type == T_Null &&
7731                         con->typename == NULL)
7732                         return TRUE;
7733         }
7734         return FALSE;
7735 }
7736
7737 /* doNegate()
7738  * Handle negation of a numeric constant.
7739  *
7740  * Formerly, we did this here because the optimizer couldn't cope with
7741  * indexquals that looked like "var = -4" --- it wants "var = const"
7742  * and a unary minus operator applied to a constant didn't qualify.
7743  * As of Postgres 7.0, that problem doesn't exist anymore because there
7744  * is a constant-subexpression simplifier in the optimizer.  However,
7745  * there's still a good reason for doing this here, which is that we can
7746  * postpone committing to a particular internal representation for simple
7747  * negative constants.  It's better to leave "-123.456" in string form
7748  * until we know what the desired type is.
7749  */
7750 static Node *
7751 doNegate(Node *n)
7752 {
7753         if (IsA(n, A_Const))
7754         {
7755                 A_Const *con = (A_Const *)n;
7756
7757                 if (con->val.type == T_Integer)
7758                 {
7759                         con->val.val.ival = -con->val.val.ival;
7760                         return n;
7761                 }
7762                 if (con->val.type == T_Float)
7763                 {
7764                         doNegateFloat(&con->val);
7765                         return n;
7766                 }
7767         }
7768
7769         return (Node *) makeSimpleA_Expr(OP, "-", NULL, n);
7770 }
7771
7772 static void
7773 doNegateFloat(Value *v)
7774 {
7775         char   *oldval = v->val.str;
7776
7777         Assert(IsA(v, Float));
7778         if (*oldval == '+')
7779                 oldval++;
7780         if (*oldval == '-')
7781                 v->val.str = oldval+1;  /* just strip the '-' */
7782         else
7783         {
7784                 char   *newval = (char *) palloc(strlen(oldval) + 2);
7785
7786                 *newval = '-';
7787                 strcpy(newval+1, oldval);
7788                 v->val.str = newval;
7789         }
7790 }
7791
7792 #include "scan.c"