]> granicus.if.org Git - postgresql/blob - src/backend/parser/gram.y
Add an OR REPLACE option to CREATE LANGUAGE.
[postgresql] / src / backend / parser / gram.y
1 %{
2
3 /*#define YYDEBUG 1*/
4 /*-------------------------------------------------------------------------
5  *
6  * gram.y
7  *        POSTGRESQL BISON rules/actions
8  *
9  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.711 2010/02/23 22:51:42 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 during parse analysis 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 "catalog/index.h"
55 #include "catalog/namespace.h"
56 #include "catalog/pg_trigger.h"
57 #include "commands/defrem.h"
58 #include "nodes/makefuncs.h"
59 #include "nodes/nodeFuncs.h"
60 #include "parser/gramparse.h"
61 #include "parser/parser.h"
62 #include "storage/lmgr.h"
63 #include "utils/date.h"
64 #include "utils/datetime.h"
65 #include "utils/numeric.h"
66 #include "utils/xml.h"
67
68
69 /* Location tracking support --- simpler than bison's default */
70 #define YYLLOC_DEFAULT(Current, Rhs, N) \
71         do { \
72                 if (N) \
73                         (Current) = (Rhs)[1]; \
74                 else \
75                         (Current) = (Rhs)[0]; \
76         } while (0)
77
78 /*
79  * Bison doesn't allocate anything that needs to live across parser calls,
80  * so we can easily have it use palloc instead of malloc.  This prevents
81  * memory leaks if we error out during parsing.  Note this only works with
82  * bison >= 2.0.  However, in bison 1.875 the default is to use alloca()
83  * if possible, so there's not really much problem anyhow, at least if
84  * you're building with gcc.
85  */
86 #define YYMALLOC palloc
87 #define YYFREE   pfree
88
89 /* Private struct for the result of privilege_target production */
90 typedef struct PrivTarget
91 {
92         GrantTargetType targtype;
93         GrantObjectType objtype;
94         List       *objs;
95 } PrivTarget;
96
97
98 #define parser_yyerror(msg)  scanner_yyerror(msg, yyscanner)
99 #define parser_errposition(pos)  scanner_errposition(pos, yyscanner)
100
101 static void base_yyerror(YYLTYPE *yylloc, core_yyscan_t yyscanner,
102                                                  const char *msg);
103 static Node *makeColumnRef(char *colname, List *indirection,
104                                                    int location, core_yyscan_t yyscanner);
105 static Node *makeTypeCast(Node *arg, TypeName *typename, int location);
106 static Node *makeStringConst(char *str, int location);
107 static Node *makeStringConstCast(char *str, int location, TypeName *typename);
108 static Node *makeIntConst(int val, int location);
109 static Node *makeFloatConst(char *str, int location);
110 static Node *makeBitStringConst(char *str, int location);
111 static Node *makeNullAConst(int location);
112 static Node *makeAConst(Value *v, int location);
113 static Node *makeBoolAConst(bool state, int location);
114 static FuncCall *makeOverlaps(List *largs, List *rargs,
115                                                           int location, core_yyscan_t yyscanner);
116 static void check_qualified_name(List *names, core_yyscan_t yyscanner);
117 static List *check_func_name(List *names, core_yyscan_t yyscanner);
118 static List *check_indirection(List *indirection, core_yyscan_t yyscanner);
119 static List *extractArgTypes(List *parameters);
120 static SelectStmt *findLeftmostSelect(SelectStmt *node);
121 static void insertSelectOptions(SelectStmt *stmt,
122                                                                 List *sortClause, List *lockingClause,
123                                                                 Node *limitOffset, Node *limitCount,
124                                                                 WithClause *withClause,
125                                                                 core_yyscan_t yyscanner);
126 static Node *makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg);
127 static Node *doNegate(Node *n, int location);
128 static void doNegateFloat(Value *v);
129 static Node *makeAArrayExpr(List *elements, int location);
130 static Node *makeXmlExpr(XmlExprOp op, char *name, List *named_args,
131                                                  List *args, int location);
132 static List *mergeTableFuncParameters(List *func_args, List *columns);
133 static TypeName *TableFuncTypeName(List *columns);
134
135 %}
136
137 %pure-parser
138 %expect 0
139 %name-prefix="base_yy"
140 %locations
141
142 %parse-param {core_yyscan_t yyscanner}
143 %lex-param   {core_yyscan_t yyscanner}
144
145 %union
146 {
147         core_YYSTYPE            core_yystype;
148         /* these fields must match core_YYSTYPE: */
149         int                                     ival;
150         char                            *str;
151         const char                      *keyword;
152
153         char                            chr;
154         bool                            boolean;
155         JoinType                        jtype;
156         DropBehavior            dbehavior;
157         OnCommitAction          oncommit;
158         List                            *list;
159         Node                            *node;
160         Value                           *value;
161         ObjectType                      objtype;
162         TypeName                        *typnam;
163         FunctionParameter   *fun_param;
164         FunctionParameterMode fun_param_mode;
165         FuncWithArgs            *funwithargs;
166         DefElem                         *defelt;
167         SortBy                          *sortby;
168         WindowDef                       *windef;
169         JoinExpr                        *jexpr;
170         IndexElem                       *ielem;
171         Alias                           *alias;
172         RangeVar                        *range;
173         IntoClause                      *into;
174         WithClause                      *with;
175         A_Indices                       *aind;
176         ResTarget                       *target;
177         struct PrivTarget       *privtarget;
178         AccessPriv                      *accesspriv;
179         InsertStmt                      *istmt;
180         VariableSetStmt         *vsetstmt;
181 }
182
183 %type <node>    stmt schema_stmt
184                 AlterDatabaseStmt AlterDatabaseSetStmt AlterDomainStmt AlterFdwStmt
185                 AlterForeignServerStmt AlterGroupStmt
186                 AlterObjectSchemaStmt AlterOwnerStmt AlterSeqStmt AlterTableStmt
187                 AlterUserStmt AlterUserMappingStmt AlterUserSetStmt
188                 AlterRoleStmt AlterRoleSetStmt
189                 AlterDefaultPrivilegesStmt DefACLAction
190                 AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt
191                 ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt
192                 CreateDomainStmt CreateGroupStmt CreateOpClassStmt
193                 CreateOpFamilyStmt AlterOpFamilyStmt CreatePLangStmt
194                 CreateSchemaStmt CreateSeqStmt CreateStmt CreateTableSpaceStmt
195                 CreateFdwStmt CreateForeignServerStmt CreateAssertStmt CreateTrigStmt
196                 CreateUserStmt CreateUserMappingStmt CreateRoleStmt
197                 CreatedbStmt DeclareCursorStmt DefineStmt DeleteStmt DiscardStmt DoStmt
198                 DropGroupStmt DropOpClassStmt DropOpFamilyStmt DropPLangStmt DropStmt
199                 DropAssertStmt DropTrigStmt DropRuleStmt DropCastStmt DropRoleStmt
200                 DropUserStmt DropdbStmt DropTableSpaceStmt DropFdwStmt
201                 DropForeignServerStmt DropUserMappingStmt ExplainStmt FetchStmt
202                 GrantStmt GrantRoleStmt IndexStmt InsertStmt ListenStmt LoadStmt
203                 LockStmt NotifyStmt ExplainableStmt PreparableStmt
204                 CreateFunctionStmt AlterFunctionStmt ReindexStmt RemoveAggrStmt
205                 RemoveFuncStmt RemoveOperStmt RenameStmt RevokeStmt RevokeRoleStmt
206                 RuleActionStmt RuleActionStmtOrEmpty RuleStmt
207                 SelectStmt TransactionStmt TruncateStmt
208                 UnlistenStmt UpdateStmt VacuumStmt
209                 VariableResetStmt VariableSetStmt VariableShowStmt
210                 ViewStmt CheckPointStmt CreateConversionStmt
211                 DeallocateStmt PrepareStmt ExecuteStmt
212                 DropOwnedStmt ReassignOwnedStmt
213                 AlterTSConfigurationStmt AlterTSDictionaryStmt
214
215 %type <node>    select_no_parens select_with_parens select_clause
216                                 simple_select values_clause
217
218 %type <node>    alter_column_default opclass_item opclass_drop alter_using
219 %type <ival>    add_drop opt_asc_desc opt_nulls_order
220
221 %type <node>    alter_table_cmd
222 %type <list>    alter_table_cmds
223
224 %type <dbehavior>       opt_drop_behavior
225
226 %type <list>    createdb_opt_list alterdb_opt_list copy_opt_list
227                                 transaction_mode_list
228 %type <defelt>  createdb_opt_item alterdb_opt_item copy_opt_item
229                                 transaction_mode_item
230
231 %type <ival>    opt_lock lock_type cast_context
232 %type <ival>    vacuum_option_list vacuum_option_elem
233 %type <boolean> opt_force opt_or_replace
234                                 opt_grant_grant_option opt_grant_admin_option
235                                 opt_nowait opt_if_exists opt_with_data
236
237 %type <list>    OptRoleList AlterOptRoleList
238 %type <defelt>  CreateOptRoleElem AlterOptRoleElem
239
240 %type <str>             opt_type
241 %type <str>             foreign_server_version opt_foreign_server_version
242 %type <str>             auth_ident
243 %type <str>             opt_in_database
244
245 %type <str>             OptSchemaName
246 %type <list>    OptSchemaEltList
247
248 %type <boolean> TriggerActionTime TriggerForSpec opt_trusted opt_restart_seqs
249
250 %type <list>    TriggerEvents TriggerOneEvent
251 %type <value>   TriggerFuncArg
252 %type <node>    TriggerWhen
253
254 %type <str>             copy_file_name
255                                 database_name access_method_clause access_method attr_name
256                                 name cursor_name file_name
257                                 index_name opt_index_name cluster_index_specification
258
259 %type <list>    func_name handler_name qual_Op qual_all_Op subquery_Op
260                                 opt_class opt_inline_handler opt_validator validator_clause
261
262 %type <range>   qualified_name OptConstrFromTable
263
264 %type <str>             all_Op MathOp
265
266 %type <str>             iso_level opt_encoding
267 %type <node>    grantee
268 %type <list>    grantee_list
269 %type <accesspriv> privilege
270 %type <list>    privileges privilege_list
271 %type <privtarget> privilege_target
272 %type <funwithargs> function_with_argtypes
273 %type <list>    function_with_argtypes_list
274 %type <ival>    defacl_privilege_target
275 %type <defelt>  DefACLOption
276 %type <list>    DefACLOptionList
277
278 %type <list>    stmtblock stmtmulti
279                                 OptTableElementList TableElementList OptInherit definition
280                                 OptTypedTableElementList TypedTableElementList
281                                 reloptions opt_reloptions
282                                 OptWith opt_distinct opt_definition func_args func_args_list
283                                 func_args_with_defaults func_args_with_defaults_list
284                                 func_as createfunc_opt_list alterfunc_opt_list
285                                 aggr_args old_aggr_definition old_aggr_list
286                                 oper_argtypes RuleActionList RuleActionMulti
287                                 opt_column_list columnList opt_name_list
288                                 sort_clause opt_sort_clause sortby_list index_params
289                                 name_list from_clause from_list opt_array_bounds
290                                 qualified_name_list any_name any_name_list
291                                 any_operator expr_list attrs
292                                 target_list insert_column_list set_target_list
293                                 set_clause_list set_clause multiple_set_clause
294                                 ctext_expr_list ctext_row def_list indirection opt_indirection
295                                 reloption_list group_clause TriggerFuncArgs select_limit
296                                 opt_select_limit opclass_item_list opclass_drop_list
297                                 opt_opfamily transaction_mode_list_or_empty
298                                 TableFuncElementList opt_type_modifiers
299                                 prep_type_clause
300                                 execute_param_clause using_clause returning_clause
301                                 opt_enum_val_list enum_val_list table_func_column_list
302                                 create_generic_options alter_generic_options
303                                 relation_expr_list dostmt_opt_list
304
305 %type <range>   OptTempTableName
306 %type <into>    into_clause create_as_target
307
308 %type <defelt>  createfunc_opt_item common_func_opt_item dostmt_opt_item
309 %type <fun_param> func_arg func_arg_with_default table_func_column
310 %type <fun_param_mode> arg_class
311 %type <typnam>  func_return func_type
312
313 %type <boolean>  TriggerForType OptTemp
314 %type <oncommit> OnCommitOption
315
316 %type <node>    for_locking_item
317 %type <list>    for_locking_clause opt_for_locking_clause for_locking_items
318 %type <list>    locked_rels_list
319 %type <boolean> opt_all
320
321 %type <node>    join_outer join_qual
322 %type <jtype>   join_type
323
324 %type <list>    extract_list overlay_list position_list
325 %type <list>    substr_list trim_list
326 %type <list>    opt_interval interval_second
327 %type <node>    overlay_placing substr_from substr_for
328
329 %type <boolean> opt_instead
330 %type <boolean> opt_unique opt_concurrently opt_verbose opt_full
331 %type <boolean> opt_freeze opt_default opt_recheck
332 %type <defelt>  opt_binary opt_oids copy_delimiter
333
334 %type <boolean> copy_from
335
336 %type <ival>    opt_column event cursor_options opt_hold opt_set_data
337 %type <objtype> reindex_type drop_type comment_type
338
339 %type <node>    fetch_args limit_clause select_limit_value
340                                 offset_clause select_offset_value
341                                 select_offset_value2 opt_select_fetch_first_value
342 %type <ival>    row_or_rows first_or_next
343
344 %type <list>    OptSeqOptList SeqOptList
345 %type <defelt>  SeqOptElem
346
347 %type <istmt>   insert_rest
348
349 %type <vsetstmt> set_rest SetResetClause
350
351 %type <node>    TableElement TypedTableElement ConstraintElem TableFuncElement
352 %type <node>    columnDef columnOptions
353 %type <defelt>  def_elem reloption_elem old_aggr_elem
354 %type <node>    def_arg columnElem where_clause where_or_current_clause
355                                 a_expr b_expr c_expr func_expr AexprConst indirection_el
356                                 columnref in_expr having_clause func_table array_expr
357                                 ExclusionWhereClause
358 %type <list>    ExclusionConstraintList ExclusionConstraintElem
359 %type <list>    func_arg_list
360 %type <node>    func_arg_expr
361 %type <list>    row type_list array_expr_list
362 %type <node>    case_expr case_arg when_clause case_default
363 %type <list>    when_clause_list
364 %type <ival>    sub_type
365 %type <list>    OptCreateAs CreateAsList
366 %type <node>    CreateAsElement ctext_expr
367 %type <value>   NumericOnly
368 %type <alias>   alias_clause
369 %type <sortby>  sortby
370 %type <ielem>   index_elem
371 %type <node>    table_ref
372 %type <jexpr>   joined_table
373 %type <range>   relation_expr
374 %type <range>   relation_expr_opt_alias
375 %type <target>  target_el single_set_clause set_target insert_column_item
376
377 %type <str>             generic_option_name
378 %type <node>    generic_option_arg
379 %type <defelt>  generic_option_elem alter_generic_option_elem
380 %type <list>    generic_option_list alter_generic_option_list
381 %type <str>             explain_option_name
382 %type <node>    explain_option_arg
383 %type <defelt>  explain_option_elem
384 %type <list>    explain_option_list
385 %type <node>    copy_generic_opt_arg copy_generic_opt_arg_list_item
386 %type <defelt>  copy_generic_opt_elem
387 %type <list>    copy_generic_opt_list copy_generic_opt_arg_list
388 %type <list>    copy_options
389
390 %type <typnam>  Typename SimpleTypename ConstTypename
391                                 GenericType Numeric opt_float
392                                 Character ConstCharacter
393                                 CharacterWithLength CharacterWithoutLength
394                                 ConstDatetime ConstInterval
395                                 Bit ConstBit BitWithLength BitWithoutLength
396 %type <str>             character
397 %type <str>             extract_arg
398 %type <str>             opt_charset
399 %type <boolean> opt_varying opt_timezone
400
401 %type <ival>    Iconst SignedIconst
402 %type <list>    Iconst_list
403 %type <str>             Sconst comment_text notify_payload
404 %type <str>             RoleId opt_granted_by opt_boolean ColId_or_Sconst
405 %type <list>    var_list
406 %type <str>             ColId ColLabel var_name type_function_name param_name
407 %type <node>    var_value zone_value
408
409 %type <keyword> unreserved_keyword type_func_name_keyword
410 %type <keyword> col_name_keyword reserved_keyword
411
412 %type <node>    TableConstraint TableLikeClause
413 %type <ival>    TableLikeOptionList TableLikeOption
414 %type <list>    ColQualList
415 %type <node>    ColConstraint ColConstraintElem ConstraintAttr
416 %type <ival>    key_actions key_delete key_match key_update key_action
417 %type <ival>    ConstraintAttributeSpec ConstraintDeferrabilitySpec
418                                 ConstraintTimeSpec
419
420 %type <list>    constraints_set_list
421 %type <boolean> constraints_set_mode
422 %type <str>             OptTableSpace OptConsTableSpace OptTableSpaceOwner
423 %type <list>    opt_check_option
424
425 %type <target>  xml_attribute_el
426 %type <list>    xml_attribute_list xml_attributes
427 %type <node>    xml_root_version opt_xml_root_standalone
428 %type <ival>    document_or_content
429 %type <boolean> xml_whitespace_option
430
431 %type <node>    common_table_expr
432 %type <with>    with_clause
433 %type <list>    cte_list
434
435 %type <list>    window_clause window_definition_list opt_partition_clause
436 %type <windef>  window_definition over_clause window_specification
437                                 opt_frame_clause frame_extent frame_bound
438 %type <str>             opt_existing_window_name
439
440
441 /*
442  * Non-keyword token types.  These are hard-wired into the "flex" lexer.
443  * They must be listed first so that their numeric codes do not depend on
444  * the set of keywords.  PL/pgsql depends on this so that it can share the
445  * same lexer.  If you add/change tokens here, fix PL/pgsql to match!
446  *
447  * DOT_DOT and COLON_EQUALS are unused in the core SQL grammar, and so will
448  * always provoke parse errors.  They are needed by PL/pgsql.
449  */
450 %token <str>    IDENT FCONST SCONST BCONST XCONST Op
451 %token <ival>   ICONST PARAM
452 %token                  TYPECAST DOT_DOT COLON_EQUALS
453
454 /*
455  * If you want to make any keyword changes, update the keyword table in
456  * src/include/parser/kwlist.h and add new keywords to the appropriate one
457  * of the reserved-or-not-so-reserved keyword lists, below; search
458  * this file for "Keyword category lists".
459  */
460
461 /* ordinary key words in alphabetical order */
462 %token <keyword> ABORT_P ABSOLUTE_P ACCESS ACTION ADD_P ADMIN AFTER
463         AGGREGATE ALL ALSO ALTER ALWAYS ANALYSE ANALYZE AND ANY ARRAY AS ASC
464         ASSERTION ASSIGNMENT ASYMMETRIC AT AUTHORIZATION
465
466         BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT
467         BOOLEAN_P BOTH BY
468
469         CACHE CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
470         CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
471         CLUSTER COALESCE COLLATE COLUMN COMMENT COMMENTS COMMIT
472         COMMITTED CONCURRENTLY CONFIGURATION CONNECTION CONSTRAINT CONSTRAINTS
473         CONTENT_P CONTINUE_P CONVERSION_P COPY COST CREATE CREATEDB
474         CREATEROLE CREATEUSER CROSS CSV CURRENT_P
475         CURRENT_CATALOG CURRENT_DATE CURRENT_ROLE CURRENT_SCHEMA
476         CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR CYCLE
477
478         DATA_P DATABASE DAY_P DEALLOCATE DEC DECIMAL_P DECLARE DEFAULT DEFAULTS
479         DEFERRABLE DEFERRED DEFINER DELETE_P DELIMITER DELIMITERS DESC
480         DICTIONARY DISABLE_P DISCARD DISTINCT DO DOCUMENT_P DOMAIN_P DOUBLE_P DROP
481
482         EACH ELSE ENABLE_P ENCODING ENCRYPTED END_P ENUM_P ESCAPE EXCEPT
483         EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN EXTERNAL EXTRACT
484
485         FALSE_P FAMILY FETCH FIRST_P FLOAT_P FOLLOWING FOR FORCE FOREIGN FORWARD
486         FREEZE FROM FULL FUNCTION FUNCTIONS
487
488         GLOBAL GRANT GRANTED GREATEST GROUP_P
489
490         HANDLER HAVING HEADER_P HOLD HOUR_P
491
492         IDENTITY_P IF_P ILIKE IMMEDIATE IMMUTABLE IMPLICIT_P IN_P
493         INCLUDING INCREMENT INDEX INDEXES INHERIT INHERITS INITIALLY INLINE_P
494         INNER_P INOUT INPUT_P INSENSITIVE INSERT INSTEAD INT_P INTEGER
495         INTERSECT INTERVAL INTO INVOKER IS ISNULL ISOLATION
496
497         JOIN
498
499         KEY
500
501         LANGUAGE LARGE_P LAST_P LC_COLLATE_P LC_CTYPE_P LEADING
502         LEAST LEFT LEVEL LIKE LIMIT LISTEN LOAD LOCAL LOCALTIME LOCALTIMESTAMP
503         LOCATION LOCK_P LOGIN_P
504
505         MAPPING MATCH MAXVALUE MINUTE_P MINVALUE MODE MONTH_P MOVE
506
507         NAME_P NAMES NATIONAL NATURAL NCHAR NEXT NO NOCREATEDB
508         NOCREATEROLE NOCREATEUSER NOINHERIT NOLOGIN_P NONE NOSUPERUSER
509         NOT NOTHING NOTIFY NOTNULL NOWAIT NULL_P NULLIF NULLS_P NUMERIC
510
511         OBJECT_P OF OFF OFFSET OIDS ON ONLY OPERATOR OPTION OPTIONS OR
512         ORDER OUT_P OUTER_P OVER OVERLAPS OVERLAY OWNED OWNER
513
514         PARSER PARTIAL PARTITION PASSWORD PLACING PLANS POSITION
515         PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
516         PRIOR PRIVILEGES PROCEDURAL PROCEDURE
517
518         QUOTE
519
520         RANGE READ REAL REASSIGN RECHECK RECURSIVE REFERENCES REINDEX
521         RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA RESET RESTART
522         RESTRICT RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROW ROWS RULE
523
524         SAVEPOINT SCHEMA SCROLL SEARCH SECOND_P SECURITY SELECT SEQUENCE SEQUENCES
525         SERIALIZABLE SERVER SESSION SESSION_USER SET SETOF SHARE
526         SHOW SIMILAR SIMPLE SMALLINT SOME STABLE STANDALONE_P START STATEMENT
527         STATISTICS STDIN STDOUT STORAGE STRICT_P STRIP_P SUBSTRING SUPERUSER_P
528         SYMMETRIC SYSID SYSTEM_P
529
530         TABLE TABLES TABLESPACE TEMP TEMPLATE TEMPORARY TEXT_P THEN TIME TIMESTAMP
531         TO TRAILING TRANSACTION TREAT TRIGGER TRIM TRUE_P
532         TRUNCATE TRUSTED TYPE_P
533
534         UNBOUNDED UNCOMMITTED UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNTIL
535         UPDATE USER USING
536
537         VACUUM VALID VALIDATOR VALUE_P VALUES VARCHAR VARIADIC VARYING
538         VERBOSE VERSION_P VIEW VOLATILE
539
540         WHEN WHERE WHITESPACE_P WINDOW WITH WITHOUT WORK WRAPPER WRITE
541
542         XML_P XMLATTRIBUTES XMLCONCAT XMLELEMENT XMLFOREST XMLPARSE
543         XMLPI XMLROOT XMLSERIALIZE
544
545         YEAR_P YES_P
546
547         ZONE
548
549 /*
550  * The grammar thinks these are keywords, but they are not in the kwlist.h
551  * list and so can never be entered directly.  The filter in parser.c
552  * creates these tokens when required.
553  */
554 %token                  NULLS_FIRST NULLS_LAST WITH_TIME
555
556
557 /* Precedence: lowest to highest */
558 %nonassoc       SET                             /* see relation_expr_opt_alias */
559 %left           UNION EXCEPT
560 %left           INTERSECT
561 %left           OR
562 %left           AND
563 %right          NOT
564 %right          '='
565 %nonassoc       '<' '>'
566 %nonassoc       LIKE ILIKE SIMILAR
567 %nonassoc       ESCAPE
568 %nonassoc       OVERLAPS
569 %nonassoc       BETWEEN
570 %nonassoc       IN_P
571 %left           POSTFIXOP               /* dummy for postfix Op rules */
572 /*
573  * To support target_el without AS, we must give IDENT an explicit priority
574  * between POSTFIXOP and Op.  We can safely assign the same priority to
575  * various unreserved keywords as needed to resolve ambiguities (this can't
576  * have any bad effects since obviously the keywords will still behave the
577  * same as if they weren't keywords).  We need to do this for PARTITION,
578  * RANGE, ROWS to support opt_existing_window_name; and for RANGE, ROWS
579  * so that they can follow a_expr without creating
580  * postfix-operator problems.
581  *
582  * The frame_bound productions UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING
583  * are even messier: since UNBOUNDED is an unreserved keyword (per spec!),
584  * there is no principled way to distinguish these from the productions
585  * a_expr PRECEDING/FOLLOWING.  We hack this up by giving UNBOUNDED slightly
586  * lower precedence than PRECEDING and FOLLOWING.  At present this doesn't
587  * appear to cause UNBOUNDED to be treated differently from other unreserved
588  * keywords anywhere else in the grammar, but it's definitely risky.  We can
589  * blame any funny behavior of UNBOUNDED on the SQL standard, though.
590  */
591 %nonassoc       UNBOUNDED               /* ideally should have same precedence as IDENT */
592 %nonassoc       IDENT PARTITION RANGE ROWS PRECEDING FOLLOWING
593 %left           Op OPERATOR             /* multi-character ops and user-defined operators */
594 %nonassoc       NOTNULL
595 %nonassoc       ISNULL
596 %nonassoc       IS NULL_P TRUE_P FALSE_P UNKNOWN /* sets precedence for IS NULL, etc */
597 %left           '+' '-'
598 %left           '*' '/' '%'
599 %left           '^'
600 /* Unary Operators */
601 %left           AT ZONE                 /* sets precedence for AT TIME ZONE */
602 %right          UMINUS
603 %left           '[' ']'
604 %left           '(' ')'
605 %left           TYPECAST
606 %left           '.'
607 /*
608  * These might seem to be low-precedence, but actually they are not part
609  * of the arithmetic hierarchy at all in their use as JOIN operators.
610  * We make them high-precedence to support their use as function names.
611  * They wouldn't be given a precedence at all, were it not that we need
612  * left-associativity among the JOIN rules themselves.
613  */
614 %left           JOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
615 /* kluge to keep xml_whitespace_option from causing shift/reduce conflicts */
616 %right          PRESERVE STRIP_P
617
618 %%
619
620 /*
621  *      The target production for the whole parse.
622  */
623 stmtblock:      stmtmulti
624                         {
625                                 pg_yyget_extra(yyscanner)->parsetree = $1;
626                         }
627                 ;
628
629 /* the thrashing around here is to discard "empty" statements... */
630 stmtmulti:      stmtmulti ';' stmt
631                                 {
632                                         if ($3 != NULL)
633                                                 $$ = lappend($1, $3);
634                                         else
635                                                 $$ = $1;
636                                 }
637                         | stmt
638                                 {
639                                         if ($1 != NULL)
640                                                 $$ = list_make1($1);
641                                         else
642                                                 $$ = NIL;
643                                 }
644                 ;
645
646 stmt :
647                         AlterDatabaseStmt
648                         | AlterDatabaseSetStmt
649                         | AlterDefaultPrivilegesStmt
650                         | AlterDomainStmt
651                         | AlterFdwStmt
652                         | AlterForeignServerStmt
653                         | AlterFunctionStmt
654                         | AlterGroupStmt
655                         | AlterObjectSchemaStmt
656                         | AlterOwnerStmt
657                         | AlterSeqStmt
658                         | AlterTableStmt
659                         | AlterRoleSetStmt
660                         | AlterRoleStmt
661                         | AlterTSConfigurationStmt
662                         | AlterTSDictionaryStmt
663                         | AlterUserMappingStmt
664                         | AlterUserSetStmt
665                         | AlterUserStmt
666                         | AnalyzeStmt
667                         | CheckPointStmt
668                         | ClosePortalStmt
669                         | ClusterStmt
670                         | CommentStmt
671                         | ConstraintsSetStmt
672                         | CopyStmt
673                         | CreateAsStmt
674                         | CreateAssertStmt
675                         | CreateCastStmt
676                         | CreateConversionStmt
677                         | CreateDomainStmt
678                         | CreateFdwStmt
679                         | CreateForeignServerStmt
680                         | CreateFunctionStmt
681                         | CreateGroupStmt
682                         | CreateOpClassStmt
683                         | CreateOpFamilyStmt
684                         | AlterOpFamilyStmt
685                         | CreatePLangStmt
686                         | CreateSchemaStmt
687                         | CreateSeqStmt
688                         | CreateStmt
689                         | CreateTableSpaceStmt
690                         | CreateTrigStmt
691                         | CreateRoleStmt
692                         | CreateUserStmt
693                         | CreateUserMappingStmt
694                         | CreatedbStmt
695                         | DeallocateStmt
696                         | DeclareCursorStmt
697                         | DefineStmt
698                         | DeleteStmt
699                         | DiscardStmt
700                         | DoStmt
701                         | DropAssertStmt
702                         | DropCastStmt
703                         | DropFdwStmt
704                         | DropForeignServerStmt
705                         | DropGroupStmt
706                         | DropOpClassStmt
707                         | DropOpFamilyStmt
708                         | DropOwnedStmt
709                         | DropPLangStmt
710                         | DropRuleStmt
711                         | DropStmt
712                         | DropTableSpaceStmt
713                         | DropTrigStmt
714                         | DropRoleStmt
715                         | DropUserStmt
716                         | DropUserMappingStmt
717                         | DropdbStmt
718                         | ExecuteStmt
719                         | ExplainStmt
720                         | FetchStmt
721                         | GrantStmt
722                         | GrantRoleStmt
723                         | IndexStmt
724                         | InsertStmt
725                         | ListenStmt
726                         | LoadStmt
727                         | LockStmt
728                         | NotifyStmt
729                         | PrepareStmt
730                         | ReassignOwnedStmt
731                         | ReindexStmt
732                         | RemoveAggrStmt
733                         | RemoveFuncStmt
734                         | RemoveOperStmt
735                         | RenameStmt
736                         | RevokeStmt
737                         | RevokeRoleStmt
738                         | RuleStmt
739                         | SelectStmt
740                         | TransactionStmt
741                         | TruncateStmt
742                         | UnlistenStmt
743                         | UpdateStmt
744                         | VacuumStmt
745                         | VariableResetStmt
746                         | VariableSetStmt
747                         | VariableShowStmt
748                         | ViewStmt
749                         | /*EMPTY*/
750                                 { $$ = NULL; }
751                 ;
752
753 /*****************************************************************************
754  *
755  * Create a new Postgres DBMS role
756  *
757  *****************************************************************************/
758
759 CreateRoleStmt:
760                         CREATE ROLE RoleId opt_with OptRoleList
761                                 {
762                                         CreateRoleStmt *n = makeNode(CreateRoleStmt);
763                                         n->stmt_type = ROLESTMT_ROLE;
764                                         n->role = $3;
765                                         n->options = $5;
766                                         $$ = (Node *)n;
767                                 }
768                 ;
769
770
771 opt_with:       WITH                                                                    {}
772                         | /*EMPTY*/                                                             {}
773                 ;
774
775 /*
776  * Options for CREATE ROLE and ALTER ROLE (also used by CREATE/ALTER USER
777  * for backwards compatibility).  Note: the only option required by SQL99
778  * is "WITH ADMIN name".
779  */
780 OptRoleList:
781                         OptRoleList CreateOptRoleElem                   { $$ = lappend($1, $2); }
782                         | /* EMPTY */                                                   { $$ = NIL; }
783                 ;
784
785 AlterOptRoleList:
786                         AlterOptRoleList AlterOptRoleElem               { $$ = lappend($1, $2); }
787                         | /* EMPTY */                                                   { $$ = NIL; }
788                 ;
789
790 AlterOptRoleElem:
791                         PASSWORD Sconst
792                                 {
793                                         $$ = makeDefElem("password",
794                                                                          (Node *)makeString($2));
795                                 }
796                         | PASSWORD NULL_P
797                                 {
798                                         $$ = makeDefElem("password", NULL);
799                                 }
800                         | ENCRYPTED PASSWORD Sconst
801                                 {
802                                         $$ = makeDefElem("encryptedPassword",
803                                                                          (Node *)makeString($3));
804                                 }
805                         | UNENCRYPTED PASSWORD Sconst
806                                 {
807                                         $$ = makeDefElem("unencryptedPassword",
808                                                                          (Node *)makeString($3));
809                                 }
810                         | SUPERUSER_P
811                                 {
812                                         $$ = makeDefElem("superuser", (Node *)makeInteger(TRUE));
813                                 }
814                         | NOSUPERUSER
815                                 {
816                                         $$ = makeDefElem("superuser", (Node *)makeInteger(FALSE));
817                                 }
818                         | INHERIT
819                                 {
820                                         $$ = makeDefElem("inherit", (Node *)makeInteger(TRUE));
821                                 }
822                         | NOINHERIT
823                                 {
824                                         $$ = makeDefElem("inherit", (Node *)makeInteger(FALSE));
825                                 }
826                         | CREATEDB
827                                 {
828                                         $$ = makeDefElem("createdb", (Node *)makeInteger(TRUE));
829                                 }
830                         | NOCREATEDB
831                                 {
832                                         $$ = makeDefElem("createdb", (Node *)makeInteger(FALSE));
833                                 }
834                         | CREATEROLE
835                                 {
836                                         $$ = makeDefElem("createrole", (Node *)makeInteger(TRUE));
837                                 }
838                         | NOCREATEROLE
839                                 {
840                                         $$ = makeDefElem("createrole", (Node *)makeInteger(FALSE));
841                                 }
842                         | CREATEUSER
843                                 {
844                                         /* For backwards compatibility, synonym for SUPERUSER */
845                                         $$ = makeDefElem("superuser", (Node *)makeInteger(TRUE));
846                                 }
847                         | NOCREATEUSER
848                                 {
849                                         $$ = makeDefElem("superuser", (Node *)makeInteger(FALSE));
850                                 }
851                         | LOGIN_P
852                                 {
853                                         $$ = makeDefElem("canlogin", (Node *)makeInteger(TRUE));
854                                 }
855                         | NOLOGIN_P
856                                 {
857                                         $$ = makeDefElem("canlogin", (Node *)makeInteger(FALSE));
858                                 }
859                         | CONNECTION LIMIT SignedIconst
860                                 {
861                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($3));
862                                 }
863                         | VALID UNTIL Sconst
864                                 {
865                                         $$ = makeDefElem("validUntil", (Node *)makeString($3));
866                                 }
867                 /*      Supported but not documented for roles, for use by ALTER GROUP. */
868                         | USER name_list
869                                 {
870                                         $$ = makeDefElem("rolemembers", (Node *)$2);
871                                 }
872                 ;
873
874 CreateOptRoleElem:
875                         AlterOptRoleElem                        { $$ = $1; }
876                         /* The following are not supported by ALTER ROLE/USER/GROUP */
877                         | SYSID Iconst
878                                 {
879                                         $$ = makeDefElem("sysid", (Node *)makeInteger($2));
880                                 }
881                         | ADMIN name_list
882                                 {
883                                         $$ = makeDefElem("adminmembers", (Node *)$2);
884                                 }
885                         | ROLE name_list
886                                 {
887                                         $$ = makeDefElem("rolemembers", (Node *)$2);
888                                 }
889                         | IN_P ROLE name_list
890                                 {
891                                         $$ = makeDefElem("addroleto", (Node *)$3);
892                                 }
893                         | IN_P GROUP_P name_list
894                                 {
895                                         $$ = makeDefElem("addroleto", (Node *)$3);
896                                 }
897                 ;
898
899
900 /*****************************************************************************
901  *
902  * Create a new Postgres DBMS user (role with implied login ability)
903  *
904  *****************************************************************************/
905
906 CreateUserStmt:
907                         CREATE USER RoleId opt_with OptRoleList
908                                 {
909                                         CreateRoleStmt *n = makeNode(CreateRoleStmt);
910                                         n->stmt_type = ROLESTMT_USER;
911                                         n->role = $3;
912                                         n->options = $5;
913                                         $$ = (Node *)n;
914                                 }
915                 ;
916
917
918 /*****************************************************************************
919  *
920  * Alter a postgresql DBMS role
921  *
922  *****************************************************************************/
923
924 AlterRoleStmt:
925                         ALTER ROLE RoleId opt_with AlterOptRoleList
926                                  {
927                                         AlterRoleStmt *n = makeNode(AlterRoleStmt);
928                                         n->role = $3;
929                                         n->action = +1; /* add, if there are members */
930                                         n->options = $5;
931                                         $$ = (Node *)n;
932                                  }
933                 ;
934
935 opt_in_database:
936                            /* EMPTY */                                  { $$ = NULL; }
937                         | IN_P DATABASE database_name   { $$ = $3; }
938                 ;
939
940 AlterRoleSetStmt:
941                         ALTER ROLE RoleId opt_in_database SetResetClause
942                                 {
943                                         AlterRoleSetStmt *n = makeNode(AlterRoleSetStmt);
944                                         n->role = $3;
945                                         n->database = $4;
946                                         n->setstmt = $5;
947                                         $$ = (Node *)n;
948                                 }
949                 ;
950
951
952 /*****************************************************************************
953  *
954  * Alter a postgresql DBMS user
955  *
956  *****************************************************************************/
957
958 AlterUserStmt:
959                         ALTER USER RoleId opt_with AlterOptRoleList
960                                  {
961                                         AlterRoleStmt *n = makeNode(AlterRoleStmt);
962                                         n->role = $3;
963                                         n->action = +1; /* add, if there are members */
964                                         n->options = $5;
965                                         $$ = (Node *)n;
966                                  }
967                 ;
968
969
970 AlterUserSetStmt:
971                         ALTER USER RoleId SetResetClause
972                                 {
973                                         AlterRoleSetStmt *n = makeNode(AlterRoleSetStmt);
974                                         n->role = $3;
975                                         n->database = NULL;
976                                         n->setstmt = $4;
977                                         $$ = (Node *)n;
978                                 }
979                         ;
980
981
982 /*****************************************************************************
983  *
984  * Drop a postgresql DBMS role
985  *
986  * XXX Ideally this would have CASCADE/RESTRICT options, but since a role
987  * might own objects in multiple databases, there is presently no way to
988  * implement either cascading or restricting.  Caveat DBA.
989  *****************************************************************************/
990
991 DropRoleStmt:
992                         DROP ROLE name_list
993                                 {
994                                         DropRoleStmt *n = makeNode(DropRoleStmt);
995                                         n->missing_ok = FALSE;
996                                         n->roles = $3;
997                                         $$ = (Node *)n;
998                                 }
999                         | DROP ROLE IF_P EXISTS name_list
1000                                 {
1001                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1002                                         n->missing_ok = TRUE;
1003                                         n->roles = $5;
1004                                         $$ = (Node *)n;
1005                                 }
1006                         ;
1007
1008 /*****************************************************************************
1009  *
1010  * Drop a postgresql DBMS user
1011  *
1012  * XXX Ideally this would have CASCADE/RESTRICT options, but since a user
1013  * might own objects in multiple databases, there is presently no way to
1014  * implement either cascading or restricting.  Caveat DBA.
1015  *****************************************************************************/
1016
1017 DropUserStmt:
1018                         DROP USER name_list
1019                                 {
1020                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1021                                         n->missing_ok = FALSE;
1022                                         n->roles = $3;
1023                                         $$ = (Node *)n;
1024                                 }
1025                         | DROP USER IF_P EXISTS name_list
1026                                 {
1027                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1028                                         n->roles = $5;
1029                                         n->missing_ok = TRUE;
1030                                         $$ = (Node *)n;
1031                                 }
1032                         ;
1033
1034
1035 /*****************************************************************************
1036  *
1037  * Create a postgresql group (role without login ability)
1038  *
1039  *****************************************************************************/
1040
1041 CreateGroupStmt:
1042                         CREATE GROUP_P RoleId opt_with OptRoleList
1043                                 {
1044                                         CreateRoleStmt *n = makeNode(CreateRoleStmt);
1045                                         n->stmt_type = ROLESTMT_GROUP;
1046                                         n->role = $3;
1047                                         n->options = $5;
1048                                         $$ = (Node *)n;
1049                                 }
1050                 ;
1051
1052
1053 /*****************************************************************************
1054  *
1055  * Alter a postgresql group
1056  *
1057  *****************************************************************************/
1058
1059 AlterGroupStmt:
1060                         ALTER GROUP_P RoleId add_drop USER name_list
1061                                 {
1062                                         AlterRoleStmt *n = makeNode(AlterRoleStmt);
1063                                         n->role = $3;
1064                                         n->action = $4;
1065                                         n->options = list_make1(makeDefElem("rolemembers",
1066                                                                                                                 (Node *)$6));
1067                                         $$ = (Node *)n;
1068                                 }
1069                 ;
1070
1071 add_drop:       ADD_P                                                                   { $$ = +1; }
1072                         | DROP                                                                  { $$ = -1; }
1073                 ;
1074
1075
1076 /*****************************************************************************
1077  *
1078  * Drop a postgresql group
1079  *
1080  * XXX see above notes about cascading DROP USER; groups have same problem.
1081  *****************************************************************************/
1082
1083 DropGroupStmt:
1084                         DROP GROUP_P name_list
1085                                 {
1086                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1087                                         n->missing_ok = FALSE;
1088                                         n->roles = $3;
1089                                         $$ = (Node *)n;
1090                                 }
1091                         | DROP GROUP_P IF_P EXISTS name_list
1092                                 {
1093                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1094                                         n->missing_ok = TRUE;
1095                                         n->roles = $5;
1096                                         $$ = (Node *)n;
1097                                 }
1098                 ;
1099
1100
1101 /*****************************************************************************
1102  *
1103  * Manipulate a schema
1104  *
1105  *****************************************************************************/
1106
1107 CreateSchemaStmt:
1108                         CREATE SCHEMA OptSchemaName AUTHORIZATION RoleId OptSchemaEltList
1109                                 {
1110                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
1111                                         /* One can omit the schema name or the authorization id. */
1112                                         if ($3 != NULL)
1113                                                 n->schemaname = $3;
1114                                         else
1115                                                 n->schemaname = $5;
1116                                         n->authid = $5;
1117                                         n->schemaElts = $6;
1118                                         $$ = (Node *)n;
1119                                 }
1120                         | CREATE SCHEMA ColId OptSchemaEltList
1121                                 {
1122                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
1123                                         /* ...but not both */
1124                                         n->schemaname = $3;
1125                                         n->authid = NULL;
1126                                         n->schemaElts = $4;
1127                                         $$ = (Node *)n;
1128                                 }
1129                 ;
1130
1131 OptSchemaName:
1132                         ColId                                                                   { $$ = $1; }
1133                         | /* EMPTY */                                                   { $$ = NULL; }
1134                 ;
1135
1136 OptSchemaEltList:
1137                         OptSchemaEltList schema_stmt                    { $$ = lappend($1, $2); }
1138                         | /* EMPTY */                                                   { $$ = NIL; }
1139                 ;
1140
1141 /*
1142  *      schema_stmt are the ones that can show up inside a CREATE SCHEMA
1143  *      statement (in addition to by themselves).
1144  */
1145 schema_stmt:
1146                         CreateStmt
1147                         | IndexStmt
1148                         | CreateSeqStmt
1149                         | CreateTrigStmt
1150                         | GrantStmt
1151                         | ViewStmt
1152                 ;
1153
1154
1155 /*****************************************************************************
1156  *
1157  * Set PG internal variable
1158  *        SET name TO 'var_value'
1159  * Include SQL92 syntax (thomas 1997-10-22):
1160  *        SET TIME ZONE 'var_value'
1161  *
1162  *****************************************************************************/
1163
1164 VariableSetStmt:
1165                         SET set_rest
1166                                 {
1167                                         VariableSetStmt *n = $2;
1168                                         n->is_local = false;
1169                                         $$ = (Node *) n;
1170                                 }
1171                         | SET LOCAL set_rest
1172                                 {
1173                                         VariableSetStmt *n = $3;
1174                                         n->is_local = true;
1175                                         $$ = (Node *) n;
1176                                 }
1177                         | SET SESSION set_rest
1178                                 {
1179                                         VariableSetStmt *n = $3;
1180                                         n->is_local = false;
1181                                         $$ = (Node *) n;
1182                                 }
1183                 ;
1184
1185 set_rest:       /* Generic SET syntaxes: */
1186                         var_name TO var_list
1187                                 {
1188                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1189                                         n->kind = VAR_SET_VALUE;
1190                                         n->name = $1;
1191                                         n->args = $3;
1192                                         $$ = n;
1193                                 }
1194                         | var_name '=' var_list
1195                                 {
1196                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1197                                         n->kind = VAR_SET_VALUE;
1198                                         n->name = $1;
1199                                         n->args = $3;
1200                                         $$ = n;
1201                                 }
1202                         | var_name TO DEFAULT
1203                                 {
1204                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1205                                         n->kind = VAR_SET_DEFAULT;
1206                                         n->name = $1;
1207                                         $$ = n;
1208                                 }
1209                         | var_name '=' DEFAULT
1210                                 {
1211                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1212                                         n->kind = VAR_SET_DEFAULT;
1213                                         n->name = $1;
1214                                         $$ = n;
1215                                 }
1216                         | var_name FROM CURRENT_P
1217                                 {
1218                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1219                                         n->kind = VAR_SET_CURRENT;
1220                                         n->name = $1;
1221                                         $$ = n;
1222                                 }
1223                         /* Special syntaxes mandated by SQL standard: */
1224                         | TIME ZONE zone_value
1225                                 {
1226                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1227                                         n->kind = VAR_SET_VALUE;
1228                                         n->name = "timezone";
1229                                         if ($3 != NULL)
1230                                                 n->args = list_make1($3);
1231                                         else
1232                                                 n->kind = VAR_SET_DEFAULT;
1233                                         $$ = n;
1234                                 }
1235                         | TRANSACTION transaction_mode_list
1236                                 {
1237                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1238                                         n->kind = VAR_SET_MULTI;
1239                                         n->name = "TRANSACTION";
1240                                         n->args = $2;
1241                                         $$ = n;
1242                                 }
1243                         | SESSION CHARACTERISTICS AS TRANSACTION transaction_mode_list
1244                                 {
1245                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1246                                         n->kind = VAR_SET_MULTI;
1247                                         n->name = "SESSION CHARACTERISTICS";
1248                                         n->args = $5;
1249                                         $$ = n;
1250                                 }
1251                         | CATALOG_P Sconst
1252                                 {
1253                                         ereport(ERROR,
1254                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1255                                                          errmsg("current database cannot be changed"),
1256                                                          parser_errposition(@2)));
1257                                         $$ = NULL; /*not reached*/
1258                                 }
1259                         | SCHEMA Sconst
1260                                 {
1261                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1262                                         n->kind = VAR_SET_VALUE;
1263                                         n->name = "search_path";
1264                                         n->args = list_make1(makeStringConst($2, @2));
1265                                         $$ = n;
1266                                 }
1267                         | NAMES opt_encoding
1268                                 {
1269                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1270                                         n->kind = VAR_SET_VALUE;
1271                                         n->name = "client_encoding";
1272                                         if ($2 != NULL)
1273                                                 n->args = list_make1(makeStringConst($2, @2));
1274                                         else
1275                                                 n->kind = VAR_SET_DEFAULT;
1276                                         $$ = n;
1277                                 }
1278                         | ROLE ColId_or_Sconst
1279                                 {
1280                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1281                                         n->kind = VAR_SET_VALUE;
1282                                         n->name = "role";
1283                                         n->args = list_make1(makeStringConst($2, @2));
1284                                         $$ = n;
1285                                 }
1286                         | SESSION AUTHORIZATION ColId_or_Sconst
1287                                 {
1288                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1289                                         n->kind = VAR_SET_VALUE;
1290                                         n->name = "session_authorization";
1291                                         n->args = list_make1(makeStringConst($3, @3));
1292                                         $$ = n;
1293                                 }
1294                         | SESSION AUTHORIZATION DEFAULT
1295                                 {
1296                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1297                                         n->kind = VAR_SET_DEFAULT;
1298                                         n->name = "session_authorization";
1299                                         $$ = n;
1300                                 }
1301                         | XML_P OPTION document_or_content
1302                                 {
1303                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1304                                         n->kind = VAR_SET_VALUE;
1305                                         n->name = "xmloption";
1306                                         n->args = list_make1(makeStringConst($3 == XMLOPTION_DOCUMENT ? "DOCUMENT" : "CONTENT", @3));
1307                                         $$ = n;
1308                                 }
1309                 ;
1310
1311 var_name:       ColId                                                           { $$ = $1; }
1312                         | var_name '.' ColId
1313                                 {
1314                                         $$ = palloc(strlen($1) + strlen($3) + 2);
1315                                         sprintf($$, "%s.%s", $1, $3);
1316                                 }
1317                 ;
1318
1319 var_list:       var_value                                                               { $$ = list_make1($1); }
1320                         | var_list ',' var_value                                { $$ = lappend($1, $3); }
1321                 ;
1322
1323 var_value:      opt_boolean
1324                                 { $$ = makeStringConst($1, @1); }
1325                         | ColId_or_Sconst
1326                                 { $$ = makeStringConst($1, @1); }
1327                         | NumericOnly
1328                                 { $$ = makeAConst($1, @1); }
1329                 ;
1330
1331 iso_level:      READ UNCOMMITTED                                                { $$ = "read uncommitted"; }
1332                         | READ COMMITTED                                                { $$ = "read committed"; }
1333                         | REPEATABLE READ                                               { $$ = "repeatable read"; }
1334                         | SERIALIZABLE                                                  { $$ = "serializable"; }
1335                 ;
1336
1337 opt_boolean:
1338                         TRUE_P                                                                  { $$ = "true"; }
1339                         | FALSE_P                                                               { $$ = "false"; }
1340                         | ON                                                                    { $$ = "on"; }
1341                         | OFF                                                                   { $$ = "off"; }
1342                 ;
1343
1344 /* Timezone values can be:
1345  * - a string such as 'pst8pdt'
1346  * - an identifier such as "pst8pdt"
1347  * - an integer or floating point number
1348  * - a time interval per SQL99
1349  * ColId gives reduce/reduce errors against ConstInterval and LOCAL,
1350  * so use IDENT (meaning we reject anything that is a key word).
1351  */
1352 zone_value:
1353                         Sconst
1354                                 {
1355                                         $$ = makeStringConst($1, @1);
1356                                 }
1357                         | IDENT
1358                                 {
1359                                         $$ = makeStringConst($1, @1);
1360                                 }
1361                         | ConstInterval Sconst opt_interval
1362                                 {
1363                                         TypeName *t = $1;
1364                                         if ($3 != NIL)
1365                                         {
1366                                                 A_Const *n = (A_Const *) linitial($3);
1367                                                 if ((n->val.val.ival & ~(INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE))) != 0)
1368                                                         ereport(ERROR,
1369                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1370                                                                          errmsg("time zone interval must be HOUR or HOUR TO MINUTE"),
1371                                                                          parser_errposition(@3)));
1372                                         }
1373                                         t->typmods = $3;
1374                                         $$ = makeStringConstCast($2, @2, t);
1375                                 }
1376                         | ConstInterval '(' Iconst ')' Sconst opt_interval
1377                                 {
1378                                         TypeName *t = $1;
1379                                         if ($6 != NIL)
1380                                         {
1381                                                 A_Const *n = (A_Const *) linitial($6);
1382                                                 if ((n->val.val.ival & ~(INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE))) != 0)
1383                                                         ereport(ERROR,
1384                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1385                                                                          errmsg("time zone interval must be HOUR or HOUR TO MINUTE"),
1386                                                                          parser_errposition(@6)));
1387                                                 if (list_length($6) != 1)
1388                                                         ereport(ERROR,
1389                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1390                                                                          errmsg("interval precision specified twice"),
1391                                                                          parser_errposition(@1)));
1392                                                 t->typmods = lappend($6, makeIntConst($3, @3));
1393                                         }
1394                                         else
1395                                                 t->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
1396                                                                                                 makeIntConst($3, @3));
1397                                         $$ = makeStringConstCast($5, @5, t);
1398                                 }
1399                         | NumericOnly                                                   { $$ = makeAConst($1, @1); }
1400                         | DEFAULT                                                               { $$ = NULL; }
1401                         | LOCAL                                                                 { $$ = NULL; }
1402                 ;
1403
1404 opt_encoding:
1405                         Sconst                                                                  { $$ = $1; }
1406                         | DEFAULT                                                               { $$ = NULL; }
1407                         | /*EMPTY*/                                                             { $$ = NULL; }
1408                 ;
1409
1410 ColId_or_Sconst:
1411                         ColId                                                                   { $$ = $1; }
1412                         | Sconst                                                                { $$ = $1; }
1413                 ;
1414
1415 VariableResetStmt:
1416                         RESET var_name
1417                                 {
1418                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1419                                         n->kind = VAR_RESET;
1420                                         n->name = $2;
1421                                         $$ = (Node *) n;
1422                                 }
1423                         | RESET TIME ZONE
1424                                 {
1425                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1426                                         n->kind = VAR_RESET;
1427                                         n->name = "timezone";
1428                                         $$ = (Node *) n;
1429                                 }
1430                         | RESET TRANSACTION ISOLATION LEVEL
1431                                 {
1432                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1433                                         n->kind = VAR_RESET;
1434                                         n->name = "transaction_isolation";
1435                                         $$ = (Node *) n;
1436                                 }
1437                         | RESET SESSION AUTHORIZATION
1438                                 {
1439                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1440                                         n->kind = VAR_RESET;
1441                                         n->name = "session_authorization";
1442                                         $$ = (Node *) n;
1443                                 }
1444                         | RESET ALL
1445                                 {
1446                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1447                                         n->kind = VAR_RESET_ALL;
1448                                         $$ = (Node *) n;
1449                                 }
1450                 ;
1451
1452 /* SetResetClause allows SET or RESET without LOCAL */
1453 SetResetClause:
1454                         SET set_rest                                    { $$ = $2; }
1455                         | VariableResetStmt                             { $$ = (VariableSetStmt *) $1; }
1456                 ;
1457
1458
1459 VariableShowStmt:
1460                         SHOW var_name
1461                                 {
1462                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1463                                         n->name = $2;
1464                                         $$ = (Node *) n;
1465                                 }
1466                         | SHOW TIME ZONE
1467                                 {
1468                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1469                                         n->name = "timezone";
1470                                         $$ = (Node *) n;
1471                                 }
1472                         | SHOW TRANSACTION ISOLATION LEVEL
1473                                 {
1474                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1475                                         n->name = "transaction_isolation";
1476                                         $$ = (Node *) n;
1477                                 }
1478                         | SHOW SESSION AUTHORIZATION
1479                                 {
1480                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1481                                         n->name = "session_authorization";
1482                                         $$ = (Node *) n;
1483                                 }
1484                         | SHOW ALL
1485                                 {
1486                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1487                                         n->name = "all";
1488                                         $$ = (Node *) n;
1489                                 }
1490                 ;
1491
1492
1493 ConstraintsSetStmt:
1494                         SET CONSTRAINTS constraints_set_list constraints_set_mode
1495                                 {
1496                                         ConstraintsSetStmt *n = makeNode(ConstraintsSetStmt);
1497                                         n->constraints = $3;
1498                                         n->deferred    = $4;
1499                                         $$ = (Node *) n;
1500                                 }
1501                 ;
1502
1503 constraints_set_list:
1504                         ALL                                                                             { $$ = NIL; }
1505                         | qualified_name_list                                   { $$ = $1; }
1506                 ;
1507
1508 constraints_set_mode:
1509                         DEFERRED                                                                { $$ = TRUE; }
1510                         | IMMEDIATE                                                             { $$ = FALSE; }
1511                 ;
1512
1513
1514 /*
1515  * Checkpoint statement
1516  */
1517 CheckPointStmt:
1518                         CHECKPOINT
1519                                 {
1520                                         CheckPointStmt *n = makeNode(CheckPointStmt);
1521                                         $$ = (Node *)n;
1522                                 }
1523                 ;
1524
1525
1526 /*****************************************************************************
1527  *
1528  * DISCARD { ALL | TEMP | PLANS }
1529  *
1530  *****************************************************************************/
1531
1532 DiscardStmt:
1533                         DISCARD ALL
1534                                 {
1535                                         DiscardStmt *n = makeNode(DiscardStmt);
1536                                         n->target = DISCARD_ALL;
1537                                         $$ = (Node *) n;
1538                                 }
1539                         | DISCARD TEMP
1540                                 {
1541                                         DiscardStmt *n = makeNode(DiscardStmt);
1542                                         n->target = DISCARD_TEMP;
1543                                         $$ = (Node *) n;
1544                                 }
1545                         | DISCARD TEMPORARY
1546                                 {
1547                                         DiscardStmt *n = makeNode(DiscardStmt);
1548                                         n->target = DISCARD_TEMP;
1549                                         $$ = (Node *) n;
1550                                 }
1551                         | DISCARD PLANS
1552                                 {
1553                                         DiscardStmt *n = makeNode(DiscardStmt);
1554                                         n->target = DISCARD_PLANS;
1555                                         $$ = (Node *) n;
1556                                 }
1557                 ;
1558
1559
1560 /*****************************************************************************
1561  *
1562  *      ALTER [ TABLE | INDEX | SEQUENCE | VIEW ] variations
1563  *
1564  * Note: we accept all subcommands for each of the four variants, and sort
1565  * out what's really legal at execution time.
1566  *****************************************************************************/
1567
1568 AlterTableStmt:
1569                         ALTER TABLE relation_expr alter_table_cmds
1570                                 {
1571                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1572                                         n->relation = $3;
1573                                         n->cmds = $4;
1574                                         n->relkind = OBJECT_TABLE;
1575                                         $$ = (Node *)n;
1576                                 }
1577                 |       ALTER INDEX qualified_name alter_table_cmds
1578                                 {
1579                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1580                                         n->relation = $3;
1581                                         n->cmds = $4;
1582                                         n->relkind = OBJECT_INDEX;
1583                                         $$ = (Node *)n;
1584                                 }
1585                 |       ALTER SEQUENCE qualified_name alter_table_cmds
1586                                 {
1587                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1588                                         n->relation = $3;
1589                                         n->cmds = $4;
1590                                         n->relkind = OBJECT_SEQUENCE;
1591                                         $$ = (Node *)n;
1592                                 }
1593                 |       ALTER VIEW qualified_name alter_table_cmds
1594                                 {
1595                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1596                                         n->relation = $3;
1597                                         n->cmds = $4;
1598                                         n->relkind = OBJECT_VIEW;
1599                                         $$ = (Node *)n;
1600                                 }
1601                 ;
1602
1603 alter_table_cmds:
1604                         alter_table_cmd                                                 { $$ = list_make1($1); }
1605                         | alter_table_cmds ',' alter_table_cmd  { $$ = lappend($1, $3); }
1606                 ;
1607
1608 alter_table_cmd:
1609                         /* ALTER TABLE <name> ADD <coldef> */
1610                         ADD_P columnDef
1611                                 {
1612                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1613                                         n->subtype = AT_AddColumn;
1614                                         n->def = $2;
1615                                         $$ = (Node *)n;
1616                                 }
1617                         /* ALTER TABLE <name> ADD COLUMN <coldef> */
1618                         | ADD_P COLUMN columnDef
1619                                 {
1620                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1621                                         n->subtype = AT_AddColumn;
1622                                         n->def = $3;
1623                                         $$ = (Node *)n;
1624                                 }
1625                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
1626                         | ALTER opt_column ColId alter_column_default
1627                                 {
1628                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1629                                         n->subtype = AT_ColumnDefault;
1630                                         n->name = $3;
1631                                         n->def = $4;
1632                                         $$ = (Node *)n;
1633                                 }
1634                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> DROP NOT NULL */
1635                         | ALTER opt_column ColId DROP NOT NULL_P
1636                                 {
1637                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1638                                         n->subtype = AT_DropNotNull;
1639                                         n->name = $3;
1640                                         $$ = (Node *)n;
1641                                 }
1642                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET NOT NULL */
1643                         | ALTER opt_column ColId SET NOT NULL_P
1644                                 {
1645                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1646                                         n->subtype = AT_SetNotNull;
1647                                         n->name = $3;
1648                                         $$ = (Node *)n;
1649                                 }
1650                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET STATISTICS <SignedIconst> */
1651                         | ALTER opt_column ColId SET STATISTICS SignedIconst
1652                                 {
1653                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1654                                         n->subtype = AT_SetStatistics;
1655                                         n->name = $3;
1656                                         n->def = (Node *) makeInteger($6);
1657                                         $$ = (Node *)n;
1658                                 }
1659                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET ( column_parameter = value [, ... ] ) */
1660                         | ALTER opt_column ColId SET reloptions
1661                                 {
1662                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1663                                         n->subtype = AT_SetOptions;
1664                                         n->name = $3;
1665                                         n->def = (Node *) $5;
1666                                         $$ = (Node *)n;
1667                                 }
1668                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET ( column_parameter = value [, ... ] ) */
1669                         | ALTER opt_column ColId RESET reloptions
1670                                 {
1671                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1672                                         n->subtype = AT_ResetOptions;
1673                                         n->name = $3;
1674                                         n->def = (Node *) $5;
1675                                         $$ = (Node *)n;
1676                                 }
1677                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET STORAGE <storagemode> */
1678                         | ALTER opt_column ColId SET STORAGE ColId
1679                                 {
1680                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1681                                         n->subtype = AT_SetStorage;
1682                                         n->name = $3;
1683                                         n->def = (Node *) makeString($6);
1684                                         $$ = (Node *)n;
1685                                 }
1686                         /* ALTER TABLE <name> DROP [COLUMN] IF EXISTS <colname> [RESTRICT|CASCADE] */
1687                         | DROP opt_column IF_P EXISTS ColId opt_drop_behavior
1688                                 {
1689                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1690                                         n->subtype = AT_DropColumn;
1691                                         n->name = $5;
1692                                         n->behavior = $6;
1693                                         n->missing_ok = TRUE;
1694                                         $$ = (Node *)n;
1695                                 }
1696                         /* ALTER TABLE <name> DROP [COLUMN] <colname> [RESTRICT|CASCADE] */
1697                         | DROP opt_column ColId opt_drop_behavior
1698                                 {
1699                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1700                                         n->subtype = AT_DropColumn;
1701                                         n->name = $3;
1702                                         n->behavior = $4;
1703                                         n->missing_ok = FALSE;
1704                                         $$ = (Node *)n;
1705                                 }
1706                         /*
1707                          * ALTER TABLE <name> ALTER [COLUMN] <colname> [SET DATA] TYPE <typename>
1708                          *              [ USING <expression> ]
1709                          */
1710                         | ALTER opt_column ColId opt_set_data TYPE_P Typename alter_using
1711                                 {
1712                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1713                                         n->subtype = AT_AlterColumnType;
1714                                         n->name = $3;
1715                                         n->def = (Node *) $6;
1716                                         n->transform = $7;
1717                                         $$ = (Node *)n;
1718                                 }
1719                         /* ALTER TABLE <name> ADD CONSTRAINT ... */
1720                         | ADD_P TableConstraint
1721                                 {
1722                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1723                                         n->subtype = AT_AddConstraint;
1724                                         n->def = $2;
1725                                         $$ = (Node *)n;
1726                                 }
1727                         /* ALTER TABLE <name> DROP CONSTRAINT IF EXISTS <name> [RESTRICT|CASCADE] */
1728                         | DROP CONSTRAINT IF_P EXISTS name opt_drop_behavior
1729                                 {
1730                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1731                                         n->subtype = AT_DropConstraint;
1732                                         n->name = $5;
1733                                         n->behavior = $6;
1734                                         n->missing_ok = TRUE;
1735                                         $$ = (Node *)n;
1736                                 }
1737                         /* ALTER TABLE <name> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
1738                         | DROP CONSTRAINT name opt_drop_behavior
1739                                 {
1740                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1741                                         n->subtype = AT_DropConstraint;
1742                                         n->name = $3;
1743                                         n->behavior = $4;
1744                                         n->missing_ok = FALSE;
1745                                         $$ = (Node *)n;
1746                                 }
1747                         /* ALTER TABLE <name> SET WITH OIDS  */
1748                         | SET WITH OIDS
1749                                 {
1750                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1751                                         n->subtype = AT_AddOids;
1752                                         $$ = (Node *)n;
1753                                 }
1754                         /* ALTER TABLE <name> SET WITHOUT OIDS  */
1755                         | SET WITHOUT OIDS
1756                                 {
1757                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1758                                         n->subtype = AT_DropOids;
1759                                         $$ = (Node *)n;
1760                                 }
1761                         /* ALTER TABLE <name> CLUSTER ON <indexname> */
1762                         | CLUSTER ON name
1763                                 {
1764                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1765                                         n->subtype = AT_ClusterOn;
1766                                         n->name = $3;
1767                                         $$ = (Node *)n;
1768                                 }
1769                         /* ALTER TABLE <name> SET WITHOUT CLUSTER */
1770                         | SET WITHOUT CLUSTER
1771                                 {
1772                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1773                                         n->subtype = AT_DropCluster;
1774                                         n->name = NULL;
1775                                         $$ = (Node *)n;
1776                                 }
1777                         /* ALTER TABLE <name> ENABLE TRIGGER <trig> */
1778                         | ENABLE_P TRIGGER name
1779                                 {
1780                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1781                                         n->subtype = AT_EnableTrig;
1782                                         n->name = $3;
1783                                         $$ = (Node *)n;
1784                                 }
1785                         /* ALTER TABLE <name> ENABLE ALWAYS TRIGGER <trig> */
1786                         | ENABLE_P ALWAYS TRIGGER name
1787                                 {
1788                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1789                                         n->subtype = AT_EnableAlwaysTrig;
1790                                         n->name = $4;
1791                                         $$ = (Node *)n;
1792                                 }
1793                         /* ALTER TABLE <name> ENABLE REPLICA TRIGGER <trig> */
1794                         | ENABLE_P REPLICA TRIGGER name
1795                                 {
1796                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1797                                         n->subtype = AT_EnableReplicaTrig;
1798                                         n->name = $4;
1799                                         $$ = (Node *)n;
1800                                 }
1801                         /* ALTER TABLE <name> ENABLE TRIGGER ALL */
1802                         | ENABLE_P TRIGGER ALL
1803                                 {
1804                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1805                                         n->subtype = AT_EnableTrigAll;
1806                                         $$ = (Node *)n;
1807                                 }
1808                         /* ALTER TABLE <name> ENABLE TRIGGER USER */
1809                         | ENABLE_P TRIGGER USER
1810                                 {
1811                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1812                                         n->subtype = AT_EnableTrigUser;
1813                                         $$ = (Node *)n;
1814                                 }
1815                         /* ALTER TABLE <name> DISABLE TRIGGER <trig> */
1816                         | DISABLE_P TRIGGER name
1817                                 {
1818                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1819                                         n->subtype = AT_DisableTrig;
1820                                         n->name = $3;
1821                                         $$ = (Node *)n;
1822                                 }
1823                         /* ALTER TABLE <name> DISABLE TRIGGER ALL */
1824                         | DISABLE_P TRIGGER ALL
1825                                 {
1826                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1827                                         n->subtype = AT_DisableTrigAll;
1828                                         $$ = (Node *)n;
1829                                 }
1830                         /* ALTER TABLE <name> DISABLE TRIGGER USER */
1831                         | DISABLE_P TRIGGER USER
1832                                 {
1833                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1834                                         n->subtype = AT_DisableTrigUser;
1835                                         $$ = (Node *)n;
1836                                 }
1837                         /* ALTER TABLE <name> ENABLE RULE <rule> */
1838                         | ENABLE_P RULE name
1839                                 {
1840                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1841                                         n->subtype = AT_EnableRule;
1842                                         n->name = $3;
1843                                         $$ = (Node *)n;
1844                                 }
1845                         /* ALTER TABLE <name> ENABLE ALWAYS RULE <rule> */
1846                         | ENABLE_P ALWAYS RULE name
1847                                 {
1848                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1849                                         n->subtype = AT_EnableAlwaysRule;
1850                                         n->name = $4;
1851                                         $$ = (Node *)n;
1852                                 }
1853                         /* ALTER TABLE <name> ENABLE REPLICA RULE <rule> */
1854                         | ENABLE_P REPLICA RULE name
1855                                 {
1856                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1857                                         n->subtype = AT_EnableReplicaRule;
1858                                         n->name = $4;
1859                                         $$ = (Node *)n;
1860                                 }
1861                         /* ALTER TABLE <name> DISABLE RULE <rule> */
1862                         | DISABLE_P RULE name
1863                                 {
1864                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1865                                         n->subtype = AT_DisableRule;
1866                                         n->name = $3;
1867                                         $$ = (Node *)n;
1868                                 }
1869                         /* ALTER TABLE <name> INHERIT <parent> */
1870                         | INHERIT qualified_name
1871                                 {
1872                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1873                                         n->subtype = AT_AddInherit;
1874                                         n->def = (Node *) $2;
1875                                         $$ = (Node *)n;
1876                                 }
1877                         /* ALTER TABLE <name> NO INHERIT <parent> */
1878                         | NO INHERIT qualified_name
1879                                 {
1880                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1881                                         n->subtype = AT_DropInherit;
1882                                         n->def = (Node *) $3;
1883                                         $$ = (Node *)n;
1884                                 }
1885                         /* ALTER TABLE <name> OWNER TO RoleId */
1886                         | OWNER TO RoleId
1887                                 {
1888                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1889                                         n->subtype = AT_ChangeOwner;
1890                                         n->name = $3;
1891                                         $$ = (Node *)n;
1892                                 }
1893                         /* ALTER TABLE <name> SET TABLESPACE <tablespacename> */
1894                         | SET TABLESPACE name
1895                                 {
1896                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1897                                         n->subtype = AT_SetTableSpace;
1898                                         n->name = $3;
1899                                         $$ = (Node *)n;
1900                                 }
1901                         /* ALTER TABLE <name> SET (...) */
1902                         | SET reloptions
1903                                 {
1904                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1905                                         n->subtype = AT_SetRelOptions;
1906                                         n->def = (Node *)$2;
1907                                         $$ = (Node *)n;
1908                                 }
1909                         /* ALTER TABLE <name> RESET (...) */
1910                         | RESET reloptions
1911                                 {
1912                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1913                                         n->subtype = AT_ResetRelOptions;
1914                                         n->def = (Node *)$2;
1915                                         $$ = (Node *)n;
1916                                 }
1917                 ;
1918
1919 alter_column_default:
1920                         SET DEFAULT a_expr                      { $$ = $3; }
1921                         | DROP DEFAULT                          { $$ = NULL; }
1922                 ;
1923
1924 opt_drop_behavior:
1925                         CASCADE                                         { $$ = DROP_CASCADE; }
1926                         | RESTRICT                                      { $$ = DROP_RESTRICT; }
1927                         | /* EMPTY */                           { $$ = DROP_RESTRICT; /* default */ }
1928                 ;
1929
1930 alter_using:
1931                         USING a_expr                            { $$ = $2; }
1932                         | /* EMPTY */                           { $$ = NULL; }
1933                 ;
1934
1935 reloptions:
1936                         '(' reloption_list ')'                                  { $$ = $2; }
1937                 ;
1938
1939 opt_reloptions:         WITH reloptions                                 { $$ = $2; }
1940                          |              /* EMPTY */                                             { $$ = NIL; }
1941                 ;
1942
1943 reloption_list:
1944                         reloption_elem                                                  { $$ = list_make1($1); }
1945                         | reloption_list ',' reloption_elem             { $$ = lappend($1, $3); }
1946                 ;
1947
1948 /* This should match def_elem and also allow qualified names */
1949 reloption_elem:
1950                         ColLabel '=' def_arg
1951                                 {
1952                                         $$ = makeDefElem($1, (Node *) $3);
1953                                 }
1954                         | ColLabel
1955                                 {
1956                                         $$ = makeDefElem($1, NULL);
1957                                 }
1958                         | ColLabel '.' ColLabel '=' def_arg
1959                                 {
1960                                         $$ = makeDefElemExtended($1, $3, (Node *) $5,
1961                                                                                          DEFELEM_UNSPEC);
1962                                 }
1963                         | ColLabel '.' ColLabel
1964                                 {
1965                                         $$ = makeDefElemExtended($1, $3, NULL, DEFELEM_UNSPEC);
1966                                 }
1967                 ;
1968
1969
1970 /*****************************************************************************
1971  *
1972  *              QUERY :
1973  *                              close <portalname>
1974  *
1975  *****************************************************************************/
1976
1977 ClosePortalStmt:
1978                         CLOSE cursor_name
1979                                 {
1980                                         ClosePortalStmt *n = makeNode(ClosePortalStmt);
1981                                         n->portalname = $2;
1982                                         $$ = (Node *)n;
1983                                 }
1984                         | CLOSE ALL
1985                                 {
1986                                         ClosePortalStmt *n = makeNode(ClosePortalStmt);
1987                                         n->portalname = NULL;
1988                                         $$ = (Node *)n;
1989                                 }
1990                 ;
1991
1992
1993 /*****************************************************************************
1994  *
1995  *              QUERY :
1996  *                              COPY relname [(columnList)] FROM/TO file [WITH] [(options)]
1997  *                              COPY ( SELECT ... ) TO file [WITH] [(options)]
1998  *
1999  *                              In the preferred syntax the options are comma-separated
2000  *                              and use generic identifiers instead of keywords.  The pre-9.0
2001  *                              syntax had a hard-wired, space-separated set of options.
2002  *
2003  *                              Really old syntax, from versions 7.2 and prior:
2004  *                              COPY [ BINARY ] table [ WITH OIDS ] FROM/TO file
2005  *                                      [ [ USING ] DELIMITERS 'delimiter' ] ]
2006  *                                      [ WITH NULL AS 'null string' ]
2007  *                              This option placement is not supported with COPY (SELECT...).
2008  *
2009  *****************************************************************************/
2010
2011 CopyStmt:       COPY opt_binary qualified_name opt_column_list opt_oids
2012                         copy_from copy_file_name copy_delimiter opt_with copy_options
2013                                 {
2014                                         CopyStmt *n = makeNode(CopyStmt);
2015                                         n->relation = $3;
2016                                         n->query = NULL;
2017                                         n->attlist = $4;
2018                                         n->is_from = $6;
2019                                         n->filename = $7;
2020
2021                                         n->options = NIL;
2022                                         /* Concatenate user-supplied flags */
2023                                         if ($2)
2024                                                 n->options = lappend(n->options, $2);
2025                                         if ($5)
2026                                                 n->options = lappend(n->options, $5);
2027                                         if ($8)
2028                                                 n->options = lappend(n->options, $8);
2029                                         if ($10)
2030                                                 n->options = list_concat(n->options, $10);
2031                                         $$ = (Node *)n;
2032                                 }
2033                         | COPY select_with_parens TO copy_file_name opt_with copy_options
2034                                 {
2035                                         CopyStmt *n = makeNode(CopyStmt);
2036                                         n->relation = NULL;
2037                                         n->query = $2;
2038                                         n->attlist = NIL;
2039                                         n->is_from = false;
2040                                         n->filename = $4;
2041                                         n->options = $6;
2042                                         $$ = (Node *)n;
2043                                 }
2044                 ;
2045
2046 copy_from:
2047                         FROM                                                                    { $$ = TRUE; }
2048                         | TO                                                                    { $$ = FALSE; }
2049                 ;
2050
2051 /*
2052  * copy_file_name NULL indicates stdio is used. Whether stdin or stdout is
2053  * used depends on the direction. (It really doesn't make sense to copy from
2054  * stdout. We silently correct the "typo".)              - AY 9/94
2055  */
2056 copy_file_name:
2057                         Sconst                                                                  { $$ = $1; }
2058                         | STDIN                                                                 { $$ = NULL; }
2059                         | STDOUT                                                                { $$ = NULL; }
2060                 ;
2061
2062 copy_options: copy_opt_list                                                     { $$ = $1; }
2063                         | '(' copy_generic_opt_list ')'                 { $$ = $2; }
2064                 ;
2065
2066 /* old COPY option syntax */
2067 copy_opt_list:
2068                         copy_opt_list copy_opt_item                             { $$ = lappend($1, $2); }
2069                         | /* EMPTY */                                                   { $$ = NIL; }
2070                 ;
2071
2072 copy_opt_item:
2073                         BINARY
2074                                 {
2075                                         $$ = makeDefElem("format", (Node *)makeString("binary"));
2076                                 }
2077                         | OIDS
2078                                 {
2079                                         $$ = makeDefElem("oids", (Node *)makeInteger(TRUE));
2080                                 }
2081                         | DELIMITER opt_as Sconst
2082                                 {
2083                                         $$ = makeDefElem("delimiter", (Node *)makeString($3));
2084                                 }
2085                         | NULL_P opt_as Sconst
2086                                 {
2087                                         $$ = makeDefElem("null", (Node *)makeString($3));
2088                                 }
2089                         | CSV
2090                                 {
2091                                         $$ = makeDefElem("format", (Node *)makeString("csv"));
2092                                 }
2093                         | HEADER_P
2094                                 {
2095                                         $$ = makeDefElem("header", (Node *)makeInteger(TRUE));
2096                                 }
2097                         | QUOTE opt_as Sconst
2098                                 {
2099                                         $$ = makeDefElem("quote", (Node *)makeString($3));
2100                                 }
2101                         | ESCAPE opt_as Sconst
2102                                 {
2103                                         $$ = makeDefElem("escape", (Node *)makeString($3));
2104                                 }
2105                         | FORCE QUOTE columnList
2106                                 {
2107                                         $$ = makeDefElem("force_quote", (Node *)$3);
2108                                 }
2109                         | FORCE QUOTE '*'
2110                                 {
2111                                         $$ = makeDefElem("force_quote", (Node *)makeNode(A_Star));
2112                                 }
2113                         | FORCE NOT NULL_P columnList
2114                                 {
2115                                         $$ = makeDefElem("force_not_null", (Node *)$4);
2116                                 }
2117                 ;
2118
2119 /* The following exist for backward compatibility with very old versions */
2120
2121 opt_binary:
2122                         BINARY
2123                                 {
2124                                         $$ = makeDefElem("format", (Node *)makeString("binary"));
2125                                 }
2126                         | /*EMPTY*/                                                             { $$ = NULL; }
2127                 ;
2128
2129 opt_oids:
2130                         WITH OIDS
2131                                 {
2132                                         $$ = makeDefElem("oids", (Node *)makeInteger(TRUE));
2133                                 }
2134                         | /*EMPTY*/                                                             { $$ = NULL; }
2135                 ;
2136
2137 copy_delimiter:
2138                         opt_using DELIMITERS Sconst
2139                                 {
2140                                         $$ = makeDefElem("delimiter", (Node *)makeString($3));
2141                                 }
2142                         | /*EMPTY*/                                                             { $$ = NULL; }
2143                 ;
2144
2145 opt_using:
2146                         USING                                                                   {}
2147                         | /*EMPTY*/                                                             {}
2148                 ;
2149
2150 /* new COPY option syntax */
2151 copy_generic_opt_list:
2152                         copy_generic_opt_elem
2153                                 {
2154                                         $$ = list_make1($1);
2155                                 }
2156                         | copy_generic_opt_list ',' copy_generic_opt_elem
2157                                 {
2158                                         $$ = lappend($1, $3);
2159                                 }
2160                 ;
2161
2162 copy_generic_opt_elem:
2163                         ColLabel copy_generic_opt_arg
2164                                 {
2165                                         $$ = makeDefElem($1, $2);
2166                                 }
2167                 ;
2168
2169 copy_generic_opt_arg:
2170                         opt_boolean                                             { $$ = (Node *) makeString($1); }
2171                         | ColId_or_Sconst                               { $$ = (Node *) makeString($1); }
2172                         | NumericOnly                                   { $$ = (Node *) $1; }
2173                         | '*'                                                   { $$ = (Node *) makeNode(A_Star); }
2174                         | '(' copy_generic_opt_arg_list ')'             { $$ = (Node *) $2; }
2175                         | /* EMPTY */                                   { $$ = NULL; }
2176                 ;
2177
2178 copy_generic_opt_arg_list:
2179                           copy_generic_opt_arg_list_item
2180                                 {
2181                                         $$ = list_make1($1);
2182                                 }
2183                         | copy_generic_opt_arg_list ',' copy_generic_opt_arg_list_item
2184                                 {
2185                                         $$ = lappend($1, $3);
2186                                 }
2187                 ;
2188
2189 /* beware of emitting non-string list elements here; see commands/define.c */
2190 copy_generic_opt_arg_list_item:
2191                         opt_boolean                             { $$ = (Node *) makeString($1); }
2192                         | ColId_or_Sconst               { $$ = (Node *) makeString($1); }
2193                 ;
2194
2195
2196 /*****************************************************************************
2197  *
2198  *              QUERY :
2199  *                              CREATE TABLE relname
2200  *
2201  *****************************************************************************/
2202
2203 CreateStmt:     CREATE OptTemp TABLE qualified_name '(' OptTableElementList ')'
2204                         OptInherit OptWith OnCommitOption OptTableSpace
2205                                 {
2206                                         CreateStmt *n = makeNode(CreateStmt);
2207                                         $4->istemp = $2;
2208                                         n->relation = $4;
2209                                         n->tableElts = $6;
2210                                         n->inhRelations = $8;
2211                                         n->constraints = NIL;
2212                                         n->options = $9;
2213                                         n->oncommit = $10;
2214                                         n->tablespacename = $11;
2215                                         $$ = (Node *)n;
2216                                 }
2217                 | CREATE OptTemp TABLE qualified_name OF any_name
2218                         OptTypedTableElementList OptWith OnCommitOption OptTableSpace
2219                                 {
2220                                         CreateStmt *n = makeNode(CreateStmt);
2221                                         $4->istemp = $2;
2222                                         n->relation = $4;
2223                                         n->tableElts = $7;
2224                                         n->ofTypename = makeTypeNameFromNameList($6);
2225                                         n->ofTypename->location = @6;
2226                                         n->constraints = NIL;
2227                                         n->options = $8;
2228                                         n->oncommit = $9;
2229                                         n->tablespacename = $10;
2230                                         $$ = (Node *)n;
2231                                 }
2232                 ;
2233
2234 /*
2235  * Redundancy here is needed to avoid shift/reduce conflicts,
2236  * since TEMP is not a reserved word.  See also OptTempTableName.
2237  *
2238  * NOTE: we accept both GLOBAL and LOCAL options; since we have no modules
2239  * the LOCAL keyword is really meaningless.
2240  */
2241 OptTemp:        TEMPORARY                                               { $$ = TRUE; }
2242                         | TEMP                                                  { $$ = TRUE; }
2243                         | LOCAL TEMPORARY                               { $$ = TRUE; }
2244                         | LOCAL TEMP                                    { $$ = TRUE; }
2245                         | GLOBAL TEMPORARY                              { $$ = TRUE; }
2246                         | GLOBAL TEMP                                   { $$ = TRUE; }
2247                         | /*EMPTY*/                                             { $$ = FALSE; }
2248                 ;
2249
2250 OptTableElementList:
2251                         TableElementList                                        { $$ = $1; }
2252                         | /*EMPTY*/                                                     { $$ = NIL; }
2253                 ;
2254
2255 OptTypedTableElementList:
2256                         '(' TypedTableElementList ')'           { $$ = $2; }
2257                         | /*EMPTY*/                                                     { $$ = NIL; }
2258                 ;
2259
2260 TableElementList:
2261                         TableElement
2262                                 {
2263                                         $$ = list_make1($1);
2264                                 }
2265                         | TableElementList ',' TableElement
2266                                 {
2267                                         $$ = lappend($1, $3);
2268                                 }
2269                 ;
2270
2271 TypedTableElementList:
2272                         TypedTableElement
2273                                 {
2274                                         $$ = list_make1($1);
2275                                 }
2276                         | TypedTableElementList ',' TypedTableElement
2277                                 {
2278                                         $$ = lappend($1, $3);
2279                                 }
2280                 ;
2281
2282 TableElement:
2283                         columnDef                                                       { $$ = $1; }
2284                         | TableLikeClause                                       { $$ = $1; }
2285                         | TableConstraint                                       { $$ = $1; }
2286                 ;
2287
2288 TypedTableElement:
2289                         columnOptions                                           { $$ = $1; }
2290                         | TableConstraint                                       { $$ = $1; }
2291                 ;
2292
2293 columnDef:      ColId Typename ColQualList
2294                                 {
2295                                         ColumnDef *n = makeNode(ColumnDef);
2296                                         n->colname = $1;
2297                                         n->typeName = $2;
2298                                         n->constraints = $3;
2299                                         n->is_local = true;
2300                                         $$ = (Node *)n;
2301                                 }
2302                 ;
2303
2304 columnOptions:  ColId WITH OPTIONS ColQualList
2305                                 {
2306                                         ColumnDef *n = makeNode(ColumnDef);
2307                                         n->colname = $1;
2308                                         n->constraints = $4;
2309                                         n->is_local = true;
2310                                         $$ = (Node *)n;
2311                                 }
2312                 ;
2313
2314 ColQualList:
2315                         ColQualList ColConstraint                               { $$ = lappend($1, $2); }
2316                         | /*EMPTY*/                                                             { $$ = NIL; }
2317                 ;
2318
2319 ColConstraint:
2320                         CONSTRAINT name ColConstraintElem
2321                                 {
2322                                         Constraint *n = (Constraint *) $3;
2323                                         Assert(IsA(n, Constraint));
2324                                         n->conname = $2;
2325                                         n->location = @1;
2326                                         $$ = (Node *) n;
2327                                 }
2328                         | ColConstraintElem                                             { $$ = $1; }
2329                         | ConstraintAttr                                                { $$ = $1; }
2330                 ;
2331
2332 /* DEFAULT NULL is already the default for Postgres.
2333  * But define it here and carry it forward into the system
2334  * to make it explicit.
2335  * - thomas 1998-09-13
2336  *
2337  * WITH NULL and NULL are not SQL92-standard syntax elements,
2338  * so leave them out. Use DEFAULT NULL to explicitly indicate
2339  * that a column may have that value. WITH NULL leads to
2340  * shift/reduce conflicts with WITH TIME ZONE anyway.
2341  * - thomas 1999-01-08
2342  *
2343  * DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
2344  * conflict on NOT (since NOT might start a subsequent NOT NULL constraint,
2345  * or be part of a_expr NOT LIKE or similar constructs).
2346  */
2347 ColConstraintElem:
2348                         NOT NULL_P
2349                                 {
2350                                         Constraint *n = makeNode(Constraint);
2351                                         n->contype = CONSTR_NOTNULL;
2352                                         n->location = @1;
2353                                         $$ = (Node *)n;
2354                                 }
2355                         | NULL_P
2356                                 {
2357                                         Constraint *n = makeNode(Constraint);
2358                                         n->contype = CONSTR_NULL;
2359                                         n->location = @1;
2360                                         $$ = (Node *)n;
2361                                 }
2362                         | UNIQUE opt_definition OptConsTableSpace
2363                                 {
2364                                         Constraint *n = makeNode(Constraint);
2365                                         n->contype = CONSTR_UNIQUE;
2366                                         n->location = @1;
2367                                         n->keys = NULL;
2368                                         n->options = $2;
2369                                         n->indexspace = $3;
2370                                         $$ = (Node *)n;
2371                                 }
2372                         | PRIMARY KEY opt_definition OptConsTableSpace
2373                                 {
2374                                         Constraint *n = makeNode(Constraint);
2375                                         n->contype = CONSTR_PRIMARY;
2376                                         n->location = @1;
2377                                         n->keys = NULL;
2378                                         n->options = $3;
2379                                         n->indexspace = $4;
2380                                         $$ = (Node *)n;
2381                                 }
2382                         | CHECK '(' a_expr ')'
2383                                 {
2384                                         Constraint *n = makeNode(Constraint);
2385                                         n->contype = CONSTR_CHECK;
2386                                         n->location = @1;
2387                                         n->raw_expr = $3;
2388                                         n->cooked_expr = NULL;
2389                                         $$ = (Node *)n;
2390                                 }
2391                         | DEFAULT b_expr
2392                                 {
2393                                         Constraint *n = makeNode(Constraint);
2394                                         n->contype = CONSTR_DEFAULT;
2395                                         n->location = @1;
2396                                         n->raw_expr = $2;
2397                                         n->cooked_expr = NULL;
2398                                         $$ = (Node *)n;
2399                                 }
2400                         | REFERENCES qualified_name opt_column_list key_match key_actions
2401                                 {
2402                                         Constraint *n = makeNode(Constraint);
2403                                         n->contype = CONSTR_FOREIGN;
2404                                         n->location = @1;
2405                                         n->pktable                      = $2;
2406                                         n->fk_attrs                     = NIL;
2407                                         n->pk_attrs                     = $3;
2408                                         n->fk_matchtype         = $4;
2409                                         n->fk_upd_action        = (char) ($5 >> 8);
2410                                         n->fk_del_action        = (char) ($5 & 0xFF);
2411                                         n->skip_validation  = FALSE;
2412                                         $$ = (Node *)n;
2413                                 }
2414                 ;
2415
2416 /*
2417  * ConstraintAttr represents constraint attributes, which we parse as if
2418  * they were independent constraint clauses, in order to avoid shift/reduce
2419  * conflicts (since NOT might start either an independent NOT NULL clause
2420  * or an attribute).  parse_utilcmd.c is responsible for attaching the
2421  * attribute information to the preceding "real" constraint node, and for
2422  * complaining if attribute clauses appear in the wrong place or wrong
2423  * combinations.
2424  *
2425  * See also ConstraintAttributeSpec, which can be used in places where
2426  * there is no parsing conflict.
2427  */
2428 ConstraintAttr:
2429                         DEFERRABLE
2430                                 {
2431                                         Constraint *n = makeNode(Constraint);
2432                                         n->contype = CONSTR_ATTR_DEFERRABLE;
2433                                         n->location = @1;
2434                                         $$ = (Node *)n;
2435                                 }
2436                         | NOT DEFERRABLE
2437                                 {
2438                                         Constraint *n = makeNode(Constraint);
2439                                         n->contype = CONSTR_ATTR_NOT_DEFERRABLE;
2440                                         n->location = @1;
2441                                         $$ = (Node *)n;
2442                                 }
2443                         | INITIALLY DEFERRED
2444                                 {
2445                                         Constraint *n = makeNode(Constraint);
2446                                         n->contype = CONSTR_ATTR_DEFERRED;
2447                                         n->location = @1;
2448                                         $$ = (Node *)n;
2449                                 }
2450                         | INITIALLY IMMEDIATE
2451                                 {
2452                                         Constraint *n = makeNode(Constraint);
2453                                         n->contype = CONSTR_ATTR_IMMEDIATE;
2454                                         n->location = @1;
2455                                         $$ = (Node *)n;
2456                                 }
2457                 ;
2458
2459
2460 /*
2461  * SQL99 supports wholesale borrowing of a table definition via the LIKE clause.
2462  * This seems to be a poor man's inheritance capability, with the resulting
2463  * tables completely decoupled except for the original commonality in definitions.
2464  *
2465  * This is very similar to CREATE TABLE AS except for the INCLUDING DEFAULTS extension
2466  * which is a part of SQL:2003.
2467  */
2468 TableLikeClause:
2469                         LIKE qualified_name TableLikeOptionList
2470                                 {
2471                                         InhRelation *n = makeNode(InhRelation);
2472                                         n->relation = $2;
2473                                         n->options = $3;
2474                                         $$ = (Node *)n;
2475                                 }
2476                 ;
2477
2478 TableLikeOptionList:
2479                                 TableLikeOptionList INCLUDING TableLikeOption   { $$ = $1 | $3; }
2480                                 | TableLikeOptionList EXCLUDING TableLikeOption { $$ = $1 & ~$3; }
2481                                 | /* EMPTY */                                           { $$ = 0; }
2482                 ;
2483
2484 TableLikeOption:
2485                                 DEFAULTS                        { $$ = CREATE_TABLE_LIKE_DEFAULTS; }
2486                                 | CONSTRAINTS           { $$ = CREATE_TABLE_LIKE_CONSTRAINTS; }
2487                                 | INDEXES                       { $$ = CREATE_TABLE_LIKE_INDEXES; }
2488                                 | STORAGE                       { $$ = CREATE_TABLE_LIKE_STORAGE; }
2489                                 | COMMENTS                      { $$ = CREATE_TABLE_LIKE_COMMENTS; }
2490                                 | ALL                           { $$ = CREATE_TABLE_LIKE_ALL; }
2491                 ;
2492
2493
2494 /* ConstraintElem specifies constraint syntax which is not embedded into
2495  *      a column definition. ColConstraintElem specifies the embedded form.
2496  * - thomas 1997-12-03
2497  */
2498 TableConstraint:
2499                         CONSTRAINT name ConstraintElem
2500                                 {
2501                                         Constraint *n = (Constraint *) $3;
2502                                         Assert(IsA(n, Constraint));
2503                                         n->conname = $2;
2504                                         n->location = @1;
2505                                         $$ = (Node *) n;
2506                                 }
2507                         | ConstraintElem                                                { $$ = $1; }
2508                 ;
2509
2510 ConstraintElem:
2511                         CHECK '(' a_expr ')' ConstraintAttributeSpec
2512                                 {
2513                                         Constraint *n = makeNode(Constraint);
2514                                         n->contype = CONSTR_CHECK;
2515                                         n->location = @1;
2516                                         n->raw_expr = $3;
2517                                         n->cooked_expr = NULL;
2518                                         if ($5 != 0)
2519                                                 ereport(ERROR,
2520                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2521                                                                  errmsg("CHECK constraints cannot be deferred"),
2522                                                                  parser_errposition(@5)));
2523                                         $$ = (Node *)n;
2524                                 }
2525                         | UNIQUE '(' columnList ')' opt_definition OptConsTableSpace
2526                                 ConstraintAttributeSpec
2527                                 {
2528                                         Constraint *n = makeNode(Constraint);
2529                                         n->contype = CONSTR_UNIQUE;
2530                                         n->location = @1;
2531                                         n->keys = $3;
2532                                         n->options = $5;
2533                                         n->indexspace = $6;
2534                                         n->deferrable = ($7 & 1) != 0;
2535                                         n->initdeferred = ($7 & 2) != 0;
2536                                         $$ = (Node *)n;
2537                                 }
2538                         | PRIMARY KEY '(' columnList ')' opt_definition OptConsTableSpace
2539                                 ConstraintAttributeSpec
2540                                 {
2541                                         Constraint *n = makeNode(Constraint);
2542                                         n->contype = CONSTR_PRIMARY;
2543                                         n->location = @1;
2544                                         n->keys = $4;
2545                                         n->options = $6;
2546                                         n->indexspace = $7;
2547                                         n->deferrable = ($8 & 1) != 0;
2548                                         n->initdeferred = ($8 & 2) != 0;
2549                                         $$ = (Node *)n;
2550                                 }
2551                         | EXCLUDE access_method_clause '(' ExclusionConstraintList ')'
2552                                 opt_definition OptConsTableSpace ExclusionWhereClause
2553                                 ConstraintAttributeSpec
2554                                 {
2555                                         Constraint *n = makeNode(Constraint);
2556                                         n->contype = CONSTR_EXCLUSION;
2557                                         n->location = @1;
2558                                         n->access_method        = $2;
2559                                         n->exclusions           = $4;
2560                                         n->options                      = $6;
2561                                         n->indexspace           = $7;
2562                                         n->where_clause         = $8;
2563                                         n->deferrable           = ($9 & 1) != 0;
2564                                         n->initdeferred         = ($9 & 2) != 0;
2565                                         $$ = (Node *)n;
2566                                 }
2567                         | FOREIGN KEY '(' columnList ')' REFERENCES qualified_name
2568                                 opt_column_list key_match key_actions ConstraintAttributeSpec
2569                                 {
2570                                         Constraint *n = makeNode(Constraint);
2571                                         n->contype = CONSTR_FOREIGN;
2572                                         n->location = @1;
2573                                         n->pktable                      = $7;
2574                                         n->fk_attrs                     = $4;
2575                                         n->pk_attrs                     = $8;
2576                                         n->fk_matchtype         = $9;
2577                                         n->fk_upd_action        = (char) ($10 >> 8);
2578                                         n->fk_del_action        = (char) ($10 & 0xFF);
2579                                         n->skip_validation  = FALSE;
2580                                         n->deferrable           = ($11 & 1) != 0;
2581                                         n->initdeferred         = ($11 & 2) != 0;
2582                                         $$ = (Node *)n;
2583                                 }
2584                 ;
2585
2586 opt_column_list:
2587                         '(' columnList ')'                                              { $$ = $2; }
2588                         | /*EMPTY*/                                                             { $$ = NIL; }
2589                 ;
2590
2591 columnList:
2592                         columnElem                                                              { $$ = list_make1($1); }
2593                         | columnList ',' columnElem                             { $$ = lappend($1, $3); }
2594                 ;
2595
2596 columnElem: ColId
2597                                 {
2598                                         $$ = (Node *) makeString($1);
2599                                 }
2600                 ;
2601
2602 key_match:  MATCH FULL
2603                         {
2604                                 $$ = FKCONSTR_MATCH_FULL;
2605                         }
2606                 | MATCH PARTIAL
2607                         {
2608                                 ereport(ERROR,
2609                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2610                                                  errmsg("MATCH PARTIAL not yet implemented"),
2611                                                  parser_errposition(@1)));
2612                                 $$ = FKCONSTR_MATCH_PARTIAL;
2613                         }
2614                 | MATCH SIMPLE
2615                         {
2616                                 $$ = FKCONSTR_MATCH_UNSPECIFIED;
2617                         }
2618                 | /*EMPTY*/
2619                         {
2620                                 $$ = FKCONSTR_MATCH_UNSPECIFIED;
2621                         }
2622                 ;
2623
2624 ExclusionConstraintList:
2625                         ExclusionConstraintElem                                 { $$ = list_make1($1); }
2626                         | ExclusionConstraintList ',' ExclusionConstraintElem
2627                                                                                                         { $$ = lappend($1, $3); }
2628                 ;
2629
2630 ExclusionConstraintElem: index_elem WITH any_operator
2631                         {
2632                                 $$ = list_make2($1, $3);
2633                         }
2634                         /* allow OPERATOR() decoration for the benefit of ruleutils.c */
2635                         | index_elem WITH OPERATOR '(' any_operator ')'
2636                         {
2637                                 $$ = list_make2($1, $5);
2638                         }
2639                 ;
2640
2641 ExclusionWhereClause:
2642                         WHERE '(' a_expr ')'                                    { $$ = $3; }
2643                         | /*EMPTY*/                                                             { $$ = NULL; }
2644                 ;
2645
2646 /*
2647  * We combine the update and delete actions into one value temporarily
2648  * for simplicity of parsing, and then break them down again in the
2649  * calling production.  update is in the left 8 bits, delete in the right.
2650  * Note that NOACTION is the default.
2651  */
2652 key_actions:
2653                         key_update
2654                                 { $$ = ($1 << 8) | (FKCONSTR_ACTION_NOACTION & 0xFF); }
2655                         | key_delete
2656                                 { $$ = (FKCONSTR_ACTION_NOACTION << 8) | ($1 & 0xFF); }
2657                         | key_update key_delete
2658                                 { $$ = ($1 << 8) | ($2 & 0xFF); }
2659                         | key_delete key_update
2660                                 { $$ = ($2 << 8) | ($1 & 0xFF); }
2661                         | /*EMPTY*/
2662                                 { $$ = (FKCONSTR_ACTION_NOACTION << 8) | (FKCONSTR_ACTION_NOACTION & 0xFF); }
2663                 ;
2664
2665 key_update: ON UPDATE key_action                { $$ = $3; }
2666                 ;
2667
2668 key_delete: ON DELETE_P key_action              { $$ = $3; }
2669                 ;
2670
2671 key_action:
2672                         NO ACTION                                       { $$ = FKCONSTR_ACTION_NOACTION; }
2673                         | RESTRICT                                      { $$ = FKCONSTR_ACTION_RESTRICT; }
2674                         | CASCADE                                       { $$ = FKCONSTR_ACTION_CASCADE; }
2675                         | SET NULL_P                            { $$ = FKCONSTR_ACTION_SETNULL; }
2676                         | SET DEFAULT                           { $$ = FKCONSTR_ACTION_SETDEFAULT; }
2677                 ;
2678
2679 OptInherit: INHERITS '(' qualified_name_list ')'        { $$ = $3; }
2680                         | /*EMPTY*/                                                             { $$ = NIL; }
2681                 ;
2682
2683 /* WITH (options) is preferred, WITH OIDS and WITHOUT OIDS are legacy forms */
2684 OptWith:
2685                         WITH reloptions                         { $$ = $2; }
2686                         | WITH OIDS                                     { $$ = list_make1(defWithOids(true)); }
2687                         | WITHOUT OIDS                          { $$ = list_make1(defWithOids(false)); }
2688                         | /*EMPTY*/                                     { $$ = NIL; }
2689                 ;
2690
2691 OnCommitOption:  ON COMMIT DROP                         { $$ = ONCOMMIT_DROP; }
2692                         | ON COMMIT DELETE_P ROWS               { $$ = ONCOMMIT_DELETE_ROWS; }
2693                         | ON COMMIT PRESERVE ROWS               { $$ = ONCOMMIT_PRESERVE_ROWS; }
2694                         | /*EMPTY*/                                             { $$ = ONCOMMIT_NOOP; }
2695                 ;
2696
2697 OptTableSpace:   TABLESPACE name                                        { $$ = $2; }
2698                         | /*EMPTY*/                                                             { $$ = NULL; }
2699                 ;
2700
2701 OptConsTableSpace:   USING INDEX TABLESPACE name        { $$ = $4; }
2702                         | /*EMPTY*/                                                             { $$ = NULL; }
2703                 ;
2704
2705
2706 /*
2707  * Note: CREATE TABLE ... AS SELECT ... is just another spelling for
2708  * SELECT ... INTO.
2709  */
2710
2711 CreateAsStmt:
2712                 CREATE OptTemp TABLE create_as_target AS SelectStmt opt_with_data
2713                                 {
2714                                         /*
2715                                          * When the SelectStmt is a set-operation tree, we must
2716                                          * stuff the INTO information into the leftmost component
2717                                          * Select, because that's where analyze.c will expect
2718                                          * to find it.  Similarly, the output column names must
2719                                          * be attached to that Select's target list.
2720                                          */
2721                                         SelectStmt *n = findLeftmostSelect((SelectStmt *) $6);
2722                                         if (n->intoClause != NULL)
2723                                                 ereport(ERROR,
2724                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2725                                                                  errmsg("CREATE TABLE AS cannot specify INTO"),
2726                                                                  parser_errposition(exprLocation((Node *) n->intoClause))));
2727                                         $4->rel->istemp = $2;
2728                                         n->intoClause = $4;
2729                                         /* Implement WITH NO DATA by forcing top-level LIMIT 0 */
2730                                         if (!$7)
2731                                                 ((SelectStmt *) $6)->limitCount = makeIntConst(0, -1);
2732                                         $$ = $6;
2733                                 }
2734                 ;
2735
2736 create_as_target:
2737                         qualified_name OptCreateAs OptWith OnCommitOption OptTableSpace
2738                                 {
2739                                         $$ = makeNode(IntoClause);
2740                                         $$->rel = $1;
2741                                         $$->colNames = $2;
2742                                         $$->options = $3;
2743                                         $$->onCommit = $4;
2744                                         $$->tableSpaceName = $5;
2745                                 }
2746                 ;
2747
2748 OptCreateAs:
2749                         '(' CreateAsList ')'                                    { $$ = $2; }
2750                         | /*EMPTY*/                                                             { $$ = NIL; }
2751                 ;
2752
2753 CreateAsList:
2754                         CreateAsElement                                                 { $$ = list_make1($1); }
2755                         | CreateAsList ',' CreateAsElement              { $$ = lappend($1, $3); }
2756                 ;
2757
2758 CreateAsElement:
2759                         ColId
2760                                 {
2761                                         ColumnDef *n = makeNode(ColumnDef);
2762                                         n->colname = $1;
2763                                         n->typeName = NULL;
2764                                         n->inhcount = 0;
2765                                         n->is_local = true;
2766                                         n->is_not_null = false;
2767                                         n->raw_default = NULL;
2768                                         n->cooked_default = NULL;
2769                                         n->constraints = NIL;
2770                                         $$ = (Node *)n;
2771                                 }
2772                 ;
2773
2774 opt_with_data:
2775                         WITH DATA_P                                                             { $$ = TRUE; }
2776                         | WITH NO DATA_P                                                { $$ = FALSE; }
2777                         | /*EMPTY*/                                                             { $$ = TRUE; }
2778                 ;
2779
2780
2781 /*****************************************************************************
2782  *
2783  *              QUERY :
2784  *                              CREATE SEQUENCE seqname
2785  *                              ALTER SEQUENCE seqname
2786  *
2787  *****************************************************************************/
2788
2789 CreateSeqStmt:
2790                         CREATE OptTemp SEQUENCE qualified_name OptSeqOptList
2791                                 {
2792                                         CreateSeqStmt *n = makeNode(CreateSeqStmt);
2793                                         $4->istemp = $2;
2794                                         n->sequence = $4;
2795                                         n->options = $5;
2796                                         $$ = (Node *)n;
2797                                 }
2798                 ;
2799
2800 AlterSeqStmt:
2801                         ALTER SEQUENCE qualified_name SeqOptList
2802                                 {
2803                                         AlterSeqStmt *n = makeNode(AlterSeqStmt);
2804                                         n->sequence = $3;
2805                                         n->options = $4;
2806                                         $$ = (Node *)n;
2807                                 }
2808                 ;
2809
2810 OptSeqOptList: SeqOptList                                                       { $$ = $1; }
2811                         | /*EMPTY*/                                                             { $$ = NIL; }
2812                 ;
2813
2814 SeqOptList: SeqOptElem                                                          { $$ = list_make1($1); }
2815                         | SeqOptList SeqOptElem                                 { $$ = lappend($1, $2); }
2816                 ;
2817
2818 SeqOptElem: CACHE NumericOnly
2819                                 {
2820                                         $$ = makeDefElem("cache", (Node *)$2);
2821                                 }
2822                         | CYCLE
2823                                 {
2824                                         $$ = makeDefElem("cycle", (Node *)makeInteger(TRUE));
2825                                 }
2826                         | NO CYCLE
2827                                 {
2828                                         $$ = makeDefElem("cycle", (Node *)makeInteger(FALSE));
2829                                 }
2830                         | INCREMENT opt_by NumericOnly
2831                                 {
2832                                         $$ = makeDefElem("increment", (Node *)$3);
2833                                 }
2834                         | MAXVALUE NumericOnly
2835                                 {
2836                                         $$ = makeDefElem("maxvalue", (Node *)$2);
2837                                 }
2838                         | MINVALUE NumericOnly
2839                                 {
2840                                         $$ = makeDefElem("minvalue", (Node *)$2);
2841                                 }
2842                         | NO MAXVALUE
2843                                 {
2844                                         $$ = makeDefElem("maxvalue", NULL);
2845                                 }
2846                         | NO MINVALUE
2847                                 {
2848                                         $$ = makeDefElem("minvalue", NULL);
2849                                 }
2850                         | OWNED BY any_name
2851                                 {
2852                                         $$ = makeDefElem("owned_by", (Node *)$3);
2853                                 }
2854                         | START opt_with NumericOnly
2855                                 {
2856                                         $$ = makeDefElem("start", (Node *)$3);
2857                                 }
2858                         | RESTART
2859                                 {
2860                                         $$ = makeDefElem("restart", NULL);
2861                                 }
2862                         | RESTART opt_with NumericOnly
2863                                 {
2864                                         $$ = makeDefElem("restart", (Node *)$3);
2865                                 }
2866                 ;
2867
2868 opt_by:         BY                              {}
2869                         | /* empty */   {}
2870           ;
2871
2872 NumericOnly:
2873                         FCONST                                                          { $$ = makeFloat($1); }
2874                         | '-' FCONST
2875                                 {
2876                                         $$ = makeFloat($2);
2877                                         doNegateFloat($$);
2878                                 }
2879                         | SignedIconst                                          { $$ = makeInteger($1); }
2880                 ;
2881
2882 /*****************************************************************************
2883  *
2884  *              QUERIES :
2885  *                              CREATE [OR REPLACE] [TRUSTED] [PROCEDURAL] LANGUAGE ...
2886  *                              DROP [PROCEDURAL] LANGUAGE ...
2887  *
2888  *****************************************************************************/
2889
2890 CreatePLangStmt:
2891                         CREATE opt_or_replace opt_trusted opt_procedural LANGUAGE ColId_or_Sconst
2892                         {
2893                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
2894                                 n->replace = $2;
2895                                 n->plname = $6;
2896                                 /* parameters are all to be supplied by system */
2897                                 n->plhandler = NIL;
2898                                 n->plinline = NIL;
2899                                 n->plvalidator = NIL;
2900                                 n->pltrusted = false;
2901                                 $$ = (Node *)n;
2902                         }
2903                         | CREATE opt_or_replace opt_trusted opt_procedural LANGUAGE ColId_or_Sconst
2904                           HANDLER handler_name opt_inline_handler opt_validator
2905                         {
2906                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
2907                                 n->replace = $2;
2908                                 n->plname = $6;
2909                                 n->plhandler = $8;
2910                                 n->plinline = $9;
2911                                 n->plvalidator = $10;
2912                                 n->pltrusted = $3;
2913                                 $$ = (Node *)n;
2914                         }
2915                 ;
2916
2917 opt_trusted:
2918                         TRUSTED                                                                 { $$ = TRUE; }
2919                         | /*EMPTY*/                                                             { $$ = FALSE; }
2920                 ;
2921
2922 /* This ought to be just func_name, but that causes reduce/reduce conflicts
2923  * (CREATE LANGUAGE is the only place where func_name isn't followed by '(').
2924  * Work around by using simple names, instead.
2925  */
2926 handler_name:
2927                         name                                            { $$ = list_make1(makeString($1)); }
2928                         | name attrs                            { $$ = lcons(makeString($1), $2); }
2929                 ;
2930
2931 opt_inline_handler:
2932                         INLINE_P handler_name                                   { $$ = $2; }
2933                         | /*EMPTY*/                                                             { $$ = NIL; }
2934                 ;
2935
2936 validator_clause:
2937                         VALIDATOR handler_name                                  { $$ = $2; }
2938                         | NO VALIDATOR                                                  { $$ = NIL; }
2939                 ;
2940
2941 opt_validator:
2942                         validator_clause                                                { $$ = $1; }
2943                         | /*EMPTY*/                                                             { $$ = NIL; }
2944                 ;
2945
2946 DropPLangStmt:
2947                         DROP opt_procedural LANGUAGE ColId_or_Sconst opt_drop_behavior
2948                                 {
2949                                         DropPLangStmt *n = makeNode(DropPLangStmt);
2950                                         n->plname = $4;
2951                                         n->behavior = $5;
2952                                         n->missing_ok = false;
2953                                         $$ = (Node *)n;
2954                                 }
2955                         | DROP opt_procedural LANGUAGE IF_P EXISTS ColId_or_Sconst opt_drop_behavior
2956                                 {
2957                                         DropPLangStmt *n = makeNode(DropPLangStmt);
2958                                         n->plname = $6;
2959                                         n->behavior = $7;
2960                                         n->missing_ok = true;
2961                                         $$ = (Node *)n;
2962                                 }
2963                 ;
2964
2965 opt_procedural:
2966                         PROCEDURAL                                                              {}
2967                         | /*EMPTY*/                                                             {}
2968                 ;
2969
2970 /*****************************************************************************
2971  *
2972  *              QUERY:
2973  *             CREATE TABLESPACE tablespace LOCATION '/path/to/tablespace/'
2974  *
2975  *****************************************************************************/
2976
2977 CreateTableSpaceStmt: CREATE TABLESPACE name OptTableSpaceOwner LOCATION Sconst
2978                                 {
2979                                         CreateTableSpaceStmt *n = makeNode(CreateTableSpaceStmt);
2980                                         n->tablespacename = $3;
2981                                         n->owner = $4;
2982                                         n->location = $6;
2983                                         $$ = (Node *) n;
2984                                 }
2985                 ;
2986
2987 OptTableSpaceOwner: OWNER name                  { $$ = $2; }
2988                         | /*EMPTY */                            { $$ = NULL; }
2989                 ;
2990
2991 /*****************************************************************************
2992  *
2993  *              QUERY :
2994  *                              DROP TABLESPACE <tablespace>
2995  *
2996  *              No need for drop behaviour as we cannot implement dependencies for
2997  *              objects in other databases; we can only support RESTRICT.
2998  *
2999  ****************************************************************************/
3000
3001 DropTableSpaceStmt: DROP TABLESPACE name
3002                                 {
3003                                         DropTableSpaceStmt *n = makeNode(DropTableSpaceStmt);
3004                                         n->tablespacename = $3;
3005                                         n->missing_ok = false;
3006                                         $$ = (Node *) n;
3007                                 }
3008                                 |  DROP TABLESPACE IF_P EXISTS name
3009                 {
3010                                         DropTableSpaceStmt *n = makeNode(DropTableSpaceStmt);
3011                                         n->tablespacename = $5;
3012                                         n->missing_ok = true;
3013                                         $$ = (Node *) n;
3014                                 }
3015                 ;
3016
3017 /*****************************************************************************
3018  *
3019  *              QUERY:
3020  *             CREATE FOREIGN DATA WRAPPER name [ VALIDATOR name ]
3021  *
3022  *****************************************************************************/
3023
3024 CreateFdwStmt: CREATE FOREIGN DATA_P WRAPPER name opt_validator create_generic_options
3025                                 {
3026                                         CreateFdwStmt *n = makeNode(CreateFdwStmt);
3027                                         n->fdwname = $5;
3028                                         n->validator = $6;
3029                                         n->options = $7;
3030                                         $$ = (Node *) n;
3031                                 }
3032                 ;
3033
3034 /*****************************************************************************
3035  *
3036  *              QUERY :
3037  *                              DROP FOREIGN DATA WRAPPER name
3038  *
3039  ****************************************************************************/
3040
3041 DropFdwStmt: DROP FOREIGN DATA_P WRAPPER name opt_drop_behavior
3042                                 {
3043                                         DropFdwStmt *n = makeNode(DropFdwStmt);
3044                                         n->fdwname = $5;
3045                                         n->missing_ok = false;
3046                                         n->behavior = $6;
3047                                         $$ = (Node *) n;
3048                                 }
3049                                 |  DROP FOREIGN DATA_P WRAPPER IF_P EXISTS name opt_drop_behavior
3050                 {
3051                                         DropFdwStmt *n = makeNode(DropFdwStmt);
3052                                         n->fdwname = $7;
3053                                         n->missing_ok = true;
3054                                         n->behavior = $8;
3055                                         $$ = (Node *) n;
3056                                 }
3057                 ;
3058
3059 /*****************************************************************************
3060  *
3061  *              QUERY :
3062  *                              ALTER FOREIGN DATA WRAPPER name
3063  *
3064  ****************************************************************************/
3065
3066 AlterFdwStmt: ALTER FOREIGN DATA_P WRAPPER name validator_clause alter_generic_options
3067                                 {
3068                                         AlterFdwStmt *n = makeNode(AlterFdwStmt);
3069                                         n->fdwname = $5;
3070                                         n->validator = $6;
3071                                         n->change_validator = true;
3072                                         n->options = $7;
3073                                         $$ = (Node *) n;
3074                                 }
3075                         | ALTER FOREIGN DATA_P WRAPPER name validator_clause
3076                                 {
3077                                         AlterFdwStmt *n = makeNode(AlterFdwStmt);
3078                                         n->fdwname = $5;
3079                                         n->validator = $6;
3080                                         n->change_validator = true;
3081                                         $$ = (Node *) n;
3082                                 }
3083                         | ALTER FOREIGN DATA_P WRAPPER name alter_generic_options
3084                                 {
3085                                         AlterFdwStmt *n = makeNode(AlterFdwStmt);
3086                                         n->fdwname = $5;
3087                                         n->options = $6;
3088                                         $$ = (Node *) n;
3089                                 }
3090                 ;
3091
3092 /* Options definition for CREATE FDW, SERVER and USER MAPPING */
3093 create_generic_options:
3094                         OPTIONS '(' generic_option_list ')'                     { $$ = $3; }
3095                         | /*EMPTY*/                                                                     { $$ = NIL; }
3096                 ;
3097
3098 generic_option_list:
3099                         generic_option_elem
3100                                 {
3101                                         $$ = list_make1($1);
3102                                 }
3103                         | generic_option_list ',' generic_option_elem
3104                                 {
3105                                         $$ = lappend($1, $3);
3106                                 }
3107                 ;
3108
3109 /* Options definition for ALTER FDW, SERVER and USER MAPPING */
3110 alter_generic_options:
3111                         OPTIONS '(' alter_generic_option_list ')'               { $$ = $3; }
3112                 ;
3113
3114 alter_generic_option_list:
3115                         alter_generic_option_elem
3116                                 {
3117                                         $$ = list_make1($1);
3118                                 }
3119                         | alter_generic_option_list ',' alter_generic_option_elem
3120                                 {
3121                                         $$ = lappend($1, $3);
3122                                 }
3123                 ;
3124
3125 alter_generic_option_elem:
3126                         generic_option_elem
3127                                 {
3128                                         $$ = $1;
3129                                 }
3130                         | SET generic_option_elem
3131                                 {
3132                                         $$ = $2;
3133                                         $$->defaction = DEFELEM_SET;
3134                                 }
3135                         | ADD_P generic_option_elem
3136                                 {
3137                                         $$ = $2;
3138                                         $$->defaction = DEFELEM_ADD;
3139                                 }
3140                         | DROP generic_option_name
3141                                 {
3142                                         $$ = makeDefElemExtended(NULL, $2, NULL, DEFELEM_DROP);
3143                                 }
3144                 ;
3145
3146 generic_option_elem:
3147                         generic_option_name generic_option_arg
3148                                 {
3149                                         $$ = makeDefElem($1, $2);
3150                                 }
3151                 ;
3152
3153 generic_option_name:
3154                                 ColLabel                        { $$ = $1; }
3155                 ;
3156
3157 /* We could use def_arg here, but the spec only requires string literals */
3158 generic_option_arg:
3159                                 Sconst                          { $$ = (Node *) makeString($1); }
3160                 ;
3161
3162 /*****************************************************************************
3163  *
3164  *              QUERY:
3165  *             CREATE SERVER name [TYPE] [VERSION] [OPTIONS]
3166  *
3167  *****************************************************************************/
3168
3169 CreateForeignServerStmt: CREATE SERVER name opt_type opt_foreign_server_version
3170                                                  FOREIGN DATA_P WRAPPER name create_generic_options
3171                                 {
3172                                         CreateForeignServerStmt *n = makeNode(CreateForeignServerStmt);
3173                                         n->servername = $3;
3174                                         n->servertype = $4;
3175                                         n->version = $5;
3176                                         n->fdwname = $9;
3177                                         n->options = $10;
3178                                         $$ = (Node *) n;
3179                                 }
3180                 ;
3181
3182 opt_type:
3183                         TYPE_P Sconst                   { $$ = $2; }
3184                         | /*EMPTY*/                             { $$ = NULL; }
3185                 ;
3186
3187
3188 foreign_server_version:
3189                         VERSION_P Sconst                { $$ = $2; }
3190                 |       VERSION_P NULL_P                { $$ = NULL; }
3191                 ;
3192
3193 opt_foreign_server_version:
3194                         foreign_server_version  { $$ = $1; }
3195                         | /*EMPTY*/                             { $$ = NULL; }
3196                 ;
3197
3198 /*****************************************************************************
3199  *
3200  *              QUERY :
3201  *                              DROP SERVER name
3202  *
3203  ****************************************************************************/
3204
3205 DropForeignServerStmt: DROP SERVER name opt_drop_behavior
3206                                 {
3207                                         DropForeignServerStmt *n = makeNode(DropForeignServerStmt);
3208                                         n->servername = $3;
3209                                         n->missing_ok = false;
3210                                         n->behavior = $4;
3211                                         $$ = (Node *) n;
3212                                 }
3213                                 |  DROP SERVER IF_P EXISTS name opt_drop_behavior
3214                 {
3215                                         DropForeignServerStmt *n = makeNode(DropForeignServerStmt);
3216                                         n->servername = $5;
3217                                         n->missing_ok = true;
3218                                         n->behavior = $6;
3219                                         $$ = (Node *) n;
3220                                 }
3221                 ;
3222
3223 /*****************************************************************************
3224  *
3225  *              QUERY :
3226  *                              ALTER SERVER name [VERSION] [OPTIONS]
3227  *
3228  ****************************************************************************/
3229
3230 AlterForeignServerStmt: ALTER SERVER name foreign_server_version alter_generic_options
3231                                 {
3232                                         AlterForeignServerStmt *n = makeNode(AlterForeignServerStmt);
3233                                         n->servername = $3;
3234                                         n->version = $4;
3235                                         n->options = $5;
3236                                         n->has_version = true;
3237                                         $$ = (Node *) n;
3238                                 }
3239                         | ALTER SERVER name foreign_server_version
3240                                 {
3241                                         AlterForeignServerStmt *n = makeNode(AlterForeignServerStmt);
3242                                         n->servername = $3;
3243                                         n->version = $4;
3244                                         n->has_version = true;
3245                                         $$ = (Node *) n;
3246                                 }
3247                         | ALTER SERVER name alter_generic_options
3248                                 {
3249                                         AlterForeignServerStmt *n = makeNode(AlterForeignServerStmt);
3250                                         n->servername = $3;
3251                                         n->options = $4;
3252                                         $$ = (Node *) n;
3253                                 }
3254                 ;
3255
3256 /*****************************************************************************
3257  *
3258  *              QUERY:
3259  *             CREATE USER MAPPING FOR auth_ident SERVER name [OPTIONS]
3260  *
3261  *****************************************************************************/
3262
3263 CreateUserMappingStmt: CREATE USER MAPPING FOR auth_ident SERVER name create_generic_options
3264                                 {
3265                                         CreateUserMappingStmt *n = makeNode(CreateUserMappingStmt);
3266                                         n->username = $5;
3267                                         n->servername = $7;
3268                                         n->options = $8;
3269                                         $$ = (Node *) n;
3270                                 }
3271                 ;
3272
3273 /* User mapping authorization identifier */
3274 auth_ident:
3275                         CURRENT_USER    { $$ = "current_user"; }
3276                 |       USER                    { $$ = "current_user"; }
3277                 |       RoleId                  { $$ = (strcmp($1, "public") == 0) ? NULL : $1; }
3278                 ;
3279
3280 /*****************************************************************************
3281  *
3282  *              QUERY :
3283  *                              DROP USER MAPPING FOR auth_ident SERVER name
3284  *
3285  ****************************************************************************/
3286
3287 DropUserMappingStmt: DROP USER MAPPING FOR auth_ident SERVER name
3288                                 {
3289                                         DropUserMappingStmt *n = makeNode(DropUserMappingStmt);
3290                                         n->username = $5;
3291                                         n->servername = $7;
3292                                         n->missing_ok = false;
3293                                         $$ = (Node *) n;
3294                                 }
3295                                 |  DROP USER MAPPING IF_P EXISTS FOR auth_ident SERVER name
3296                 {
3297                                         DropUserMappingStmt *n = makeNode(DropUserMappingStmt);
3298                                         n->username = $7;
3299                                         n->servername = $9;
3300                                         n->missing_ok = true;
3301                                         $$ = (Node *) n;
3302                                 }
3303                 ;
3304
3305 /*****************************************************************************
3306  *
3307  *              QUERY :
3308  *                              ALTER USER MAPPING FOR auth_ident SERVER name OPTIONS
3309  *
3310  ****************************************************************************/
3311
3312 AlterUserMappingStmt: ALTER USER MAPPING FOR auth_ident SERVER name alter_generic_options
3313                                 {
3314                                         AlterUserMappingStmt *n = makeNode(AlterUserMappingStmt);
3315                                         n->username = $5;
3316                                         n->servername = $7;
3317                                         n->options = $8;
3318                                         $$ = (Node *) n;
3319                                 }
3320                 ;
3321
3322 /*****************************************************************************
3323  *
3324  *              QUERIES :
3325  *                              CREATE TRIGGER ...
3326  *                              DROP TRIGGER ...
3327  *
3328  *****************************************************************************/
3329
3330 CreateTrigStmt:
3331                         CREATE TRIGGER name TriggerActionTime TriggerEvents ON
3332                         qualified_name TriggerForSpec TriggerWhen
3333                         EXECUTE PROCEDURE func_name '(' TriggerFuncArgs ')'
3334                                 {
3335                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
3336                                         n->trigname = $3;
3337                                         n->relation = $7;
3338                                         n->funcname = $12;
3339                                         n->args = $14;
3340                                         n->before = $4;
3341                                         n->row = $8;
3342                                         n->events = intVal(linitial($5));
3343                                         n->columns = (List *) lsecond($5);
3344                                         n->whenClause = $9;
3345                                         n->isconstraint  = FALSE;
3346                                         n->deferrable    = FALSE;
3347                                         n->initdeferred  = FALSE;
3348                                         n->constrrel = NULL;
3349                                         $$ = (Node *)n;
3350                                 }
3351                         | CREATE CONSTRAINT TRIGGER name AFTER TriggerEvents ON
3352                         qualified_name OptConstrFromTable ConstraintAttributeSpec
3353                         FOR EACH ROW TriggerWhen
3354                         EXECUTE PROCEDURE func_name '(' TriggerFuncArgs ')'
3355                                 {
3356                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
3357                                         n->trigname = $4;
3358                                         n->relation = $8;
3359                                         n->funcname = $17;
3360                                         n->args = $19;
3361                                         n->before = FALSE;
3362                                         n->row = TRUE;
3363                                         n->events = intVal(linitial($6));
3364                                         n->columns = (List *) lsecond($6);
3365                                         n->whenClause = $14;
3366                                         n->isconstraint  = TRUE;
3367                                         n->deferrable = ($10 & 1) != 0;
3368                                         n->initdeferred = ($10 & 2) != 0;
3369                                         n->constrrel = $9;
3370                                         $$ = (Node *)n;
3371                                 }
3372                 ;
3373
3374 TriggerActionTime:
3375                         BEFORE                                                                  { $$ = TRUE; }
3376                         | AFTER                                                                 { $$ = FALSE; }
3377                 ;
3378
3379 TriggerEvents:
3380                         TriggerOneEvent
3381                                 { $$ = $1; }
3382                         | TriggerEvents OR TriggerOneEvent
3383                                 {
3384                                         int             events1 = intVal(linitial($1));
3385                                         int             events2 = intVal(linitial($3));
3386                                         List   *columns1 = (List *) lsecond($1);
3387                                         List   *columns2 = (List *) lsecond($3);
3388
3389                                         if (events1 & events2)
3390                                                 parser_yyerror("duplicate trigger events specified");
3391                                         /*
3392                                          * concat'ing the columns lists loses information about
3393                                          * which columns went with which event, but so long as
3394                                          * only UPDATE carries columns and we disallow multiple
3395                                          * UPDATE items, it doesn't matter.  Command execution
3396                                          * should just ignore the columns for non-UPDATE events.
3397                                          */
3398                                         $$ = list_make2(makeInteger(events1 | events2),
3399                                                                         list_concat(columns1, columns2));
3400                                 }
3401                 ;
3402
3403 TriggerOneEvent:
3404                         INSERT
3405                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_INSERT), NIL); }
3406                         | DELETE_P
3407                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_DELETE), NIL); }
3408                         | UPDATE
3409                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_UPDATE), NIL); }
3410                         | UPDATE OF columnList
3411                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_UPDATE), $3); }
3412                         | TRUNCATE
3413                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_TRUNCATE), NIL); }
3414                 ;
3415
3416 TriggerForSpec:
3417                         FOR TriggerForOpt TriggerForType
3418                                 {
3419                                         $$ = $3;
3420                                 }
3421                         | /* EMPTY */
3422                                 {
3423                                         /*
3424                                          * If ROW/STATEMENT not specified, default to
3425                                          * STATEMENT, per SQL
3426                                          */
3427                                         $$ = FALSE;
3428                                 }
3429                 ;
3430
3431 TriggerForOpt:
3432                         EACH                                                                    {}
3433                         | /*EMPTY*/                                                             {}
3434                 ;
3435
3436 TriggerForType:
3437                         ROW                                                                             { $$ = TRUE; }
3438                         | STATEMENT                                                             { $$ = FALSE; }
3439                 ;
3440
3441 TriggerWhen:
3442                         WHEN '(' a_expr ')'                                             { $$ = $3; }
3443                         | /*EMPTY*/                                                             { $$ = NULL; }
3444                 ;
3445
3446 TriggerFuncArgs:
3447                         TriggerFuncArg                                                  { $$ = list_make1($1); }
3448                         | TriggerFuncArgs ',' TriggerFuncArg    { $$ = lappend($1, $3); }
3449                         | /*EMPTY*/                                                             { $$ = NIL; }
3450                 ;
3451
3452 TriggerFuncArg:
3453                         Iconst
3454                                 {
3455                                         char buf[64];
3456                                         snprintf(buf, sizeof(buf), "%d", $1);
3457                                         $$ = makeString(pstrdup(buf));
3458                                 }
3459                         | FCONST                                                                { $$ = makeString($1); }
3460                         | Sconst                                                                { $$ = makeString($1); }
3461                         | BCONST                                                                { $$ = makeString($1); }
3462                         | XCONST                                                                { $$ = makeString($1); }
3463                         | ColId                                                                 { $$ = makeString($1); }
3464                 ;
3465
3466 OptConstrFromTable:
3467                         FROM qualified_name                                             { $$ = $2; }
3468                         | /*EMPTY*/                                                             { $$ = NULL; }
3469                 ;
3470
3471 ConstraintAttributeSpec:
3472                         ConstraintDeferrabilitySpec
3473                                 { $$ = $1; }
3474                         | ConstraintDeferrabilitySpec ConstraintTimeSpec
3475                                 {
3476                                         if ($1 == 0 && $2 != 0)
3477                                                 ereport(ERROR,
3478                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3479                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3480                                                                  parser_errposition(@1)));
3481                                         $$ = $1 | $2;
3482                                 }
3483                         | ConstraintTimeSpec
3484                                 {
3485                                         if ($1 != 0)
3486                                                 $$ = 3;
3487                                         else
3488                                                 $$ = 0;
3489                                 }
3490                         | ConstraintTimeSpec ConstraintDeferrabilitySpec
3491                                 {
3492                                         if ($2 == 0 && $1 != 0)
3493                                                 ereport(ERROR,
3494                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3495                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
3496                                                                  parser_errposition(@1)));
3497                                         $$ = $1 | $2;
3498                                 }
3499                         | /*EMPTY*/
3500                                 { $$ = 0; }
3501                 ;
3502
3503 ConstraintDeferrabilitySpec:
3504                         NOT DEFERRABLE                                                  { $$ = 0; }
3505                         | DEFERRABLE                                                    { $$ = 1; }
3506                 ;
3507
3508 ConstraintTimeSpec:
3509                         INITIALLY IMMEDIATE                                             { $$ = 0; }
3510                         | INITIALLY DEFERRED                                    { $$ = 2; }
3511                 ;
3512
3513
3514 DropTrigStmt:
3515                         DROP TRIGGER name ON qualified_name opt_drop_behavior
3516                                 {
3517                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
3518                                         n->relation = $5;
3519                                         n->property = $3;
3520                                         n->behavior = $6;
3521                                         n->removeType = OBJECT_TRIGGER;
3522                                         n->missing_ok = false;
3523                                         $$ = (Node *) n;
3524                                 }
3525                         | DROP TRIGGER IF_P EXISTS name ON qualified_name opt_drop_behavior
3526                                 {
3527                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
3528                                         n->relation = $7;
3529                                         n->property = $5;
3530                                         n->behavior = $8;
3531                                         n->removeType = OBJECT_TRIGGER;
3532                                         n->missing_ok = true;
3533                                         $$ = (Node *) n;
3534                                 }
3535                 ;
3536
3537
3538 /*****************************************************************************
3539  *
3540  *              QUERIES :
3541  *                              CREATE ASSERTION ...
3542  *                              DROP ASSERTION ...
3543  *
3544  *****************************************************************************/
3545
3546 CreateAssertStmt:
3547                         CREATE ASSERTION name CHECK '(' a_expr ')'
3548                         ConstraintAttributeSpec
3549                                 {
3550                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
3551                                         n->trigname = $3;
3552                                         n->args = list_make1($6);
3553                                         n->isconstraint  = TRUE;
3554                                         n->deferrable = ($8 & 1) != 0;
3555                                         n->initdeferred = ($8 & 2) != 0;
3556
3557                                         ereport(ERROR,
3558                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3559                                                          errmsg("CREATE ASSERTION is not yet implemented")));
3560
3561                                         $$ = (Node *)n;
3562                                 }
3563                 ;
3564
3565 DropAssertStmt:
3566                         DROP ASSERTION name opt_drop_behavior
3567                                 {
3568                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
3569                                         n->relation = NULL;
3570                                         n->property = $3;
3571                                         n->behavior = $4;
3572                                         n->removeType = OBJECT_TRIGGER; /* XXX */
3573                                         ereport(ERROR,
3574                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3575                                                          errmsg("DROP ASSERTION is not yet implemented")));
3576                                         $$ = (Node *) n;
3577                                 }
3578                 ;
3579
3580
3581 /*****************************************************************************
3582  *
3583  *              QUERY :
3584  *                              define (aggregate,operator,type)
3585  *
3586  *****************************************************************************/
3587
3588 DefineStmt:
3589                         CREATE AGGREGATE func_name aggr_args definition
3590                                 {
3591                                         DefineStmt *n = makeNode(DefineStmt);
3592                                         n->kind = OBJECT_AGGREGATE;
3593                                         n->oldstyle = false;
3594                                         n->defnames = $3;
3595                                         n->args = $4;
3596                                         n->definition = $5;
3597                                         $$ = (Node *)n;
3598                                 }
3599                         | CREATE AGGREGATE func_name old_aggr_definition
3600                                 {
3601                                         /* old-style (pre-8.2) syntax for CREATE AGGREGATE */
3602                                         DefineStmt *n = makeNode(DefineStmt);
3603                                         n->kind = OBJECT_AGGREGATE;
3604                                         n->oldstyle = true;
3605                                         n->defnames = $3;
3606                                         n->args = NIL;
3607                                         n->definition = $4;
3608                                         $$ = (Node *)n;
3609                                 }
3610                         | CREATE OPERATOR any_operator definition
3611                                 {
3612                                         DefineStmt *n = makeNode(DefineStmt);
3613                                         n->kind = OBJECT_OPERATOR;
3614                                         n->oldstyle = false;
3615                                         n->defnames = $3;
3616                                         n->args = NIL;
3617                                         n->definition = $4;
3618                                         $$ = (Node *)n;
3619                                 }
3620                         | CREATE TYPE_P any_name definition
3621                                 {
3622                                         DefineStmt *n = makeNode(DefineStmt);
3623                                         n->kind = OBJECT_TYPE;
3624                                         n->oldstyle = false;
3625                                         n->defnames = $3;
3626                                         n->args = NIL;
3627                                         n->definition = $4;
3628                                         $$ = (Node *)n;
3629                                 }
3630                         | CREATE TYPE_P any_name
3631                                 {
3632                                         /* Shell type (identified by lack of definition) */
3633                                         DefineStmt *n = makeNode(DefineStmt);
3634                                         n->kind = OBJECT_TYPE;
3635                                         n->oldstyle = false;
3636                                         n->defnames = $3;
3637                                         n->args = NIL;
3638                                         n->definition = NIL;
3639                                         $$ = (Node *)n;
3640                                 }
3641                         | CREATE TYPE_P any_name AS '(' TableFuncElementList ')'
3642                                 {
3643                                         CompositeTypeStmt *n = makeNode(CompositeTypeStmt);
3644                                         RangeVar *r = makeNode(RangeVar);
3645
3646                                         /* can't use qualified_name, sigh */
3647                                         switch (list_length($3))
3648                                         {
3649                                                 case 1:
3650                                                         r->catalogname = NULL;
3651                                                         r->schemaname = NULL;
3652                                                         r->relname = strVal(linitial($3));
3653                                                         break;
3654                                                 case 2:
3655                                                         r->catalogname = NULL;
3656                                                         r->schemaname = strVal(linitial($3));
3657                                                         r->relname = strVal(lsecond($3));
3658                                                         break;
3659                                                 case 3:
3660                                                         r->catalogname = strVal(linitial($3));
3661                                                         r->schemaname = strVal(lsecond($3));
3662                                                         r->relname = strVal(lthird($3));
3663                                                         break;
3664                                                 default:
3665                                                         ereport(ERROR,
3666                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
3667                                                                          errmsg("improper qualified name (too many dotted names): %s",
3668                                                                                         NameListToString($3)),
3669                                                                                         parser_errposition(@3)));
3670                                                         break;
3671                                         }
3672                                         r->location = @3;
3673                                         n->typevar = r;
3674                                         n->coldeflist = $6;
3675                                         $$ = (Node *)n;
3676                                 }
3677                         | CREATE TYPE_P any_name AS ENUM_P '(' opt_enum_val_list ')'
3678                                 {
3679                                         CreateEnumStmt *n = makeNode(CreateEnumStmt);
3680                                         n->typeName = $3;
3681                                         n->vals = $7;
3682                                         $$ = (Node *)n;
3683                                 }
3684                         | CREATE TEXT_P SEARCH PARSER any_name definition
3685                                 {
3686                                         DefineStmt *n = makeNode(DefineStmt);
3687                                         n->kind = OBJECT_TSPARSER;
3688                                         n->args = NIL;
3689                                         n->defnames = $5;
3690                                         n->definition = $6;
3691                                         $$ = (Node *)n;
3692                                 }
3693                         | CREATE TEXT_P SEARCH DICTIONARY any_name definition
3694                                 {
3695                                         DefineStmt *n = makeNode(DefineStmt);
3696                                         n->kind = OBJECT_TSDICTIONARY;
3697                                         n->args = NIL;
3698                                         n->defnames = $5;
3699                                         n->definition = $6;
3700                                         $$ = (Node *)n;
3701                                 }
3702                         | CREATE TEXT_P SEARCH TEMPLATE any_name definition
3703                                 {
3704                                         DefineStmt *n = makeNode(DefineStmt);
3705                                         n->kind = OBJECT_TSTEMPLATE;
3706                                         n->args = NIL;
3707                                         n->defnames = $5;
3708                                         n->definition = $6;
3709                                         $$ = (Node *)n;
3710                                 }
3711                         | CREATE TEXT_P SEARCH CONFIGURATION any_name definition
3712                                 {
3713                                         DefineStmt *n = makeNode(DefineStmt);
3714                                         n->kind = OBJECT_TSCONFIGURATION;
3715                                         n->args = NIL;
3716                                         n->defnames = $5;
3717                                         n->definition = $6;
3718                                         $$ = (Node *)n;
3719                                 }
3720                 ;
3721
3722 definition: '(' def_list ')'                                            { $$ = $2; }
3723                 ;
3724
3725 def_list:       def_elem                                                                { $$ = list_make1($1); }
3726                         | def_list ',' def_elem                                 { $$ = lappend($1, $3); }
3727                 ;
3728
3729 def_elem:       ColLabel '=' def_arg
3730                                 {
3731                                         $$ = makeDefElem($1, (Node *) $3);
3732                                 }
3733                         | ColLabel
3734                                 {
3735                                         $$ = makeDefElem($1, NULL);
3736                                 }
3737                 ;
3738
3739 /* Note: any simple identifier will be returned as a type name! */
3740 def_arg:        func_type                                               { $$ = (Node *)$1; }
3741                         | reserved_keyword                              { $$ = (Node *)makeString(pstrdup($1)); }
3742                         | qual_all_Op                                   { $$ = (Node *)$1; }
3743                         | NumericOnly                                   { $$ = (Node *)$1; }
3744                         | Sconst                                                { $$ = (Node *)makeString($1); }
3745                 ;
3746
3747 aggr_args:      '(' type_list ')'                                               { $$ = $2; }
3748                         | '(' '*' ')'                                                   { $$ = NIL; }
3749                 ;
3750
3751 old_aggr_definition: '(' old_aggr_list ')'                      { $$ = $2; }
3752                 ;
3753
3754 old_aggr_list: old_aggr_elem                                            { $$ = list_make1($1); }
3755                         | old_aggr_list ',' old_aggr_elem               { $$ = lappend($1, $3); }
3756                 ;
3757
3758 /*
3759  * Must use IDENT here to avoid reduce/reduce conflicts; fortunately none of
3760  * the item names needed in old aggregate definitions are likely to become
3761  * SQL keywords.
3762  */
3763 old_aggr_elem:  IDENT '=' def_arg
3764                                 {
3765                                         $$ = makeDefElem($1, (Node *)$3);
3766                                 }
3767                 ;
3768
3769 opt_enum_val_list:
3770                 enum_val_list                                                   { $$ = $1; }
3771                 | /*EMPTY*/                                                             { $$ = NIL; }
3772                 ;
3773
3774 enum_val_list:  Sconst
3775                                 { $$ = list_make1(makeString($1)); }
3776                         | enum_val_list ',' Sconst
3777                                 { $$ = lappend($1, makeString($3)); }
3778                 ;
3779
3780
3781 /*****************************************************************************
3782  *
3783  *              QUERIES :
3784  *                              CREATE OPERATOR CLASS ...
3785  *                              CREATE OPERATOR FAMILY ...
3786  *                              ALTER OPERATOR FAMILY ...
3787  *                              DROP OPERATOR CLASS ...
3788  *                              DROP OPERATOR FAMILY ...
3789  *
3790  *****************************************************************************/
3791
3792 CreateOpClassStmt:
3793                         CREATE OPERATOR CLASS any_name opt_default FOR TYPE_P Typename
3794                         USING access_method opt_opfamily AS opclass_item_list
3795                                 {
3796                                         CreateOpClassStmt *n = makeNode(CreateOpClassStmt);
3797                                         n->opclassname = $4;
3798                                         n->isDefault = $5;
3799                                         n->datatype = $8;
3800                                         n->amname = $10;
3801                                         n->opfamilyname = $11;
3802                                         n->items = $13;
3803                                         $$ = (Node *) n;
3804                                 }
3805                 ;
3806
3807 opclass_item_list:
3808                         opclass_item                                                    { $$ = list_make1($1); }
3809                         | opclass_item_list ',' opclass_item    { $$ = lappend($1, $3); }
3810                 ;
3811
3812 opclass_item:
3813                         OPERATOR Iconst any_operator opt_recheck
3814                                 {
3815                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3816                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
3817                                         n->name = $3;
3818                                         n->args = NIL;
3819                                         n->number = $2;
3820                                         $$ = (Node *) n;
3821                                 }
3822                         | OPERATOR Iconst any_operator oper_argtypes opt_recheck
3823                                 {
3824                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3825                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
3826                                         n->name = $3;
3827                                         n->args = $4;
3828                                         n->number = $2;
3829                                         $$ = (Node *) n;
3830                                 }
3831                         | FUNCTION Iconst func_name func_args
3832                                 {
3833                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3834                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
3835                                         n->name = $3;
3836                                         n->args = extractArgTypes($4);
3837                                         n->number = $2;
3838                                         $$ = (Node *) n;
3839                                 }
3840                         | FUNCTION Iconst '(' type_list ')' func_name func_args
3841                                 {
3842                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3843                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
3844                                         n->name = $6;
3845                                         n->args = extractArgTypes($7);
3846                                         n->number = $2;
3847                                         n->class_args = $4;
3848                                         $$ = (Node *) n;
3849                                 }
3850                         | STORAGE Typename
3851                                 {
3852                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3853                                         n->itemtype = OPCLASS_ITEM_STORAGETYPE;
3854                                         n->storedtype = $2;
3855                                         $$ = (Node *) n;
3856                                 }
3857                 ;
3858
3859 opt_default:    DEFAULT                                         { $$ = TRUE; }
3860                         | /*EMPTY*/                                             { $$ = FALSE; }
3861                 ;
3862
3863 opt_opfamily:   FAMILY any_name                         { $$ = $2; }
3864                         | /*EMPTY*/                                             { $$ = NIL; }
3865                 ;
3866
3867 opt_recheck:    RECHECK
3868                                 {
3869                                         /*
3870                                          * RECHECK no longer does anything in opclass definitions,
3871                                          * but we still accept it to ease porting of old database
3872                                          * dumps.
3873                                          */
3874                                         ereport(NOTICE,
3875                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3876                                                          errmsg("RECHECK is no longer required"),
3877                                                          errhint("Update your data type."),
3878                                                          parser_errposition(@1)));
3879                                         $$ = TRUE;
3880                                 }
3881                         | /*EMPTY*/                                             { $$ = FALSE; }
3882                 ;
3883
3884
3885 CreateOpFamilyStmt:
3886                         CREATE OPERATOR FAMILY any_name USING access_method
3887                                 {
3888                                         CreateOpFamilyStmt *n = makeNode(CreateOpFamilyStmt);
3889                                         n->opfamilyname = $4;
3890                                         n->amname = $6;
3891                                         $$ = (Node *) n;
3892                                 }
3893                 ;
3894
3895 AlterOpFamilyStmt:
3896                         ALTER OPERATOR FAMILY any_name USING access_method ADD_P opclass_item_list
3897                                 {
3898                                         AlterOpFamilyStmt *n = makeNode(AlterOpFamilyStmt);
3899                                         n->opfamilyname = $4;
3900                                         n->amname = $6;
3901                                         n->isDrop = false;
3902                                         n->items = $8;
3903                                         $$ = (Node *) n;
3904                                 }
3905                         | ALTER OPERATOR FAMILY any_name USING access_method DROP opclass_drop_list
3906                                 {
3907                                         AlterOpFamilyStmt *n = makeNode(AlterOpFamilyStmt);
3908                                         n->opfamilyname = $4;
3909                                         n->amname = $6;
3910                                         n->isDrop = true;
3911                                         n->items = $8;
3912                                         $$ = (Node *) n;
3913                                 }
3914                 ;
3915
3916 opclass_drop_list:
3917                         opclass_drop                                                    { $$ = list_make1($1); }
3918                         | opclass_drop_list ',' opclass_drop    { $$ = lappend($1, $3); }
3919                 ;
3920
3921 opclass_drop:
3922                         OPERATOR Iconst '(' type_list ')'
3923                                 {
3924                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3925                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
3926                                         n->number = $2;
3927                                         n->args = $4;
3928                                         $$ = (Node *) n;
3929                                 }
3930                         | FUNCTION Iconst '(' type_list ')'
3931                                 {
3932                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3933                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
3934                                         n->number = $2;
3935                                         n->args = $4;
3936                                         $$ = (Node *) n;
3937                                 }
3938                 ;
3939
3940
3941 DropOpClassStmt:
3942                         DROP OPERATOR CLASS any_name USING access_method opt_drop_behavior
3943                                 {
3944                                         RemoveOpClassStmt *n = makeNode(RemoveOpClassStmt);
3945                                         n->opclassname = $4;
3946                                         n->amname = $6;
3947                                         n->behavior = $7;
3948                                         n->missing_ok = false;
3949                                         $$ = (Node *) n;
3950                                 }
3951                         | DROP OPERATOR CLASS IF_P EXISTS any_name USING access_method opt_drop_behavior
3952                                 {
3953                                         RemoveOpClassStmt *n = makeNode(RemoveOpClassStmt);
3954                                         n->opclassname = $6;
3955                                         n->amname = $8;
3956                                         n->behavior = $9;
3957                                         n->missing_ok = true;
3958                                         $$ = (Node *) n;
3959                                 }
3960                 ;
3961
3962 DropOpFamilyStmt:
3963                         DROP OPERATOR FAMILY any_name USING access_method opt_drop_behavior
3964                                 {
3965                                         RemoveOpFamilyStmt *n = makeNode(RemoveOpFamilyStmt);
3966                                         n->opfamilyname = $4;
3967                                         n->amname = $6;
3968                                         n->behavior = $7;
3969                                         n->missing_ok = false;
3970                                         $$ = (Node *) n;
3971                                 }
3972                         | DROP OPERATOR FAMILY IF_P EXISTS any_name USING access_method opt_drop_behavior
3973                                 {
3974                                         RemoveOpFamilyStmt *n = makeNode(RemoveOpFamilyStmt);
3975                                         n->opfamilyname = $6;
3976                                         n->amname = $8;
3977                                         n->behavior = $9;
3978                                         n->missing_ok = true;
3979                                         $$ = (Node *) n;
3980                                 }
3981                 ;
3982
3983
3984 /*****************************************************************************
3985  *
3986  *              QUERY:
3987  *
3988  *              DROP OWNED BY username [, username ...] [ RESTRICT | CASCADE ]
3989  *              REASSIGN OWNED BY username [, username ...] TO username
3990  *
3991  *****************************************************************************/
3992 DropOwnedStmt:
3993                         DROP OWNED BY name_list opt_drop_behavior
3994                                 {
3995                                         DropOwnedStmt *n = makeNode(DropOwnedStmt);
3996                                         n->roles = $4;
3997                                         n->behavior = $5;
3998                                         $$ = (Node *)n;
3999                                 }
4000                 ;
4001
4002 ReassignOwnedStmt:
4003                         REASSIGN OWNED BY name_list TO name
4004                                 {
4005                                         ReassignOwnedStmt *n = makeNode(ReassignOwnedStmt);
4006                                         n->roles = $4;
4007                                         n->newrole = $6;
4008                                         $$ = (Node *)n;
4009                                 }
4010                 ;
4011
4012 /*****************************************************************************
4013  *
4014  *              QUERY:
4015  *
4016  *              DROP itemtype [ IF EXISTS ] itemname [, itemname ...]
4017  *           [ RESTRICT | CASCADE ]
4018  *
4019  *****************************************************************************/
4020
4021 DropStmt:       DROP drop_type IF_P EXISTS any_name_list opt_drop_behavior
4022                                 {
4023                                         DropStmt *n = makeNode(DropStmt);
4024                                         n->removeType = $2;
4025                                         n->missing_ok = TRUE;
4026                                         n->objects = $5;
4027                                         n->behavior = $6;
4028                                         $$ = (Node *)n;
4029                                 }
4030                         | DROP drop_type any_name_list opt_drop_behavior
4031                                 {
4032                                         DropStmt *n = makeNode(DropStmt);
4033                                         n->removeType = $2;
4034                                         n->missing_ok = FALSE;
4035                                         n->objects = $3;
4036                                         n->behavior = $4;
4037                                         $$ = (Node *)n;
4038                                 }
4039                 ;
4040
4041
4042 drop_type:      TABLE                                                                   { $$ = OBJECT_TABLE; }
4043                         | SEQUENCE                                                              { $$ = OBJECT_SEQUENCE; }
4044                         | VIEW                                                                  { $$ = OBJECT_VIEW; }
4045                         | INDEX                                                                 { $$ = OBJECT_INDEX; }
4046                         | TYPE_P                                                                { $$ = OBJECT_TYPE; }
4047                         | DOMAIN_P                                                              { $$ = OBJECT_DOMAIN; }
4048                         | CONVERSION_P                                                  { $$ = OBJECT_CONVERSION; }
4049                         | SCHEMA                                                                { $$ = OBJECT_SCHEMA; }
4050                         | TEXT_P SEARCH PARSER                                  { $$ = OBJECT_TSPARSER; }
4051                         | TEXT_P SEARCH DICTIONARY                              { $$ = OBJECT_TSDICTIONARY; }
4052                         | TEXT_P SEARCH TEMPLATE                                { $$ = OBJECT_TSTEMPLATE; }
4053                         | TEXT_P SEARCH CONFIGURATION                   { $$ = OBJECT_TSCONFIGURATION; }
4054                 ;
4055
4056 any_name_list:
4057                         any_name                                                                { $$ = list_make1($1); }
4058                         | any_name_list ',' any_name                    { $$ = lappend($1, $3); }
4059                 ;
4060
4061 any_name:       ColId                                           { $$ = list_make1(makeString($1)); }
4062                         | ColId attrs                           { $$ = lcons(makeString($1), $2); }
4063                 ;
4064
4065 attrs:          '.' attr_name
4066                                         { $$ = list_make1(makeString($2)); }
4067                         | attrs '.' attr_name
4068                                         { $$ = lappend($1, makeString($3)); }
4069                 ;
4070
4071
4072 /*****************************************************************************
4073  *
4074  *              QUERY:
4075  *                              truncate table relname1, relname2, ...
4076  *
4077  *****************************************************************************/
4078
4079 TruncateStmt:
4080                         TRUNCATE opt_table relation_expr_list opt_restart_seqs opt_drop_behavior
4081                                 {
4082                                         TruncateStmt *n = makeNode(TruncateStmt);
4083                                         n->relations = $3;
4084                                         n->restart_seqs = $4;
4085                                         n->behavior = $5;
4086                                         $$ = (Node *)n;
4087                                 }
4088                 ;
4089
4090 opt_restart_seqs:
4091                         CONTINUE_P IDENTITY_P           { $$ = false; }
4092                         | RESTART IDENTITY_P            { $$ = true; }
4093                         | /* EMPTY */                           { $$ = false; }
4094                 ;
4095
4096 /*****************************************************************************
4097  *
4098  *      The COMMENT ON statement can take different forms based upon the type of
4099  *      the object associated with the comment. The form of the statement is:
4100  *
4101  *      COMMENT ON [ [ DATABASE | DOMAIN | INDEX | SEQUENCE | TABLE | TYPE | VIEW |
4102  *                                 CONVERSION | LANGUAGE | OPERATOR CLASS | LARGE OBJECT |
4103  *                                 CAST | COLUMN | SCHEMA | TABLESPACE | ROLE |
4104  *                                 TEXT SEARCH PARSER | TEXT SEARCH DICTIONARY |
4105  *                                 TEXT SEARCH TEMPLATE |
4106  *                                 TEXT SEARCH CONFIGURATION ] <objname> |
4107  *                               AGGREGATE <aggname> (arg1, ...) |
4108  *                               FUNCTION <funcname> (arg1, arg2, ...) |
4109  *                               OPERATOR <op> (leftoperand_typ, rightoperand_typ) |
4110  *                               TRIGGER <triggername> ON <relname> |
4111  *                               CONSTRAINT <constraintname> ON <relname> |
4112  *                               RULE <rulename> ON <relname> ]
4113  *                         IS 'text'
4114  *
4115  *****************************************************************************/
4116
4117 CommentStmt:
4118                         COMMENT ON comment_type any_name IS comment_text
4119                                 {
4120                                         CommentStmt *n = makeNode(CommentStmt);
4121                                         n->objtype = $3;
4122                                         n->objname = $4;
4123                                         n->objargs = NIL;
4124                                         n->comment = $6;
4125                                         $$ = (Node *) n;
4126                                 }
4127                         | COMMENT ON AGGREGATE func_name aggr_args IS comment_text
4128                                 {
4129                                         CommentStmt *n = makeNode(CommentStmt);
4130                                         n->objtype = OBJECT_AGGREGATE;
4131                                         n->objname = $4;
4132                                         n->objargs = $5;
4133                                         n->comment = $7;
4134                                         $$ = (Node *) n;
4135                                 }
4136                         | COMMENT ON FUNCTION func_name func_args IS comment_text
4137                                 {
4138                                         CommentStmt *n = makeNode(CommentStmt);
4139                                         n->objtype = OBJECT_FUNCTION;
4140                                         n->objname = $4;
4141                                         n->objargs = extractArgTypes($5);
4142                                         n->comment = $7;
4143                                         $$ = (Node *) n;
4144                                 }
4145                         | COMMENT ON OPERATOR any_operator oper_argtypes IS comment_text
4146                                 {
4147                                         CommentStmt *n = makeNode(CommentStmt);
4148                                         n->objtype = OBJECT_OPERATOR;
4149                                         n->objname = $4;
4150                                         n->objargs = $5;
4151                                         n->comment = $7;
4152                                         $$ = (Node *) n;
4153                                 }
4154                         | COMMENT ON CONSTRAINT name ON any_name IS comment_text
4155                                 {
4156                                         CommentStmt *n = makeNode(CommentStmt);
4157                                         n->objtype = OBJECT_CONSTRAINT;
4158                                         n->objname = lappend($6, makeString($4));
4159                                         n->objargs = NIL;
4160                                         n->comment = $8;
4161                                         $$ = (Node *) n;
4162                                 }
4163                         | COMMENT ON RULE name ON any_name IS comment_text
4164                                 {
4165                                         CommentStmt *n = makeNode(CommentStmt);
4166                                         n->objtype = OBJECT_RULE;
4167                                         n->objname = lappend($6, makeString($4));
4168                                         n->objargs = NIL;
4169                                         n->comment = $8;
4170                                         $$ = (Node *) n;
4171                                 }
4172                         | COMMENT ON RULE name IS comment_text
4173                                 {
4174                                         /* Obsolete syntax supported for awhile for compatibility */
4175                                         CommentStmt *n = makeNode(CommentStmt);
4176                                         n->objtype = OBJECT_RULE;
4177                                         n->objname = list_make1(makeString($4));
4178                                         n->objargs = NIL;
4179                                         n->comment = $6;
4180                                         $$ = (Node *) n;
4181                                 }
4182                         | COMMENT ON TRIGGER name ON any_name IS comment_text
4183                                 {
4184                                         CommentStmt *n = makeNode(CommentStmt);
4185                                         n->objtype = OBJECT_TRIGGER;
4186                                         n->objname = lappend($6, makeString($4));
4187                                         n->objargs = NIL;
4188                                         n->comment = $8;
4189                                         $$ = (Node *) n;
4190                                 }
4191                         | COMMENT ON OPERATOR CLASS any_name USING access_method IS comment_text
4192                                 {
4193                                         CommentStmt *n = makeNode(CommentStmt);
4194                                         n->objtype = OBJECT_OPCLASS;
4195                                         n->objname = $5;
4196                                         n->objargs = list_make1(makeString($7));
4197                                         n->comment = $9;
4198                                         $$ = (Node *) n;
4199                                 }
4200                         | COMMENT ON OPERATOR FAMILY any_name USING access_method IS comment_text
4201                                 {
4202                                         CommentStmt *n = makeNode(CommentStmt);
4203                                         n->objtype = OBJECT_OPFAMILY;
4204                                         n->objname = $5;
4205                                         n->objargs = list_make1(makeString($7));
4206                                         n->comment = $9;
4207                                         $$ = (Node *) n;
4208                                 }
4209                         | COMMENT ON LARGE_P OBJECT_P NumericOnly IS comment_text
4210                                 {
4211                                         CommentStmt *n = makeNode(CommentStmt);
4212                                         n->objtype = OBJECT_LARGEOBJECT;
4213                                         n->objname = list_make1($5);
4214                                         n->objargs = NIL;
4215                                         n->comment = $7;
4216                                         $$ = (Node *) n;
4217                                 }
4218                         | COMMENT ON CAST '(' Typename AS Typename ')' IS comment_text
4219                                 {
4220                                         CommentStmt *n = makeNode(CommentStmt);
4221                                         n->objtype = OBJECT_CAST;
4222                                         n->objname = list_make1($5);
4223                                         n->objargs = list_make1($7);
4224                                         n->comment = $10;
4225                                         $$ = (Node *) n;
4226                                 }
4227                         | COMMENT ON opt_procedural LANGUAGE any_name IS comment_text
4228                                 {
4229                                         CommentStmt *n = makeNode(CommentStmt);
4230                                         n->objtype = OBJECT_LANGUAGE;
4231                                         n->objname = $5;
4232                                         n->objargs = NIL;
4233                                         n->comment = $7;
4234                                         $$ = (Node *) n;
4235                                 }
4236                         | COMMENT ON TEXT_P SEARCH PARSER any_name IS comment_text
4237                                 {
4238                                         CommentStmt *n = makeNode(CommentStmt);
4239                                         n->objtype = OBJECT_TSPARSER;
4240                                         n->objname = $6;
4241                                         n->comment = $8;
4242                                         $$ = (Node *) n;
4243                                 }
4244                         | COMMENT ON TEXT_P SEARCH DICTIONARY any_name IS comment_text
4245                                 {
4246                                         CommentStmt *n = makeNode(CommentStmt);
4247                                         n->objtype = OBJECT_TSDICTIONARY;
4248                                         n->objname = $6;
4249                                         n->comment = $8;
4250                                         $$ = (Node *) n;
4251                                 }
4252                         | COMMENT ON TEXT_P SEARCH TEMPLATE any_name IS comment_text
4253                                 {
4254                                         CommentStmt *n = makeNode(CommentStmt);
4255                                         n->objtype = OBJECT_TSTEMPLATE;
4256                                         n->objname = $6;
4257                                         n->comment = $8;
4258                                         $$ = (Node *) n;
4259                                 }
4260                         | COMMENT ON TEXT_P SEARCH CONFIGURATION any_name IS comment_text
4261                                 {
4262                                         CommentStmt *n = makeNode(CommentStmt);
4263                                         n->objtype = OBJECT_TSCONFIGURATION;
4264                                         n->objname = $6;
4265                                         n->comment = $8;
4266                                         $$ = (Node *) n;
4267                                 }
4268                 ;
4269
4270 comment_type:
4271                         COLUMN                                                          { $$ = OBJECT_COLUMN; }
4272                         | DATABASE                                                      { $$ = OBJECT_DATABASE; }
4273                         | SCHEMA                                                        { $$ = OBJECT_SCHEMA; }
4274                         | INDEX                                                         { $$ = OBJECT_INDEX; }
4275                         | SEQUENCE                                                      { $$ = OBJECT_SEQUENCE; }
4276                         | TABLE                                                         { $$ = OBJECT_TABLE; }
4277                         | DOMAIN_P                                                      { $$ = OBJECT_TYPE; }
4278                         | TYPE_P                                                        { $$ = OBJECT_TYPE; }
4279                         | VIEW                                                          { $$ = OBJECT_VIEW; }
4280                         | CONVERSION_P                                          { $$ = OBJECT_CONVERSION; }
4281                         | TABLESPACE                                            { $$ = OBJECT_TABLESPACE; }
4282                         | ROLE                                                          { $$ = OBJECT_ROLE; }
4283                 ;
4284
4285 comment_text:
4286                         Sconst                                                          { $$ = $1; }
4287                         | NULL_P                                                        { $$ = NULL; }
4288                 ;
4289
4290 /*****************************************************************************
4291  *
4292  *              QUERY:
4293  *                      fetch/move
4294  *
4295  *****************************************************************************/
4296
4297 FetchStmt:      FETCH fetch_args
4298                                 {
4299                                         FetchStmt *n = (FetchStmt *) $2;
4300                                         n->ismove = FALSE;
4301                                         $$ = (Node *)n;
4302                                 }
4303                         | MOVE fetch_args
4304                                 {
4305                                         FetchStmt *n = (FetchStmt *) $2;
4306                                         n->ismove = TRUE;
4307                                         $$ = (Node *)n;
4308                                 }
4309                 ;
4310
4311 fetch_args:     cursor_name
4312                                 {
4313                                         FetchStmt *n = makeNode(FetchStmt);
4314                                         n->portalname = $1;
4315                                         n->direction = FETCH_FORWARD;
4316                                         n->howMany = 1;
4317                                         $$ = (Node *)n;
4318                                 }
4319                         | from_in cursor_name
4320                                 {
4321                                         FetchStmt *n = makeNode(FetchStmt);
4322                                         n->portalname = $2;
4323                                         n->direction = FETCH_FORWARD;
4324                                         n->howMany = 1;
4325                                         $$ = (Node *)n;
4326                                 }
4327                         | NEXT opt_from_in cursor_name
4328                                 {
4329                                         FetchStmt *n = makeNode(FetchStmt);
4330                                         n->portalname = $3;
4331                                         n->direction = FETCH_FORWARD;
4332                                         n->howMany = 1;
4333                                         $$ = (Node *)n;
4334                                 }
4335                         | PRIOR opt_from_in cursor_name
4336                                 {
4337                                         FetchStmt *n = makeNode(FetchStmt);
4338                                         n->portalname = $3;
4339                                         n->direction = FETCH_BACKWARD;
4340                                         n->howMany = 1;
4341                                         $$ = (Node *)n;
4342                                 }
4343                         | FIRST_P opt_from_in cursor_name
4344                                 {
4345                                         FetchStmt *n = makeNode(FetchStmt);
4346                                         n->portalname = $3;
4347                                         n->direction = FETCH_ABSOLUTE;
4348                                         n->howMany = 1;
4349                                         $$ = (Node *)n;
4350                                 }
4351                         | LAST_P opt_from_in cursor_name
4352                                 {
4353                                         FetchStmt *n = makeNode(FetchStmt);
4354                                         n->portalname = $3;
4355                                         n->direction = FETCH_ABSOLUTE;
4356                                         n->howMany = -1;
4357                                         $$ = (Node *)n;
4358                                 }
4359                         | ABSOLUTE_P SignedIconst opt_from_in cursor_name
4360                                 {
4361                                         FetchStmt *n = makeNode(FetchStmt);
4362                                         n->portalname = $4;
4363                                         n->direction = FETCH_ABSOLUTE;
4364                                         n->howMany = $2;
4365                                         $$ = (Node *)n;
4366                                 }
4367                         | RELATIVE_P SignedIconst opt_from_in cursor_name
4368                                 {
4369                                         FetchStmt *n = makeNode(FetchStmt);
4370                                         n->portalname = $4;
4371                                         n->direction = FETCH_RELATIVE;
4372                                         n->howMany = $2;
4373                                         $$ = (Node *)n;
4374                                 }
4375                         | SignedIconst opt_from_in cursor_name
4376                                 {
4377                                         FetchStmt *n = makeNode(FetchStmt);
4378                                         n->portalname = $3;
4379                                         n->direction = FETCH_FORWARD;
4380                                         n->howMany = $1;
4381                                         $$ = (Node *)n;
4382                                 }
4383                         | ALL opt_from_in cursor_name
4384                                 {
4385                                         FetchStmt *n = makeNode(FetchStmt);
4386                                         n->portalname = $3;
4387                                         n->direction = FETCH_FORWARD;
4388                                         n->howMany = FETCH_ALL;
4389                                         $$ = (Node *)n;
4390                                 }
4391                         | FORWARD opt_from_in cursor_name
4392                                 {
4393                                         FetchStmt *n = makeNode(FetchStmt);
4394                                         n->portalname = $3;
4395                                         n->direction = FETCH_FORWARD;
4396                                         n->howMany = 1;
4397                                         $$ = (Node *)n;
4398                                 }
4399                         | FORWARD SignedIconst opt_from_in cursor_name
4400                                 {
4401                                         FetchStmt *n = makeNode(FetchStmt);
4402                                         n->portalname = $4;
4403                                         n->direction = FETCH_FORWARD;
4404                                         n->howMany = $2;
4405                                         $$ = (Node *)n;
4406                                 }
4407                         | FORWARD ALL opt_from_in cursor_name
4408                                 {
4409                                         FetchStmt *n = makeNode(FetchStmt);
4410                                         n->portalname = $4;
4411                                         n->direction = FETCH_FORWARD;
4412                                         n->howMany = FETCH_ALL;
4413                                         $$ = (Node *)n;
4414                                 }
4415                         | BACKWARD opt_from_in cursor_name
4416                                 {
4417                                         FetchStmt *n = makeNode(FetchStmt);
4418                                         n->portalname = $3;
4419                                         n->direction = FETCH_BACKWARD;
4420                                         n->howMany = 1;
4421                                         $$ = (Node *)n;
4422                                 }
4423                         | BACKWARD SignedIconst opt_from_in cursor_name
4424                                 {
4425                                         FetchStmt *n = makeNode(FetchStmt);
4426                                         n->portalname = $4;
4427                                         n->direction = FETCH_BACKWARD;
4428                                         n->howMany = $2;
4429                                         $$ = (Node *)n;
4430                                 }
4431                         | BACKWARD ALL opt_from_in cursor_name
4432                                 {
4433                                         FetchStmt *n = makeNode(FetchStmt);
4434                                         n->portalname = $4;
4435                                         n->direction = FETCH_BACKWARD;
4436                                         n->howMany = FETCH_ALL;
4437                                         $$ = (Node *)n;
4438                                 }
4439                 ;
4440
4441 from_in:        FROM                                                                    {}
4442                         | IN_P                                                                  {}
4443                 ;
4444
4445 opt_from_in:    from_in                                                         {}
4446                         | /* EMPTY */                                                   {}
4447                 ;
4448
4449
4450 /*****************************************************************************
4451  *
4452  * GRANT and REVOKE statements
4453  *
4454  *****************************************************************************/
4455
4456 GrantStmt:      GRANT privileges ON privilege_target TO grantee_list
4457                         opt_grant_grant_option
4458                                 {
4459                                         GrantStmt *n = makeNode(GrantStmt);
4460                                         n->is_grant = true;
4461                                         n->privileges = $2;
4462                                         n->targtype = ($4)->targtype;
4463                                         n->objtype = ($4)->objtype;
4464                                         n->objects = ($4)->objs;
4465                                         n->grantees = $6;
4466                                         n->grant_option = $7;
4467                                         $$ = (Node*)n;
4468                                 }
4469                 ;
4470
4471 RevokeStmt:
4472                         REVOKE privileges ON privilege_target
4473                         FROM grantee_list opt_drop_behavior
4474                                 {
4475                                         GrantStmt *n = makeNode(GrantStmt);
4476                                         n->is_grant = false;
4477                                         n->grant_option = false;
4478                                         n->privileges = $2;
4479                                         n->targtype = ($4)->targtype;
4480                                         n->objtype = ($4)->objtype;
4481                                         n->objects = ($4)->objs;
4482                                         n->grantees = $6;
4483                                         n->behavior = $7;
4484                                         $$ = (Node *)n;
4485                                 }
4486                         | REVOKE GRANT OPTION FOR privileges ON privilege_target
4487                         FROM grantee_list opt_drop_behavior
4488                                 {
4489                                         GrantStmt *n = makeNode(GrantStmt);
4490                                         n->is_grant = false;
4491                                         n->grant_option = true;
4492                                         n->privileges = $5;
4493                                         n->targtype = ($7)->targtype;
4494                                         n->objtype = ($7)->objtype;
4495                                         n->objects = ($7)->objs;
4496                                         n->grantees = $9;
4497                                         n->behavior = $10;
4498                                         $$ = (Node *)n;
4499                                 }
4500                 ;
4501
4502
4503 /*
4504  * Privilege names are represented as strings; the validity of the privilege
4505  * names gets checked at execution.  This is a bit annoying but we have little
4506  * choice because of the syntactic conflict with lists of role names in
4507  * GRANT/REVOKE.  What's more, we have to call out in the "privilege"
4508  * production any reserved keywords that need to be usable as privilege names.
4509  */
4510
4511 /* either ALL [PRIVILEGES] or a list of individual privileges */
4512 privileges: privilege_list
4513                                 { $$ = $1; }
4514                         | ALL
4515                                 { $$ = NIL; }
4516                         | ALL PRIVILEGES
4517                                 { $$ = NIL; }
4518                         | ALL '(' columnList ')'
4519                                 {
4520                                         AccessPriv *n = makeNode(AccessPriv);
4521                                         n->priv_name = NULL;
4522                                         n->cols = $3;
4523                                         $$ = list_make1(n);
4524                                 }
4525                         | ALL PRIVILEGES '(' columnList ')'
4526                                 {
4527                                         AccessPriv *n = makeNode(AccessPriv);
4528                                         n->priv_name = NULL;
4529                                         n->cols = $4;
4530                                         $$ = list_make1(n);
4531                                 }
4532                 ;
4533
4534 privilege_list: privilege                                                       { $$ = list_make1($1); }
4535                         | privilege_list ',' privilege                  { $$ = lappend($1, $3); }
4536                 ;
4537
4538 privilege:      SELECT opt_column_list
4539                         {
4540                                 AccessPriv *n = makeNode(AccessPriv);
4541                                 n->priv_name = pstrdup($1);
4542                                 n->cols = $2;
4543                                 $$ = n;
4544                         }
4545                 | REFERENCES opt_column_list
4546                         {
4547                                 AccessPriv *n = makeNode(AccessPriv);
4548                                 n->priv_name = pstrdup($1);
4549                                 n->cols = $2;
4550                                 $$ = n;
4551                         }
4552                 | CREATE opt_column_list
4553                         {
4554                                 AccessPriv *n = makeNode(AccessPriv);
4555                                 n->priv_name = pstrdup($1);
4556                                 n->cols = $2;
4557                                 $$ = n;
4558                         }
4559                 | ColId opt_column_list
4560                         {
4561                                 AccessPriv *n = makeNode(AccessPriv);
4562                                 n->priv_name = $1;
4563                                 n->cols = $2;
4564                                 $$ = n;
4565                         }
4566                 ;
4567
4568
4569 /* Don't bother trying to fold the first two rules into one using
4570  * opt_table.  You're going to get conflicts.
4571  */
4572 privilege_target:
4573                         qualified_name_list
4574                                 {
4575                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4576                                         n->targtype = ACL_TARGET_OBJECT;
4577                                         n->objtype = ACL_OBJECT_RELATION;
4578                                         n->objs = $1;
4579                                         $$ = n;
4580                                 }
4581                         | TABLE qualified_name_list
4582                                 {
4583                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4584                                         n->targtype = ACL_TARGET_OBJECT;
4585                                         n->objtype = ACL_OBJECT_RELATION;
4586                                         n->objs = $2;
4587                                         $$ = n;
4588                                 }
4589                         | SEQUENCE qualified_name_list
4590                                 {
4591                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4592                                         n->targtype = ACL_TARGET_OBJECT;
4593                                         n->objtype = ACL_OBJECT_SEQUENCE;
4594                                         n->objs = $2;
4595                                         $$ = n;
4596                                 }
4597                         | FOREIGN DATA_P WRAPPER name_list
4598                                 {
4599                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4600                                         n->targtype = ACL_TARGET_OBJECT;
4601                                         n->objtype = ACL_OBJECT_FDW;
4602                                         n->objs = $4;
4603                                         $$ = n;
4604                                 }
4605                         | FOREIGN SERVER name_list
4606                                 {
4607                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4608                                         n->targtype = ACL_TARGET_OBJECT;
4609                                         n->objtype = ACL_OBJECT_FOREIGN_SERVER;
4610                                         n->objs = $3;
4611                                         $$ = n;
4612                                 }
4613                         | FUNCTION function_with_argtypes_list
4614                                 {
4615                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4616                                         n->targtype = ACL_TARGET_OBJECT;
4617                                         n->objtype = ACL_OBJECT_FUNCTION;
4618                                         n->objs = $2;
4619                                         $$ = n;
4620                                 }
4621                         | DATABASE name_list
4622                                 {
4623                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4624                                         n->targtype = ACL_TARGET_OBJECT;
4625                                         n->objtype = ACL_OBJECT_DATABASE;
4626                                         n->objs = $2;
4627                                         $$ = n;
4628                                 }
4629                         | LANGUAGE name_list
4630                                 {
4631                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4632                                         n->targtype = ACL_TARGET_OBJECT;
4633                                         n->objtype = ACL_OBJECT_LANGUAGE;
4634                                         n->objs = $2;
4635                                         $$ = n;
4636                                 }
4637                         | LARGE_P OBJECT_P Iconst_list
4638                                 {
4639                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4640                                         n->targtype = ACL_TARGET_OBJECT;
4641                                         n->objtype = ACL_OBJECT_LARGEOBJECT;
4642                                         n->objs = $3;
4643                                         $$ = n;
4644                                 }
4645                         | SCHEMA name_list
4646                                 {
4647                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4648                                         n->targtype = ACL_TARGET_OBJECT;
4649                                         n->objtype = ACL_OBJECT_NAMESPACE;
4650                                         n->objs = $2;
4651                                         $$ = n;
4652                                 }
4653                         | TABLESPACE name_list
4654                                 {
4655                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4656                                         n->targtype = ACL_TARGET_OBJECT;
4657                                         n->objtype = ACL_OBJECT_TABLESPACE;
4658                                         n->objs = $2;
4659                                         $$ = n;
4660                                 }
4661                         | ALL TABLES IN_P SCHEMA name_list
4662                                 {
4663                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4664                                         n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
4665                                         n->objtype = ACL_OBJECT_RELATION;
4666                                         n->objs = $5;
4667                                         $$ = n;
4668                                 }
4669                         | ALL SEQUENCES IN_P SCHEMA name_list
4670                                 {
4671                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4672                                         n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
4673                                         n->objtype = ACL_OBJECT_SEQUENCE;
4674                                         n->objs = $5;
4675                                         $$ = n;
4676                                 }
4677                         | ALL FUNCTIONS IN_P SCHEMA name_list
4678                                 {
4679                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
4680                                         n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
4681                                         n->objtype = ACL_OBJECT_FUNCTION;
4682                                         n->objs = $5;
4683                                         $$ = n;
4684                                 }
4685                 ;
4686
4687
4688 grantee_list:
4689                         grantee                                                                 { $$ = list_make1($1); }
4690                         | grantee_list ',' grantee                              { $$ = lappend($1, $3); }
4691                 ;
4692
4693 grantee:        RoleId
4694                                 {
4695                                         PrivGrantee *n = makeNode(PrivGrantee);
4696                                         /* This hack lets us avoid reserving PUBLIC as a keyword*/
4697                                         if (strcmp($1, "public") == 0)
4698                                                 n->rolname = NULL;
4699                                         else
4700                                                 n->rolname = $1;
4701                                         $$ = (Node *)n;
4702                                 }
4703                         | GROUP_P RoleId
4704                                 {
4705                                         PrivGrantee *n = makeNode(PrivGrantee);
4706                                         /* Treat GROUP PUBLIC as a synonym for PUBLIC */
4707                                         if (strcmp($2, "public") == 0)
4708                                                 n->rolname = NULL;
4709                                         else
4710                                                 n->rolname = $2;
4711                                         $$ = (Node *)n;
4712                                 }
4713                 ;
4714
4715
4716 opt_grant_grant_option:
4717                         WITH GRANT OPTION { $$ = TRUE; }
4718                         | /*EMPTY*/ { $$ = FALSE; }
4719                 ;
4720
4721 function_with_argtypes_list:
4722                         function_with_argtypes                                  { $$ = list_make1($1); }
4723                         | function_with_argtypes_list ',' function_with_argtypes
4724                                                                                                         { $$ = lappend($1, $3); }
4725                 ;
4726
4727 function_with_argtypes:
4728                         func_name func_args
4729                                 {
4730                                         FuncWithArgs *n = makeNode(FuncWithArgs);
4731                                         n->funcname = $1;
4732                                         n->funcargs = extractArgTypes($2);
4733                                         $$ = n;
4734                                 }
4735                 ;
4736
4737 /*****************************************************************************
4738  *
4739  * GRANT and REVOKE ROLE statements
4740  *
4741  *****************************************************************************/
4742
4743 GrantRoleStmt:
4744                         GRANT privilege_list TO name_list opt_grant_admin_option opt_granted_by
4745                                 {
4746                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
4747                                         n->is_grant = true;
4748                                         n->granted_roles = $2;
4749                                         n->grantee_roles = $4;
4750                                         n->admin_opt = $5;
4751                                         n->grantor = $6;
4752                                         $$ = (Node*)n;
4753                                 }
4754                 ;
4755
4756 RevokeRoleStmt:
4757                         REVOKE privilege_list FROM name_list opt_granted_by opt_drop_behavior
4758                                 {
4759                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
4760                                         n->is_grant = false;
4761                                         n->admin_opt = false;
4762                                         n->granted_roles = $2;
4763                                         n->grantee_roles = $4;
4764                                         n->behavior = $6;
4765                                         $$ = (Node*)n;
4766                                 }
4767                         | REVOKE ADMIN OPTION FOR privilege_list FROM name_list opt_granted_by opt_drop_behavior
4768                                 {
4769                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
4770                                         n->is_grant = false;
4771                                         n->admin_opt = true;
4772                                         n->granted_roles = $5;
4773                                         n->grantee_roles = $7;
4774                                         n->behavior = $9;
4775                                         $$ = (Node*)n;
4776                                 }
4777                 ;
4778
4779 opt_grant_admin_option: WITH ADMIN OPTION                               { $$ = TRUE; }
4780                         | /*EMPTY*/                                                                     { $$ = FALSE; }
4781                 ;
4782
4783 opt_granted_by: GRANTED BY RoleId                                               { $$ = $3; }
4784                         | /*EMPTY*/                                                                     { $$ = NULL; }
4785                 ;
4786
4787 /*****************************************************************************
4788  *
4789  * ALTER DEFAULT PRIVILEGES statement
4790  *
4791  *****************************************************************************/
4792
4793 AlterDefaultPrivilegesStmt:
4794                         ALTER DEFAULT PRIVILEGES DefACLOptionList DefACLAction
4795                                 {
4796                                         AlterDefaultPrivilegesStmt *n = makeNode(AlterDefaultPrivilegesStmt);
4797                                         n->options = $4;
4798                                         n->action = (GrantStmt *) $5;
4799                                         $$ = (Node*)n;
4800                                 }
4801                 ;
4802
4803 DefACLOptionList:
4804                         DefACLOptionList DefACLOption                   { $$ = lappend($1, $2); }
4805                         | /* EMPTY */                                                   { $$ = NIL; }
4806                 ;
4807
4808 DefACLOption:
4809                         IN_P SCHEMA name_list
4810                                 {
4811                                         $$ = makeDefElem("schemas", (Node *)$3);
4812                                 }
4813                         | FOR ROLE name_list
4814                                 {
4815                                         $$ = makeDefElem("roles", (Node *)$3);
4816                                 }
4817                         | FOR USER name_list
4818                                 {
4819                                         $$ = makeDefElem("roles", (Node *)$3);
4820                                 }
4821                 ;
4822
4823 /*
4824  * This should match GRANT/REVOKE, except that individual target objects
4825  * are not mentioned and we only allow a subset of object types.
4826  */
4827 DefACLAction:
4828                         GRANT privileges ON defacl_privilege_target TO grantee_list
4829                         opt_grant_grant_option
4830                                 {
4831                                         GrantStmt *n = makeNode(GrantStmt);
4832                                         n->is_grant = true;
4833                                         n->privileges = $2;
4834                                         n->targtype = ACL_TARGET_DEFAULTS;
4835                                         n->objtype = $4;
4836                                         n->objects = NIL;
4837                                         n->grantees = $6;
4838                                         n->grant_option = $7;
4839                                         $$ = (Node*)n;
4840                                 }
4841                         | REVOKE privileges ON defacl_privilege_target
4842                         FROM grantee_list opt_drop_behavior
4843                                 {
4844                                         GrantStmt *n = makeNode(GrantStmt);
4845                                         n->is_grant = false;
4846                                         n->grant_option = false;
4847                                         n->privileges = $2;
4848                                         n->targtype = ACL_TARGET_DEFAULTS;
4849                                         n->objtype = $4;
4850                                         n->objects = NIL;
4851                                         n->grantees = $6;
4852                                         n->behavior = $7;
4853                                         $$ = (Node *)n;
4854                                 }
4855                         | REVOKE GRANT OPTION FOR privileges ON defacl_privilege_target
4856                         FROM grantee_list opt_drop_behavior
4857                                 {
4858                                         GrantStmt *n = makeNode(GrantStmt);
4859                                         n->is_grant = false;
4860                                         n->grant_option = true;
4861                                         n->privileges = $5;
4862                                         n->targtype = ACL_TARGET_DEFAULTS;
4863                                         n->objtype = $7;
4864                                         n->objects = NIL;
4865                                         n->grantees = $9;
4866                                         n->behavior = $10;
4867                                         $$ = (Node *)n;
4868                                 }
4869                 ;
4870
4871 defacl_privilege_target:
4872                         TABLES                  { $$ = ACL_OBJECT_RELATION; }
4873                         | FUNCTIONS             { $$ = ACL_OBJECT_FUNCTION; }
4874                         | SEQUENCES             { $$ = ACL_OBJECT_SEQUENCE; }
4875                 ;
4876
4877
4878 /*****************************************************************************
4879  *
4880  *              QUERY: CREATE INDEX
4881  *
4882  * Note: we cannot put TABLESPACE clause after WHERE clause unless we are
4883  * willing to make TABLESPACE a fully reserved word.
4884  *****************************************************************************/
4885
4886 IndexStmt:      CREATE opt_unique INDEX opt_concurrently opt_index_name
4887                         ON qualified_name access_method_clause '(' index_params ')'
4888                         opt_reloptions OptTableSpace where_clause
4889                                 {
4890                                         IndexStmt *n = makeNode(IndexStmt);
4891                                         n->unique = $2;
4892                                         n->concurrent = $4;
4893                                         n->idxname = $5;
4894                                         n->relation = $7;
4895                                         n->accessMethod = $8;
4896                                         n->indexParams = $10;
4897                                         n->options = $12;
4898                                         n->tableSpace = $13;
4899                                         n->whereClause = $14;
4900                                         $$ = (Node *)n;
4901                                 }
4902                 ;
4903
4904 opt_unique:
4905                         UNIQUE                                                                  { $$ = TRUE; }
4906                         | /*EMPTY*/                                                             { $$ = FALSE; }
4907                 ;
4908
4909 opt_concurrently:
4910                         CONCURRENTLY                                                    { $$ = TRUE; }
4911                         | /*EMPTY*/                                                             { $$ = FALSE; }
4912                 ;
4913
4914 opt_index_name:
4915                         index_name                                                              { $$ = $1; }
4916                         | /*EMPTY*/                                                             { $$ = NULL; }
4917                 ;
4918
4919 access_method_clause:
4920                         USING access_method                                             { $$ = $2; }
4921                         | /*EMPTY*/                                                             { $$ = DEFAULT_INDEX_TYPE; }
4922                 ;
4923
4924 index_params:   index_elem                                                      { $$ = list_make1($1); }
4925                         | index_params ',' index_elem                   { $$ = lappend($1, $3); }
4926                 ;
4927
4928 /*
4929  * Index attributes can be either simple column references, or arbitrary
4930  * expressions in parens.  For backwards-compatibility reasons, we allow
4931  * an expression that's just a function call to be written without parens.
4932  */
4933 index_elem:     ColId opt_class opt_asc_desc opt_nulls_order
4934                                 {
4935                                         $$ = makeNode(IndexElem);
4936                                         $$->name = $1;
4937                                         $$->expr = NULL;
4938                                         $$->indexcolname = NULL;
4939                                         $$->opclass = $2;
4940                                         $$->ordering = $3;
4941                                         $$->nulls_ordering = $4;
4942                                 }
4943                         | func_expr opt_class opt_asc_desc opt_nulls_order
4944                                 {
4945                                         $$ = makeNode(IndexElem);
4946                                         $$->name = NULL;
4947                                         $$->expr = $1;
4948                                         $$->indexcolname = NULL;
4949                                         $$->opclass = $2;
4950                                         $$->ordering = $3;
4951                                         $$->nulls_ordering = $4;
4952                                 }
4953                         | '(' a_expr ')' opt_class opt_asc_desc opt_nulls_order
4954                                 {
4955                                         $$ = makeNode(IndexElem);
4956                                         $$->name = NULL;
4957                                         $$->expr = $2;
4958                                         $$->indexcolname = NULL;
4959                                         $$->opclass = $4;
4960                                         $$->ordering = $5;
4961                                         $$->nulls_ordering = $6;
4962                                 }
4963                 ;
4964
4965 opt_class:      any_name                                                                { $$ = $1; }
4966                         | USING any_name                                                { $$ = $2; }
4967                         | /*EMPTY*/                                                             { $$ = NIL; }
4968                 ;
4969
4970 opt_asc_desc: ASC                                                       { $$ = SORTBY_ASC; }
4971                         | DESC                                                  { $$ = SORTBY_DESC; }
4972                         | /*EMPTY*/                                             { $$ = SORTBY_DEFAULT; }
4973                 ;
4974
4975 opt_nulls_order: NULLS_FIRST                            { $$ = SORTBY_NULLS_FIRST; }
4976                         | NULLS_LAST                                    { $$ = SORTBY_NULLS_LAST; }
4977                         | /*EMPTY*/                                             { $$ = SORTBY_NULLS_DEFAULT; }
4978                 ;
4979
4980
4981 /*****************************************************************************
4982  *
4983  *              QUERY:
4984  *                              create [or replace] function <fname>
4985  *                                              [(<type-1> { , <type-n>})]
4986  *                                              returns <type-r>
4987  *                                              as <filename or code in language as appropriate>
4988  *                                              language <lang> [with parameters]
4989  *
4990  *****************************************************************************/
4991
4992 CreateFunctionStmt:
4993                         CREATE opt_or_replace FUNCTION func_name func_args_with_defaults
4994                         RETURNS func_return createfunc_opt_list opt_definition
4995                                 {
4996                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
4997                                         n->replace = $2;
4998                                         n->funcname = $4;
4999                                         n->parameters = $5;
5000                                         n->returnType = $7;
5001                                         n->options = $8;
5002                                         n->withClause = $9;
5003                                         $$ = (Node *)n;
5004                                 }
5005                         | CREATE opt_or_replace FUNCTION func_name func_args_with_defaults
5006                           RETURNS TABLE '(' table_func_column_list ')' createfunc_opt_list opt_definition
5007                                 {
5008                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
5009                                         n->replace = $2;
5010                                         n->funcname = $4;
5011                                         n->parameters = mergeTableFuncParameters($5, $9);
5012                                         n->returnType = TableFuncTypeName($9);
5013                                         n->returnType->location = @7;
5014                                         n->options = $11;
5015                                         n->withClause = $12;
5016                                         $$ = (Node *)n;
5017                                 }
5018                         | CREATE opt_or_replace FUNCTION func_name func_args_with_defaults
5019                           createfunc_opt_list opt_definition
5020                                 {
5021                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
5022                                         n->replace = $2;
5023                                         n->funcname = $4;
5024                                         n->parameters = $5;
5025                                         n->returnType = NULL;
5026                                         n->options = $6;
5027                                         n->withClause = $7;
5028                                         $$ = (Node *)n;
5029                                 }
5030                 ;
5031
5032 opt_or_replace:
5033                         OR REPLACE                                                              { $$ = TRUE; }
5034                         | /*EMPTY*/                                                             { $$ = FALSE; }
5035                 ;
5036
5037 func_args:      '(' func_args_list ')'                                  { $$ = $2; }
5038                         | '(' ')'                                                               { $$ = NIL; }
5039                 ;
5040
5041 func_args_list:
5042                         func_arg                                                                { $$ = list_make1($1); }
5043                         | func_args_list ',' func_arg                   { $$ = lappend($1, $3); }
5044                 ;
5045
5046 /*
5047  * func_args_with_defaults is separate because we only want to accept
5048  * defaults in CREATE FUNCTION, not in ALTER etc.
5049  */
5050 func_args_with_defaults:
5051                 '(' func_args_with_defaults_list ')'            { $$ = $2; }
5052                 | '(' ')'                                                                       { $$ = NIL; }
5053                 ;
5054
5055 func_args_with_defaults_list:
5056                 func_arg_with_default                                           { $$ = list_make1($1); }
5057                 | func_args_with_defaults_list ',' func_arg_with_default
5058                                                                                                         { $$ = lappend($1, $3); }
5059                 ;
5060
5061 /*
5062  * The style with arg_class first is SQL99 standard, but Oracle puts
5063  * param_name first; accept both since it's likely people will try both
5064  * anyway.  Don't bother trying to save productions by letting arg_class
5065  * have an empty alternative ... you'll get shift/reduce conflicts.
5066  *
5067  * We can catch over-specified arguments here if we want to,
5068  * but for now better to silently swallow typmod, etc.
5069  * - thomas 2000-03-22
5070  */
5071 func_arg:
5072                         arg_class param_name func_type
5073                                 {
5074                                         FunctionParameter *n = makeNode(FunctionParameter);
5075                                         n->name = $2;
5076                                         n->argType = $3;
5077                                         n->mode = $1;
5078                                         n->defexpr = NULL;
5079                                         $$ = n;
5080                                 }
5081                         | param_name arg_class func_type
5082                                 {
5083                                         FunctionParameter *n = makeNode(FunctionParameter);
5084                                         n->name = $1;
5085                                         n->argType = $3;
5086                                         n->mode = $2;
5087                                         n->defexpr = NULL;
5088                                         $$ = n;
5089                                 }
5090                         | param_name func_type
5091                                 {
5092                                         FunctionParameter *n = makeNode(FunctionParameter);
5093                                         n->name = $1;
5094                                         n->argType = $2;
5095                                         n->mode = FUNC_PARAM_IN;
5096                                         n->defexpr = NULL;
5097                                         $$ = n;
5098                                 }
5099                         | arg_class func_type
5100                                 {
5101                                         FunctionParameter *n = makeNode(FunctionParameter);
5102                                         n->name = NULL;
5103                                         n->argType = $2;
5104                                         n->mode = $1;
5105                                         n->defexpr = NULL;
5106                                         $$ = n;
5107                                 }
5108                         | func_type
5109                                 {
5110                                         FunctionParameter *n = makeNode(FunctionParameter);
5111                                         n->name = NULL;
5112                                         n->argType = $1;
5113                                         n->mode = FUNC_PARAM_IN;
5114                                         n->defexpr = NULL;
5115                                         $$ = n;
5116                                 }
5117                 ;
5118
5119 /* INOUT is SQL99 standard, IN OUT is for Oracle compatibility */
5120 arg_class:      IN_P                                                            { $$ = FUNC_PARAM_IN; }
5121                         | OUT_P                                                         { $$ = FUNC_PARAM_OUT; }
5122                         | INOUT                                                         { $$ = FUNC_PARAM_INOUT; }
5123                         | IN_P OUT_P                                            { $$ = FUNC_PARAM_INOUT; }
5124                         | VARIADIC                                                      { $$ = FUNC_PARAM_VARIADIC; }
5125                 ;
5126
5127 /*
5128  * Ideally param_name should be ColId, but that causes too many conflicts.
5129  */
5130 param_name:     type_function_name
5131                 ;
5132
5133 func_return:
5134                         func_type
5135                                 {
5136                                         /* We can catch over-specified results here if we want to,
5137                                          * but for now better to silently swallow typmod, etc.
5138                                          * - thomas 2000-03-22
5139                                          */
5140                                         $$ = $1;
5141                                 }
5142                 ;
5143
5144 /*
5145  * We would like to make the %TYPE productions here be ColId attrs etc,
5146  * but that causes reduce/reduce conflicts.  type_function_name
5147  * is next best choice.
5148  */
5149 func_type:      Typename                                                                { $$ = $1; }
5150                         | type_function_name attrs '%' TYPE_P
5151                                 {
5152                                         $$ = makeTypeNameFromNameList(lcons(makeString($1), $2));
5153                                         $$->pct_type = true;
5154                                         $$->location = @1;
5155                                 }
5156                         | SETOF type_function_name attrs '%' TYPE_P
5157                                 {
5158                                         $$ = makeTypeNameFromNameList(lcons(makeString($2), $3));
5159                                         $$->pct_type = true;
5160                                         $$->setof = TRUE;
5161                                         $$->location = @2;
5162                                 }
5163                 ;
5164
5165 func_arg_with_default:
5166                 func_arg
5167                             {
5168                                     $$ = $1;
5169                             }
5170                 | func_arg DEFAULT a_expr
5171                             {
5172                                     $$ = $1;
5173                                     $$->defexpr = $3;
5174                             }
5175                 | func_arg '=' a_expr
5176                             {
5177                                     $$ = $1;
5178                                     $$->defexpr = $3;
5179                             }
5180                 ;
5181
5182
5183 createfunc_opt_list:
5184                         /* Must be at least one to prevent conflict */
5185                         createfunc_opt_item                     { $$ = list_make1($1); }
5186                         | createfunc_opt_list createfunc_opt_item { $$ = lappend($1, $2); }
5187         ;
5188
5189 /*
5190  * Options common to both CREATE FUNCTION and ALTER FUNCTION
5191  */
5192 common_func_opt_item:
5193                         CALLED ON NULL_P INPUT_P
5194                                 {
5195                                         $$ = makeDefElem("strict", (Node *)makeInteger(FALSE));
5196                                 }
5197                         | RETURNS NULL_P ON NULL_P INPUT_P
5198                                 {
5199                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
5200                                 }
5201                         | STRICT_P
5202                                 {
5203                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
5204                                 }
5205                         | IMMUTABLE
5206                                 {
5207                                         $$ = makeDefElem("volatility", (Node *)makeString("immutable"));
5208                                 }
5209                         | STABLE
5210                                 {
5211                                         $$ = makeDefElem("volatility", (Node *)makeString("stable"));
5212                                 }
5213                         | VOLATILE
5214                                 {
5215                                         $$ = makeDefElem("volatility", (Node *)makeString("volatile"));
5216                                 }
5217                         | EXTERNAL SECURITY DEFINER
5218                                 {
5219                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
5220                                 }
5221                         | EXTERNAL SECURITY INVOKER
5222                                 {
5223                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
5224                                 }
5225                         | SECURITY DEFINER
5226                                 {
5227                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
5228                                 }
5229                         | SECURITY INVOKER
5230                                 {
5231                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
5232                                 }
5233                         | COST NumericOnly
5234                                 {
5235                                         $$ = makeDefElem("cost", (Node *)$2);
5236                                 }
5237                         | ROWS NumericOnly
5238                                 {
5239                                         $$ = makeDefElem("rows", (Node *)$2);
5240                                 }
5241                         | SetResetClause
5242                                 {
5243                                         /* we abuse the normal content of a DefElem here */
5244                                         $$ = makeDefElem("set", (Node *)$1);
5245                                 }
5246                 ;
5247
5248 createfunc_opt_item:
5249                         AS func_as
5250                                 {
5251                                         $$ = makeDefElem("as", (Node *)$2);
5252                                 }
5253                         | LANGUAGE ColId_or_Sconst
5254                                 {
5255                                         $$ = makeDefElem("language", (Node *)makeString($2));
5256                                 }
5257                         | WINDOW
5258                                 {
5259                                         $$ = makeDefElem("window", (Node *)makeInteger(TRUE));
5260                                 }
5261                         | common_func_opt_item
5262                                 {
5263                                         $$ = $1;
5264                                 }
5265                 ;
5266
5267 func_as:        Sconst                                          { $$ = list_make1(makeString($1)); }
5268                         | Sconst ',' Sconst
5269                                 {
5270                                         $$ = list_make2(makeString($1), makeString($3));
5271                                 }
5272                 ;
5273
5274 opt_definition:
5275                         WITH definition                                                 { $$ = $2; }
5276                         | /*EMPTY*/                                                             { $$ = NIL; }
5277                 ;
5278
5279 table_func_column:      param_name func_type
5280                                 {
5281                                         FunctionParameter *n = makeNode(FunctionParameter);
5282                                         n->name = $1;
5283                                         n->argType = $2;
5284                                         n->mode = FUNC_PARAM_TABLE;
5285                                         n->defexpr = NULL;
5286                                         $$ = n;
5287                                 }
5288                 ;
5289
5290 table_func_column_list:
5291                         table_func_column
5292                                 {
5293                                         $$ = list_make1($1);
5294                                 }
5295                         | table_func_column_list ',' table_func_column
5296                                 {
5297                                         $$ = lappend($1, $3);
5298                                 }
5299                 ;
5300
5301 /*****************************************************************************
5302  * ALTER FUNCTION
5303  *
5304  * RENAME and OWNER subcommands are already provided by the generic
5305  * ALTER infrastructure, here we just specify alterations that can
5306  * only be applied to functions.
5307  *
5308  *****************************************************************************/
5309 AlterFunctionStmt:
5310                         ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
5311                                 {
5312                                         AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
5313                                         n->func = $3;
5314                                         n->actions = $4;
5315                                         $$ = (Node *) n;
5316                                 }
5317                 ;
5318
5319 alterfunc_opt_list:
5320                         /* At least one option must be specified */
5321                         common_func_opt_item                                    { $$ = list_make1($1); }
5322                         | alterfunc_opt_list common_func_opt_item { $$ = lappend($1, $2); }
5323                 ;
5324
5325 /* Ignored, merely for SQL compliance */
5326 opt_restrict:
5327                         RESTRICT
5328                         | /* EMPTY */
5329                 ;
5330
5331
5332 /*****************************************************************************
5333  *
5334  *              QUERY:
5335  *
5336  *              DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
5337  *              DROP AGGREGATE aggname (arg1, ...) [ RESTRICT | CASCADE ]
5338  *              DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
5339  *
5340  *****************************************************************************/
5341
5342 RemoveFuncStmt:
5343                         DROP FUNCTION func_name func_args opt_drop_behavior
5344                                 {
5345                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
5346                                         n->kind = OBJECT_FUNCTION;
5347                                         n->name = $3;
5348                                         n->args = extractArgTypes($4);
5349                                         n->behavior = $5;
5350                                         n->missing_ok = false;
5351                                         $$ = (Node *)n;
5352                                 }
5353                         | DROP FUNCTION IF_P EXISTS func_name func_args opt_drop_behavior
5354                                 {
5355                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
5356                                         n->kind = OBJECT_FUNCTION;
5357                                         n->name = $5;
5358                                         n->args = extractArgTypes($6);
5359                                         n->behavior = $7;
5360                                         n->missing_ok = true;
5361                                         $$ = (Node *)n;
5362                                 }
5363                 ;
5364
5365 RemoveAggrStmt:
5366                         DROP AGGREGATE func_name aggr_args opt_drop_behavior
5367                                 {
5368                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
5369                                         n->kind = OBJECT_AGGREGATE;
5370                                         n->name = $3;
5371                                         n->args = $4;
5372                                         n->behavior = $5;
5373                                         n->missing_ok = false;
5374                                         $$ = (Node *)n;
5375                                 }
5376                         | DROP AGGREGATE IF_P EXISTS func_name aggr_args opt_drop_behavior
5377                                 {
5378                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
5379                                         n->kind = OBJECT_AGGREGATE;
5380                                         n->name = $5;
5381                                         n->args = $6;
5382                                         n->behavior = $7;
5383                                         n->missing_ok = true;
5384                                         $$ = (Node *)n;
5385                                 }
5386                 ;
5387
5388 RemoveOperStmt:
5389                         DROP OPERATOR any_operator oper_argtypes opt_drop_behavior
5390                                 {
5391                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
5392                                         n->kind = OBJECT_OPERATOR;
5393                                         n->name = $3;
5394                                         n->args = $4;
5395                                         n->behavior = $5;
5396                                         n->missing_ok = false;
5397                                         $$ = (Node *)n;
5398                                 }
5399                         | DROP OPERATOR IF_P EXISTS any_operator oper_argtypes opt_drop_behavior
5400                                 {
5401                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
5402                                         n->kind = OBJECT_OPERATOR;
5403                                         n->name = $5;
5404                                         n->args = $6;
5405                                         n->behavior = $7;
5406                                         n->missing_ok = true;
5407                                         $$ = (Node *)n;
5408                                 }
5409                 ;
5410
5411 oper_argtypes:
5412                         '(' Typename ')'
5413                                 {
5414                                    ereport(ERROR,
5415                                                    (errcode(ERRCODE_SYNTAX_ERROR),
5416                                                         errmsg("missing argument"),
5417                                                         errhint("Use NONE to denote the missing argument of a unary operator."),
5418                                                         parser_errposition(@3)));
5419                                 }
5420                         | '(' Typename ',' Typename ')'
5421                                         { $$ = list_make2($2, $4); }
5422                         | '(' NONE ',' Typename ')'                                     /* left unary */
5423                                         { $$ = list_make2(NULL, $4); }
5424                         | '(' Typename ',' NONE ')'                                     /* right unary */
5425                                         { $$ = list_make2($2, NULL); }
5426                 ;
5427
5428 any_operator:
5429                         all_Op
5430                                         { $$ = list_make1(makeString($1)); }
5431                         | ColId '.' any_operator
5432                                         { $$ = lcons(makeString($1), $3); }
5433                 ;
5434
5435 /*****************************************************************************
5436  *
5437  *              DO <anonymous code block> [ LANGUAGE language ]
5438  *
5439  * We use a DefElem list for future extensibility, and to allow flexibility
5440  * in the clause order.
5441  *
5442  *****************************************************************************/
5443
5444 DoStmt: DO dostmt_opt_list
5445                                 {
5446                                         DoStmt *n = makeNode(DoStmt);
5447                                         n->args = $2;
5448                                         $$ = (Node *)n;
5449                                 }
5450                 ;
5451
5452 dostmt_opt_list:
5453                         dostmt_opt_item                                         { $$ = list_make1($1); }
5454                         | dostmt_opt_list dostmt_opt_item       { $$ = lappend($1, $2); }
5455                 ;
5456
5457 dostmt_opt_item:
5458                         Sconst
5459                                 {
5460                                         $$ = makeDefElem("as", (Node *)makeString($1));
5461                                 }
5462                         | LANGUAGE ColId_or_Sconst
5463                                 {
5464                                         $$ = makeDefElem("language", (Node *)makeString($2));
5465                                 }
5466                 ;
5467
5468 /*****************************************************************************
5469  *
5470  *              CREATE CAST / DROP CAST
5471  *
5472  *****************************************************************************/
5473
5474 CreateCastStmt: CREATE CAST '(' Typename AS Typename ')'
5475                                         WITH FUNCTION function_with_argtypes cast_context
5476                                 {
5477                                         CreateCastStmt *n = makeNode(CreateCastStmt);
5478                                         n->sourcetype = $4;
5479                                         n->targettype = $6;
5480                                         n->func = $10;
5481                                         n->context = (CoercionContext) $11;
5482                                         n->inout = false;
5483                                         $$ = (Node *)n;
5484                                 }
5485                         | CREATE CAST '(' Typename AS Typename ')'
5486                                         WITHOUT FUNCTION cast_context
5487                                 {
5488                                         CreateCastStmt *n = makeNode(CreateCastStmt);
5489                                         n->sourcetype = $4;
5490                                         n->targettype = $6;
5491                                         n->func = NULL;
5492                                         n->context = (CoercionContext) $10;
5493                                         n->inout = false;
5494                                         $$ = (Node *)n;
5495                                 }
5496                         | CREATE CAST '(' Typename AS Typename ')'
5497                                         WITH INOUT cast_context
5498                                 {
5499                                         CreateCastStmt *n = makeNode(CreateCastStmt);
5500                                         n->sourcetype = $4;
5501                                         n->targettype = $6;
5502                                         n->func = NULL;
5503                                         n->context = (CoercionContext) $10;
5504                                         n->inout = true;
5505                                         $$ = (Node *)n;
5506                                 }
5507                 ;
5508
5509 cast_context:  AS IMPLICIT_P                                    { $$ = COERCION_IMPLICIT; }
5510                 | AS ASSIGNMENT                                                 { $$ = COERCION_ASSIGNMENT; }
5511                 | /*EMPTY*/                                                             { $$ = COERCION_EXPLICIT; }
5512                 ;
5513
5514
5515 DropCastStmt: DROP CAST opt_if_exists '(' Typename AS Typename ')' opt_drop_behavior
5516                                 {
5517                                         DropCastStmt *n = makeNode(DropCastStmt);
5518                                         n->sourcetype = $5;
5519                                         n->targettype = $7;
5520                                         n->behavior = $9;
5521                                         n->missing_ok = $3;
5522                                         $$ = (Node *)n;
5523                                 }
5524                 ;
5525
5526 opt_if_exists: IF_P EXISTS                                              { $$ = TRUE; }
5527                 | /*EMPTY*/                                                             { $$ = FALSE; }
5528                 ;
5529
5530
5531 /*****************************************************************************
5532  *
5533  *              QUERY:
5534  *
5535  *              REINDEX type <name> [FORCE]
5536  *
5537  * FORCE no longer does anything, but we accept it for backwards compatibility
5538  *****************************************************************************/
5539
5540 ReindexStmt:
5541                         REINDEX reindex_type qualified_name opt_force
5542                                 {
5543                                         ReindexStmt *n = makeNode(ReindexStmt);
5544                                         n->kind = $2;
5545                                         n->relation = $3;
5546                                         n->name = NULL;
5547                                         $$ = (Node *)n;
5548                                 }
5549                         | REINDEX SYSTEM_P name opt_force
5550                                 {
5551                                         ReindexStmt *n = makeNode(ReindexStmt);
5552                                         n->kind = OBJECT_DATABASE;
5553                                         n->name = $3;
5554                                         n->relation = NULL;
5555                                         n->do_system = true;
5556                                         n->do_user = false;
5557                                         $$ = (Node *)n;
5558                                 }
5559                         | REINDEX DATABASE name opt_force
5560                                 {
5561                                         ReindexStmt *n = makeNode(ReindexStmt);
5562                                         n->kind = OBJECT_DATABASE;
5563                                         n->name = $3;
5564                                         n->relation = NULL;
5565                                         n->do_system = true;
5566                                         n->do_user = true;
5567                                         $$ = (Node *)n;
5568                                 }
5569                 ;
5570
5571 reindex_type:
5572                         INDEX                                                                   { $$ = OBJECT_INDEX; }
5573                         | TABLE                                                                 { $$ = OBJECT_TABLE; }
5574                 ;
5575
5576 opt_force:      FORCE                                                                   {  $$ = TRUE; }
5577                         | /* EMPTY */                                                   {  $$ = FALSE; }
5578                 ;
5579
5580
5581 /*****************************************************************************
5582  *
5583  * ALTER THING name RENAME TO newname
5584  *
5585  *****************************************************************************/
5586
5587 RenameStmt: ALTER AGGREGATE func_name aggr_args RENAME TO name
5588                                 {
5589                                         RenameStmt *n = makeNode(RenameStmt);
5590                                         n->renameType = OBJECT_AGGREGATE;
5591                                         n->object = $3;
5592                                         n->objarg = $4;
5593                                         n->newname = $7;
5594                                         $$ = (Node *)n;
5595                                 }
5596                         | ALTER CONVERSION_P any_name RENAME TO name
5597                                 {
5598                                         RenameStmt *n = makeNode(RenameStmt);
5599                                         n->renameType = OBJECT_CONVERSION;
5600                                         n->object = $3;
5601                                         n->newname = $6;
5602                                         $$ = (Node *)n;
5603                                 }
5604                         | ALTER DATABASE database_name RENAME TO database_name
5605                                 {
5606                                         RenameStmt *n = makeNode(RenameStmt);
5607                                         n->renameType = OBJECT_DATABASE;
5608                                         n->subname = $3;
5609                                         n->newname = $6;
5610                                         $$ = (Node *)n;
5611                                 }
5612                         | ALTER FUNCTION function_with_argtypes RENAME TO name
5613                                 {
5614                                         RenameStmt *n = makeNode(RenameStmt);
5615                                         n->renameType = OBJECT_FUNCTION;
5616                                         n->object = $3->funcname;
5617                                         n->objarg = $3->funcargs;
5618                                         n->newname = $6;
5619                                         $$ = (Node *)n;
5620                                 }
5621                         | ALTER GROUP_P RoleId RENAME TO RoleId
5622                                 {
5623                                         RenameStmt *n = makeNode(RenameStmt);
5624                                         n->renameType = OBJECT_ROLE;
5625                                         n->subname = $3;
5626                                         n->newname = $6;
5627                                         $$ = (Node *)n;
5628                                 }
5629                         | ALTER opt_procedural LANGUAGE name RENAME TO name
5630                                 {
5631                                         RenameStmt *n = makeNode(RenameStmt);
5632                                         n->renameType = OBJECT_LANGUAGE;
5633                                         n->subname = $4;
5634                                         n->newname = $7;
5635                                         $$ = (Node *)n;
5636                                 }
5637                         | ALTER OPERATOR CLASS any_name USING access_method RENAME TO name
5638                                 {
5639                                         RenameStmt *n = makeNode(RenameStmt);
5640                                         n->renameType = OBJECT_OPCLASS;
5641                                         n->object = $4;
5642                                         n->subname = $6;
5643                                         n->newname = $9;
5644                                         $$ = (Node *)n;
5645                                 }
5646                         | ALTER OPERATOR FAMILY any_name USING access_method RENAME TO name
5647                                 {
5648                                         RenameStmt *n = makeNode(RenameStmt);
5649                                         n->renameType = OBJECT_OPFAMILY;
5650                                         n->object = $4;
5651                                         n->subname = $6;
5652                                         n->newname = $9;
5653                                         $$ = (Node *)n;
5654                                 }
5655                         | ALTER SCHEMA name RENAME TO name
5656                                 {
5657                                         RenameStmt *n = makeNode(RenameStmt);
5658                                         n->renameType = OBJECT_SCHEMA;
5659                                         n->subname = $3;
5660                                         n->newname = $6;
5661                                         $$ = (Node *)n;
5662                                 }
5663                         | ALTER TABLE relation_expr RENAME TO name
5664                                 {
5665                                         RenameStmt *n = makeNode(RenameStmt);
5666                                         n->renameType = OBJECT_TABLE;
5667                                         n->relation = $3;
5668                                         n->subname = NULL;
5669                                         n->newname = $6;
5670                                         $$ = (Node *)n;
5671                                 }
5672                         | ALTER SEQUENCE qualified_name RENAME TO name
5673                                 {
5674                                         RenameStmt *n = makeNode(RenameStmt);
5675                                         n->renameType = OBJECT_SEQUENCE;
5676                                         n->relation = $3;
5677                                         n->subname = NULL;
5678                                         n->newname = $6;
5679                                         $$ = (Node *)n;
5680                                 }
5681                         | ALTER VIEW qualified_name RENAME TO name
5682                                 {
5683                                         RenameStmt *n = makeNode(RenameStmt);
5684                                         n->renameType = OBJECT_VIEW;
5685                                         n->relation = $3;
5686                                         n->subname = NULL;
5687                                         n->newname = $6;
5688                                         $$ = (Node *)n;
5689                                 }
5690                         | ALTER INDEX qualified_name RENAME TO name
5691                                 {
5692                                         RenameStmt *n = makeNode(RenameStmt);
5693                                         n->renameType = OBJECT_INDEX;
5694                                         n->relation = $3;
5695                                         n->subname = NULL;
5696                                         n->newname = $6;
5697                                         $$ = (Node *)n;
5698                                 }
5699                         | ALTER TABLE relation_expr RENAME opt_column name TO name
5700                                 {
5701                                         RenameStmt *n = makeNode(RenameStmt);
5702                                         n->renameType = OBJECT_COLUMN;
5703                                         n->relation = $3;
5704                                         n->subname = $6;
5705                                         n->newname = $8;
5706                                         $$ = (Node *)n;
5707                                 }
5708                         | ALTER TRIGGER name ON qualified_name RENAME TO name
5709                                 {
5710                                         RenameStmt *n = makeNode(RenameStmt);
5711                                         n->renameType = OBJECT_TRIGGER;
5712                                         n->relation = $5;
5713                                         n->subname = $3;
5714                                         n->newname = $8;
5715                                         $$ = (Node *)n;
5716                                 }
5717                         | ALTER ROLE RoleId RENAME TO RoleId
5718                                 {
5719                                         RenameStmt *n = makeNode(RenameStmt);
5720                                         n->renameType = OBJECT_ROLE;
5721                                         n->subname = $3;
5722                                         n->newname = $6;
5723                                         $$ = (Node *)n;
5724                                 }
5725                         | ALTER USER RoleId RENAME TO RoleId
5726                                 {
5727                                         RenameStmt *n = makeNode(RenameStmt);
5728                                         n->renameType = OBJECT_ROLE;
5729                                         n->subname = $3;
5730                                         n->newname = $6;
5731                                         $$ = (Node *)n;
5732                                 }
5733                         | ALTER TABLESPACE name RENAME TO name
5734                                 {
5735                                         RenameStmt *n = makeNode(RenameStmt);
5736                                         n->renameType = OBJECT_TABLESPACE;
5737                                         n->subname = $3;
5738                                         n->newname = $6;
5739                                         $$ = (Node *)n;
5740                                 }
5741                         | ALTER TABLESPACE name SET reloptions
5742                                 {
5743                                         AlterTableSpaceOptionsStmt *n =
5744                                                 makeNode(AlterTableSpaceOptionsStmt);
5745                                         n->tablespacename = $3;
5746                                         n->options = $5;
5747                                         n->isReset = FALSE;
5748                                         $$ = (Node *)n;
5749                                 }
5750                         | ALTER TABLESPACE name RESET reloptions
5751                                 {
5752                                         AlterTableSpaceOptionsStmt *n =
5753                                                 makeNode(AlterTableSpaceOptionsStmt);
5754                                         n->tablespacename = $3;
5755                                         n->options = $5;
5756                                         n->isReset = TRUE;
5757                                         $$ = (Node *)n;
5758                                 }
5759                         | ALTER TEXT_P SEARCH PARSER any_name RENAME TO name
5760                                 {
5761                                         RenameStmt *n = makeNode(RenameStmt);
5762                                         n->renameType = OBJECT_TSPARSER;
5763                                         n->object = $5;
5764                                         n->newname = $8;
5765                                         $$ = (Node *)n;
5766                                 }
5767                         | ALTER TEXT_P SEARCH DICTIONARY any_name RENAME TO name
5768                                 {
5769                                         RenameStmt *n = makeNode(RenameStmt);
5770                                         n->renameType = OBJECT_TSDICTIONARY;
5771                                         n->object = $5;
5772                                         n->newname = $8;
5773                                         $$ = (Node *)n;
5774                                 }
5775                         | ALTER TEXT_P SEARCH TEMPLATE any_name RENAME TO name
5776                                 {
5777                                         RenameStmt *n = makeNode(RenameStmt);
5778                                         n->renameType = OBJECT_TSTEMPLATE;
5779                                         n->object = $5;
5780                                         n->newname = $8;
5781                                         $$ = (Node *)n;
5782                                 }
5783                         | ALTER TEXT_P SEARCH CONFIGURATION any_name RENAME TO name
5784                                 {
5785                                         RenameStmt *n = makeNode(RenameStmt);
5786                                         n->renameType = OBJECT_TSCONFIGURATION;
5787                                         n->object = $5;
5788                                         n->newname = $8;
5789                                         $$ = (Node *)n;
5790                                 }
5791                         | ALTER TYPE_P any_name RENAME TO name
5792                                 {
5793                                         RenameStmt *n = makeNode(RenameStmt);
5794                                         n->renameType = OBJECT_TYPE;
5795                                         n->object = $3;
5796                                         n->newname = $6;
5797                                         $$ = (Node *)n;
5798                                 }
5799                 ;
5800
5801 opt_column: COLUMN                                                                      { $$ = COLUMN; }
5802                         | /*EMPTY*/                                                             { $$ = 0; }
5803                 ;
5804
5805 opt_set_data: SET DATA_P                                                                        { $$ = 1; }
5806                         | /*EMPTY*/                                                             { $$ = 0; }
5807                 ;
5808
5809 /*****************************************************************************
5810  *
5811  * ALTER THING name SET SCHEMA name
5812  *
5813  *****************************************************************************/
5814
5815 AlterObjectSchemaStmt:
5816                         ALTER AGGREGATE func_name aggr_args SET SCHEMA name
5817                                 {
5818                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5819                                         n->objectType = OBJECT_AGGREGATE;
5820                                         n->object = $3;
5821                                         n->objarg = $4;
5822                                         n->newschema = $7;
5823                                         $$ = (Node *)n;
5824                                 }
5825                         | ALTER DOMAIN_P any_name SET SCHEMA name
5826                                 {
5827                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5828                                         n->objectType = OBJECT_DOMAIN;
5829                                         n->object = $3;
5830                                         n->newschema = $6;
5831                                         $$ = (Node *)n;
5832                                 }
5833                         | ALTER FUNCTION function_with_argtypes SET SCHEMA name
5834                                 {
5835                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5836                                         n->objectType = OBJECT_FUNCTION;
5837                                         n->object = $3->funcname;
5838                                         n->objarg = $3->funcargs;
5839                                         n->newschema = $6;
5840                                         $$ = (Node *)n;
5841                                 }
5842                         | ALTER TABLE relation_expr SET SCHEMA name
5843                                 {
5844                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5845                                         n->objectType = OBJECT_TABLE;
5846                                         n->relation = $3;
5847                                         n->newschema = $6;
5848                                         $$ = (Node *)n;
5849                                 }
5850                         | ALTER SEQUENCE qualified_name SET SCHEMA name
5851                                 {
5852                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5853                                         n->objectType = OBJECT_SEQUENCE;
5854                                         n->relation = $3;
5855                                         n->newschema = $6;
5856                                         $$ = (Node *)n;
5857                                 }
5858                         | ALTER VIEW qualified_name SET SCHEMA name
5859                                 {
5860                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5861                                         n->objectType = OBJECT_VIEW;
5862                                         n->relation = $3;
5863                                         n->newschema = $6;
5864                                         $$ = (Node *)n;
5865                                 }
5866                         | ALTER TYPE_P any_name SET SCHEMA name
5867                                 {
5868                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5869                                         n->objectType = OBJECT_TYPE;
5870                                         n->object = $3;
5871                                         n->newschema = $6;
5872                                         $$ = (Node *)n;
5873                                 }
5874                 ;
5875
5876 /*****************************************************************************
5877  *
5878  * ALTER THING name OWNER TO newname
5879  *
5880  *****************************************************************************/
5881
5882 AlterOwnerStmt: ALTER AGGREGATE func_name aggr_args OWNER TO RoleId
5883                                 {
5884                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5885                                         n->objectType = OBJECT_AGGREGATE;
5886                                         n->object = $3;
5887                                         n->objarg = $4;
5888                                         n->newowner = $7;
5889                                         $$ = (Node *)n;
5890                                 }
5891                         | ALTER CONVERSION_P any_name OWNER TO RoleId
5892                                 {
5893                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5894                                         n->objectType = OBJECT_CONVERSION;
5895                                         n->object = $3;
5896                                         n->newowner = $6;
5897                                         $$ = (Node *)n;
5898                                 }
5899                         | ALTER DATABASE database_name OWNER TO RoleId
5900                                 {
5901                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5902                                         n->objectType = OBJECT_DATABASE;
5903                                         n->object = list_make1(makeString($3));
5904                                         n->newowner = $6;
5905                                         $$ = (Node *)n;
5906                                 }
5907                         | ALTER DOMAIN_P any_name OWNER TO RoleId
5908                                 {
5909                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5910                                         n->objectType = OBJECT_DOMAIN;
5911                                         n->object = $3;
5912                                         n->newowner = $6;
5913                                         $$ = (Node *)n;
5914                                 }
5915                         | ALTER FUNCTION function_with_argtypes OWNER TO RoleId
5916                                 {
5917                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5918                                         n->objectType = OBJECT_FUNCTION;
5919                                         n->object = $3->funcname;
5920                                         n->objarg = $3->funcargs;
5921                                         n->newowner = $6;
5922                                         $$ = (Node *)n;
5923                                 }
5924                         | ALTER opt_procedural LANGUAGE name OWNER TO RoleId
5925                                 {
5926                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5927                                         n->objectType = OBJECT_LANGUAGE;
5928                                         n->object = list_make1(makeString($4));
5929                                         n->newowner = $7;
5930                                         $$ = (Node *)n;
5931                                 }
5932                         | ALTER LARGE_P OBJECT_P Iconst OWNER TO RoleId
5933                                 {
5934                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5935                                         n->objectType = OBJECT_LARGEOBJECT;
5936                                         n->object = list_make1(makeInteger($4));
5937                                         n->newowner = $7;
5938                                         $$ = (Node *)n;
5939                                 }
5940                         | ALTER OPERATOR any_operator oper_argtypes OWNER TO RoleId
5941                                 {
5942                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5943                                         n->objectType = OBJECT_OPERATOR;
5944                                         n->object = $3;
5945                                         n->objarg = $4;
5946                                         n->newowner = $7;
5947                                         $$ = (Node *)n;
5948                                 }
5949                         | ALTER OPERATOR CLASS any_name USING access_method OWNER TO RoleId
5950                                 {
5951                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5952                                         n->objectType = OBJECT_OPCLASS;
5953                                         n->object = $4;
5954                                         n->addname = $6;
5955                                         n->newowner = $9;
5956                                         $$ = (Node *)n;
5957                                 }
5958                         | ALTER OPERATOR FAMILY any_name USING access_method OWNER TO RoleId
5959                                 {
5960                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5961                                         n->objectType = OBJECT_OPFAMILY;
5962                                         n->object = $4;
5963                                         n->addname = $6;
5964                                         n->newowner = $9;
5965                                         $$ = (Node *)n;
5966                                 }
5967                         | ALTER SCHEMA name OWNER TO RoleId
5968                                 {
5969                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5970                                         n->objectType = OBJECT_SCHEMA;
5971                                         n->object = list_make1(makeString($3));
5972                                         n->newowner = $6;
5973                                         $$ = (Node *)n;
5974                                 }
5975                         | ALTER TYPE_P any_name OWNER TO RoleId
5976                                 {
5977                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5978                                         n->objectType = OBJECT_TYPE;
5979                                         n->object = $3;
5980                                         n->newowner = $6;
5981                                         $$ = (Node *)n;
5982                                 }
5983                         | ALTER TABLESPACE name OWNER TO RoleId
5984                                 {
5985                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5986                                         n->objectType = OBJECT_TABLESPACE;
5987                                         n->object = list_make1(makeString($3));
5988                                         n->newowner = $6;
5989                                         $$ = (Node *)n;
5990                                 }
5991                         | ALTER TEXT_P SEARCH DICTIONARY any_name OWNER TO RoleId
5992                                 {
5993                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5994                                         n->objectType = OBJECT_TSDICTIONARY;
5995                                         n->object = $5;
5996                                         n->newowner = $8;
5997                                         $$ = (Node *)n;
5998                                 }
5999                         | ALTER TEXT_P SEARCH CONFIGURATION any_name OWNER TO RoleId
6000                                 {
6001                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
6002                                         n->objectType = OBJECT_TSCONFIGURATION;
6003                                         n->object = $5;
6004                                         n->newowner = $8;
6005                                         $$ = (Node *)n;
6006                                 }
6007                         | ALTER FOREIGN DATA_P WRAPPER name OWNER TO RoleId
6008                                 {
6009                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
6010                                         n->objectType = OBJECT_FDW;
6011                                         n->object = list_make1(makeString($5));
6012                                         n->newowner = $8;
6013                                         $$ = (Node *)n;
6014                                 }
6015                         | ALTER SERVER name OWNER TO RoleId
6016                                 {
6017                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
6018                                         n->objectType = OBJECT_FOREIGN_SERVER;
6019                                         n->object = list_make1(makeString($3));
6020                                         n->newowner = $6;
6021                                         $$ = (Node *)n;
6022                                 }
6023                 ;
6024
6025
6026 /*****************************************************************************
6027  *
6028  *              QUERY:  Define Rewrite Rule
6029  *
6030  *****************************************************************************/
6031
6032 RuleStmt:       CREATE opt_or_replace RULE name AS
6033                         ON event TO qualified_name where_clause
6034                         DO opt_instead RuleActionList
6035                                 {
6036                                         RuleStmt *n = makeNode(RuleStmt);
6037                                         n->replace = $2;
6038                                         n->relation = $9;
6039                                         n->rulename = $4;
6040                                         n->whereClause = $10;
6041                                         n->event = $7;
6042                                         n->instead = $12;
6043                                         n->actions = $13;
6044                                         $$ = (Node *)n;
6045                                 }
6046                 ;
6047
6048 RuleActionList:
6049                         NOTHING                                                                 { $$ = NIL; }
6050                         | RuleActionStmt                                                { $$ = list_make1($1); }
6051                         | '(' RuleActionMulti ')'                               { $$ = $2; }
6052                 ;
6053
6054 /* the thrashing around here is to discard "empty" statements... */
6055 RuleActionMulti:
6056                         RuleActionMulti ';' RuleActionStmtOrEmpty
6057                                 { if ($3 != NULL)
6058                                         $$ = lappend($1, $3);
6059                                   else
6060                                         $$ = $1;
6061                                 }
6062                         | RuleActionStmtOrEmpty
6063                                 { if ($1 != NULL)
6064                                         $$ = list_make1($1);
6065                                   else
6066                                         $$ = NIL;
6067                                 }
6068                 ;
6069
6070 RuleActionStmt:
6071                         SelectStmt
6072                         | InsertStmt
6073                         | UpdateStmt
6074                         | DeleteStmt
6075                         | NotifyStmt
6076                 ;
6077
6078 RuleActionStmtOrEmpty:
6079                         RuleActionStmt                                                  { $$ = $1; }
6080                         |       /*EMPTY*/                                                       { $$ = NULL; }
6081                 ;
6082
6083 event:          SELECT                                                                  { $$ = CMD_SELECT; }
6084                         | UPDATE                                                                { $$ = CMD_UPDATE; }
6085                         | DELETE_P                                                              { $$ = CMD_DELETE; }
6086                         | INSERT                                                                { $$ = CMD_INSERT; }
6087                  ;
6088
6089 opt_instead:
6090                         INSTEAD                                                                 { $$ = TRUE; }
6091                         | ALSO                                                                  { $$ = FALSE; }
6092                         | /*EMPTY*/                                                             { $$ = FALSE; }
6093                 ;
6094
6095
6096 DropRuleStmt:
6097                         DROP RULE name ON qualified_name opt_drop_behavior
6098                                 {
6099                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
6100                                         n->relation = $5;
6101                                         n->property = $3;
6102                                         n->behavior = $6;
6103                                         n->removeType = OBJECT_RULE;
6104                                         n->missing_ok = false;
6105                                         $$ = (Node *) n;
6106                                 }
6107                         | DROP RULE IF_P EXISTS name ON qualified_name opt_drop_behavior
6108                                 {
6109                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
6110                                         n->relation = $7;
6111                                         n->property = $5;
6112                                         n->behavior = $8;
6113                                         n->removeType = OBJECT_RULE;
6114                                         n->missing_ok = true;
6115                                         $$ = (Node *) n;
6116                                 }
6117                 ;
6118
6119
6120 /*****************************************************************************
6121  *
6122  *              QUERY:
6123  *                              NOTIFY <identifier> can appear both in rule bodies and
6124  *                              as a query-level command
6125  *
6126  *****************************************************************************/
6127
6128 NotifyStmt: NOTIFY ColId notify_payload
6129                                 {
6130                                         NotifyStmt *n = makeNode(NotifyStmt);
6131                                         n->conditionname = $2;
6132                                         n->payload = $3;
6133                                         $$ = (Node *)n;
6134                                 }
6135                 ;
6136
6137 notify_payload:
6138                         ',' Sconst                                                      { $$ = $2; }
6139                         | /*EMPTY*/                                                     { $$ = NULL; }
6140                 ;
6141
6142 ListenStmt: LISTEN ColId
6143                                 {
6144                                         ListenStmt *n = makeNode(ListenStmt);
6145                                         n->conditionname = $2;
6146                                         $$ = (Node *)n;
6147                                 }
6148                 ;
6149
6150 UnlistenStmt:
6151                         UNLISTEN ColId
6152                                 {
6153                                         UnlistenStmt *n = makeNode(UnlistenStmt);
6154                                         n->conditionname = $2;
6155                                         $$ = (Node *)n;
6156                                 }
6157                         | UNLISTEN '*'
6158                                 {
6159                                         UnlistenStmt *n = makeNode(UnlistenStmt);
6160                                         n->conditionname = NULL;
6161                                         $$ = (Node *)n;
6162                                 }
6163                 ;
6164
6165
6166 /*****************************************************************************
6167  *
6168  *              Transactions:
6169  *
6170  *              BEGIN / COMMIT / ROLLBACK
6171  *              (also older versions END / ABORT)
6172  *
6173  *****************************************************************************/
6174
6175 TransactionStmt:
6176                         ABORT_P opt_transaction
6177                                 {
6178                                         TransactionStmt *n = makeNode(TransactionStmt);
6179                                         n->kind = TRANS_STMT_ROLLBACK;
6180                                         n->options = NIL;
6181                                         $$ = (Node *)n;
6182                                 }
6183                         | BEGIN_P opt_transaction transaction_mode_list_or_empty
6184                                 {
6185                                         TransactionStmt *n = makeNode(TransactionStmt);
6186                                         n->kind = TRANS_STMT_BEGIN;
6187                                         n->options = $3;
6188                                         $$ = (Node *)n;
6189                                 }
6190                         | START TRANSACTION transaction_mode_list_or_empty
6191                                 {
6192                                         TransactionStmt *n = makeNode(TransactionStmt);
6193                                         n->kind = TRANS_STMT_START;
6194                                         n->options = $3;
6195                                         $$ = (Node *)n;
6196                                 }
6197                         | COMMIT opt_transaction
6198                                 {
6199                                         TransactionStmt *n = makeNode(TransactionStmt);
6200                                         n->kind = TRANS_STMT_COMMIT;
6201                                         n->options = NIL;
6202                                         $$ = (Node *)n;
6203                                 }
6204                         | END_P opt_transaction
6205                                 {
6206                                         TransactionStmt *n = makeNode(TransactionStmt);
6207                                         n->kind = TRANS_STMT_COMMIT;
6208                                         n->options = NIL;
6209                                         $$ = (Node *)n;
6210                                 }
6211                         | ROLLBACK opt_transaction
6212                                 {
6213                                         TransactionStmt *n = makeNode(TransactionStmt);
6214                                         n->kind = TRANS_STMT_ROLLBACK;
6215                                         n->options = NIL;
6216                                         $$ = (Node *)n;
6217                                 }
6218                         | SAVEPOINT ColId
6219                                 {
6220                                         TransactionStmt *n = makeNode(TransactionStmt);
6221                                         n->kind = TRANS_STMT_SAVEPOINT;
6222                                         n->options = list_make1(makeDefElem("savepoint_name",
6223                                                                                                                 (Node *)makeString($2)));
6224                                         $$ = (Node *)n;
6225                                 }
6226                         | RELEASE SAVEPOINT ColId
6227                                 {
6228                                         TransactionStmt *n = makeNode(TransactionStmt);
6229                                         n->kind = TRANS_STMT_RELEASE;
6230                                         n->options = list_make1(makeDefElem("savepoint_name",
6231                                                                                                                 (Node *)makeString($3)));
6232                                         $$ = (Node *)n;
6233                                 }
6234                         | RELEASE ColId
6235                                 {
6236                                         TransactionStmt *n = makeNode(TransactionStmt);
6237                                         n->kind = TRANS_STMT_RELEASE;
6238                                         n->options = list_make1(makeDefElem("savepoint_name",
6239                                                                                                                 (Node *)makeString($2)));
6240                                         $$ = (Node *)n;
6241                                 }
6242                         | ROLLBACK opt_transaction TO SAVEPOINT ColId
6243                                 {
6244                                         TransactionStmt *n = makeNode(TransactionStmt);
6245                                         n->kind = TRANS_STMT_ROLLBACK_TO;
6246                                         n->options = list_make1(makeDefElem("savepoint_name",
6247                                                                                                                 (Node *)makeString($5)));
6248                                         $$ = (Node *)n;
6249                                 }
6250                         | ROLLBACK opt_transaction TO ColId
6251                                 {
6252                                         TransactionStmt *n = makeNode(TransactionStmt);
6253                                         n->kind = TRANS_STMT_ROLLBACK_TO;
6254                                         n->options = list_make1(makeDefElem("savepoint_name",
6255                                                                                                                 (Node *)makeString($4)));
6256                                         $$ = (Node *)n;
6257                                 }
6258                         | PREPARE TRANSACTION Sconst
6259                                 {
6260                                         TransactionStmt *n = makeNode(TransactionStmt);
6261                                         n->kind = TRANS_STMT_PREPARE;
6262                                         n->gid = $3;
6263                                         $$ = (Node *)n;
6264                                 }
6265                         | COMMIT PREPARED Sconst
6266                                 {
6267                                         TransactionStmt *n = makeNode(TransactionStmt);
6268                                         n->kind = TRANS_STMT_COMMIT_PREPARED;
6269                                         n->gid = $3;
6270                                         $$ = (Node *)n;
6271                                 }
6272                         | ROLLBACK PREPARED Sconst
6273                                 {
6274                                         TransactionStmt *n = makeNode(TransactionStmt);
6275                                         n->kind = TRANS_STMT_ROLLBACK_PREPARED;
6276                                         n->gid = $3;
6277                                         $$ = (Node *)n;
6278                                 }
6279                 ;
6280
6281 opt_transaction:        WORK                                                    {}
6282                         | TRANSACTION                                                   {}
6283                         | /*EMPTY*/                                                             {}
6284                 ;
6285
6286 transaction_mode_item:
6287                         ISOLATION LEVEL iso_level
6288                                         { $$ = makeDefElem("transaction_isolation",
6289                                                                            makeStringConst($3, @3)); }
6290                         | READ ONLY
6291                                         { $$ = makeDefElem("transaction_read_only",
6292                                                                            makeIntConst(TRUE, @1)); }
6293                         | READ WRITE
6294                                         { $$ = makeDefElem("transaction_read_only",
6295                                                                            makeIntConst(FALSE, @1)); }
6296                 ;
6297
6298 /* Syntax with commas is SQL-spec, without commas is Postgres historical */
6299 transaction_mode_list:
6300                         transaction_mode_item
6301                                         { $$ = list_make1($1); }
6302                         | transaction_mode_list ',' transaction_mode_item
6303                                         { $$ = lappend($1, $3); }
6304                         | transaction_mode_list transaction_mode_item
6305                                         { $$ = lappend($1, $2); }
6306                 ;
6307
6308 transaction_mode_list_or_empty:
6309                         transaction_mode_list
6310                         | /* EMPTY */
6311                                         { $$ = NIL; }
6312                 ;
6313
6314
6315 /*****************************************************************************
6316  *
6317  *      QUERY:
6318  *              CREATE [ OR REPLACE ] [ TEMP ] VIEW <viewname> '('target-list ')'
6319  *                      AS <query> [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
6320  *
6321  *****************************************************************************/
6322
6323 ViewStmt: CREATE OptTemp VIEW qualified_name opt_column_list
6324                                 AS SelectStmt opt_check_option
6325                                 {
6326                                         ViewStmt *n = makeNode(ViewStmt);
6327                                         n->view = $4;
6328                                         n->view->istemp = $2;
6329                                         n->aliases = $5;
6330                                         n->query = $7;
6331                                         n->replace = false;
6332                                         $$ = (Node *) n;
6333                                 }
6334                 | CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list
6335                                 AS SelectStmt opt_check_option
6336                                 {
6337                                         ViewStmt *n = makeNode(ViewStmt);
6338                                         n->view = $6;
6339                                         n->view->istemp = $4;
6340                                         n->aliases = $7;
6341                                         n->query = $9;
6342                                         n->replace = true;
6343                                         $$ = (Node *) n;
6344                                 }
6345                 ;
6346
6347 opt_check_option:
6348                 WITH CHECK OPTION
6349                                 {
6350                                         ereport(ERROR,
6351                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6352                                                          errmsg("WITH CHECK OPTION is not implemented")));
6353                                 }
6354                 | WITH CASCADED CHECK OPTION
6355                                 {
6356                                         ereport(ERROR,
6357                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6358                                                          errmsg("WITH CHECK OPTION is not implemented")));
6359                                 }
6360                 | WITH LOCAL CHECK OPTION
6361                                 {
6362                                         ereport(ERROR,
6363                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6364                                                          errmsg("WITH CHECK OPTION is not implemented")));
6365                                 }
6366                 | /* EMPTY */                                                   { $$ = NIL; }
6367                 ;
6368
6369 /*****************************************************************************
6370  *
6371  *              QUERY:
6372  *                              LOAD "filename"
6373  *
6374  *****************************************************************************/
6375
6376 LoadStmt:       LOAD file_name
6377                                 {
6378                                         LoadStmt *n = makeNode(LoadStmt);
6379                                         n->filename = $2;
6380                                         $$ = (Node *)n;
6381                                 }
6382                 ;
6383
6384
6385 /*****************************************************************************
6386  *
6387  *              CREATE DATABASE
6388  *
6389  *****************************************************************************/
6390
6391 CreatedbStmt:
6392                         CREATE DATABASE database_name opt_with createdb_opt_list
6393                                 {
6394                                         CreatedbStmt *n = makeNode(CreatedbStmt);
6395                                         n->dbname = $3;
6396                                         n->options = $5;
6397                                         $$ = (Node *)n;
6398                                 }
6399                 ;
6400
6401 createdb_opt_list:
6402                         createdb_opt_list createdb_opt_item             { $$ = lappend($1, $2); }
6403                         | /* EMPTY */                                                   { $$ = NIL; }
6404                 ;
6405
6406 createdb_opt_item:
6407                         TABLESPACE opt_equal name
6408                                 {
6409                                         $$ = makeDefElem("tablespace", (Node *)makeString($3));
6410                                 }
6411                         | TABLESPACE opt_equal DEFAULT
6412                                 {
6413                                         $$ = makeDefElem("tablespace", NULL);
6414                                 }
6415                         | LOCATION opt_equal Sconst
6416                                 {
6417                                         $$ = makeDefElem("location", (Node *)makeString($3));
6418                                 }
6419                         | LOCATION opt_equal DEFAULT
6420                                 {
6421                                         $$ = makeDefElem("location", NULL);
6422                                 }
6423                         | TEMPLATE opt_equal name
6424                                 {
6425                                         $$ = makeDefElem("template", (Node *)makeString($3));
6426                                 }
6427                         | TEMPLATE opt_equal DEFAULT
6428                                 {
6429                                         $$ = makeDefElem("template", NULL);
6430                                 }
6431                         | ENCODING opt_equal Sconst
6432                                 {
6433                                         $$ = makeDefElem("encoding", (Node *)makeString($3));
6434                                 }
6435                         | ENCODING opt_equal Iconst
6436                                 {
6437                                         $$ = makeDefElem("encoding", (Node *)makeInteger($3));
6438                                 }
6439                         | ENCODING opt_equal DEFAULT
6440                                 {
6441                                         $$ = makeDefElem("encoding", NULL);
6442                                 }
6443                         | LC_COLLATE_P opt_equal Sconst
6444                                 {
6445                                         $$ = makeDefElem("lc_collate", (Node *)makeString($3));
6446                                 }
6447                         | LC_COLLATE_P opt_equal DEFAULT
6448                                 {
6449                                         $$ = makeDefElem("lc_collate", NULL);
6450                                 }
6451                         | LC_CTYPE_P opt_equal Sconst
6452                                 {
6453                                         $$ = makeDefElem("lc_ctype", (Node *)makeString($3));
6454                                 }
6455                         | LC_CTYPE_P opt_equal DEFAULT
6456                                 {
6457                                         $$ = makeDefElem("lc_ctype", NULL);
6458                                 }
6459                         | CONNECTION LIMIT opt_equal SignedIconst
6460                                 {
6461                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($4));
6462                                 }
6463                         | OWNER opt_equal name
6464                                 {
6465                                         $$ = makeDefElem("owner", (Node *)makeString($3));
6466                                 }
6467                         | OWNER opt_equal DEFAULT
6468                                 {
6469                                         $$ = makeDefElem("owner", NULL);
6470                                 }
6471                 ;
6472
6473 /*
6474  *      Though the equals sign doesn't match other WITH options, pg_dump uses
6475  *      equals for backward compatibility, and it doesn't seem worth removing it.
6476  */
6477 opt_equal:      '='                                                                             {}
6478                         | /*EMPTY*/                                                             {}
6479                 ;
6480
6481
6482 /*****************************************************************************
6483  *
6484  *              ALTER DATABASE
6485  *
6486  *****************************************************************************/
6487
6488 AlterDatabaseStmt:
6489                         ALTER DATABASE database_name opt_with alterdb_opt_list
6490                                  {
6491                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
6492                                         n->dbname = $3;
6493                                         n->options = $5;
6494                                         $$ = (Node *)n;
6495                                  }
6496                         | ALTER DATABASE database_name SET TABLESPACE name
6497                                  {
6498                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
6499                                         n->dbname = $3;
6500                                         n->options = list_make1(makeDefElem("tablespace",
6501                                                                                                         (Node *)makeString($6)));
6502                                         $$ = (Node *)n;
6503                                  }
6504                 ;
6505
6506 AlterDatabaseSetStmt:
6507                         ALTER DATABASE database_name SetResetClause
6508                                 {
6509                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
6510                                         n->dbname = $3;
6511                                         n->setstmt = $4;
6512                                         $$ = (Node *)n;
6513                                 }
6514                 ;
6515
6516
6517 alterdb_opt_list:
6518                         alterdb_opt_list alterdb_opt_item               { $$ = lappend($1, $2); }
6519                         | /* EMPTY */                                                   { $$ = NIL; }
6520                 ;
6521
6522 alterdb_opt_item:
6523                         CONNECTION LIMIT opt_equal SignedIconst
6524                                 {
6525                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($4));
6526                                 }
6527                 ;
6528
6529
6530 /*****************************************************************************
6531  *
6532  *              DROP DATABASE [ IF EXISTS ]
6533  *
6534  * This is implicitly CASCADE, no need for drop behavior
6535  *****************************************************************************/
6536
6537 DropdbStmt: DROP DATABASE database_name
6538                                 {
6539                                         DropdbStmt *n = makeNode(DropdbStmt);
6540                                         n->dbname = $3;
6541                                         n->missing_ok = FALSE;
6542                                         $$ = (Node *)n;
6543                                 }
6544                         | DROP DATABASE IF_P EXISTS database_name
6545                                 {
6546                                         DropdbStmt *n = makeNode(DropdbStmt);
6547                                         n->dbname = $5;
6548                                         n->missing_ok = TRUE;
6549                                         $$ = (Node *)n;
6550                                 }
6551                 ;
6552
6553
6554 /*****************************************************************************
6555  *
6556  * Manipulate a domain
6557  *
6558  *****************************************************************************/
6559
6560 CreateDomainStmt:
6561                         CREATE DOMAIN_P any_name opt_as Typename ColQualList
6562                                 {
6563                                         CreateDomainStmt *n = makeNode(CreateDomainStmt);
6564                                         n->domainname = $3;
6565                                         n->typeName = $5;
6566                                         n->constraints = $6;
6567                                         $$ = (Node *)n;
6568                                 }
6569                 ;
6570
6571 AlterDomainStmt:
6572                         /* ALTER DOMAIN <domain> {SET DEFAULT <expr>|DROP DEFAULT} */
6573                         ALTER DOMAIN_P any_name alter_column_default
6574                                 {
6575                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6576                                         n->subtype = 'T';
6577                                         n->typeName = $3;
6578                                         n->def = $4;
6579                                         $$ = (Node *)n;
6580                                 }
6581                         /* ALTER DOMAIN <domain> DROP NOT NULL */
6582                         | ALTER DOMAIN_P any_name DROP NOT NULL_P
6583                                 {
6584                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6585                                         n->subtype = 'N';
6586                                         n->typeName = $3;
6587                                         $$ = (Node *)n;
6588                                 }
6589                         /* ALTER DOMAIN <domain> SET NOT NULL */
6590                         | ALTER DOMAIN_P any_name SET NOT NULL_P
6591                                 {
6592                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6593                                         n->subtype = 'O';
6594                                         n->typeName = $3;
6595                                         $$ = (Node *)n;
6596                                 }
6597                         /* ALTER DOMAIN <domain> ADD CONSTRAINT ... */
6598                         | ALTER DOMAIN_P any_name ADD_P TableConstraint
6599                                 {
6600                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6601                                         n->subtype = 'C';
6602                                         n->typeName = $3;
6603                                         n->def = $5;
6604                                         $$ = (Node *)n;
6605                                 }
6606                         /* ALTER DOMAIN <domain> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
6607                         | ALTER DOMAIN_P any_name DROP CONSTRAINT name opt_drop_behavior
6608                                 {
6609                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6610                                         n->subtype = 'X';
6611                                         n->typeName = $3;
6612                                         n->name = $6;
6613                                         n->behavior = $7;
6614                                         $$ = (Node *)n;
6615                                 }
6616                         ;
6617
6618 opt_as:         AS                                                                              {}
6619                         | /* EMPTY */                                                   {}
6620                 ;
6621
6622
6623 /*****************************************************************************
6624  *
6625  * Manipulate a text search dictionary or configuration
6626  *
6627  *****************************************************************************/
6628
6629 AlterTSDictionaryStmt:
6630                         ALTER TEXT_P SEARCH DICTIONARY any_name definition
6631                                 {
6632                                         AlterTSDictionaryStmt *n = makeNode(AlterTSDictionaryStmt);
6633                                         n->dictname = $5;
6634                                         n->options = $6;
6635                                         $$ = (Node *)n;
6636                                 }
6637                 ;
6638
6639 AlterTSConfigurationStmt:
6640                         ALTER TEXT_P SEARCH CONFIGURATION any_name ADD_P MAPPING FOR name_list WITH any_name_list
6641                                 {
6642                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6643                                         n->cfgname = $5;
6644                                         n->tokentype = $9;
6645                                         n->dicts = $11;
6646                                         n->override = false;
6647                                         n->replace = false;
6648                                         $$ = (Node*)n;
6649                                 }
6650                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list WITH any_name_list
6651                                 {
6652                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6653                                         n->cfgname = $5;
6654                                         n->tokentype = $9;
6655                                         n->dicts = $11;
6656                                         n->override = true;
6657                                         n->replace = false;
6658                                         $$ = (Node*)n;
6659                                 }
6660                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING REPLACE any_name WITH any_name
6661                                 {
6662                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6663                                         n->cfgname = $5;
6664                                         n->tokentype = NIL;
6665                                         n->dicts = list_make2($9,$11);
6666                                         n->override = false;
6667                                         n->replace = true;
6668                                         $$ = (Node*)n;
6669                                 }
6670                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list REPLACE any_name WITH any_name
6671                                 {
6672                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6673                                         n->cfgname = $5;
6674                                         n->tokentype = $9;
6675                                         n->dicts = list_make2($11,$13);
6676                                         n->override = false;
6677                                         n->replace = true;
6678                                         $$ = (Node*)n;
6679                                 }
6680                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING FOR name_list
6681                                 {
6682                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6683                                         n->cfgname = $5;
6684                                         n->tokentype = $9;
6685                                         n->missing_ok = false;
6686                                         $$ = (Node*)n;
6687                                 }
6688                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING IF_P EXISTS FOR name_list
6689                                 {
6690                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6691                                         n->cfgname = $5;
6692                                         n->tokentype = $11;
6693                                         n->missing_ok = true;
6694                                         $$ = (Node*)n;
6695                                 }
6696                 ;
6697
6698
6699 /*****************************************************************************
6700  *
6701  * Manipulate a conversion
6702  *
6703  *              CREATE [DEFAULT] CONVERSION <conversion_name>
6704  *              FOR <encoding_name> TO <encoding_name> FROM <func_name>
6705  *
6706  *****************************************************************************/
6707
6708 CreateConversionStmt:
6709                         CREATE opt_default CONVERSION_P any_name FOR Sconst
6710                         TO Sconst FROM any_name
6711                         {
6712                           CreateConversionStmt *n = makeNode(CreateConversionStmt);
6713                           n->conversion_name = $4;
6714                           n->for_encoding_name = $6;
6715                           n->to_encoding_name = $8;
6716                           n->func_name = $10;
6717                           n->def = $2;
6718                           $$ = (Node *)n;
6719                         }
6720                 ;
6721
6722 /*****************************************************************************
6723  *
6724  *              QUERY:
6725  *                              CLUSTER [VERBOSE] <qualified_name> [ USING <index_name> ]
6726  *                              CLUSTER [VERBOSE]
6727  *                              CLUSTER [VERBOSE] <index_name> ON <qualified_name> (for pre-8.3)
6728  *
6729  *****************************************************************************/
6730
6731 ClusterStmt:
6732                         CLUSTER opt_verbose qualified_name cluster_index_specification
6733                                 {
6734                                ClusterStmt *n = makeNode(ClusterStmt);
6735                                    n->relation = $3;
6736                                    n->indexname = $4;
6737                                    n->verbose = $2;
6738                                    $$ = (Node*)n;
6739                                 }
6740                         | CLUSTER opt_verbose
6741                             {
6742                                    ClusterStmt *n = makeNode(ClusterStmt);
6743                                    n->relation = NULL;
6744                                    n->indexname = NULL;
6745                                    n->verbose = $2;
6746                                    $$ = (Node*)n;
6747                                 }
6748                         /* kept for pre-8.3 compatibility */
6749                         | CLUSTER opt_verbose index_name ON qualified_name
6750                                 {
6751                                    ClusterStmt *n = makeNode(ClusterStmt);
6752                                    n->relation = $5;
6753                                    n->indexname = $3;
6754                                    n->verbose = $2;
6755                                    $$ = (Node*)n;
6756                                 }
6757                 ;
6758
6759 cluster_index_specification:
6760                         USING index_name                { $$ = $2; }
6761                         | /*EMPTY*/                             { $$ = NULL; }
6762                 ;
6763
6764
6765 /*****************************************************************************
6766  *
6767  *              QUERY:
6768  *                              VACUUM
6769  *                              ANALYZE
6770  *
6771  *****************************************************************************/
6772
6773 VacuumStmt: VACUUM opt_full opt_freeze opt_verbose
6774                                 {
6775                                         VacuumStmt *n = makeNode(VacuumStmt);
6776                                         n->options = VACOPT_VACUUM;
6777                                         if ($2)
6778                                                 n->options |= VACOPT_FULL;
6779                                         if ($4)
6780                                                 n->options |= VACOPT_VERBOSE;
6781                                         n->freeze_min_age = $3 ? 0 : -1;
6782                                         n->freeze_table_age = $3 ? 0 : -1;
6783                                         n->relation = NULL;
6784                                         n->va_cols = NIL;
6785                                         $$ = (Node *)n;
6786                                 }
6787                         | VACUUM opt_full opt_freeze opt_verbose qualified_name
6788                                 {
6789                                         VacuumStmt *n = makeNode(VacuumStmt);
6790                                         n->options = VACOPT_VACUUM;
6791                                         if ($2)
6792                                                 n->options |= VACOPT_FULL;
6793                                         if ($4)
6794                                                 n->options |= VACOPT_VERBOSE;
6795                                         n->freeze_min_age = $3 ? 0 : -1;
6796                                         n->freeze_table_age = $3 ? 0 : -1;
6797                                         n->relation = $5;
6798                                         n->va_cols = NIL;
6799                                         $$ = (Node *)n;
6800                                 }
6801                         | VACUUM opt_full opt_freeze opt_verbose AnalyzeStmt
6802                                 {
6803                                         VacuumStmt *n = (VacuumStmt *) $5;
6804                                         n->options |= VACOPT_VACUUM;
6805                                         if ($2)
6806                                                 n->options |= VACOPT_FULL;
6807                                         if ($4)
6808                                                 n->options |= VACOPT_VERBOSE;
6809                                         n->freeze_min_age = $3 ? 0 : -1;
6810                                         n->freeze_table_age = $3 ? 0 : -1;
6811                                         $$ = (Node *)n;
6812                                 }
6813                         | VACUUM '(' vacuum_option_list ')'
6814                                 {
6815                                         VacuumStmt *n = makeNode(VacuumStmt);
6816                                         n->options = VACOPT_VACUUM | $3;
6817                                         if (n->options & VACOPT_FREEZE)
6818                                                 n->freeze_min_age = n->freeze_table_age = 0;
6819                                         else
6820                                                 n->freeze_min_age = n->freeze_table_age = -1;
6821                                         n->relation = NULL;
6822                                         n->va_cols = NIL;
6823                                         $$ = (Node *) n;
6824                                 }
6825                         | VACUUM '(' vacuum_option_list ')' qualified_name opt_name_list
6826                                 {
6827                                         VacuumStmt *n = makeNode(VacuumStmt);
6828                                         n->options = VACOPT_VACUUM | $3;
6829                                         if (n->options & VACOPT_FREEZE)
6830                                                 n->freeze_min_age = n->freeze_table_age = 0;
6831                                         else
6832                                                 n->freeze_min_age = n->freeze_table_age = -1;
6833                                         n->relation = $5;
6834                                         n->va_cols = $6;
6835                                         if (n->va_cols != NIL)  /* implies analyze */
6836                                                 n->options |= VACOPT_ANALYZE;
6837                                         $$ = (Node *) n;
6838                                 }
6839                 ;
6840
6841 vacuum_option_list:
6842                         vacuum_option_elem                                                              { $$ = $1; }
6843                         | vacuum_option_list ',' vacuum_option_elem             { $$ = $1 | $3; }
6844                 ;
6845
6846 vacuum_option_elem:
6847                         analyze_keyword         { $$ = VACOPT_ANALYZE; }
6848                         | VERBOSE                       { $$ = VACOPT_VERBOSE; }
6849                         | FREEZE                        { $$ = VACOPT_FREEZE; }
6850                         | FULL                          { $$ = VACOPT_FULL; }
6851                 ;
6852
6853 AnalyzeStmt:
6854                         analyze_keyword opt_verbose
6855                                 {
6856                                         VacuumStmt *n = makeNode(VacuumStmt);
6857                                         n->options = VACOPT_ANALYZE;
6858                                         if ($2)
6859                                                 n->options |= VACOPT_VERBOSE;
6860                                         n->freeze_min_age = -1;
6861                                         n->freeze_table_age = -1;
6862                                         n->relation = NULL;
6863                                         n->va_cols = NIL;
6864                                         $$ = (Node *)n;
6865                                 }
6866                         | analyze_keyword opt_verbose qualified_name opt_name_list
6867                                 {
6868                                         VacuumStmt *n = makeNode(VacuumStmt);
6869                                         n->options = VACOPT_ANALYZE;
6870                                         if ($2)
6871                                                 n->options |= VACOPT_VERBOSE;
6872                                         n->freeze_min_age = -1;
6873                                         n->freeze_table_age = -1;
6874                                         n->relation = $3;
6875                                         n->va_cols = $4;
6876                                         $$ = (Node *)n;
6877                                 }
6878                 ;
6879
6880 analyze_keyword:
6881                         ANALYZE                                                                 {}
6882                         | ANALYSE /* British */                                 {}
6883                 ;
6884
6885 opt_verbose:
6886                         VERBOSE                                                                 { $$ = TRUE; }
6887                         | /*EMPTY*/                                                             { $$ = FALSE; }
6888                 ;
6889
6890 opt_full:       FULL                                                                    { $$ = TRUE; }
6891                         | /*EMPTY*/                                                             { $$ = FALSE; }
6892                 ;
6893
6894 opt_freeze: FREEZE                                                                      { $$ = TRUE; }
6895                         | /*EMPTY*/                                                             { $$ = FALSE; }
6896                 ;
6897
6898 opt_name_list:
6899                         '(' name_list ')'                                               { $$ = $2; }
6900                         | /*EMPTY*/                                                             { $$ = NIL; }
6901                 ;
6902
6903
6904 /*****************************************************************************
6905  *
6906  *              QUERY:
6907  *                              EXPLAIN [ANALYZE] [VERBOSE] query
6908  *                              EXPLAIN ( options ) query
6909  *
6910  *****************************************************************************/
6911
6912 ExplainStmt:
6913                 EXPLAIN ExplainableStmt
6914                                 {
6915                                         ExplainStmt *n = makeNode(ExplainStmt);
6916                                         n->query = $2;
6917                                         n->options = NIL;
6918                                         $$ = (Node *) n;
6919                                 }
6920                 | EXPLAIN analyze_keyword opt_verbose ExplainableStmt
6921                                 {
6922                                         ExplainStmt *n = makeNode(ExplainStmt);
6923                                         n->query = $4;
6924                                         n->options = list_make1(makeDefElem("analyze", NULL));
6925                                         if ($3)
6926                                                 n->options = lappend(n->options,
6927                                                                                          makeDefElem("verbose", NULL));
6928                                         $$ = (Node *) n;
6929                                 }
6930                 | EXPLAIN VERBOSE ExplainableStmt
6931                                 {
6932                                         ExplainStmt *n = makeNode(ExplainStmt);
6933                                         n->query = $3;
6934                                         n->options = list_make1(makeDefElem("verbose", NULL));
6935                                         $$ = (Node *) n;
6936                                 }
6937                 | EXPLAIN '(' explain_option_list ')' ExplainableStmt
6938                                 {
6939                                         ExplainStmt *n = makeNode(ExplainStmt);
6940                                         n->query = $5;
6941                                         n->options = $3;
6942                                         $$ = (Node *) n;
6943                                 }
6944                 ;
6945
6946 ExplainableStmt:
6947                         SelectStmt
6948                         | InsertStmt
6949                         | UpdateStmt
6950                         | DeleteStmt
6951                         | DeclareCursorStmt
6952                         | CreateAsStmt
6953                         | ExecuteStmt                                   /* by default all are $$=$1 */
6954                 ;
6955
6956 explain_option_list:
6957                         explain_option_elem
6958                                 {
6959                                         $$ = list_make1($1);
6960                                 }
6961                         | explain_option_list ',' explain_option_elem
6962                                 {
6963                                         $$ = lappend($1, $3);
6964                                 }
6965                 ;
6966
6967 explain_option_elem:
6968                         explain_option_name explain_option_arg
6969                                 {
6970                                         $$ = makeDefElem($1, $2);
6971                                 }
6972                 ;
6973
6974 explain_option_name:
6975                         ColId                                   { $$ = $1; }
6976                         | analyze_keyword               { $$ = "analyze"; }
6977                         | VERBOSE                               { $$ = "verbose"; }
6978                 ;
6979
6980 explain_option_arg:
6981                         opt_boolean                             { $$ = (Node *) makeString($1); }
6982                         | ColId_or_Sconst               { $$ = (Node *) makeString($1); }
6983                         | NumericOnly                   { $$ = (Node *) $1; }
6984                         | /* EMPTY */                   { $$ = NULL; }
6985                 ;
6986
6987 /*****************************************************************************
6988  *
6989  *              QUERY:
6990  *                              PREPARE <plan_name> [(args, ...)] AS <query>
6991  *
6992  *****************************************************************************/
6993
6994 PrepareStmt: PREPARE name prep_type_clause AS PreparableStmt
6995                                 {
6996                                         PrepareStmt *n = makeNode(PrepareStmt);
6997                                         n->name = $2;
6998                                         n->argtypes = $3;
6999                                         n->query = $5;
7000                                         $$ = (Node *) n;
7001                                 }
7002                 ;
7003
7004 prep_type_clause: '(' type_list ')'                     { $$ = $2; }
7005                                 | /* EMPTY */                           { $$ = NIL; }
7006                 ;
7007
7008 PreparableStmt:
7009                         SelectStmt
7010                         | InsertStmt
7011                         | UpdateStmt
7012                         | DeleteStmt                                    /* by default all are $$=$1 */
7013                 ;
7014
7015 /*****************************************************************************
7016  *
7017  * EXECUTE <plan_name> [(params, ...)]
7018  * CREATE TABLE <name> AS EXECUTE <plan_name> [(params, ...)]
7019  *
7020  *****************************************************************************/
7021
7022 ExecuteStmt: EXECUTE name execute_param_clause
7023                                 {
7024                                         ExecuteStmt *n = makeNode(ExecuteStmt);
7025                                         n->name = $2;
7026                                         n->params = $3;
7027                                         n->into = NULL;
7028                                         $$ = (Node *) n;
7029                                 }
7030                         | CREATE OptTemp TABLE create_as_target AS
7031                                 EXECUTE name execute_param_clause
7032                                 {
7033                                         ExecuteStmt *n = makeNode(ExecuteStmt);
7034                                         n->name = $7;
7035                                         n->params = $8;
7036                                         $4->rel->istemp = $2;
7037                                         n->into = $4;
7038                                         if ($4->colNames)
7039                                                 ereport(ERROR,
7040                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
7041                                                                  errmsg("column name list not allowed in CREATE TABLE / AS EXECUTE")));
7042                                         /* ... because it's not implemented, but it could be */
7043                                         $$ = (Node *) n;
7044                                 }
7045                 ;
7046
7047 execute_param_clause: '(' expr_list ')'                         { $$ = $2; }
7048                                         | /* EMPTY */                                   { $$ = NIL; }
7049                                         ;
7050
7051 /*****************************************************************************
7052  *
7053  *              QUERY:
7054  *                              DEALLOCATE [PREPARE] <plan_name>
7055  *
7056  *****************************************************************************/
7057
7058 DeallocateStmt: DEALLOCATE name
7059                                         {
7060                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
7061                                                 n->name = $2;
7062                                                 $$ = (Node *) n;
7063                                         }
7064                                 | DEALLOCATE PREPARE name
7065                                         {
7066                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
7067                                                 n->name = $3;
7068                                                 $$ = (Node *) n;
7069                                         }
7070                                 | DEALLOCATE ALL
7071                                         {
7072                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
7073                                                 n->name = NULL;
7074                                                 $$ = (Node *) n;
7075                                         }
7076                                 | DEALLOCATE PREPARE ALL
7077                                         {
7078                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
7079                                                 n->name = NULL;
7080                                                 $$ = (Node *) n;
7081                                         }
7082                 ;
7083
7084 /*****************************************************************************
7085  *
7086  *              QUERY:
7087  *                              INSERT STATEMENTS
7088  *
7089  *****************************************************************************/
7090
7091 InsertStmt:
7092                         INSERT INTO qualified_name insert_rest returning_clause
7093                                 {
7094                                         $4->relation = $3;
7095                                         $4->returningList = $5;
7096                                         $$ = (Node *) $4;
7097                                 }
7098                 ;
7099
7100 insert_rest:
7101                         SelectStmt
7102                                 {
7103                                         $$ = makeNode(InsertStmt);
7104                                         $$->cols = NIL;
7105                                         $$->selectStmt = $1;
7106                                 }
7107                         | '(' insert_column_list ')' SelectStmt
7108                                 {
7109                                         $$ = makeNode(InsertStmt);
7110                                         $$->cols = $2;
7111                                         $$->selectStmt = $4;
7112                                 }
7113                         | DEFAULT VALUES
7114                                 {
7115                                         $$ = makeNode(InsertStmt);
7116                                         $$->cols = NIL;
7117                                         $$->selectStmt = NULL;
7118                                 }
7119                 ;
7120
7121 insert_column_list:
7122                         insert_column_item
7123                                         { $$ = list_make1($1); }
7124                         | insert_column_list ',' insert_column_item
7125                                         { $$ = lappend($1, $3); }
7126                 ;
7127
7128 insert_column_item:
7129                         ColId opt_indirection
7130                                 {
7131                                         $$ = makeNode(ResTarget);
7132                                         $$->name = $1;
7133                                         $$->indirection = check_indirection($2, yyscanner);
7134                                         $$->val = NULL;
7135                                         $$->location = @1;
7136                                 }
7137                 ;
7138
7139 returning_clause:
7140                         RETURNING target_list           { $$ = $2; }
7141                         | /* EMPTY */                           { $$ = NIL; }
7142                 ;
7143
7144
7145 /*****************************************************************************
7146  *
7147  *              QUERY:
7148  *                              DELETE STATEMENTS
7149  *
7150  *****************************************************************************/
7151
7152 DeleteStmt: DELETE_P FROM relation_expr_opt_alias
7153                         using_clause where_or_current_clause returning_clause
7154                                 {
7155                                         DeleteStmt *n = makeNode(DeleteStmt);
7156                                         n->relation = $3;
7157                                         n->usingClause = $4;
7158                                         n->whereClause = $5;
7159                                         n->returningList = $6;
7160                                         $$ = (Node *)n;
7161                                 }
7162                 ;
7163
7164 using_clause:
7165                         USING from_list                                         { $$ = $2; }
7166                         | /*EMPTY*/                                                             { $$ = NIL; }
7167                 ;
7168
7169
7170 /*****************************************************************************
7171  *
7172  *              QUERY:
7173  *                              LOCK TABLE
7174  *
7175  *****************************************************************************/
7176
7177 LockStmt:       LOCK_P opt_table relation_expr_list opt_lock opt_nowait
7178                                 {
7179                                         LockStmt *n = makeNode(LockStmt);
7180
7181                                         n->relations = $3;
7182                                         n->mode = $4;
7183                                         n->nowait = $5;
7184                                         $$ = (Node *)n;
7185                                 }
7186                 ;
7187
7188 opt_lock:       IN_P lock_type MODE                     { $$ = $2; }
7189                         | /*EMPTY*/                                             { $$ = AccessExclusiveLock; }
7190                 ;
7191
7192 lock_type:      ACCESS SHARE                                    { $$ = AccessShareLock; }
7193                         | ROW SHARE                                             { $$ = RowShareLock; }
7194                         | ROW EXCLUSIVE                                 { $$ = RowExclusiveLock; }
7195                         | SHARE UPDATE EXCLUSIVE                { $$ = ShareUpdateExclusiveLock; }
7196                         | SHARE                                                 { $$ = ShareLock; }
7197                         | SHARE ROW EXCLUSIVE                   { $$ = ShareRowExclusiveLock; }
7198                         | EXCLUSIVE                                             { $$ = ExclusiveLock; }
7199                         | ACCESS EXCLUSIVE                              { $$ = AccessExclusiveLock; }
7200                 ;
7201
7202 opt_nowait:     NOWAIT                                                  { $$ = TRUE; }
7203                         | /*EMPTY*/                                             { $$ = FALSE; }
7204                 ;
7205
7206
7207 /*****************************************************************************
7208  *
7209  *              QUERY:
7210  *                              UpdateStmt (UPDATE)
7211  *
7212  *****************************************************************************/
7213
7214 UpdateStmt: UPDATE relation_expr_opt_alias
7215                         SET set_clause_list
7216                         from_clause
7217                         where_or_current_clause
7218                         returning_clause
7219                                 {
7220                                         UpdateStmt *n = makeNode(UpdateStmt);
7221                                         n->relation = $2;
7222                                         n->targetList = $4;
7223                                         n->fromClause = $5;
7224                                         n->whereClause = $6;
7225                                         n->returningList = $7;
7226                                         $$ = (Node *)n;
7227                                 }
7228                 ;
7229
7230 set_clause_list:
7231                         set_clause                                                      { $$ = $1; }
7232                         | set_clause_list ',' set_clause        { $$ = list_concat($1,$3); }
7233                 ;
7234
7235 set_clause:
7236                         single_set_clause                                               { $$ = list_make1($1); }
7237                         | multiple_set_clause                                   { $$ = $1; }
7238                 ;
7239
7240 single_set_clause:
7241                         set_target '=' ctext_expr
7242                                 {
7243                                         $$ = $1;
7244                                         $$->val = (Node *) $3;
7245                                 }
7246                 ;
7247
7248 multiple_set_clause:
7249                         '(' set_target_list ')' '=' ctext_row
7250                                 {
7251                                         ListCell *col_cell;
7252                                         ListCell *val_cell;
7253
7254                                         /*
7255                                          * Break the ctext_row apart, merge individual expressions
7256                                          * into the destination ResTargets.  XXX this approach
7257                                          * cannot work for general row expressions as sources.
7258                                          */
7259                                         if (list_length($2) != list_length($5))
7260                                                 ereport(ERROR,
7261                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
7262                                                                  errmsg("number of columns does not match number of values"),
7263                                                                  parser_errposition(@1)));
7264                                         forboth(col_cell, $2, val_cell, $5)
7265                                         {
7266                                                 ResTarget *res_col = (ResTarget *) lfirst(col_cell);
7267                                                 Node *res_val = (Node *) lfirst(val_cell);
7268
7269                                                 res_col->val = res_val;
7270                                         }
7271
7272                                         $$ = $2;
7273                                 }
7274                 ;
7275
7276 set_target:
7277                         ColId opt_indirection
7278                                 {
7279                                         $$ = makeNode(ResTarget);
7280                                         $$->name = $1;
7281                                         $$->indirection = check_indirection($2, yyscanner);
7282                                         $$->val = NULL; /* upper production sets this */
7283                                         $$->location = @1;
7284                                 }
7285                 ;
7286
7287 set_target_list:
7288                         set_target                                                              { $$ = list_make1($1); }
7289                         | set_target_list ',' set_target                { $$ = lappend($1,$3); }
7290                 ;
7291
7292
7293 /*****************************************************************************
7294  *
7295  *              QUERY:
7296  *                              CURSOR STATEMENTS
7297  *
7298  *****************************************************************************/
7299 DeclareCursorStmt: DECLARE cursor_name cursor_options CURSOR opt_hold FOR SelectStmt
7300                                 {
7301                                         DeclareCursorStmt *n = makeNode(DeclareCursorStmt);
7302                                         n->portalname = $2;
7303                                         /* currently we always set FAST_PLAN option */
7304                                         n->options = $3 | $5 | CURSOR_OPT_FAST_PLAN;
7305                                         n->query = $7;
7306                                         $$ = (Node *)n;
7307                                 }
7308                 ;
7309
7310 cursor_name:    name                                            { $$ = $1; }
7311                 ;
7312
7313 cursor_options: /*EMPTY*/                                       { $$ = 0; }
7314                         | cursor_options NO SCROLL              { $$ = $1 | CURSOR_OPT_NO_SCROLL; }
7315                         | cursor_options SCROLL                 { $$ = $1 | CURSOR_OPT_SCROLL; }
7316                         | cursor_options BINARY                 { $$ = $1 | CURSOR_OPT_BINARY; }
7317                         | cursor_options INSENSITIVE    { $$ = $1 | CURSOR_OPT_INSENSITIVE; }
7318                 ;
7319
7320 opt_hold: /* EMPTY */                                           { $$ = 0; }
7321                         | WITH HOLD                                             { $$ = CURSOR_OPT_HOLD; }
7322                         | WITHOUT HOLD                                  { $$ = 0; }
7323                 ;
7324
7325 /*****************************************************************************
7326  *
7327  *              QUERY:
7328  *                              SELECT STATEMENTS
7329  *
7330  *****************************************************************************/
7331
7332 /* A complete SELECT statement looks like this.
7333  *
7334  * The rule returns either a single SelectStmt node or a tree of them,
7335  * representing a set-operation tree.
7336  *
7337  * There is an ambiguity when a sub-SELECT is within an a_expr and there
7338  * are excess parentheses: do the parentheses belong to the sub-SELECT or
7339  * to the surrounding a_expr?  We don't really care, but bison wants to know.
7340  * To resolve the ambiguity, we are careful to define the grammar so that
7341  * the decision is staved off as long as possible: as long as we can keep
7342  * absorbing parentheses into the sub-SELECT, we will do so, and only when
7343  * it's no longer possible to do that will we decide that parens belong to
7344  * the expression.      For example, in "SELECT (((SELECT 2)) + 3)" the extra
7345  * parentheses are treated as part of the sub-select.  The necessity of doing
7346  * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)".      Had we
7347  * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
7348  * SELECT viewpoint when we see the UNION.
7349  *
7350  * This approach is implemented by defining a nonterminal select_with_parens,
7351  * which represents a SELECT with at least one outer layer of parentheses,
7352  * and being careful to use select_with_parens, never '(' SelectStmt ')',
7353  * in the expression grammar.  We will then have shift-reduce conflicts
7354  * which we can resolve in favor of always treating '(' <select> ')' as
7355  * a select_with_parens.  To resolve the conflicts, the productions that
7356  * conflict with the select_with_parens productions are manually given
7357  * precedences lower than the precedence of ')', thereby ensuring that we
7358  * shift ')' (and then reduce to select_with_parens) rather than trying to
7359  * reduce the inner <select> nonterminal to something else.  We use UMINUS
7360  * precedence for this, which is a fairly arbitrary choice.
7361  *
7362  * To be able to define select_with_parens itself without ambiguity, we need
7363  * a nonterminal select_no_parens that represents a SELECT structure with no
7364  * outermost parentheses.  This is a little bit tedious, but it works.
7365  *
7366  * In non-expression contexts, we use SelectStmt which can represent a SELECT
7367  * with or without outer parentheses.
7368  */
7369
7370 SelectStmt: select_no_parens                    %prec UMINUS
7371                         | select_with_parens            %prec UMINUS
7372                 ;
7373
7374 select_with_parens:
7375                         '(' select_no_parens ')'                                { $$ = $2; }
7376                         | '(' select_with_parens ')'                    { $$ = $2; }
7377                 ;
7378
7379 /*
7380  * This rule parses the equivalent of the standard's <query expression>.
7381  * The duplicative productions are annoying, but hard to get rid of without
7382  * creating shift/reduce conflicts.
7383  *
7384  *      FOR UPDATE/SHARE may be before or after LIMIT/OFFSET.
7385  *      In <=7.2.X, LIMIT/OFFSET had to be after FOR UPDATE
7386  *      We now support both orderings, but prefer LIMIT/OFFSET before FOR UPDATE/SHARE
7387  *      2002-08-28 bjm
7388  */
7389 select_no_parens:
7390                         simple_select                                           { $$ = $1; }
7391                         | select_clause sort_clause
7392                                 {
7393                                         insertSelectOptions((SelectStmt *) $1, $2, NIL,
7394                                                                                 NULL, NULL, NULL,
7395                                                                                 yyscanner);
7396                                         $$ = $1;
7397                                 }
7398                         | select_clause opt_sort_clause for_locking_clause opt_select_limit
7399                                 {
7400                                         insertSelectOptions((SelectStmt *) $1, $2, $3,
7401                                                                                 list_nth($4, 0), list_nth($4, 1),
7402                                                                                 NULL,
7403                                                                                 yyscanner);
7404                                         $$ = $1;
7405                                 }
7406                         | select_clause opt_sort_clause select_limit opt_for_locking_clause
7407                                 {
7408                                         insertSelectOptions((SelectStmt *) $1, $2, $4,
7409                                                                                 list_nth($3, 0), list_nth($3, 1),
7410                                                                                 NULL,
7411                                                                                 yyscanner);
7412                                         $$ = $1;
7413                                 }
7414                         | with_clause select_clause
7415                                 {
7416                                         insertSelectOptions((SelectStmt *) $2, NULL, NIL,
7417                                                                                 NULL, NULL,
7418                                                                                 $1,
7419                                                                                 yyscanner);
7420                                         $$ = $2;
7421                                 }
7422                         | with_clause select_clause sort_clause
7423                                 {
7424                                         insertSelectOptions((SelectStmt *) $2, $3, NIL,
7425                                                                                 NULL, NULL,
7426                                                                                 $1,
7427                                                                                 yyscanner);
7428                                         $$ = $2;
7429                                 }
7430                         | with_clause select_clause opt_sort_clause for_locking_clause opt_select_limit
7431                                 {
7432                                         insertSelectOptions((SelectStmt *) $2, $3, $4,
7433                                                                                 list_nth($5, 0), list_nth($5, 1),
7434                                                                                 $1,
7435                                                                                 yyscanner);
7436                                         $$ = $2;
7437                                 }
7438                         | with_clause select_clause opt_sort_clause select_limit opt_for_locking_clause
7439                                 {
7440                                         insertSelectOptions((SelectStmt *) $2, $3, $5,
7441                                                                                 list_nth($4, 0), list_nth($4, 1),
7442                                                                                 $1,
7443                                                                                 yyscanner);
7444                                         $$ = $2;
7445                                 }
7446                 ;
7447
7448 select_clause:
7449                         simple_select                                                   { $$ = $1; }
7450                         | select_with_parens                                    { $$ = $1; }
7451                 ;
7452
7453 /*
7454  * This rule parses SELECT statements that can appear within set operations,
7455  * including UNION, INTERSECT and EXCEPT.  '(' and ')' can be used to specify
7456  * the ordering of the set operations.  Without '(' and ')' we want the
7457  * operations to be ordered per the precedence specs at the head of this file.
7458  *
7459  * As with select_no_parens, simple_select cannot have outer parentheses,
7460  * but can have parenthesized subclauses.
7461  *
7462  * Note that sort clauses cannot be included at this level --- SQL92 requires
7463  *              SELECT foo UNION SELECT bar ORDER BY baz
7464  * to be parsed as
7465  *              (SELECT foo UNION SELECT bar) ORDER BY baz
7466  * not
7467  *              SELECT foo UNION (SELECT bar ORDER BY baz)
7468  * Likewise for WITH, FOR UPDATE and LIMIT.  Therefore, those clauses are
7469  * described as part of the select_no_parens production, not simple_select.
7470  * This does not limit functionality, because you can reintroduce these
7471  * clauses inside parentheses.
7472  *
7473  * NOTE: only the leftmost component SelectStmt should have INTO.
7474  * However, this is not checked by the grammar; parse analysis must check it.
7475  */
7476 simple_select:
7477                         SELECT opt_distinct target_list
7478                         into_clause from_clause where_clause
7479                         group_clause having_clause window_clause
7480                                 {
7481                                         SelectStmt *n = makeNode(SelectStmt);
7482                                         n->distinctClause = $2;
7483                                         n->targetList = $3;
7484                                         n->intoClause = $4;
7485                                         n->fromClause = $5;
7486                                         n->whereClause = $6;
7487                                         n->groupClause = $7;
7488                                         n->havingClause = $8;
7489                                         n->windowClause = $9;
7490                                         $$ = (Node *)n;
7491                                 }
7492                         | values_clause                                                 { $$ = $1; }
7493                         | TABLE relation_expr
7494                                 {
7495                                         /* same as SELECT * FROM relation_expr */
7496                                         ColumnRef *cr = makeNode(ColumnRef);
7497                                         ResTarget *rt = makeNode(ResTarget);
7498                                         SelectStmt *n = makeNode(SelectStmt);
7499
7500                                         cr->fields = list_make1(makeNode(A_Star));
7501                                         cr->location = -1;
7502
7503                                         rt->name = NULL;
7504                                         rt->indirection = NIL;
7505                                         rt->val = (Node *)cr;
7506                                         rt->location = -1;
7507
7508                                         n->targetList = list_make1(rt);
7509                                         n->fromClause = list_make1($2);
7510                                         $$ = (Node *)n;
7511                                 }
7512                         | select_clause UNION opt_all select_clause
7513                                 {
7514                                         $$ = makeSetOp(SETOP_UNION, $3, $1, $4);
7515                                 }
7516                         | select_clause INTERSECT opt_all select_clause
7517                                 {
7518                                         $$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
7519                                 }
7520                         | select_clause EXCEPT opt_all select_clause
7521                                 {
7522                                         $$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
7523                                 }
7524                 ;
7525
7526 /*
7527  * SQL standard WITH clause looks like:
7528  *
7529  * WITH [ RECURSIVE ] <query name> [ (<column>,...) ]
7530  *              AS (query) [ SEARCH or CYCLE clause ]
7531  *
7532  * We don't currently support the SEARCH or CYCLE clause.
7533  */
7534 with_clause:
7535                 WITH cte_list
7536                         {
7537                                 $$ = makeNode(WithClause);
7538                                 $$->ctes = $2;
7539                                 $$->recursive = false;
7540                                 $$->location = @1;
7541                         }
7542                 | WITH RECURSIVE cte_list
7543                         {
7544                                 $$ = makeNode(WithClause);
7545                                 $$->ctes = $3;
7546                                 $$->recursive = true;
7547                                 $$->location = @1;
7548                         }
7549                 ;
7550
7551 cte_list:
7552                 common_table_expr                                               { $$ = list_make1($1); }
7553                 | cte_list ',' common_table_expr                { $$ = lappend($1, $3); }
7554                 ;
7555
7556 common_table_expr:  name opt_name_list AS select_with_parens
7557                         {
7558                                 CommonTableExpr *n = makeNode(CommonTableExpr);
7559                                 n->ctename = $1;
7560                                 n->aliascolnames = $2;
7561                                 n->ctequery = $4;
7562                                 n->location = @1;
7563                                 $$ = (Node *) n;
7564                         }
7565                 ;
7566
7567 into_clause:
7568                         INTO OptTempTableName
7569                                 {
7570                                         $$ = makeNode(IntoClause);
7571                                         $$->rel = $2;
7572                                         $$->colNames = NIL;
7573                                         $$->options = NIL;
7574                                         $$->onCommit = ONCOMMIT_NOOP;
7575                                         $$->tableSpaceName = NULL;
7576                                 }
7577                         | /*EMPTY*/
7578                                 { $$ = NULL; }
7579                 ;
7580
7581 /*
7582  * Redundancy here is needed to avoid shift/reduce conflicts,
7583  * since TEMP is not a reserved word.  See also OptTemp.
7584  */
7585 OptTempTableName:
7586                         TEMPORARY opt_table qualified_name
7587                                 {
7588                                         $$ = $3;
7589                                         $$->istemp = true;
7590                                 }
7591                         | TEMP opt_table qualified_name
7592                                 {
7593                                         $$ = $3;
7594                                         $$->istemp = true;
7595                                 }
7596                         | LOCAL TEMPORARY opt_table qualified_name
7597                                 {
7598                                         $$ = $4;
7599                                         $$->istemp = true;
7600                                 }
7601                         | LOCAL TEMP opt_table qualified_name
7602                                 {
7603                                         $$ = $4;
7604                                         $$->istemp = true;
7605                                 }
7606                         | GLOBAL TEMPORARY opt_table qualified_name
7607                                 {
7608                                         $$ = $4;
7609                                         $$->istemp = true;
7610                                 }
7611                         | GLOBAL TEMP opt_table qualified_name
7612                                 {
7613                                         $$ = $4;
7614                                         $$->istemp = true;
7615                                 }
7616                         | TABLE qualified_name
7617                                 {
7618                                         $$ = $2;
7619                                         $$->istemp = false;
7620                                 }
7621                         | qualified_name
7622                                 {
7623                                         $$ = $1;
7624                                         $$->istemp = false;
7625                                 }
7626                 ;
7627
7628 opt_table:      TABLE                                                                   {}
7629                         | /*EMPTY*/                                                             {}
7630                 ;
7631
7632 opt_all:        ALL                                                                             { $$ = TRUE; }
7633                         | DISTINCT                                                              { $$ = FALSE; }
7634                         | /*EMPTY*/                                                             { $$ = FALSE; }
7635                 ;
7636
7637 /* We use (NIL) as a placeholder to indicate that all target expressions
7638  * should be placed in the DISTINCT list during parsetree analysis.
7639  */
7640 opt_distinct:
7641                         DISTINCT                                                                { $$ = list_make1(NIL); }
7642                         | DISTINCT ON '(' expr_list ')'                 { $$ = $4; }
7643                         | ALL                                                                   { $$ = NIL; }
7644                         | /*EMPTY*/                                                             { $$ = NIL; }
7645                 ;
7646
7647 opt_sort_clause:
7648                         sort_clause                                                             { $$ = $1;}
7649                         | /*EMPTY*/                                                             { $$ = NIL; }
7650                 ;
7651
7652 sort_clause:
7653                         ORDER BY sortby_list                                    { $$ = $3; }
7654                 ;
7655
7656 sortby_list:
7657                         sortby                                                                  { $$ = list_make1($1); }
7658                         | sortby_list ',' sortby                                { $$ = lappend($1, $3); }
7659                 ;
7660
7661 sortby:         a_expr USING qual_all_Op opt_nulls_order
7662                                 {
7663                                         $$ = makeNode(SortBy);
7664                                         $$->node = $1;
7665                                         $$->sortby_dir = SORTBY_USING;
7666                                         $$->sortby_nulls = $4;
7667                                         $$->useOp = $3;
7668                                         $$->location = @3;
7669                                 }
7670                         | a_expr opt_asc_desc opt_nulls_order
7671                                 {
7672                                         $$ = makeNode(SortBy);
7673                                         $$->node = $1;
7674                                         $$->sortby_dir = $2;
7675                                         $$->sortby_nulls = $3;
7676                                         $$->useOp = NIL;
7677                                         $$->location = -1;              /* no operator */
7678                                 }
7679                 ;
7680
7681
7682 select_limit:
7683                         limit_clause offset_clause                      { $$ = list_make2($2, $1); }
7684                         | offset_clause limit_clause            { $$ = list_make2($1, $2); }
7685                         | limit_clause                                          { $$ = list_make2(NULL, $1); }
7686                         | offset_clause                                         { $$ = list_make2($1, NULL); }
7687                 ;
7688
7689 opt_select_limit:
7690                         select_limit                                            { $$ = $1; }
7691                         | /* EMPTY */                                           { $$ = list_make2(NULL,NULL); }
7692                 ;
7693
7694 limit_clause:
7695                         LIMIT select_limit_value
7696                                 { $$ = $2; }
7697                         | LIMIT select_limit_value ',' select_offset_value
7698                                 {
7699                                         /* Disabled because it was too confusing, bjm 2002-02-18 */
7700                                         ereport(ERROR,
7701                                                         (errcode(ERRCODE_SYNTAX_ERROR),
7702                                                          errmsg("LIMIT #,# syntax is not supported"),
7703                                                          errhint("Use separate LIMIT and OFFSET clauses."),
7704                                                          parser_errposition(@1)));
7705                                 }
7706                         /* SQL:2008 syntax */
7707                         | FETCH first_or_next opt_select_fetch_first_value row_or_rows ONLY
7708                                 { $$ = $3; }
7709                 ;
7710
7711 offset_clause:
7712                         OFFSET select_offset_value
7713                                 { $$ = $2; }
7714                         /* SQL:2008 syntax */
7715                         | OFFSET select_offset_value2 row_or_rows
7716                                 { $$ = $2; }
7717                 ;
7718
7719 select_limit_value:
7720                         a_expr                                                                  { $$ = $1; }
7721                         | ALL
7722                                 {
7723                                         /* LIMIT ALL is represented as a NULL constant */
7724                                         $$ = makeNullAConst(@1);
7725                                 }
7726                 ;
7727
7728 select_offset_value:
7729                         a_expr                                                                  { $$ = $1; }
7730                 ;
7731
7732 /*
7733  * Allowing full expressions without parentheses causes various parsing
7734  * problems with the trailing ROW/ROWS key words.  SQL only calls for
7735  * constants, so we allow the rest only with parentheses.  If omitted,
7736  * default to 1.
7737  */
7738 opt_select_fetch_first_value:
7739                         SignedIconst                                            { $$ = makeIntConst($1, @1); }
7740                         | '(' a_expr ')'                                        { $$ = $2; }
7741                         | /*EMPTY*/                                                     { $$ = makeIntConst(1, -1); }
7742                 ;
7743
7744 /*
7745  * Again, the trailing ROW/ROWS in this case prevent the full expression
7746  * syntax.  c_expr is the best we can do.
7747  */
7748 select_offset_value2:
7749                         c_expr                                                                  { $$ = $1; }
7750                 ;
7751
7752 /* noise words */
7753 row_or_rows: ROW                                                                        { $$ = 0; }
7754                         | ROWS                                                                  { $$ = 0; }
7755                 ;
7756
7757 first_or_next: FIRST_P                                                          { $$ = 0; }
7758                         | NEXT                                                                  { $$ = 0; }
7759                 ;
7760
7761
7762 group_clause:
7763                         GROUP_P BY expr_list                                    { $$ = $3; }
7764                         | /*EMPTY*/                                                             { $$ = NIL; }
7765                 ;
7766
7767 having_clause:
7768                         HAVING a_expr                                                   { $$ = $2; }
7769                         | /*EMPTY*/                                                             { $$ = NULL; }
7770                 ;
7771
7772 for_locking_clause:
7773                         for_locking_items                                               { $$ = $1; }
7774                         | FOR READ ONLY                                                 { $$ = NIL; }
7775                 ;
7776
7777 opt_for_locking_clause:
7778                         for_locking_clause                                              { $$ = $1; }
7779                         | /* EMPTY */                                                   { $$ = NIL; }
7780                 ;
7781
7782 for_locking_items:
7783                         for_locking_item                                                { $$ = list_make1($1); }
7784                         | for_locking_items for_locking_item    { $$ = lappend($1, $2); }
7785                 ;
7786
7787 for_locking_item:
7788                         FOR UPDATE locked_rels_list opt_nowait
7789                                 {
7790                                         LockingClause *n = makeNode(LockingClause);
7791                                         n->lockedRels = $3;
7792                                         n->forUpdate = TRUE;
7793                                         n->noWait = $4;
7794                                         $$ = (Node *) n;
7795                                 }
7796                         | FOR SHARE locked_rels_list opt_nowait
7797                                 {
7798                                         LockingClause *n = makeNode(LockingClause);
7799                                         n->lockedRels = $3;
7800                                         n->forUpdate = FALSE;
7801                                         n->noWait = $4;
7802                                         $$ = (Node *) n;
7803                                 }
7804                 ;
7805
7806 locked_rels_list:
7807                         OF qualified_name_list                                  { $$ = $2; }
7808                         | /* EMPTY */                                                   { $$ = NIL; }
7809                 ;
7810
7811
7812 values_clause:
7813                         VALUES ctext_row
7814                                 {
7815                                         SelectStmt *n = makeNode(SelectStmt);
7816                                         n->valuesLists = list_make1($2);
7817                                         $$ = (Node *) n;
7818                                 }
7819                         | values_clause ',' ctext_row
7820                                 {
7821                                         SelectStmt *n = (SelectStmt *) $1;
7822                                         n->valuesLists = lappend(n->valuesLists, $3);
7823                                         $$ = (Node *) n;
7824                                 }
7825                 ;
7826
7827
7828 /*****************************************************************************
7829  *
7830  *      clauses common to all Optimizable Stmts:
7831  *              from_clause             - allow list of both JOIN expressions and table names
7832  *              where_clause    - qualifications for joins or restrictions
7833  *
7834  *****************************************************************************/
7835
7836 from_clause:
7837                         FROM from_list                                                  { $$ = $2; }
7838                         | /*EMPTY*/                                                             { $$ = NIL; }
7839                 ;
7840
7841 from_list:
7842                         table_ref                                                               { $$ = list_make1($1); }
7843                         | from_list ',' table_ref                               { $$ = lappend($1, $3); }
7844                 ;
7845
7846 /*
7847  * table_ref is where an alias clause can be attached.  Note we cannot make
7848  * alias_clause have an empty production because that causes parse conflicts
7849  * between table_ref := '(' joined_table ')' alias_clause
7850  * and joined_table := '(' joined_table ')'.  So, we must have the
7851  * redundant-looking productions here instead.
7852  */
7853 table_ref:      relation_expr
7854                                 {
7855                                         $$ = (Node *) $1;
7856                                 }
7857                         | relation_expr alias_clause
7858                                 {
7859                                         $1->alias = $2;
7860                                         $$ = (Node *) $1;
7861                                 }
7862                         | func_table
7863                                 {
7864                                         RangeFunction *n = makeNode(RangeFunction);
7865                                         n->funccallnode = $1;
7866                                         n->coldeflist = NIL;
7867                                         $$ = (Node *) n;
7868                                 }
7869                         | func_table alias_clause
7870                                 {
7871                                         RangeFunction *n = makeNode(RangeFunction);
7872                                         n->funccallnode = $1;
7873                                         n->alias = $2;
7874                                         n->coldeflist = NIL;
7875                                         $$ = (Node *) n;
7876                                 }
7877                         | func_table AS '(' TableFuncElementList ')'
7878                                 {
7879                                         RangeFunction *n = makeNode(RangeFunction);
7880                                         n->funccallnode = $1;
7881                                         n->coldeflist = $4;
7882                                         $$ = (Node *) n;
7883                                 }
7884                         | func_table AS ColId '(' TableFuncElementList ')'
7885                                 {
7886                                         RangeFunction *n = makeNode(RangeFunction);
7887                                         Alias *a = makeNode(Alias);
7888                                         n->funccallnode = $1;
7889                                         a->aliasname = $3;
7890                                         n->alias = a;
7891                                         n->coldeflist = $5;
7892                                         $$ = (Node *) n;
7893                                 }
7894                         | func_table ColId '(' TableFuncElementList ')'
7895                                 {
7896                                         RangeFunction *n = makeNode(RangeFunction);
7897                                         Alias *a = makeNode(Alias);
7898                                         n->funccallnode = $1;
7899                                         a->aliasname = $2;
7900                                         n->alias = a;
7901                                         n->coldeflist = $4;
7902                                         $$ = (Node *) n;
7903                                 }
7904                         | select_with_parens
7905                                 {
7906                                         /*
7907                                          * The SQL spec does not permit a subselect
7908                                          * (<derived_table>) without an alias clause,
7909                                          * so we don't either.  This avoids the problem
7910                                          * of needing to invent a unique refname for it.
7911                                          * That could be surmounted if there's sufficient
7912                                          * popular demand, but for now let's just implement
7913                                          * the spec and see if anyone complains.
7914                                          * However, it does seem like a good idea to emit
7915                                          * an error message that's better than "syntax error".
7916                                          */
7917                                         if (IsA($1, SelectStmt) &&
7918                                                 ((SelectStmt *) $1)->valuesLists)
7919                                                 ereport(ERROR,
7920                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
7921                                                                  errmsg("VALUES in FROM must have an alias"),
7922                                                                  errhint("For example, FROM (VALUES ...) [AS] foo."),
7923                                                                  parser_errposition(@1)));
7924                                         else
7925                                                 ereport(ERROR,
7926                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
7927                                                                  errmsg("subquery in FROM must have an alias"),
7928                                                                  errhint("For example, FROM (SELECT ...) [AS] foo."),
7929                                                                  parser_errposition(@1)));
7930                                         $$ = NULL;
7931                                 }
7932                         | select_with_parens alias_clause
7933                                 {
7934                                         RangeSubselect *n = makeNode(RangeSubselect);
7935                                         n->subquery = $1;
7936                                         n->alias = $2;
7937                                         $$ = (Node *) n;
7938                                 }
7939                         | joined_table
7940                                 {
7941                                         $$ = (Node *) $1;
7942                                 }
7943                         | '(' joined_table ')' alias_clause
7944                                 {
7945                                         $2->alias = $4;
7946                                         $$ = (Node *) $2;
7947                                 }
7948                 ;
7949
7950
7951 /*
7952  * It may seem silly to separate joined_table from table_ref, but there is
7953  * method in SQL92's madness: if you don't do it this way you get reduce-
7954  * reduce conflicts, because it's not clear to the parser generator whether
7955  * to expect alias_clause after ')' or not.  For the same reason we must
7956  * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
7957  * join_type to expand to empty; if we try it, the parser generator can't
7958  * figure out when to reduce an empty join_type right after table_ref.
7959  *
7960  * Note that a CROSS JOIN is the same as an unqualified
7961  * INNER JOIN, and an INNER JOIN/ON has the same shape
7962  * but a qualification expression to limit membership.
7963  * A NATURAL JOIN implicitly matches column names between
7964  * tables and the shape is determined by which columns are
7965  * in common. We'll collect columns during the later transformations.
7966  */
7967
7968 joined_table:
7969                         '(' joined_table ')'
7970                                 {
7971                                         $$ = $2;
7972                                 }
7973                         | table_ref CROSS JOIN table_ref
7974                                 {
7975                                         /* CROSS JOIN is same as unqualified inner join */
7976                                         JoinExpr *n = makeNode(JoinExpr);
7977                                         n->jointype = JOIN_INNER;
7978                                         n->isNatural = FALSE;
7979                                         n->larg = $1;
7980                                         n->rarg = $4;
7981                                         n->usingClause = NIL;
7982                                         n->quals = NULL;
7983                                         $$ = n;
7984                                 }
7985                         | table_ref join_type JOIN table_ref join_qual
7986                                 {
7987                                         JoinExpr *n = makeNode(JoinExpr);
7988                                         n->jointype = $2;
7989                                         n->isNatural = FALSE;
7990                                         n->larg = $1;
7991                                         n->rarg = $4;
7992                                         if ($5 != NULL && IsA($5, List))
7993                                                 n->usingClause = (List *) $5; /* USING clause */
7994                                         else
7995                                                 n->quals = $5; /* ON clause */
7996                                         $$ = n;
7997                                 }
7998                         | table_ref JOIN table_ref join_qual
7999                                 {
8000                                         /* letting join_type reduce to empty doesn't work */
8001                                         JoinExpr *n = makeNode(JoinExpr);
8002                                         n->jointype = JOIN_INNER;
8003                                         n->isNatural = FALSE;
8004                                         n->larg = $1;
8005                                         n->rarg = $3;
8006                                         if ($4 != NULL && IsA($4, List))
8007                                                 n->usingClause = (List *) $4; /* USING clause */
8008                                         else
8009                                                 n->quals = $4; /* ON clause */
8010                                         $$ = n;
8011                                 }
8012                         | table_ref NATURAL join_type JOIN table_ref
8013                                 {
8014                                         JoinExpr *n = makeNode(JoinExpr);
8015                                         n->jointype = $3;
8016                                         n->isNatural = TRUE;
8017                                         n->larg = $1;
8018                                         n->rarg = $5;
8019                                         n->usingClause = NIL; /* figure out which columns later... */
8020                                         n->quals = NULL; /* fill later */
8021                                         $$ = n;
8022                                 }
8023                         | table_ref NATURAL JOIN table_ref
8024                                 {
8025                                         /* letting join_type reduce to empty doesn't work */
8026                                         JoinExpr *n = makeNode(JoinExpr);
8027                                         n->jointype = JOIN_INNER;
8028                                         n->isNatural = TRUE;
8029                                         n->larg = $1;
8030                                         n->rarg = $4;
8031                                         n->usingClause = NIL; /* figure out which columns later... */
8032                                         n->quals = NULL; /* fill later */
8033                                         $$ = n;
8034                                 }
8035                 ;
8036
8037 alias_clause:
8038                         AS ColId '(' name_list ')'
8039                                 {
8040                                         $$ = makeNode(Alias);
8041                                         $$->aliasname = $2;
8042                                         $$->colnames = $4;
8043                                 }
8044                         | AS ColId
8045                                 {
8046                                         $$ = makeNode(Alias);
8047                                         $$->aliasname = $2;
8048                                 }
8049                         | ColId '(' name_list ')'
8050                                 {
8051                                         $$ = makeNode(Alias);
8052                                         $$->aliasname = $1;
8053                                         $$->colnames = $3;
8054                                 }
8055                         | ColId
8056                                 {
8057                                         $$ = makeNode(Alias);
8058                                         $$->aliasname = $1;
8059                                 }
8060                 ;
8061
8062 join_type:      FULL join_outer                                                 { $$ = JOIN_FULL; }
8063                         | LEFT join_outer                                               { $$ = JOIN_LEFT; }
8064                         | RIGHT join_outer                                              { $$ = JOIN_RIGHT; }
8065                         | INNER_P                                                               { $$ = JOIN_INNER; }
8066                 ;
8067
8068 /* OUTER is just noise... */
8069 join_outer: OUTER_P                                                                     { $$ = NULL; }
8070                         | /*EMPTY*/                                                             { $$ = NULL; }
8071                 ;
8072
8073 /* JOIN qualification clauses
8074  * Possibilities are:
8075  *      USING ( column list ) allows only unqualified column names,
8076  *                                                which must match between tables.
8077  *      ON expr allows more general qualifications.
8078  *
8079  * We return USING as a List node, while an ON-expr will not be a List.
8080  */
8081
8082 join_qual:      USING '(' name_list ')'                                 { $$ = (Node *) $3; }
8083                         | ON a_expr                                                             { $$ = $2; }
8084                 ;
8085
8086
8087 relation_expr:
8088                         qualified_name
8089                                 {
8090                                         /* default inheritance */
8091                                         $$ = $1;
8092                                         $$->inhOpt = INH_DEFAULT;
8093                                         $$->alias = NULL;
8094                                 }
8095                         | qualified_name '*'
8096                                 {
8097                                         /* inheritance query */
8098                                         $$ = $1;
8099                                         $$->inhOpt = INH_YES;
8100                                         $$->alias = NULL;
8101                                 }
8102                         | ONLY qualified_name
8103                                 {
8104                                         /* no inheritance */
8105                                         $$ = $2;
8106                                         $$->inhOpt = INH_NO;
8107                                         $$->alias = NULL;
8108                                 }
8109                         | ONLY '(' qualified_name ')'
8110                                 {
8111                                         /* no inheritance, SQL99-style syntax */
8112                                         $$ = $3;
8113                                         $$->inhOpt = INH_NO;
8114                                         $$->alias = NULL;
8115                                 }
8116                 ;
8117
8118
8119 relation_expr_list:
8120                         relation_expr                                                   { $$ = list_make1($1); }
8121                         | relation_expr_list ',' relation_expr  { $$ = lappend($1, $3); }
8122                 ;
8123
8124
8125 /*
8126  * Given "UPDATE foo set set ...", we have to decide without looking any
8127  * further ahead whether the first "set" is an alias or the UPDATE's SET
8128  * keyword.  Since "set" is allowed as a column name both interpretations
8129  * are feasible.  We resolve the shift/reduce conflict by giving the first
8130  * relation_expr_opt_alias production a higher precedence than the SET token
8131  * has, causing the parser to prefer to reduce, in effect assuming that the
8132  * SET is not an alias.
8133  */
8134 relation_expr_opt_alias: relation_expr                                  %prec UMINUS
8135                                 {
8136                                         $$ = $1;
8137                                 }
8138                         | relation_expr ColId
8139                                 {
8140                                         Alias *alias = makeNode(Alias);
8141                                         alias->aliasname = $2;
8142                                         $1->alias = alias;
8143                                         $$ = $1;
8144                                 }
8145                         | relation_expr AS ColId
8146                                 {
8147                                         Alias *alias = makeNode(Alias);
8148                                         alias->aliasname = $3;
8149                                         $1->alias = alias;
8150                                         $$ = $1;
8151                                 }
8152                 ;
8153
8154
8155 func_table: func_expr                                                           { $$ = $1; }
8156                 ;
8157
8158
8159 where_clause:
8160                         WHERE a_expr                                                    { $$ = $2; }
8161                         | /*EMPTY*/                                                             { $$ = NULL; }
8162                 ;
8163
8164 /* variant for UPDATE and DELETE */
8165 where_or_current_clause:
8166                         WHERE a_expr                                                    { $$ = $2; }
8167                         | WHERE CURRENT_P OF name
8168                                 {
8169                                         CurrentOfExpr *n = makeNode(CurrentOfExpr);
8170                                         /* cvarno is filled in by parse analysis */
8171                                         n->cursor_name = $4;
8172                                         n->cursor_param = 0;
8173                                         $$ = (Node *) n;
8174                                 }
8175                         | /*EMPTY*/                                                             { $$ = NULL; }
8176                 ;
8177
8178
8179 TableFuncElementList:
8180                         TableFuncElement
8181                                 {
8182                                         $$ = list_make1($1);
8183                                 }
8184                         | TableFuncElementList ',' TableFuncElement
8185                                 {
8186                                         $$ = lappend($1, $3);
8187                                 }
8188                 ;
8189
8190 TableFuncElement:       ColId Typename
8191                                 {
8192                                         ColumnDef *n = makeNode(ColumnDef);
8193                                         n->colname = $1;
8194                                         n->typeName = $2;
8195                                         n->constraints = NIL;
8196                                         n->is_local = true;
8197                                         $$ = (Node *)n;
8198                                 }
8199                 ;
8200
8201 /*****************************************************************************
8202  *
8203  *      Type syntax
8204  *              SQL92 introduces a large amount of type-specific syntax.
8205  *              Define individual clauses to handle these cases, and use
8206  *               the generic case to handle regular type-extensible Postgres syntax.
8207  *              - thomas 1997-10-10
8208  *
8209  *****************************************************************************/
8210
8211 Typename:       SimpleTypename opt_array_bounds
8212                                 {
8213                                         $$ = $1;
8214                                         $$->arrayBounds = $2;
8215                                 }
8216                         | SETOF SimpleTypename opt_array_bounds
8217                                 {
8218                                         $$ = $2;
8219                                         $$->arrayBounds = $3;
8220                                         $$->setof = TRUE;
8221                                 }
8222                         /* SQL standard syntax, currently only one-dimensional */
8223                         | SimpleTypename ARRAY '[' Iconst ']'
8224                                 {
8225                                         $$ = $1;
8226                                         $$->arrayBounds = list_make1(makeInteger($4));
8227                                 }
8228                         | SETOF SimpleTypename ARRAY '[' Iconst ']'
8229                                 {
8230                                         $$ = $2;
8231                                         $$->arrayBounds = list_make1(makeInteger($5));
8232                                         $$->setof = TRUE;
8233                                 }
8234                         | SimpleTypename ARRAY
8235                                 {
8236                                         $$ = $1;
8237                                         $$->arrayBounds = list_make1(makeInteger(-1));
8238                                 }
8239                         | SETOF SimpleTypename ARRAY
8240                                 {
8241                                         $$ = $2;
8242                                         $$->arrayBounds = list_make1(makeInteger(-1));
8243                                         $$->setof = TRUE;
8244                                 }
8245                 ;
8246
8247 opt_array_bounds:
8248                         opt_array_bounds '[' ']'
8249                                         {  $$ = lappend($1, makeInteger(-1)); }
8250                         | opt_array_bounds '[' Iconst ']'
8251                                         {  $$ = lappend($1, makeInteger($3)); }
8252                         | /*EMPTY*/
8253                                         {  $$ = NIL; }
8254                 ;
8255
8256 SimpleTypename:
8257                         GenericType                                                             { $$ = $1; }
8258                         | Numeric                                                               { $$ = $1; }
8259                         | Bit                                                                   { $$ = $1; }
8260                         | Character                                                             { $$ = $1; }
8261                         | ConstDatetime                                                 { $$ = $1; }
8262                         | ConstInterval opt_interval
8263                                 {
8264                                         $$ = $1;
8265                                         $$->typmods = $2;
8266                                 }
8267                         | ConstInterval '(' Iconst ')' opt_interval
8268                                 {
8269                                         $$ = $1;
8270                                         if ($5 != NIL)
8271                                         {
8272                                                 if (list_length($5) != 1)
8273                                                         ereport(ERROR,
8274                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
8275                                                                          errmsg("interval precision specified twice"),
8276                                                                          parser_errposition(@1)));
8277                                                 $$->typmods = lappend($5, makeIntConst($3, @3));
8278                                         }
8279                                         else
8280                                                 $$->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
8281                                                                                                  makeIntConst($3, @3));
8282                                 }
8283                 ;
8284
8285 /* We have a separate ConstTypename to allow defaulting fixed-length
8286  * types such as CHAR() and BIT() to an unspecified length.
8287  * SQL9x requires that these default to a length of one, but this
8288  * makes no sense for constructs like CHAR 'hi' and BIT '0101',
8289  * where there is an obvious better choice to make.
8290  * Note that ConstInterval is not included here since it must
8291  * be pushed up higher in the rules to accomodate the postfix
8292  * options (e.g. INTERVAL '1' YEAR). Likewise, we have to handle
8293  * the generic-type-name case in AExprConst to avoid premature
8294  * reduce/reduce conflicts against function names.
8295  */
8296 ConstTypename:
8297                         Numeric                                                                 { $$ = $1; }
8298                         | ConstBit                                                              { $$ = $1; }
8299                         | ConstCharacter                                                { $$ = $1; }
8300                         | ConstDatetime                                                 { $$ = $1; }
8301                 ;
8302
8303 /*
8304  * GenericType covers all type names that don't have special syntax mandated
8305  * by the standard, including qualified names.  We also allow type modifiers.
8306  * To avoid parsing conflicts against function invocations, the modifiers
8307  * have to be shown as expr_list here, but parse analysis will only accept
8308  * constants for them.
8309  */
8310 GenericType:
8311                         type_function_name opt_type_modifiers
8312                                 {
8313                                         $$ = makeTypeName($1);
8314                                         $$->typmods = $2;
8315                                         $$->location = @1;
8316                                 }
8317                         | type_function_name attrs opt_type_modifiers
8318                                 {
8319                                         $$ = makeTypeNameFromNameList(lcons(makeString($1), $2));
8320                                         $$->typmods = $3;
8321                                         $$->location = @1;
8322                                 }
8323                 ;
8324
8325 opt_type_modifiers: '(' expr_list ')'                           { $$ = $2; }
8326                                         | /* EMPTY */                                   { $$ = NIL; }
8327                 ;
8328
8329 /*
8330  * SQL92 numeric data types
8331  */
8332 Numeric:        INT_P
8333                                 {
8334                                         $$ = SystemTypeName("int4");
8335                                         $$->location = @1;
8336                                 }
8337                         | INTEGER
8338                                 {
8339                                         $$ = SystemTypeName("int4");
8340                                         $$->location = @1;
8341                                 }
8342                         | SMALLINT
8343                                 {
8344                                         $$ = SystemTypeName("int2");
8345                                         $$->location = @1;
8346                                 }
8347                         | BIGINT
8348                                 {
8349                                         $$ = SystemTypeName("int8");
8350                                         $$->location = @1;
8351                                 }
8352                         | REAL
8353                                 {
8354                                         $$ = SystemTypeName("float4");
8355                                         $$->location = @1;
8356                                 }
8357                         | FLOAT_P opt_float
8358                                 {
8359                                         $$ = $2;
8360                                         $$->location = @1;
8361                                 }
8362                         | DOUBLE_P PRECISION
8363                                 {
8364                                         $$ = SystemTypeName("float8");
8365                                         $$->location = @1;
8366                                 }
8367                         | DECIMAL_P opt_type_modifiers
8368                                 {
8369                                         $$ = SystemTypeName("numeric");
8370                                         $$->typmods = $2;
8371                                         $$->location = @1;
8372                                 }
8373                         | DEC opt_type_modifiers
8374                                 {
8375                                         $$ = SystemTypeName("numeric");
8376                                         $$->typmods = $2;
8377                                         $$->location = @1;
8378                                 }
8379                         | NUMERIC opt_type_modifiers
8380                                 {
8381                                         $$ = SystemTypeName("numeric");
8382                                         $$->typmods = $2;
8383                                         $$->location = @1;
8384                                 }
8385                         | BOOLEAN_P
8386                                 {
8387                                         $$ = SystemTypeName("bool");
8388                                         $$->location = @1;
8389                                 }
8390                 ;
8391
8392 opt_float:      '(' Iconst ')'
8393                                 {
8394                                         /*
8395                                          * Check FLOAT() precision limits assuming IEEE floating
8396                                          * types - thomas 1997-09-18
8397                                          */
8398                                         if ($2 < 1)
8399                                                 ereport(ERROR,
8400                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8401                                                                  errmsg("precision for type float must be at least 1 bit"),
8402                                                                  parser_errposition(@2)));
8403                                         else if ($2 <= 24)
8404                                                 $$ = SystemTypeName("float4");
8405                                         else if ($2 <= 53)
8406                                                 $$ = SystemTypeName("float8");
8407                                         else
8408                                                 ereport(ERROR,
8409                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
8410                                                                  errmsg("precision for type float must be less than 54 bits"),
8411                                                                  parser_errposition(@2)));
8412                                 }
8413                         | /*EMPTY*/
8414                                 {
8415                                         $$ = SystemTypeName("float8");
8416                                 }
8417                 ;
8418
8419 /*
8420  * SQL92 bit-field data types
8421  * The following implements BIT() and BIT VARYING().
8422  */
8423 Bit:            BitWithLength
8424                                 {
8425                                         $$ = $1;
8426                                 }
8427                         | BitWithoutLength
8428                                 {
8429                                         $$ = $1;
8430                                 }
8431                 ;
8432
8433 /* ConstBit is like Bit except "BIT" defaults to unspecified length */
8434 /* See notes for ConstCharacter, which addresses same issue for "CHAR" */
8435 ConstBit:       BitWithLength
8436                                 {
8437                                         $$ = $1;
8438                                 }
8439                         | BitWithoutLength
8440                                 {
8441                                         $$ = $1;
8442                                         $$->typmods = NIL;
8443                                 }
8444                 ;
8445
8446 BitWithLength:
8447                         BIT opt_varying '(' expr_list ')'
8448                                 {
8449                                         char *typname;
8450
8451                                         typname = $2 ? "varbit" : "bit";
8452                                         $$ = SystemTypeName(typname);
8453                                         $$->typmods = $4;
8454                                         $$->location = @1;
8455                                 }
8456                 ;
8457
8458 BitWithoutLength:
8459                         BIT opt_varying
8460                                 {
8461                                         /* bit defaults to bit(1), varbit to no limit */
8462                                         if ($2)
8463                                         {
8464                                                 $$ = SystemTypeName("varbit");
8465                                         }
8466                                         else
8467                                         {
8468                                                 $$ = SystemTypeName("bit");
8469                                                 $$->typmods = list_make1(makeIntConst(1, -1));
8470                                         }
8471                                         $$->location = @1;
8472                                 }
8473                 ;
8474
8475
8476 /*
8477  * SQL92 character data types
8478  * The following implements CHAR() and VARCHAR().
8479  */
8480 Character:  CharacterWithLength
8481                                 {
8482                                         $$ = $1;
8483                                 }
8484                         | CharacterWithoutLength
8485                                 {
8486                                         $$ = $1;
8487                                 }
8488                 ;
8489
8490 ConstCharacter:  CharacterWithLength
8491                                 {
8492                                         $$ = $1;
8493                                 }
8494                         | CharacterWithoutLength
8495                                 {
8496                                         /* Length was not specified so allow to be unrestricted.
8497                                          * This handles problems with fixed-length (bpchar) strings
8498                                          * which in column definitions must default to a length
8499                                          * of one, but should not be constrained if the length
8500                                          * was not specified.
8501                                          */
8502                                         $$ = $1;
8503                                         $$->typmods = NIL;
8504                                 }
8505                 ;
8506
8507 CharacterWithLength:  character '(' Iconst ')' opt_charset
8508                                 {
8509                                         if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
8510                                         {
8511                                                 char *type;
8512
8513                                                 type = palloc(strlen($1) + 1 + strlen($5) + 1);
8514                                                 strcpy(type, $1);
8515                                                 strcat(type, "_");
8516                                                 strcat(type, $5);
8517                                                 $1 = type;
8518                                         }
8519
8520                                         $$ = SystemTypeName($1);
8521                                         $$->typmods = list_make1(makeIntConst($3, @3));
8522                                         $$->location = @1;
8523                                 }
8524                 ;
8525
8526 CharacterWithoutLength:  character opt_charset
8527                                 {
8528                                         if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
8529                                         {
8530                                                 char *type;
8531
8532                                                 type = palloc(strlen($1) + 1 + strlen($2) + 1);
8533                                                 strcpy(type, $1);
8534                                                 strcat(type, "_");
8535                                                 strcat(type, $2);
8536                                                 $1 = type;
8537                                         }
8538
8539                                         $$ = SystemTypeName($1);
8540
8541                                         /* char defaults to char(1), varchar to no limit */
8542                                         if (strcmp($1, "bpchar") == 0)
8543                                                 $$->typmods = list_make1(makeIntConst(1, -1));
8544
8545                                         $$->location = @1;
8546                                 }
8547                 ;
8548
8549 character:      CHARACTER opt_varying
8550                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
8551                         | CHAR_P opt_varying
8552                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
8553                         | VARCHAR
8554                                                                                 { $$ = "varchar"; }
8555                         | NATIONAL CHARACTER opt_varying
8556                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
8557                         | NATIONAL CHAR_P opt_varying
8558                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
8559                         | NCHAR opt_varying
8560                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
8561                 ;
8562
8563 opt_varying:
8564                         VARYING                                                                 { $$ = TRUE; }
8565                         | /*EMPTY*/                                                             { $$ = FALSE; }
8566                 ;
8567
8568 opt_charset:
8569                         CHARACTER SET ColId                                             { $$ = $3; }
8570                         | /*EMPTY*/                                                             { $$ = NULL; }
8571                 ;
8572
8573 /*
8574  * SQL92 date/time types
8575  */
8576 ConstDatetime:
8577                         TIMESTAMP '(' Iconst ')' opt_timezone
8578                                 {
8579                                         if ($5)
8580                                                 $$ = SystemTypeName("timestamptz");
8581                                         else
8582                                                 $$ = SystemTypeName("timestamp");
8583                                         $$->typmods = list_make1(makeIntConst($3, @3));
8584                                         $$->location = @1;
8585                                 }
8586                         | TIMESTAMP opt_timezone
8587                                 {
8588                                         if ($2)
8589                                                 $$ = SystemTypeName("timestamptz");
8590                                         else
8591                                                 $$ = SystemTypeName("timestamp");
8592                                         $$->location = @1;
8593                                 }
8594                         | TIME '(' Iconst ')' opt_timezone
8595                                 {
8596                                         if ($5)
8597                                                 $$ = SystemTypeName("timetz");
8598                                         else
8599                                                 $$ = SystemTypeName("time");
8600                                         $$->typmods = list_make1(makeIntConst($3, @3));
8601                                         $$->location = @1;
8602                                 }
8603                         | TIME opt_timezone
8604                                 {
8605                                         if ($2)
8606                                                 $$ = SystemTypeName("timetz");
8607                                         else
8608                                                 $$ = SystemTypeName("time");
8609                                         $$->location = @1;
8610                                 }
8611                 ;
8612
8613 ConstInterval:
8614                         INTERVAL
8615                                 {
8616                                         $$ = SystemTypeName("interval");
8617                                         $$->location = @1;
8618                                 }
8619                 ;
8620
8621 opt_timezone:
8622                         WITH_TIME ZONE                                                  { $$ = TRUE; }
8623                         | WITHOUT TIME ZONE                                             { $$ = FALSE; }
8624                         | /*EMPTY*/                                                             { $$ = FALSE; }
8625                 ;
8626
8627 opt_interval:
8628                         YEAR_P
8629                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR), @1)); }
8630                         | MONTH_P
8631                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MONTH), @1)); }
8632                         | DAY_P
8633                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY), @1)); }
8634                         | HOUR_P
8635                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR), @1)); }
8636                         | MINUTE_P
8637                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MINUTE), @1)); }
8638                         | interval_second
8639                                 { $$ = $1; }
8640                         | YEAR_P TO MONTH_P
8641                                 {
8642                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR) |
8643                                                                                                  INTERVAL_MASK(MONTH), @1));
8644                                 }
8645                         | DAY_P TO HOUR_P
8646                                 {
8647                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
8648                                                                                                  INTERVAL_MASK(HOUR), @1));
8649                                 }
8650                         | DAY_P TO MINUTE_P
8651                                 {
8652                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
8653                                                                                                  INTERVAL_MASK(HOUR) |
8654                                                                                                  INTERVAL_MASK(MINUTE), @1));
8655                                 }
8656                         | DAY_P TO interval_second
8657                                 {
8658                                         $$ = $3;
8659                                         linitial($$) = makeIntConst(INTERVAL_MASK(DAY) |
8660                                                                                                 INTERVAL_MASK(HOUR) |
8661                                                                                                 INTERVAL_MASK(MINUTE) |
8662                                                                                                 INTERVAL_MASK(SECOND), @1);
8663                                 }
8664                         | HOUR_P TO MINUTE_P
8665                                 {
8666                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR) |
8667                                                                                                  INTERVAL_MASK(MINUTE), @1));
8668                                 }
8669                         | HOUR_P TO interval_second
8670                                 {
8671                                         $$ = $3;
8672                                         linitial($$) = makeIntConst(INTERVAL_MASK(HOUR) |
8673                                                                                                 INTERVAL_MASK(MINUTE) |
8674                                                                                                 INTERVAL_MASK(SECOND), @1);
8675                                 }
8676                         | MINUTE_P TO interval_second
8677                                 {
8678                                         $$ = $3;
8679                                         linitial($$) = makeIntConst(INTERVAL_MASK(MINUTE) |
8680                                                                                                 INTERVAL_MASK(SECOND), @1);
8681                                 }
8682                         | /*EMPTY*/
8683                                 { $$ = NIL; }
8684                 ;
8685
8686 interval_second:
8687                         SECOND_P
8688                                 {
8689                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(SECOND), @1));
8690                                 }
8691                         | SECOND_P '(' Iconst ')'
8692                                 {
8693                                         $$ = list_make2(makeIntConst(INTERVAL_MASK(SECOND), @1),
8694                                                                         makeIntConst($3, @3));
8695                                 }
8696                 ;
8697
8698
8699 /*****************************************************************************
8700  *
8701  *      expression grammar
8702  *
8703  *****************************************************************************/
8704
8705 /*
8706  * General expressions
8707  * This is the heart of the expression syntax.
8708  *
8709  * We have two expression types: a_expr is the unrestricted kind, and
8710  * b_expr is a subset that must be used in some places to avoid shift/reduce
8711  * conflicts.  For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
8712  * because that use of AND conflicts with AND as a boolean operator.  So,
8713  * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
8714  *
8715  * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
8716  * always be used by surrounding it with parens.
8717  *
8718  * c_expr is all the productions that are common to a_expr and b_expr;
8719  * it's factored out just to eliminate redundant coding.
8720  */
8721 a_expr:         c_expr                                                                  { $$ = $1; }
8722                         | a_expr TYPECAST Typename
8723                                         { $$ = makeTypeCast($1, $3, @2); }
8724                         | a_expr AT TIME ZONE a_expr
8725                                 {
8726                                         FuncCall *n = makeNode(FuncCall);
8727                                         n->funcname = SystemFuncName("timezone");
8728                                         n->args = list_make2($5, $1);
8729                                         n->agg_order = NIL;
8730                                         n->agg_star = FALSE;
8731                                         n->agg_distinct = FALSE;
8732                                         n->func_variadic = FALSE;
8733                                         n->over = NULL;
8734                                         n->location = @2;
8735                                         $$ = (Node *) n;
8736                                 }
8737                 /*
8738                  * These operators must be called out explicitly in order to make use
8739                  * of bison's automatic operator-precedence handling.  All other
8740                  * operator names are handled by the generic productions using "Op",
8741                  * below; and all those operators will have the same precedence.
8742                  *
8743                  * If you add more explicitly-known operators, be sure to add them
8744                  * also to b_expr and to the MathOp list above.
8745                  */
8746                         | '+' a_expr                                    %prec UMINUS
8747                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
8748                         | '-' a_expr                                    %prec UMINUS
8749                                 { $$ = doNegate($2, @1); }
8750                         | a_expr '+' a_expr
8751                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", $1, $3, @2); }
8752                         | a_expr '-' a_expr
8753                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "-", $1, $3, @2); }
8754                         | a_expr '*' a_expr
8755                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", $1, $3, @2); }
8756                         | a_expr '/' a_expr
8757                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "/", $1, $3, @2); }
8758                         | a_expr '%' a_expr
8759                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "%", $1, $3, @2); }
8760                         | a_expr '^' a_expr
8761                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "^", $1, $3, @2); }
8762                         | a_expr '<' a_expr
8763                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $3, @2); }
8764                         | a_expr '>' a_expr
8765                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $3, @2); }
8766                         | a_expr '=' a_expr
8767                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "=", $1, $3, @2); }
8768
8769                         | a_expr qual_Op a_expr                         %prec Op
8770                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
8771                         | qual_Op a_expr                                        %prec Op
8772                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
8773                         | a_expr qual_Op                                        %prec POSTFIXOP
8774                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
8775
8776                         | a_expr AND a_expr
8777                                 { $$ = (Node *) makeA_Expr(AEXPR_AND, NIL, $1, $3, @2); }
8778                         | a_expr OR a_expr
8779                                 { $$ = (Node *) makeA_Expr(AEXPR_OR, NIL, $1, $3, @2); }
8780                         | NOT a_expr
8781                                 { $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL, $2, @1); }
8782
8783                         | a_expr LIKE a_expr
8784                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~", $1, $3, @2); }
8785                         | a_expr LIKE a_expr ESCAPE a_expr
8786                                 {
8787                                         FuncCall *n = makeNode(FuncCall);
8788                                         n->funcname = SystemFuncName("like_escape");
8789                                         n->args = list_make2($3, $5);
8790                                         n->agg_order = NIL;
8791                                         n->agg_star = FALSE;
8792                                         n->agg_distinct = FALSE;
8793                                         n->func_variadic = FALSE;
8794                                         n->over = NULL;
8795                                         n->location = @2;
8796                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~", $1, (Node *) n, @2);
8797                                 }
8798                         | a_expr NOT LIKE a_expr
8799                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~", $1, $4, @2); }
8800                         | a_expr NOT LIKE a_expr ESCAPE a_expr
8801                                 {
8802                                         FuncCall *n = makeNode(FuncCall);
8803                                         n->funcname = SystemFuncName("like_escape");
8804                                         n->args = list_make2($4, $6);
8805                                         n->agg_order = NIL;
8806                                         n->agg_star = FALSE;
8807                                         n->agg_distinct = FALSE;
8808                                         n->func_variadic = FALSE;
8809                                         n->over = NULL;
8810                                         n->location = @2;
8811                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~", $1, (Node *) n, @2);
8812                                 }
8813                         | a_expr ILIKE a_expr
8814                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~*", $1, $3, @2); }
8815                         | a_expr ILIKE a_expr ESCAPE a_expr
8816                                 {
8817                                         FuncCall *n = makeNode(FuncCall);
8818                                         n->funcname = SystemFuncName("like_escape");
8819                                         n->args = list_make2($3, $5);
8820                                         n->agg_order = NIL;
8821                                         n->agg_star = FALSE;
8822                                         n->agg_distinct = FALSE;
8823                                         n->func_variadic = FALSE;
8824                                         n->over = NULL;
8825                                         n->location = @2;
8826                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~*", $1, (Node *) n, @2);
8827                                 }
8828                         | a_expr NOT ILIKE a_expr
8829                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~*", $1, $4, @2); }
8830                         | a_expr NOT ILIKE a_expr ESCAPE a_expr
8831                                 {
8832                                         FuncCall *n = makeNode(FuncCall);
8833                                         n->funcname = SystemFuncName("like_escape");
8834                                         n->args = list_make2($4, $6);
8835                                         n->agg_order = NIL;
8836                                         n->agg_star = FALSE;
8837                                         n->agg_distinct = FALSE;
8838                                         n->func_variadic = FALSE;
8839                                         n->over = NULL;
8840                                         n->location = @2;
8841                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~*", $1, (Node *) n, @2);
8842                                 }
8843
8844                         | a_expr SIMILAR TO a_expr                              %prec SIMILAR
8845                                 {
8846                                         FuncCall *n = makeNode(FuncCall);
8847                                         n->funcname = SystemFuncName("similar_escape");
8848                                         n->args = list_make2($4, makeNullAConst(-1));
8849                                         n->agg_order = NIL;
8850                                         n->agg_star = FALSE;
8851                                         n->agg_distinct = FALSE;
8852                                         n->func_variadic = FALSE;
8853                                         n->over = NULL;
8854                                         n->location = @2;
8855                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~", $1, (Node *) n, @2);
8856                                 }
8857                         | a_expr SIMILAR TO a_expr ESCAPE a_expr
8858                                 {
8859                                         FuncCall *n = makeNode(FuncCall);
8860                                         n->funcname = SystemFuncName("similar_escape");
8861                                         n->args = list_make2($4, $6);
8862                                         n->agg_order = NIL;
8863                                         n->agg_star = FALSE;
8864                                         n->agg_distinct = FALSE;
8865                                         n->func_variadic = FALSE;
8866                                         n->over = NULL;
8867                                         n->location = @2;
8868                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~", $1, (Node *) n, @2);
8869                                 }
8870                         | a_expr NOT SIMILAR TO a_expr                  %prec SIMILAR
8871                                 {
8872                                         FuncCall *n = makeNode(FuncCall);
8873                                         n->funcname = SystemFuncName("similar_escape");
8874                                         n->args = list_make2($5, makeNullAConst(-1));
8875                                         n->agg_order = NIL;
8876                                         n->agg_star = FALSE;
8877                                         n->agg_distinct = FALSE;
8878                                         n->func_variadic = FALSE;
8879                                         n->over = NULL;
8880                                         n->location = @2;
8881                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~", $1, (Node *) n, @2);
8882                                 }
8883                         | a_expr NOT SIMILAR TO a_expr ESCAPE a_expr
8884                                 {
8885                                         FuncCall *n = makeNode(FuncCall);
8886                                         n->funcname = SystemFuncName("similar_escape");
8887                                         n->args = list_make2($5, $7);
8888                                         n->agg_order = NIL;
8889                                         n->agg_star = FALSE;
8890                                         n->agg_distinct = FALSE;
8891                                         n->func_variadic = FALSE;
8892                                         n->over = NULL;
8893                                         n->location = @2;
8894                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~", $1, (Node *) n, @2);
8895                                 }
8896
8897                         /* NullTest clause
8898                          * Define SQL92-style Null test clause.
8899                          * Allow two forms described in the standard:
8900                          *      a IS NULL
8901                          *      a IS NOT NULL
8902                          * Allow two SQL extensions
8903                          *      a ISNULL
8904                          *      a NOTNULL
8905                          */
8906                         | a_expr IS NULL_P
8907                                 {
8908                                         NullTest *n = makeNode(NullTest);
8909                                         n->arg = (Expr *) $1;
8910                                         n->nulltesttype = IS_NULL;
8911                                         $$ = (Node *)n;
8912                                 }
8913                         | a_expr ISNULL
8914                                 {
8915                                         NullTest *n = makeNode(NullTest);
8916                                         n->arg = (Expr *) $1;
8917                                         n->nulltesttype = IS_NULL;
8918                                         $$ = (Node *)n;
8919                                 }
8920                         | a_expr IS NOT NULL_P
8921                                 {
8922                                         NullTest *n = makeNode(NullTest);
8923                                         n->arg = (Expr *) $1;
8924                                         n->nulltesttype = IS_NOT_NULL;
8925                                         $$ = (Node *)n;
8926                                 }
8927                         | a_expr NOTNULL
8928                                 {
8929                                         NullTest *n = makeNode(NullTest);
8930                                         n->arg = (Expr *) $1;
8931                                         n->nulltesttype = IS_NOT_NULL;
8932                                         $$ = (Node *)n;
8933                                 }
8934                         | row OVERLAPS row
8935                                 {
8936                                         $$ = (Node *)makeOverlaps($1, $3, @2, yyscanner);
8937                                 }
8938                         | a_expr IS TRUE_P
8939                                 {
8940                                         BooleanTest *b = makeNode(BooleanTest);
8941                                         b->arg = (Expr *) $1;
8942                                         b->booltesttype = IS_TRUE;
8943                                         $$ = (Node *)b;
8944                                 }
8945                         | a_expr IS NOT TRUE_P
8946                                 {
8947                                         BooleanTest *b = makeNode(BooleanTest);
8948                                         b->arg = (Expr *) $1;
8949                                         b->booltesttype = IS_NOT_TRUE;
8950                                         $$ = (Node *)b;
8951                                 }
8952                         | a_expr IS FALSE_P
8953                                 {
8954                                         BooleanTest *b = makeNode(BooleanTest);
8955                                         b->arg = (Expr *) $1;
8956                                         b->booltesttype = IS_FALSE;
8957                                         $$ = (Node *)b;
8958                                 }
8959                         | a_expr IS NOT FALSE_P
8960                                 {
8961                                         BooleanTest *b = makeNode(BooleanTest);
8962                                         b->arg = (Expr *) $1;
8963                                         b->booltesttype = IS_NOT_FALSE;
8964                                         $$ = (Node *)b;
8965                                 }
8966                         | a_expr IS UNKNOWN
8967                                 {
8968                                         BooleanTest *b = makeNode(BooleanTest);
8969                                         b->arg = (Expr *) $1;
8970                                         b->booltesttype = IS_UNKNOWN;
8971                                         $$ = (Node *)b;
8972                                 }
8973                         | a_expr IS NOT UNKNOWN
8974                                 {
8975                                         BooleanTest *b = makeNode(BooleanTest);
8976                                         b->arg = (Expr *) $1;
8977                                         b->booltesttype = IS_NOT_UNKNOWN;
8978                                         $$ = (Node *)b;
8979                                 }
8980                         | a_expr IS DISTINCT FROM a_expr                        %prec IS
8981                                 {
8982                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
8983                                 }
8984                         | a_expr IS NOT DISTINCT FROM a_expr            %prec IS
8985                                 {
8986                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
8987                                                                         (Node *) makeSimpleA_Expr(AEXPR_DISTINCT,
8988                                                                                                                           "=", $1, $6, @2),
8989                                                                                          @2);
8990
8991                                 }
8992                         | a_expr IS OF '(' type_list ')'                        %prec IS
8993                                 {
8994                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
8995                                 }
8996                         | a_expr IS NOT OF '(' type_list ')'            %prec IS
8997                                 {
8998                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
8999                                 }
9000                         /*
9001                          *      Ideally we would not use hard-wired operators below but
9002                          *      instead use opclasses.  However, mixed data types and other
9003                          *      issues make this difficult:
9004                          *      http://archives.postgresql.org/pgsql-hackers/2008-08/msg01142.php
9005                          */
9006                         | a_expr BETWEEN opt_asymmetric b_expr AND b_expr               %prec BETWEEN
9007                                 {
9008                                         $$ = (Node *) makeA_Expr(AEXPR_AND, NIL,
9009                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $4, @2),
9010                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $6, @2),
9011                                                                                          @2);
9012                                 }
9013                         | a_expr NOT BETWEEN opt_asymmetric b_expr AND b_expr   %prec BETWEEN
9014                                 {
9015                                         $$ = (Node *) makeA_Expr(AEXPR_OR, NIL,
9016                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $5, @2),
9017                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $7, @2),
9018                                                                                          @2);
9019                                 }
9020                         | a_expr BETWEEN SYMMETRIC b_expr AND b_expr                    %prec BETWEEN
9021                                 {
9022                                         $$ = (Node *) makeA_Expr(AEXPR_OR, NIL,
9023                                                 (Node *) makeA_Expr(AEXPR_AND, NIL,
9024                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $4, @2),
9025                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $6, @2),
9026                                                                                         @2),
9027                                                 (Node *) makeA_Expr(AEXPR_AND, NIL,
9028                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $6, @2),
9029                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $4, @2),
9030                                                                                         @2),
9031                                                                                          @2);
9032                                 }
9033                         | a_expr NOT BETWEEN SYMMETRIC b_expr AND b_expr                %prec BETWEEN
9034                                 {
9035                                         $$ = (Node *) makeA_Expr(AEXPR_AND, NIL,
9036                                                 (Node *) makeA_Expr(AEXPR_OR, NIL,
9037                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $5, @2),
9038                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $7, @2),
9039                                                                                         @2),
9040                                                 (Node *) makeA_Expr(AEXPR_OR, NIL,
9041                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $7, @2),
9042                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $5, @2),
9043                                                                                         @2),
9044                                                                                          @2);
9045                                 }
9046                         | a_expr IN_P in_expr
9047                                 {
9048                                         /* in_expr returns a SubLink or a list of a_exprs */
9049                                         if (IsA($3, SubLink))
9050                                         {
9051                                                 /* generate foo = ANY (subquery) */
9052                                                 SubLink *n = (SubLink *) $3;
9053                                                 n->subLinkType = ANY_SUBLINK;
9054                                                 n->testexpr = $1;
9055                                                 n->operName = list_make1(makeString("="));
9056                                                 n->location = @2;
9057                                                 $$ = (Node *)n;
9058                                         }
9059                                         else
9060                                         {
9061                                                 /* generate scalar IN expression */
9062                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "=", $1, $3, @2);
9063                                         }
9064                                 }
9065                         | a_expr NOT IN_P in_expr
9066                                 {
9067                                         /* in_expr returns a SubLink or a list of a_exprs */
9068                                         if (IsA($4, SubLink))
9069                                         {
9070                                                 /* generate NOT (foo = ANY (subquery)) */
9071                                                 /* Make an = ANY node */
9072                                                 SubLink *n = (SubLink *) $4;
9073                                                 n->subLinkType = ANY_SUBLINK;
9074                                                 n->testexpr = $1;
9075                                                 n->operName = list_make1(makeString("="));
9076                                                 n->location = @3;
9077                                                 /* Stick a NOT on top */
9078                                                 $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL, (Node *) n, @2);
9079                                         }
9080                                         else
9081                                         {
9082                                                 /* generate scalar NOT IN expression */
9083                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "<>", $1, $4, @2);
9084                                         }
9085                                 }
9086                         | a_expr subquery_Op sub_type select_with_parens        %prec Op
9087                                 {
9088                                         SubLink *n = makeNode(SubLink);
9089                                         n->subLinkType = $3;
9090                                         n->testexpr = $1;
9091                                         n->operName = $2;
9092                                         n->subselect = $4;
9093                                         n->location = @2;
9094                                         $$ = (Node *)n;
9095                                 }
9096                         | a_expr subquery_Op sub_type '(' a_expr ')'            %prec Op
9097                                 {
9098                                         if ($3 == ANY_SUBLINK)
9099                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ANY, $2, $1, $5, @2);
9100                                         else
9101                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ALL, $2, $1, $5, @2);
9102                                 }
9103                         | UNIQUE select_with_parens
9104                                 {
9105                                         /* Not sure how to get rid of the parentheses
9106                                          * but there are lots of shift/reduce errors without them.
9107                                          *
9108                                          * Should be able to implement this by plopping the entire
9109                                          * select into a node, then transforming the target expressions
9110                                          * from whatever they are into count(*), and testing the
9111                                          * entire result equal to one.
9112                                          * But, will probably implement a separate node in the executor.
9113                                          */
9114                                         ereport(ERROR,
9115                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9116                                                          errmsg("UNIQUE predicate is not yet implemented"),
9117                                                          parser_errposition(@1)));
9118                                 }
9119                         | a_expr IS DOCUMENT_P                                  %prec IS
9120                                 {
9121                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
9122                                                                          list_make1($1), @2);
9123                                 }
9124                         | a_expr IS NOT DOCUMENT_P                              %prec IS
9125                                 {
9126                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
9127                                                                                          makeXmlExpr(IS_DOCUMENT, NULL, NIL,
9128                                                                                                                  list_make1($1), @2),
9129                                                                                          @2);
9130                                 }
9131                 ;
9132
9133 /*
9134  * Restricted expressions
9135  *
9136  * b_expr is a subset of the complete expression syntax defined by a_expr.
9137  *
9138  * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
9139  * cause trouble in the places where b_expr is used.  For simplicity, we
9140  * just eliminate all the boolean-keyword-operator productions from b_expr.
9141  */
9142 b_expr:         c_expr
9143                                 { $$ = $1; }
9144                         | b_expr TYPECAST Typename
9145                                 { $$ = makeTypeCast($1, $3, @2); }
9146                         | '+' b_expr                                    %prec UMINUS
9147                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
9148                         | '-' b_expr                                    %prec UMINUS
9149                                 { $$ = doNegate($2, @1); }
9150                         | b_expr '+' b_expr
9151                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", $1, $3, @2); }
9152                         | b_expr '-' b_expr
9153                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "-", $1, $3, @2); }
9154                         | b_expr '*' b_expr
9155                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", $1, $3, @2); }
9156                         | b_expr '/' b_expr
9157                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "/", $1, $3, @2); }
9158                         | b_expr '%' b_expr
9159                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "%", $1, $3, @2); }
9160                         | b_expr '^' b_expr
9161                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "^", $1, $3, @2); }
9162                         | b_expr '<' b_expr
9163                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $3, @2); }
9164                         | b_expr '>' b_expr
9165                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $3, @2); }
9166                         | b_expr '=' b_expr
9167                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "=", $1, $3, @2); }
9168                         | b_expr qual_Op b_expr                         %prec Op
9169                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
9170                         | qual_Op b_expr                                        %prec Op
9171                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
9172                         | b_expr qual_Op                                        %prec POSTFIXOP
9173                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
9174                         | b_expr IS DISTINCT FROM b_expr                %prec IS
9175                                 {
9176                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
9177                                 }
9178                         | b_expr IS NOT DISTINCT FROM b_expr    %prec IS
9179                                 {
9180                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL,
9181                                                 NULL, (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $6, @2), @2);
9182                                 }
9183                         | b_expr IS OF '(' type_list ')'                %prec IS
9184                                 {
9185                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
9186                                 }
9187                         | b_expr IS NOT OF '(' type_list ')'    %prec IS
9188                                 {
9189                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
9190                                 }
9191                         | b_expr IS DOCUMENT_P                                  %prec IS
9192                                 {
9193                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
9194                                                                          list_make1($1), @2);
9195                                 }
9196                         | b_expr IS NOT DOCUMENT_P                              %prec IS
9197                                 {
9198                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
9199                                                                                          makeXmlExpr(IS_DOCUMENT, NULL, NIL,
9200                                                                                                                  list_make1($1), @2),
9201                                                                                          @2);
9202                                 }
9203                 ;
9204
9205 /*
9206  * Productions that can be used in both a_expr and b_expr.
9207  *
9208  * Note: productions that refer recursively to a_expr or b_expr mostly
9209  * cannot appear here.  However, it's OK to refer to a_exprs that occur
9210  * inside parentheses, such as function arguments; that cannot introduce
9211  * ambiguity to the b_expr syntax.
9212  */
9213 c_expr:         columnref                                                               { $$ = $1; }
9214                         | AexprConst                                                    { $$ = $1; }
9215                         | PARAM opt_indirection
9216                                 {
9217                                         ParamRef *p = makeNode(ParamRef);
9218                                         p->number = $1;
9219                                         p->location = @1;
9220                                         if ($2)
9221                                         {
9222                                                 A_Indirection *n = makeNode(A_Indirection);
9223                                                 n->arg = (Node *) p;
9224                                                 n->indirection = check_indirection($2, yyscanner);
9225                                                 $$ = (Node *) n;
9226                                         }
9227                                         else
9228                                                 $$ = (Node *) p;
9229                                 }
9230                         | '(' a_expr ')' opt_indirection
9231                                 {
9232                                         if ($4)
9233                                         {
9234                                                 A_Indirection *n = makeNode(A_Indirection);
9235                                                 n->arg = $2;
9236                                                 n->indirection = check_indirection($4, yyscanner);
9237                                                 $$ = (Node *)n;
9238                                         }
9239                                         else
9240                                                 $$ = $2;
9241                                 }
9242                         | case_expr
9243                                 { $$ = $1; }
9244                         | func_expr
9245                                 { $$ = $1; }
9246                         | select_with_parens                    %prec UMINUS
9247                                 {
9248                                         SubLink *n = makeNode(SubLink);
9249                                         n->subLinkType = EXPR_SUBLINK;
9250                                         n->testexpr = NULL;
9251                                         n->operName = NIL;
9252                                         n->subselect = $1;
9253                                         n->location = @1;
9254                                         $$ = (Node *)n;
9255                                 }
9256                         | EXISTS select_with_parens
9257                                 {
9258                                         SubLink *n = makeNode(SubLink);
9259                                         n->subLinkType = EXISTS_SUBLINK;
9260                                         n->testexpr = NULL;
9261                                         n->operName = NIL;
9262                                         n->subselect = $2;
9263                                         n->location = @1;
9264                                         $$ = (Node *)n;
9265                                 }
9266                         | ARRAY select_with_parens
9267                                 {
9268                                         SubLink *n = makeNode(SubLink);
9269                                         n->subLinkType = ARRAY_SUBLINK;
9270                                         n->testexpr = NULL;
9271                                         n->operName = NIL;
9272                                         n->subselect = $2;
9273                                         n->location = @1;
9274                                         $$ = (Node *)n;
9275                                 }
9276                         | ARRAY array_expr
9277                                 {
9278                                         A_ArrayExpr *n = (A_ArrayExpr *) $2;
9279                                         Assert(IsA(n, A_ArrayExpr));
9280                                         /* point outermost A_ArrayExpr to the ARRAY keyword */
9281                                         n->location = @1;
9282                                         $$ = (Node *)n;
9283                                 }
9284                         | row
9285                                 {
9286                                         RowExpr *r = makeNode(RowExpr);
9287                                         r->args = $1;
9288                                         r->row_typeid = InvalidOid;     /* not analyzed yet */
9289                                         r->location = @1;
9290                                         $$ = (Node *)r;
9291                                 }
9292                 ;
9293
9294 /*
9295  * func_expr is split out from c_expr just so that we have a classification
9296  * for "everything that is a function call or looks like one".  This isn't
9297  * very important, but it saves us having to document which variants are
9298  * legal in the backwards-compatible functional-index syntax for CREATE INDEX.
9299  * (Note that many of the special SQL functions wouldn't actually make any
9300  * sense as functional index entries, but we ignore that consideration here.)
9301  */
9302 func_expr:      func_name '(' ')' over_clause
9303                                 {
9304                                         FuncCall *n = makeNode(FuncCall);
9305                                         n->funcname = $1;
9306                                         n->args = NIL;
9307                                         n->agg_order = NIL;
9308                                         n->agg_star = FALSE;
9309                                         n->agg_distinct = FALSE;
9310                                         n->func_variadic = FALSE;
9311                                         n->over = $4;
9312                                         n->location = @1;
9313                                         $$ = (Node *)n;
9314                                 }
9315                         | func_name '(' func_arg_list ')' over_clause
9316                                 {
9317                                         FuncCall *n = makeNode(FuncCall);
9318                                         n->funcname = $1;
9319                                         n->args = $3;
9320                                         n->agg_order = NIL;
9321                                         n->agg_star = FALSE;
9322                                         n->agg_distinct = FALSE;
9323                                         n->func_variadic = FALSE;
9324                                         n->over = $5;
9325                                         n->location = @1;
9326                                         $$ = (Node *)n;
9327                                 }
9328                         | func_name '(' VARIADIC func_arg_expr ')' over_clause
9329                                 {
9330                                         FuncCall *n = makeNode(FuncCall);
9331                                         n->funcname = $1;
9332                                         n->args = list_make1($4);
9333                                         n->agg_order = NIL;
9334                                         n->agg_star = FALSE;
9335                                         n->agg_distinct = FALSE;
9336                                         n->func_variadic = TRUE;
9337                                         n->over = $6;
9338                                         n->location = @1;
9339                                         $$ = (Node *)n;
9340                                 }
9341                         | func_name '(' func_arg_list ',' VARIADIC func_arg_expr ')' over_clause
9342                                 {
9343                                         FuncCall *n = makeNode(FuncCall);
9344                                         n->funcname = $1;
9345                                         n->args = lappend($3, $6);
9346                                         n->agg_order = NIL;
9347                                         n->agg_star = FALSE;
9348                                         n->agg_distinct = FALSE;
9349                                         n->func_variadic = TRUE;
9350                                         n->over = $8;
9351                                         n->location = @1;
9352                                         $$ = (Node *)n;
9353                                 }
9354                         | func_name '(' func_arg_list sort_clause ')' over_clause
9355                                 {
9356                                         FuncCall *n = makeNode(FuncCall);
9357                                         n->funcname = $1;
9358                                         n->args = $3;
9359                                         n->agg_order = $4;
9360                                         n->agg_star = FALSE;
9361                                         n->agg_distinct = FALSE;
9362                                         n->func_variadic = FALSE;
9363                                         n->over = $6;
9364                                         n->location = @1;
9365                                         $$ = (Node *)n;
9366                                 }
9367                         | func_name '(' ALL func_arg_list opt_sort_clause ')' over_clause
9368                                 {
9369                                         FuncCall *n = makeNode(FuncCall);
9370                                         n->funcname = $1;
9371                                         n->args = $4;
9372                                         n->agg_order = $5;
9373                                         n->agg_star = FALSE;
9374                                         n->agg_distinct = FALSE;
9375                                         /* Ideally we'd mark the FuncCall node to indicate
9376                                          * "must be an aggregate", but there's no provision
9377                                          * for that in FuncCall at the moment.
9378                                          */
9379                                         n->func_variadic = FALSE;
9380                                         n->over = $7;
9381                                         n->location = @1;
9382                                         $$ = (Node *)n;
9383                                 }
9384                         | func_name '(' DISTINCT func_arg_list opt_sort_clause ')' over_clause
9385                                 {
9386                                         FuncCall *n = makeNode(FuncCall);
9387                                         n->funcname = $1;
9388                                         n->args = $4;
9389                                         n->agg_order = $5;
9390                                         n->agg_star = FALSE;
9391                                         n->agg_distinct = TRUE;
9392                                         n->func_variadic = FALSE;
9393                                         n->over = $7;
9394                                         n->location = @1;
9395                                         $$ = (Node *)n;
9396                                 }
9397                         | func_name '(' '*' ')' over_clause
9398                                 {
9399                                         /*
9400                                          * We consider AGGREGATE(*) to invoke a parameterless
9401                                          * aggregate.  This does the right thing for COUNT(*),
9402                                          * and there are no other aggregates in SQL92 that accept
9403                                          * '*' as parameter.
9404                                          *
9405                                          * The FuncCall node is also marked agg_star = true,
9406                                          * so that later processing can detect what the argument
9407                                          * really was.
9408                                          */
9409                                         FuncCall *n = makeNode(FuncCall);
9410                                         n->funcname = $1;
9411                                         n->args = NIL;
9412                                         n->agg_order = NIL;
9413                                         n->agg_star = TRUE;
9414                                         n->agg_distinct = FALSE;
9415                                         n->func_variadic = FALSE;
9416                                         n->over = $5;
9417                                         n->location = @1;
9418                                         $$ = (Node *)n;
9419                                 }
9420                         | CURRENT_DATE
9421                                 {
9422                                         /*
9423                                          * Translate as "'now'::text::date".
9424                                          *
9425                                          * We cannot use "'now'::date" because coerce_type() will
9426                                          * immediately reduce that to a constant representing
9427                                          * today's date.  We need to delay the conversion until
9428                                          * runtime, else the wrong things will happen when
9429                                          * CURRENT_DATE is used in a column default value or rule.
9430                                          *
9431                                          * This could be simplified if we had a way to generate
9432                                          * an expression tree representing runtime application
9433                                          * of type-input conversion functions.  (As of PG 7.3
9434                                          * that is actually possible, but not clear that we want
9435                                          * to rely on it.)
9436                                          */
9437                                         Node *n;
9438                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9439                                         $$ = makeTypeCast(n, SystemTypeName("date"), -1);
9440                                 }
9441                         | CURRENT_TIME
9442                                 {
9443                                         /*
9444                                          * Translate as "'now'::text::timetz".
9445                                          * See comments for CURRENT_DATE.
9446                                          */
9447                                         Node *n;
9448                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9449                                         $$ = makeTypeCast(n, SystemTypeName("timetz"), -1);
9450                                 }
9451                         | CURRENT_TIME '(' Iconst ')'
9452                                 {
9453                                         /*
9454                                          * Translate as "'now'::text::timetz(n)".
9455                                          * See comments for CURRENT_DATE.
9456                                          */
9457                                         Node *n;
9458                                         TypeName *d;
9459                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9460                                         d = SystemTypeName("timetz");
9461                                         d->typmods = list_make1(makeIntConst($3, @3));
9462                                         $$ = makeTypeCast(n, d, -1);
9463                                 }
9464                         | CURRENT_TIMESTAMP
9465                                 {
9466                                         /*
9467                                          * Translate as "now()", since we have a function that
9468                                          * does exactly what is needed.
9469                                          */
9470                                         FuncCall *n = makeNode(FuncCall);
9471                                         n->funcname = SystemFuncName("now");
9472                                         n->args = NIL;
9473                                         n->agg_order = NIL;
9474                                         n->agg_star = FALSE;
9475                                         n->agg_distinct = FALSE;
9476                                         n->func_variadic = FALSE;
9477                                         n->over = NULL;
9478                                         n->location = @1;
9479                                         $$ = (Node *)n;
9480                                 }
9481                         | CURRENT_TIMESTAMP '(' Iconst ')'
9482                                 {
9483                                         /*
9484                                          * Translate as "'now'::text::timestamptz(n)".
9485                                          * See comments for CURRENT_DATE.
9486                                          */
9487                                         Node *n;
9488                                         TypeName *d;
9489                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9490                                         d = SystemTypeName("timestamptz");
9491                                         d->typmods = list_make1(makeIntConst($3, @3));
9492                                         $$ = makeTypeCast(n, d, -1);
9493                                 }
9494                         | LOCALTIME
9495                                 {
9496                                         /*
9497                                          * Translate as "'now'::text::time".
9498                                          * See comments for CURRENT_DATE.
9499                                          */
9500                                         Node *n;
9501                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9502                                         $$ = makeTypeCast((Node *)n, SystemTypeName("time"), -1);
9503                                 }
9504                         | LOCALTIME '(' Iconst ')'
9505                                 {
9506                                         /*
9507                                          * Translate as "'now'::text::time(n)".
9508                                          * See comments for CURRENT_DATE.
9509                                          */
9510                                         Node *n;
9511                                         TypeName *d;
9512                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9513                                         d = SystemTypeName("time");
9514                                         d->typmods = list_make1(makeIntConst($3, @3));
9515                                         $$ = makeTypeCast((Node *)n, d, -1);
9516                                 }
9517                         | LOCALTIMESTAMP
9518                                 {
9519                                         /*
9520                                          * Translate as "'now'::text::timestamp".
9521                                          * See comments for CURRENT_DATE.
9522                                          */
9523                                         Node *n;
9524                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9525                                         $$ = makeTypeCast(n, SystemTypeName("timestamp"), -1);
9526                                 }
9527                         | LOCALTIMESTAMP '(' Iconst ')'
9528                                 {
9529                                         /*
9530                                          * Translate as "'now'::text::timestamp(n)".
9531                                          * See comments for CURRENT_DATE.
9532                                          */
9533                                         Node *n;
9534                                         TypeName *d;
9535                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
9536                                         d = SystemTypeName("timestamp");
9537                                         d->typmods = list_make1(makeIntConst($3, @3));
9538                                         $$ = makeTypeCast(n, d, -1);
9539                                 }
9540                         | CURRENT_ROLE
9541                                 {
9542                                         FuncCall *n = makeNode(FuncCall);
9543                                         n->funcname = SystemFuncName("current_user");
9544                                         n->args = NIL;
9545                                         n->agg_order = NIL;
9546                                         n->agg_star = FALSE;
9547                                         n->agg_distinct = FALSE;
9548                                         n->func_variadic = FALSE;
9549                                         n->over = NULL;
9550                                         n->location = @1;
9551                                         $$ = (Node *)n;
9552                                 }
9553                         | CURRENT_USER
9554                                 {
9555                                         FuncCall *n = makeNode(FuncCall);
9556                                         n->funcname = SystemFuncName("current_user");
9557                                         n->args = NIL;
9558                                         n->agg_order = NIL;
9559                                         n->agg_star = FALSE;
9560                                         n->agg_distinct = FALSE;
9561                                         n->func_variadic = FALSE;
9562                                         n->over = NULL;
9563                                         n->location = @1;
9564                                         $$ = (Node *)n;
9565                                 }
9566                         | SESSION_USER
9567                                 {
9568                                         FuncCall *n = makeNode(FuncCall);
9569                                         n->funcname = SystemFuncName("session_user");
9570                                         n->args = NIL;
9571                                         n->agg_order = NIL;
9572                                         n->agg_star = FALSE;
9573                                         n->agg_distinct = FALSE;
9574                                         n->func_variadic = FALSE;
9575                                         n->over = NULL;
9576                                         n->location = @1;
9577                                         $$ = (Node *)n;
9578                                 }
9579                         | USER
9580                                 {
9581                                         FuncCall *n = makeNode(FuncCall);
9582                                         n->funcname = SystemFuncName("current_user");
9583                                         n->args = NIL;
9584                                         n->agg_order = NIL;
9585                                         n->agg_star = FALSE;
9586                                         n->agg_distinct = FALSE;
9587                                         n->func_variadic = FALSE;
9588                                         n->over = NULL;
9589                                         n->location = @1;
9590                                         $$ = (Node *)n;
9591                                 }
9592                         | CURRENT_CATALOG
9593                                 {
9594                                         FuncCall *n = makeNode(FuncCall);
9595                                         n->funcname = SystemFuncName("current_database");
9596                                         n->args = NIL;
9597                                         n->agg_order = NIL;
9598                                         n->agg_star = FALSE;
9599                                         n->agg_distinct = FALSE;
9600                                         n->func_variadic = FALSE;
9601                                         n->over = NULL;
9602                                         n->location = @1;
9603                                         $$ = (Node *)n;
9604                                 }
9605                         | CURRENT_SCHEMA
9606                                 {
9607                                         FuncCall *n = makeNode(FuncCall);
9608                                         n->funcname = SystemFuncName("current_schema");
9609                                         n->args = NIL;
9610                                         n->agg_order = NIL;
9611                                         n->agg_star = FALSE;
9612                                         n->agg_distinct = FALSE;
9613                                         n->func_variadic = FALSE;
9614                                         n->over = NULL;
9615                                         n->location = @1;
9616                                         $$ = (Node *)n;
9617                                 }
9618                         | CAST '(' a_expr AS Typename ')'
9619                                 { $$ = makeTypeCast($3, $5, @1); }
9620                         | EXTRACT '(' extract_list ')'
9621                                 {
9622                                         FuncCall *n = makeNode(FuncCall);
9623                                         n->funcname = SystemFuncName("date_part");
9624                                         n->args = $3;
9625                                         n->agg_order = NIL;
9626                                         n->agg_star = FALSE;
9627                                         n->agg_distinct = FALSE;
9628                                         n->func_variadic = FALSE;
9629                                         n->over = NULL;
9630                                         n->location = @1;
9631                                         $$ = (Node *)n;
9632                                 }
9633                         | OVERLAY '(' overlay_list ')'
9634                                 {
9635                                         /* overlay(A PLACING B FROM C FOR D) is converted to
9636                                          * overlay(A, B, C, D)
9637                                          * overlay(A PLACING B FROM C) is converted to
9638                                          * overlay(A, B, C)
9639                                          */
9640                                         FuncCall *n = makeNode(FuncCall);
9641                                         n->funcname = SystemFuncName("overlay");
9642                                         n->args = $3;
9643                                         n->agg_order = NIL;
9644                                         n->agg_star = FALSE;
9645                                         n->agg_distinct = FALSE;
9646                                         n->func_variadic = FALSE;
9647                                         n->over = NULL;
9648                                         n->location = @1;
9649                                         $$ = (Node *)n;
9650                                 }
9651                         | POSITION '(' position_list ')'
9652                                 {
9653                                         /* position(A in B) is converted to position(B, A) */
9654                                         FuncCall *n = makeNode(FuncCall);
9655                                         n->funcname = SystemFuncName("position");
9656                                         n->args = $3;
9657                                         n->agg_order = NIL;
9658                                         n->agg_star = FALSE;
9659                                         n->agg_distinct = FALSE;
9660                                         n->func_variadic = FALSE;
9661                                         n->over = NULL;
9662                                         n->location = @1;
9663                                         $$ = (Node *)n;
9664                                 }
9665                         | SUBSTRING '(' substr_list ')'
9666                                 {
9667                                         /* substring(A from B for C) is converted to
9668                                          * substring(A, B, C) - thomas 2000-11-28
9669                                          */
9670                                         FuncCall *n = makeNode(FuncCall);
9671                                         n->funcname = SystemFuncName("substring");
9672                                         n->args = $3;
9673                                         n->agg_order = NIL;
9674                                         n->agg_star = FALSE;
9675                                         n->agg_distinct = FALSE;
9676                                         n->func_variadic = FALSE;
9677                                         n->over = NULL;
9678                                         n->location = @1;
9679                                         $$ = (Node *)n;
9680                                 }
9681                         | TREAT '(' a_expr AS Typename ')'
9682                                 {
9683                                         /* TREAT(expr AS target) converts expr of a particular type to target,
9684                                          * which is defined to be a subtype of the original expression.
9685                                          * In SQL99, this is intended for use with structured UDTs,
9686                                          * but let's make this a generally useful form allowing stronger
9687                                          * coercions than are handled by implicit casting.
9688                                          */
9689                                         FuncCall *n = makeNode(FuncCall);
9690                                         /* Convert SystemTypeName() to SystemFuncName() even though
9691                                          * at the moment they result in the same thing.
9692                                          */
9693                                         n->funcname = SystemFuncName(((Value *)llast($5->names))->val.str);
9694                                         n->args = list_make1($3);
9695                                         n->agg_order = NIL;
9696                                         n->agg_star = FALSE;
9697                                         n->agg_distinct = FALSE;
9698                                         n->func_variadic = FALSE;
9699                                         n->over = NULL;
9700                                         n->location = @1;
9701                                         $$ = (Node *)n;
9702                                 }
9703                         | TRIM '(' BOTH trim_list ')'
9704                                 {
9705                                         /* various trim expressions are defined in SQL92
9706                                          * - thomas 1997-07-19
9707                                          */
9708                                         FuncCall *n = makeNode(FuncCall);
9709                                         n->funcname = SystemFuncName("btrim");
9710                                         n->args = $4;
9711                                         n->agg_order = NIL;
9712                                         n->agg_star = FALSE;
9713                                         n->agg_distinct = FALSE;
9714                                         n->func_variadic = FALSE;
9715                                         n->over = NULL;
9716                                         n->location = @1;
9717                                         $$ = (Node *)n;
9718                                 }
9719                         | TRIM '(' LEADING trim_list ')'
9720                                 {
9721                                         FuncCall *n = makeNode(FuncCall);
9722                                         n->funcname = SystemFuncName("ltrim");
9723                                         n->args = $4;
9724                                         n->agg_order = NIL;
9725                                         n->agg_star = FALSE;
9726                                         n->agg_distinct = FALSE;
9727                                         n->func_variadic = FALSE;
9728                                         n->over = NULL;
9729                                         n->location = @1;
9730                                         $$ = (Node *)n;
9731                                 }
9732                         | TRIM '(' TRAILING trim_list ')'
9733                                 {
9734                                         FuncCall *n = makeNode(FuncCall);
9735                                         n->funcname = SystemFuncName("rtrim");
9736                                         n->args = $4;
9737                                         n->agg_order = NIL;
9738                                         n->agg_star = FALSE;
9739                                         n->agg_distinct = FALSE;
9740                                         n->func_variadic = FALSE;
9741                                         n->over = NULL;
9742                                         n->location = @1;
9743                                         $$ = (Node *)n;
9744                                 }
9745                         | TRIM '(' trim_list ')'
9746                                 {
9747                                         FuncCall *n = makeNode(FuncCall);
9748                                         n->funcname = SystemFuncName("btrim");
9749                                         n->args = $3;
9750                                         n->agg_order = NIL;
9751                                         n->agg_star = FALSE;
9752                                         n->agg_distinct = FALSE;
9753                                         n->func_variadic = FALSE;
9754                                         n->over = NULL;
9755                                         n->location = @1;
9756                                         $$ = (Node *)n;
9757                                 }
9758                         | NULLIF '(' a_expr ',' a_expr ')'
9759                                 {
9760                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_NULLIF, "=", $3, $5, @1);
9761                                 }
9762                         | COALESCE '(' expr_list ')'
9763                                 {
9764                                         CoalesceExpr *c = makeNode(CoalesceExpr);
9765                                         c->args = $3;
9766                                         c->location = @1;
9767                                         $$ = (Node *)c;
9768                                 }
9769                         | GREATEST '(' expr_list ')'
9770                                 {
9771                                         MinMaxExpr *v = makeNode(MinMaxExpr);
9772                                         v->args = $3;
9773                                         v->op = IS_GREATEST;
9774                                         v->location = @1;
9775                                         $$ = (Node *)v;
9776                                 }
9777                         | LEAST '(' expr_list ')'
9778                                 {
9779                                         MinMaxExpr *v = makeNode(MinMaxExpr);
9780                                         v->args = $3;
9781                                         v->op = IS_LEAST;
9782                                         v->location = @1;
9783                                         $$ = (Node *)v;
9784                                 }
9785                         | XMLCONCAT '(' expr_list ')'
9786                                 {
9787                                         $$ = makeXmlExpr(IS_XMLCONCAT, NULL, NIL, $3, @1);
9788                                 }
9789                         | XMLELEMENT '(' NAME_P ColLabel ')'
9790                                 {
9791                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, NIL, @1);
9792                                 }
9793                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ')'
9794                                 {
9795                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, NIL, @1);
9796                                 }
9797                         | XMLELEMENT '(' NAME_P ColLabel ',' expr_list ')'
9798                                 {
9799                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, $6, @1);
9800                                 }
9801                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ',' expr_list ')'
9802                                 {
9803                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, $8, @1);
9804                                 }
9805                         | XMLFOREST '(' xml_attribute_list ')'
9806                                 {
9807                                         $$ = makeXmlExpr(IS_XMLFOREST, NULL, $3, NIL, @1);
9808                                 }
9809                         | XMLPARSE '(' document_or_content a_expr xml_whitespace_option ')'
9810                                 {
9811                                         XmlExpr *x = (XmlExpr *)
9812                                                 makeXmlExpr(IS_XMLPARSE, NULL, NIL,
9813                                                                         list_make2($4, makeBoolAConst($5, -1)),
9814                                                                         @1);
9815                                         x->xmloption = $3;
9816                                         $$ = (Node *)x;
9817                                 }
9818                         | XMLPI '(' NAME_P ColLabel ')'
9819                                 {
9820                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, NIL, @1);
9821                                 }
9822                         | XMLPI '(' NAME_P ColLabel ',' a_expr ')'
9823                                 {
9824                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, list_make1($6), @1);
9825                                 }
9826                         | XMLROOT '(' a_expr ',' xml_root_version opt_xml_root_standalone ')'
9827                                 {
9828                                         $$ = makeXmlExpr(IS_XMLROOT, NULL, NIL,
9829                                                                          list_make3($3, $5, $6), @1);
9830                                 }
9831                         | XMLSERIALIZE '(' document_or_content a_expr AS SimpleTypename ')'
9832                                 {
9833                                         XmlSerialize *n = makeNode(XmlSerialize);
9834                                         n->xmloption = $3;
9835                                         n->expr = $4;
9836                                         n->typeName = $6;
9837                                         n->location = @1;
9838                                         $$ = (Node *)n;
9839                                 }
9840                 ;
9841
9842 /*
9843  * SQL/XML support
9844  */
9845 xml_root_version: VERSION_P a_expr
9846                                 { $$ = $2; }
9847                         | VERSION_P NO VALUE_P
9848                                 { $$ = makeNullAConst(-1); }
9849                 ;
9850
9851 opt_xml_root_standalone: ',' STANDALONE_P YES_P
9852                                 { $$ = makeIntConst(XML_STANDALONE_YES, -1); }
9853                         | ',' STANDALONE_P NO
9854                                 { $$ = makeIntConst(XML_STANDALONE_NO, -1); }
9855                         | ',' STANDALONE_P NO VALUE_P
9856                                 { $$ = makeIntConst(XML_STANDALONE_NO_VALUE, -1); }
9857                         | /*EMPTY*/
9858                                 { $$ = makeIntConst(XML_STANDALONE_OMITTED, -1); }
9859                 ;
9860
9861 xml_attributes: XMLATTRIBUTES '(' xml_attribute_list ')'        { $$ = $3; }
9862                 ;
9863
9864 xml_attribute_list:     xml_attribute_el                                        { $$ = list_make1($1); }
9865                         | xml_attribute_list ',' xml_attribute_el       { $$ = lappend($1, $3); }
9866                 ;
9867
9868 xml_attribute_el: a_expr AS ColLabel
9869                                 {
9870                                         $$ = makeNode(ResTarget);
9871                                         $$->name = $3;
9872                                         $$->indirection = NIL;
9873                                         $$->val = (Node *) $1;
9874                                         $$->location = @1;
9875                                 }
9876                         | a_expr
9877                                 {
9878                                         $$ = makeNode(ResTarget);
9879                                         $$->name = NULL;
9880                                         $$->indirection = NIL;
9881                                         $$->val = (Node *) $1;
9882                                         $$->location = @1;
9883                                 }
9884                 ;
9885
9886 document_or_content: DOCUMENT_P                                         { $$ = XMLOPTION_DOCUMENT; }
9887                         | CONTENT_P                                                             { $$ = XMLOPTION_CONTENT; }
9888                 ;
9889
9890 xml_whitespace_option: PRESERVE WHITESPACE_P            { $$ = TRUE; }
9891                         | STRIP_P WHITESPACE_P                                  { $$ = FALSE; }
9892                         | /*EMPTY*/                                                             { $$ = FALSE; }
9893                 ;
9894
9895 /*
9896  * Window Definitions
9897  */
9898 window_clause:
9899                         WINDOW window_definition_list                   { $$ = $2; }
9900                         | /*EMPTY*/                                                             { $$ = NIL; }
9901                 ;
9902
9903 window_definition_list:
9904                         window_definition                                               { $$ = list_make1($1); }
9905                         | window_definition_list ',' window_definition
9906                                                                                                         { $$ = lappend($1, $3); }
9907                 ;
9908
9909 window_definition:
9910                         ColId AS window_specification
9911                                 {
9912                                         WindowDef *n = $3;
9913                                         n->name = $1;
9914                                         $$ = n;
9915                                 }
9916                 ;
9917
9918 over_clause: OVER window_specification
9919                                 { $$ = $2; }
9920                         | OVER ColId
9921                                 {
9922                                         WindowDef *n = makeNode(WindowDef);
9923                                         n->name = $2;
9924                                         n->refname = NULL;
9925                                         n->partitionClause = NIL;
9926                                         n->orderClause = NIL;
9927                                         n->frameOptions = FRAMEOPTION_DEFAULTS;
9928                                         n->startOffset = NULL;
9929                                         n->endOffset = NULL;
9930                                         n->location = @2;
9931                                         $$ = n;
9932                                 }
9933                         | /*EMPTY*/
9934                                 { $$ = NULL; }
9935                 ;
9936
9937 window_specification: '(' opt_existing_window_name opt_partition_clause
9938                                                 opt_sort_clause opt_frame_clause ')'
9939                                 {
9940                                         WindowDef *n = makeNode(WindowDef);
9941                                         n->name = NULL;
9942                                         n->refname = $2;
9943                                         n->partitionClause = $3;
9944                                         n->orderClause = $4;
9945                                         /* copy relevant fields of opt_frame_clause */
9946                                         n->frameOptions = $5->frameOptions;
9947                                         n->startOffset = $5->startOffset;
9948                                         n->endOffset = $5->endOffset;
9949                                         n->location = @1;
9950                                         $$ = n;
9951                                 }
9952                 ;
9953
9954 /*
9955  * If we see PARTITION, RANGE, or ROWS as the first token after the '('
9956  * of a window_specification, we want the assumption to be that there is
9957  * no existing_window_name; but those keywords are unreserved and so could
9958  * be ColIds.  We fix this by making them have the same precedence as IDENT
9959  * and giving the empty production here a slightly higher precedence, so
9960  * that the shift/reduce conflict is resolved in favor of reducing the rule.
9961  * These keywords are thus precluded from being an existing_window_name but
9962  * are not reserved for any other purpose.
9963  */
9964 opt_existing_window_name: ColId                                         { $$ = $1; }
9965                         | /*EMPTY*/                             %prec Op                { $$ = NULL; }
9966                 ;
9967
9968 opt_partition_clause: PARTITION BY expr_list            { $$ = $3; }
9969                         | /*EMPTY*/                                                             { $$ = NIL; }
9970                 ;
9971
9972 /*
9973  * For frame clauses, we return a WindowDef, but only some fields are used:
9974  * frameOptions, startOffset, and endOffset.
9975  *
9976  * This is only a subset of the full SQL:2008 frame_clause grammar.
9977  * We don't support <window frame exclusion> yet.
9978  */
9979 opt_frame_clause:
9980                         RANGE frame_extent
9981                                 {
9982                                         WindowDef *n = $2;
9983                                         n->frameOptions |= FRAMEOPTION_NONDEFAULT | FRAMEOPTION_RANGE;
9984                                         if (n->frameOptions & (FRAMEOPTION_START_VALUE_PRECEDING |
9985                                                                                    FRAMEOPTION_END_VALUE_PRECEDING))
9986                                                 ereport(ERROR,
9987                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9988                                                                  errmsg("RANGE PRECEDING is only supported with UNBOUNDED"),
9989                                                                  parser_errposition(@1)));
9990                                         if (n->frameOptions & (FRAMEOPTION_START_VALUE_FOLLOWING |
9991                                                                                    FRAMEOPTION_END_VALUE_FOLLOWING))
9992                                                 ereport(ERROR,
9993                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9994                                                                  errmsg("RANGE FOLLOWING is only supported with UNBOUNDED"),
9995                                                                  parser_errposition(@1)));
9996                                         $$ = n;
9997                                 }
9998                         | ROWS frame_extent
9999                                 {
10000                                         WindowDef *n = $2;
10001                                         n->frameOptions |= FRAMEOPTION_NONDEFAULT | FRAMEOPTION_ROWS;
10002                                         $$ = n;
10003                                 }
10004                         | /*EMPTY*/
10005                                 {
10006                                         WindowDef *n = makeNode(WindowDef);
10007                                         n->frameOptions = FRAMEOPTION_DEFAULTS;
10008                                         n->startOffset = NULL;
10009                                         n->endOffset = NULL;
10010                                         $$ = n;
10011                                 }
10012                 ;
10013
10014 frame_extent: frame_bound
10015                                 {
10016                                         WindowDef *n = $1;
10017                                         /* reject invalid cases */
10018                                         if (n->frameOptions & FRAMEOPTION_START_UNBOUNDED_FOLLOWING)
10019                                                 ereport(ERROR,
10020                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
10021                                                                  errmsg("frame start cannot be UNBOUNDED FOLLOWING"),
10022                                                                  parser_errposition(@1)));
10023                                         if (n->frameOptions & FRAMEOPTION_START_VALUE_FOLLOWING)
10024                                                 ereport(ERROR,
10025                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
10026                                                                  errmsg("frame starting from following row cannot end with current row"),
10027                                                                  parser_errposition(@1)));
10028                                         n->frameOptions |= FRAMEOPTION_END_CURRENT_ROW;
10029                                         $$ = n;
10030                                 }
10031                         | BETWEEN frame_bound AND frame_bound
10032                                 {
10033                                         WindowDef *n1 = $2;
10034                                         WindowDef *n2 = $4;
10035                                         /* form merged options */
10036                                         int             frameOptions = n1->frameOptions;
10037                                         /* shift converts START_ options to END_ options */
10038                                         frameOptions |= n2->frameOptions << 1;
10039                                         frameOptions |= FRAMEOPTION_BETWEEN;
10040                                         /* reject invalid cases */
10041                                         if (frameOptions & FRAMEOPTION_START_UNBOUNDED_FOLLOWING)
10042                                                 ereport(ERROR,
10043                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
10044                                                                  errmsg("frame start cannot be UNBOUNDED FOLLOWING"),
10045                                                                  parser_errposition(@2)));
10046                                         if (frameOptions & FRAMEOPTION_END_UNBOUNDED_PRECEDING)
10047                                                 ereport(ERROR,
10048                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
10049                                                                  errmsg("frame end cannot be UNBOUNDED PRECEDING"),
10050                                                                  parser_errposition(@4)));
10051                                         if ((frameOptions & FRAMEOPTION_START_CURRENT_ROW) &&
10052                                                 (frameOptions & FRAMEOPTION_END_VALUE_PRECEDING))
10053                                                 ereport(ERROR,
10054                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
10055                                                                  errmsg("frame starting from current row cannot have preceding rows"),
10056                                                                  parser_errposition(@4)));
10057                                         if ((frameOptions & FRAMEOPTION_START_VALUE_FOLLOWING) &&
10058                                                 (frameOptions & (FRAMEOPTION_END_VALUE_PRECEDING |
10059                                                                                  FRAMEOPTION_END_CURRENT_ROW)))
10060                                                 ereport(ERROR,
10061                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
10062                                                                  errmsg("frame starting from following row cannot have preceding rows"),
10063                                                                  parser_errposition(@4)));
10064                                         n1->frameOptions = frameOptions;
10065                                         n1->endOffset = n2->startOffset;
10066                                         $$ = n1;
10067                                 }
10068                 ;
10069
10070 /*
10071  * This is used for both frame start and frame end, with output set up on
10072  * the assumption it's frame start; the frame_extent productions must reject
10073  * invalid cases.
10074  */
10075 frame_bound:
10076                         UNBOUNDED PRECEDING
10077                                 {
10078                                         WindowDef *n = makeNode(WindowDef);
10079                                         n->frameOptions = FRAMEOPTION_START_UNBOUNDED_PRECEDING;
10080                                         n->startOffset = NULL;
10081                                         n->endOffset = NULL;
10082                                         $$ = n;
10083                                 }
10084                         | UNBOUNDED FOLLOWING
10085                                 {
10086                                         WindowDef *n = makeNode(WindowDef);
10087                                         n->frameOptions = FRAMEOPTION_START_UNBOUNDED_FOLLOWING;
10088                                         n->startOffset = NULL;
10089                                         n->endOffset = NULL;
10090                                         $$ = n;
10091                                 }
10092                         | CURRENT_P ROW
10093                                 {
10094                                         WindowDef *n = makeNode(WindowDef);
10095                                         n->frameOptions = FRAMEOPTION_START_CURRENT_ROW;
10096                                         n->startOffset = NULL;
10097                                         n->endOffset = NULL;
10098                                         $$ = n;
10099                                 }
10100                         | a_expr PRECEDING
10101                                 {
10102                                         WindowDef *n = makeNode(WindowDef);
10103                                         n->frameOptions = FRAMEOPTION_START_VALUE_PRECEDING;
10104                                         n->startOffset = $1;
10105                                         n->endOffset = NULL;
10106                                         $$ = n;
10107                                 }
10108                         | a_expr FOLLOWING
10109                                 {
10110                                         WindowDef *n = makeNode(WindowDef);
10111                                         n->frameOptions = FRAMEOPTION_START_VALUE_FOLLOWING;
10112                                         n->startOffset = $1;
10113                                         n->endOffset = NULL;
10114                                         $$ = n;
10115                                 }
10116                 ;
10117
10118
10119 /*
10120  * Supporting nonterminals for expressions.
10121  */
10122
10123 /* Explicit row production.
10124  *
10125  * SQL99 allows an optional ROW keyword, so we can now do single-element rows
10126  * without conflicting with the parenthesized a_expr production.  Without the
10127  * ROW keyword, there must be more than one a_expr inside the parens.
10128  */
10129 row:            ROW '(' expr_list ')'                                   { $$ = $3; }
10130                         | ROW '(' ')'                                                   { $$ = NIL; }
10131                         | '(' expr_list ',' a_expr ')'                  { $$ = lappend($2, $4); }
10132                 ;
10133
10134 sub_type:       ANY                                                                             { $$ = ANY_SUBLINK; }
10135                         | SOME                                                                  { $$ = ANY_SUBLINK; }
10136                         | ALL                                                                   { $$ = ALL_SUBLINK; }
10137                 ;
10138
10139 all_Op:         Op                                                                              { $$ = $1; }
10140                         | MathOp                                                                { $$ = $1; }
10141                 ;
10142
10143 MathOp:          '+'                                                                    { $$ = "+"; }
10144                         | '-'                                                                   { $$ = "-"; }
10145                         | '*'                                                                   { $$ = "*"; }
10146                         | '/'                                                                   { $$ = "/"; }
10147                         | '%'                                                                   { $$ = "%"; }
10148                         | '^'                                                                   { $$ = "^"; }
10149                         | '<'                                                                   { $$ = "<"; }
10150                         | '>'                                                                   { $$ = ">"; }
10151                         | '='                                                                   { $$ = "="; }
10152                 ;
10153
10154 qual_Op:        Op
10155                                         { $$ = list_make1(makeString($1)); }
10156                         | OPERATOR '(' any_operator ')'
10157                                         { $$ = $3; }
10158                 ;
10159
10160 qual_all_Op:
10161                         all_Op
10162                                         { $$ = list_make1(makeString($1)); }
10163                         | OPERATOR '(' any_operator ')'
10164                                         { $$ = $3; }
10165                 ;
10166
10167 subquery_Op:
10168                         all_Op
10169                                         { $$ = list_make1(makeString($1)); }
10170                         | OPERATOR '(' any_operator ')'
10171                                         { $$ = $3; }
10172                         | LIKE
10173                                         { $$ = list_make1(makeString("~~")); }
10174                         | NOT LIKE
10175                                         { $$ = list_make1(makeString("!~~")); }
10176                         | ILIKE
10177                                         { $$ = list_make1(makeString("~~*")); }
10178                         | NOT ILIKE
10179                                         { $$ = list_make1(makeString("!~~*")); }
10180 /* cannot put SIMILAR TO here, because SIMILAR TO is a hack.
10181  * the regular expression is preprocessed by a function (similar_escape),
10182  * and the ~ operator for posix regular expressions is used.
10183  *        x SIMILAR TO y     ->    x ~ similar_escape(y)
10184  * this transformation is made on the fly by the parser upwards.
10185  * however the SubLink structure which handles any/some/all stuff
10186  * is not ready for such a thing.
10187  */
10188                         ;
10189
10190 expr_list:      a_expr
10191                                 {
10192                                         $$ = list_make1($1);
10193                                 }
10194                         | expr_list ',' a_expr
10195                                 {
10196                                         $$ = lappend($1, $3);
10197                                 }
10198                 ;
10199
10200 /* function arguments can have names */
10201 func_arg_list:  func_arg_expr
10202                                 {
10203                                         $$ = list_make1($1);
10204                                 }
10205                         | func_arg_list ',' func_arg_expr
10206                                 {
10207                                         $$ = lappend($1, $3);
10208                                 }
10209                 ;
10210
10211 func_arg_expr:  a_expr
10212                                 {
10213                                         $$ = $1;
10214                                 }
10215                         | a_expr AS param_name
10216                                 {
10217                                         NamedArgExpr *na = makeNode(NamedArgExpr);
10218                                         na->arg = (Expr *) $1;
10219                                         na->name = $3;
10220                                         na->argnumber = -1;             /* until determined */
10221                                         na->location = @3;
10222                                         $$ = (Node *) na;
10223                                 }
10224                 ;
10225
10226 type_list:      Typename                                                                { $$ = list_make1($1); }
10227                         | type_list ',' Typename                                { $$ = lappend($1, $3); }
10228                 ;
10229
10230 array_expr: '[' expr_list ']'
10231                                 {
10232                                         $$ = makeAArrayExpr($2, @1);
10233                                 }
10234                         | '[' array_expr_list ']'
10235                                 {
10236                                         $$ = makeAArrayExpr($2, @1);
10237                                 }
10238                         | '[' ']'
10239                                 {
10240                                         $$ = makeAArrayExpr(NIL, @1);
10241                                 }
10242                 ;
10243
10244 array_expr_list: array_expr                                                     { $$ = list_make1($1); }
10245                         | array_expr_list ',' array_expr                { $$ = lappend($1, $3); }
10246                 ;
10247
10248
10249 extract_list:
10250                         extract_arg FROM a_expr
10251                                 {
10252                                         $$ = list_make2(makeStringConst($1, @1), $3);
10253                                 }
10254                         | /*EMPTY*/                                                             { $$ = NIL; }
10255                 ;
10256
10257 /* Allow delimited string Sconst in extract_arg as an SQL extension.
10258  * - thomas 2001-04-12
10259  */
10260 extract_arg:
10261                         IDENT                                                                   { $$ = $1; }
10262                         | YEAR_P                                                                { $$ = "year"; }
10263                         | MONTH_P                                                               { $$ = "month"; }
10264                         | DAY_P                                                                 { $$ = "day"; }
10265                         | HOUR_P                                                                { $$ = "hour"; }
10266                         | MINUTE_P                                                              { $$ = "minute"; }
10267                         | SECOND_P                                                              { $$ = "second"; }
10268                         | Sconst                                                                { $$ = $1; }
10269                 ;
10270
10271 /* OVERLAY() arguments
10272  * SQL99 defines the OVERLAY() function:
10273  * o overlay(text placing text from int for int)
10274  * o overlay(text placing text from int)
10275  * and similarly for binary strings
10276  */
10277 overlay_list:
10278                         a_expr overlay_placing substr_from substr_for
10279                                 {
10280                                         $$ = list_make4($1, $2, $3, $4);
10281                                 }
10282                         | a_expr overlay_placing substr_from
10283                                 {
10284                                         $$ = list_make3($1, $2, $3);
10285                                 }
10286                 ;
10287
10288 overlay_placing:
10289                         PLACING a_expr
10290                                 { $$ = $2; }
10291                 ;
10292
10293 /* position_list uses b_expr not a_expr to avoid conflict with general IN */
10294
10295 position_list:
10296                         b_expr IN_P b_expr                                              { $$ = list_make2($3, $1); }
10297                         | /*EMPTY*/                                                             { $$ = NIL; }
10298                 ;
10299
10300 /* SUBSTRING() arguments
10301  * SQL9x defines a specific syntax for arguments to SUBSTRING():
10302  * o substring(text from int for int)
10303  * o substring(text from int) get entire string from starting point "int"
10304  * o substring(text for int) get first "int" characters of string
10305  * o substring(text from pattern) get entire string matching pattern
10306  * o substring(text from pattern for escape) same with specified escape char
10307  * We also want to support generic substring functions which accept
10308  * the usual generic list of arguments. So we will accept both styles
10309  * here, and convert the SQL9x style to the generic list for further
10310  * processing. - thomas 2000-11-28
10311  */
10312 substr_list:
10313                         a_expr substr_from substr_for
10314                                 {
10315                                         $$ = list_make3($1, $2, $3);
10316                                 }
10317                         | a_expr substr_for substr_from
10318                                 {
10319                                         /* not legal per SQL99, but might as well allow it */
10320                                         $$ = list_make3($1, $3, $2);
10321                                 }
10322                         | a_expr substr_from
10323                                 {
10324                                         $$ = list_make2($1, $2);
10325                                 }
10326                         | a_expr substr_for
10327                                 {
10328                                         /*
10329                                          * Since there are no cases where this syntax allows
10330                                          * a textual FOR value, we forcibly cast the argument
10331                                          * to int4.  The possible matches in pg_proc are
10332                                          * substring(text,int4) and substring(text,text),
10333                                          * and we don't want the parser to choose the latter,
10334                                          * which it is likely to do if the second argument
10335                                          * is unknown or doesn't have an implicit cast to int4.
10336                                          */
10337                                         $$ = list_make3($1, makeIntConst(1, -1),
10338                                                                         makeTypeCast($2,
10339                                                                                                  SystemTypeName("int4"), -1));
10340                                 }
10341                         | expr_list
10342                                 {
10343                                         $$ = $1;
10344                                 }
10345                         | /*EMPTY*/
10346                                 { $$ = NIL; }
10347                 ;
10348
10349 substr_from:
10350                         FROM a_expr                                                             { $$ = $2; }
10351                 ;
10352
10353 substr_for: FOR a_expr                                                          { $$ = $2; }
10354                 ;
10355
10356 trim_list:      a_expr FROM expr_list                                   { $$ = lappend($3, $1); }
10357                         | FROM expr_list                                                { $$ = $2; }
10358                         | expr_list                                                             { $$ = $1; }
10359                 ;
10360
10361 in_expr:        select_with_parens
10362                                 {
10363                                         SubLink *n = makeNode(SubLink);
10364                                         n->subselect = $1;
10365                                         /* other fields will be filled later */
10366                                         $$ = (Node *)n;
10367                                 }
10368                         | '(' expr_list ')'                                             { $$ = (Node *)$2; }
10369                 ;
10370
10371 /*
10372  * Define SQL92-style case clause.
10373  * - Full specification
10374  *      CASE WHEN a = b THEN c ... ELSE d END
10375  * - Implicit argument
10376  *      CASE a WHEN b THEN c ... ELSE d END
10377  */
10378 case_expr:      CASE case_arg when_clause_list case_default END_P
10379                                 {
10380                                         CaseExpr *c = makeNode(CaseExpr);
10381                                         c->casetype = InvalidOid; /* not analyzed yet */
10382                                         c->arg = (Expr *) $2;
10383                                         c->args = $3;
10384                                         c->defresult = (Expr *) $4;
10385                                         c->location = @1;
10386                                         $$ = (Node *)c;
10387                                 }
10388                 ;
10389
10390 when_clause_list:
10391                         /* There must be at least one */
10392                         when_clause                                                             { $$ = list_make1($1); }
10393                         | when_clause_list when_clause                  { $$ = lappend($1, $2); }
10394                 ;
10395
10396 when_clause:
10397                         WHEN a_expr THEN a_expr
10398                                 {
10399                                         CaseWhen *w = makeNode(CaseWhen);
10400                                         w->expr = (Expr *) $2;
10401                                         w->result = (Expr *) $4;
10402                                         w->location = @1;
10403                                         $$ = (Node *)w;
10404                                 }
10405                 ;
10406
10407 case_default:
10408                         ELSE a_expr                                                             { $$ = $2; }
10409                         | /*EMPTY*/                                                             { $$ = NULL; }
10410                 ;
10411
10412 case_arg:       a_expr                                                                  { $$ = $1; }
10413                         | /*EMPTY*/                                                             { $$ = NULL; }
10414                 ;
10415
10416 columnref:      ColId
10417                                 {
10418                                         $$ = makeColumnRef($1, NIL, @1, yyscanner);
10419                                 }
10420                         | ColId indirection
10421                                 {
10422                                         $$ = makeColumnRef($1, $2, @1, yyscanner);
10423                                 }
10424                 ;
10425
10426 indirection_el:
10427                         '.' attr_name
10428                                 {
10429                                         $$ = (Node *) makeString($2);
10430                                 }
10431                         | '.' '*'
10432                                 {
10433                                         $$ = (Node *) makeNode(A_Star);
10434                                 }
10435                         | '[' a_expr ']'
10436                                 {
10437                                         A_Indices *ai = makeNode(A_Indices);
10438                                         ai->lidx = NULL;
10439                                         ai->uidx = $2;
10440                                         $$ = (Node *) ai;
10441                                 }
10442                         | '[' a_expr ':' a_expr ']'
10443                                 {
10444                                         A_Indices *ai = makeNode(A_Indices);
10445                                         ai->lidx = $2;
10446                                         ai->uidx = $4;
10447                                         $$ = (Node *) ai;
10448                                 }
10449                 ;
10450
10451 indirection:
10452                         indirection_el                                                  { $$ = list_make1($1); }
10453                         | indirection indirection_el                    { $$ = lappend($1, $2); }
10454                 ;
10455
10456 opt_indirection:
10457                         /*EMPTY*/                                                               { $$ = NIL; }
10458                         | opt_indirection indirection_el                { $$ = lappend($1, $2); }
10459                 ;
10460
10461 opt_asymmetric: ASYMMETRIC
10462                         | /*EMPTY*/
10463                 ;
10464
10465 /*
10466  * The SQL spec defines "contextually typed value expressions" and
10467  * "contextually typed row value constructors", which for our purposes
10468  * are the same as "a_expr" and "row" except that DEFAULT can appear at
10469  * the top level.
10470  */
10471
10472 ctext_expr:
10473                         a_expr                                  { $$ = (Node *) $1; }
10474                         | DEFAULT
10475                                 {
10476                                         SetToDefault *n = makeNode(SetToDefault);
10477                                         n->location = @1;
10478                                         $$ = (Node *) n;
10479                                 }
10480                 ;
10481
10482 ctext_expr_list:
10483                         ctext_expr                                                              { $$ = list_make1($1); }
10484                         | ctext_expr_list ',' ctext_expr                { $$ = lappend($1, $3); }
10485                 ;
10486
10487 /*
10488  * We should allow ROW '(' ctext_expr_list ')' too, but that seems to require
10489  * making VALUES a fully reserved word, which will probably break more apps
10490  * than allowing the noise-word is worth.
10491  */
10492 ctext_row: '(' ctext_expr_list ')'                                      { $$ = $2; }
10493                 ;
10494
10495
10496 /*****************************************************************************
10497  *
10498  *      target list for SELECT
10499  *
10500  *****************************************************************************/
10501
10502 target_list:
10503                         target_el                                                               { $$ = list_make1($1); }
10504                         | target_list ',' target_el                             { $$ = lappend($1, $3); }
10505                 ;
10506
10507 target_el:      a_expr AS ColLabel
10508                                 {
10509                                         $$ = makeNode(ResTarget);
10510                                         $$->name = $3;
10511                                         $$->indirection = NIL;
10512                                         $$->val = (Node *)$1;
10513                                         $$->location = @1;
10514                                 }
10515                         /*
10516                          * We support omitting AS only for column labels that aren't
10517                          * any known keyword.  There is an ambiguity against postfix
10518                          * operators: is "a ! b" an infix expression, or a postfix
10519                          * expression and a column label?  We prefer to resolve this
10520                          * as an infix expression, which we accomplish by assigning
10521                          * IDENT a precedence higher than POSTFIXOP.
10522                          */
10523                         | a_expr IDENT
10524                                 {
10525                                         $$ = makeNode(ResTarget);
10526                                         $$->name = $2;
10527                                         $$->indirection = NIL;
10528                                         $$->val = (Node *)$1;
10529                                         $$->location = @1;
10530                                 }
10531                         | a_expr
10532                                 {
10533                                         $$ = makeNode(ResTarget);
10534                                         $$->name = NULL;
10535                                         $$->indirection = NIL;
10536                                         $$->val = (Node *)$1;
10537                                         $$->location = @1;
10538                                 }
10539                         | '*'
10540                                 {
10541                                         ColumnRef *n = makeNode(ColumnRef);
10542                                         n->fields = list_make1(makeNode(A_Star));
10543                                         n->location = @1;
10544
10545                                         $$ = makeNode(ResTarget);
10546                                         $$->name = NULL;
10547                                         $$->indirection = NIL;
10548                                         $$->val = (Node *)n;
10549                                         $$->location = @1;
10550                                 }
10551                 ;
10552
10553
10554 /*****************************************************************************
10555  *
10556  *      Names and constants
10557  *
10558  *****************************************************************************/
10559
10560 qualified_name_list:
10561                         qualified_name                                                  { $$ = list_make1($1); }
10562                         | qualified_name_list ',' qualified_name { $$ = lappend($1, $3); }
10563                 ;
10564
10565 /*
10566  * The production for a qualified relation name has to exactly match the
10567  * production for a qualified func_name, because in a FROM clause we cannot
10568  * tell which we are parsing until we see what comes after it ('(' for a
10569  * func_name, something else for a relation). Therefore we allow 'indirection'
10570  * which may contain subscripts, and reject that case in the C code.
10571  */
10572 qualified_name:
10573                         ColId
10574                                 {
10575                                         $$ = makeNode(RangeVar);
10576                                         $$->catalogname = NULL;
10577                                         $$->schemaname = NULL;
10578                                         $$->relname = $1;
10579                                         $$->location = @1;
10580                                 }
10581                         | ColId indirection
10582                                 {
10583                                         check_qualified_name($2, yyscanner);
10584                                         $$ = makeNode(RangeVar);
10585                                         switch (list_length($2))
10586                                         {
10587                                                 case 1:
10588                                                         $$->catalogname = NULL;
10589                                                         $$->schemaname = $1;
10590                                                         $$->relname = strVal(linitial($2));
10591                                                         break;
10592                                                 case 2:
10593                                                         $$->catalogname = $1;
10594                                                         $$->schemaname = strVal(linitial($2));
10595                                                         $$->relname = strVal(lsecond($2));
10596                                                         break;
10597                                                 default:
10598                                                         ereport(ERROR,
10599                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
10600                                                                          errmsg("improper qualified name (too many dotted names): %s",
10601                                                                                         NameListToString(lcons(makeString($1), $2))),
10602                                                                          parser_errposition(@1)));
10603                                                         break;
10604                                         }
10605                                         $$->location = @1;
10606                                 }
10607                 ;
10608
10609 name_list:      name
10610                                         { $$ = list_make1(makeString($1)); }
10611                         | name_list ',' name
10612                                         { $$ = lappend($1, makeString($3)); }
10613                 ;
10614
10615
10616 name:           ColId                                                                   { $$ = $1; };
10617
10618 database_name:
10619                         ColId                                                                   { $$ = $1; };
10620
10621 access_method:
10622                         ColId                                                                   { $$ = $1; };
10623
10624 attr_name:      ColLabel                                                                { $$ = $1; };
10625
10626 index_name: ColId                                                                       { $$ = $1; };
10627
10628 file_name:      Sconst                                                                  { $$ = $1; };
10629
10630 /*
10631  * The production for a qualified func_name has to exactly match the
10632  * production for a qualified columnref, because we cannot tell which we
10633  * are parsing until we see what comes after it ('(' or Sconst for a func_name,
10634  * anything else for a columnref).  Therefore we allow 'indirection' which
10635  * may contain subscripts, and reject that case in the C code.  (If we
10636  * ever implement SQL99-like methods, such syntax may actually become legal!)
10637  */
10638 func_name:      type_function_name
10639                                         { $$ = list_make1(makeString($1)); }
10640                         | ColId indirection
10641                                         {
10642                                                 $$ = check_func_name(lcons(makeString($1), $2),
10643                                                                                          yyscanner);
10644                                         }
10645                 ;
10646
10647
10648 /*
10649  * Constants
10650  */
10651 AexprConst: Iconst
10652                                 {
10653                                         $$ = makeIntConst($1, @1);
10654                                 }
10655                         | FCONST
10656                                 {
10657                                         $$ = makeFloatConst($1, @1);
10658                                 }
10659                         | Sconst
10660                                 {
10661                                         $$ = makeStringConst($1, @1);
10662                                 }
10663                         | BCONST
10664                                 {
10665                                         $$ = makeBitStringConst($1, @1);
10666                                 }
10667                         | XCONST
10668                                 {
10669                                         /* This is a bit constant per SQL99:
10670                                          * Without Feature F511, "BIT data type",
10671                                          * a <general literal> shall not be a
10672                                          * <bit string literal> or a <hex string literal>.
10673                                          */
10674                                         $$ = makeBitStringConst($1, @1);
10675                                 }
10676                         | func_name Sconst
10677                                 {
10678                                         /* generic type 'literal' syntax */
10679                                         TypeName *t = makeTypeNameFromNameList($1);
10680                                         t->location = @1;
10681                                         $$ = makeStringConstCast($2, @2, t);
10682                                 }
10683                         | func_name '(' func_arg_list ')' Sconst
10684                                 {
10685                                         /* generic syntax with a type modifier */
10686                                         TypeName *t = makeTypeNameFromNameList($1);
10687                                         ListCell *lc;
10688
10689                                         /*
10690                                          * We must use func_arg_list in the production to avoid
10691                                          * reduce/reduce conflicts, but we don't actually wish
10692                                          * to allow NamedArgExpr in this context.
10693                                          */
10694                                         foreach(lc, $3)
10695                                         {
10696                                                 NamedArgExpr *arg = (NamedArgExpr *) lfirst(lc);
10697
10698                                                 if (IsA(arg, NamedArgExpr))
10699                                                         ereport(ERROR,
10700                                                                     (errcode(ERRCODE_SYNTAX_ERROR),
10701                                                                      errmsg("type modifier cannot have AS name"),
10702                                                                      parser_errposition(arg->location)));
10703                                         }
10704                                         t->typmods = $3;
10705                                         t->location = @1;
10706                                         $$ = makeStringConstCast($5, @5, t);
10707                                 }
10708                         | ConstTypename Sconst
10709                                 {
10710                                         $$ = makeStringConstCast($2, @2, $1);
10711                                 }
10712                         | ConstInterval Sconst opt_interval
10713                                 {
10714                                         TypeName *t = $1;
10715                                         t->typmods = $3;
10716                                         $$ = makeStringConstCast($2, @2, t);
10717                                 }
10718                         | ConstInterval '(' Iconst ')' Sconst opt_interval
10719                                 {
10720                                         TypeName *t = $1;
10721                                         if ($6 != NIL)
10722                                         {
10723                                                 if (list_length($6) != 1)
10724                                                         ereport(ERROR,
10725                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
10726                                                                          errmsg("interval precision specified twice"),
10727                                                                          parser_errposition(@1)));
10728                                                 t->typmods = lappend($6, makeIntConst($3, @3));
10729                                         }
10730                                         else
10731                                                 t->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
10732                                                                                                 makeIntConst($3, @3));
10733                                         $$ = makeStringConstCast($5, @5, t);
10734                                 }
10735                         | TRUE_P
10736                                 {
10737                                         $$ = makeBoolAConst(TRUE, @1);
10738                                 }
10739                         | FALSE_P
10740                                 {
10741                                         $$ = makeBoolAConst(FALSE, @1);
10742                                 }
10743                         | NULL_P
10744                                 {
10745                                         $$ = makeNullAConst(@1);
10746                                 }
10747                 ;
10748
10749 Iconst:         ICONST                                                                  { $$ = $1; };
10750 Sconst:         SCONST                                                                  { $$ = $1; };
10751 RoleId:         ColId                                                                   { $$ = $1; };
10752
10753 SignedIconst: Iconst                                                            { $$ = $1; }
10754                         | '+' Iconst                                                    { $$ = + $2; }
10755                         | '-' Iconst                                                    { $$ = - $2; }
10756                 ;
10757
10758 Iconst_list:    Iconst                                          { $$ = list_make1(makeInteger($1)); }
10759                                 | Iconst_list ',' Iconst        { $$ = lappend($1, makeInteger($3)); }
10760                 ;
10761
10762 /*
10763  * Name classification hierarchy.
10764  *
10765  * IDENT is the lexeme returned by the lexer for identifiers that match
10766  * no known keyword.  In most cases, we can accept certain keywords as
10767  * names, not only IDENTs.      We prefer to accept as many such keywords
10768  * as possible to minimize the impact of "reserved words" on programmers.
10769  * So, we divide names into several possible classes.  The classification
10770  * is chosen in part to make keywords acceptable as names wherever possible.
10771  */
10772
10773 /* Column identifier --- names that can be column, table, etc names.
10774  */
10775 ColId:          IDENT                                                                   { $$ = $1; }
10776                         | unreserved_keyword                                    { $$ = pstrdup($1); }
10777                         | col_name_keyword                                              { $$ = pstrdup($1); }
10778                 ;
10779
10780 /* Type/function identifier --- names that can be type or function names.
10781  */
10782 type_function_name:     IDENT                                                   { $$ = $1; }
10783                         | unreserved_keyword                                    { $$ = pstrdup($1); }
10784                         | type_func_name_keyword                                { $$ = pstrdup($1); }
10785                 ;
10786
10787 /* Column label --- allowed labels in "AS" clauses.
10788  * This presently includes *all* Postgres keywords.
10789  */
10790 ColLabel:       IDENT                                                                   { $$ = $1; }
10791                         | unreserved_keyword                                    { $$ = pstrdup($1); }
10792                         | col_name_keyword                                              { $$ = pstrdup($1); }
10793                         | type_func_name_keyword                                { $$ = pstrdup($1); }
10794                         | reserved_keyword                                              { $$ = pstrdup($1); }
10795                 ;
10796
10797
10798 /*
10799  * Keyword category lists.  Generally, every keyword present in
10800  * the Postgres grammar should appear in exactly one of these lists.
10801  *
10802  * Put a new keyword into the first list that it can go into without causing
10803  * shift or reduce conflicts.  The earlier lists define "less reserved"
10804  * categories of keywords.
10805  *
10806  * Make sure that each keyword's category in keywords.c matches where
10807  * it is listed here.  (Someday we may be able to generate these lists and
10808  * keywords.c's table from a common master list.)
10809  */
10810
10811 /* "Unreserved" keywords --- available for use as any kind of name.
10812  */
10813 unreserved_keyword:
10814                           ABORT_P
10815                         | ABSOLUTE_P
10816                         | ACCESS
10817                         | ACTION
10818                         | ADD_P
10819                         | ADMIN
10820                         | AFTER
10821                         | AGGREGATE
10822                         | ALSO
10823                         | ALTER
10824                         | ALWAYS
10825                         | ASSERTION
10826                         | ASSIGNMENT
10827                         | AT
10828                         | BACKWARD
10829                         | BEFORE
10830                         | BEGIN_P
10831                         | BY
10832                         | CACHE
10833                         | CALLED
10834                         | CASCADE
10835                         | CASCADED
10836                         | CATALOG_P
10837                         | CHAIN
10838                         | CHARACTERISTICS
10839                         | CHECKPOINT
10840                         | CLASS
10841                         | CLOSE
10842                         | CLUSTER
10843                         | COMMENT
10844                         | COMMENTS
10845                         | COMMIT
10846                         | COMMITTED
10847                         | CONFIGURATION
10848                         | CONNECTION
10849                         | CONSTRAINTS
10850                         | CONTENT_P
10851                         | CONTINUE_P
10852                         | CONVERSION_P
10853                         | COPY
10854                         | COST
10855                         | CREATEDB
10856                         | CREATEROLE
10857                         | CREATEUSER
10858                         | CSV
10859                         | CURRENT_P
10860                         | CURSOR
10861                         | CYCLE
10862                         | DATA_P
10863                         | DATABASE
10864                         | DAY_P
10865                         | DEALLOCATE
10866                         | DECLARE
10867                         | DEFAULTS
10868                         | DEFERRED
10869                         | DEFINER
10870                         | DELETE_P
10871                         | DELIMITER
10872                         | DELIMITERS
10873                         | DICTIONARY
10874                         | DISABLE_P
10875                         | DISCARD
10876                         | DOCUMENT_P
10877                         | DOMAIN_P
10878                         | DOUBLE_P
10879                         | DROP
10880                         | EACH
10881                         | ENABLE_P
10882                         | ENCODING
10883                         | ENCRYPTED
10884                         | ENUM_P
10885                         | ESCAPE
10886                         | EXCLUDE
10887                         | EXCLUDING
10888                         | EXCLUSIVE
10889                         | EXECUTE
10890                         | EXPLAIN
10891                         | EXTERNAL
10892                         | FAMILY
10893                         | FIRST_P
10894                         | FOLLOWING
10895                         | FORCE
10896                         | FORWARD
10897                         | FUNCTION
10898                         | FUNCTIONS
10899                         | GLOBAL
10900                         | GRANTED
10901                         | HANDLER
10902                         | HEADER_P
10903                         | HOLD
10904                         | HOUR_P
10905                         | IDENTITY_P
10906                         | IF_P
10907                         | IMMEDIATE
10908                         | IMMUTABLE
10909                         | IMPLICIT_P
10910                         | INCLUDING
10911                         | INCREMENT
10912                         | INDEX
10913                         | INDEXES
10914                         | INHERIT
10915                         | INHERITS
10916                         | INLINE_P
10917                         | INPUT_P
10918                         | INSENSITIVE
10919                         | INSERT
10920                         | INSTEAD
10921                         | INVOKER
10922                         | ISOLATION
10923                         | KEY
10924                         | LANGUAGE
10925                         | LARGE_P
10926                         | LAST_P
10927                         | LC_COLLATE_P
10928                         | LC_CTYPE_P
10929                         | LEVEL
10930                         | LISTEN
10931                         | LOAD
10932                         | LOCAL
10933                         | LOCATION
10934                         | LOCK_P
10935                         | LOGIN_P
10936                         | MAPPING
10937                         | MATCH
10938                         | MAXVALUE
10939                         | MINUTE_P
10940                         | MINVALUE
10941                         | MODE
10942                         | MONTH_P
10943                         | MOVE
10944                         | NAME_P
10945                         | NAMES
10946                         | NEXT
10947                         | NO
10948                         | NOCREATEDB
10949                         | NOCREATEROLE
10950                         | NOCREATEUSER
10951                         | NOINHERIT
10952                         | NOLOGIN_P
10953                         | NOSUPERUSER
10954                         | NOTHING
10955                         | NOTIFY
10956                         | NOWAIT
10957                         | NULLS_P
10958                         | OBJECT_P
10959                         | OF
10960                         | OIDS
10961                         | OPERATOR
10962                         | OPTION
10963                         | OPTIONS
10964                         | OWNED
10965                         | OWNER
10966                         | PARSER
10967                         | PARTIAL
10968                         | PARTITION
10969                         | PASSWORD
10970                         | PLANS
10971                         | PRECEDING
10972                         | PREPARE
10973                         | PREPARED
10974                         | PRESERVE
10975                         | PRIOR
10976                         | PRIVILEGES
10977                         | PROCEDURAL
10978                         | PROCEDURE
10979                         | QUOTE
10980                         | RANGE
10981                         | READ
10982                         | REASSIGN
10983                         | RECHECK
10984                         | RECURSIVE
10985                         | REINDEX
10986                         | RELATIVE_P
10987                         | RELEASE
10988                         | RENAME
10989                         | REPEATABLE
10990                         | REPLACE
10991                         | REPLICA
10992                         | RESET
10993                         | RESTART
10994                         | RESTRICT
10995                         | RETURNS
10996                         | REVOKE
10997                         | ROLE
10998                         | ROLLBACK
10999                         | ROWS
11000                         | RULE
11001                         | SAVEPOINT
11002                         | SCHEMA
11003                         | SCROLL
11004                         | SEARCH
11005                         | SECOND_P
11006                         | SECURITY
11007                         | SEQUENCE
11008                         | SEQUENCES
11009                         | SERIALIZABLE
11010                         | SERVER
11011                         | SESSION
11012                         | SET
11013                         | SHARE
11014                         | SHOW
11015                         | SIMPLE
11016                         | STABLE
11017                         | STANDALONE_P
11018                         | START
11019                         | STATEMENT
11020                         | STATISTICS
11021                         | STDIN
11022                         | STDOUT
11023                         | STORAGE
11024                         | STRICT_P
11025                         | STRIP_P
11026                         | SUPERUSER_P
11027                         | SYSID
11028                         | SYSTEM_P
11029                         | TABLES
11030                         | TABLESPACE
11031                         | TEMP
11032                         | TEMPLATE
11033                         | TEMPORARY
11034                         | TEXT_P
11035                         | TRANSACTION
11036                         | TRIGGER
11037                         | TRUNCATE
11038                         | TRUSTED
11039                         | TYPE_P
11040                         | UNBOUNDED
11041                         | UNCOMMITTED
11042                         | UNENCRYPTED
11043                         | UNKNOWN
11044                         | UNLISTEN
11045                         | UNTIL
11046                         | UPDATE
11047                         | VACUUM
11048                         | VALID
11049                         | VALIDATOR
11050                         | VALUE_P
11051                         | VARYING
11052                         | VERSION_P
11053                         | VIEW
11054                         | VOLATILE
11055                         | WHITESPACE_P
11056                         | WITHOUT
11057                         | WORK
11058                         | WRAPPER
11059                         | WRITE
11060                         | XML_P
11061                         | YEAR_P
11062                         | YES_P
11063                         | ZONE
11064                 ;
11065
11066 /* Column identifier --- keywords that can be column, table, etc names.
11067  *
11068  * Many of these keywords will in fact be recognized as type or function
11069  * names too; but they have special productions for the purpose, and so
11070  * can't be treated as "generic" type or function names.
11071  *
11072  * The type names appearing here are not usable as function names
11073  * because they can be followed by '(' in typename productions, which
11074  * looks too much like a function call for an LR(1) parser.
11075  */
11076 col_name_keyword:
11077                           BETWEEN
11078                         | BIGINT
11079                         | BIT
11080                         | BOOLEAN_P
11081                         | CHAR_P
11082                         | CHARACTER
11083                         | COALESCE
11084                         | DEC
11085                         | DECIMAL_P
11086                         | EXISTS
11087                         | EXTRACT
11088                         | FLOAT_P
11089                         | GREATEST
11090                         | INOUT
11091                         | INT_P
11092                         | INTEGER
11093                         | INTERVAL
11094                         | LEAST
11095                         | NATIONAL
11096                         | NCHAR
11097                         | NONE
11098                         | NULLIF
11099                         | NUMERIC
11100                         | OUT_P
11101                         | OVERLAY
11102                         | POSITION
11103                         | PRECISION
11104                         | REAL
11105                         | ROW
11106                         | SETOF
11107                         | SMALLINT
11108                         | SUBSTRING
11109                         | TIME
11110                         | TIMESTAMP
11111                         | TREAT
11112                         | TRIM
11113                         | VALUES
11114                         | VARCHAR
11115                         | XMLATTRIBUTES
11116                         | XMLCONCAT
11117                         | XMLELEMENT
11118                         | XMLFOREST
11119                         | XMLPARSE
11120                         | XMLPI
11121                         | XMLROOT
11122                         | XMLSERIALIZE
11123                 ;
11124
11125 /* Type/function identifier --- keywords that can be type or function names.
11126  *
11127  * Most of these are keywords that are used as operators in expressions;
11128  * in general such keywords can't be column names because they would be
11129  * ambiguous with variables, but they are unambiguous as function identifiers.
11130  *
11131  * Do not include POSITION, SUBSTRING, etc here since they have explicit
11132  * productions in a_expr to support the goofy SQL9x argument syntax.
11133  * - thomas 2000-11-28
11134  */
11135 type_func_name_keyword:
11136                           AUTHORIZATION
11137                         | BINARY
11138                         | CONCURRENTLY
11139                         | CROSS
11140                         | CURRENT_SCHEMA
11141                         | FREEZE
11142                         | FULL
11143                         | ILIKE
11144                         | INNER_P
11145                         | IS
11146                         | ISNULL
11147                         | JOIN
11148                         | LEFT
11149                         | LIKE
11150                         | NATURAL
11151                         | NOTNULL
11152                         | OUTER_P
11153                         | OVER
11154                         | OVERLAPS
11155                         | RIGHT
11156                         | SIMILAR
11157                         | VERBOSE
11158                 ;
11159
11160 /* Reserved keyword --- these keywords are usable only as a ColLabel.
11161  *
11162  * Keywords appear here if they could not be distinguished from variable,
11163  * type, or function names in some contexts.  Don't put things here unless
11164  * forced to.
11165  */
11166 reserved_keyword:
11167                           ALL
11168                         | ANALYSE
11169                         | ANALYZE
11170                         | AND
11171                         | ANY
11172                         | ARRAY
11173                         | AS
11174                         | ASC
11175                         | ASYMMETRIC
11176                         | BOTH
11177                         | CASE
11178                         | CAST
11179                         | CHECK
11180                         | COLLATE
11181                         | COLUMN
11182                         | CONSTRAINT
11183                         | CREATE
11184                         | CURRENT_CATALOG
11185                         | CURRENT_DATE
11186                         | CURRENT_ROLE
11187                         | CURRENT_TIME
11188                         | CURRENT_TIMESTAMP
11189                         | CURRENT_USER
11190                         | DEFAULT
11191                         | DEFERRABLE
11192                         | DESC
11193                         | DISTINCT
11194                         | DO
11195                         | ELSE
11196                         | END_P
11197                         | EXCEPT
11198                         | FALSE_P
11199                         | FETCH
11200                         | FOR
11201                         | FOREIGN
11202                         | FROM
11203                         | GRANT
11204                         | GROUP_P
11205                         | HAVING
11206                         | IN_P
11207                         | INITIALLY
11208                         | INTERSECT
11209                         | INTO
11210                         | LEADING
11211                         | LIMIT
11212                         | LOCALTIME
11213                         | LOCALTIMESTAMP
11214                         | NOT
11215                         | NULL_P
11216                         | OFF
11217                         | OFFSET
11218                         | ON
11219                         | ONLY
11220                         | OR
11221                         | ORDER
11222                         | PLACING
11223                         | PRIMARY
11224                         | REFERENCES
11225                         | RETURNING
11226                         | SELECT
11227                         | SESSION_USER
11228                         | SOME
11229                         | SYMMETRIC
11230                         | TABLE
11231                         | THEN
11232                         | TO
11233                         | TRAILING
11234                         | TRUE_P
11235                         | UNION
11236                         | UNIQUE
11237                         | USER
11238                         | USING
11239                         | VARIADIC
11240                         | WHEN
11241                         | WHERE
11242                         | WINDOW
11243                         | WITH
11244                 ;
11245
11246 %%
11247
11248 /*
11249  * The signature of this function is required by bison.  However, we
11250  * ignore the passed yylloc and instead use the last token position
11251  * available from the scanner.
11252  */
11253 static void
11254 base_yyerror(YYLTYPE *yylloc, core_yyscan_t yyscanner, const char *msg)
11255 {
11256         parser_yyerror(msg);
11257 }
11258
11259 static Node *
11260 makeColumnRef(char *colname, List *indirection,
11261                           int location, core_yyscan_t yyscanner)
11262 {
11263         /*
11264          * Generate a ColumnRef node, with an A_Indirection node added if there
11265          * is any subscripting in the specified indirection list.  However,
11266          * any field selection at the start of the indirection list must be
11267          * transposed into the "fields" part of the ColumnRef node.
11268          */
11269         ColumnRef  *c = makeNode(ColumnRef);
11270         int             nfields = 0;
11271         ListCell *l;
11272
11273         c->location = location;
11274         foreach(l, indirection)
11275         {
11276                 if (IsA(lfirst(l), A_Indices))
11277                 {
11278                         A_Indirection *i = makeNode(A_Indirection);
11279
11280                         if (nfields == 0)
11281                         {
11282                                 /* easy case - all indirection goes to A_Indirection */
11283                                 c->fields = list_make1(makeString(colname));
11284                                 i->indirection = check_indirection(indirection, yyscanner);
11285                         }
11286                         else
11287                         {
11288                                 /* got to split the list in two */
11289                                 i->indirection = check_indirection(list_copy_tail(indirection,
11290                                                                                                                                   nfields),
11291                                                                                                    yyscanner);
11292                                 indirection = list_truncate(indirection, nfields);
11293                                 c->fields = lcons(makeString(colname), indirection);
11294                         }
11295                         i->arg = (Node *) c;
11296                         return (Node *) i;
11297                 }
11298                 else if (IsA(lfirst(l), A_Star))
11299                 {
11300                         /* We only allow '*' at the end of a ColumnRef */
11301                         if (lnext(l) != NULL)
11302                                 parser_yyerror("improper use of \"*\"");
11303                 }
11304                 nfields++;
11305         }
11306         /* No subscripting, so all indirection gets added to field list */
11307         c->fields = lcons(makeString(colname), indirection);
11308         return (Node *) c;
11309 }
11310
11311 static Node *
11312 makeTypeCast(Node *arg, TypeName *typename, int location)
11313 {
11314         TypeCast *n = makeNode(TypeCast);
11315         n->arg = arg;
11316         n->typeName = typename;
11317         n->location = location;
11318         return (Node *) n;
11319 }
11320
11321 static Node *
11322 makeStringConst(char *str, int location)
11323 {
11324         A_Const *n = makeNode(A_Const);
11325
11326         n->val.type = T_String;
11327         n->val.val.str = str;
11328         n->location = location;
11329
11330         return (Node *)n;
11331 }
11332
11333 static Node *
11334 makeStringConstCast(char *str, int location, TypeName *typename)
11335 {
11336         Node *s = makeStringConst(str, location);
11337
11338         return makeTypeCast(s, typename, -1);
11339 }
11340
11341 static Node *
11342 makeIntConst(int val, int location)
11343 {
11344         A_Const *n = makeNode(A_Const);
11345
11346         n->val.type = T_Integer;
11347         n->val.val.ival = val;
11348         n->location = location;
11349
11350         return (Node *)n;
11351 }
11352
11353 static Node *
11354 makeFloatConst(char *str, int location)
11355 {
11356         A_Const *n = makeNode(A_Const);
11357
11358         n->val.type = T_Float;
11359         n->val.val.str = str;
11360         n->location = location;
11361
11362         return (Node *)n;
11363 }
11364
11365 static Node *
11366 makeBitStringConst(char *str, int location)
11367 {
11368         A_Const *n = makeNode(A_Const);
11369
11370         n->val.type = T_BitString;
11371         n->val.val.str = str;
11372         n->location = location;
11373
11374         return (Node *)n;
11375 }
11376
11377 static Node *
11378 makeNullAConst(int location)
11379 {
11380         A_Const *n = makeNode(A_Const);
11381
11382         n->val.type = T_Null;
11383         n->location = location;
11384
11385         return (Node *)n;
11386 }
11387
11388 static Node *
11389 makeAConst(Value *v, int location)
11390 {
11391         Node *n;
11392
11393         switch (v->type)
11394         {
11395                 case T_Float:
11396                         n = makeFloatConst(v->val.str, location);
11397                         break;
11398
11399                 case T_Integer:
11400                         n = makeIntConst(v->val.ival, location);
11401                         break;
11402
11403                 case T_String:
11404                 default:
11405                         n = makeStringConst(v->val.str, location);
11406                         break;
11407         }
11408
11409         return n;
11410 }
11411
11412 /* makeBoolAConst()
11413  * Create an A_Const string node and put it inside a boolean cast.
11414  */
11415 static Node *
11416 makeBoolAConst(bool state, int location)
11417 {
11418         A_Const *n = makeNode(A_Const);
11419
11420         n->val.type = T_String;
11421         n->val.val.str = (state ? "t" : "f");
11422         n->location = location;
11423
11424         return makeTypeCast((Node *)n, SystemTypeName("bool"), -1);
11425 }
11426
11427 /* makeOverlaps()
11428  * Create and populate a FuncCall node to support the OVERLAPS operator.
11429  */
11430 static FuncCall *
11431 makeOverlaps(List *largs, List *rargs, int location, core_yyscan_t yyscanner)
11432 {
11433         FuncCall *n = makeNode(FuncCall);
11434
11435         n->funcname = SystemFuncName("overlaps");
11436         if (list_length(largs) == 1)
11437                 largs = lappend(largs, largs);
11438         else if (list_length(largs) != 2)
11439                 ereport(ERROR,
11440                                 (errcode(ERRCODE_SYNTAX_ERROR),
11441                                  errmsg("wrong number of parameters on left side of OVERLAPS expression"),
11442                                  parser_errposition(location)));
11443         if (list_length(rargs) == 1)
11444                 rargs = lappend(rargs, rargs);
11445         else if (list_length(rargs) != 2)
11446                 ereport(ERROR,
11447                                 (errcode(ERRCODE_SYNTAX_ERROR),
11448                                  errmsg("wrong number of parameters on right side of OVERLAPS expression"),
11449                                  parser_errposition(location)));
11450         n->args = list_concat(largs, rargs);
11451         n->agg_order = NIL;
11452         n->agg_star = FALSE;
11453         n->agg_distinct = FALSE;
11454         n->func_variadic = FALSE;
11455         n->over = NULL;
11456         n->location = location;
11457         return n;
11458 }
11459
11460 /* check_qualified_name --- check the result of qualified_name production
11461  *
11462  * It's easiest to let the grammar production for qualified_name allow
11463  * subscripts and '*', which we then must reject here.
11464  */
11465 static void
11466 check_qualified_name(List *names, core_yyscan_t yyscanner)
11467 {
11468         ListCell   *i;
11469
11470         foreach(i, names)
11471         {
11472                 if (!IsA(lfirst(i), String))
11473                         parser_yyerror("syntax error");
11474         }
11475 }
11476
11477 /* check_func_name --- check the result of func_name production
11478  *
11479  * It's easiest to let the grammar production for func_name allow subscripts
11480  * and '*', which we then must reject here.
11481  */
11482 static List *
11483 check_func_name(List *names, core_yyscan_t yyscanner)
11484 {
11485         ListCell   *i;
11486
11487         foreach(i, names)
11488         {
11489                 if (!IsA(lfirst(i), String))
11490                         parser_yyerror("syntax error");
11491         }
11492         return names;
11493 }
11494
11495 /* check_indirection --- check the result of indirection production
11496  *
11497  * We only allow '*' at the end of the list, but it's hard to enforce that
11498  * in the grammar, so do it here.
11499  */
11500 static List *
11501 check_indirection(List *indirection, core_yyscan_t yyscanner)
11502 {
11503         ListCell *l;
11504
11505         foreach(l, indirection)
11506         {
11507                 if (IsA(lfirst(l), A_Star))
11508                 {
11509                         if (lnext(l) != NULL)
11510                                 parser_yyerror("improper use of \"*\"");
11511                 }
11512         }
11513         return indirection;
11514 }
11515
11516 /* extractArgTypes()
11517  * Given a list of FunctionParameter nodes, extract a list of just the
11518  * argument types (TypeNames) for input parameters only.  This is what
11519  * is needed to look up an existing function, which is what is wanted by
11520  * the productions that use this call.
11521  */
11522 static List *
11523 extractArgTypes(List *parameters)
11524 {
11525         List       *result = NIL;
11526         ListCell   *i;
11527
11528         foreach(i, parameters)
11529         {
11530                 FunctionParameter *p = (FunctionParameter *) lfirst(i);
11531
11532                 if (p->mode != FUNC_PARAM_OUT && p->mode != FUNC_PARAM_TABLE)
11533                         result = lappend(result, p->argType);
11534         }
11535         return result;
11536 }
11537
11538 /* findLeftmostSelect()
11539  * Find the leftmost component SelectStmt in a set-operation parsetree.
11540  */
11541 static SelectStmt *
11542 findLeftmostSelect(SelectStmt *node)
11543 {
11544         while (node && node->op != SETOP_NONE)
11545                 node = node->larg;
11546         Assert(node && IsA(node, SelectStmt) && node->larg == NULL);
11547         return node;
11548 }
11549
11550 /* insertSelectOptions()
11551  * Insert ORDER BY, etc into an already-constructed SelectStmt.
11552  *
11553  * This routine is just to avoid duplicating code in SelectStmt productions.
11554  */
11555 static void
11556 insertSelectOptions(SelectStmt *stmt,
11557                                         List *sortClause, List *lockingClause,
11558                                         Node *limitOffset, Node *limitCount,
11559                                         WithClause *withClause,
11560                                         core_yyscan_t yyscanner)
11561 {
11562         Assert(IsA(stmt, SelectStmt));
11563
11564         /*
11565          * Tests here are to reject constructs like
11566          *      (SELECT foo ORDER BY bar) ORDER BY baz
11567          */
11568         if (sortClause)
11569         {
11570                 if (stmt->sortClause)
11571                         ereport(ERROR,
11572                                         (errcode(ERRCODE_SYNTAX_ERROR),
11573                                          errmsg("multiple ORDER BY clauses not allowed"),
11574                                          parser_errposition(exprLocation((Node *) sortClause))));
11575                 stmt->sortClause = sortClause;
11576         }
11577         /* We can handle multiple locking clauses, though */
11578         stmt->lockingClause = list_concat(stmt->lockingClause, lockingClause);
11579         if (limitOffset)
11580         {
11581                 if (stmt->limitOffset)
11582                         ereport(ERROR,
11583                                         (errcode(ERRCODE_SYNTAX_ERROR),
11584                                          errmsg("multiple OFFSET clauses not allowed"),
11585                                          parser_errposition(exprLocation(limitOffset))));
11586                 stmt->limitOffset = limitOffset;
11587         }
11588         if (limitCount)
11589         {
11590                 if (stmt->limitCount)
11591                         ereport(ERROR,
11592                                         (errcode(ERRCODE_SYNTAX_ERROR),
11593                                          errmsg("multiple LIMIT clauses not allowed"),
11594                                          parser_errposition(exprLocation(limitCount))));
11595                 stmt->limitCount = limitCount;
11596         }
11597         if (withClause)
11598         {
11599                 if (stmt->withClause)
11600                         ereport(ERROR,
11601                                         (errcode(ERRCODE_SYNTAX_ERROR),
11602                                          errmsg("multiple WITH clauses not allowed"),
11603                                          parser_errposition(exprLocation((Node *) withClause))));
11604                 stmt->withClause = withClause;
11605         }
11606 }
11607
11608 static Node *
11609 makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
11610 {
11611         SelectStmt *n = makeNode(SelectStmt);
11612
11613         n->op = op;
11614         n->all = all;
11615         n->larg = (SelectStmt *) larg;
11616         n->rarg = (SelectStmt *) rarg;
11617         return (Node *) n;
11618 }
11619
11620 /* SystemFuncName()
11621  * Build a properly-qualified reference to a built-in function.
11622  */
11623 List *
11624 SystemFuncName(char *name)
11625 {
11626         return list_make2(makeString("pg_catalog"), makeString(name));
11627 }
11628
11629 /* SystemTypeName()
11630  * Build a properly-qualified reference to a built-in type.
11631  *
11632  * typmod is defaulted, but may be changed afterwards by caller.
11633  * Likewise for the location.
11634  */
11635 TypeName *
11636 SystemTypeName(char *name)
11637 {
11638         return makeTypeNameFromNameList(list_make2(makeString("pg_catalog"),
11639                                                                                            makeString(name)));
11640 }
11641
11642 /* doNegate()
11643  * Handle negation of a numeric constant.
11644  *
11645  * Formerly, we did this here because the optimizer couldn't cope with
11646  * indexquals that looked like "var = -4" --- it wants "var = const"
11647  * and a unary minus operator applied to a constant didn't qualify.
11648  * As of Postgres 7.0, that problem doesn't exist anymore because there
11649  * is a constant-subexpression simplifier in the optimizer.  However,
11650  * there's still a good reason for doing this here, which is that we can
11651  * postpone committing to a particular internal representation for simple
11652  * negative constants.  It's better to leave "-123.456" in string form
11653  * until we know what the desired type is.
11654  */
11655 static Node *
11656 doNegate(Node *n, int location)
11657 {
11658         if (IsA(n, A_Const))
11659         {
11660                 A_Const *con = (A_Const *)n;
11661
11662                 /* report the constant's location as that of the '-' sign */
11663                 con->location = location;
11664
11665                 if (con->val.type == T_Integer)
11666                 {
11667                         con->val.val.ival = -con->val.val.ival;
11668                         return n;
11669                 }
11670                 if (con->val.type == T_Float)
11671                 {
11672                         doNegateFloat(&con->val);
11673                         return n;
11674                 }
11675         }
11676
11677         return (Node *) makeSimpleA_Expr(AEXPR_OP, "-", NULL, n, location);
11678 }
11679
11680 static void
11681 doNegateFloat(Value *v)
11682 {
11683         char   *oldval = v->val.str;
11684
11685         Assert(IsA(v, Float));
11686         if (*oldval == '+')
11687                 oldval++;
11688         if (*oldval == '-')
11689                 v->val.str = oldval+1;  /* just strip the '-' */
11690         else
11691         {
11692                 char   *newval = (char *) palloc(strlen(oldval) + 2);
11693
11694                 *newval = '-';
11695                 strcpy(newval+1, oldval);
11696                 v->val.str = newval;
11697         }
11698 }
11699
11700 static Node *
11701 makeAArrayExpr(List *elements, int location)
11702 {
11703         A_ArrayExpr *n = makeNode(A_ArrayExpr);
11704
11705         n->elements = elements;
11706         n->location = location;
11707         return (Node *) n;
11708 }
11709
11710 static Node *
11711 makeXmlExpr(XmlExprOp op, char *name, List *named_args, List *args,
11712                         int location)
11713 {
11714         XmlExpr    *x = makeNode(XmlExpr);
11715
11716         x->op = op;
11717         x->name = name;
11718         /*
11719          * named_args is a list of ResTarget; it'll be split apart into separate
11720          * expression and name lists in transformXmlExpr().
11721          */
11722         x->named_args = named_args;
11723         x->arg_names = NIL;
11724         x->args = args;
11725         /* xmloption, if relevant, must be filled in by caller */
11726         /* type and typmod will be filled in during parse analysis */
11727         x->location = location;
11728         return (Node *) x;
11729 }
11730
11731 /* parser_init()
11732  * Initialize to parse one query string
11733  */
11734 void
11735 parser_init(base_yy_extra_type *yyext)
11736 {
11737         yyext->parsetree = NIL;         /* in case grammar forgets to set it */
11738 }
11739
11740 /*
11741  * Merge the input and output parameters of a table function.
11742  */
11743 static List *
11744 mergeTableFuncParameters(List *func_args, List *columns)
11745 {
11746         ListCell   *lc;
11747
11748         /* Explicit OUT and INOUT parameters shouldn't be used in this syntax */
11749         foreach(lc, func_args)
11750         {
11751                 FunctionParameter *p = (FunctionParameter *) lfirst(lc);
11752
11753                 if (p->mode != FUNC_PARAM_IN && p->mode != FUNC_PARAM_VARIADIC)
11754                         ereport(ERROR,
11755                                         (errcode(ERRCODE_SYNTAX_ERROR),
11756                                          errmsg("OUT and INOUT arguments aren't allowed in TABLE functions")));
11757         }
11758
11759         return list_concat(func_args, columns);
11760 }
11761
11762 /*
11763  * Determine return type of a TABLE function.  A single result column
11764  * returns setof that column's type; otherwise return setof record.
11765  */
11766 static TypeName *
11767 TableFuncTypeName(List *columns)
11768 {
11769         TypeName *result;
11770
11771         if (list_length(columns) == 1)
11772         {
11773                 FunctionParameter *p = (FunctionParameter *) linitial(columns);
11774
11775                 result = (TypeName *) copyObject(p->argType);
11776         }
11777         else
11778                 result = SystemTypeName("record");
11779
11780         result->setof = true;
11781
11782         return result;
11783 }
11784
11785 /*
11786  * Must undefine this stuff before including scan.c, since it has different
11787  * definitions for these macros.
11788  */
11789 #undef yyerror
11790 #undef yylval
11791 #undef yylloc
11792
11793 #include "scan.c"