OSDN Git Service

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