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