]> granicus.if.org Git - postgresql/blob - src/backend/parser/gram.y
Add CASCADE support for CREATE EXTENSION.
[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-2015, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        src/backend/parser/gram.y
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  *
25  *        In general, nothing in this file should initiate database accesses
26  *        nor depend on changeable state (such as SET variables).  If you do
27  *        database accesses, your code will fail when we have aborted the
28  *        current transaction and are just parsing commands to find the next
29  *        ROLLBACK or COMMIT.  If you make use of SET variables, then you
30  *        will do the wrong thing in multi-query strings like this:
31  *                      SET SQL_inheritance TO off; SELECT * FROM foo;
32  *        because the entire string is parsed by gram.y before the SET gets
33  *        executed.  Anything that depends on the database or changeable state
34  *        should be handled during parse analysis so that it happens at the
35  *        right time not the wrong time.  The handling of SQL_inheritance is
36  *        a good example.
37  *
38  * WARNINGS
39  *        If you use a list, make sure the datum is a node so that the printing
40  *        routines work.
41  *
42  *        Sometimes we assign constants to makeStrings. Make sure we don't free
43  *        those.
44  *
45  *-------------------------------------------------------------------------
46  */
47 #include "postgres.h"
48
49 #include <ctype.h>
50 #include <limits.h>
51
52 #include "catalog/index.h"
53 #include "catalog/namespace.h"
54 #include "catalog/pg_trigger.h"
55 #include "commands/defrem.h"
56 #include "commands/trigger.h"
57 #include "nodes/makefuncs.h"
58 #include "nodes/nodeFuncs.h"
59 #include "parser/gramparse.h"
60 #include "parser/parser.h"
61 #include "parser/parse_expr.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 /*
70  * Location tracking support --- simpler than bison's default, since we only
71  * want to track the start position not the end position of each nonterminal.
72  */
73 #define YYLLOC_DEFAULT(Current, Rhs, N) \
74         do { \
75                 if ((N) > 0) \
76                         (Current) = (Rhs)[1]; \
77                 else \
78                         (Current) = (-1); \
79         } while (0)
80
81 /*
82  * The above macro assigns -1 (unknown) as the parse location of any
83  * nonterminal that was reduced from an empty rule.  This is problematic
84  * for nonterminals defined like
85  *              OptFooList: / * EMPTY * / { ... } | OptFooList Foo { ... } ;
86  * because we'll set -1 as the location during the first reduction and then
87  * copy it during each subsequent reduction, leaving us with -1 for the
88  * location even when the list is not empty.  To fix that, do this in the
89  * action for the nonempty rule(s):
90  *              if (@$ < 0) @$ = @2;
91  * (Although we have many nonterminals that follow this pattern, we only
92  * bother with fixing @$ like this when the nonterminal's parse location
93  * is actually referenced in some rule.)
94  */
95
96 /*
97  * Bison doesn't allocate anything that needs to live across parser calls,
98  * so we can easily have it use palloc instead of malloc.  This prevents
99  * memory leaks if we error out during parsing.  Note this only works with
100  * bison >= 2.0.  However, in bison 1.875 the default is to use alloca()
101  * if possible, so there's not really much problem anyhow, at least if
102  * you're building with gcc.
103  */
104 #define YYMALLOC palloc
105 #define YYFREE   pfree
106
107 /* Private struct for the result of privilege_target production */
108 typedef struct PrivTarget
109 {
110         GrantTargetType targtype;
111         GrantObjectType objtype;
112         List       *objs;
113 } PrivTarget;
114
115 /* Private struct for the result of import_qualification production */
116 typedef struct ImportQual
117 {
118         ImportForeignSchemaType type;
119         List       *table_names;
120 } ImportQual;
121
122 /* ConstraintAttributeSpec yields an integer bitmask of these flags: */
123 #define CAS_NOT_DEFERRABLE                      0x01
124 #define CAS_DEFERRABLE                          0x02
125 #define CAS_INITIALLY_IMMEDIATE         0x04
126 #define CAS_INITIALLY_DEFERRED          0x08
127 #define CAS_NOT_VALID                           0x10
128 #define CAS_NO_INHERIT                          0x20
129
130
131 #define parser_yyerror(msg)  scanner_yyerror(msg, yyscanner)
132 #define parser_errposition(pos)  scanner_errposition(pos, yyscanner)
133
134 static void base_yyerror(YYLTYPE *yylloc, core_yyscan_t yyscanner,
135                                                  const char *msg);
136 static Node *makeColumnRef(char *colname, List *indirection,
137                                                    int location, core_yyscan_t yyscanner);
138 static Node *makeTypeCast(Node *arg, TypeName *typename, int location);
139 static Node *makeStringConst(char *str, int location);
140 static Node *makeStringConstCast(char *str, int location, TypeName *typename);
141 static Node *makeIntConst(int val, int location);
142 static Node *makeFloatConst(char *str, int location);
143 static Node *makeBitStringConst(char *str, int location);
144 static Node *makeNullAConst(int location);
145 static Node *makeAConst(Value *v, int location);
146 static Node *makeBoolAConst(bool state, int location);
147 static Node *makeRoleSpec(RoleSpecType type, int location);
148 static void check_qualified_name(List *names, core_yyscan_t yyscanner);
149 static List *check_func_name(List *names, core_yyscan_t yyscanner);
150 static List *check_indirection(List *indirection, core_yyscan_t yyscanner);
151 static List *extractArgTypes(List *parameters);
152 static List *extractAggrArgTypes(List *aggrargs);
153 static List *makeOrderedSetArgs(List *directargs, List *orderedargs,
154                                                                 core_yyscan_t yyscanner);
155 static void insertSelectOptions(SelectStmt *stmt,
156                                                                 List *sortClause, List *lockingClause,
157                                                                 Node *limitOffset, Node *limitCount,
158                                                                 WithClause *withClause,
159                                                                 core_yyscan_t yyscanner);
160 static Node *makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg);
161 static Node *doNegate(Node *n, int location);
162 static void doNegateFloat(Value *v);
163 static Node *makeAndExpr(Node *lexpr, Node *rexpr, int location);
164 static Node *makeOrExpr(Node *lexpr, Node *rexpr, int location);
165 static Node *makeNotExpr(Node *expr, int location);
166 static Node *makeAArrayExpr(List *elements, int location);
167 static Node *makeXmlExpr(XmlExprOp op, char *name, List *named_args,
168                                                  List *args, int location);
169 static List *mergeTableFuncParameters(List *func_args, List *columns);
170 static TypeName *TableFuncTypeName(List *columns);
171 static RangeVar *makeRangeVarFromAnyName(List *names, int position, core_yyscan_t yyscanner);
172 static void SplitColQualList(List *qualList,
173                                                          List **constraintList, CollateClause **collClause,
174                                                          core_yyscan_t yyscanner);
175 static void processCASbits(int cas_bits, int location, const char *constrType,
176                            bool *deferrable, bool *initdeferred, bool *not_valid,
177                            bool *no_inherit, core_yyscan_t yyscanner);
178 static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
179
180 %}
181
182 %pure-parser
183 %expect 0
184 %name-prefix="base_yy"
185 %locations
186
187 %parse-param {core_yyscan_t yyscanner}
188 %lex-param   {core_yyscan_t yyscanner}
189
190 %union
191 {
192         core_YYSTYPE            core_yystype;
193         /* these fields must match core_YYSTYPE: */
194         int                                     ival;
195         char                            *str;
196         const char                      *keyword;
197
198         char                            chr;
199         bool                            boolean;
200         JoinType                        jtype;
201         DropBehavior            dbehavior;
202         OnCommitAction          oncommit;
203         List                            *list;
204         Node                            *node;
205         Value                           *value;
206         ObjectType                      objtype;
207         TypeName                        *typnam;
208         FunctionParameter   *fun_param;
209         FunctionParameterMode fun_param_mode;
210         FuncWithArgs            *funwithargs;
211         DefElem                         *defelt;
212         SortBy                          *sortby;
213         WindowDef                       *windef;
214         JoinExpr                        *jexpr;
215         IndexElem                       *ielem;
216         Alias                           *alias;
217         RangeVar                        *range;
218         IntoClause                      *into;
219         WithClause                      *with;
220         InferClause                     *infer;
221         OnConflictClause        *onconflict;
222         A_Indices                       *aind;
223         ResTarget                       *target;
224         struct PrivTarget       *privtarget;
225         AccessPriv                      *accesspriv;
226         struct ImportQual       *importqual;
227         InsertStmt                      *istmt;
228         VariableSetStmt         *vsetstmt;
229 }
230
231 %type <node>    stmt schema_stmt
232                 AlterEventTrigStmt
233                 AlterDatabaseStmt AlterDatabaseSetStmt AlterDomainStmt AlterEnumStmt
234                 AlterFdwStmt AlterForeignServerStmt AlterGroupStmt
235                 AlterObjectSchemaStmt AlterOwnerStmt AlterOperatorStmt AlterSeqStmt AlterSystemStmt AlterTableStmt
236                 AlterTblSpcStmt AlterExtensionStmt AlterExtensionContentsStmt AlterForeignTableStmt
237                 AlterCompositeTypeStmt AlterUserStmt AlterUserMappingStmt AlterUserSetStmt
238                 AlterRoleStmt AlterRoleSetStmt AlterPolicyStmt
239                 AlterDefaultPrivilegesStmt DefACLAction
240                 AnalyzeStmt ClosePortalStmt ClusterStmt CommentStmt
241                 ConstraintsSetStmt CopyStmt CreateAsStmt CreateCastStmt
242                 CreateDomainStmt CreateExtensionStmt CreateGroupStmt CreateOpClassStmt
243                 CreateOpFamilyStmt AlterOpFamilyStmt CreatePLangStmt
244                 CreateSchemaStmt CreateSeqStmt CreateStmt CreateTableSpaceStmt
245                 CreateFdwStmt CreateForeignServerStmt CreateForeignTableStmt
246                 CreateAssertStmt CreateTransformStmt CreateTrigStmt CreateEventTrigStmt
247                 CreateUserStmt CreateUserMappingStmt CreateRoleStmt CreatePolicyStmt
248                 CreatedbStmt DeclareCursorStmt DefineStmt DeleteStmt DiscardStmt DoStmt
249                 DropGroupStmt DropOpClassStmt DropOpFamilyStmt DropPLangStmt DropStmt
250                 DropAssertStmt DropTrigStmt DropRuleStmt DropCastStmt DropRoleStmt
251                 DropPolicyStmt DropUserStmt DropdbStmt DropTableSpaceStmt DropFdwStmt
252                 DropTransformStmt
253                 DropForeignServerStmt DropUserMappingStmt ExplainStmt FetchStmt
254                 GrantStmt GrantRoleStmt ImportForeignSchemaStmt IndexStmt InsertStmt
255                 ListenStmt LoadStmt LockStmt NotifyStmt ExplainableStmt PreparableStmt
256                 CreateFunctionStmt AlterFunctionStmt ReindexStmt RemoveAggrStmt
257                 RemoveFuncStmt RemoveOperStmt RenameStmt RevokeStmt RevokeRoleStmt
258                 RuleActionStmt RuleActionStmtOrEmpty RuleStmt
259                 SecLabelStmt SelectStmt TransactionStmt TruncateStmt
260                 UnlistenStmt UpdateStmt VacuumStmt
261                 VariableResetStmt VariableSetStmt VariableShowStmt
262                 ViewStmt CheckPointStmt CreateConversionStmt
263                 DeallocateStmt PrepareStmt ExecuteStmt
264                 DropOwnedStmt ReassignOwnedStmt
265                 AlterTSConfigurationStmt AlterTSDictionaryStmt
266                 CreateMatViewStmt RefreshMatViewStmt
267
268 %type <node>    select_no_parens select_with_parens select_clause
269                                 simple_select values_clause
270
271 %type <node>    alter_column_default opclass_item opclass_drop alter_using
272 %type <ival>    add_drop opt_asc_desc opt_nulls_order
273
274 %type <node>    alter_table_cmd alter_type_cmd opt_collate_clause
275            replica_identity
276 %type <list>    alter_table_cmds alter_type_cmds
277
278 %type <dbehavior>       opt_drop_behavior
279
280 %type <list>    createdb_opt_list createdb_opt_items copy_opt_list
281                                 transaction_mode_list
282                                 create_extension_opt_list alter_extension_opt_list
283 %type <defelt>  createdb_opt_item copy_opt_item
284                                 transaction_mode_item
285                                 create_extension_opt_item alter_extension_opt_item
286
287 %type <ival>    opt_lock lock_type cast_context
288 %type <ival>    vacuum_option_list vacuum_option_elem
289 %type <boolean> opt_or_replace
290                                 opt_grant_grant_option opt_grant_admin_option
291                                 opt_nowait opt_if_exists opt_with_data
292 %type <ival>    opt_nowait_or_skip
293
294 %type <list>    OptRoleList AlterOptRoleList
295 %type <defelt>  CreateOptRoleElem AlterOptRoleElem
296
297 %type <str>             opt_type
298 %type <str>             foreign_server_version opt_foreign_server_version
299 %type <str>             opt_in_database
300
301 %type <str>             OptSchemaName
302 %type <list>    OptSchemaEltList
303
304 %type <boolean> TriggerForSpec TriggerForType
305 %type <ival>    TriggerActionTime
306 %type <list>    TriggerEvents TriggerOneEvent
307 %type <value>   TriggerFuncArg
308 %type <node>    TriggerWhen
309
310 %type <list>    event_trigger_when_list event_trigger_value_list
311 %type <defelt>  event_trigger_when_item
312 %type <chr>             enable_trigger
313
314 %type <str>             copy_file_name
315                                 database_name access_method_clause access_method attr_name
316                                 name cursor_name file_name
317                                 index_name opt_index_name cluster_index_specification
318
319 %type <list>    func_name handler_name qual_Op qual_all_Op subquery_Op
320                                 opt_class opt_inline_handler opt_validator validator_clause
321                                 opt_collate
322
323 %type <range>   qualified_name insert_target OptConstrFromTable
324
325 %type <str>             all_Op MathOp
326
327 %type <str>             row_security_cmd RowSecurityDefaultForCmd
328 %type <node>    RowSecurityOptionalWithCheck RowSecurityOptionalExpr
329 %type <list>    RowSecurityDefaultToRole RowSecurityOptionalToRole
330
331 %type <str>             iso_level opt_encoding
332 %type <node>    grantee
333 %type <list>    grantee_list
334 %type <accesspriv> privilege
335 %type <list>    privileges privilege_list
336 %type <privtarget> privilege_target
337 %type <funwithargs> function_with_argtypes
338 %type <list>    function_with_argtypes_list
339 %type <ival>    defacl_privilege_target
340 %type <defelt>  DefACLOption
341 %type <list>    DefACLOptionList
342 %type <ival>    import_qualification_type
343 %type <importqual> import_qualification
344
345 %type <list>    stmtblock stmtmulti
346                                 OptTableElementList TableElementList OptInherit definition
347                                 OptTypedTableElementList TypedTableElementList
348                                 reloptions opt_reloptions
349                                 OptWith distinct_clause opt_all_clause opt_definition func_args func_args_list
350                                 func_args_with_defaults func_args_with_defaults_list
351                                 aggr_args aggr_args_list
352                                 func_as createfunc_opt_list alterfunc_opt_list
353                                 old_aggr_definition old_aggr_list
354                                 oper_argtypes RuleActionList RuleActionMulti
355                                 opt_column_list columnList opt_name_list
356                                 sort_clause opt_sort_clause sortby_list index_params
357                                 name_list role_list from_clause from_list opt_array_bounds
358                                 qualified_name_list any_name any_name_list type_name_list
359                                 any_operator expr_list attrs
360                                 target_list opt_target_list insert_column_list set_target_list
361                                 set_clause_list set_clause multiple_set_clause
362                                 ctext_expr_list ctext_row def_list operator_def_list indirection opt_indirection
363                                 reloption_list group_clause TriggerFuncArgs select_limit
364                                 opt_select_limit opclass_item_list opclass_drop_list
365                                 opclass_purpose opt_opfamily transaction_mode_list_or_empty
366                                 OptTableFuncElementList TableFuncElementList opt_type_modifiers
367                                 prep_type_clause
368                                 execute_param_clause using_clause returning_clause
369                                 opt_enum_val_list enum_val_list table_func_column_list
370                                 create_generic_options alter_generic_options
371                                 relation_expr_list dostmt_opt_list
372                                 transform_element_list transform_type_list
373
374 %type <list>    group_by_list
375 %type <node>    group_by_item empty_grouping_set rollup_clause cube_clause
376 %type <node>    grouping_sets_clause
377
378 %type <list>    opt_fdw_options fdw_options
379 %type <defelt>  fdw_option
380
381 %type <range>   OptTempTableName
382 %type <into>    into_clause create_as_target create_mv_target
383
384 %type <defelt>  createfunc_opt_item common_func_opt_item dostmt_opt_item
385 %type <fun_param> func_arg func_arg_with_default table_func_column aggr_arg
386 %type <fun_param_mode> arg_class
387 %type <typnam>  func_return func_type
388
389 %type <boolean>  opt_trusted opt_restart_seqs
390 %type <ival>     OptTemp
391 %type <ival>     OptNoLog
392 %type <oncommit> OnCommitOption
393
394 %type <ival>    for_locking_strength
395 %type <node>    for_locking_item
396 %type <list>    for_locking_clause opt_for_locking_clause for_locking_items
397 %type <list>    locked_rels_list
398 %type <boolean> all_or_distinct
399
400 %type <node>    join_outer join_qual
401 %type <jtype>   join_type
402
403 %type <list>    extract_list overlay_list position_list
404 %type <list>    substr_list trim_list
405 %type <list>    opt_interval interval_second
406 %type <node>    overlay_placing substr_from substr_for
407
408 %type <boolean> opt_instead
409 %type <boolean> opt_unique opt_concurrently opt_verbose opt_full
410 %type <boolean> opt_freeze opt_default opt_recheck
411 %type <defelt>  opt_binary opt_oids copy_delimiter
412
413 %type <boolean> copy_from opt_program
414
415 %type <ival>    opt_column event cursor_options opt_hold opt_set_data
416 %type <objtype> drop_type comment_type security_label_type
417
418 %type <node>    fetch_args limit_clause select_limit_value
419                                 offset_clause select_offset_value
420                                 select_offset_value2 opt_select_fetch_first_value
421 %type <ival>    row_or_rows first_or_next
422
423 %type <list>    OptSeqOptList SeqOptList
424 %type <defelt>  SeqOptElem
425
426 %type <istmt>   insert_rest
427 %type <infer>   opt_conf_expr
428 %type <onconflict> opt_on_conflict
429
430 %type <vsetstmt> generic_set set_rest set_rest_more generic_reset reset_rest
431                                  SetResetClause FunctionSetResetClause
432
433 %type <node>    TableElement TypedTableElement ConstraintElem TableFuncElement
434 %type <node>    columnDef columnOptions
435 %type <defelt>  def_elem reloption_elem old_aggr_elem operator_def_elem
436 %type <node>    def_arg columnElem where_clause where_or_current_clause
437                                 a_expr b_expr c_expr AexprConst indirection_el
438                                 columnref in_expr having_clause func_table array_expr
439                                 ExclusionWhereClause
440 %type <list>    rowsfrom_item rowsfrom_list opt_col_def_list
441 %type <boolean> opt_ordinality
442 %type <list>    ExclusionConstraintList ExclusionConstraintElem
443 %type <list>    func_arg_list
444 %type <node>    func_arg_expr
445 %type <list>    row explicit_row implicit_row type_list array_expr_list
446 %type <node>    case_expr case_arg when_clause case_default
447 %type <list>    when_clause_list
448 %type <ival>    sub_type
449 %type <node>    ctext_expr
450 %type <value>   NumericOnly
451 %type <list>    NumericOnly_list
452 %type <alias>   alias_clause opt_alias_clause
453 %type <list>    func_alias_clause
454 %type <sortby>  sortby
455 %type <ielem>   index_elem
456 %type <node>    table_ref
457 %type <jexpr>   joined_table
458 %type <range>   relation_expr
459 %type <range>   relation_expr_opt_alias
460 %type <node>    tablesample_clause opt_repeatable_clause
461 %type <target>  target_el single_set_clause set_target insert_column_item
462
463 %type <str>             generic_option_name
464 %type <node>    generic_option_arg
465 %type <defelt>  generic_option_elem alter_generic_option_elem
466 %type <list>    generic_option_list alter_generic_option_list
467 %type <str>             explain_option_name
468 %type <node>    explain_option_arg
469 %type <defelt>  explain_option_elem
470 %type <list>    explain_option_list
471
472 %type <ival>    reindex_target_type reindex_target_multitable
473 %type <ival>    reindex_option_list reindex_option_elem
474
475 %type <node>    copy_generic_opt_arg copy_generic_opt_arg_list_item
476 %type <defelt>  copy_generic_opt_elem
477 %type <list>    copy_generic_opt_list copy_generic_opt_arg_list
478 %type <list>    copy_options
479
480 %type <typnam>  Typename SimpleTypename ConstTypename
481                                 GenericType Numeric opt_float
482                                 Character ConstCharacter
483                                 CharacterWithLength CharacterWithoutLength
484                                 ConstDatetime ConstInterval
485                                 Bit ConstBit BitWithLength BitWithoutLength
486 %type <str>             character
487 %type <str>             extract_arg
488 %type <str>             opt_charset
489 %type <boolean> opt_varying opt_timezone opt_no_inherit
490
491 %type <ival>    Iconst SignedIconst
492 %type <str>             Sconst comment_text notify_payload
493 %type <str>             RoleId opt_boolean_or_string
494 %type <list>    var_list
495 %type <str>             ColId ColLabel var_name type_function_name param_name
496 %type <str>             NonReservedWord NonReservedWord_or_Sconst
497 %type <str>             createdb_opt_name
498 %type <node>    var_value zone_value
499 %type <node>    auth_ident RoleSpec opt_granted_by
500
501 %type <keyword> unreserved_keyword type_func_name_keyword
502 %type <keyword> col_name_keyword reserved_keyword
503
504 %type <node>    TableConstraint TableLikeClause
505 %type <ival>    TableLikeOptionList TableLikeOption
506 %type <list>    ColQualList
507 %type <node>    ColConstraint ColConstraintElem ConstraintAttr
508 %type <ival>    key_actions key_delete key_match key_update key_action
509 %type <ival>    ConstraintAttributeSpec ConstraintAttributeElem
510 %type <str>             ExistingIndex
511
512 %type <list>    constraints_set_list
513 %type <boolean> constraints_set_mode
514 %type <str>             OptTableSpace OptConsTableSpace
515 %type <node>    OptTableSpaceOwner
516 %type <ival>    opt_check_option
517
518 %type <str>             opt_provider security_label
519
520 %type <target>  xml_attribute_el
521 %type <list>    xml_attribute_list xml_attributes
522 %type <node>    xml_root_version opt_xml_root_standalone
523 %type <node>    xmlexists_argument
524 %type <ival>    document_or_content
525 %type <boolean> xml_whitespace_option
526
527 %type <node>    func_application func_expr_common_subexpr
528 %type <node>    func_expr func_expr_windowless
529 %type <node>    common_table_expr
530 %type <with>    with_clause opt_with_clause
531 %type <list>    cte_list
532
533 %type <list>    within_group_clause
534 %type <node>    filter_clause
535 %type <list>    window_clause window_definition_list opt_partition_clause
536 %type <windef>  window_definition over_clause window_specification
537                                 opt_frame_clause frame_extent frame_bound
538 %type <str>             opt_existing_window_name
539 %type <boolean> opt_if_not_exists
540
541 /*
542  * Non-keyword token types.  These are hard-wired into the "flex" lexer.
543  * They must be listed first so that their numeric codes do not depend on
544  * the set of keywords.  PL/pgsql depends on this so that it can share the
545  * same lexer.  If you add/change tokens here, fix PL/pgsql to match!
546  *
547  * DOT_DOT is unused in the core SQL grammar, and so will always provoke
548  * parse errors.  It is needed by PL/pgsql.
549  */
550 %token <str>    IDENT FCONST SCONST BCONST XCONST Op
551 %token <ival>   ICONST PARAM
552 %token                  TYPECAST DOT_DOT COLON_EQUALS EQUALS_GREATER
553 %token                  LESS_EQUALS GREATER_EQUALS NOT_EQUALS
554
555 /*
556  * If you want to make any keyword changes, update the keyword table in
557  * src/include/parser/kwlist.h and add new keywords to the appropriate one
558  * of the reserved-or-not-so-reserved keyword lists, below; search
559  * this file for "Keyword category lists".
560  */
561
562 /* ordinary key words in alphabetical order */
563 %token <keyword> ABORT_P ABSOLUTE_P ACCESS ACTION ADD_P ADMIN AFTER
564         AGGREGATE ALL ALSO ALTER ALWAYS ANALYSE ANALYZE AND ANY ARRAY AS ASC
565         ASSERTION ASSIGNMENT ASYMMETRIC AT ATTRIBUTE AUTHORIZATION
566
567         BACKWARD BEFORE BEGIN_P BETWEEN BIGINT BINARY BIT
568         BOOLEAN_P BOTH BY
569
570         CACHE CALLED CASCADE CASCADED CASE CAST CATALOG_P CHAIN CHAR_P
571         CHARACTER CHARACTERISTICS CHECK CHECKPOINT CLASS CLOSE
572         CLUSTER COALESCE COLLATE COLLATION COLUMN COMMENT COMMENTS COMMIT
573         COMMITTED CONCURRENTLY CONFIGURATION CONFLICT CONNECTION CONSTRAINT
574         CONSTRAINTS CONTENT_P CONTINUE_P CONVERSION_P COPY COST CREATE
575         CROSS CSV CUBE CURRENT_P
576         CURRENT_CATALOG CURRENT_DATE CURRENT_ROLE CURRENT_SCHEMA
577         CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR CYCLE
578
579         DATA_P DATABASE DAY_P DEALLOCATE DEC DECIMAL_P DECLARE DEFAULT DEFAULTS
580         DEFERRABLE DEFERRED DEFINER DELETE_P DELIMITER DELIMITERS DESC
581         DICTIONARY DISABLE_P DISCARD DISTINCT DO DOCUMENT_P DOMAIN_P DOUBLE_P DROP
582
583         EACH ELSE ENABLE_P ENCODING ENCRYPTED END_P ENUM_P ESCAPE EVENT EXCEPT
584         EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN
585         EXTENSION EXTERNAL EXTRACT
586
587         FALSE_P FAMILY FETCH FILTER FIRST_P FLOAT_P FOLLOWING FOR
588         FORCE FOREIGN FORWARD FREEZE FROM FULL FUNCTION FUNCTIONS
589
590         GLOBAL GRANT GRANTED GREATEST GROUP_P GROUPING
591
592         HANDLER HAVING HEADER_P HOLD HOUR_P
593
594         IDENTITY_P IF_P ILIKE IMMEDIATE IMMUTABLE IMPLICIT_P IMPORT_P IN_P
595         INCLUDING INCREMENT INDEX INDEXES INHERIT INHERITS INITIALLY INLINE_P
596         INNER_P INOUT INPUT_P INSENSITIVE INSERT INSTEAD INT_P INTEGER
597         INTERSECT INTERVAL INTO INVOKER IS ISNULL ISOLATION
598
599         JOIN
600
601         KEY
602
603         LABEL LANGUAGE LARGE_P LAST_P LATERAL_P
604         LEADING LEAKPROOF LEAST LEFT LEVEL LIKE LIMIT LISTEN LOAD LOCAL
605         LOCALTIME LOCALTIMESTAMP LOCATION LOCK_P LOCKED LOGGED
606
607         MAPPING MATCH MATERIALIZED MAXVALUE MINUTE_P MINVALUE MODE MONTH_P MOVE
608
609         NAME_P NAMES NATIONAL NATURAL NCHAR NEXT NO NONE
610         NOT NOTHING NOTIFY NOTNULL NOWAIT NULL_P NULLIF
611         NULLS_P NUMERIC
612
613         OBJECT_P OF OFF OFFSET OIDS ON ONLY OPERATOR OPTION OPTIONS OR
614         ORDER ORDINALITY OUT_P OUTER_P OVER OVERLAPS OVERLAY OWNED OWNER
615
616         PARALLEL PARSER PARTIAL PARTITION PASSING PASSWORD PLACING PLANS POLICY
617         POSITION PRECEDING PRECISION PRESERVE PREPARE PREPARED PRIMARY
618         PRIOR PRIVILEGES PROCEDURAL PROCEDURE PROGRAM
619
620         QUOTE
621
622         RANGE READ REAL REASSIGN RECHECK RECURSIVE REF REFERENCES REFRESH REINDEX
623         RELATIVE_P RELEASE RENAME REPEATABLE REPLACE REPLICA
624         RESET RESTART RESTRICT RETURNING RETURNS REVOKE RIGHT ROLE ROLLBACK ROLLUP
625         ROW ROWS RULE
626
627         SAVEPOINT SCHEMA SCROLL SEARCH SECOND_P SECURITY SELECT SEQUENCE SEQUENCES
628         SERIALIZABLE SERVER SESSION SESSION_USER SET SETS SETOF SHARE SHOW
629         SIMILAR SIMPLE SKIP SMALLINT SNAPSHOT SOME SQL_P STABLE STANDALONE_P START
630         STATEMENT STATISTICS STDIN STDOUT STORAGE STRICT_P STRIP_P SUBSTRING
631         SYMMETRIC SYSID SYSTEM_P
632
633         TABLE TABLES TABLESAMPLE TABLESPACE TEMP TEMPLATE TEMPORARY TEXT_P THEN
634         TIME TIMESTAMP TO TRAILING TRANSACTION TRANSFORM TREAT TRIGGER TRIM TRUE_P
635         TRUNCATE TRUSTED TYPE_P TYPES_P
636
637         UNBOUNDED UNCOMMITTED UNENCRYPTED UNION UNIQUE UNKNOWN UNLISTEN UNLOGGED
638         UNTIL UPDATE USER USING
639
640         VACUUM VALID VALIDATE VALIDATOR VALUE_P VALUES VARCHAR VARIADIC VARYING
641         VERBOSE VERSION_P VIEW VIEWS VOLATILE
642
643         WHEN WHERE WHITESPACE_P WINDOW WITH WITHIN WITHOUT WORK WRAPPER WRITE
644
645         XML_P XMLATTRIBUTES XMLCONCAT XMLELEMENT XMLEXISTS XMLFOREST XMLPARSE
646         XMLPI XMLROOT XMLSERIALIZE
647
648         YEAR_P YES_P
649
650         ZONE
651
652 /*
653  * The grammar thinks these are keywords, but they are not in the kwlist.h
654  * list and so can never be entered directly.  The filter in parser.c
655  * creates these tokens when required (based on looking one token ahead).
656  *
657  * NOT_LA exists so that productions such as NOT LIKE can be given the same
658  * precedence as LIKE; otherwise they'd effectively have the same precedence
659  * as NOT, at least with respect to their left-hand subexpression.
660  * NULLS_LA and WITH_LA are needed to make the grammar LALR(1).
661  */
662 %token          NOT_LA NULLS_LA WITH_LA
663
664
665 /* Precedence: lowest to highest */
666 %nonassoc       SET                             /* see relation_expr_opt_alias */
667 %left           UNION EXCEPT
668 %left           INTERSECT
669 %left           OR
670 %left           AND
671 %right          NOT
672 %nonassoc       IS ISNULL NOTNULL       /* IS sets precedence for IS NULL, etc */
673 %nonassoc       '<' '>' '=' LESS_EQUALS GREATER_EQUALS NOT_EQUALS
674 %nonassoc       BETWEEN IN_P LIKE ILIKE SIMILAR NOT_LA
675 %nonassoc       ESCAPE                  /* ESCAPE must be just above LIKE/ILIKE/SIMILAR */
676 %left           POSTFIXOP               /* dummy for postfix Op rules */
677 /*
678  * To support target_el without AS, we must give IDENT an explicit priority
679  * between POSTFIXOP and Op.  We can safely assign the same priority to
680  * various unreserved keywords as needed to resolve ambiguities (this can't
681  * have any bad effects since obviously the keywords will still behave the
682  * same as if they weren't keywords).  We need to do this for PARTITION,
683  * RANGE, ROWS to support opt_existing_window_name; and for RANGE, ROWS
684  * so that they can follow a_expr without creating postfix-operator problems;
685  * and for NULL so that it can follow b_expr in ColQualList without creating
686  * postfix-operator problems.
687  *
688  * To support CUBE and ROLLUP in GROUP BY without reserving them, we give them
689  * an explicit priority lower than '(', so that a rule with CUBE '(' will shift
690  * rather than reducing a conflicting rule that takes CUBE as a function name.
691  * Using the same precedence as IDENT seems right for the reasons given above.
692  *
693  * The frame_bound productions UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING
694  * are even messier: since UNBOUNDED is an unreserved keyword (per spec!),
695  * there is no principled way to distinguish these from the productions
696  * a_expr PRECEDING/FOLLOWING.  We hack this up by giving UNBOUNDED slightly
697  * lower precedence than PRECEDING and FOLLOWING.  At present this doesn't
698  * appear to cause UNBOUNDED to be treated differently from other unreserved
699  * keywords anywhere else in the grammar, but it's definitely risky.  We can
700  * blame any funny behavior of UNBOUNDED on the SQL standard, though.
701  */
702 %nonassoc       UNBOUNDED               /* ideally should have same precedence as IDENT */
703 %nonassoc       IDENT NULL_P PARTITION RANGE ROWS PRECEDING FOLLOWING CUBE ROLLUP
704 %left           Op OPERATOR             /* multi-character ops and user-defined operators */
705 %left           '+' '-'
706 %left           '*' '/' '%'
707 %left           '^'
708 /* Unary Operators */
709 %left           AT                              /* sets precedence for AT TIME ZONE */
710 %left           COLLATE
711 %right          UMINUS
712 %left           '[' ']'
713 %left           '(' ')'
714 %left           TYPECAST
715 %left           '.'
716 /*
717  * These might seem to be low-precedence, but actually they are not part
718  * of the arithmetic hierarchy at all in their use as JOIN operators.
719  * We make them high-precedence to support their use as function names.
720  * They wouldn't be given a precedence at all, were it not that we need
721  * left-associativity among the JOIN rules themselves.
722  */
723 %left           JOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
724 /* kluge to keep xml_whitespace_option from causing shift/reduce conflicts */
725 %right          PRESERVE STRIP_P
726
727 %%
728
729 /*
730  *      The target production for the whole parse.
731  */
732 stmtblock:      stmtmulti
733                         {
734                                 pg_yyget_extra(yyscanner)->parsetree = $1;
735                         }
736                 ;
737
738 /* the thrashing around here is to discard "empty" statements... */
739 stmtmulti:      stmtmulti ';' stmt
740                                 {
741                                         if ($3 != NULL)
742                                                 $$ = lappend($1, $3);
743                                         else
744                                                 $$ = $1;
745                                 }
746                         | stmt
747                                 {
748                                         if ($1 != NULL)
749                                                 $$ = list_make1($1);
750                                         else
751                                                 $$ = NIL;
752                                 }
753                 ;
754
755 stmt :
756                         AlterEventTrigStmt
757                         | AlterDatabaseStmt
758                         | AlterDatabaseSetStmt
759                         | AlterDefaultPrivilegesStmt
760                         | AlterDomainStmt
761                         | AlterEnumStmt
762                         | AlterExtensionStmt
763                         | AlterExtensionContentsStmt
764                         | AlterFdwStmt
765                         | AlterForeignServerStmt
766                         | AlterForeignTableStmt
767                         | AlterFunctionStmt
768                         | AlterGroupStmt
769                         | AlterObjectSchemaStmt
770                         | AlterOwnerStmt
771                         | AlterOperatorStmt
772                         | AlterPolicyStmt
773                         | AlterSeqStmt
774                         | AlterSystemStmt
775                         | AlterTableStmt
776                         | AlterTblSpcStmt
777                         | AlterCompositeTypeStmt
778                         | AlterRoleSetStmt
779                         | AlterRoleStmt
780                         | AlterTSConfigurationStmt
781                         | AlterTSDictionaryStmt
782                         | AlterUserMappingStmt
783                         | AlterUserSetStmt
784                         | AlterUserStmt
785                         | AnalyzeStmt
786                         | CheckPointStmt
787                         | ClosePortalStmt
788                         | ClusterStmt
789                         | CommentStmt
790                         | ConstraintsSetStmt
791                         | CopyStmt
792                         | CreateAsStmt
793                         | CreateAssertStmt
794                         | CreateCastStmt
795                         | CreateConversionStmt
796                         | CreateDomainStmt
797                         | CreateExtensionStmt
798                         | CreateFdwStmt
799                         | CreateForeignServerStmt
800                         | CreateForeignTableStmt
801                         | CreateFunctionStmt
802                         | CreateGroupStmt
803                         | CreateMatViewStmt
804                         | CreateOpClassStmt
805                         | CreateOpFamilyStmt
806                         | AlterOpFamilyStmt
807                         | CreatePolicyStmt
808                         | CreatePLangStmt
809                         | CreateSchemaStmt
810                         | CreateSeqStmt
811                         | CreateStmt
812                         | CreateTableSpaceStmt
813                         | CreateTransformStmt
814                         | CreateTrigStmt
815                         | CreateEventTrigStmt
816                         | CreateRoleStmt
817                         | CreateUserStmt
818                         | CreateUserMappingStmt
819                         | CreatedbStmt
820                         | DeallocateStmt
821                         | DeclareCursorStmt
822                         | DefineStmt
823                         | DeleteStmt
824                         | DiscardStmt
825                         | DoStmt
826                         | DropAssertStmt
827                         | DropCastStmt
828                         | DropFdwStmt
829                         | DropForeignServerStmt
830                         | DropGroupStmt
831                         | DropOpClassStmt
832                         | DropOpFamilyStmt
833                         | DropOwnedStmt
834                         | DropPolicyStmt
835                         | DropPLangStmt
836                         | DropRuleStmt
837                         | DropStmt
838                         | DropTableSpaceStmt
839                         | DropTransformStmt
840                         | DropTrigStmt
841                         | DropRoleStmt
842                         | DropUserStmt
843                         | DropUserMappingStmt
844                         | DropdbStmt
845                         | ExecuteStmt
846                         | ExplainStmt
847                         | FetchStmt
848                         | GrantStmt
849                         | GrantRoleStmt
850                         | ImportForeignSchemaStmt
851                         | IndexStmt
852                         | InsertStmt
853                         | ListenStmt
854                         | RefreshMatViewStmt
855                         | LoadStmt
856                         | LockStmt
857                         | NotifyStmt
858                         | PrepareStmt
859                         | ReassignOwnedStmt
860                         | ReindexStmt
861                         | RemoveAggrStmt
862                         | RemoveFuncStmt
863                         | RemoveOperStmt
864                         | RenameStmt
865                         | RevokeStmt
866                         | RevokeRoleStmt
867                         | RuleStmt
868                         | SecLabelStmt
869                         | SelectStmt
870                         | TransactionStmt
871                         | TruncateStmt
872                         | UnlistenStmt
873                         | UpdateStmt
874                         | VacuumStmt
875                         | VariableResetStmt
876                         | VariableSetStmt
877                         | VariableShowStmt
878                         | ViewStmt
879                         | /*EMPTY*/
880                                 { $$ = NULL; }
881                 ;
882
883 /*****************************************************************************
884  *
885  * Create a new Postgres DBMS role
886  *
887  *****************************************************************************/
888
889 CreateRoleStmt:
890                         CREATE ROLE RoleId opt_with OptRoleList
891                                 {
892                                         CreateRoleStmt *n = makeNode(CreateRoleStmt);
893                                         n->stmt_type = ROLESTMT_ROLE;
894                                         n->role = $3;
895                                         n->options = $5;
896                                         $$ = (Node *)n;
897                                 }
898                 ;
899
900
901 opt_with:       WITH                                                                    {}
902                         | WITH_LA                                                               {}
903                         | /*EMPTY*/                                                             {}
904                 ;
905
906 /*
907  * Options for CREATE ROLE and ALTER ROLE (also used by CREATE/ALTER USER
908  * for backwards compatibility).  Note: the only option required by SQL99
909  * is "WITH ADMIN name".
910  */
911 OptRoleList:
912                         OptRoleList CreateOptRoleElem                   { $$ = lappend($1, $2); }
913                         | /* EMPTY */                                                   { $$ = NIL; }
914                 ;
915
916 AlterOptRoleList:
917                         AlterOptRoleList AlterOptRoleElem               { $$ = lappend($1, $2); }
918                         | /* EMPTY */                                                   { $$ = NIL; }
919                 ;
920
921 AlterOptRoleElem:
922                         PASSWORD Sconst
923                                 {
924                                         $$ = makeDefElem("password",
925                                                                          (Node *)makeString($2));
926                                 }
927                         | PASSWORD NULL_P
928                                 {
929                                         $$ = makeDefElem("password", NULL);
930                                 }
931                         | ENCRYPTED PASSWORD Sconst
932                                 {
933                                         $$ = makeDefElem("encryptedPassword",
934                                                                          (Node *)makeString($3));
935                                 }
936                         | UNENCRYPTED PASSWORD Sconst
937                                 {
938                                         $$ = makeDefElem("unencryptedPassword",
939                                                                          (Node *)makeString($3));
940                                 }
941                         | INHERIT
942                                 {
943                                         $$ = makeDefElem("inherit", (Node *)makeInteger(TRUE));
944                                 }
945                         | CONNECTION LIMIT SignedIconst
946                                 {
947                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($3));
948                                 }
949                         | VALID UNTIL Sconst
950                                 {
951                                         $$ = makeDefElem("validUntil", (Node *)makeString($3));
952                                 }
953                 /*      Supported but not documented for roles, for use by ALTER GROUP. */
954                         | USER role_list
955                                 {
956                                         $$ = makeDefElem("rolemembers", (Node *)$2);
957                                 }
958                         | IDENT
959                                 {
960                                         /*
961                                          * We handle identifiers that aren't parser keywords with
962                                          * the following special-case codes, to avoid bloating the
963                                          * size of the main parser.
964                                          */
965                                         if (strcmp($1, "superuser") == 0)
966                                                 $$ = makeDefElem("superuser", (Node *)makeInteger(TRUE));
967                                         else if (strcmp($1, "nosuperuser") == 0)
968                                                 $$ = makeDefElem("superuser", (Node *)makeInteger(FALSE));
969                                         else if (strcmp($1, "createuser") == 0)
970                                         {
971                                                 /* For backwards compatibility, synonym for SUPERUSER */
972                                                 $$ = makeDefElem("superuser", (Node *)makeInteger(TRUE));
973                                         }
974                                         else if (strcmp($1, "nocreateuser") == 0)
975                                         {
976                                                 /* For backwards compatibility, synonym for SUPERUSER */
977                                                 $$ = makeDefElem("superuser", (Node *)makeInteger(FALSE));
978                                         }
979                                         else if (strcmp($1, "createrole") == 0)
980                                                 $$ = makeDefElem("createrole", (Node *)makeInteger(TRUE));
981                                         else if (strcmp($1, "nocreaterole") == 0)
982                                                 $$ = makeDefElem("createrole", (Node *)makeInteger(FALSE));
983                                         else if (strcmp($1, "replication") == 0)
984                                                 $$ = makeDefElem("isreplication", (Node *)makeInteger(TRUE));
985                                         else if (strcmp($1, "noreplication") == 0)
986                                                 $$ = makeDefElem("isreplication", (Node *)makeInteger(FALSE));
987                                         else if (strcmp($1, "createdb") == 0)
988                                                 $$ = makeDefElem("createdb", (Node *)makeInteger(TRUE));
989                                         else if (strcmp($1, "nocreatedb") == 0)
990                                                 $$ = makeDefElem("createdb", (Node *)makeInteger(FALSE));
991                                         else if (strcmp($1, "login") == 0)
992                                                 $$ = makeDefElem("canlogin", (Node *)makeInteger(TRUE));
993                                         else if (strcmp($1, "nologin") == 0)
994                                                 $$ = makeDefElem("canlogin", (Node *)makeInteger(FALSE));
995                                         else if (strcmp($1, "bypassrls") == 0)
996                                                 $$ = makeDefElem("bypassrls", (Node *)makeInteger(TRUE));
997                                         else if (strcmp($1, "nobypassrls") == 0)
998                                                 $$ = makeDefElem("bypassrls", (Node *)makeInteger(FALSE));
999                                         else if (strcmp($1, "noinherit") == 0)
1000                                         {
1001                                                 /*
1002                                                  * Note that INHERIT is a keyword, so it's handled by main parser, but
1003                                                  * NOINHERIT is handled here.
1004                                                  */
1005                                                 $$ = makeDefElem("inherit", (Node *)makeInteger(FALSE));
1006                                         }
1007                                         else
1008                                                 ereport(ERROR,
1009                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1010                                                                  errmsg("unrecognized role option \"%s\"", $1),
1011                                                                          parser_errposition(@1)));
1012                                 }
1013                 ;
1014
1015 CreateOptRoleElem:
1016                         AlterOptRoleElem                        { $$ = $1; }
1017                         /* The following are not supported by ALTER ROLE/USER/GROUP */
1018                         | SYSID Iconst
1019                                 {
1020                                         $$ = makeDefElem("sysid", (Node *)makeInteger($2));
1021                                 }
1022                         | ADMIN role_list
1023                                 {
1024                                         $$ = makeDefElem("adminmembers", (Node *)$2);
1025                                 }
1026                         | ROLE role_list
1027                                 {
1028                                         $$ = makeDefElem("rolemembers", (Node *)$2);
1029                                 }
1030                         | IN_P ROLE role_list
1031                                 {
1032                                         $$ = makeDefElem("addroleto", (Node *)$3);
1033                                 }
1034                         | IN_P GROUP_P role_list
1035                                 {
1036                                         $$ = makeDefElem("addroleto", (Node *)$3);
1037                                 }
1038                 ;
1039
1040
1041 /*****************************************************************************
1042  *
1043  * Create a new Postgres DBMS user (role with implied login ability)
1044  *
1045  *****************************************************************************/
1046
1047 CreateUserStmt:
1048                         CREATE USER RoleId opt_with OptRoleList
1049                                 {
1050                                         CreateRoleStmt *n = makeNode(CreateRoleStmt);
1051                                         n->stmt_type = ROLESTMT_USER;
1052                                         n->role = $3;
1053                                         n->options = $5;
1054                                         $$ = (Node *)n;
1055                                 }
1056                 ;
1057
1058
1059 /*****************************************************************************
1060  *
1061  * Alter a postgresql DBMS role
1062  *
1063  *****************************************************************************/
1064
1065 AlterRoleStmt:
1066                         ALTER ROLE RoleSpec opt_with AlterOptRoleList
1067                                  {
1068                                         AlterRoleStmt *n = makeNode(AlterRoleStmt);
1069                                         n->role = $3;
1070                                         n->action = +1; /* add, if there are members */
1071                                         n->options = $5;
1072                                         $$ = (Node *)n;
1073                                  }
1074                 ;
1075
1076 opt_in_database:
1077                            /* EMPTY */                                  { $$ = NULL; }
1078                         | IN_P DATABASE database_name   { $$ = $3; }
1079                 ;
1080
1081 AlterRoleSetStmt:
1082                         ALTER ROLE RoleSpec opt_in_database SetResetClause
1083                                 {
1084                                         AlterRoleSetStmt *n = makeNode(AlterRoleSetStmt);
1085                                         n->role = $3;
1086                                         n->database = $4;
1087                                         n->setstmt = $5;
1088                                         $$ = (Node *)n;
1089                                 }
1090                         | ALTER ROLE ALL opt_in_database SetResetClause
1091                                 {
1092                                         AlterRoleSetStmt *n = makeNode(AlterRoleSetStmt);
1093                                         n->role = NULL;
1094                                         n->database = $4;
1095                                         n->setstmt = $5;
1096                                         $$ = (Node *)n;
1097                                 }
1098                 ;
1099
1100
1101 /*****************************************************************************
1102  *
1103  * Alter a postgresql DBMS user
1104  *
1105  *****************************************************************************/
1106
1107 AlterUserStmt:
1108                         ALTER USER RoleSpec opt_with AlterOptRoleList
1109                                  {
1110                                         AlterRoleStmt *n = makeNode(AlterRoleStmt);
1111                                         n->role = $3;
1112                                         n->action = +1; /* add, if there are members */
1113                                         n->options = $5;
1114                                         $$ = (Node *)n;
1115                                  }
1116                 ;
1117
1118
1119 AlterUserSetStmt:
1120                         ALTER USER RoleSpec SetResetClause
1121                                 {
1122                                         AlterRoleSetStmt *n = makeNode(AlterRoleSetStmt);
1123                                         n->role = $3;
1124                                         n->database = NULL;
1125                                         n->setstmt = $4;
1126                                         $$ = (Node *)n;
1127                                 }
1128                         ;
1129
1130
1131 /*****************************************************************************
1132  *
1133  * Drop a postgresql DBMS role
1134  *
1135  * XXX Ideally this would have CASCADE/RESTRICT options, but since a role
1136  * might own objects in multiple databases, there is presently no way to
1137  * implement either cascading or restricting.  Caveat DBA.
1138  *****************************************************************************/
1139
1140 DropRoleStmt:
1141                         DROP ROLE role_list
1142                                 {
1143                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1144                                         n->missing_ok = FALSE;
1145                                         n->roles = $3;
1146                                         $$ = (Node *)n;
1147                                 }
1148                         | DROP ROLE IF_P EXISTS role_list
1149                                 {
1150                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1151                                         n->missing_ok = TRUE;
1152                                         n->roles = $5;
1153                                         $$ = (Node *)n;
1154                                 }
1155                         ;
1156
1157 /*****************************************************************************
1158  *
1159  * Drop a postgresql DBMS user
1160  *
1161  * XXX Ideally this would have CASCADE/RESTRICT options, but since a user
1162  * might own objects in multiple databases, there is presently no way to
1163  * implement either cascading or restricting.  Caveat DBA.
1164  *****************************************************************************/
1165
1166 DropUserStmt:
1167                         DROP USER role_list
1168                                 {
1169                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1170                                         n->missing_ok = FALSE;
1171                                         n->roles = $3;
1172                                         $$ = (Node *)n;
1173                                 }
1174                         | DROP USER IF_P EXISTS role_list
1175                                 {
1176                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1177                                         n->roles = $5;
1178                                         n->missing_ok = TRUE;
1179                                         $$ = (Node *)n;
1180                                 }
1181                         ;
1182
1183
1184 /*****************************************************************************
1185  *
1186  * Create a postgresql group (role without login ability)
1187  *
1188  *****************************************************************************/
1189
1190 CreateGroupStmt:
1191                         CREATE GROUP_P RoleId opt_with OptRoleList
1192                                 {
1193                                         CreateRoleStmt *n = makeNode(CreateRoleStmt);
1194                                         n->stmt_type = ROLESTMT_GROUP;
1195                                         n->role = $3;
1196                                         n->options = $5;
1197                                         $$ = (Node *)n;
1198                                 }
1199                 ;
1200
1201
1202 /*****************************************************************************
1203  *
1204  * Alter a postgresql group
1205  *
1206  *****************************************************************************/
1207
1208 AlterGroupStmt:
1209                         ALTER GROUP_P RoleSpec add_drop USER role_list
1210                                 {
1211                                         AlterRoleStmt *n = makeNode(AlterRoleStmt);
1212                                         n->role = $3;
1213                                         n->action = $4;
1214                                         n->options = list_make1(makeDefElem("rolemembers",
1215                                                                                                                 (Node *)$6));
1216                                         $$ = (Node *)n;
1217                                 }
1218                 ;
1219
1220 add_drop:       ADD_P                                                                   { $$ = +1; }
1221                         | DROP                                                                  { $$ = -1; }
1222                 ;
1223
1224
1225 /*****************************************************************************
1226  *
1227  * Drop a postgresql group
1228  *
1229  * XXX see above notes about cascading DROP USER; groups have same problem.
1230  *****************************************************************************/
1231
1232 DropGroupStmt:
1233                         DROP GROUP_P role_list
1234                                 {
1235                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1236                                         n->missing_ok = FALSE;
1237                                         n->roles = $3;
1238                                         $$ = (Node *)n;
1239                                 }
1240                         | DROP GROUP_P IF_P EXISTS role_list
1241                                 {
1242                                         DropRoleStmt *n = makeNode(DropRoleStmt);
1243                                         n->missing_ok = TRUE;
1244                                         n->roles = $5;
1245                                         $$ = (Node *)n;
1246                                 }
1247                 ;
1248
1249
1250 /*****************************************************************************
1251  *
1252  * Manipulate a schema
1253  *
1254  *****************************************************************************/
1255
1256 CreateSchemaStmt:
1257                         CREATE SCHEMA OptSchemaName AUTHORIZATION RoleSpec OptSchemaEltList
1258                                 {
1259                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
1260                                         /* One can omit the schema name or the authorization id. */
1261                                         n->schemaname = $3;
1262                                         n->authrole = $5;
1263                                         n->schemaElts = $6;
1264                                         n->if_not_exists = false;
1265                                         $$ = (Node *)n;
1266                                 }
1267                         | CREATE SCHEMA ColId OptSchemaEltList
1268                                 {
1269                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
1270                                         /* ...but not both */
1271                                         n->schemaname = $3;
1272                                         n->authrole = NULL;
1273                                         n->schemaElts = $4;
1274                                         n->if_not_exists = false;
1275                                         $$ = (Node *)n;
1276                                 }
1277                         | CREATE SCHEMA IF_P NOT EXISTS OptSchemaName AUTHORIZATION RoleSpec OptSchemaEltList
1278                                 {
1279                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
1280                                         /* schema name can be omitted here, too */
1281                                         n->schemaname = $6;
1282                                         n->authrole = $8;
1283                                         if ($9 != NIL)
1284                                                 ereport(ERROR,
1285                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1286                                                                  errmsg("CREATE SCHEMA IF NOT EXISTS cannot include schema elements"),
1287                                                                  parser_errposition(@9)));
1288                                         n->schemaElts = $9;
1289                                         n->if_not_exists = true;
1290                                         $$ = (Node *)n;
1291                                 }
1292                         | CREATE SCHEMA IF_P NOT EXISTS ColId OptSchemaEltList
1293                                 {
1294                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
1295                                         /* ...but not here */
1296                                         n->schemaname = $6;
1297                                         n->authrole = NULL;
1298                                         if ($7 != NIL)
1299                                                 ereport(ERROR,
1300                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1301                                                                  errmsg("CREATE SCHEMA IF NOT EXISTS cannot include schema elements"),
1302                                                                  parser_errposition(@7)));
1303                                         n->schemaElts = $7;
1304                                         n->if_not_exists = true;
1305                                         $$ = (Node *)n;
1306                                 }
1307                 ;
1308
1309 OptSchemaName:
1310                         ColId                                                                   { $$ = $1; }
1311                         | /* EMPTY */                                                   { $$ = NULL; }
1312                 ;
1313
1314 OptSchemaEltList:
1315                         OptSchemaEltList schema_stmt
1316                                 {
1317                                         if (@$ < 0)                     /* see comments for YYLLOC_DEFAULT */
1318                                                 @$ = @2;
1319                                         $$ = lappend($1, $2);
1320                                 }
1321                         | /* EMPTY */
1322                                 { $$ = NIL; }
1323                 ;
1324
1325 /*
1326  *      schema_stmt are the ones that can show up inside a CREATE SCHEMA
1327  *      statement (in addition to by themselves).
1328  */
1329 schema_stmt:
1330                         CreateStmt
1331                         | IndexStmt
1332                         | CreateSeqStmt
1333                         | CreateTrigStmt
1334                         | GrantStmt
1335                         | ViewStmt
1336                 ;
1337
1338
1339 /*****************************************************************************
1340  *
1341  * Set PG internal variable
1342  *        SET name TO 'var_value'
1343  * Include SQL syntax (thomas 1997-10-22):
1344  *        SET TIME ZONE 'var_value'
1345  *
1346  *****************************************************************************/
1347
1348 VariableSetStmt:
1349                         SET set_rest
1350                                 {
1351                                         VariableSetStmt *n = $2;
1352                                         n->is_local = false;
1353                                         $$ = (Node *) n;
1354                                 }
1355                         | SET LOCAL set_rest
1356                                 {
1357                                         VariableSetStmt *n = $3;
1358                                         n->is_local = true;
1359                                         $$ = (Node *) n;
1360                                 }
1361                         | SET SESSION set_rest
1362                                 {
1363                                         VariableSetStmt *n = $3;
1364                                         n->is_local = false;
1365                                         $$ = (Node *) n;
1366                                 }
1367                 ;
1368
1369 set_rest:
1370                         TRANSACTION transaction_mode_list
1371                                 {
1372                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1373                                         n->kind = VAR_SET_MULTI;
1374                                         n->name = "TRANSACTION";
1375                                         n->args = $2;
1376                                         $$ = n;
1377                                 }
1378                         | SESSION CHARACTERISTICS AS TRANSACTION transaction_mode_list
1379                                 {
1380                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1381                                         n->kind = VAR_SET_MULTI;
1382                                         n->name = "SESSION CHARACTERISTICS";
1383                                         n->args = $5;
1384                                         $$ = n;
1385                                 }
1386                         | set_rest_more
1387                         ;
1388
1389 generic_set:
1390                         var_name TO var_list
1391                                 {
1392                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1393                                         n->kind = VAR_SET_VALUE;
1394                                         n->name = $1;
1395                                         n->args = $3;
1396                                         $$ = n;
1397                                 }
1398                         | var_name '=' var_list
1399                                 {
1400                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1401                                         n->kind = VAR_SET_VALUE;
1402                                         n->name = $1;
1403                                         n->args = $3;
1404                                         $$ = n;
1405                                 }
1406                         | var_name TO DEFAULT
1407                                 {
1408                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1409                                         n->kind = VAR_SET_DEFAULT;
1410                                         n->name = $1;
1411                                         $$ = n;
1412                                 }
1413                         | var_name '=' DEFAULT
1414                                 {
1415                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1416                                         n->kind = VAR_SET_DEFAULT;
1417                                         n->name = $1;
1418                                         $$ = n;
1419                                 }
1420
1421 set_rest_more:  /* Generic SET syntaxes: */
1422                         generic_set                                             {$$ = $1;}
1423                         | var_name FROM CURRENT_P
1424                                 {
1425                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1426                                         n->kind = VAR_SET_CURRENT;
1427                                         n->name = $1;
1428                                         $$ = n;
1429                                 }
1430                         /* Special syntaxes mandated by SQL standard: */
1431                         | TIME ZONE zone_value
1432                                 {
1433                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1434                                         n->kind = VAR_SET_VALUE;
1435                                         n->name = "timezone";
1436                                         if ($3 != NULL)
1437                                                 n->args = list_make1($3);
1438                                         else
1439                                                 n->kind = VAR_SET_DEFAULT;
1440                                         $$ = n;
1441                                 }
1442                         | CATALOG_P Sconst
1443                                 {
1444                                         ereport(ERROR,
1445                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1446                                                          errmsg("current database cannot be changed"),
1447                                                          parser_errposition(@2)));
1448                                         $$ = NULL; /*not reached*/
1449                                 }
1450                         | SCHEMA Sconst
1451                                 {
1452                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1453                                         n->kind = VAR_SET_VALUE;
1454                                         n->name = "search_path";
1455                                         n->args = list_make1(makeStringConst($2, @2));
1456                                         $$ = n;
1457                                 }
1458                         | NAMES opt_encoding
1459                                 {
1460                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1461                                         n->kind = VAR_SET_VALUE;
1462                                         n->name = "client_encoding";
1463                                         if ($2 != NULL)
1464                                                 n->args = list_make1(makeStringConst($2, @2));
1465                                         else
1466                                                 n->kind = VAR_SET_DEFAULT;
1467                                         $$ = n;
1468                                 }
1469                         | ROLE NonReservedWord_or_Sconst
1470                                 {
1471                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1472                                         n->kind = VAR_SET_VALUE;
1473                                         n->name = "role";
1474                                         n->args = list_make1(makeStringConst($2, @2));
1475                                         $$ = n;
1476                                 }
1477                         | SESSION AUTHORIZATION NonReservedWord_or_Sconst
1478                                 {
1479                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1480                                         n->kind = VAR_SET_VALUE;
1481                                         n->name = "session_authorization";
1482                                         n->args = list_make1(makeStringConst($3, @3));
1483                                         $$ = n;
1484                                 }
1485                         | SESSION AUTHORIZATION DEFAULT
1486                                 {
1487                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1488                                         n->kind = VAR_SET_DEFAULT;
1489                                         n->name = "session_authorization";
1490                                         $$ = n;
1491                                 }
1492                         | XML_P OPTION document_or_content
1493                                 {
1494                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1495                                         n->kind = VAR_SET_VALUE;
1496                                         n->name = "xmloption";
1497                                         n->args = list_make1(makeStringConst($3 == XMLOPTION_DOCUMENT ? "DOCUMENT" : "CONTENT", @3));
1498                                         $$ = n;
1499                                 }
1500                         /* Special syntaxes invented by PostgreSQL: */
1501                         | TRANSACTION SNAPSHOT Sconst
1502                                 {
1503                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1504                                         n->kind = VAR_SET_MULTI;
1505                                         n->name = "TRANSACTION SNAPSHOT";
1506                                         n->args = list_make1(makeStringConst($3, @3));
1507                                         $$ = n;
1508                                 }
1509                 ;
1510
1511 var_name:       ColId                                                           { $$ = $1; }
1512                         | var_name '.' ColId
1513                                 { $$ = psprintf("%s.%s", $1, $3); }
1514                 ;
1515
1516 var_list:       var_value                                                               { $$ = list_make1($1); }
1517                         | var_list ',' var_value                                { $$ = lappend($1, $3); }
1518                 ;
1519
1520 var_value:      opt_boolean_or_string
1521                                 { $$ = makeStringConst($1, @1); }
1522                         | NumericOnly
1523                                 { $$ = makeAConst($1, @1); }
1524                 ;
1525
1526 iso_level:      READ UNCOMMITTED                                                { $$ = "read uncommitted"; }
1527                         | READ COMMITTED                                                { $$ = "read committed"; }
1528                         | REPEATABLE READ                                               { $$ = "repeatable read"; }
1529                         | SERIALIZABLE                                                  { $$ = "serializable"; }
1530                 ;
1531
1532 opt_boolean_or_string:
1533                         TRUE_P                                                                  { $$ = "true"; }
1534                         | FALSE_P                                                               { $$ = "false"; }
1535                         | ON                                                                    { $$ = "on"; }
1536                         /*
1537                          * OFF is also accepted as a boolean value, but is handled by
1538                          * the NonReservedWord rule.  The action for booleans and strings
1539                          * is the same, so we don't need to distinguish them here.
1540                          */
1541                         | NonReservedWord_or_Sconst                             { $$ = $1; }
1542                 ;
1543
1544 /* Timezone values can be:
1545  * - a string such as 'pst8pdt'
1546  * - an identifier such as "pst8pdt"
1547  * - an integer or floating point number
1548  * - a time interval per SQL99
1549  * ColId gives reduce/reduce errors against ConstInterval and LOCAL,
1550  * so use IDENT (meaning we reject anything that is a key word).
1551  */
1552 zone_value:
1553                         Sconst
1554                                 {
1555                                         $$ = makeStringConst($1, @1);
1556                                 }
1557                         | IDENT
1558                                 {
1559                                         $$ = makeStringConst($1, @1);
1560                                 }
1561                         | ConstInterval Sconst opt_interval
1562                                 {
1563                                         TypeName *t = $1;
1564                                         if ($3 != NIL)
1565                                         {
1566                                                 A_Const *n = (A_Const *) linitial($3);
1567                                                 if ((n->val.val.ival & ~(INTERVAL_MASK(HOUR) | INTERVAL_MASK(MINUTE))) != 0)
1568                                                         ereport(ERROR,
1569                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1570                                                                          errmsg("time zone interval must be HOUR or HOUR TO MINUTE"),
1571                                                                          parser_errposition(@3)));
1572                                         }
1573                                         t->typmods = $3;
1574                                         $$ = makeStringConstCast($2, @2, t);
1575                                 }
1576                         | ConstInterval '(' Iconst ')' Sconst
1577                                 {
1578                                         TypeName *t = $1;
1579                                         t->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
1580                                                                                         makeIntConst($3, @3));
1581                                         $$ = makeStringConstCast($5, @5, t);
1582                                 }
1583                         | NumericOnly                                                   { $$ = makeAConst($1, @1); }
1584                         | DEFAULT                                                               { $$ = NULL; }
1585                         | LOCAL                                                                 { $$ = NULL; }
1586                 ;
1587
1588 opt_encoding:
1589                         Sconst                                                                  { $$ = $1; }
1590                         | DEFAULT                                                               { $$ = NULL; }
1591                         | /*EMPTY*/                                                             { $$ = NULL; }
1592                 ;
1593
1594 NonReservedWord_or_Sconst:
1595                         NonReservedWord                                                 { $$ = $1; }
1596                         | Sconst                                                                { $$ = $1; }
1597                 ;
1598
1599 VariableResetStmt:
1600                         RESET reset_rest                                                { $$ = (Node *) $2; }
1601                 ;
1602
1603 reset_rest:
1604                         generic_reset                                                   { $$ = $1; }
1605                         | TIME ZONE
1606                                 {
1607                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1608                                         n->kind = VAR_RESET;
1609                                         n->name = "timezone";
1610                                         $$ = n;
1611                                 }
1612                         | TRANSACTION ISOLATION LEVEL
1613                                 {
1614                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1615                                         n->kind = VAR_RESET;
1616                                         n->name = "transaction_isolation";
1617                                         $$ = n;
1618                                 }
1619                         | SESSION AUTHORIZATION
1620                                 {
1621                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1622                                         n->kind = VAR_RESET;
1623                                         n->name = "session_authorization";
1624                                         $$ = n;
1625                                 }
1626                 ;
1627
1628 generic_reset:
1629                         var_name
1630                                 {
1631                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1632                                         n->kind = VAR_RESET;
1633                                         n->name = $1;
1634                                         $$ = n;
1635                                 }
1636                         | ALL
1637                                 {
1638                                         VariableSetStmt *n = makeNode(VariableSetStmt);
1639                                         n->kind = VAR_RESET_ALL;
1640                                         $$ = n;
1641                                 }
1642                 ;
1643
1644 /* SetResetClause allows SET or RESET without LOCAL */
1645 SetResetClause:
1646                         SET set_rest                                    { $$ = $2; }
1647                         | VariableResetStmt                             { $$ = (VariableSetStmt *) $1; }
1648                 ;
1649
1650 /* SetResetClause allows SET or RESET without LOCAL */
1651 FunctionSetResetClause:
1652                         SET set_rest_more                               { $$ = $2; }
1653                         | VariableResetStmt                             { $$ = (VariableSetStmt *) $1; }
1654                 ;
1655
1656
1657 VariableShowStmt:
1658                         SHOW var_name
1659                                 {
1660                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1661                                         n->name = $2;
1662                                         $$ = (Node *) n;
1663                                 }
1664                         | SHOW TIME ZONE
1665                                 {
1666                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1667                                         n->name = "timezone";
1668                                         $$ = (Node *) n;
1669                                 }
1670                         | SHOW TRANSACTION ISOLATION LEVEL
1671                                 {
1672                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1673                                         n->name = "transaction_isolation";
1674                                         $$ = (Node *) n;
1675                                 }
1676                         | SHOW SESSION AUTHORIZATION
1677                                 {
1678                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1679                                         n->name = "session_authorization";
1680                                         $$ = (Node *) n;
1681                                 }
1682                         | SHOW ALL
1683                                 {
1684                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1685                                         n->name = "all";
1686                                         $$ = (Node *) n;
1687                                 }
1688                 ;
1689
1690
1691 ConstraintsSetStmt:
1692                         SET CONSTRAINTS constraints_set_list constraints_set_mode
1693                                 {
1694                                         ConstraintsSetStmt *n = makeNode(ConstraintsSetStmt);
1695                                         n->constraints = $3;
1696                                         n->deferred = $4;
1697                                         $$ = (Node *) n;
1698                                 }
1699                 ;
1700
1701 constraints_set_list:
1702                         ALL                                                                             { $$ = NIL; }
1703                         | qualified_name_list                                   { $$ = $1; }
1704                 ;
1705
1706 constraints_set_mode:
1707                         DEFERRED                                                                { $$ = TRUE; }
1708                         | IMMEDIATE                                                             { $$ = FALSE; }
1709                 ;
1710
1711
1712 /*
1713  * Checkpoint statement
1714  */
1715 CheckPointStmt:
1716                         CHECKPOINT
1717                                 {
1718                                         CheckPointStmt *n = makeNode(CheckPointStmt);
1719                                         $$ = (Node *)n;
1720                                 }
1721                 ;
1722
1723
1724 /*****************************************************************************
1725  *
1726  * DISCARD { ALL | TEMP | PLANS | SEQUENCES }
1727  *
1728  *****************************************************************************/
1729
1730 DiscardStmt:
1731                         DISCARD ALL
1732                                 {
1733                                         DiscardStmt *n = makeNode(DiscardStmt);
1734                                         n->target = DISCARD_ALL;
1735                                         $$ = (Node *) n;
1736                                 }
1737                         | DISCARD TEMP
1738                                 {
1739                                         DiscardStmt *n = makeNode(DiscardStmt);
1740                                         n->target = DISCARD_TEMP;
1741                                         $$ = (Node *) n;
1742                                 }
1743                         | DISCARD TEMPORARY
1744                                 {
1745                                         DiscardStmt *n = makeNode(DiscardStmt);
1746                                         n->target = DISCARD_TEMP;
1747                                         $$ = (Node *) n;
1748                                 }
1749                         | DISCARD PLANS
1750                                 {
1751                                         DiscardStmt *n = makeNode(DiscardStmt);
1752                                         n->target = DISCARD_PLANS;
1753                                         $$ = (Node *) n;
1754                                 }
1755                         | DISCARD SEQUENCES
1756                                 {
1757                                         DiscardStmt *n = makeNode(DiscardStmt);
1758                                         n->target = DISCARD_SEQUENCES;
1759                                         $$ = (Node *) n;
1760                                 }
1761
1762                 ;
1763
1764
1765 /*****************************************************************************
1766  *
1767  *      ALTER [ TABLE | INDEX | SEQUENCE | VIEW | MATERIALIZED VIEW ] variations
1768  *
1769  * Note: we accept all subcommands for each of the five variants, and sort
1770  * out what's really legal at execution time.
1771  *****************************************************************************/
1772
1773 AlterTableStmt:
1774                         ALTER TABLE relation_expr alter_table_cmds
1775                                 {
1776                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1777                                         n->relation = $3;
1778                                         n->cmds = $4;
1779                                         n->relkind = OBJECT_TABLE;
1780                                         n->missing_ok = false;
1781                                         $$ = (Node *)n;
1782                                 }
1783                 |       ALTER TABLE IF_P EXISTS relation_expr alter_table_cmds
1784                                 {
1785                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1786                                         n->relation = $5;
1787                                         n->cmds = $6;
1788                                         n->relkind = OBJECT_TABLE;
1789                                         n->missing_ok = true;
1790                                         $$ = (Node *)n;
1791                                 }
1792                 |       ALTER TABLE ALL IN_P TABLESPACE name SET TABLESPACE name opt_nowait
1793                                 {
1794                                         AlterTableMoveAllStmt *n =
1795                                                 makeNode(AlterTableMoveAllStmt);
1796                                         n->orig_tablespacename = $6;
1797                                         n->objtype = OBJECT_TABLE;
1798                                         n->roles = NIL;
1799                                         n->new_tablespacename = $9;
1800                                         n->nowait = $10;
1801                                         $$ = (Node *)n;
1802                                 }
1803                 |       ALTER TABLE ALL IN_P TABLESPACE name OWNED BY role_list SET TABLESPACE name opt_nowait
1804                                 {
1805                                         AlterTableMoveAllStmt *n =
1806                                                 makeNode(AlterTableMoveAllStmt);
1807                                         n->orig_tablespacename = $6;
1808                                         n->objtype = OBJECT_TABLE;
1809                                         n->roles = $9;
1810                                         n->new_tablespacename = $12;
1811                                         n->nowait = $13;
1812                                         $$ = (Node *)n;
1813                                 }
1814                 |       ALTER INDEX qualified_name alter_table_cmds
1815                                 {
1816                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1817                                         n->relation = $3;
1818                                         n->cmds = $4;
1819                                         n->relkind = OBJECT_INDEX;
1820                                         n->missing_ok = false;
1821                                         $$ = (Node *)n;
1822                                 }
1823                 |       ALTER INDEX IF_P EXISTS qualified_name alter_table_cmds
1824                                 {
1825                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1826                                         n->relation = $5;
1827                                         n->cmds = $6;
1828                                         n->relkind = OBJECT_INDEX;
1829                                         n->missing_ok = true;
1830                                         $$ = (Node *)n;
1831                                 }
1832                 |       ALTER INDEX ALL IN_P TABLESPACE name SET TABLESPACE name opt_nowait
1833                                 {
1834                                         AlterTableMoveAllStmt *n =
1835                                                 makeNode(AlterTableMoveAllStmt);
1836                                         n->orig_tablespacename = $6;
1837                                         n->objtype = OBJECT_INDEX;
1838                                         n->roles = NIL;
1839                                         n->new_tablespacename = $9;
1840                                         n->nowait = $10;
1841                                         $$ = (Node *)n;
1842                                 }
1843                 |       ALTER INDEX ALL IN_P TABLESPACE name OWNED BY role_list SET TABLESPACE name opt_nowait
1844                                 {
1845                                         AlterTableMoveAllStmt *n =
1846                                                 makeNode(AlterTableMoveAllStmt);
1847                                         n->orig_tablespacename = $6;
1848                                         n->objtype = OBJECT_INDEX;
1849                                         n->roles = $9;
1850                                         n->new_tablespacename = $12;
1851                                         n->nowait = $13;
1852                                         $$ = (Node *)n;
1853                                 }
1854                 |       ALTER SEQUENCE qualified_name alter_table_cmds
1855                                 {
1856                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1857                                         n->relation = $3;
1858                                         n->cmds = $4;
1859                                         n->relkind = OBJECT_SEQUENCE;
1860                                         n->missing_ok = false;
1861                                         $$ = (Node *)n;
1862                                 }
1863                 |       ALTER SEQUENCE IF_P EXISTS qualified_name alter_table_cmds
1864                                 {
1865                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1866                                         n->relation = $5;
1867                                         n->cmds = $6;
1868                                         n->relkind = OBJECT_SEQUENCE;
1869                                         n->missing_ok = true;
1870                                         $$ = (Node *)n;
1871                                 }
1872                 |       ALTER VIEW qualified_name alter_table_cmds
1873                                 {
1874                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1875                                         n->relation = $3;
1876                                         n->cmds = $4;
1877                                         n->relkind = OBJECT_VIEW;
1878                                         n->missing_ok = false;
1879                                         $$ = (Node *)n;
1880                                 }
1881                 |       ALTER VIEW IF_P EXISTS qualified_name alter_table_cmds
1882                                 {
1883                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1884                                         n->relation = $5;
1885                                         n->cmds = $6;
1886                                         n->relkind = OBJECT_VIEW;
1887                                         n->missing_ok = true;
1888                                         $$ = (Node *)n;
1889                                 }
1890                 |       ALTER MATERIALIZED VIEW qualified_name alter_table_cmds
1891                                 {
1892                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1893                                         n->relation = $4;
1894                                         n->cmds = $5;
1895                                         n->relkind = OBJECT_MATVIEW;
1896                                         n->missing_ok = false;
1897                                         $$ = (Node *)n;
1898                                 }
1899                 |       ALTER MATERIALIZED VIEW IF_P EXISTS qualified_name alter_table_cmds
1900                                 {
1901                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1902                                         n->relation = $6;
1903                                         n->cmds = $7;
1904                                         n->relkind = OBJECT_MATVIEW;
1905                                         n->missing_ok = true;
1906                                         $$ = (Node *)n;
1907                                 }
1908                 |       ALTER MATERIALIZED VIEW ALL IN_P TABLESPACE name SET TABLESPACE name opt_nowait
1909                                 {
1910                                         AlterTableMoveAllStmt *n =
1911                                                 makeNode(AlterTableMoveAllStmt);
1912                                         n->orig_tablespacename = $7;
1913                                         n->objtype = OBJECT_MATVIEW;
1914                                         n->roles = NIL;
1915                                         n->new_tablespacename = $10;
1916                                         n->nowait = $11;
1917                                         $$ = (Node *)n;
1918                                 }
1919                 |       ALTER MATERIALIZED VIEW ALL IN_P TABLESPACE name OWNED BY role_list SET TABLESPACE name opt_nowait
1920                                 {
1921                                         AlterTableMoveAllStmt *n =
1922                                                 makeNode(AlterTableMoveAllStmt);
1923                                         n->orig_tablespacename = $7;
1924                                         n->objtype = OBJECT_MATVIEW;
1925                                         n->roles = $10;
1926                                         n->new_tablespacename = $13;
1927                                         n->nowait = $14;
1928                                         $$ = (Node *)n;
1929                                 }
1930                 ;
1931
1932 alter_table_cmds:
1933                         alter_table_cmd                                                 { $$ = list_make1($1); }
1934                         | alter_table_cmds ',' alter_table_cmd  { $$ = lappend($1, $3); }
1935                 ;
1936
1937 alter_table_cmd:
1938                         /* ALTER TABLE <name> ADD <coldef> */
1939                         ADD_P columnDef
1940                                 {
1941                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1942                                         n->subtype = AT_AddColumn;
1943                                         n->def = $2;
1944                                         n->missing_ok = false;
1945                                         $$ = (Node *)n;
1946                                 }
1947                         /* ALTER TABLE <name> ADD IF NOT EXISTS <coldef> */
1948                         | ADD_P IF_P NOT EXISTS columnDef
1949                                 {
1950                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1951                                         n->subtype = AT_AddColumn;
1952                                         n->def = $5;
1953                                         n->missing_ok = true;
1954                                         $$ = (Node *)n;
1955                                 }
1956                         /* ALTER TABLE <name> ADD COLUMN <coldef> */
1957                         | ADD_P COLUMN columnDef
1958                                 {
1959                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1960                                         n->subtype = AT_AddColumn;
1961                                         n->def = $3;
1962                                         n->missing_ok = false;
1963                                         $$ = (Node *)n;
1964                                 }
1965                         /* ALTER TABLE <name> ADD COLUMN IF NOT EXISTS <coldef> */
1966                         | ADD_P COLUMN IF_P NOT EXISTS columnDef
1967                                 {
1968                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1969                                         n->subtype = AT_AddColumn;
1970                                         n->def = $6;
1971                                         n->missing_ok = true;
1972                                         $$ = (Node *)n;
1973                                 }
1974                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
1975                         | ALTER opt_column ColId alter_column_default
1976                                 {
1977                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1978                                         n->subtype = AT_ColumnDefault;
1979                                         n->name = $3;
1980                                         n->def = $4;
1981                                         $$ = (Node *)n;
1982                                 }
1983                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> DROP NOT NULL */
1984                         | ALTER opt_column ColId DROP NOT NULL_P
1985                                 {
1986                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1987                                         n->subtype = AT_DropNotNull;
1988                                         n->name = $3;
1989                                         $$ = (Node *)n;
1990                                 }
1991                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET NOT NULL */
1992                         | ALTER opt_column ColId SET NOT NULL_P
1993                                 {
1994                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1995                                         n->subtype = AT_SetNotNull;
1996                                         n->name = $3;
1997                                         $$ = (Node *)n;
1998                                 }
1999                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET STATISTICS <SignedIconst> */
2000                         | ALTER opt_column ColId SET STATISTICS SignedIconst
2001                                 {
2002                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2003                                         n->subtype = AT_SetStatistics;
2004                                         n->name = $3;
2005                                         n->def = (Node *) makeInteger($6);
2006                                         $$ = (Node *)n;
2007                                 }
2008                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET ( column_parameter = value [, ... ] ) */
2009                         | ALTER opt_column ColId SET reloptions
2010                                 {
2011                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2012                                         n->subtype = AT_SetOptions;
2013                                         n->name = $3;
2014                                         n->def = (Node *) $5;
2015                                         $$ = (Node *)n;
2016                                 }
2017                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET ( column_parameter = value [, ... ] ) */
2018                         | ALTER opt_column ColId RESET reloptions
2019                                 {
2020                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2021                                         n->subtype = AT_ResetOptions;
2022                                         n->name = $3;
2023                                         n->def = (Node *) $5;
2024                                         $$ = (Node *)n;
2025                                 }
2026                         /* ALTER TABLE <name> ALTER [COLUMN] <colname> SET STORAGE <storagemode> */
2027                         | ALTER opt_column ColId SET STORAGE ColId
2028                                 {
2029                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2030                                         n->subtype = AT_SetStorage;
2031                                         n->name = $3;
2032                                         n->def = (Node *) makeString($6);
2033                                         $$ = (Node *)n;
2034                                 }
2035                         /* ALTER TABLE <name> DROP [COLUMN] IF EXISTS <colname> [RESTRICT|CASCADE] */
2036                         | DROP opt_column IF_P EXISTS ColId opt_drop_behavior
2037                                 {
2038                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2039                                         n->subtype = AT_DropColumn;
2040                                         n->name = $5;
2041                                         n->behavior = $6;
2042                                         n->missing_ok = TRUE;
2043                                         $$ = (Node *)n;
2044                                 }
2045                         /* ALTER TABLE <name> DROP [COLUMN] <colname> [RESTRICT|CASCADE] */
2046                         | DROP opt_column ColId opt_drop_behavior
2047                                 {
2048                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2049                                         n->subtype = AT_DropColumn;
2050                                         n->name = $3;
2051                                         n->behavior = $4;
2052                                         n->missing_ok = FALSE;
2053                                         $$ = (Node *)n;
2054                                 }
2055                         /*
2056                          * ALTER TABLE <name> ALTER [COLUMN] <colname> [SET DATA] TYPE <typename>
2057                          *              [ USING <expression> ]
2058                          */
2059                         | ALTER opt_column ColId opt_set_data TYPE_P Typename opt_collate_clause alter_using
2060                                 {
2061                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2062                                         ColumnDef *def = makeNode(ColumnDef);
2063                                         n->subtype = AT_AlterColumnType;
2064                                         n->name = $3;
2065                                         n->def = (Node *) def;
2066                                         /* We only use these fields of the ColumnDef node */
2067                                         def->typeName = $6;
2068                                         def->collClause = (CollateClause *) $7;
2069                                         def->raw_default = $8;
2070                                         def->location = @3;
2071                                         $$ = (Node *)n;
2072                                 }
2073                         /* ALTER FOREIGN TABLE <name> ALTER [COLUMN] <colname> OPTIONS */
2074                         | ALTER opt_column ColId alter_generic_options
2075                                 {
2076                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2077                                         n->subtype = AT_AlterColumnGenericOptions;
2078                                         n->name = $3;
2079                                         n->def = (Node *) $4;
2080                                         $$ = (Node *)n;
2081                                 }
2082                         /* ALTER TABLE <name> ADD CONSTRAINT ... */
2083                         | ADD_P TableConstraint
2084                                 {
2085                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2086                                         n->subtype = AT_AddConstraint;
2087                                         n->def = $2;
2088                                         $$ = (Node *)n;
2089                                 }
2090                         /* ALTER TABLE <name> ALTER CONSTRAINT ... */
2091                         | ALTER CONSTRAINT name ConstraintAttributeSpec
2092                                 {
2093                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2094                                         Constraint *c = makeNode(Constraint);
2095                                         n->subtype = AT_AlterConstraint;
2096                                         n->def = (Node *) c;
2097                                         c->contype = CONSTR_FOREIGN; /* others not supported, yet */
2098                                         c->conname = $3;
2099                                         processCASbits($4, @4, "ALTER CONSTRAINT statement",
2100                                                                         &c->deferrable,
2101                                                                         &c->initdeferred,
2102                                                                         NULL, NULL, yyscanner);
2103                                         $$ = (Node *)n;
2104                                 }
2105                         /* ALTER TABLE <name> VALIDATE CONSTRAINT ... */
2106                         | VALIDATE CONSTRAINT name
2107                                 {
2108                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2109                                         n->subtype = AT_ValidateConstraint;
2110                                         n->name = $3;
2111                                         $$ = (Node *)n;
2112                                 }
2113                         /* ALTER TABLE <name> DROP CONSTRAINT IF EXISTS <name> [RESTRICT|CASCADE] */
2114                         | DROP CONSTRAINT IF_P EXISTS name opt_drop_behavior
2115                                 {
2116                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2117                                         n->subtype = AT_DropConstraint;
2118                                         n->name = $5;
2119                                         n->behavior = $6;
2120                                         n->missing_ok = TRUE;
2121                                         $$ = (Node *)n;
2122                                 }
2123                         /* ALTER TABLE <name> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
2124                         | DROP CONSTRAINT name opt_drop_behavior
2125                                 {
2126                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2127                                         n->subtype = AT_DropConstraint;
2128                                         n->name = $3;
2129                                         n->behavior = $4;
2130                                         n->missing_ok = FALSE;
2131                                         $$ = (Node *)n;
2132                                 }
2133                         /* ALTER TABLE <name> SET WITH OIDS  */
2134                         | SET WITH OIDS
2135                                 {
2136                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2137                                         n->subtype = AT_AddOids;
2138                                         $$ = (Node *)n;
2139                                 }
2140                         /* ALTER TABLE <name> SET WITHOUT OIDS  */
2141                         | SET WITHOUT OIDS
2142                                 {
2143                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2144                                         n->subtype = AT_DropOids;
2145                                         $$ = (Node *)n;
2146                                 }
2147                         /* ALTER TABLE <name> CLUSTER ON <indexname> */
2148                         | CLUSTER ON name
2149                                 {
2150                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2151                                         n->subtype = AT_ClusterOn;
2152                                         n->name = $3;
2153                                         $$ = (Node *)n;
2154                                 }
2155                         /* ALTER TABLE <name> SET WITHOUT CLUSTER */
2156                         | SET WITHOUT CLUSTER
2157                                 {
2158                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2159                                         n->subtype = AT_DropCluster;
2160                                         n->name = NULL;
2161                                         $$ = (Node *)n;
2162                                 }
2163                         /* ALTER TABLE <name> SET LOGGED  */
2164                         | SET LOGGED
2165                                 {
2166                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2167                                         n->subtype = AT_SetLogged;
2168                                         $$ = (Node *)n;
2169                                 }
2170                         /* ALTER TABLE <name> SET UNLOGGED  */
2171                         | SET UNLOGGED
2172                                 {
2173                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2174                                         n->subtype = AT_SetUnLogged;
2175                                         $$ = (Node *)n;
2176                                 }
2177                         /* ALTER TABLE <name> ENABLE TRIGGER <trig> */
2178                         | ENABLE_P TRIGGER name
2179                                 {
2180                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2181                                         n->subtype = AT_EnableTrig;
2182                                         n->name = $3;
2183                                         $$ = (Node *)n;
2184                                 }
2185                         /* ALTER TABLE <name> ENABLE ALWAYS TRIGGER <trig> */
2186                         | ENABLE_P ALWAYS TRIGGER name
2187                                 {
2188                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2189                                         n->subtype = AT_EnableAlwaysTrig;
2190                                         n->name = $4;
2191                                         $$ = (Node *)n;
2192                                 }
2193                         /* ALTER TABLE <name> ENABLE REPLICA TRIGGER <trig> */
2194                         | ENABLE_P REPLICA TRIGGER name
2195                                 {
2196                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2197                                         n->subtype = AT_EnableReplicaTrig;
2198                                         n->name = $4;
2199                                         $$ = (Node *)n;
2200                                 }
2201                         /* ALTER TABLE <name> ENABLE TRIGGER ALL */
2202                         | ENABLE_P TRIGGER ALL
2203                                 {
2204                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2205                                         n->subtype = AT_EnableTrigAll;
2206                                         $$ = (Node *)n;
2207                                 }
2208                         /* ALTER TABLE <name> ENABLE TRIGGER USER */
2209                         | ENABLE_P TRIGGER USER
2210                                 {
2211                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2212                                         n->subtype = AT_EnableTrigUser;
2213                                         $$ = (Node *)n;
2214                                 }
2215                         /* ALTER TABLE <name> DISABLE TRIGGER <trig> */
2216                         | DISABLE_P TRIGGER name
2217                                 {
2218                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2219                                         n->subtype = AT_DisableTrig;
2220                                         n->name = $3;
2221                                         $$ = (Node *)n;
2222                                 }
2223                         /* ALTER TABLE <name> DISABLE TRIGGER ALL */
2224                         | DISABLE_P TRIGGER ALL
2225                                 {
2226                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2227                                         n->subtype = AT_DisableTrigAll;
2228                                         $$ = (Node *)n;
2229                                 }
2230                         /* ALTER TABLE <name> DISABLE TRIGGER USER */
2231                         | DISABLE_P TRIGGER USER
2232                                 {
2233                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2234                                         n->subtype = AT_DisableTrigUser;
2235                                         $$ = (Node *)n;
2236                                 }
2237                         /* ALTER TABLE <name> ENABLE RULE <rule> */
2238                         | ENABLE_P RULE name
2239                                 {
2240                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2241                                         n->subtype = AT_EnableRule;
2242                                         n->name = $3;
2243                                         $$ = (Node *)n;
2244                                 }
2245                         /* ALTER TABLE <name> ENABLE ALWAYS RULE <rule> */
2246                         | ENABLE_P ALWAYS RULE name
2247                                 {
2248                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2249                                         n->subtype = AT_EnableAlwaysRule;
2250                                         n->name = $4;
2251                                         $$ = (Node *)n;
2252                                 }
2253                         /* ALTER TABLE <name> ENABLE REPLICA RULE <rule> */
2254                         | ENABLE_P REPLICA RULE name
2255                                 {
2256                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2257                                         n->subtype = AT_EnableReplicaRule;
2258                                         n->name = $4;
2259                                         $$ = (Node *)n;
2260                                 }
2261                         /* ALTER TABLE <name> DISABLE RULE <rule> */
2262                         | DISABLE_P RULE name
2263                                 {
2264                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2265                                         n->subtype = AT_DisableRule;
2266                                         n->name = $3;
2267                                         $$ = (Node *)n;
2268                                 }
2269                         /* ALTER TABLE <name> INHERIT <parent> */
2270                         | INHERIT qualified_name
2271                                 {
2272                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2273                                         n->subtype = AT_AddInherit;
2274                                         n->def = (Node *) $2;
2275                                         $$ = (Node *)n;
2276                                 }
2277                         /* ALTER TABLE <name> NO INHERIT <parent> */
2278                         | NO INHERIT qualified_name
2279                                 {
2280                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2281                                         n->subtype = AT_DropInherit;
2282                                         n->def = (Node *) $3;
2283                                         $$ = (Node *)n;
2284                                 }
2285                         /* ALTER TABLE <name> OF <type_name> */
2286                         | OF any_name
2287                                 {
2288                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2289                                         TypeName *def = makeTypeNameFromNameList($2);
2290                                         def->location = @2;
2291                                         n->subtype = AT_AddOf;
2292                                         n->def = (Node *) def;
2293                                         $$ = (Node *)n;
2294                                 }
2295                         /* ALTER TABLE <name> NOT OF */
2296                         | NOT OF
2297                                 {
2298                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2299                                         n->subtype = AT_DropOf;
2300                                         $$ = (Node *)n;
2301                                 }
2302                         /* ALTER TABLE <name> OWNER TO RoleSpec */
2303                         | OWNER TO RoleSpec
2304                                 {
2305                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2306                                         n->subtype = AT_ChangeOwner;
2307                                         n->newowner = $3;
2308                                         $$ = (Node *)n;
2309                                 }
2310                         /* ALTER TABLE <name> SET TABLESPACE <tablespacename> */
2311                         | SET TABLESPACE name
2312                                 {
2313                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2314                                         n->subtype = AT_SetTableSpace;
2315                                         n->name = $3;
2316                                         $$ = (Node *)n;
2317                                 }
2318                         /* ALTER TABLE <name> SET (...) */
2319                         | SET reloptions
2320                                 {
2321                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2322                                         n->subtype = AT_SetRelOptions;
2323                                         n->def = (Node *)$2;
2324                                         $$ = (Node *)n;
2325                                 }
2326                         /* ALTER TABLE <name> RESET (...) */
2327                         | RESET reloptions
2328                                 {
2329                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2330                                         n->subtype = AT_ResetRelOptions;
2331                                         n->def = (Node *)$2;
2332                                         $$ = (Node *)n;
2333                                 }
2334                         /* ALTER TABLE <name> REPLICA IDENTITY  */
2335                         | REPLICA IDENTITY_P replica_identity
2336                                 {
2337                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2338                                         n->subtype = AT_ReplicaIdentity;
2339                                         n->def = $3;
2340                                         $$ = (Node *)n;
2341                                 }
2342                         /* ALTER TABLE <name> ENABLE ROW LEVEL SECURITY */
2343                         | ENABLE_P ROW LEVEL SECURITY
2344                                 {
2345                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2346                                         n->subtype = AT_EnableRowSecurity;
2347                                         $$ = (Node *)n;
2348                                 }
2349                         /* ALTER TABLE <name> DISABLE ROW LEVEL SECURITY */
2350                         | DISABLE_P ROW LEVEL SECURITY
2351                                 {
2352                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2353                                         n->subtype = AT_DisableRowSecurity;
2354                                         $$ = (Node *)n;
2355                                 }
2356                         | alter_generic_options
2357                                 {
2358                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2359                                         n->subtype = AT_GenericOptions;
2360                                         n->def = (Node *)$1;
2361                                         $$ = (Node *) n;
2362                                 }
2363                 ;
2364
2365 alter_column_default:
2366                         SET DEFAULT a_expr                      { $$ = $3; }
2367                         | DROP DEFAULT                          { $$ = NULL; }
2368                 ;
2369
2370 opt_drop_behavior:
2371                         CASCADE                                         { $$ = DROP_CASCADE; }
2372                         | RESTRICT                                      { $$ = DROP_RESTRICT; }
2373                         | /* EMPTY */                           { $$ = DROP_RESTRICT; /* default */ }
2374                 ;
2375
2376 opt_collate_clause:
2377                         COLLATE any_name
2378                                 {
2379                                         CollateClause *n = makeNode(CollateClause);
2380                                         n->arg = NULL;
2381                                         n->collname = $2;
2382                                         n->location = @1;
2383                                         $$ = (Node *) n;
2384                                 }
2385                         | /* EMPTY */                           { $$ = NULL; }
2386                 ;
2387
2388 alter_using:
2389                         USING a_expr                            { $$ = $2; }
2390                         | /* EMPTY */                           { $$ = NULL; }
2391                 ;
2392
2393 replica_identity:
2394                         NOTHING
2395                                 {
2396                                         ReplicaIdentityStmt *n = makeNode(ReplicaIdentityStmt);
2397                                         n->identity_type = REPLICA_IDENTITY_NOTHING;
2398                                         n->name = NULL;
2399                                         $$ = (Node *) n;
2400                                 }
2401                         | FULL
2402                                 {
2403                                         ReplicaIdentityStmt *n = makeNode(ReplicaIdentityStmt);
2404                                         n->identity_type = REPLICA_IDENTITY_FULL;
2405                                         n->name = NULL;
2406                                         $$ = (Node *) n;
2407                                 }
2408                         | DEFAULT
2409                                 {
2410                                         ReplicaIdentityStmt *n = makeNode(ReplicaIdentityStmt);
2411                                         n->identity_type = REPLICA_IDENTITY_DEFAULT;
2412                                         n->name = NULL;
2413                                         $$ = (Node *) n;
2414                                 }
2415                         | USING INDEX name
2416                                 {
2417                                         ReplicaIdentityStmt *n = makeNode(ReplicaIdentityStmt);
2418                                         n->identity_type = REPLICA_IDENTITY_INDEX;
2419                                         n->name = $3;
2420                                         $$ = (Node *) n;
2421                                 }
2422 ;
2423
2424 reloptions:
2425                         '(' reloption_list ')'                                  { $$ = $2; }
2426                 ;
2427
2428 opt_reloptions:         WITH reloptions                                 { $$ = $2; }
2429                          |              /* EMPTY */                                             { $$ = NIL; }
2430                 ;
2431
2432 reloption_list:
2433                         reloption_elem                                                  { $$ = list_make1($1); }
2434                         | reloption_list ',' reloption_elem             { $$ = lappend($1, $3); }
2435                 ;
2436
2437 /* This should match def_elem and also allow qualified names */
2438 reloption_elem:
2439                         ColLabel '=' def_arg
2440                                 {
2441                                         $$ = makeDefElem($1, (Node *) $3);
2442                                 }
2443                         | ColLabel
2444                                 {
2445                                         $$ = makeDefElem($1, NULL);
2446                                 }
2447                         | ColLabel '.' ColLabel '=' def_arg
2448                                 {
2449                                         $$ = makeDefElemExtended($1, $3, (Node *) $5,
2450                                                                                          DEFELEM_UNSPEC);
2451                                 }
2452                         | ColLabel '.' ColLabel
2453                                 {
2454                                         $$ = makeDefElemExtended($1, $3, NULL, DEFELEM_UNSPEC);
2455                                 }
2456                 ;
2457
2458
2459 /*****************************************************************************
2460  *
2461  *      ALTER TYPE
2462  *
2463  * really variants of the ALTER TABLE subcommands with different spellings
2464  *****************************************************************************/
2465
2466 AlterCompositeTypeStmt:
2467                         ALTER TYPE_P any_name alter_type_cmds
2468                                 {
2469                                         AlterTableStmt *n = makeNode(AlterTableStmt);
2470
2471                                         /* can't use qualified_name, sigh */
2472                                         n->relation = makeRangeVarFromAnyName($3, @3, yyscanner);
2473                                         n->cmds = $4;
2474                                         n->relkind = OBJECT_TYPE;
2475                                         $$ = (Node *)n;
2476                                 }
2477                         ;
2478
2479 alter_type_cmds:
2480                         alter_type_cmd                                                  { $$ = list_make1($1); }
2481                         | alter_type_cmds ',' alter_type_cmd    { $$ = lappend($1, $3); }
2482                 ;
2483
2484 alter_type_cmd:
2485                         /* ALTER TYPE <name> ADD ATTRIBUTE <coldef> [RESTRICT|CASCADE] */
2486                         ADD_P ATTRIBUTE TableFuncElement opt_drop_behavior
2487                                 {
2488                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2489                                         n->subtype = AT_AddColumn;
2490                                         n->def = $3;
2491                                         n->behavior = $4;
2492                                         $$ = (Node *)n;
2493                                 }
2494                         /* ALTER TYPE <name> DROP ATTRIBUTE IF EXISTS <attname> [RESTRICT|CASCADE] */
2495                         | DROP ATTRIBUTE IF_P EXISTS ColId opt_drop_behavior
2496                                 {
2497                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2498                                         n->subtype = AT_DropColumn;
2499                                         n->name = $5;
2500                                         n->behavior = $6;
2501                                         n->missing_ok = TRUE;
2502                                         $$ = (Node *)n;
2503                                 }
2504                         /* ALTER TYPE <name> DROP ATTRIBUTE <attname> [RESTRICT|CASCADE] */
2505                         | DROP ATTRIBUTE ColId opt_drop_behavior
2506                                 {
2507                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2508                                         n->subtype = AT_DropColumn;
2509                                         n->name = $3;
2510                                         n->behavior = $4;
2511                                         n->missing_ok = FALSE;
2512                                         $$ = (Node *)n;
2513                                 }
2514                         /* ALTER TYPE <name> ALTER ATTRIBUTE <attname> [SET DATA] TYPE <typename> [RESTRICT|CASCADE] */
2515                         | ALTER ATTRIBUTE ColId opt_set_data TYPE_P Typename opt_collate_clause opt_drop_behavior
2516                                 {
2517                                         AlterTableCmd *n = makeNode(AlterTableCmd);
2518                                         ColumnDef *def = makeNode(ColumnDef);
2519                                         n->subtype = AT_AlterColumnType;
2520                                         n->name = $3;
2521                                         n->def = (Node *) def;
2522                                         n->behavior = $8;
2523                                         /* We only use these fields of the ColumnDef node */
2524                                         def->typeName = $6;
2525                                         def->collClause = (CollateClause *) $7;
2526                                         def->raw_default = NULL;
2527                                         def->location = @3;
2528                                         $$ = (Node *)n;
2529                                 }
2530                 ;
2531
2532
2533 /*****************************************************************************
2534  *
2535  *              QUERY :
2536  *                              close <portalname>
2537  *
2538  *****************************************************************************/
2539
2540 ClosePortalStmt:
2541                         CLOSE cursor_name
2542                                 {
2543                                         ClosePortalStmt *n = makeNode(ClosePortalStmt);
2544                                         n->portalname = $2;
2545                                         $$ = (Node *)n;
2546                                 }
2547                         | CLOSE ALL
2548                                 {
2549                                         ClosePortalStmt *n = makeNode(ClosePortalStmt);
2550                                         n->portalname = NULL;
2551                                         $$ = (Node *)n;
2552                                 }
2553                 ;
2554
2555
2556 /*****************************************************************************
2557  *
2558  *              QUERY :
2559  *                              COPY relname [(columnList)] FROM/TO file [WITH] [(options)]
2560  *                              COPY ( SELECT ... ) TO file     [WITH] [(options)]
2561  *
2562  *                              where 'file' can be one of:
2563  *                              { PROGRAM 'command' | STDIN | STDOUT | 'filename' }
2564  *
2565  *                              In the preferred syntax the options are comma-separated
2566  *                              and use generic identifiers instead of keywords.  The pre-9.0
2567  *                              syntax had a hard-wired, space-separated set of options.
2568  *
2569  *                              Really old syntax, from versions 7.2 and prior:
2570  *                              COPY [ BINARY ] table [ WITH OIDS ] FROM/TO file
2571  *                                      [ [ USING ] DELIMITERS 'delimiter' ] ]
2572  *                                      [ WITH NULL AS 'null string' ]
2573  *                              This option placement is not supported with COPY (SELECT...).
2574  *
2575  *****************************************************************************/
2576
2577 CopyStmt:       COPY opt_binary qualified_name opt_column_list opt_oids
2578                         copy_from opt_program copy_file_name copy_delimiter opt_with copy_options
2579                                 {
2580                                         CopyStmt *n = makeNode(CopyStmt);
2581                                         n->relation = $3;
2582                                         n->query = NULL;
2583                                         n->attlist = $4;
2584                                         n->is_from = $6;
2585                                         n->is_program = $7;
2586                                         n->filename = $8;
2587
2588                                         if (n->is_program && n->filename == NULL)
2589                                                 ereport(ERROR,
2590                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2591                                                                  errmsg("STDIN/STDOUT not allowed with PROGRAM"),
2592                                                                  parser_errposition(@8)));
2593
2594                                         n->options = NIL;
2595                                         /* Concatenate user-supplied flags */
2596                                         if ($2)
2597                                                 n->options = lappend(n->options, $2);
2598                                         if ($5)
2599                                                 n->options = lappend(n->options, $5);
2600                                         if ($9)
2601                                                 n->options = lappend(n->options, $9);
2602                                         if ($11)
2603                                                 n->options = list_concat(n->options, $11);
2604                                         $$ = (Node *)n;
2605                                 }
2606                         | COPY select_with_parens TO opt_program copy_file_name opt_with copy_options
2607                                 {
2608                                         CopyStmt *n = makeNode(CopyStmt);
2609                                         n->relation = NULL;
2610                                         n->query = $2;
2611                                         n->attlist = NIL;
2612                                         n->is_from = false;
2613                                         n->is_program = $4;
2614                                         n->filename = $5;
2615                                         n->options = $7;
2616
2617                                         if (n->is_program && n->filename == NULL)
2618                                                 ereport(ERROR,
2619                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2620                                                                  errmsg("STDIN/STDOUT not allowed with PROGRAM"),
2621                                                                  parser_errposition(@5)));
2622
2623                                         $$ = (Node *)n;
2624                                 }
2625                 ;
2626
2627 copy_from:
2628                         FROM                                                                    { $$ = TRUE; }
2629                         | TO                                                                    { $$ = FALSE; }
2630                 ;
2631
2632 opt_program:
2633                         PROGRAM                                                                 { $$ = TRUE; }
2634                         | /* EMPTY */                                                   { $$ = FALSE; }
2635                 ;
2636
2637 /*
2638  * copy_file_name NULL indicates stdio is used. Whether stdin or stdout is
2639  * used depends on the direction. (It really doesn't make sense to copy from
2640  * stdout. We silently correct the "typo".)              - AY 9/94
2641  */
2642 copy_file_name:
2643                         Sconst                                                                  { $$ = $1; }
2644                         | STDIN                                                                 { $$ = NULL; }
2645                         | STDOUT                                                                { $$ = NULL; }
2646                 ;
2647
2648 copy_options: copy_opt_list                                                     { $$ = $1; }
2649                         | '(' copy_generic_opt_list ')'                 { $$ = $2; }
2650                 ;
2651
2652 /* old COPY option syntax */
2653 copy_opt_list:
2654                         copy_opt_list copy_opt_item                             { $$ = lappend($1, $2); }
2655                         | /* EMPTY */                                                   { $$ = NIL; }
2656                 ;
2657
2658 copy_opt_item:
2659                         BINARY
2660                                 {
2661                                         $$ = makeDefElem("format", (Node *)makeString("binary"));
2662                                 }
2663                         | OIDS
2664                                 {
2665                                         $$ = makeDefElem("oids", (Node *)makeInteger(TRUE));
2666                                 }
2667                         | FREEZE
2668                                 {
2669                                         $$ = makeDefElem("freeze", (Node *)makeInteger(TRUE));
2670                                 }
2671                         | DELIMITER opt_as Sconst
2672                                 {
2673                                         $$ = makeDefElem("delimiter", (Node *)makeString($3));
2674                                 }
2675                         | NULL_P opt_as Sconst
2676                                 {
2677                                         $$ = makeDefElem("null", (Node *)makeString($3));
2678                                 }
2679                         | CSV
2680                                 {
2681                                         $$ = makeDefElem("format", (Node *)makeString("csv"));
2682                                 }
2683                         | HEADER_P
2684                                 {
2685                                         $$ = makeDefElem("header", (Node *)makeInteger(TRUE));
2686                                 }
2687                         | QUOTE opt_as Sconst
2688                                 {
2689                                         $$ = makeDefElem("quote", (Node *)makeString($3));
2690                                 }
2691                         | ESCAPE opt_as Sconst
2692                                 {
2693                                         $$ = makeDefElem("escape", (Node *)makeString($3));
2694                                 }
2695                         | FORCE QUOTE columnList
2696                                 {
2697                                         $$ = makeDefElem("force_quote", (Node *)$3);
2698                                 }
2699                         | FORCE QUOTE '*'
2700                                 {
2701                                         $$ = makeDefElem("force_quote", (Node *)makeNode(A_Star));
2702                                 }
2703                         | FORCE NOT NULL_P columnList
2704                                 {
2705                                         $$ = makeDefElem("force_not_null", (Node *)$4);
2706                                 }
2707                         | FORCE NULL_P columnList
2708                                 {
2709                                         $$ = makeDefElem("force_null", (Node *)$3);
2710                                 }
2711                         | ENCODING Sconst
2712                                 {
2713                                         $$ = makeDefElem("encoding", (Node *)makeString($2));
2714                                 }
2715                 ;
2716
2717 /* The following exist for backward compatibility with very old versions */
2718
2719 opt_binary:
2720                         BINARY
2721                                 {
2722                                         $$ = makeDefElem("format", (Node *)makeString("binary"));
2723                                 }
2724                         | /*EMPTY*/                                                             { $$ = NULL; }
2725                 ;
2726
2727 opt_oids:
2728                         WITH OIDS
2729                                 {
2730                                         $$ = makeDefElem("oids", (Node *)makeInteger(TRUE));
2731                                 }
2732                         | /*EMPTY*/                                                             { $$ = NULL; }
2733                 ;
2734
2735 copy_delimiter:
2736                         opt_using DELIMITERS Sconst
2737                                 {
2738                                         $$ = makeDefElem("delimiter", (Node *)makeString($3));
2739                                 }
2740                         | /*EMPTY*/                                                             { $$ = NULL; }
2741                 ;
2742
2743 opt_using:
2744                         USING                                                                   {}
2745                         | /*EMPTY*/                                                             {}
2746                 ;
2747
2748 /* new COPY option syntax */
2749 copy_generic_opt_list:
2750                         copy_generic_opt_elem
2751                                 {
2752                                         $$ = list_make1($1);
2753                                 }
2754                         | copy_generic_opt_list ',' copy_generic_opt_elem
2755                                 {
2756                                         $$ = lappend($1, $3);
2757                                 }
2758                 ;
2759
2760 copy_generic_opt_elem:
2761                         ColLabel copy_generic_opt_arg
2762                                 {
2763                                         $$ = makeDefElem($1, $2);
2764                                 }
2765                 ;
2766
2767 copy_generic_opt_arg:
2768                         opt_boolean_or_string                   { $$ = (Node *) makeString($1); }
2769                         | NumericOnly                                   { $$ = (Node *) $1; }
2770                         | '*'                                                   { $$ = (Node *) makeNode(A_Star); }
2771                         | '(' copy_generic_opt_arg_list ')'             { $$ = (Node *) $2; }
2772                         | /* EMPTY */                                   { $$ = NULL; }
2773                 ;
2774
2775 copy_generic_opt_arg_list:
2776                           copy_generic_opt_arg_list_item
2777                                 {
2778                                         $$ = list_make1($1);
2779                                 }
2780                         | copy_generic_opt_arg_list ',' copy_generic_opt_arg_list_item
2781                                 {
2782                                         $$ = lappend($1, $3);
2783                                 }
2784                 ;
2785
2786 /* beware of emitting non-string list elements here; see commands/define.c */
2787 copy_generic_opt_arg_list_item:
2788                         opt_boolean_or_string   { $$ = (Node *) makeString($1); }
2789                 ;
2790
2791
2792 /*****************************************************************************
2793  *
2794  *              QUERY :
2795  *                              CREATE TABLE relname
2796  *
2797  *****************************************************************************/
2798
2799 CreateStmt:     CREATE OptTemp TABLE qualified_name '(' OptTableElementList ')'
2800                         OptInherit OptWith OnCommitOption OptTableSpace
2801                                 {
2802                                         CreateStmt *n = makeNode(CreateStmt);
2803                                         $4->relpersistence = $2;
2804                                         n->relation = $4;
2805                                         n->tableElts = $6;
2806                                         n->inhRelations = $8;
2807                                         n->ofTypename = NULL;
2808                                         n->constraints = NIL;
2809                                         n->options = $9;
2810                                         n->oncommit = $10;
2811                                         n->tablespacename = $11;
2812                                         n->if_not_exists = false;
2813                                         $$ = (Node *)n;
2814                                 }
2815                 | CREATE OptTemp TABLE IF_P NOT EXISTS qualified_name '('
2816                         OptTableElementList ')' OptInherit OptWith OnCommitOption
2817                         OptTableSpace
2818                                 {
2819                                         CreateStmt *n = makeNode(CreateStmt);
2820                                         $7->relpersistence = $2;
2821                                         n->relation = $7;
2822                                         n->tableElts = $9;
2823                                         n->inhRelations = $11;
2824                                         n->ofTypename = NULL;
2825                                         n->constraints = NIL;
2826                                         n->options = $12;
2827                                         n->oncommit = $13;
2828                                         n->tablespacename = $14;
2829                                         n->if_not_exists = true;
2830                                         $$ = (Node *)n;
2831                                 }
2832                 | CREATE OptTemp TABLE qualified_name OF any_name
2833                         OptTypedTableElementList OptWith OnCommitOption OptTableSpace
2834                                 {
2835                                         CreateStmt *n = makeNode(CreateStmt);
2836                                         $4->relpersistence = $2;
2837                                         n->relation = $4;
2838                                         n->tableElts = $7;
2839                                         n->inhRelations = NIL;
2840                                         n->ofTypename = makeTypeNameFromNameList($6);
2841                                         n->ofTypename->location = @6;
2842                                         n->constraints = NIL;
2843                                         n->options = $8;
2844                                         n->oncommit = $9;
2845                                         n->tablespacename = $10;
2846                                         n->if_not_exists = false;
2847                                         $$ = (Node *)n;
2848                                 }
2849                 | CREATE OptTemp TABLE IF_P NOT EXISTS qualified_name OF any_name
2850                         OptTypedTableElementList OptWith OnCommitOption OptTableSpace
2851                                 {
2852                                         CreateStmt *n = makeNode(CreateStmt);
2853                                         $7->relpersistence = $2;
2854                                         n->relation = $7;
2855                                         n->tableElts = $10;
2856                                         n->inhRelations = NIL;
2857                                         n->ofTypename = makeTypeNameFromNameList($9);
2858                                         n->ofTypename->location = @9;
2859                                         n->constraints = NIL;
2860                                         n->options = $11;
2861                                         n->oncommit = $12;
2862                                         n->tablespacename = $13;
2863                                         n->if_not_exists = true;
2864                                         $$ = (Node *)n;
2865                                 }
2866                 ;
2867
2868 /*
2869  * Redundancy here is needed to avoid shift/reduce conflicts,
2870  * since TEMP is not a reserved word.  See also OptTempTableName.
2871  *
2872  * NOTE: we accept both GLOBAL and LOCAL options.  They currently do nothing,
2873  * but future versions might consider GLOBAL to request SQL-spec-compliant
2874  * temp table behavior, so warn about that.  Since we have no modules the
2875  * LOCAL keyword is really meaningless; furthermore, some other products
2876  * implement LOCAL as meaning the same as our default temp table behavior,
2877  * so we'll probably continue to treat LOCAL as a noise word.
2878  */
2879 OptTemp:        TEMPORARY                                       { $$ = RELPERSISTENCE_TEMP; }
2880                         | TEMP                                          { $$ = RELPERSISTENCE_TEMP; }
2881                         | LOCAL TEMPORARY                       { $$ = RELPERSISTENCE_TEMP; }
2882                         | LOCAL TEMP                            { $$ = RELPERSISTENCE_TEMP; }
2883                         | GLOBAL TEMPORARY
2884                                 {
2885                                         ereport(WARNING,
2886                                                         (errmsg("GLOBAL is deprecated in temporary table creation"),
2887                                                          parser_errposition(@1)));
2888                                         $$ = RELPERSISTENCE_TEMP;
2889                                 }
2890                         | GLOBAL TEMP
2891                                 {
2892                                         ereport(WARNING,
2893                                                         (errmsg("GLOBAL is deprecated in temporary table creation"),
2894                                                          parser_errposition(@1)));
2895                                         $$ = RELPERSISTENCE_TEMP;
2896                                 }
2897                         | UNLOGGED                                      { $$ = RELPERSISTENCE_UNLOGGED; }
2898                         | /*EMPTY*/                                     { $$ = RELPERSISTENCE_PERMANENT; }
2899                 ;
2900
2901 OptTableElementList:
2902                         TableElementList                                        { $$ = $1; }
2903                         | /*EMPTY*/                                                     { $$ = NIL; }
2904                 ;
2905
2906 OptTypedTableElementList:
2907                         '(' TypedTableElementList ')'           { $$ = $2; }
2908                         | /*EMPTY*/                                                     { $$ = NIL; }
2909                 ;
2910
2911 TableElementList:
2912                         TableElement
2913                                 {
2914                                         $$ = list_make1($1);
2915                                 }
2916                         | TableElementList ',' TableElement
2917                                 {
2918                                         $$ = lappend($1, $3);
2919                                 }
2920                 ;
2921
2922 TypedTableElementList:
2923                         TypedTableElement
2924                                 {
2925                                         $$ = list_make1($1);
2926                                 }
2927                         | TypedTableElementList ',' TypedTableElement
2928                                 {
2929                                         $$ = lappend($1, $3);
2930                                 }
2931                 ;
2932
2933 TableElement:
2934                         columnDef                                                       { $$ = $1; }
2935                         | TableLikeClause                                       { $$ = $1; }
2936                         | TableConstraint                                       { $$ = $1; }
2937                 ;
2938
2939 TypedTableElement:
2940                         columnOptions                                           { $$ = $1; }
2941                         | TableConstraint                                       { $$ = $1; }
2942                 ;
2943
2944 columnDef:      ColId Typename create_generic_options ColQualList
2945                                 {
2946                                         ColumnDef *n = makeNode(ColumnDef);
2947                                         n->colname = $1;
2948                                         n->typeName = $2;
2949                                         n->inhcount = 0;
2950                                         n->is_local = true;
2951                                         n->is_not_null = false;
2952                                         n->is_from_type = false;
2953                                         n->storage = 0;
2954                                         n->raw_default = NULL;
2955                                         n->cooked_default = NULL;
2956                                         n->collOid = InvalidOid;
2957                                         n->fdwoptions = $3;
2958                                         SplitColQualList($4, &n->constraints, &n->collClause,
2959                                                                          yyscanner);
2960                                         n->location = @1;
2961                                         $$ = (Node *)n;
2962                                 }
2963                 ;
2964
2965 columnOptions:  ColId WITH OPTIONS ColQualList
2966                                 {
2967                                         ColumnDef *n = makeNode(ColumnDef);
2968                                         n->colname = $1;
2969                                         n->typeName = NULL;
2970                                         n->inhcount = 0;
2971                                         n->is_local = true;
2972                                         n->is_not_null = false;
2973                                         n->is_from_type = false;
2974                                         n->storage = 0;
2975                                         n->raw_default = NULL;
2976                                         n->cooked_default = NULL;
2977                                         n->collOid = InvalidOid;
2978                                         SplitColQualList($4, &n->constraints, &n->collClause,
2979                                                                          yyscanner);
2980                                         n->location = @1;
2981                                         $$ = (Node *)n;
2982                                 }
2983                 ;
2984
2985 ColQualList:
2986                         ColQualList ColConstraint                               { $$ = lappend($1, $2); }
2987                         | /*EMPTY*/                                                             { $$ = NIL; }
2988                 ;
2989
2990 ColConstraint:
2991                         CONSTRAINT name ColConstraintElem
2992                                 {
2993                                         Constraint *n = (Constraint *) $3;
2994                                         Assert(IsA(n, Constraint));
2995                                         n->conname = $2;
2996                                         n->location = @1;
2997                                         $$ = (Node *) n;
2998                                 }
2999                         | ColConstraintElem                                             { $$ = $1; }
3000                         | ConstraintAttr                                                { $$ = $1; }
3001                         | COLLATE any_name
3002                                 {
3003                                         /*
3004                                          * Note: the CollateClause is momentarily included in
3005                                          * the list built by ColQualList, but we split it out
3006                                          * again in SplitColQualList.
3007                                          */
3008                                         CollateClause *n = makeNode(CollateClause);
3009                                         n->arg = NULL;
3010                                         n->collname = $2;
3011                                         n->location = @1;
3012                                         $$ = (Node *) n;
3013                                 }
3014                 ;
3015
3016 /* DEFAULT NULL is already the default for Postgres.
3017  * But define it here and carry it forward into the system
3018  * to make it explicit.
3019  * - thomas 1998-09-13
3020  *
3021  * WITH NULL and NULL are not SQL-standard syntax elements,
3022  * so leave them out. Use DEFAULT NULL to explicitly indicate
3023  * that a column may have that value. WITH NULL leads to
3024  * shift/reduce conflicts with WITH TIME ZONE anyway.
3025  * - thomas 1999-01-08
3026  *
3027  * DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
3028  * conflict on NOT (since NOT might start a subsequent NOT NULL constraint,
3029  * or be part of a_expr NOT LIKE or similar constructs).
3030  */
3031 ColConstraintElem:
3032                         NOT NULL_P
3033                                 {
3034                                         Constraint *n = makeNode(Constraint);
3035                                         n->contype = CONSTR_NOTNULL;
3036                                         n->location = @1;
3037                                         $$ = (Node *)n;
3038                                 }
3039                         | NULL_P
3040                                 {
3041                                         Constraint *n = makeNode(Constraint);
3042                                         n->contype = CONSTR_NULL;
3043                                         n->location = @1;
3044                                         $$ = (Node *)n;
3045                                 }
3046                         | UNIQUE opt_definition OptConsTableSpace
3047                                 {
3048                                         Constraint *n = makeNode(Constraint);
3049                                         n->contype = CONSTR_UNIQUE;
3050                                         n->location = @1;
3051                                         n->keys = NULL;
3052                                         n->options = $2;
3053                                         n->indexname = NULL;
3054                                         n->indexspace = $3;
3055                                         $$ = (Node *)n;
3056                                 }
3057                         | PRIMARY KEY opt_definition OptConsTableSpace
3058                                 {
3059                                         Constraint *n = makeNode(Constraint);
3060                                         n->contype = CONSTR_PRIMARY;
3061                                         n->location = @1;
3062                                         n->keys = NULL;
3063                                         n->options = $3;
3064                                         n->indexname = NULL;
3065                                         n->indexspace = $4;
3066                                         $$ = (Node *)n;
3067                                 }
3068                         | CHECK '(' a_expr ')' opt_no_inherit
3069                                 {
3070                                         Constraint *n = makeNode(Constraint);
3071                                         n->contype = CONSTR_CHECK;
3072                                         n->location = @1;
3073                                         n->is_no_inherit = $5;
3074                                         n->raw_expr = $3;
3075                                         n->cooked_expr = NULL;
3076                                         $$ = (Node *)n;
3077                                 }
3078                         | DEFAULT b_expr
3079                                 {
3080                                         Constraint *n = makeNode(Constraint);
3081                                         n->contype = CONSTR_DEFAULT;
3082                                         n->location = @1;
3083                                         n->raw_expr = $2;
3084                                         n->cooked_expr = NULL;
3085                                         $$ = (Node *)n;
3086                                 }
3087                         | REFERENCES qualified_name opt_column_list key_match key_actions
3088                                 {
3089                                         Constraint *n = makeNode(Constraint);
3090                                         n->contype = CONSTR_FOREIGN;
3091                                         n->location = @1;
3092                                         n->pktable                      = $2;
3093                                         n->fk_attrs                     = NIL;
3094                                         n->pk_attrs                     = $3;
3095                                         n->fk_matchtype         = $4;
3096                                         n->fk_upd_action        = (char) ($5 >> 8);
3097                                         n->fk_del_action        = (char) ($5 & 0xFF);
3098                                         n->skip_validation  = false;
3099                                         n->initially_valid  = true;
3100                                         $$ = (Node *)n;
3101                                 }
3102                 ;
3103
3104 /*
3105  * ConstraintAttr represents constraint attributes, which we parse as if
3106  * they were independent constraint clauses, in order to avoid shift/reduce
3107  * conflicts (since NOT might start either an independent NOT NULL clause
3108  * or an attribute).  parse_utilcmd.c is responsible for attaching the
3109  * attribute information to the preceding "real" constraint node, and for
3110  * complaining if attribute clauses appear in the wrong place or wrong
3111  * combinations.
3112  *
3113  * See also ConstraintAttributeSpec, which can be used in places where
3114  * there is no parsing conflict.  (Note: currently, NOT VALID and NO INHERIT
3115  * are allowed clauses in ConstraintAttributeSpec, but not here.  Someday we
3116  * might need to allow them here too, but for the moment it doesn't seem
3117  * useful in the statements that use ConstraintAttr.)
3118  */
3119 ConstraintAttr:
3120                         DEFERRABLE
3121                                 {
3122                                         Constraint *n = makeNode(Constraint);
3123                                         n->contype = CONSTR_ATTR_DEFERRABLE;
3124                                         n->location = @1;
3125                                         $$ = (Node *)n;
3126                                 }
3127                         | NOT DEFERRABLE
3128                                 {
3129                                         Constraint *n = makeNode(Constraint);
3130                                         n->contype = CONSTR_ATTR_NOT_DEFERRABLE;
3131                                         n->location = @1;
3132                                         $$ = (Node *)n;
3133                                 }
3134                         | INITIALLY DEFERRED
3135                                 {
3136                                         Constraint *n = makeNode(Constraint);
3137                                         n->contype = CONSTR_ATTR_DEFERRED;
3138                                         n->location = @1;
3139                                         $$ = (Node *)n;
3140                                 }
3141                         | INITIALLY IMMEDIATE
3142                                 {
3143                                         Constraint *n = makeNode(Constraint);
3144                                         n->contype = CONSTR_ATTR_IMMEDIATE;
3145                                         n->location = @1;
3146                                         $$ = (Node *)n;
3147                                 }
3148                 ;
3149
3150
3151 TableLikeClause:
3152                         LIKE qualified_name TableLikeOptionList
3153                                 {
3154                                         TableLikeClause *n = makeNode(TableLikeClause);
3155                                         n->relation = $2;
3156                                         n->options = $3;
3157                                         $$ = (Node *)n;
3158                                 }
3159                 ;
3160
3161 TableLikeOptionList:
3162                                 TableLikeOptionList INCLUDING TableLikeOption   { $$ = $1 | $3; }
3163                                 | TableLikeOptionList EXCLUDING TableLikeOption { $$ = $1 & ~$3; }
3164                                 | /* EMPTY */                                           { $$ = 0; }
3165                 ;
3166
3167 TableLikeOption:
3168                                 DEFAULTS                        { $$ = CREATE_TABLE_LIKE_DEFAULTS; }
3169                                 | CONSTRAINTS           { $$ = CREATE_TABLE_LIKE_CONSTRAINTS; }
3170                                 | INDEXES                       { $$ = CREATE_TABLE_LIKE_INDEXES; }
3171                                 | STORAGE                       { $$ = CREATE_TABLE_LIKE_STORAGE; }
3172                                 | COMMENTS                      { $$ = CREATE_TABLE_LIKE_COMMENTS; }
3173                                 | ALL                           { $$ = CREATE_TABLE_LIKE_ALL; }
3174                 ;
3175
3176
3177 /* ConstraintElem specifies constraint syntax which is not embedded into
3178  *      a column definition. ColConstraintElem specifies the embedded form.
3179  * - thomas 1997-12-03
3180  */
3181 TableConstraint:
3182                         CONSTRAINT name ConstraintElem
3183                                 {
3184                                         Constraint *n = (Constraint *) $3;
3185                                         Assert(IsA(n, Constraint));
3186                                         n->conname = $2;
3187                                         n->location = @1;
3188                                         $$ = (Node *) n;
3189                                 }
3190                         | ConstraintElem                                                { $$ = $1; }
3191                 ;
3192
3193 ConstraintElem:
3194                         CHECK '(' a_expr ')' ConstraintAttributeSpec
3195                                 {
3196                                         Constraint *n = makeNode(Constraint);
3197                                         n->contype = CONSTR_CHECK;
3198                                         n->location = @1;
3199                                         n->raw_expr = $3;
3200                                         n->cooked_expr = NULL;
3201                                         processCASbits($5, @5, "CHECK",
3202                                                                    NULL, NULL, &n->skip_validation,
3203                                                                    &n->is_no_inherit, yyscanner);
3204                                         n->initially_valid = !n->skip_validation;
3205                                         $$ = (Node *)n;
3206                                 }
3207                         | UNIQUE '(' columnList ')' opt_definition OptConsTableSpace
3208                                 ConstraintAttributeSpec
3209                                 {
3210                                         Constraint *n = makeNode(Constraint);
3211                                         n->contype = CONSTR_UNIQUE;
3212                                         n->location = @1;
3213                                         n->keys = $3;
3214                                         n->options = $5;
3215                                         n->indexname = NULL;
3216                                         n->indexspace = $6;
3217                                         processCASbits($7, @7, "UNIQUE",
3218                                                                    &n->deferrable, &n->initdeferred, NULL,
3219                                                                    NULL, yyscanner);
3220                                         $$ = (Node *)n;
3221                                 }
3222                         | UNIQUE ExistingIndex ConstraintAttributeSpec
3223                                 {
3224                                         Constraint *n = makeNode(Constraint);
3225                                         n->contype = CONSTR_UNIQUE;
3226                                         n->location = @1;
3227                                         n->keys = NIL;
3228                                         n->options = NIL;
3229                                         n->indexname = $2;
3230                                         n->indexspace = NULL;
3231                                         processCASbits($3, @3, "UNIQUE",
3232                                                                    &n->deferrable, &n->initdeferred, NULL,
3233                                                                    NULL, yyscanner);
3234                                         $$ = (Node *)n;
3235                                 }
3236                         | PRIMARY KEY '(' columnList ')' opt_definition OptConsTableSpace
3237                                 ConstraintAttributeSpec
3238                                 {
3239                                         Constraint *n = makeNode(Constraint);
3240                                         n->contype = CONSTR_PRIMARY;
3241                                         n->location = @1;
3242                                         n->keys = $4;
3243                                         n->options = $6;
3244                                         n->indexname = NULL;
3245                                         n->indexspace = $7;
3246                                         processCASbits($8, @8, "PRIMARY KEY",
3247                                                                    &n->deferrable, &n->initdeferred, NULL,
3248                                                                    NULL, yyscanner);
3249                                         $$ = (Node *)n;
3250                                 }
3251                         | PRIMARY KEY ExistingIndex ConstraintAttributeSpec
3252                                 {
3253                                         Constraint *n = makeNode(Constraint);
3254                                         n->contype = CONSTR_PRIMARY;
3255                                         n->location = @1;
3256                                         n->keys = NIL;
3257                                         n->options = NIL;
3258                                         n->indexname = $3;
3259                                         n->indexspace = NULL;
3260                                         processCASbits($4, @4, "PRIMARY KEY",
3261                                                                    &n->deferrable, &n->initdeferred, NULL,
3262                                                                    NULL, yyscanner);
3263                                         $$ = (Node *)n;
3264                                 }
3265                         | EXCLUDE access_method_clause '(' ExclusionConstraintList ')'
3266                                 opt_definition OptConsTableSpace ExclusionWhereClause
3267                                 ConstraintAttributeSpec
3268                                 {
3269                                         Constraint *n = makeNode(Constraint);
3270                                         n->contype = CONSTR_EXCLUSION;
3271                                         n->location = @1;
3272                                         n->access_method        = $2;
3273                                         n->exclusions           = $4;
3274                                         n->options                      = $6;
3275                                         n->indexname            = NULL;
3276                                         n->indexspace           = $7;
3277                                         n->where_clause         = $8;
3278                                         processCASbits($9, @9, "EXCLUDE",
3279                                                                    &n->deferrable, &n->initdeferred, NULL,
3280                                                                    NULL, yyscanner);
3281                                         $$ = (Node *)n;
3282                                 }
3283                         | FOREIGN KEY '(' columnList ')' REFERENCES qualified_name
3284                                 opt_column_list key_match key_actions ConstraintAttributeSpec
3285                                 {
3286                                         Constraint *n = makeNode(Constraint);
3287                                         n->contype = CONSTR_FOREIGN;
3288                                         n->location = @1;
3289                                         n->pktable                      = $7;
3290                                         n->fk_attrs                     = $4;
3291                                         n->pk_attrs                     = $8;
3292                                         n->fk_matchtype         = $9;
3293                                         n->fk_upd_action        = (char) ($10 >> 8);
3294                                         n->fk_del_action        = (char) ($10 & 0xFF);
3295                                         processCASbits($11, @11, "FOREIGN KEY",
3296                                                                    &n->deferrable, &n->initdeferred,
3297                                                                    &n->skip_validation, NULL,
3298                                                                    yyscanner);
3299                                         n->initially_valid = !n->skip_validation;
3300                                         $$ = (Node *)n;
3301                                 }
3302                 ;
3303
3304 opt_no_inherit: NO INHERIT                                                      {  $$ = TRUE; }
3305                         | /* EMPTY */                                                   {  $$ = FALSE; }
3306                 ;
3307
3308 opt_column_list:
3309                         '(' columnList ')'                                              { $$ = $2; }
3310                         | /*EMPTY*/                                                             { $$ = NIL; }
3311                 ;
3312
3313 columnList:
3314                         columnElem                                                              { $$ = list_make1($1); }
3315                         | columnList ',' columnElem                             { $$ = lappend($1, $3); }
3316                 ;
3317
3318 columnElem: ColId
3319                                 {
3320                                         $$ = (Node *) makeString($1);
3321                                 }
3322                 ;
3323
3324 key_match:  MATCH FULL
3325                         {
3326                                 $$ = FKCONSTR_MATCH_FULL;
3327                         }
3328                 | MATCH PARTIAL
3329                         {
3330                                 ereport(ERROR,
3331                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3332                                                  errmsg("MATCH PARTIAL not yet implemented"),
3333                                                  parser_errposition(@1)));
3334                                 $$ = FKCONSTR_MATCH_PARTIAL;
3335                         }
3336                 | MATCH SIMPLE
3337                         {
3338                                 $$ = FKCONSTR_MATCH_SIMPLE;
3339                         }
3340                 | /*EMPTY*/
3341                         {
3342                                 $$ = FKCONSTR_MATCH_SIMPLE;
3343                         }
3344                 ;
3345
3346 ExclusionConstraintList:
3347                         ExclusionConstraintElem                                 { $$ = list_make1($1); }
3348                         | ExclusionConstraintList ',' ExclusionConstraintElem
3349                                                                                                         { $$ = lappend($1, $3); }
3350                 ;
3351
3352 ExclusionConstraintElem: index_elem WITH any_operator
3353                         {
3354                                 $$ = list_make2($1, $3);
3355                         }
3356                         /* allow OPERATOR() decoration for the benefit of ruleutils.c */
3357                         | index_elem WITH OPERATOR '(' any_operator ')'
3358                         {
3359                                 $$ = list_make2($1, $5);
3360                         }
3361                 ;
3362
3363 ExclusionWhereClause:
3364                         WHERE '(' a_expr ')'                                    { $$ = $3; }
3365                         | /*EMPTY*/                                                             { $$ = NULL; }
3366                 ;
3367
3368 /*
3369  * We combine the update and delete actions into one value temporarily
3370  * for simplicity of parsing, and then break them down again in the
3371  * calling production.  update is in the left 8 bits, delete in the right.
3372  * Note that NOACTION is the default.
3373  */
3374 key_actions:
3375                         key_update
3376                                 { $$ = ($1 << 8) | (FKCONSTR_ACTION_NOACTION & 0xFF); }
3377                         | key_delete
3378                                 { $$ = (FKCONSTR_ACTION_NOACTION << 8) | ($1 & 0xFF); }
3379                         | key_update key_delete
3380                                 { $$ = ($1 << 8) | ($2 & 0xFF); }
3381                         | key_delete key_update
3382                                 { $$ = ($2 << 8) | ($1 & 0xFF); }
3383                         | /*EMPTY*/
3384                                 { $$ = (FKCONSTR_ACTION_NOACTION << 8) | (FKCONSTR_ACTION_NOACTION & 0xFF); }
3385                 ;
3386
3387 key_update: ON UPDATE key_action                { $$ = $3; }
3388                 ;
3389
3390 key_delete: ON DELETE_P key_action              { $$ = $3; }
3391                 ;
3392
3393 key_action:
3394                         NO ACTION                                       { $$ = FKCONSTR_ACTION_NOACTION; }
3395                         | RESTRICT                                      { $$ = FKCONSTR_ACTION_RESTRICT; }
3396                         | CASCADE                                       { $$ = FKCONSTR_ACTION_CASCADE; }
3397                         | SET NULL_P                            { $$ = FKCONSTR_ACTION_SETNULL; }
3398                         | SET DEFAULT                           { $$ = FKCONSTR_ACTION_SETDEFAULT; }
3399                 ;
3400
3401 OptInherit: INHERITS '(' qualified_name_list ')'        { $$ = $3; }
3402                         | /*EMPTY*/                                                             { $$ = NIL; }
3403                 ;
3404
3405 /* WITH (options) is preferred, WITH OIDS and WITHOUT OIDS are legacy forms */
3406 OptWith:
3407                         WITH reloptions                         { $$ = $2; }
3408                         | WITH OIDS                                     { $$ = list_make1(defWithOids(true)); }
3409                         | WITHOUT OIDS                          { $$ = list_make1(defWithOids(false)); }
3410                         | /*EMPTY*/                                     { $$ = NIL; }
3411                 ;
3412
3413 OnCommitOption:  ON COMMIT DROP                         { $$ = ONCOMMIT_DROP; }
3414                         | ON COMMIT DELETE_P ROWS               { $$ = ONCOMMIT_DELETE_ROWS; }
3415                         | ON COMMIT PRESERVE ROWS               { $$ = ONCOMMIT_PRESERVE_ROWS; }
3416                         | /*EMPTY*/                                             { $$ = ONCOMMIT_NOOP; }
3417                 ;
3418
3419 OptTableSpace:   TABLESPACE name                                        { $$ = $2; }
3420                         | /*EMPTY*/                                                             { $$ = NULL; }
3421                 ;
3422
3423 OptConsTableSpace:   USING INDEX TABLESPACE name        { $$ = $4; }
3424                         | /*EMPTY*/                                                             { $$ = NULL; }
3425                 ;
3426
3427 ExistingIndex:   USING INDEX index_name                         { $$ = $3; }
3428                 ;
3429
3430
3431 /*****************************************************************************
3432  *
3433  *              QUERY :
3434  *                              CREATE TABLE relname AS SelectStmt [ WITH [NO] DATA ]
3435  *
3436  *
3437  * Note: SELECT ... INTO is a now-deprecated alternative for this.
3438  *
3439  *****************************************************************************/
3440
3441 CreateAsStmt:
3442                 CREATE OptTemp TABLE create_as_target AS SelectStmt opt_with_data
3443                                 {
3444                                         CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
3445                                         ctas->query = $6;
3446                                         ctas->into = $4;
3447                                         ctas->relkind = OBJECT_TABLE;
3448                                         ctas->is_select_into = false;
3449                                         ctas->if_not_exists = false;
3450                                         /* cram additional flags into the IntoClause */
3451                                         $4->rel->relpersistence = $2;
3452                                         $4->skipData = !($7);
3453                                         $$ = (Node *) ctas;
3454                                 }
3455                 | CREATE OptTemp TABLE IF_P NOT EXISTS create_as_target AS SelectStmt opt_with_data
3456                                 {
3457                                         CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
3458                                         ctas->query = $9;
3459                                         ctas->into = $7;
3460                                         ctas->relkind = OBJECT_TABLE;
3461                                         ctas->is_select_into = false;
3462                                         ctas->if_not_exists = true;
3463                                         /* cram additional flags into the IntoClause */
3464                                         $7->rel->relpersistence = $2;
3465                                         $7->skipData = !($10);
3466                                         $$ = (Node *) ctas;
3467                                 }
3468                 ;
3469
3470 create_as_target:
3471                         qualified_name opt_column_list OptWith OnCommitOption OptTableSpace
3472                                 {
3473                                         $$ = makeNode(IntoClause);
3474                                         $$->rel = $1;
3475                                         $$->colNames = $2;
3476                                         $$->options = $3;
3477                                         $$->onCommit = $4;
3478                                         $$->tableSpaceName = $5;
3479                                         $$->viewQuery = NULL;
3480                                         $$->skipData = false;           /* might get changed later */
3481                                 }
3482                 ;
3483
3484 opt_with_data:
3485                         WITH DATA_P                                                             { $$ = TRUE; }
3486                         | WITH NO DATA_P                                                { $$ = FALSE; }
3487                         | /*EMPTY*/                                                             { $$ = TRUE; }
3488                 ;
3489
3490
3491 /*****************************************************************************
3492  *
3493  *              QUERY :
3494  *                              CREATE MATERIALIZED VIEW relname AS SelectStmt
3495  *
3496  *****************************************************************************/
3497
3498 CreateMatViewStmt:
3499                 CREATE OptNoLog MATERIALIZED VIEW create_mv_target AS SelectStmt opt_with_data
3500                                 {
3501                                         CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
3502                                         ctas->query = $7;
3503                                         ctas->into = $5;
3504                                         ctas->relkind = OBJECT_MATVIEW;
3505                                         ctas->is_select_into = false;
3506                                         ctas->if_not_exists = false;
3507                                         /* cram additional flags into the IntoClause */
3508                                         $5->rel->relpersistence = $2;
3509                                         $5->skipData = !($8);
3510                                         $$ = (Node *) ctas;
3511                                 }
3512                 | CREATE OptNoLog MATERIALIZED VIEW IF_P NOT EXISTS create_mv_target AS SelectStmt opt_with_data
3513                                 {
3514                                         CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
3515                                         ctas->query = $10;
3516                                         ctas->into = $8;
3517                                         ctas->relkind = OBJECT_MATVIEW;
3518                                         ctas->is_select_into = false;
3519                                         ctas->if_not_exists = true;
3520                                         /* cram additional flags into the IntoClause */
3521                                         $8->rel->relpersistence = $2;
3522                                         $8->skipData = !($11);
3523                                         $$ = (Node *) ctas;
3524                                 }
3525                 ;
3526
3527 create_mv_target:
3528                         qualified_name opt_column_list opt_reloptions OptTableSpace
3529                                 {
3530                                         $$ = makeNode(IntoClause);
3531                                         $$->rel = $1;
3532                                         $$->colNames = $2;
3533                                         $$->options = $3;
3534                                         $$->onCommit = ONCOMMIT_NOOP;
3535                                         $$->tableSpaceName = $4;
3536                                         $$->viewQuery = NULL;           /* filled at analysis time */
3537                                         $$->skipData = false;           /* might get changed later */
3538                                 }
3539                 ;
3540
3541 OptNoLog:       UNLOGGED                                        { $$ = RELPERSISTENCE_UNLOGGED; }
3542                         | /*EMPTY*/                                     { $$ = RELPERSISTENCE_PERMANENT; }
3543                 ;
3544
3545
3546 /*****************************************************************************
3547  *
3548  *              QUERY :
3549  *                              REFRESH MATERIALIZED VIEW qualified_name
3550  *
3551  *****************************************************************************/
3552
3553 RefreshMatViewStmt:
3554                         REFRESH MATERIALIZED VIEW opt_concurrently qualified_name opt_with_data
3555                                 {
3556                                         RefreshMatViewStmt *n = makeNode(RefreshMatViewStmt);
3557                                         n->concurrent = $4;
3558                                         n->relation = $5;
3559                                         n->skipData = !($6);
3560                                         $$ = (Node *) n;
3561                                 }
3562                 ;
3563
3564
3565 /*****************************************************************************
3566  *
3567  *              QUERY :
3568  *                              CREATE SEQUENCE seqname
3569  *                              ALTER SEQUENCE seqname
3570  *
3571  *****************************************************************************/
3572
3573 CreateSeqStmt:
3574                         CREATE OptTemp SEQUENCE qualified_name OptSeqOptList
3575                                 {
3576                                         CreateSeqStmt *n = makeNode(CreateSeqStmt);
3577                                         $4->relpersistence = $2;
3578                                         n->sequence = $4;
3579                                         n->options = $5;
3580                                         n->ownerId = InvalidOid;
3581                                         n->if_not_exists = false;
3582                                         $$ = (Node *)n;
3583                                 }
3584                         | CREATE OptTemp SEQUENCE IF_P NOT EXISTS qualified_name OptSeqOptList
3585                                 {
3586                                         CreateSeqStmt *n = makeNode(CreateSeqStmt);
3587                                         $7->relpersistence = $2;
3588                                         n->sequence = $7;
3589                                         n->options = $8;
3590                                         n->ownerId = InvalidOid;
3591                                         n->if_not_exists = true;
3592                                         $$ = (Node *)n;
3593                                 }
3594                 ;
3595
3596 AlterSeqStmt:
3597                         ALTER SEQUENCE qualified_name SeqOptList
3598                                 {
3599                                         AlterSeqStmt *n = makeNode(AlterSeqStmt);
3600                                         n->sequence = $3;
3601                                         n->options = $4;
3602                                         n->missing_ok = false;
3603                                         $$ = (Node *)n;
3604                                 }
3605                         | ALTER SEQUENCE IF_P EXISTS qualified_name SeqOptList
3606                                 {
3607                                         AlterSeqStmt *n = makeNode(AlterSeqStmt);
3608                                         n->sequence = $5;
3609                                         n->options = $6;
3610                                         n->missing_ok = true;
3611                                         $$ = (Node *)n;
3612                                 }
3613
3614                 ;
3615
3616 OptSeqOptList: SeqOptList                                                       { $$ = $1; }
3617                         | /*EMPTY*/                                                             { $$ = NIL; }
3618                 ;
3619
3620 SeqOptList: SeqOptElem                                                          { $$ = list_make1($1); }
3621                         | SeqOptList SeqOptElem                                 { $$ = lappend($1, $2); }
3622                 ;
3623
3624 SeqOptElem: CACHE NumericOnly
3625                                 {
3626                                         $$ = makeDefElem("cache", (Node *)$2);
3627                                 }
3628                         | CYCLE
3629                                 {
3630                                         $$ = makeDefElem("cycle", (Node *)makeInteger(TRUE));
3631                                 }
3632                         | NO CYCLE
3633                                 {
3634                                         $$ = makeDefElem("cycle", (Node *)makeInteger(FALSE));
3635                                 }
3636                         | INCREMENT opt_by NumericOnly
3637                                 {
3638                                         $$ = makeDefElem("increment", (Node *)$3);
3639                                 }
3640                         | MAXVALUE NumericOnly
3641                                 {
3642                                         $$ = makeDefElem("maxvalue", (Node *)$2);
3643                                 }
3644                         | MINVALUE NumericOnly
3645                                 {
3646                                         $$ = makeDefElem("minvalue", (Node *)$2);
3647                                 }
3648                         | NO MAXVALUE
3649                                 {
3650                                         $$ = makeDefElem("maxvalue", NULL);
3651                                 }
3652                         | NO MINVALUE
3653                                 {
3654                                         $$ = makeDefElem("minvalue", NULL);
3655                                 }
3656                         | OWNED BY any_name
3657                                 {
3658                                         $$ = makeDefElem("owned_by", (Node *)$3);
3659                                 }
3660                         | START opt_with NumericOnly
3661                                 {
3662                                         $$ = makeDefElem("start", (Node *)$3);
3663                                 }
3664                         | RESTART
3665                                 {
3666                                         $$ = makeDefElem("restart", NULL);
3667                                 }
3668                         | RESTART opt_with NumericOnly
3669                                 {
3670                                         $$ = makeDefElem("restart", (Node *)$3);
3671                                 }
3672                 ;
3673
3674 opt_by:         BY                              {}
3675                         | /* empty */   {}
3676           ;
3677
3678 NumericOnly:
3679                         FCONST                                                          { $$ = makeFloat($1); }
3680                         | '-' FCONST
3681                                 {
3682                                         $$ = makeFloat($2);
3683                                         doNegateFloat($$);
3684                                 }
3685                         | SignedIconst                                          { $$ = makeInteger($1); }
3686                 ;
3687
3688 NumericOnly_list:       NumericOnly                                             { $$ = list_make1($1); }
3689                                 | NumericOnly_list ',' NumericOnly      { $$ = lappend($1, $3); }
3690                 ;
3691
3692 /*****************************************************************************
3693  *
3694  *              QUERIES :
3695  *                              CREATE [OR REPLACE] [TRUSTED] [PROCEDURAL] LANGUAGE ...
3696  *                              DROP [PROCEDURAL] LANGUAGE ...
3697  *
3698  *****************************************************************************/
3699
3700 CreatePLangStmt:
3701                         CREATE opt_or_replace opt_trusted opt_procedural LANGUAGE NonReservedWord_or_Sconst
3702                         {
3703                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
3704                                 n->replace = $2;
3705                                 n->plname = $6;
3706                                 /* parameters are all to be supplied by system */
3707                                 n->plhandler = NIL;
3708                                 n->plinline = NIL;
3709                                 n->plvalidator = NIL;
3710                                 n->pltrusted = false;
3711                                 $$ = (Node *)n;
3712                         }
3713                         | CREATE opt_or_replace opt_trusted opt_procedural LANGUAGE NonReservedWord_or_Sconst
3714                           HANDLER handler_name opt_inline_handler opt_validator
3715                         {
3716                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
3717                                 n->replace = $2;
3718                                 n->plname = $6;
3719                                 n->plhandler = $8;
3720                                 n->plinline = $9;
3721                                 n->plvalidator = $10;
3722                                 n->pltrusted = $3;
3723                                 $$ = (Node *)n;
3724                         }
3725                 ;
3726
3727 opt_trusted:
3728                         TRUSTED                                                                 { $$ = TRUE; }
3729                         | /*EMPTY*/                                                             { $$ = FALSE; }
3730                 ;
3731
3732 /* This ought to be just func_name, but that causes reduce/reduce conflicts
3733  * (CREATE LANGUAGE is the only place where func_name isn't followed by '(').
3734  * Work around by using simple names, instead.
3735  */
3736 handler_name:
3737                         name                                            { $$ = list_make1(makeString($1)); }
3738                         | name attrs                            { $$ = lcons(makeString($1), $2); }
3739                 ;
3740
3741 opt_inline_handler:
3742                         INLINE_P handler_name                                   { $$ = $2; }
3743                         | /*EMPTY*/                                                             { $$ = NIL; }
3744                 ;
3745
3746 validator_clause:
3747                         VALIDATOR handler_name                                  { $$ = $2; }
3748                         | NO VALIDATOR                                                  { $$ = NIL; }
3749                 ;
3750
3751 opt_validator:
3752                         validator_clause                                                { $$ = $1; }
3753                         | /*EMPTY*/                                                             { $$ = NIL; }
3754                 ;
3755
3756 DropPLangStmt:
3757                         DROP opt_procedural LANGUAGE NonReservedWord_or_Sconst opt_drop_behavior
3758                                 {
3759                                         DropStmt *n = makeNode(DropStmt);
3760                                         n->removeType = OBJECT_LANGUAGE;
3761                                         n->objects = list_make1(list_make1(makeString($4)));
3762                                         n->arguments = NIL;
3763                                         n->behavior = $5;
3764                                         n->missing_ok = false;
3765                                         n->concurrent = false;
3766                                         $$ = (Node *)n;
3767                                 }
3768                         | DROP opt_procedural LANGUAGE IF_P EXISTS NonReservedWord_or_Sconst opt_drop_behavior
3769                                 {
3770                                         DropStmt *n = makeNode(DropStmt);
3771                                         n->removeType = OBJECT_LANGUAGE;
3772                                         n->objects = list_make1(list_make1(makeString($6)));
3773                                         n->behavior = $7;
3774                                         n->missing_ok = true;
3775                                         n->concurrent = false;
3776                                         $$ = (Node *)n;
3777                                 }
3778                 ;
3779
3780 opt_procedural:
3781                         PROCEDURAL                                                              {}
3782                         | /*EMPTY*/                                                             {}
3783                 ;
3784
3785 /*****************************************************************************
3786  *
3787  *              QUERY:
3788  *             CREATE TABLESPACE tablespace LOCATION '/path/to/tablespace/'
3789  *
3790  *****************************************************************************/
3791
3792 CreateTableSpaceStmt: CREATE TABLESPACE name OptTableSpaceOwner LOCATION Sconst opt_reloptions
3793                                 {
3794                                         CreateTableSpaceStmt *n = makeNode(CreateTableSpaceStmt);
3795                                         n->tablespacename = $3;
3796                                         n->owner = $4;
3797                                         n->location = $6;
3798                                         n->options = $7;
3799                                         $$ = (Node *) n;
3800                                 }
3801                 ;
3802
3803 OptTableSpaceOwner: OWNER RoleSpec              { $$ = $2; }
3804                         | /*EMPTY */                            { $$ = NULL; }
3805                 ;
3806
3807 /*****************************************************************************
3808  *
3809  *              QUERY :
3810  *                              DROP TABLESPACE <tablespace>
3811  *
3812  *              No need for drop behaviour as we cannot implement dependencies for
3813  *              objects in other databases; we can only support RESTRICT.
3814  *
3815  ****************************************************************************/
3816
3817 DropTableSpaceStmt: DROP TABLESPACE name
3818                                 {
3819                                         DropTableSpaceStmt *n = makeNode(DropTableSpaceStmt);
3820                                         n->tablespacename = $3;
3821                                         n->missing_ok = false;
3822                                         $$ = (Node *) n;
3823                                 }
3824                                 |  DROP TABLESPACE IF_P EXISTS name
3825                                 {
3826                                         DropTableSpaceStmt *n = makeNode(DropTableSpaceStmt);
3827                                         n->tablespacename = $5;
3828                                         n->missing_ok = true;
3829                                         $$ = (Node *) n;
3830                                 }
3831                 ;
3832
3833 /*****************************************************************************
3834  *
3835  *              QUERY:
3836  *             CREATE EXTENSION extension
3837  *             [ WITH ] [ SCHEMA schema ] [ VERSION version ] [ FROM oldversion ]
3838  *
3839  *****************************************************************************/
3840
3841 CreateExtensionStmt: CREATE EXTENSION name opt_with create_extension_opt_list
3842                                 {
3843                                         CreateExtensionStmt *n = makeNode(CreateExtensionStmt);
3844                                         n->extname = $3;
3845                                         n->if_not_exists = false;
3846                                         n->options = $5;
3847                                         $$ = (Node *) n;
3848                                 }
3849                                 | CREATE EXTENSION IF_P NOT EXISTS name opt_with create_extension_opt_list
3850                                 {
3851                                         CreateExtensionStmt *n = makeNode(CreateExtensionStmt);
3852                                         n->extname = $6;
3853                                         n->if_not_exists = true;
3854                                         n->options = $8;
3855                                         $$ = (Node *) n;
3856                                 }
3857                 ;
3858
3859 create_extension_opt_list:
3860                         create_extension_opt_list create_extension_opt_item
3861                                 { $$ = lappend($1, $2); }
3862                         | /* EMPTY */
3863                                 { $$ = NIL; }
3864                 ;
3865
3866 create_extension_opt_item:
3867                         SCHEMA name
3868                                 {
3869                                         $$ = makeDefElem("schema", (Node *)makeString($2));
3870                                 }
3871                         | VERSION_P NonReservedWord_or_Sconst
3872                                 {
3873                                         $$ = makeDefElem("new_version", (Node *)makeString($2));
3874                                 }
3875                         | FROM NonReservedWord_or_Sconst
3876                                 {
3877                                         $$ = makeDefElem("old_version", (Node *)makeString($2));
3878                                 }
3879                         | CASCADE
3880                                 {
3881                                         $$ = makeDefElem("cascade", (Node *)makeInteger(TRUE));
3882                                 }
3883                 ;
3884
3885 /*****************************************************************************
3886  *
3887  * ALTER EXTENSION name UPDATE [ TO version ]
3888  *
3889  *****************************************************************************/
3890
3891 AlterExtensionStmt: ALTER EXTENSION name UPDATE alter_extension_opt_list
3892                                 {
3893                                         AlterExtensionStmt *n = makeNode(AlterExtensionStmt);
3894                                         n->extname = $3;
3895                                         n->options = $5;
3896                                         $$ = (Node *) n;
3897                                 }
3898                 ;
3899
3900 alter_extension_opt_list:
3901                         alter_extension_opt_list alter_extension_opt_item
3902                                 { $$ = lappend($1, $2); }
3903                         | /* EMPTY */
3904                                 { $$ = NIL; }
3905                 ;
3906
3907 alter_extension_opt_item:
3908                         TO NonReservedWord_or_Sconst
3909                                 {
3910                                         $$ = makeDefElem("new_version", (Node *)makeString($2));
3911                                 }
3912                 ;
3913
3914 /*****************************************************************************
3915  *
3916  * ALTER EXTENSION name ADD/DROP object-identifier
3917  *
3918  *****************************************************************************/
3919
3920 AlterExtensionContentsStmt:
3921                         ALTER EXTENSION name add_drop AGGREGATE func_name aggr_args
3922                                 {
3923                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3924                                         n->extname = $3;
3925                                         n->action = $4;
3926                                         n->objtype = OBJECT_AGGREGATE;
3927                                         n->objname = $6;
3928                                         n->objargs = extractAggrArgTypes($7);
3929                                         $$ = (Node *)n;
3930                                 }
3931                         | ALTER EXTENSION name add_drop CAST '(' Typename AS Typename ')'
3932                                 {
3933                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3934                                         n->extname = $3;
3935                                         n->action = $4;
3936                                         n->objtype = OBJECT_CAST;
3937                                         n->objname = list_make1($7);
3938                                         n->objargs = list_make1($9);
3939                                         $$ = (Node *) n;
3940                                 }
3941                         | ALTER EXTENSION name add_drop COLLATION any_name
3942                                 {
3943                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3944                                         n->extname = $3;
3945                                         n->action = $4;
3946                                         n->objtype = OBJECT_COLLATION;
3947                                         n->objname = $6;
3948                                         $$ = (Node *)n;
3949                                 }
3950                         | ALTER EXTENSION name add_drop CONVERSION_P any_name
3951                                 {
3952                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3953                                         n->extname = $3;
3954                                         n->action = $4;
3955                                         n->objtype = OBJECT_CONVERSION;
3956                                         n->objname = $6;
3957                                         $$ = (Node *)n;
3958                                 }
3959                         | ALTER EXTENSION name add_drop DOMAIN_P Typename
3960                                 {
3961                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3962                                         n->extname = $3;
3963                                         n->action = $4;
3964                                         n->objtype = OBJECT_DOMAIN;
3965                                         n->objname = list_make1($6);
3966                                         $$ = (Node *)n;
3967                                 }
3968                         | ALTER EXTENSION name add_drop FUNCTION function_with_argtypes
3969                                 {
3970                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3971                                         n->extname = $3;
3972                                         n->action = $4;
3973                                         n->objtype = OBJECT_FUNCTION;
3974                                         n->objname = $6->funcname;
3975                                         n->objargs = $6->funcargs;
3976                                         $$ = (Node *)n;
3977                                 }
3978                         | ALTER EXTENSION name add_drop opt_procedural LANGUAGE name
3979                                 {
3980                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3981                                         n->extname = $3;
3982                                         n->action = $4;
3983                                         n->objtype = OBJECT_LANGUAGE;
3984                                         n->objname = list_make1(makeString($7));
3985                                         $$ = (Node *)n;
3986                                 }
3987                         | ALTER EXTENSION name add_drop OPERATOR any_operator oper_argtypes
3988                                 {
3989                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
3990                                         n->extname = $3;
3991                                         n->action = $4;
3992                                         n->objtype = OBJECT_OPERATOR;
3993                                         n->objname = $6;
3994                                         n->objargs = $7;
3995                                         $$ = (Node *)n;
3996                                 }
3997                         | ALTER EXTENSION name add_drop OPERATOR CLASS any_name USING access_method
3998                                 {
3999                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4000                                         n->extname = $3;
4001                                         n->action = $4;
4002                                         n->objtype = OBJECT_OPCLASS;
4003                                         n->objname = lcons(makeString($9), $7);
4004                                         $$ = (Node *)n;
4005                                 }
4006                         | ALTER EXTENSION name add_drop OPERATOR FAMILY any_name USING access_method
4007                                 {
4008                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4009                                         n->extname = $3;
4010                                         n->action = $4;
4011                                         n->objtype = OBJECT_OPFAMILY;
4012                                         n->objname = lcons(makeString($9), $7);
4013                                         $$ = (Node *)n;
4014                                 }
4015                         | ALTER EXTENSION name add_drop SCHEMA name
4016                                 {
4017                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4018                                         n->extname = $3;
4019                                         n->action = $4;
4020                                         n->objtype = OBJECT_SCHEMA;
4021                                         n->objname = list_make1(makeString($6));
4022                                         $$ = (Node *)n;
4023                                 }
4024                         | ALTER EXTENSION name add_drop EVENT TRIGGER name
4025                                 {
4026                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4027                                         n->extname = $3;
4028                                         n->action = $4;
4029                                         n->objtype = OBJECT_EVENT_TRIGGER;
4030                                         n->objname = list_make1(makeString($7));
4031                                         $$ = (Node *)n;
4032                                 }
4033                         | ALTER EXTENSION name add_drop TABLE any_name
4034                                 {
4035                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4036                                         n->extname = $3;
4037                                         n->action = $4;
4038                                         n->objtype = OBJECT_TABLE;
4039                                         n->objname = $6;
4040                                         $$ = (Node *)n;
4041                                 }
4042                         | ALTER EXTENSION name add_drop TEXT_P SEARCH PARSER any_name
4043                                 {
4044                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4045                                         n->extname = $3;
4046                                         n->action = $4;
4047                                         n->objtype = OBJECT_TSPARSER;
4048                                         n->objname = $8;
4049                                         $$ = (Node *)n;
4050                                 }
4051                         | ALTER EXTENSION name add_drop TEXT_P SEARCH DICTIONARY any_name
4052                                 {
4053                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4054                                         n->extname = $3;
4055                                         n->action = $4;
4056                                         n->objtype = OBJECT_TSDICTIONARY;
4057                                         n->objname = $8;
4058                                         $$ = (Node *)n;
4059                                 }
4060                         | ALTER EXTENSION name add_drop TEXT_P SEARCH TEMPLATE any_name
4061                                 {
4062                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4063                                         n->extname = $3;
4064                                         n->action = $4;
4065                                         n->objtype = OBJECT_TSTEMPLATE;
4066                                         n->objname = $8;
4067                                         $$ = (Node *)n;
4068                                 }
4069                         | ALTER EXTENSION name add_drop TEXT_P SEARCH CONFIGURATION any_name
4070                                 {
4071                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4072                                         n->extname = $3;
4073                                         n->action = $4;
4074                                         n->objtype = OBJECT_TSCONFIGURATION;
4075                                         n->objname = $8;
4076                                         $$ = (Node *)n;
4077                                 }
4078                         | ALTER EXTENSION name add_drop SEQUENCE any_name
4079                                 {
4080                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4081                                         n->extname = $3;
4082                                         n->action = $4;
4083                                         n->objtype = OBJECT_SEQUENCE;
4084                                         n->objname = $6;
4085                                         $$ = (Node *)n;
4086                                 }
4087                         | ALTER EXTENSION name add_drop VIEW any_name
4088                                 {
4089                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4090                                         n->extname = $3;
4091                                         n->action = $4;
4092                                         n->objtype = OBJECT_VIEW;
4093                                         n->objname = $6;
4094                                         $$ = (Node *)n;
4095                                 }
4096                         | ALTER EXTENSION name add_drop MATERIALIZED VIEW any_name
4097                                 {
4098                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4099                                         n->extname = $3;
4100                                         n->action = $4;
4101                                         n->objtype = OBJECT_MATVIEW;
4102                                         n->objname = $7;
4103                                         $$ = (Node *)n;
4104                                 }
4105                         | ALTER EXTENSION name add_drop FOREIGN TABLE any_name
4106                                 {
4107                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4108                                         n->extname = $3;
4109                                         n->action = $4;
4110                                         n->objtype = OBJECT_FOREIGN_TABLE;
4111                                         n->objname = $7;
4112                                         $$ = (Node *)n;
4113                                 }
4114                         | ALTER EXTENSION name add_drop FOREIGN DATA_P WRAPPER name
4115                                 {
4116                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4117                                         n->extname = $3;
4118                                         n->action = $4;
4119                                         n->objtype = OBJECT_FDW;
4120                                         n->objname = list_make1(makeString($8));
4121                                         $$ = (Node *)n;
4122                                 }
4123                         | ALTER EXTENSION name add_drop SERVER name
4124                                 {
4125                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4126                                         n->extname = $3;
4127                                         n->action = $4;
4128                                         n->objtype = OBJECT_FOREIGN_SERVER;
4129                                         n->objname = list_make1(makeString($6));
4130                                         $$ = (Node *)n;
4131                                 }
4132                         | ALTER EXTENSION name add_drop TRANSFORM FOR Typename LANGUAGE name
4133                                 {
4134                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4135                                         n->extname = $3;
4136                                         n->action = $4;
4137                                         n->objtype = OBJECT_TRANSFORM;
4138                                         n->objname = list_make1($7);
4139                                         n->objargs = list_make1(makeString($9));
4140                                         $$ = (Node *)n;
4141                                 }
4142                         | ALTER EXTENSION name add_drop TYPE_P Typename
4143                                 {
4144                                         AlterExtensionContentsStmt *n = makeNode(AlterExtensionContentsStmt);
4145                                         n->extname = $3;
4146                                         n->action = $4;
4147                                         n->objtype = OBJECT_TYPE;
4148                                         n->objname = list_make1($6);
4149                                         $$ = (Node *)n;
4150                                 }
4151                 ;
4152
4153 /*****************************************************************************
4154  *
4155  *              QUERY:
4156  *             CREATE FOREIGN DATA WRAPPER name options
4157  *
4158  *****************************************************************************/
4159
4160 CreateFdwStmt: CREATE FOREIGN DATA_P WRAPPER name opt_fdw_options create_generic_options
4161                                 {
4162                                         CreateFdwStmt *n = makeNode(CreateFdwStmt);
4163                                         n->fdwname = $5;
4164                                         n->func_options = $6;
4165                                         n->options = $7;
4166                                         $$ = (Node *) n;
4167                                 }
4168                 ;
4169
4170 fdw_option:
4171                         HANDLER handler_name                            { $$ = makeDefElem("handler", (Node *)$2); }
4172                         | NO HANDLER                                            { $$ = makeDefElem("handler", NULL); }
4173                         | VALIDATOR handler_name                        { $$ = makeDefElem("validator", (Node *)$2); }
4174                         | NO VALIDATOR                                          { $$ = makeDefElem("validator", NULL); }
4175                 ;
4176
4177 fdw_options:
4178                         fdw_option                                                      { $$ = list_make1($1); }
4179                         | fdw_options fdw_option                        { $$ = lappend($1, $2); }
4180                 ;
4181
4182 opt_fdw_options:
4183                         fdw_options                                                     { $$ = $1; }
4184                         | /*EMPTY*/                                                     { $$ = NIL; }
4185                 ;
4186
4187 /*****************************************************************************
4188  *
4189  *              QUERY :
4190  *                              DROP FOREIGN DATA WRAPPER name
4191  *
4192  ****************************************************************************/
4193
4194 DropFdwStmt: DROP FOREIGN DATA_P WRAPPER name opt_drop_behavior
4195                                 {
4196                                         DropStmt *n = makeNode(DropStmt);
4197                                         n->removeType = OBJECT_FDW;
4198                                         n->objects = list_make1(list_make1(makeString($5)));
4199                                         n->arguments = NIL;
4200                                         n->missing_ok = false;
4201                                         n->behavior = $6;
4202                                         n->concurrent = false;
4203                                         $$ = (Node *) n;
4204                                 }
4205                                 |  DROP FOREIGN DATA_P WRAPPER IF_P EXISTS name opt_drop_behavior
4206                                 {
4207                                         DropStmt *n = makeNode(DropStmt);
4208                                         n->removeType = OBJECT_FDW;
4209                                         n->objects = list_make1(list_make1(makeString($7)));
4210                                         n->arguments = NIL;
4211                                         n->missing_ok = true;
4212                                         n->behavior = $8;
4213                                         n->concurrent = false;
4214                                         $$ = (Node *) n;
4215                                 }
4216                 ;
4217
4218 /*****************************************************************************
4219  *
4220  *              QUERY :
4221  *                              ALTER FOREIGN DATA WRAPPER name options
4222  *
4223  ****************************************************************************/
4224
4225 AlterFdwStmt: ALTER FOREIGN DATA_P WRAPPER name opt_fdw_options alter_generic_options
4226                                 {
4227                                         AlterFdwStmt *n = makeNode(AlterFdwStmt);
4228                                         n->fdwname = $5;
4229                                         n->func_options = $6;
4230                                         n->options = $7;
4231                                         $$ = (Node *) n;
4232                                 }
4233                         | ALTER FOREIGN DATA_P WRAPPER name fdw_options
4234                                 {
4235                                         AlterFdwStmt *n = makeNode(AlterFdwStmt);
4236                                         n->fdwname = $5;
4237                                         n->func_options = $6;
4238                                         n->options = NIL;
4239                                         $$ = (Node *) n;
4240                                 }
4241                 ;
4242
4243 /* Options definition for CREATE FDW, SERVER and USER MAPPING */
4244 create_generic_options:
4245                         OPTIONS '(' generic_option_list ')'                     { $$ = $3; }
4246                         | /*EMPTY*/                                                                     { $$ = NIL; }
4247                 ;
4248
4249 generic_option_list:
4250                         generic_option_elem
4251                                 {
4252                                         $$ = list_make1($1);
4253                                 }
4254                         | generic_option_list ',' generic_option_elem
4255                                 {
4256                                         $$ = lappend($1, $3);
4257                                 }
4258                 ;
4259
4260 /* Options definition for ALTER FDW, SERVER and USER MAPPING */
4261 alter_generic_options:
4262                         OPTIONS '(' alter_generic_option_list ')'               { $$ = $3; }
4263                 ;
4264
4265 alter_generic_option_list:
4266                         alter_generic_option_elem
4267                                 {
4268                                         $$ = list_make1($1);
4269                                 }
4270                         | alter_generic_option_list ',' alter_generic_option_elem
4271                                 {
4272                                         $$ = lappend($1, $3);
4273                                 }
4274                 ;
4275
4276 alter_generic_option_elem:
4277                         generic_option_elem
4278                                 {
4279                                         $$ = $1;
4280                                 }
4281                         | SET generic_option_elem
4282                                 {
4283                                         $$ = $2;
4284                                         $$->defaction = DEFELEM_SET;
4285                                 }
4286                         | ADD_P generic_option_elem
4287                                 {
4288                                         $$ = $2;
4289                                         $$->defaction = DEFELEM_ADD;
4290                                 }
4291                         | DROP generic_option_name
4292                                 {
4293                                         $$ = makeDefElemExtended(NULL, $2, NULL, DEFELEM_DROP);
4294                                 }
4295                 ;
4296
4297 generic_option_elem:
4298                         generic_option_name generic_option_arg
4299                                 {
4300                                         $$ = makeDefElem($1, $2);
4301                                 }
4302                 ;
4303
4304 generic_option_name:
4305                                 ColLabel                        { $$ = $1; }
4306                 ;
4307
4308 /* We could use def_arg here, but the spec only requires string literals */
4309 generic_option_arg:
4310                                 Sconst                          { $$ = (Node *) makeString($1); }
4311                 ;
4312
4313 /*****************************************************************************
4314  *
4315  *              QUERY:
4316  *             CREATE SERVER name [TYPE] [VERSION] [OPTIONS]
4317  *
4318  *****************************************************************************/
4319
4320 CreateForeignServerStmt: CREATE SERVER name opt_type opt_foreign_server_version
4321                                                  FOREIGN DATA_P WRAPPER name create_generic_options
4322                                 {
4323                                         CreateForeignServerStmt *n = makeNode(CreateForeignServerStmt);
4324                                         n->servername = $3;
4325                                         n->servertype = $4;
4326                                         n->version = $5;
4327                                         n->fdwname = $9;
4328                                         n->options = $10;
4329                                         $$ = (Node *) n;
4330                                 }
4331                 ;
4332
4333 opt_type:
4334                         TYPE_P Sconst                   { $$ = $2; }
4335                         | /*EMPTY*/                             { $$ = NULL; }
4336                 ;
4337
4338
4339 foreign_server_version:
4340                         VERSION_P Sconst                { $$ = $2; }
4341                 |       VERSION_P NULL_P                { $$ = NULL; }
4342                 ;
4343
4344 opt_foreign_server_version:
4345                         foreign_server_version  { $$ = $1; }
4346                         | /*EMPTY*/                             { $$ = NULL; }
4347                 ;
4348
4349 /*****************************************************************************
4350  *
4351  *              QUERY :
4352  *                              DROP SERVER name
4353  *
4354  ****************************************************************************/
4355
4356 DropForeignServerStmt: DROP SERVER name opt_drop_behavior
4357                                 {
4358                                         DropStmt *n = makeNode(DropStmt);
4359                                         n->removeType = OBJECT_FOREIGN_SERVER;
4360                                         n->objects = list_make1(list_make1(makeString($3)));
4361                                         n->arguments = NIL;
4362                                         n->missing_ok = false;
4363                                         n->behavior = $4;
4364                                         n->concurrent = false;
4365                                         $$ = (Node *) n;
4366                                 }
4367                                 |  DROP SERVER IF_P EXISTS name opt_drop_behavior
4368                                 {
4369                                         DropStmt *n = makeNode(DropStmt);
4370                                         n->removeType = OBJECT_FOREIGN_SERVER;
4371                                         n->objects = list_make1(list_make1(makeString($5)));
4372                                         n->arguments = NIL;
4373                                         n->missing_ok = true;
4374                                         n->behavior = $6;
4375                                         n->concurrent = false;
4376                                         $$ = (Node *) n;
4377                                 }
4378                 ;
4379
4380 /*****************************************************************************
4381  *
4382  *              QUERY :
4383  *                              ALTER SERVER name [VERSION] [OPTIONS]
4384  *
4385  ****************************************************************************/
4386
4387 AlterForeignServerStmt: ALTER SERVER name foreign_server_version alter_generic_options
4388                                 {
4389                                         AlterForeignServerStmt *n = makeNode(AlterForeignServerStmt);
4390                                         n->servername = $3;
4391                                         n->version = $4;
4392                                         n->options = $5;
4393                                         n->has_version = true;
4394                                         $$ = (Node *) n;
4395                                 }
4396                         | ALTER SERVER name foreign_server_version
4397                                 {
4398                                         AlterForeignServerStmt *n = makeNode(AlterForeignServerStmt);
4399                                         n->servername = $3;
4400                                         n->version = $4;
4401                                         n->has_version = true;
4402                                         $$ = (Node *) n;
4403                                 }
4404                         | ALTER SERVER name alter_generic_options
4405                                 {
4406                                         AlterForeignServerStmt *n = makeNode(AlterForeignServerStmt);
4407                                         n->servername = $3;
4408                                         n->options = $4;
4409                                         $$ = (Node *) n;
4410                                 }
4411                 ;
4412
4413 /*****************************************************************************
4414  *
4415  *              QUERY:
4416  *             CREATE FOREIGN TABLE relname (...) SERVER name (...)
4417  *
4418  *****************************************************************************/
4419
4420 CreateForeignTableStmt:
4421                 CREATE FOREIGN TABLE qualified_name
4422                         '(' OptTableElementList ')'
4423                         OptInherit SERVER name create_generic_options
4424                                 {
4425                                         CreateForeignTableStmt *n = makeNode(CreateForeignTableStmt);
4426                                         $4->relpersistence = RELPERSISTENCE_PERMANENT;
4427                                         n->base.relation = $4;
4428                                         n->base.tableElts = $6;
4429                                         n->base.inhRelations = $8;
4430                                         n->base.ofTypename = NULL;
4431                                         n->base.constraints = NIL;
4432                                         n->base.options = NIL;
4433                                         n->base.oncommit = ONCOMMIT_NOOP;
4434                                         n->base.tablespacename = NULL;
4435                                         n->base.if_not_exists = false;
4436                                         /* FDW-specific data */
4437                                         n->servername = $10;
4438                                         n->options = $11;
4439                                         $$ = (Node *) n;
4440                                 }
4441                 | CREATE FOREIGN TABLE IF_P NOT EXISTS qualified_name
4442                         '(' OptTableElementList ')'
4443                         OptInherit SERVER name create_generic_options
4444                                 {
4445                                         CreateForeignTableStmt *n = makeNode(CreateForeignTableStmt);
4446                                         $7->relpersistence = RELPERSISTENCE_PERMANENT;
4447                                         n->base.relation = $7;
4448                                         n->base.tableElts = $9;
4449                                         n->base.inhRelations = $11;
4450                                         n->base.ofTypename = NULL;
4451                                         n->base.constraints = NIL;
4452                                         n->base.options = NIL;
4453                                         n->base.oncommit = ONCOMMIT_NOOP;
4454                                         n->base.tablespacename = NULL;
4455                                         n->base.if_not_exists = true;
4456                                         /* FDW-specific data */
4457                                         n->servername = $13;
4458                                         n->options = $14;
4459                                         $$ = (Node *) n;
4460                                 }
4461                 ;
4462
4463 /*****************************************************************************
4464  *
4465  *              QUERY:
4466  *             ALTER FOREIGN TABLE relname [...]
4467  *
4468  *****************************************************************************/
4469
4470 AlterForeignTableStmt:
4471                         ALTER FOREIGN TABLE relation_expr alter_table_cmds
4472                                 {
4473                                         AlterTableStmt *n = makeNode(AlterTableStmt);
4474                                         n->relation = $4;
4475                                         n->cmds = $5;
4476                                         n->relkind = OBJECT_FOREIGN_TABLE;
4477                                         n->missing_ok = false;
4478                                         $$ = (Node *)n;
4479                                 }
4480                         | ALTER FOREIGN TABLE IF_P EXISTS relation_expr alter_table_cmds
4481                                 {
4482                                         AlterTableStmt *n = makeNode(AlterTableStmt);
4483                                         n->relation = $6;
4484                                         n->cmds = $7;
4485                                         n->relkind = OBJECT_FOREIGN_TABLE;
4486                                         n->missing_ok = true;
4487                                         $$ = (Node *)n;
4488                                 }
4489                 ;
4490
4491 /*****************************************************************************
4492  *
4493  *              QUERY:
4494  *                              IMPORT FOREIGN SCHEMA remote_schema
4495  *                              [ { LIMIT TO | EXCEPT } ( table_list ) ]
4496  *                              FROM SERVER server_name INTO local_schema [ OPTIONS (...) ]
4497  *
4498  ****************************************************************************/
4499
4500 ImportForeignSchemaStmt:
4501                 IMPORT_P FOREIGN SCHEMA name import_qualification
4502                   FROM SERVER name INTO name create_generic_options
4503                         {
4504                                 ImportForeignSchemaStmt *n = makeNode(ImportForeignSchemaStmt);
4505                                 n->server_name = $8;
4506                                 n->remote_schema = $4;
4507                                 n->local_schema = $10;
4508                                 n->list_type = $5->type;
4509                                 n->table_list = $5->table_names;
4510                                 n->options = $11;
4511                                 $$ = (Node *) n;
4512                         }
4513                 ;
4514
4515 import_qualification_type:
4516                 LIMIT TO                                { $$ = FDW_IMPORT_SCHEMA_LIMIT_TO; }
4517                 | EXCEPT                                { $$ = FDW_IMPORT_SCHEMA_EXCEPT; }
4518                 ;
4519
4520 import_qualification:
4521                 import_qualification_type '(' relation_expr_list ')'
4522                         {
4523                                 ImportQual *n = (ImportQual *) palloc(sizeof(ImportQual));
4524                                 n->type = $1;
4525                                 n->table_names = $3;
4526                                 $$ = n;
4527                         }
4528                 | /*EMPTY*/
4529                         {
4530                                 ImportQual *n = (ImportQual *) palloc(sizeof(ImportQual));
4531                                 n->type = FDW_IMPORT_SCHEMA_ALL;
4532                                 n->table_names = NIL;
4533                                 $$ = n;
4534                         }
4535                 ;
4536
4537 /*****************************************************************************
4538  *
4539  *              QUERY:
4540  *             CREATE USER MAPPING FOR auth_ident SERVER name [OPTIONS]
4541  *
4542  *****************************************************************************/
4543
4544 CreateUserMappingStmt: CREATE USER MAPPING FOR auth_ident SERVER name create_generic_options
4545                                 {
4546                                         CreateUserMappingStmt *n = makeNode(CreateUserMappingStmt);
4547                                         n->user = $5;
4548                                         n->servername = $7;
4549                                         n->options = $8;
4550                                         $$ = (Node *) n;
4551                                 }
4552                 ;
4553
4554 /* User mapping authorization identifier */
4555 auth_ident: RoleSpec                    { $$ = $1; }
4556                         | USER                          { $$ = makeRoleSpec(ROLESPEC_CURRENT_USER, @1); }
4557                 ;
4558
4559 /*****************************************************************************
4560  *
4561  *              QUERY :
4562  *                              DROP USER MAPPING FOR auth_ident SERVER name
4563  *
4564  ****************************************************************************/
4565
4566 DropUserMappingStmt: DROP USER MAPPING FOR auth_ident SERVER name
4567                                 {
4568                                         DropUserMappingStmt *n = makeNode(DropUserMappingStmt);
4569                                         n->user = $5;
4570                                         n->servername = $7;
4571                                         n->missing_ok = false;
4572                                         $$ = (Node *) n;
4573                                 }
4574                                 |  DROP USER MAPPING IF_P EXISTS FOR auth_ident SERVER name
4575                                 {
4576                                         DropUserMappingStmt *n = makeNode(DropUserMappingStmt);
4577                                         n->user = $7;
4578                                         n->servername = $9;
4579                                         n->missing_ok = true;
4580                                         $$ = (Node *) n;
4581                                 }
4582                 ;
4583
4584 /*****************************************************************************
4585  *
4586  *              QUERY :
4587  *                              ALTER USER MAPPING FOR auth_ident SERVER name OPTIONS
4588  *
4589  ****************************************************************************/
4590
4591 AlterUserMappingStmt: ALTER USER MAPPING FOR auth_ident SERVER name alter_generic_options
4592                                 {
4593                                         AlterUserMappingStmt *n = makeNode(AlterUserMappingStmt);
4594                                         n->user = $5;
4595                                         n->servername = $7;
4596                                         n->options = $8;
4597                                         $$ = (Node *) n;
4598                                 }
4599                 ;
4600
4601 /*****************************************************************************
4602  *
4603  *              QUERIES:
4604  *                              CREATE POLICY name ON table [FOR cmd] [TO role, ...]
4605  *                                      [USING (qual)] [WITH CHECK (with_check)]
4606  *                              ALTER POLICY name ON table [TO role, ...]
4607  *                                      [USING (qual)] [WITH CHECK (with_check)]
4608  *                              DROP POLICY name ON table
4609  *
4610  *****************************************************************************/
4611
4612 CreatePolicyStmt:
4613                         CREATE POLICY name ON qualified_name RowSecurityDefaultForCmd
4614                                 RowSecurityDefaultToRole RowSecurityOptionalExpr
4615                                 RowSecurityOptionalWithCheck
4616                                 {
4617                                         CreatePolicyStmt *n = makeNode(CreatePolicyStmt);
4618                                         n->policy_name = $3;
4619                                         n->table = $5;
4620                                         n->cmd_name = $6;
4621                                         n->roles = $7;
4622                                         n->qual = $8;
4623                                         n->with_check = $9;
4624                                         $$ = (Node *) n;
4625                                 }
4626                 ;
4627
4628 AlterPolicyStmt:
4629                         ALTER POLICY name ON qualified_name RowSecurityOptionalToRole
4630                                 RowSecurityOptionalExpr RowSecurityOptionalWithCheck
4631                                 {
4632                                         AlterPolicyStmt *n = makeNode(AlterPolicyStmt);
4633                                         n->policy_name = $3;
4634                                         n->table = $5;
4635                                         n->roles = $6;
4636                                         n->qual = $7;
4637                                         n->with_check = $8;
4638                                         $$ = (Node *) n;
4639                                 }
4640                 ;
4641
4642 DropPolicyStmt:
4643                         DROP POLICY name ON any_name opt_drop_behavior
4644                                 {
4645                                         DropStmt *n = makeNode(DropStmt);
4646                                         n->removeType = OBJECT_POLICY;
4647                                         n->objects = list_make1(lappend($5, makeString($3)));
4648                                         n->arguments = NIL;
4649                                         n->behavior = $6;
4650                                         n->missing_ok = false;
4651                                         n->concurrent = false;
4652                                         $$ = (Node *) n;
4653                                 }
4654                         | DROP POLICY IF_P EXISTS name ON any_name opt_drop_behavior
4655                                 {
4656                                         DropStmt *n = makeNode(DropStmt);
4657                                         n->removeType = OBJECT_POLICY;
4658                                         n->objects = list_make1(lappend($7, makeString($5)));
4659                                         n->arguments = NIL;
4660                                         n->behavior = $8;
4661                                         n->missing_ok = true;
4662                                         n->concurrent = false;
4663                                         $$ = (Node *) n;
4664                                 }
4665                 ;
4666
4667 RowSecurityOptionalExpr:
4668                         USING '(' a_expr ')'    { $$ = $3; }
4669                         | /* EMPTY */                   { $$ = NULL; }
4670                 ;
4671
4672 RowSecurityOptionalWithCheck:
4673                         WITH CHECK '(' a_expr ')'               { $$ = $4; }
4674                         | /* EMPTY */                                   { $$ = NULL; }
4675                 ;
4676
4677 RowSecurityDefaultToRole:
4678                         TO role_list                    { $$ = $2; }
4679                         | /* EMPTY */                   { $$ = list_make1(makeRoleSpec(ROLESPEC_PUBLIC, -1)); }
4680                 ;
4681
4682 RowSecurityOptionalToRole:
4683                         TO role_list                    { $$ = $2; }
4684                         | /* EMPTY */                   { $$ = NULL; }
4685                 ;
4686
4687 RowSecurityDefaultForCmd:
4688                         FOR row_security_cmd    { $$ = $2; }
4689                         | /* EMPTY */                   { $$ = "all"; }
4690                 ;
4691
4692 row_security_cmd:
4693                         ALL                             { $$ = "all"; }
4694                 |       SELECT                  { $$ = "select"; }
4695                 |       INSERT                  { $$ = "insert"; }
4696                 |       UPDATE                  { $$ = "update"; }
4697                 |       DELETE_P                { $$ = "delete"; }
4698                 ;
4699
4700 /*****************************************************************************
4701  *
4702  *              QUERIES :
4703  *                              CREATE TRIGGER ...
4704  *                              DROP TRIGGER ...
4705  *
4706  *****************************************************************************/
4707
4708 CreateTrigStmt:
4709                         CREATE TRIGGER name TriggerActionTime TriggerEvents ON
4710                         qualified_name TriggerForSpec TriggerWhen
4711                         EXECUTE PROCEDURE func_name '(' TriggerFuncArgs ')'
4712                                 {
4713                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
4714                                         n->trigname = $3;
4715                                         n->relation = $7;
4716                                         n->funcname = $12;
4717                                         n->args = $14;
4718                                         n->row = $8;
4719                                         n->timing = $4;
4720                                         n->events = intVal(linitial($5));
4721                                         n->columns = (List *) lsecond($5);
4722                                         n->whenClause = $9;
4723                                         n->isconstraint  = FALSE;
4724                                         n->deferrable    = FALSE;
4725                                         n->initdeferred  = FALSE;
4726                                         n->constrrel = NULL;
4727                                         $$ = (Node *)n;
4728                                 }
4729                         | CREATE CONSTRAINT TRIGGER name AFTER TriggerEvents ON
4730                         qualified_name OptConstrFromTable ConstraintAttributeSpec
4731                         FOR EACH ROW TriggerWhen
4732                         EXECUTE PROCEDURE func_name '(' TriggerFuncArgs ')'
4733                                 {
4734                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
4735                                         n->trigname = $4;
4736                                         n->relation = $8;
4737                                         n->funcname = $17;
4738                                         n->args = $19;
4739                                         n->row = TRUE;
4740                                         n->timing = TRIGGER_TYPE_AFTER;
4741                                         n->events = intVal(linitial($6));
4742                                         n->columns = (List *) lsecond($6);
4743                                         n->whenClause = $14;
4744                                         n->isconstraint  = TRUE;
4745                                         processCASbits($10, @10, "TRIGGER",
4746                                                                    &n->deferrable, &n->initdeferred, NULL,
4747                                                                    NULL, yyscanner);
4748                                         n->constrrel = $9;
4749                                         $$ = (Node *)n;
4750                                 }
4751                 ;
4752
4753 TriggerActionTime:
4754                         BEFORE                                                          { $$ = TRIGGER_TYPE_BEFORE; }
4755                         | AFTER                                                         { $$ = TRIGGER_TYPE_AFTER; }
4756                         | INSTEAD OF                                            { $$ = TRIGGER_TYPE_INSTEAD; }
4757                 ;
4758
4759 TriggerEvents:
4760                         TriggerOneEvent
4761                                 { $$ = $1; }
4762                         | TriggerEvents OR TriggerOneEvent
4763                                 {
4764                                         int             events1 = intVal(linitial($1));
4765                                         int             events2 = intVal(linitial($3));
4766                                         List   *columns1 = (List *) lsecond($1);
4767                                         List   *columns2 = (List *) lsecond($3);
4768
4769                                         if (events1 & events2)
4770                                                 parser_yyerror("duplicate trigger events specified");
4771                                         /*
4772                                          * concat'ing the columns lists loses information about
4773                                          * which columns went with which event, but so long as
4774                                          * only UPDATE carries columns and we disallow multiple
4775                                          * UPDATE items, it doesn't matter.  Command execution
4776                                          * should just ignore the columns for non-UPDATE events.
4777                                          */
4778                                         $$ = list_make2(makeInteger(events1 | events2),
4779                                                                         list_concat(columns1, columns2));
4780                                 }
4781                 ;
4782
4783 TriggerOneEvent:
4784                         INSERT
4785                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_INSERT), NIL); }
4786                         | DELETE_P
4787                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_DELETE), NIL); }
4788                         | UPDATE
4789                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_UPDATE), NIL); }
4790                         | UPDATE OF columnList
4791                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_UPDATE), $3); }
4792                         | TRUNCATE
4793                                 { $$ = list_make2(makeInteger(TRIGGER_TYPE_TRUNCATE), NIL); }
4794                 ;
4795
4796 TriggerForSpec:
4797                         FOR TriggerForOptEach TriggerForType
4798                                 {
4799                                         $$ = $3;
4800                                 }
4801                         | /* EMPTY */
4802                                 {
4803                                         /*
4804                                          * If ROW/STATEMENT not specified, default to
4805                                          * STATEMENT, per SQL
4806                                          */
4807                                         $$ = FALSE;
4808                                 }
4809                 ;
4810
4811 TriggerForOptEach:
4812                         EACH                                                                    {}
4813                         | /*EMPTY*/                                                             {}
4814                 ;
4815
4816 TriggerForType:
4817                         ROW                                                                             { $$ = TRUE; }
4818                         | STATEMENT                                                             { $$ = FALSE; }
4819                 ;
4820
4821 TriggerWhen:
4822                         WHEN '(' a_expr ')'                                             { $$ = $3; }
4823                         | /*EMPTY*/                                                             { $$ = NULL; }
4824                 ;
4825
4826 TriggerFuncArgs:
4827                         TriggerFuncArg                                                  { $$ = list_make1($1); }
4828                         | TriggerFuncArgs ',' TriggerFuncArg    { $$ = lappend($1, $3); }
4829                         | /*EMPTY*/                                                             { $$ = NIL; }
4830                 ;
4831
4832 TriggerFuncArg:
4833                         Iconst
4834                                 {
4835                                         $$ = makeString(psprintf("%d", $1));
4836                                 }
4837                         | FCONST                                                                { $$ = makeString($1); }
4838                         | Sconst                                                                { $$ = makeString($1); }
4839                         | ColLabel                                                              { $$ = makeString($1); }
4840                 ;
4841
4842 OptConstrFromTable:
4843                         FROM qualified_name                                             { $$ = $2; }
4844                         | /*EMPTY*/                                                             { $$ = NULL; }
4845                 ;
4846
4847 ConstraintAttributeSpec:
4848                         /*EMPTY*/
4849                                 { $$ = 0; }
4850                         | ConstraintAttributeSpec ConstraintAttributeElem
4851                                 {
4852                                         /*
4853                                          * We must complain about conflicting options.
4854                                          * We could, but choose not to, complain about redundant
4855                                          * options (ie, where $2's bit is already set in $1).
4856                                          */
4857                                         int             newspec = $1 | $2;
4858
4859                                         /* special message for this case */
4860                                         if ((newspec & (CAS_NOT_DEFERRABLE | CAS_INITIALLY_DEFERRED)) == (CAS_NOT_DEFERRABLE | CAS_INITIALLY_DEFERRED))
4861                                                 ereport(ERROR,
4862                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
4863                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
4864                                                                  parser_errposition(@2)));
4865                                         /* generic message for other conflicts */
4866                                         if ((newspec & (CAS_NOT_DEFERRABLE | CAS_DEFERRABLE)) == (CAS_NOT_DEFERRABLE | CAS_DEFERRABLE) ||
4867                                                 (newspec & (CAS_INITIALLY_IMMEDIATE | CAS_INITIALLY_DEFERRED)) == (CAS_INITIALLY_IMMEDIATE | CAS_INITIALLY_DEFERRED))
4868                                                 ereport(ERROR,
4869                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
4870                                                                  errmsg("conflicting constraint properties"),
4871                                                                  parser_errposition(@2)));
4872                                         $$ = newspec;
4873                                 }
4874                 ;
4875
4876 ConstraintAttributeElem:
4877                         NOT DEFERRABLE                                  { $$ = CAS_NOT_DEFERRABLE; }
4878                         | DEFERRABLE                                    { $$ = CAS_DEFERRABLE; }
4879                         | INITIALLY IMMEDIATE                   { $$ = CAS_INITIALLY_IMMEDIATE; }
4880                         | INITIALLY DEFERRED                    { $$ = CAS_INITIALLY_DEFERRED; }
4881                         | NOT VALID                                             { $$ = CAS_NOT_VALID; }
4882                         | NO INHERIT                                    { $$ = CAS_NO_INHERIT; }
4883                 ;
4884
4885
4886 DropTrigStmt:
4887                         DROP TRIGGER name ON any_name opt_drop_behavior
4888                                 {
4889                                         DropStmt *n = makeNode(DropStmt);
4890                                         n->removeType = OBJECT_TRIGGER;
4891                                         n->objects = list_make1(lappend($5, makeString($3)));
4892                                         n->arguments = NIL;
4893                                         n->behavior = $6;
4894                                         n->missing_ok = false;
4895                                         n->concurrent = false;
4896                                         $$ = (Node *) n;
4897                                 }
4898                         | DROP TRIGGER IF_P EXISTS name ON any_name opt_drop_behavior
4899                                 {
4900                                         DropStmt *n = makeNode(DropStmt);
4901                                         n->removeType = OBJECT_TRIGGER;
4902                                         n->objects = list_make1(lappend($7, makeString($5)));
4903                                         n->arguments = NIL;
4904                                         n->behavior = $8;
4905                                         n->missing_ok = true;
4906                                         n->concurrent = false;
4907                                         $$ = (Node *) n;
4908                                 }
4909                 ;
4910
4911
4912 /*****************************************************************************
4913  *
4914  *              QUERIES :
4915  *                              CREATE EVENT TRIGGER ...
4916  *                              ALTER EVENT TRIGGER ...
4917  *
4918  *****************************************************************************/
4919
4920 CreateEventTrigStmt:
4921                         CREATE EVENT TRIGGER name ON ColLabel
4922                         EXECUTE PROCEDURE func_name '(' ')'
4923                                 {
4924                                         CreateEventTrigStmt *n = makeNode(CreateEventTrigStmt);
4925                                         n->trigname = $4;
4926                                         n->eventname = $6;
4927                                         n->whenclause = NULL;
4928                                         n->funcname = $9;
4929                                         $$ = (Node *)n;
4930                                 }
4931                   | CREATE EVENT TRIGGER name ON ColLabel
4932                         WHEN event_trigger_when_list
4933                         EXECUTE PROCEDURE func_name '(' ')'
4934                                 {
4935                                         CreateEventTrigStmt *n = makeNode(CreateEventTrigStmt);
4936                                         n->trigname = $4;
4937                                         n->eventname = $6;
4938                                         n->whenclause = $8;
4939                                         n->funcname = $11;
4940                                         $$ = (Node *)n;
4941                                 }
4942                 ;
4943
4944 event_trigger_when_list:
4945                   event_trigger_when_item
4946                         { $$ = list_make1($1); }
4947                 | event_trigger_when_list AND event_trigger_when_item
4948                         { $$ = lappend($1, $3); }
4949                 ;
4950
4951 event_trigger_when_item:
4952                 ColId IN_P '(' event_trigger_value_list ')'
4953                         { $$ = makeDefElem($1, (Node *) $4); }
4954                 ;
4955
4956 event_trigger_value_list:
4957                   SCONST
4958                         { $$ = list_make1(makeString($1)); }
4959                 | event_trigger_value_list ',' SCONST
4960                         { $$ = lappend($1, makeString($3)); }
4961                 ;
4962
4963 AlterEventTrigStmt:
4964                         ALTER EVENT TRIGGER name enable_trigger
4965                                 {
4966                                         AlterEventTrigStmt *n = makeNode(AlterEventTrigStmt);
4967                                         n->trigname = $4;
4968                                         n->tgenabled = $5;
4969                                         $$ = (Node *) n;
4970                                 }
4971                 ;
4972
4973 enable_trigger:
4974                         ENABLE_P                                        { $$ = TRIGGER_FIRES_ON_ORIGIN; }
4975                         | ENABLE_P REPLICA                      { $$ = TRIGGER_FIRES_ON_REPLICA; }
4976                         | ENABLE_P ALWAYS                       { $$ = TRIGGER_FIRES_ALWAYS; }
4977                         | DISABLE_P                                     { $$ = TRIGGER_DISABLED; }
4978                 ;
4979
4980 /*****************************************************************************
4981  *
4982  *              QUERIES :
4983  *                              CREATE ASSERTION ...
4984  *                              DROP ASSERTION ...
4985  *
4986  *****************************************************************************/
4987
4988 CreateAssertStmt:
4989                         CREATE ASSERTION name CHECK '(' a_expr ')'
4990                         ConstraintAttributeSpec
4991                                 {
4992                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
4993                                         n->trigname = $3;
4994                                         n->args = list_make1($6);
4995                                         n->isconstraint  = TRUE;
4996                                         processCASbits($8, @8, "ASSERTION",
4997                                                                    &n->deferrable, &n->initdeferred, NULL,
4998                                                                    NULL, yyscanner);
4999
5000                                         ereport(ERROR,
5001                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5002                                                          errmsg("CREATE ASSERTION is not yet implemented")));
5003
5004                                         $$ = (Node *)n;
5005                                 }
5006                 ;
5007
5008 DropAssertStmt:
5009                         DROP ASSERTION name opt_drop_behavior
5010                                 {
5011                                         DropStmt *n = makeNode(DropStmt);
5012                                         n->objects = NIL;
5013                                         n->arguments = NIL;
5014                                         n->behavior = $4;
5015                                         n->removeType = OBJECT_TRIGGER; /* XXX */
5016                                         ereport(ERROR,
5017                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5018                                                          errmsg("DROP ASSERTION is not yet implemented")));
5019                                         $$ = (Node *) n;
5020                                 }
5021                 ;
5022
5023
5024 /*****************************************************************************
5025  *
5026  *              QUERY :
5027  *                              define (aggregate,operator,type)
5028  *
5029  *****************************************************************************/
5030
5031 DefineStmt:
5032                         CREATE AGGREGATE func_name aggr_args definition
5033                                 {
5034                                         DefineStmt *n = makeNode(DefineStmt);
5035                                         n->kind = OBJECT_AGGREGATE;
5036                                         n->oldstyle = false;
5037                                         n->defnames = $3;
5038                                         n->args = $4;
5039                                         n->definition = $5;
5040                                         $$ = (Node *)n;
5041                                 }
5042                         | CREATE AGGREGATE func_name old_aggr_definition
5043                                 {
5044                                         /* old-style (pre-8.2) syntax for CREATE AGGREGATE */
5045                                         DefineStmt *n = makeNode(DefineStmt);
5046                                         n->kind = OBJECT_AGGREGATE;
5047                                         n->oldstyle = true;
5048                                         n->defnames = $3;
5049                                         n->args = NIL;
5050                                         n->definition = $4;
5051                                         $$ = (Node *)n;
5052                                 }
5053                         | CREATE OPERATOR any_operator definition
5054                                 {
5055                                         DefineStmt *n = makeNode(DefineStmt);
5056                                         n->kind = OBJECT_OPERATOR;
5057                                         n->oldstyle = false;
5058                                         n->defnames = $3;
5059                                         n->args = NIL;
5060                                         n->definition = $4;
5061                                         $$ = (Node *)n;
5062                                 }
5063                         | CREATE TYPE_P any_name definition
5064                                 {
5065                                         DefineStmt *n = makeNode(DefineStmt);
5066                                         n->kind = OBJECT_TYPE;
5067                                         n->oldstyle = false;
5068                                         n->defnames = $3;
5069                                         n->args = NIL;
5070                                         n->definition = $4;
5071                                         $$ = (Node *)n;
5072                                 }
5073                         | CREATE TYPE_P any_name
5074                                 {
5075                                         /* Shell type (identified by lack of definition) */
5076                                         DefineStmt *n = makeNode(DefineStmt);
5077                                         n->kind = OBJECT_TYPE;
5078                                         n->oldstyle = false;
5079                                         n->defnames = $3;
5080                                         n->args = NIL;
5081                                         n->definition = NIL;
5082                                         $$ = (Node *)n;
5083                                 }
5084                         | CREATE TYPE_P any_name AS '(' OptTableFuncElementList ')'
5085                                 {
5086                                         CompositeTypeStmt *n = makeNode(CompositeTypeStmt);
5087
5088                                         /* can't use qualified_name, sigh */
5089                                         n->typevar = makeRangeVarFromAnyName($3, @3, yyscanner);
5090                                         n->coldeflist = $6;
5091                                         $$ = (Node *)n;
5092                                 }
5093                         | CREATE TYPE_P any_name AS ENUM_P '(' opt_enum_val_list ')'
5094                                 {
5095                                         CreateEnumStmt *n = makeNode(CreateEnumStmt);
5096                                         n->typeName = $3;
5097                                         n->vals = $7;
5098                                         $$ = (Node *)n;
5099                                 }
5100                         | CREATE TYPE_P any_name AS RANGE definition
5101                                 {
5102                                         CreateRangeStmt *n = makeNode(CreateRangeStmt);
5103                                         n->typeName = $3;
5104                                         n->params       = $6;
5105                                         $$ = (Node *)n;
5106                                 }
5107                         | CREATE TEXT_P SEARCH PARSER any_name definition
5108                                 {
5109                                         DefineStmt *n = makeNode(DefineStmt);
5110                                         n->kind = OBJECT_TSPARSER;
5111                                         n->args = NIL;
5112                                         n->defnames = $5;
5113                                         n->definition = $6;
5114                                         $$ = (Node *)n;
5115                                 }
5116                         | CREATE TEXT_P SEARCH DICTIONARY any_name definition
5117                                 {
5118                                         DefineStmt *n = makeNode(DefineStmt);
5119                                         n->kind = OBJECT_TSDICTIONARY;
5120                                         n->args = NIL;
5121                                         n->defnames = $5;
5122                                         n->definition = $6;
5123                                         $$ = (Node *)n;
5124                                 }
5125                         | CREATE TEXT_P SEARCH TEMPLATE any_name definition
5126                                 {
5127                                         DefineStmt *n = makeNode(DefineStmt);
5128                                         n->kind = OBJECT_TSTEMPLATE;
5129                                         n->args = NIL;
5130                                         n->defnames = $5;
5131                                         n->definition = $6;
5132                                         $$ = (Node *)n;
5133                                 }
5134                         | CREATE TEXT_P SEARCH CONFIGURATION any_name definition
5135                                 {
5136                                         DefineStmt *n = makeNode(DefineStmt);
5137                                         n->kind = OBJECT_TSCONFIGURATION;
5138                                         n->args = NIL;
5139                                         n->defnames = $5;
5140                                         n->definition = $6;
5141                                         $$ = (Node *)n;
5142                                 }
5143                         | CREATE COLLATION any_name definition
5144                                 {
5145                                         DefineStmt *n = makeNode(DefineStmt);
5146                                         n->kind = OBJECT_COLLATION;
5147                                         n->args = NIL;
5148                                         n->defnames = $3;
5149                                         n->definition = $4;
5150                                         $$ = (Node *)n;
5151                                 }
5152                         | CREATE COLLATION any_name FROM any_name
5153                                 {
5154                                         DefineStmt *n = makeNode(DefineStmt);
5155                                         n->kind = OBJECT_COLLATION;
5156                                         n->args = NIL;
5157                                         n->defnames = $3;
5158                                         n->definition = list_make1(makeDefElem("from", (Node *) $5));
5159                                         $$ = (Node *)n;
5160                                 }
5161                 ;
5162
5163 definition: '(' def_list ')'                                            { $$ = $2; }
5164                 ;
5165
5166 def_list:       def_elem                                                                { $$ = list_make1($1); }
5167                         | def_list ',' def_elem                                 { $$ = lappend($1, $3); }
5168                 ;
5169
5170 def_elem:       ColLabel '=' def_arg
5171                                 {
5172                                         $$ = makeDefElem($1, (Node *) $3);
5173                                 }
5174                         | ColLabel
5175                                 {
5176                                         $$ = makeDefElem($1, NULL);
5177                                 }
5178                 ;
5179
5180 /* Note: any simple identifier will be returned as a type name! */
5181 def_arg:        func_type                                               { $$ = (Node *)$1; }
5182                         | reserved_keyword                              { $$ = (Node *)makeString(pstrdup($1)); }
5183                         | qual_all_Op                                   { $$ = (Node *)$1; }
5184                         | NumericOnly                                   { $$ = (Node *)$1; }
5185                         | Sconst                                                { $$ = (Node *)makeString($1); }
5186                 ;
5187
5188 old_aggr_definition: '(' old_aggr_list ')'                      { $$ = $2; }
5189                 ;
5190
5191 old_aggr_list: old_aggr_elem                                            { $$ = list_make1($1); }
5192                         | old_aggr_list ',' old_aggr_elem               { $$ = lappend($1, $3); }
5193                 ;
5194
5195 /*
5196  * Must use IDENT here to avoid reduce/reduce conflicts; fortunately none of
5197  * the item names needed in old aggregate definitions are likely to become
5198  * SQL keywords.
5199  */
5200 old_aggr_elem:  IDENT '=' def_arg
5201                                 {
5202                                         $$ = makeDefElem($1, (Node *)$3);
5203                                 }
5204                 ;
5205
5206 opt_enum_val_list:
5207                 enum_val_list                                                   { $$ = $1; }
5208                 | /*EMPTY*/                                                             { $$ = NIL; }
5209                 ;
5210
5211 enum_val_list:  Sconst
5212                                 { $$ = list_make1(makeString($1)); }
5213                         | enum_val_list ',' Sconst
5214                                 { $$ = lappend($1, makeString($3)); }
5215                 ;
5216
5217 /*****************************************************************************
5218  *
5219  *      ALTER TYPE enumtype ADD ...
5220  *
5221  *****************************************************************************/
5222
5223 AlterEnumStmt:
5224                 ALTER TYPE_P any_name ADD_P VALUE_P opt_if_not_exists Sconst
5225                         {
5226                                 AlterEnumStmt *n = makeNode(AlterEnumStmt);
5227                                 n->typeName = $3;
5228                                 n->newVal = $7;
5229                                 n->newValNeighbor = NULL;
5230                                 n->newValIsAfter = true;
5231                                 n->skipIfExists = $6;
5232                                 $$ = (Node *) n;
5233                         }
5234                  | ALTER TYPE_P any_name ADD_P VALUE_P opt_if_not_exists Sconst BEFORE Sconst
5235                         {
5236                                 AlterEnumStmt *n = makeNode(AlterEnumStmt);
5237                                 n->typeName = $3;
5238                                 n->newVal = $7;
5239                                 n->newValNeighbor = $9;
5240                                 n->newValIsAfter = false;
5241                                 n->skipIfExists = $6;
5242                                 $$ = (Node *) n;
5243                         }
5244                  | ALTER TYPE_P any_name ADD_P VALUE_P opt_if_not_exists Sconst AFTER Sconst
5245                         {
5246                                 AlterEnumStmt *n = makeNode(AlterEnumStmt);
5247                                 n->typeName = $3;
5248                                 n->newVal = $7;
5249                                 n->newValNeighbor = $9;
5250                                 n->newValIsAfter = true;
5251                                 n->skipIfExists = $6;
5252                                 $$ = (Node *) n;
5253                         }
5254                  ;
5255
5256 opt_if_not_exists: IF_P NOT EXISTS              { $$ = true; }
5257                 | /* empty */                          { $$ = false; }
5258                 ;
5259
5260
5261 /*****************************************************************************
5262  *
5263  *              QUERIES :
5264  *                              CREATE OPERATOR CLASS ...
5265  *                              CREATE OPERATOR FAMILY ...
5266  *                              ALTER OPERATOR FAMILY ...
5267  *                              DROP OPERATOR CLASS ...
5268  *                              DROP OPERATOR FAMILY ...
5269  *
5270  *****************************************************************************/
5271
5272 CreateOpClassStmt:
5273                         CREATE OPERATOR CLASS any_name opt_default FOR TYPE_P Typename
5274                         USING access_method opt_opfamily AS opclass_item_list
5275                                 {
5276                                         CreateOpClassStmt *n = makeNode(CreateOpClassStmt);
5277                                         n->opclassname = $4;
5278                                         n->isDefault = $5;
5279                                         n->datatype = $8;
5280                                         n->amname = $10;
5281                                         n->opfamilyname = $11;
5282                                         n->items = $13;
5283                                         $$ = (Node *) n;
5284                                 }
5285                 ;
5286
5287 opclass_item_list:
5288                         opclass_item                                                    { $$ = list_make1($1); }
5289                         | opclass_item_list ',' opclass_item    { $$ = lappend($1, $3); }
5290                 ;
5291
5292 opclass_item:
5293                         OPERATOR Iconst any_operator opclass_purpose opt_recheck
5294                                 {
5295                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
5296                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
5297                                         n->name = $3;
5298                                         n->args = NIL;
5299                                         n->number = $2;
5300                                         n->order_family = $4;
5301                                         $$ = (Node *) n;
5302                                 }
5303                         | OPERATOR Iconst any_operator oper_argtypes opclass_purpose
5304                           opt_recheck
5305                                 {
5306                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
5307                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
5308                                         n->name = $3;
5309                                         n->args = $4;
5310                                         n->number = $2;
5311                                         n->order_family = $5;
5312                                         $$ = (Node *) n;
5313                                 }
5314                         | FUNCTION Iconst func_name func_args
5315                                 {
5316                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
5317                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
5318                                         n->name = $3;
5319                                         n->args = extractArgTypes($4);
5320                                         n->number = $2;
5321                                         $$ = (Node *) n;
5322                                 }
5323                         | FUNCTION Iconst '(' type_list ')' func_name func_args
5324                                 {
5325                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
5326                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
5327                                         n->name = $6;
5328                                         n->args = extractArgTypes($7);
5329                                         n->number = $2;
5330                                         n->class_args = $4;
5331                                         $$ = (Node *) n;
5332                                 }
5333                         | STORAGE Typename
5334                                 {
5335                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
5336                                         n->itemtype = OPCLASS_ITEM_STORAGETYPE;
5337                                         n->storedtype = $2;
5338                                         $$ = (Node *) n;
5339                                 }
5340                 ;
5341
5342 opt_default:    DEFAULT                                         { $$ = TRUE; }
5343                         | /*EMPTY*/                                             { $$ = FALSE; }
5344                 ;
5345
5346 opt_opfamily:   FAMILY any_name                         { $$ = $2; }
5347                         | /*EMPTY*/                                             { $$ = NIL; }
5348                 ;
5349
5350 opclass_purpose: FOR SEARCH                                     { $$ = NIL; }
5351                         | FOR ORDER BY any_name                 { $$ = $4; }
5352                         | /*EMPTY*/                                             { $$ = NIL; }
5353                 ;
5354
5355 opt_recheck:    RECHECK
5356                                 {
5357                                         /*
5358                                          * RECHECK no longer does anything in opclass definitions,
5359                                          * but we still accept it to ease porting of old database
5360                                          * dumps.
5361                                          */
5362                                         ereport(NOTICE,
5363                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5364                                                          errmsg("RECHECK is no longer required"),
5365                                                          errhint("Update your data type."),
5366                                                          parser_errposition(@1)));
5367                                         $$ = TRUE;
5368                                 }
5369                         | /*EMPTY*/                                             { $$ = FALSE; }
5370                 ;
5371
5372
5373 CreateOpFamilyStmt:
5374                         CREATE OPERATOR FAMILY any_name USING access_method
5375                                 {
5376                                         CreateOpFamilyStmt *n = makeNode(CreateOpFamilyStmt);
5377                                         n->opfamilyname = $4;
5378                                         n->amname = $6;
5379                                         $$ = (Node *) n;
5380                                 }
5381                 ;
5382
5383 AlterOpFamilyStmt:
5384                         ALTER OPERATOR FAMILY any_name USING access_method ADD_P opclass_item_list
5385                                 {
5386                                         AlterOpFamilyStmt *n = makeNode(AlterOpFamilyStmt);
5387                                         n->opfamilyname = $4;
5388                                         n->amname = $6;
5389                                         n->isDrop = false;
5390                                         n->items = $8;
5391                                         $$ = (Node *) n;
5392                                 }
5393                         | ALTER OPERATOR FAMILY any_name USING access_method DROP opclass_drop_list
5394                                 {
5395                                         AlterOpFamilyStmt *n = makeNode(AlterOpFamilyStmt);
5396                                         n->opfamilyname = $4;
5397                                         n->amname = $6;
5398                                         n->isDrop = true;
5399                                         n->items = $8;
5400                                         $$ = (Node *) n;
5401                                 }
5402                 ;
5403
5404 opclass_drop_list:
5405                         opclass_drop                                                    { $$ = list_make1($1); }
5406                         | opclass_drop_list ',' opclass_drop    { $$ = lappend($1, $3); }
5407                 ;
5408
5409 opclass_drop:
5410                         OPERATOR Iconst '(' type_list ')'
5411                                 {
5412                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
5413                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
5414                                         n->number = $2;
5415                                         n->args = $4;
5416                                         $$ = (Node *) n;
5417                                 }
5418                         | FUNCTION Iconst '(' type_list ')'
5419                                 {
5420                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
5421                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
5422                                         n->number = $2;
5423                                         n->args = $4;
5424                                         $$ = (Node *) n;
5425                                 }
5426                 ;
5427
5428
5429 DropOpClassStmt:
5430                         DROP OPERATOR CLASS any_name USING access_method opt_drop_behavior
5431                                 {
5432                                         DropStmt *n = makeNode(DropStmt);
5433                                         n->objects = list_make1(lcons(makeString($6), $4));
5434                                         n->removeType = OBJECT_OPCLASS;
5435                                         n->behavior = $7;
5436                                         n->missing_ok = false;
5437                                         n->concurrent = false;
5438                                         $$ = (Node *) n;
5439                                 }
5440                         | DROP OPERATOR CLASS IF_P EXISTS any_name USING access_method opt_drop_behavior
5441                                 {
5442                                         DropStmt *n = makeNode(DropStmt);
5443                                         n->objects = list_make1(lcons(makeString($8), $6));
5444                                         n->removeType = OBJECT_OPCLASS;
5445                                         n->behavior = $9;
5446                                         n->missing_ok = true;
5447                                         n->concurrent = false;
5448                                         $$ = (Node *) n;
5449                                 }
5450                 ;
5451
5452 DropOpFamilyStmt:
5453                         DROP OPERATOR FAMILY any_name USING access_method opt_drop_behavior
5454                                 {
5455                                         DropStmt *n = makeNode(DropStmt);
5456                                         n->objects = list_make1(lcons(makeString($6), $4));
5457                                         n->removeType = OBJECT_OPFAMILY;
5458                                         n->behavior = $7;
5459                                         n->missing_ok = false;
5460                                         n->concurrent = false;
5461                                         $$ = (Node *) n;
5462                                 }
5463                         | DROP OPERATOR FAMILY IF_P EXISTS any_name USING access_method opt_drop_behavior
5464                                 {
5465                                         DropStmt *n = makeNode(DropStmt);
5466                                         n->objects = list_make1(lcons(makeString($8), $6));
5467                                         n->removeType = OBJECT_OPFAMILY;
5468                                         n->behavior = $9;
5469                                         n->missing_ok = true;
5470                                         n->concurrent = false;
5471                                         $$ = (Node *) n;
5472                                 }
5473                 ;
5474
5475
5476 /*****************************************************************************
5477  *
5478  *              QUERY:
5479  *
5480  *              DROP OWNED BY username [, username ...] [ RESTRICT | CASCADE ]
5481  *              REASSIGN OWNED BY username [, username ...] TO username
5482  *
5483  *****************************************************************************/
5484 DropOwnedStmt:
5485                         DROP OWNED BY role_list opt_drop_behavior
5486                                 {
5487                                         DropOwnedStmt *n = makeNode(DropOwnedStmt);
5488                                         n->roles = $4;
5489                                         n->behavior = $5;
5490                                         $$ = (Node *)n;
5491                                 }
5492                 ;
5493
5494 ReassignOwnedStmt:
5495                         REASSIGN OWNED BY role_list TO RoleSpec
5496                                 {
5497                                         ReassignOwnedStmt *n = makeNode(ReassignOwnedStmt);
5498                                         n->roles = $4;
5499                                         n->newrole = $6;
5500                                         $$ = (Node *)n;
5501                                 }
5502                 ;
5503
5504 /*****************************************************************************
5505  *
5506  *              QUERY:
5507  *
5508  *              DROP itemtype [ IF EXISTS ] itemname [, itemname ...]
5509  *           [ RESTRICT | CASCADE ]
5510  *
5511  *****************************************************************************/
5512
5513 DropStmt:       DROP drop_type IF_P EXISTS any_name_list opt_drop_behavior
5514                                 {
5515                                         DropStmt *n = makeNode(DropStmt);
5516                                         n->removeType = $2;
5517                                         n->missing_ok = TRUE;
5518                                         n->objects = $5;
5519                                         n->arguments = NIL;
5520                                         n->behavior = $6;
5521                                         n->concurrent = false;
5522                                         $$ = (Node *)n;
5523                                 }
5524                         | DROP drop_type any_name_list opt_drop_behavior
5525                                 {
5526                                         DropStmt *n = makeNode(DropStmt);
5527                                         n->removeType = $2;
5528                                         n->missing_ok = FALSE;
5529                                         n->objects = $3;
5530                                         n->arguments = NIL;
5531                                         n->behavior = $4;
5532                                         n->concurrent = false;
5533                                         $$ = (Node *)n;
5534                                 }
5535                         | DROP TYPE_P type_name_list opt_drop_behavior
5536                                 {
5537                                         DropStmt *n = makeNode(DropStmt);
5538                                         n->removeType = OBJECT_TYPE;
5539                                         n->missing_ok = FALSE;
5540                                         n->objects = $3;
5541                                         n->behavior = $4;
5542                                         n->concurrent = false;
5543                                         $$ = (Node *) n;
5544                                 }
5545                         | DROP TYPE_P IF_P EXISTS type_name_list opt_drop_behavior
5546                                 {
5547                                         DropStmt *n = makeNode(DropStmt);
5548                                         n->removeType = OBJECT_TYPE;
5549                                         n->missing_ok = TRUE;
5550                                         n->objects = $5;
5551                                         n->behavior = $6;
5552                                         n->concurrent = false;
5553                                         $$ = (Node *) n;
5554                                 }
5555                         | DROP DOMAIN_P type_name_list opt_drop_behavior
5556                                 {
5557                                         DropStmt *n = makeNode(DropStmt);
5558                                         n->removeType = OBJECT_DOMAIN;
5559                                         n->missing_ok = FALSE;
5560                                         n->objects = $3;
5561                                         n->behavior = $4;
5562                                         n->concurrent = false;
5563                                         $$ = (Node *) n;
5564                                 }
5565                         | DROP DOMAIN_P IF_P EXISTS type_name_list opt_drop_behavior
5566                                 {
5567                                         DropStmt *n = makeNode(DropStmt);
5568                                         n->removeType = OBJECT_DOMAIN;
5569                                         n->missing_ok = TRUE;
5570                                         n->objects = $5;
5571                                         n->behavior = $6;
5572                                         n->concurrent = false;
5573                                         $$ = (Node *) n;
5574                                 }
5575                         | DROP INDEX CONCURRENTLY any_name_list opt_drop_behavior
5576                                 {
5577                                         DropStmt *n = makeNode(DropStmt);
5578                                         n->removeType = OBJECT_INDEX;
5579                                         n->missing_ok = FALSE;
5580                                         n->objects = $4;
5581                                         n->arguments = NIL;
5582                                         n->behavior = $5;
5583                                         n->concurrent = true;
5584                                         $$ = (Node *)n;
5585                                 }
5586                         | DROP INDEX CONCURRENTLY IF_P EXISTS any_name_list opt_drop_behavior
5587                                 {
5588                                         DropStmt *n = makeNode(DropStmt);
5589                                         n->removeType = OBJECT_INDEX;
5590                                         n->missing_ok = TRUE;
5591                                         n->objects = $6;
5592                                         n->arguments = NIL;
5593                                         n->behavior = $7;
5594                                         n->concurrent = true;
5595                                         $$ = (Node *)n;
5596                                 }
5597                 ;
5598
5599
5600 drop_type:      TABLE                                                                   { $$ = OBJECT_TABLE; }
5601                         | SEQUENCE                                                              { $$ = OBJECT_SEQUENCE; }
5602                         | VIEW                                                                  { $$ = OBJECT_VIEW; }
5603                         | MATERIALIZED VIEW                                             { $$ = OBJECT_MATVIEW; }
5604                         | INDEX                                                                 { $$ = OBJECT_INDEX; }
5605                         | FOREIGN TABLE                                                 { $$ = OBJECT_FOREIGN_TABLE; }
5606                         | EVENT TRIGGER                                                 { $$ = OBJECT_EVENT_TRIGGER; }
5607                         | COLLATION                                                             { $$ = OBJECT_COLLATION; }
5608                         | CONVERSION_P                                                  { $$ = OBJECT_CONVERSION; }
5609                         | SCHEMA                                                                { $$ = OBJECT_SCHEMA; }
5610                         | EXTENSION                                                             { $$ = OBJECT_EXTENSION; }
5611                         | TEXT_P SEARCH PARSER                                  { $$ = OBJECT_TSPARSER; }
5612                         | TEXT_P SEARCH DICTIONARY                              { $$ = OBJECT_TSDICTIONARY; }
5613                         | TEXT_P SEARCH TEMPLATE                                { $$ = OBJECT_TSTEMPLATE; }
5614                         | TEXT_P SEARCH CONFIGURATION                   { $$ = OBJECT_TSCONFIGURATION; }
5615                 ;
5616
5617 any_name_list:
5618                         any_name                                                                { $$ = list_make1($1); }
5619                         | any_name_list ',' any_name                    { $$ = lappend($1, $3); }
5620                 ;
5621
5622 any_name:       ColId                                           { $$ = list_make1(makeString($1)); }
5623                         | ColId attrs                           { $$ = lcons(makeString($1), $2); }
5624                 ;
5625
5626 attrs:          '.' attr_name
5627                                         { $$ = list_make1(makeString($2)); }
5628                         | attrs '.' attr_name
5629                                         { $$ = lappend($1, makeString($3)); }
5630                 ;
5631
5632 type_name_list:
5633                         Typename                                                                { $$ = list_make1(list_make1($1)); }
5634                         | type_name_list ',' Typename                   { $$ = lappend($1, list_make1($3)); }
5635
5636 /*****************************************************************************
5637  *
5638  *              QUERY:
5639  *                              truncate table relname1, relname2, ...
5640  *
5641  *****************************************************************************/
5642
5643 TruncateStmt:
5644                         TRUNCATE opt_table relation_expr_list opt_restart_seqs opt_drop_behavior
5645                                 {
5646                                         TruncateStmt *n = makeNode(TruncateStmt);
5647                                         n->relations = $3;
5648                                         n->restart_seqs = $4;
5649                                         n->behavior = $5;
5650                                         $$ = (Node *)n;
5651                                 }
5652                 ;
5653
5654 opt_restart_seqs:
5655                         CONTINUE_P IDENTITY_P           { $$ = false; }
5656                         | RESTART IDENTITY_P            { $$ = true; }
5657                         | /* EMPTY */                           { $$ = false; }
5658                 ;
5659
5660 /*****************************************************************************
5661  *
5662  *      The COMMENT ON statement can take different forms based upon the type of
5663  *      the object associated with the comment. The form of the statement is:
5664  *
5665  *      COMMENT ON [ [ CONVERSION | COLLATION | DATABASE | DOMAIN |
5666  *                 EXTENSION | EVENT TRIGGER | FOREIGN DATA WRAPPER |
5667  *                 FOREIGN TABLE | INDEX | [PROCEDURAL] LANGUAGE |
5668  *                 MATERIALIZED VIEW | POLICY | ROLE | SCHEMA | SEQUENCE |
5669  *                 SERVER | TABLE | TABLESPACE |
5670  *                 TEXT SEARCH CONFIGURATION | TEXT SEARCH DICTIONARY |
5671  *                 TEXT SEARCH PARSER | TEXT SEARCH TEMPLATE | TYPE |
5672  *                 VIEW] <objname> |
5673  *                               AGGREGATE <aggname> (arg1, ...) |
5674  *                               CAST (<src type> AS <dst type>) |
5675  *                               COLUMN <relname>.<colname> |
5676  *                               CONSTRAINT <constraintname> ON <relname> |
5677  *                               CONSTRAINT <constraintname> ON DOMAIN <domainname> |
5678  *                               FUNCTION <funcname> (arg1, arg2, ...) |
5679  *                               LARGE OBJECT <oid> |
5680  *                               OPERATOR <op> (leftoperand_typ, rightoperand_typ) |
5681  *                               OPERATOR CLASS <name> USING <access-method> |
5682  *                               OPERATOR FAMILY <name> USING <access-method> |
5683  *                               RULE <rulename> ON <relname> |
5684  *                               TRIGGER <triggername> ON <relname> ]
5685  *                         IS 'text'
5686  *
5687  *****************************************************************************/
5688
5689 CommentStmt:
5690                         COMMENT ON comment_type any_name IS comment_text
5691                                 {
5692                                         CommentStmt *n = makeNode(CommentStmt);
5693                                         n->objtype = $3;
5694                                         n->objname = $4;
5695                                         n->objargs = NIL;
5696                                         n->comment = $6;
5697                                         $$ = (Node *) n;
5698                                 }
5699                         | COMMENT ON TYPE_P Typename IS comment_text
5700                                 {
5701                                         CommentStmt *n = makeNode(CommentStmt);
5702                                         n->objtype = OBJECT_TYPE;
5703                                         n->objname = list_make1($4);
5704                                         n->objargs = NIL;
5705                                         n->comment = $6;
5706                                         $$ = (Node *) n;
5707                                 }
5708                         | COMMENT ON DOMAIN_P Typename IS comment_text
5709                                 {
5710                                         CommentStmt *n = makeNode(CommentStmt);
5711                                         n->objtype = OBJECT_DOMAIN;
5712                                         n->objname = list_make1($4);
5713                                         n->objargs = NIL;
5714                                         n->comment = $6;
5715                                         $$ = (Node *) n;
5716                                 }
5717                         | COMMENT ON AGGREGATE func_name aggr_args IS comment_text
5718                                 {
5719                                         CommentStmt *n = makeNode(CommentStmt);
5720                                         n->objtype = OBJECT_AGGREGATE;
5721                                         n->objname = $4;
5722                                         n->objargs = extractAggrArgTypes($5);
5723                                         n->comment = $7;
5724                                         $$ = (Node *) n;
5725                                 }
5726                         | COMMENT ON FUNCTION func_name func_args IS comment_text
5727                                 {
5728                                         CommentStmt *n = makeNode(CommentStmt);
5729                                         n->objtype = OBJECT_FUNCTION;
5730                                         n->objname = $4;
5731                                         n->objargs = extractArgTypes($5);
5732                                         n->comment = $7;
5733                                         $$ = (Node *) n;
5734                                 }
5735                         | COMMENT ON OPERATOR any_operator oper_argtypes IS comment_text
5736                                 {
5737                                         CommentStmt *n = makeNode(CommentStmt);
5738                                         n->objtype = OBJECT_OPERATOR;
5739                                         n->objname = $4;
5740                                         n->objargs = $5;
5741                                         n->comment = $7;
5742                                         $$ = (Node *) n;
5743                                 }
5744                         | COMMENT ON CONSTRAINT name ON any_name IS comment_text
5745                                 {
5746                                         CommentStmt *n = makeNode(CommentStmt);
5747                                         n->objtype = OBJECT_TABCONSTRAINT;
5748                                         n->objname = lappend($6, makeString($4));
5749                                         n->objargs = NIL;
5750                                         n->comment = $8;
5751                                         $$ = (Node *) n;
5752                                 }
5753                         | COMMENT ON CONSTRAINT name ON DOMAIN_P any_name IS comment_text
5754                                 {
5755                                         CommentStmt *n = makeNode(CommentStmt);
5756                                         n->objtype = OBJECT_DOMCONSTRAINT;
5757                                         /*
5758                                          * should use Typename not any_name in the production, but
5759                                          * there's a shift/reduce conflict if we do that, so fix it
5760                                          * up here.
5761                                          */
5762                                         n->objname = list_make1(makeTypeNameFromNameList($7));
5763                                         n->objargs = list_make1(makeString($4));
5764                                         n->comment = $9;
5765                                         $$ = (Node *) n;
5766                                 }
5767                         | COMMENT ON POLICY name ON any_name IS comment_text
5768                                 {
5769                                         CommentStmt *n = makeNode(CommentStmt);
5770                                         n->objtype = OBJECT_POLICY;
5771                                         n->objname = lappend($6, makeString($4));
5772                                         n->objargs = NIL;
5773                                         n->comment = $8;
5774                                         $$ = (Node *) n;
5775                                 }
5776                         | COMMENT ON RULE name ON any_name IS comment_text
5777                                 {
5778                                         CommentStmt *n = makeNode(CommentStmt);
5779                                         n->objtype = OBJECT_RULE;
5780                                         n->objname = lappend($6, makeString($4));
5781                                         n->objargs = NIL;
5782                                         n->comment = $8;
5783                                         $$ = (Node *) n;
5784                                 }
5785                         | COMMENT ON RULE name IS comment_text
5786                                 {
5787                                         /* Obsolete syntax supported for awhile for compatibility */
5788                                         CommentStmt *n = makeNode(CommentStmt);
5789                                         n->objtype = OBJECT_RULE;
5790                                         n->objname = list_make1(makeString($4));
5791                                         n->objargs = NIL;
5792                                         n->comment = $6;
5793                                         $$ = (Node *) n;
5794                                 }
5795                         | COMMENT ON TRANSFORM FOR Typename LANGUAGE name IS comment_text
5796                                 {
5797                                         CommentStmt *n = makeNode(CommentStmt);
5798                                         n->objtype = OBJECT_TRANSFORM;
5799                                         n->objname = list_make1($5);
5800                                         n->objargs = list_make1(makeString($7));
5801                                         n->comment = $9;
5802                                         $$ = (Node *) n;
5803                                 }
5804                         | COMMENT ON TRIGGER name ON any_name IS comment_text
5805                                 {
5806                                         CommentStmt *n = makeNode(CommentStmt);
5807                                         n->objtype = OBJECT_TRIGGER;
5808                                         n->objname = lappend($6, makeString($4));
5809                                         n->objargs = NIL;
5810                                         n->comment = $8;
5811                                         $$ = (Node *) n;
5812                                 }
5813                         | COMMENT ON OPERATOR CLASS any_name USING access_method IS comment_text
5814                                 {
5815                                         CommentStmt *n = makeNode(CommentStmt);
5816                                         n->objtype = OBJECT_OPCLASS;
5817                                         n->objname = lcons(makeString($7), $5);
5818                                         n->comment = $9;
5819                                         $$ = (Node *) n;
5820                                 }
5821                         | COMMENT ON OPERATOR FAMILY any_name USING access_method IS comment_text
5822                                 {
5823                                         CommentStmt *n = makeNode(CommentStmt);
5824                                         n->objtype = OBJECT_OPFAMILY;
5825                                         n->objname = lcons(makeString($7), $5);
5826                                         n->objargs = NIL;
5827                                         n->comment = $9;
5828                                         $$ = (Node *) n;
5829                                 }
5830                         | COMMENT ON LARGE_P OBJECT_P NumericOnly IS comment_text
5831                                 {
5832                                         CommentStmt *n = makeNode(CommentStmt);
5833                                         n->objtype = OBJECT_LARGEOBJECT;
5834                                         n->objname = list_make1($5);
5835                                         n->objargs = NIL;
5836                                         n->comment = $7;
5837                                         $$ = (Node *) n;
5838                                 }
5839                         | COMMENT ON CAST '(' Typename AS Typename ')' IS comment_text
5840                                 {
5841                                         CommentStmt *n = makeNode(CommentStmt);
5842                                         n->objtype = OBJECT_CAST;
5843                                         n->objname = list_make1($5);
5844                                         n->objargs = list_make1($7);
5845                                         n->comment = $10;
5846                                         $$ = (Node *) n;
5847                                 }
5848                         | COMMENT ON opt_procedural LANGUAGE any_name IS comment_text
5849                                 {
5850                                         CommentStmt *n = makeNode(CommentStmt);
5851                                         n->objtype = OBJECT_LANGUAGE;
5852                                         n->objname = $5;
5853                                         n->objargs = NIL;
5854                                         n->comment = $7;
5855                                         $$ = (Node *) n;
5856                                 }
5857                 ;
5858
5859 comment_type:
5860                         COLUMN                                                          { $$ = OBJECT_COLUMN; }
5861                         | DATABASE                                                      { $$ = OBJECT_DATABASE; }
5862                         | SCHEMA                                                        { $$ = OBJECT_SCHEMA; }
5863                         | INDEX                                                         { $$ = OBJECT_INDEX; }
5864                         | SEQUENCE                                                      { $$ = OBJECT_SEQUENCE; }
5865                         | TABLE                                                         { $$ = OBJECT_TABLE; }
5866                         | VIEW                                                          { $$ = OBJECT_VIEW; }
5867                         | MATERIALIZED VIEW                                     { $$ = OBJECT_MATVIEW; }
5868                         | COLLATION                                                     { $$ = OBJECT_COLLATION; }
5869                         | CONVERSION_P                                          { $$ = OBJECT_CONVERSION; }
5870                         | TABLESPACE                                            { $$ = OBJECT_TABLESPACE; }
5871                         | EXTENSION                                                     { $$ = OBJECT_EXTENSION; }
5872                         | ROLE                                                          { $$ = OBJECT_ROLE; }
5873                         | FOREIGN TABLE                                         { $$ = OBJECT_FOREIGN_TABLE; }
5874                         | SERVER                                                        { $$ = OBJECT_FOREIGN_SERVER; }
5875                         | FOREIGN DATA_P WRAPPER                        { $$ = OBJECT_FDW; }
5876                         | EVENT TRIGGER                                         { $$ = OBJECT_EVENT_TRIGGER; }
5877                         | TEXT_P SEARCH CONFIGURATION           { $$ = OBJECT_TSCONFIGURATION; }
5878                         | TEXT_P SEARCH DICTIONARY                      { $$ = OBJECT_TSDICTIONARY; }
5879                         | TEXT_P SEARCH PARSER                          { $$ = OBJECT_TSPARSER; }
5880                         | TEXT_P SEARCH TEMPLATE                        { $$ = OBJECT_TSTEMPLATE; }
5881                 ;
5882
5883 comment_text:
5884                         Sconst                                                          { $$ = $1; }
5885                         | NULL_P                                                        { $$ = NULL; }
5886                 ;
5887
5888
5889 /*****************************************************************************
5890  *
5891  *  SECURITY LABEL [FOR <provider>] ON <object> IS <label>
5892  *
5893  *  As with COMMENT ON, <object> can refer to various types of database
5894  *  objects (e.g. TABLE, COLUMN, etc.).
5895  *
5896  *****************************************************************************/
5897
5898 SecLabelStmt:
5899                         SECURITY LABEL opt_provider ON security_label_type any_name
5900                         IS security_label
5901                                 {
5902                                         SecLabelStmt *n = makeNode(SecLabelStmt);
5903                                         n->provider = $3;
5904                                         n->objtype = $5;
5905                                         n->objname = $6;
5906                                         n->objargs = NIL;
5907                                         n->label = $8;
5908                                         $$ = (Node *) n;
5909                                 }
5910                         | SECURITY LABEL opt_provider ON TYPE_P Typename
5911                           IS security_label
5912                                 {
5913                                         SecLabelStmt *n = makeNode(SecLabelStmt);
5914                                         n->provider = $3;
5915                                         n->objtype = OBJECT_TYPE;
5916                                         n->objname = list_make1($6);
5917                                         n->objargs = NIL;
5918                                         n->label = $8;
5919                                         $$ = (Node *) n;
5920                                 }
5921                         | SECURITY LABEL opt_provider ON DOMAIN_P Typename
5922                           IS security_label
5923                                 {
5924                                         SecLabelStmt *n = makeNode(SecLabelStmt);
5925                                         n->provider = $3;
5926                                         n->objtype = OBJECT_TYPE;
5927                                         n->objname = list_make1($6);
5928                                         n->objargs = NIL;
5929                                         n->label = $8;
5930                                         $$ = (Node *) n;
5931                                 }
5932                         | SECURITY LABEL opt_provider ON AGGREGATE func_name aggr_args
5933                           IS security_label
5934                                 {
5935                                         SecLabelStmt *n = makeNode(SecLabelStmt);
5936                                         n->provider = $3;
5937                                         n->objtype = OBJECT_AGGREGATE;
5938                                         n->objname = $6;
5939                                         n->objargs = extractAggrArgTypes($7);
5940                                         n->label = $9;
5941                                         $$ = (Node *) n;
5942                                 }
5943                         | SECURITY LABEL opt_provider ON FUNCTION func_name func_args
5944                           IS security_label
5945                                 {
5946                                         SecLabelStmt *n = makeNode(SecLabelStmt);
5947                                         n->provider = $3;
5948                                         n->objtype = OBJECT_FUNCTION;
5949                                         n->objname = $6;
5950                                         n->objargs = extractArgTypes($7);
5951                                         n->label = $9;
5952                                         $$ = (Node *) n;
5953                                 }
5954                         | SECURITY LABEL opt_provider ON LARGE_P OBJECT_P NumericOnly
5955                           IS security_label
5956                                 {
5957                                         SecLabelStmt *n = makeNode(SecLabelStmt);
5958                                         n->provider = $3;
5959                                         n->objtype = OBJECT_LARGEOBJECT;
5960                                         n->objname = list_make1($7);
5961                                         n->objargs = NIL;
5962                                         n->label = $9;
5963                                         $$ = (Node *) n;
5964                                 }
5965                         | SECURITY LABEL opt_provider ON opt_procedural LANGUAGE any_name
5966                           IS security_label
5967                                 {
5968                                         SecLabelStmt *n = makeNode(SecLabelStmt);
5969                                         n->provider = $3;
5970                                         n->objtype = OBJECT_LANGUAGE;
5971                                         n->objname = $7;
5972                                         n->objargs = NIL;
5973                                         n->label = $9;
5974                                         $$ = (Node *) n;
5975                                 }
5976                 ;
5977
5978 opt_provider:   FOR NonReservedWord_or_Sconst   { $$ = $2; }
5979                                 | /* empty */                                   { $$ = NULL; }
5980                 ;
5981
5982 security_label_type:
5983                         COLUMN                                                          { $$ = OBJECT_COLUMN; }
5984                         | DATABASE                                                      { $$ = OBJECT_DATABASE; }
5985                         | EVENT TRIGGER                                         { $$ = OBJECT_EVENT_TRIGGER; }
5986                         | FOREIGN TABLE                                         { $$ = OBJECT_FOREIGN_TABLE; }
5987                         | SCHEMA                                                        { $$ = OBJECT_SCHEMA; }
5988                         | SEQUENCE                                                      { $$ = OBJECT_SEQUENCE; }
5989                         | TABLE                                                         { $$ = OBJECT_TABLE; }
5990                         | ROLE                                                          { $$ = OBJECT_ROLE; }
5991                         | TABLESPACE                                            { $$ = OBJECT_TABLESPACE; }
5992                         | VIEW                                                          { $$ = OBJECT_VIEW; }
5993                         | MATERIALIZED VIEW                                     { $$ = OBJECT_MATVIEW; }
5994                 ;
5995
5996 security_label: Sconst                          { $$ = $1; }
5997                                 | NULL_P                        { $$ = NULL; }
5998                 ;
5999
6000 /*****************************************************************************
6001  *
6002  *              QUERY:
6003  *                      fetch/move
6004  *
6005  *****************************************************************************/
6006
6007 FetchStmt:      FETCH fetch_args
6008                                 {
6009                                         FetchStmt *n = (FetchStmt *) $2;
6010                                         n->ismove = FALSE;
6011                                         $$ = (Node *)n;
6012                                 }
6013                         | MOVE fetch_args
6014                                 {
6015                                         FetchStmt *n = (FetchStmt *) $2;
6016                                         n->ismove = TRUE;
6017                                         $$ = (Node *)n;
6018                                 }
6019                 ;
6020
6021 fetch_args:     cursor_name
6022                                 {
6023                                         FetchStmt *n = makeNode(FetchStmt);
6024                                         n->portalname = $1;
6025                                         n->direction = FETCH_FORWARD;
6026                                         n->howMany = 1;
6027                                         $$ = (Node *)n;
6028                                 }
6029                         | from_in cursor_name
6030                                 {
6031                                         FetchStmt *n = makeNode(FetchStmt);
6032                                         n->portalname = $2;
6033                                         n->direction = FETCH_FORWARD;
6034                                         n->howMany = 1;
6035                                         $$ = (Node *)n;
6036                                 }
6037                         | NEXT opt_from_in cursor_name
6038                                 {
6039                                         FetchStmt *n = makeNode(FetchStmt);
6040                                         n->portalname = $3;
6041                                         n->direction = FETCH_FORWARD;
6042                                         n->howMany = 1;
6043                                         $$ = (Node *)n;
6044                                 }
6045                         | PRIOR opt_from_in cursor_name
6046                                 {
6047                                         FetchStmt *n = makeNode(FetchStmt);
6048                                         n->portalname = $3;
6049                                         n->direction = FETCH_BACKWARD;
6050                                         n->howMany = 1;
6051                                         $$ = (Node *)n;
6052                                 }
6053                         | FIRST_P opt_from_in cursor_name
6054                                 {
6055                                         FetchStmt *n = makeNode(FetchStmt);
6056                                         n->portalname = $3;
6057                                         n->direction = FETCH_ABSOLUTE;
6058                                         n->howMany = 1;
6059                                         $$ = (Node *)n;
6060                                 }
6061                         | LAST_P opt_from_in cursor_name
6062                                 {
6063                                         FetchStmt *n = makeNode(FetchStmt);
6064                                         n->portalname = $3;
6065                                         n->direction = FETCH_ABSOLUTE;
6066                                         n->howMany = -1;
6067                                         $$ = (Node *)n;
6068                                 }
6069                         | ABSOLUTE_P SignedIconst opt_from_in cursor_name
6070                                 {
6071                                         FetchStmt *n = makeNode(FetchStmt);
6072                                         n->portalname = $4;
6073                                         n->direction = FETCH_ABSOLUTE;
6074                                         n->howMany = $2;
6075                                         $$ = (Node *)n;
6076                                 }
6077                         | RELATIVE_P SignedIconst opt_from_in cursor_name
6078                                 {
6079                                         FetchStmt *n = makeNode(FetchStmt);
6080                                         n->portalname = $4;
6081                                         n->direction = FETCH_RELATIVE;
6082                                         n->howMany = $2;
6083                                         $$ = (Node *)n;
6084                                 }
6085                         | SignedIconst opt_from_in cursor_name
6086                                 {
6087                                         FetchStmt *n = makeNode(FetchStmt);
6088                                         n->portalname = $3;
6089                                         n->direction = FETCH_FORWARD;
6090                                         n->howMany = $1;
6091                                         $$ = (Node *)n;
6092                                 }
6093                         | ALL opt_from_in cursor_name
6094                                 {
6095                                         FetchStmt *n = makeNode(FetchStmt);
6096                                         n->portalname = $3;
6097                                         n->direction = FETCH_FORWARD;
6098                                         n->howMany = FETCH_ALL;
6099                                         $$ = (Node *)n;
6100                                 }
6101                         | FORWARD opt_from_in cursor_name
6102                                 {
6103                                         FetchStmt *n = makeNode(FetchStmt);
6104                                         n->portalname = $3;
6105                                         n->direction = FETCH_FORWARD;
6106                                         n->howMany = 1;
6107                                         $$ = (Node *)n;
6108                                 }
6109                         | FORWARD SignedIconst opt_from_in cursor_name
6110                                 {
6111                                         FetchStmt *n = makeNode(FetchStmt);
6112                                         n->portalname = $4;
6113                                         n->direction = FETCH_FORWARD;
6114                                         n->howMany = $2;
6115                                         $$ = (Node *)n;
6116                                 }
6117                         | FORWARD ALL opt_from_in cursor_name
6118                                 {
6119                                         FetchStmt *n = makeNode(FetchStmt);
6120                                         n->portalname = $4;
6121                                         n->direction = FETCH_FORWARD;
6122                                         n->howMany = FETCH_ALL;
6123                                         $$ = (Node *)n;
6124                                 }
6125                         | BACKWARD opt_from_in cursor_name
6126                                 {
6127                                         FetchStmt *n = makeNode(FetchStmt);
6128                                         n->portalname = $3;
6129                                         n->direction = FETCH_BACKWARD;
6130                                         n->howMany = 1;
6131                                         $$ = (Node *)n;
6132                                 }
6133                         | BACKWARD SignedIconst opt_from_in cursor_name
6134                                 {
6135                                         FetchStmt *n = makeNode(FetchStmt);
6136                                         n->portalname = $4;
6137                                         n->direction = FETCH_BACKWARD;
6138                                         n->howMany = $2;
6139                                         $$ = (Node *)n;
6140                                 }
6141                         | BACKWARD ALL opt_from_in cursor_name
6142                                 {
6143                                         FetchStmt *n = makeNode(FetchStmt);
6144                                         n->portalname = $4;
6145                                         n->direction = FETCH_BACKWARD;
6146                                         n->howMany = FETCH_ALL;
6147                                         $$ = (Node *)n;
6148                                 }
6149                 ;
6150
6151 from_in:        FROM                                                                    {}
6152                         | IN_P                                                                  {}
6153                 ;
6154
6155 opt_from_in:    from_in                                                         {}
6156                         | /* EMPTY */                                                   {}
6157                 ;
6158
6159
6160 /*****************************************************************************
6161  *
6162  * GRANT and REVOKE statements
6163  *
6164  *****************************************************************************/
6165
6166 GrantStmt:      GRANT privileges ON privilege_target TO grantee_list
6167                         opt_grant_grant_option
6168                                 {
6169                                         GrantStmt *n = makeNode(GrantStmt);
6170                                         n->is_grant = true;
6171                                         n->privileges = $2;
6172                                         n->targtype = ($4)->targtype;
6173                                         n->objtype = ($4)->objtype;
6174                                         n->objects = ($4)->objs;
6175                                         n->grantees = $6;
6176                                         n->grant_option = $7;
6177                                         $$ = (Node*)n;
6178                                 }
6179                 ;
6180
6181 RevokeStmt:
6182                         REVOKE privileges ON privilege_target
6183                         FROM grantee_list opt_drop_behavior
6184                                 {
6185                                         GrantStmt *n = makeNode(GrantStmt);
6186                                         n->is_grant = false;
6187                                         n->grant_option = false;
6188                                         n->privileges = $2;
6189                                         n->targtype = ($4)->targtype;
6190                                         n->objtype = ($4)->objtype;
6191                                         n->objects = ($4)->objs;
6192                                         n->grantees = $6;
6193                                         n->behavior = $7;
6194                                         $$ = (Node *)n;
6195                                 }
6196                         | REVOKE GRANT OPTION FOR privileges ON privilege_target
6197                         FROM grantee_list opt_drop_behavior
6198                                 {
6199                                         GrantStmt *n = makeNode(GrantStmt);
6200                                         n->is_grant = false;
6201                                         n->grant_option = true;
6202                                         n->privileges = $5;
6203                                         n->targtype = ($7)->targtype;
6204                                         n->objtype = ($7)->objtype;
6205                                         n->objects = ($7)->objs;
6206                                         n->grantees = $9;
6207                                         n->behavior = $10;
6208                                         $$ = (Node *)n;
6209                                 }
6210                 ;
6211
6212
6213 /*
6214  * Privilege names are represented as strings; the validity of the privilege
6215  * names gets checked at execution.  This is a bit annoying but we have little
6216  * choice because of the syntactic conflict with lists of role names in
6217  * GRANT/REVOKE.  What's more, we have to call out in the "privilege"
6218  * production any reserved keywords that need to be usable as privilege names.
6219  */
6220
6221 /* either ALL [PRIVILEGES] or a list of individual privileges */
6222 privileges: privilege_list
6223                                 { $$ = $1; }
6224                         | ALL
6225                                 { $$ = NIL; }
6226                         | ALL PRIVILEGES
6227                                 { $$ = NIL; }
6228                         | ALL '(' columnList ')'
6229                                 {
6230                                         AccessPriv *n = makeNode(AccessPriv);
6231                                         n->priv_name = NULL;
6232                                         n->cols = $3;
6233                                         $$ = list_make1(n);
6234                                 }
6235                         | ALL PRIVILEGES '(' columnList ')'
6236                                 {
6237                                         AccessPriv *n = makeNode(AccessPriv);
6238                                         n->priv_name = NULL;
6239                                         n->cols = $4;
6240                                         $$ = list_make1(n);
6241                                 }
6242                 ;
6243
6244 privilege_list: privilege                                                       { $$ = list_make1($1); }
6245                         | privilege_list ',' privilege                  { $$ = lappend($1, $3); }
6246                 ;
6247
6248 privilege:      SELECT opt_column_list
6249                         {
6250                                 AccessPriv *n = makeNode(AccessPriv);
6251                                 n->priv_name = pstrdup($1);
6252                                 n->cols = $2;
6253                                 $$ = n;
6254                         }
6255                 | REFERENCES opt_column_list
6256                         {
6257                                 AccessPriv *n = makeNode(AccessPriv);
6258                                 n->priv_name = pstrdup($1);
6259                                 n->cols = $2;
6260                                 $$ = n;
6261                         }
6262                 | CREATE opt_column_list
6263                         {
6264                                 AccessPriv *n = makeNode(AccessPriv);
6265                                 n->priv_name = pstrdup($1);
6266                                 n->cols = $2;
6267                                 $$ = n;
6268                         }
6269                 | ColId opt_column_list
6270                         {
6271                                 AccessPriv *n = makeNode(AccessPriv);
6272                                 n->priv_name = $1;
6273                                 n->cols = $2;
6274                                 $$ = n;
6275                         }
6276                 ;
6277
6278
6279 /* Don't bother trying to fold the first two rules into one using
6280  * opt_table.  You're going to get conflicts.
6281  */
6282 privilege_target:
6283                         qualified_name_list
6284                                 {
6285                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6286                                         n->targtype = ACL_TARGET_OBJECT;
6287                                         n->objtype = ACL_OBJECT_RELATION;
6288                                         n->objs = $1;
6289                                         $$ = n;
6290                                 }
6291                         | TABLE qualified_name_list
6292                                 {
6293                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6294                                         n->targtype = ACL_TARGET_OBJECT;
6295                                         n->objtype = ACL_OBJECT_RELATION;
6296                                         n->objs = $2;
6297                                         $$ = n;
6298                                 }
6299                         | SEQUENCE qualified_name_list
6300                                 {
6301                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6302                                         n->targtype = ACL_TARGET_OBJECT;
6303                                         n->objtype = ACL_OBJECT_SEQUENCE;
6304                                         n->objs = $2;
6305                                         $$ = n;
6306                                 }
6307                         | FOREIGN DATA_P WRAPPER name_list
6308                                 {
6309                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6310                                         n->targtype = ACL_TARGET_OBJECT;
6311                                         n->objtype = ACL_OBJECT_FDW;
6312                                         n->objs = $4;
6313                                         $$ = n;
6314                                 }
6315                         | FOREIGN SERVER name_list
6316                                 {
6317                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6318                                         n->targtype = ACL_TARGET_OBJECT;
6319                                         n->objtype = ACL_OBJECT_FOREIGN_SERVER;
6320                                         n->objs = $3;
6321                                         $$ = n;
6322                                 }
6323                         | FUNCTION function_with_argtypes_list
6324                                 {
6325                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6326                                         n->targtype = ACL_TARGET_OBJECT;
6327                                         n->objtype = ACL_OBJECT_FUNCTION;
6328                                         n->objs = $2;
6329                                         $$ = n;
6330                                 }
6331                         | DATABASE name_list
6332                                 {
6333                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6334                                         n->targtype = ACL_TARGET_OBJECT;
6335                                         n->objtype = ACL_OBJECT_DATABASE;
6336                                         n->objs = $2;
6337                                         $$ = n;
6338                                 }
6339                         | DOMAIN_P any_name_list
6340                                 {
6341                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6342                                         n->targtype = ACL_TARGET_OBJECT;
6343                                         n->objtype = ACL_OBJECT_DOMAIN;
6344                                         n->objs = $2;
6345                                         $$ = n;
6346                                 }
6347                         | LANGUAGE name_list
6348                                 {
6349                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6350                                         n->targtype = ACL_TARGET_OBJECT;
6351                                         n->objtype = ACL_OBJECT_LANGUAGE;
6352                                         n->objs = $2;
6353                                         $$ = n;
6354                                 }
6355                         | LARGE_P OBJECT_P NumericOnly_list
6356                                 {
6357                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6358                                         n->targtype = ACL_TARGET_OBJECT;
6359                                         n->objtype = ACL_OBJECT_LARGEOBJECT;
6360                                         n->objs = $3;
6361                                         $$ = n;
6362                                 }
6363                         | SCHEMA name_list
6364                                 {
6365                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6366                                         n->targtype = ACL_TARGET_OBJECT;
6367                                         n->objtype = ACL_OBJECT_NAMESPACE;
6368                                         n->objs = $2;
6369                                         $$ = n;
6370                                 }
6371                         | TABLESPACE name_list
6372                                 {
6373                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6374                                         n->targtype = ACL_TARGET_OBJECT;
6375                                         n->objtype = ACL_OBJECT_TABLESPACE;
6376                                         n->objs = $2;
6377                                         $$ = n;
6378                                 }
6379                         | TYPE_P any_name_list
6380                                 {
6381                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6382                                         n->targtype = ACL_TARGET_OBJECT;
6383                                         n->objtype = ACL_OBJECT_TYPE;
6384                                         n->objs = $2;
6385                                         $$ = n;
6386                                 }
6387                         | ALL TABLES IN_P SCHEMA name_list
6388                                 {
6389                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6390                                         n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
6391                                         n->objtype = ACL_OBJECT_RELATION;
6392                                         n->objs = $5;
6393                                         $$ = n;
6394                                 }
6395                         | ALL SEQUENCES IN_P SCHEMA name_list
6396                                 {
6397                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6398                                         n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
6399                                         n->objtype = ACL_OBJECT_SEQUENCE;
6400                                         n->objs = $5;
6401                                         $$ = n;
6402                                 }
6403                         | ALL FUNCTIONS IN_P SCHEMA name_list
6404                                 {
6405                                         PrivTarget *n = (PrivTarget *) palloc(sizeof(PrivTarget));
6406                                         n->targtype = ACL_TARGET_ALL_IN_SCHEMA;
6407                                         n->objtype = ACL_OBJECT_FUNCTION;
6408                                         n->objs = $5;
6409                                         $$ = n;
6410                                 }
6411                 ;
6412
6413
6414 grantee_list:
6415                         grantee                                                                 { $$ = list_make1($1); }
6416                         | grantee_list ',' grantee                              { $$ = lappend($1, $3); }
6417                 ;
6418
6419 grantee:
6420                         RoleSpec                                                                { $$ = $1; }
6421                         | GROUP_P RoleSpec                                              { $$ = $2; }
6422                 ;
6423
6424
6425 opt_grant_grant_option:
6426                         WITH GRANT OPTION { $$ = TRUE; }
6427                         | /*EMPTY*/ { $$ = FALSE; }
6428                 ;
6429
6430 function_with_argtypes_list:
6431                         function_with_argtypes                                  { $$ = list_make1($1); }
6432                         | function_with_argtypes_list ',' function_with_argtypes
6433                                                                                                         { $$ = lappend($1, $3); }
6434                 ;
6435
6436 function_with_argtypes:
6437                         func_name func_args
6438                                 {
6439                                         FuncWithArgs *n = makeNode(FuncWithArgs);
6440                                         n->funcname = $1;
6441                                         n->funcargs = extractArgTypes($2);
6442                                         $$ = n;
6443                                 }
6444                 ;
6445
6446 /*****************************************************************************
6447  *
6448  * GRANT and REVOKE ROLE statements
6449  *
6450  *****************************************************************************/
6451
6452 GrantRoleStmt:
6453                         GRANT privilege_list TO role_list opt_grant_admin_option opt_granted_by
6454                                 {
6455                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
6456                                         n->is_grant = true;
6457                                         n->granted_roles = $2;
6458                                         n->grantee_roles = $4;
6459                                         n->admin_opt = $5;
6460                                         n->grantor = $6;
6461                                         $$ = (Node*)n;
6462                                 }
6463                 ;
6464
6465 RevokeRoleStmt:
6466                         REVOKE privilege_list FROM role_list opt_granted_by opt_drop_behavior
6467                                 {
6468                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
6469                                         n->is_grant = false;
6470                                         n->admin_opt = false;
6471                                         n->granted_roles = $2;
6472                                         n->grantee_roles = $4;
6473                                         n->behavior = $6;
6474                                         $$ = (Node*)n;
6475                                 }
6476                         | REVOKE ADMIN OPTION FOR privilege_list FROM role_list opt_granted_by opt_drop_behavior
6477                                 {
6478                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
6479                                         n->is_grant = false;
6480                                         n->admin_opt = true;
6481                                         n->granted_roles = $5;
6482                                         n->grantee_roles = $7;
6483                                         n->behavior = $9;
6484                                         $$ = (Node*)n;
6485                                 }
6486                 ;
6487
6488 opt_grant_admin_option: WITH ADMIN OPTION                               { $$ = TRUE; }
6489                         | /*EMPTY*/                                                                     { $$ = FALSE; }
6490                 ;
6491
6492 opt_granted_by: GRANTED BY RoleSpec                                             { $$ = $3; }
6493                         | /*EMPTY*/                                                                     { $$ = NULL; }
6494                 ;
6495
6496 /*****************************************************************************
6497  *
6498  * ALTER DEFAULT PRIVILEGES statement
6499  *
6500  *****************************************************************************/
6501
6502 AlterDefaultPrivilegesStmt:
6503                         ALTER DEFAULT PRIVILEGES DefACLOptionList DefACLAction
6504                                 {
6505                                         AlterDefaultPrivilegesStmt *n = makeNode(AlterDefaultPrivilegesStmt);
6506                                         n->options = $4;
6507                                         n->action = (GrantStmt *) $5;
6508                                         $$ = (Node*)n;
6509                                 }
6510                 ;
6511
6512 DefACLOptionList:
6513                         DefACLOptionList DefACLOption                   { $$ = lappend($1, $2); }
6514                         | /* EMPTY */                                                   { $$ = NIL; }
6515                 ;
6516
6517 DefACLOption:
6518                         IN_P SCHEMA name_list
6519                                 {
6520                                         $$ = makeDefElem("schemas", (Node *)$3);
6521                                 }
6522                         | FOR ROLE role_list
6523                                 {
6524                                         $$ = makeDefElem("roles", (Node *)$3);
6525                                 }
6526                         | FOR USER role_list
6527                                 {
6528                                         $$ = makeDefElem("roles", (Node *)$3);
6529                                 }
6530                 ;
6531
6532 /*
6533  * This should match GRANT/REVOKE, except that individual target objects
6534  * are not mentioned and we only allow a subset of object types.
6535  */
6536 DefACLAction:
6537                         GRANT privileges ON defacl_privilege_target TO grantee_list
6538                         opt_grant_grant_option
6539                                 {
6540                                         GrantStmt *n = makeNode(GrantStmt);
6541                                         n->is_grant = true;
6542                                         n->privileges = $2;
6543                                         n->targtype = ACL_TARGET_DEFAULTS;
6544                                         n->objtype = $4;
6545                                         n->objects = NIL;
6546                                         n->grantees = $6;
6547                                         n->grant_option = $7;
6548                                         $$ = (Node*)n;
6549                                 }
6550                         | REVOKE privileges ON defacl_privilege_target
6551                         FROM grantee_list opt_drop_behavior
6552                                 {
6553                                         GrantStmt *n = makeNode(GrantStmt);
6554                                         n->is_grant = false;
6555                                         n->grant_option = false;
6556                                         n->privileges = $2;
6557                                         n->targtype = ACL_TARGET_DEFAULTS;
6558                                         n->objtype = $4;
6559                                         n->objects = NIL;
6560                                         n->grantees = $6;
6561                                         n->behavior = $7;
6562                                         $$ = (Node *)n;
6563                                 }
6564                         | REVOKE GRANT OPTION FOR privileges ON defacl_privilege_target
6565                         FROM grantee_list opt_drop_behavior
6566                                 {
6567                                         GrantStmt *n = makeNode(GrantStmt);
6568                                         n->is_grant = false;
6569                                         n->grant_option = true;
6570                                         n->privileges = $5;
6571                                         n->targtype = ACL_TARGET_DEFAULTS;
6572                                         n->objtype = $7;
6573                                         n->objects = NIL;
6574                                         n->grantees = $9;
6575                                         n->behavior = $10;
6576                                         $$ = (Node *)n;
6577                                 }
6578                 ;
6579
6580 defacl_privilege_target:
6581                         TABLES                  { $$ = ACL_OBJECT_RELATION; }
6582                         | FUNCTIONS             { $$ = ACL_OBJECT_FUNCTION; }
6583                         | SEQUENCES             { $$ = ACL_OBJECT_SEQUENCE; }
6584                         | TYPES_P               { $$ = ACL_OBJECT_TYPE; }
6585                 ;
6586
6587
6588 /*****************************************************************************
6589  *
6590  *              QUERY: CREATE INDEX
6591  *
6592  * Note: we cannot put TABLESPACE clause after WHERE clause unless we are
6593  * willing to make TABLESPACE a fully reserved word.
6594  *****************************************************************************/
6595
6596 IndexStmt:      CREATE opt_unique INDEX opt_concurrently opt_index_name
6597                         ON qualified_name access_method_clause '(' index_params ')'
6598                         opt_reloptions OptTableSpace where_clause
6599                                 {
6600                                         IndexStmt *n = makeNode(IndexStmt);
6601                                         n->unique = $2;
6602                                         n->concurrent = $4;
6603                                         n->idxname = $5;
6604                                         n->relation = $7;
6605                                         n->accessMethod = $8;
6606                                         n->indexParams = $10;
6607                                         n->options = $12;
6608                                         n->tableSpace = $13;
6609                                         n->whereClause = $14;
6610                                         n->excludeOpNames = NIL;
6611                                         n->idxcomment = NULL;
6612                                         n->indexOid = InvalidOid;
6613                                         n->oldNode = InvalidOid;
6614                                         n->primary = false;
6615                                         n->isconstraint = false;
6616                                         n->deferrable = false;
6617                                         n->initdeferred = false;
6618                                         n->transformed = false;
6619                                         n->if_not_exists = false;
6620                                         $$ = (Node *)n;
6621                                 }
6622                         | CREATE opt_unique INDEX opt_concurrently IF_P NOT EXISTS index_name
6623                         ON qualified_name access_method_clause '(' index_params ')'
6624                         opt_reloptions OptTableSpace where_clause
6625                                 {
6626                                         IndexStmt *n = makeNode(IndexStmt);
6627                                         n->unique = $2;
6628                                         n->concurrent = $4;
6629                                         n->idxname = $8;
6630                                         n->relation = $10;
6631                                         n->accessMethod = $11;
6632                                         n->indexParams = $13;
6633                                         n->options = $15;
6634                                         n->tableSpace = $16;
6635                                         n->whereClause = $17;
6636                                         n->excludeOpNames = NIL;
6637                                         n->idxcomment = NULL;
6638                                         n->indexOid = InvalidOid;
6639                                         n->oldNode = InvalidOid;
6640                                         n->primary = false;
6641                                         n->isconstraint = false;
6642                                         n->deferrable = false;
6643                                         n->initdeferred = false;
6644                                         n->transformed = false;
6645                                         n->if_not_exists = true;
6646                                         $$ = (Node *)n;
6647                                 }
6648                 ;
6649
6650 opt_unique:
6651                         UNIQUE                                                                  { $$ = TRUE; }
6652                         | /*EMPTY*/                                                             { $$ = FALSE; }
6653                 ;
6654
6655 opt_concurrently:
6656                         CONCURRENTLY                                                    { $$ = TRUE; }
6657                         | /*EMPTY*/                                                             { $$ = FALSE; }
6658                 ;
6659
6660 opt_index_name:
6661                         index_name                                                              { $$ = $1; }
6662                         | /*EMPTY*/                                                             { $$ = NULL; }
6663                 ;
6664
6665 access_method_clause:
6666                         USING access_method                                             { $$ = $2; }
6667                         | /*EMPTY*/                                                             { $$ = DEFAULT_INDEX_TYPE; }
6668                 ;
6669
6670 index_params:   index_elem                                                      { $$ = list_make1($1); }
6671                         | index_params ',' index_elem                   { $$ = lappend($1, $3); }
6672                 ;
6673
6674 /*
6675  * Index attributes can be either simple column references, or arbitrary
6676  * expressions in parens.  For backwards-compatibility reasons, we allow
6677  * an expression that's just a function call to be written without parens.
6678  */
6679 index_elem:     ColId opt_collate opt_class opt_asc_desc opt_nulls_order
6680                                 {
6681                                         $$ = makeNode(IndexElem);
6682                                         $$->name = $1;
6683                                         $$->expr = NULL;
6684                                         $$->indexcolname = NULL;
6685                                         $$->collation = $2;
6686                                         $$->opclass = $3;
6687                                         $$->ordering = $4;
6688                                         $$->nulls_ordering = $5;
6689                                 }
6690                         | func_expr_windowless opt_collate opt_class opt_asc_desc opt_nulls_order
6691                                 {
6692                                         $$ = makeNode(IndexElem);
6693                                         $$->name = NULL;
6694                                         $$->expr = $1;
6695                                         $$->indexcolname = NULL;
6696                                         $$->collation = $2;
6697                                         $$->opclass = $3;
6698                                         $$->ordering = $4;
6699                                         $$->nulls_ordering = $5;
6700                                 }
6701                         | '(' a_expr ')' opt_collate opt_class opt_asc_desc opt_nulls_order
6702                                 {
6703                                         $$ = makeNode(IndexElem);
6704                                         $$->name = NULL;
6705                                         $$->expr = $2;
6706                                         $$->indexcolname = NULL;
6707                                         $$->collation = $4;
6708                                         $$->opclass = $5;
6709                                         $$->ordering = $6;
6710                                         $$->nulls_ordering = $7;
6711                                 }
6712                 ;
6713
6714 opt_collate: COLLATE any_name                                           { $$ = $2; }
6715                         | /*EMPTY*/                                                             { $$ = NIL; }
6716                 ;
6717
6718 opt_class:      any_name                                                                { $$ = $1; }
6719                         | USING any_name                                                { $$ = $2; }
6720                         | /*EMPTY*/                                                             { $$ = NIL; }
6721                 ;
6722
6723 opt_asc_desc: ASC                                                       { $$ = SORTBY_ASC; }
6724                         | DESC                                                  { $$ = SORTBY_DESC; }
6725                         | /*EMPTY*/                                             { $$ = SORTBY_DEFAULT; }
6726                 ;
6727
6728 opt_nulls_order: NULLS_LA FIRST_P                       { $$ = SORTBY_NULLS_FIRST; }
6729                         | NULLS_LA LAST_P                               { $$ = SORTBY_NULLS_LAST; }
6730                         | /*EMPTY*/                                             { $$ = SORTBY_NULLS_DEFAULT; }
6731                 ;
6732
6733
6734 /*****************************************************************************
6735  *
6736  *              QUERY:
6737  *                              create [or replace] function <fname>
6738  *                                              [(<type-1> { , <type-n>})]
6739  *                                              returns <type-r>
6740  *                                              as <filename or code in language as appropriate>
6741  *                                              language <lang> [with parameters]
6742  *
6743  *****************************************************************************/
6744
6745 CreateFunctionStmt:
6746                         CREATE opt_or_replace FUNCTION func_name func_args_with_defaults
6747                         RETURNS func_return createfunc_opt_list opt_definition
6748                                 {
6749                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
6750                                         n->replace = $2;
6751                                         n->funcname = $4;
6752                                         n->parameters = $5;
6753                                         n->returnType = $7;
6754                                         n->options = $8;
6755                                         n->withClause = $9;
6756                                         $$ = (Node *)n;
6757                                 }
6758                         | CREATE opt_or_replace FUNCTION func_name func_args_with_defaults
6759                           RETURNS TABLE '(' table_func_column_list ')' createfunc_opt_list opt_definition
6760                                 {
6761                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
6762                                         n->replace = $2;
6763                                         n->funcname = $4;
6764                                         n->parameters = mergeTableFuncParameters($5, $9);
6765                                         n->returnType = TableFuncTypeName($9);
6766                                         n->returnType->location = @7;
6767                                         n->options = $11;
6768                                         n->withClause = $12;
6769                                         $$ = (Node *)n;
6770                                 }
6771                         | CREATE opt_or_replace FUNCTION func_name func_args_with_defaults
6772                           createfunc_opt_list opt_definition
6773                                 {
6774                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
6775                                         n->replace = $2;
6776                                         n->funcname = $4;
6777                                         n->parameters = $5;
6778                                         n->returnType = NULL;
6779                                         n->options = $6;
6780                                         n->withClause = $7;
6781                                         $$ = (Node *)n;
6782                                 }
6783                 ;
6784
6785 opt_or_replace:
6786                         OR REPLACE                                                              { $$ = TRUE; }
6787                         | /*EMPTY*/                                                             { $$ = FALSE; }
6788                 ;
6789
6790 func_args:      '(' func_args_list ')'                                  { $$ = $2; }
6791                         | '(' ')'                                                               { $$ = NIL; }
6792                 ;
6793
6794 func_args_list:
6795                         func_arg                                                                { $$ = list_make1($1); }
6796                         | func_args_list ',' func_arg                   { $$ = lappend($1, $3); }
6797                 ;
6798
6799 /*
6800  * func_args_with_defaults is separate because we only want to accept
6801  * defaults in CREATE FUNCTION, not in ALTER etc.
6802  */
6803 func_args_with_defaults:
6804                 '(' func_args_with_defaults_list ')'            { $$ = $2; }
6805                 | '(' ')'                                                                       { $$ = NIL; }
6806                 ;
6807
6808 func_args_with_defaults_list:
6809                 func_arg_with_default                                           { $$ = list_make1($1); }
6810                 | func_args_with_defaults_list ',' func_arg_with_default
6811                                                                                                         { $$ = lappend($1, $3); }
6812                 ;
6813
6814 /*
6815  * The style with arg_class first is SQL99 standard, but Oracle puts
6816  * param_name first; accept both since it's likely people will try both
6817  * anyway.  Don't bother trying to save productions by letting arg_class
6818  * have an empty alternative ... you'll get shift/reduce conflicts.
6819  *
6820  * We can catch over-specified arguments here if we want to,
6821  * but for now better to silently swallow typmod, etc.
6822  * - thomas 2000-03-22
6823  */
6824 func_arg:
6825                         arg_class param_name func_type
6826                                 {
6827                                         FunctionParameter *n = makeNode(FunctionParameter);
6828                                         n->name = $2;
6829                                         n->argType = $3;
6830                                         n->mode = $1;
6831                                         n->defexpr = NULL;
6832                                         $$ = n;
6833                                 }
6834                         | param_name arg_class func_type
6835                                 {
6836                                         FunctionParameter *n = makeNode(FunctionParameter);
6837                                         n->name = $1;
6838                                         n->argType = $3;
6839                                         n->mode = $2;
6840                                         n->defexpr = NULL;
6841                                         $$ = n;
6842                                 }
6843                         | param_name func_type
6844                                 {
6845                                         FunctionParameter *n = makeNode(FunctionParameter);
6846                                         n->name = $1;
6847                                         n->argType = $2;
6848                                         n->mode = FUNC_PARAM_IN;
6849                                         n->defexpr = NULL;
6850                                         $$ = n;
6851                                 }
6852                         | arg_class func_type
6853                                 {
6854                                         FunctionParameter *n = makeNode(FunctionParameter);
6855                                         n->name = NULL;
6856                                         n->argType = $2;
6857                                         n->mode = $1;
6858                                         n->defexpr = NULL;
6859                                         $$ = n;
6860                                 }
6861                         | func_type
6862                                 {
6863                                         FunctionParameter *n = makeNode(FunctionParameter);
6864                                         n->name = NULL;
6865                                         n->argType = $1;
6866                                         n->mode = FUNC_PARAM_IN;
6867                                         n->defexpr = NULL;
6868                                         $$ = n;
6869                                 }
6870                 ;
6871
6872 /* INOUT is SQL99 standard, IN OUT is for Oracle compatibility */
6873 arg_class:      IN_P                                                            { $$ = FUNC_PARAM_IN; }
6874                         | OUT_P                                                         { $$ = FUNC_PARAM_OUT; }
6875                         | INOUT                                                         { $$ = FUNC_PARAM_INOUT; }
6876                         | IN_P OUT_P                                            { $$ = FUNC_PARAM_INOUT; }
6877                         | VARIADIC                                                      { $$ = FUNC_PARAM_VARIADIC; }
6878                 ;
6879
6880 /*
6881  * Ideally param_name should be ColId, but that causes too many conflicts.
6882  */
6883 param_name:     type_function_name
6884                 ;
6885
6886 func_return:
6887                         func_type
6888                                 {
6889                                         /* We can catch over-specified results here if we want to,
6890                                          * but for now better to silently swallow typmod, etc.
6891                                          * - thomas 2000-03-22
6892                                          */
6893                                         $$ = $1;
6894                                 }
6895                 ;
6896
6897 /*
6898  * We would like to make the %TYPE productions here be ColId attrs etc,
6899  * but that causes reduce/reduce conflicts.  type_function_name
6900  * is next best choice.
6901  */
6902 func_type:      Typename                                                                { $$ = $1; }
6903                         | type_function_name attrs '%' TYPE_P
6904                                 {
6905                                         $$ = makeTypeNameFromNameList(lcons(makeString($1), $2));
6906                                         $$->pct_type = true;
6907                                         $$->location = @1;
6908                                 }
6909                         | SETOF type_function_name attrs '%' TYPE_P
6910                                 {
6911                                         $$ = makeTypeNameFromNameList(lcons(makeString($2), $3));
6912                                         $$->pct_type = true;
6913                                         $$->setof = TRUE;
6914                                         $$->location = @2;
6915                                 }
6916                 ;
6917
6918 func_arg_with_default:
6919                 func_arg
6920                                 {
6921                                         $$ = $1;
6922                                 }
6923                 | func_arg DEFAULT a_expr
6924                                 {
6925                                         $$ = $1;
6926                                         $$->defexpr = $3;
6927                                 }
6928                 | func_arg '=' a_expr
6929                                 {
6930                                         $$ = $1;
6931                                         $$->defexpr = $3;
6932                                 }
6933                 ;
6934
6935 /* Aggregate args can be most things that function args can be */
6936 aggr_arg:       func_arg
6937                                 {
6938                                         if (!($1->mode == FUNC_PARAM_IN ||
6939                                                   $1->mode == FUNC_PARAM_VARIADIC))
6940                                                 ereport(ERROR,
6941                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6942                                                                  errmsg("aggregates cannot have output arguments"),
6943                                                                  parser_errposition(@1)));
6944                                         $$ = $1;
6945                                 }
6946                 ;
6947
6948 /*
6949  * The SQL standard offers no guidance on how to declare aggregate argument
6950  * lists, since it doesn't have CREATE AGGREGATE etc.  We accept these cases:
6951  *
6952  * (*)                                                                  - normal agg with no args
6953  * (aggr_arg,...)                                               - normal agg with args
6954  * (ORDER BY aggr_arg,...)                              - ordered-set agg with no direct args
6955  * (aggr_arg,... ORDER BY aggr_arg,...) - ordered-set agg with direct args
6956  *
6957  * The zero-argument case is spelled with '*' for consistency with COUNT(*).
6958  *
6959  * An additional restriction is that if the direct-args list ends in a
6960  * VARIADIC item, the ordered-args list must contain exactly one item that
6961  * is also VARIADIC with the same type.  This allows us to collapse the two
6962  * VARIADIC items into one, which is necessary to represent the aggregate in
6963  * pg_proc.  We check this at the grammar stage so that we can return a list
6964  * in which the second VARIADIC item is already discarded, avoiding extra work
6965  * in cases such as DROP AGGREGATE.
6966  *
6967  * The return value of this production is a two-element list, in which the
6968  * first item is a sublist of FunctionParameter nodes (with any duplicate
6969  * VARIADIC item already dropped, as per above) and the second is an integer
6970  * Value node, containing -1 if there was no ORDER BY and otherwise the number
6971  * of argument declarations before the ORDER BY.  (If this number is equal
6972  * to the first sublist's length, then we dropped a duplicate VARIADIC item.)
6973  * This representation is passed as-is to CREATE AGGREGATE; for operations
6974  * on existing aggregates, we can just apply extractArgTypes to the first
6975  * sublist.
6976  */
6977 aggr_args:      '(' '*' ')'
6978                                 {
6979                                         $$ = list_make2(NIL, makeInteger(-1));
6980                                 }
6981                         | '(' aggr_args_list ')'
6982                                 {
6983                                         $$ = list_make2($2, makeInteger(-1));
6984                                 }
6985                         | '(' ORDER BY aggr_args_list ')'
6986                                 {
6987                                         $$ = list_make2($4, makeInteger(0));
6988                                 }
6989                         | '(' aggr_args_list ORDER BY aggr_args_list ')'
6990                                 {
6991                                         /* this is the only case requiring consistency checking */
6992                                         $$ = makeOrderedSetArgs($2, $5, yyscanner);
6993                                 }
6994                 ;
6995
6996 aggr_args_list:
6997                         aggr_arg                                                                { $$ = list_make1($1); }
6998                         | aggr_args_list ',' aggr_arg                   { $$ = lappend($1, $3); }
6999                 ;
7000
7001 createfunc_opt_list:
7002                         /* Must be at least one to prevent conflict */
7003                         createfunc_opt_item                                             { $$ = list_make1($1); }
7004                         | createfunc_opt_list createfunc_opt_item { $$ = lappend($1, $2); }
7005         ;
7006
7007 /*
7008  * Options common to both CREATE FUNCTION and ALTER FUNCTION
7009  */
7010 common_func_opt_item:
7011                         CALLED ON NULL_P INPUT_P
7012                                 {
7013                                         $$ = makeDefElem("strict", (Node *)makeInteger(FALSE));
7014                                 }
7015                         | RETURNS NULL_P ON NULL_P INPUT_P
7016                                 {
7017                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
7018                                 }
7019                         | STRICT_P
7020                                 {
7021                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
7022                                 }
7023                         | IMMUTABLE
7024                                 {
7025                                         $$ = makeDefElem("volatility", (Node *)makeString("immutable"));
7026                                 }
7027                         | STABLE
7028                                 {
7029                                         $$ = makeDefElem("volatility", (Node *)makeString("stable"));
7030                                 }
7031                         | VOLATILE
7032                                 {
7033                                         $$ = makeDefElem("volatility", (Node *)makeString("volatile"));
7034                                 }
7035                         | EXTERNAL SECURITY DEFINER
7036                                 {
7037                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
7038                                 }
7039                         | EXTERNAL SECURITY INVOKER
7040                                 {
7041                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
7042                                 }
7043                         | SECURITY DEFINER
7044                                 {
7045                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
7046                                 }
7047                         | SECURITY INVOKER
7048                                 {
7049                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
7050                                 }
7051                         | LEAKPROOF
7052                                 {
7053                                         $$ = makeDefElem("leakproof", (Node *)makeInteger(TRUE));
7054                                 }
7055                         | NOT LEAKPROOF
7056                                 {
7057                                         $$ = makeDefElem("leakproof", (Node *)makeInteger(FALSE));
7058                                 }
7059                         | COST NumericOnly
7060                                 {
7061                                         $$ = makeDefElem("cost", (Node *)$2);
7062                                 }
7063                         | ROWS NumericOnly
7064                                 {
7065                                         $$ = makeDefElem("rows", (Node *)$2);
7066                                 }
7067                         | FunctionSetResetClause
7068                                 {
7069                                         /* we abuse the normal content of a DefElem here */
7070                                         $$ = makeDefElem("set", (Node *)$1);
7071                                 }
7072                         | PARALLEL ColId
7073                                 {
7074                                         $$ = makeDefElem("parallel", (Node *)makeString($2));
7075                                 }
7076                 ;
7077
7078 createfunc_opt_item:
7079                         AS func_as
7080                                 {
7081                                         $$ = makeDefElem("as", (Node *)$2);
7082                                 }
7083                         | LANGUAGE NonReservedWord_or_Sconst
7084                                 {
7085                                         $$ = makeDefElem("language", (Node *)makeString($2));
7086                                 }
7087                         | TRANSFORM transform_type_list
7088                                 {
7089                                         $$ = makeDefElem("transform", (Node *)$2);
7090                                 }
7091                         | WINDOW
7092                                 {
7093                                         $$ = makeDefElem("window", (Node *)makeInteger(TRUE));
7094                                 }
7095                         | common_func_opt_item
7096                                 {
7097                                         $$ = $1;
7098                                 }
7099                 ;
7100
7101 func_as:        Sconst                                          { $$ = list_make1(makeString($1)); }
7102                         | Sconst ',' Sconst
7103                                 {
7104                                         $$ = list_make2(makeString($1), makeString($3));
7105                                 }
7106                 ;
7107
7108 transform_type_list:
7109                         FOR TYPE_P Typename { $$ = list_make1($3); }
7110                         | transform_type_list ',' FOR TYPE_P Typename { $$ = lappend($1, $5); }
7111                 ;
7112
7113 opt_definition:
7114                         WITH definition                                                 { $$ = $2; }
7115                         | /*EMPTY*/                                                             { $$ = NIL; }
7116                 ;
7117
7118 table_func_column:      param_name func_type
7119                                 {
7120                                         FunctionParameter *n = makeNode(FunctionParameter);
7121                                         n->name = $1;
7122                                         n->argType = $2;
7123                                         n->mode = FUNC_PARAM_TABLE;
7124                                         n->defexpr = NULL;
7125                                         $$ = n;
7126                                 }
7127                 ;
7128
7129 table_func_column_list:
7130                         table_func_column
7131                                 {
7132                                         $$ = list_make1($1);
7133                                 }
7134                         | table_func_column_list ',' table_func_column
7135                                 {
7136                                         $$ = lappend($1, $3);
7137                                 }
7138                 ;
7139
7140 /*****************************************************************************
7141  * ALTER FUNCTION
7142  *
7143  * RENAME and OWNER subcommands are already provided by the generic
7144  * ALTER infrastructure, here we just specify alterations that can
7145  * only be applied to functions.
7146  *
7147  *****************************************************************************/
7148 AlterFunctionStmt:
7149                         ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
7150                                 {
7151                                         AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
7152                                         n->func = $3;
7153                                         n->actions = $4;
7154                                         $$ = (Node *) n;
7155                                 }
7156                 ;
7157
7158 alterfunc_opt_list:
7159                         /* At least one option must be specified */
7160                         common_func_opt_item                                    { $$ = list_make1($1); }
7161                         | alterfunc_opt_list common_func_opt_item { $$ = lappend($1, $2); }
7162                 ;
7163
7164 /* Ignored, merely for SQL compliance */
7165 opt_restrict:
7166                         RESTRICT
7167                         | /* EMPTY */
7168                 ;
7169
7170
7171 /*****************************************************************************
7172  *
7173  *              QUERY:
7174  *
7175  *              DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
7176  *              DROP AGGREGATE aggname (arg1, ...) [ RESTRICT | CASCADE ]
7177  *              DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
7178  *
7179  *****************************************************************************/
7180
7181 RemoveFuncStmt:
7182                         DROP FUNCTION func_name func_args opt_drop_behavior
7183                                 {
7184                                         DropStmt *n = makeNode(DropStmt);
7185                                         n->removeType = OBJECT_FUNCTION;
7186                                         n->objects = list_make1($3);
7187                                         n->arguments = list_make1(extractArgTypes($4));
7188                                         n->behavior = $5;
7189                                         n->missing_ok = false;
7190                                         n->concurrent = false;
7191                                         $$ = (Node *)n;
7192                                 }
7193                         | DROP FUNCTION IF_P EXISTS func_name func_args opt_drop_behavior
7194                                 {
7195                                         DropStmt *n = makeNode(DropStmt);
7196                                         n->removeType = OBJECT_FUNCTION;
7197                                         n->objects = list_make1($5);
7198                                         n->arguments = list_make1(extractArgTypes($6));
7199                                         n->behavior = $7;
7200                                         n->missing_ok = true;
7201                                         n->concurrent = false;
7202                                         $$ = (Node *)n;
7203                                 }
7204                 ;
7205
7206 RemoveAggrStmt:
7207                         DROP AGGREGATE func_name aggr_args opt_drop_behavior
7208                                 {
7209                                         DropStmt *n = makeNode(DropStmt);
7210                                         n->removeType = OBJECT_AGGREGATE;
7211                                         n->objects = list_make1($3);
7212                                         n->arguments = list_make1(extractAggrArgTypes($4));
7213                                         n->behavior = $5;
7214                                         n->missing_ok = false;
7215                                         n->concurrent = false;
7216                                         $$ = (Node *)n;
7217                                 }
7218                         | DROP AGGREGATE IF_P EXISTS func_name aggr_args opt_drop_behavior
7219                                 {
7220                                         DropStmt *n = makeNode(DropStmt);
7221                                         n->removeType = OBJECT_AGGREGATE;
7222                                         n->objects = list_make1($5);
7223                                         n->arguments = list_make1(extractAggrArgTypes($6));
7224                                         n->behavior = $7;
7225                                         n->missing_ok = true;
7226                                         n->concurrent = false;
7227                                         $$ = (Node *)n;
7228                                 }
7229                 ;
7230
7231 RemoveOperStmt:
7232                         DROP OPERATOR any_operator oper_argtypes opt_drop_behavior
7233                                 {
7234                                         DropStmt *n = makeNode(DropStmt);
7235                                         n->removeType = OBJECT_OPERATOR;
7236                                         n->objects = list_make1($3);
7237                                         n->arguments = list_make1($4);
7238                                         n->behavior = $5;
7239                                         n->missing_ok = false;
7240                                         n->concurrent = false;
7241                                         $$ = (Node *)n;
7242                                 }
7243                         | DROP OPERATOR IF_P EXISTS any_operator oper_argtypes opt_drop_behavior
7244                                 {
7245                                         DropStmt *n = makeNode(DropStmt);
7246                                         n->removeType = OBJECT_OPERATOR;
7247                                         n->objects = list_make1($5);
7248                                         n->arguments = list_make1($6);
7249                                         n->behavior = $7;
7250                                         n->missing_ok = true;
7251                                         n->concurrent = false;
7252                                         $$ = (Node *)n;
7253                                 }
7254                 ;
7255
7256 oper_argtypes:
7257                         '(' Typename ')'
7258                                 {
7259                                    ereport(ERROR,
7260                                                    (errcode(ERRCODE_SYNTAX_ERROR),
7261                                                         errmsg("missing argument"),
7262                                                         errhint("Use NONE to denote the missing argument of a unary operator."),
7263                                                         parser_errposition(@3)));
7264                                 }
7265                         | '(' Typename ',' Typename ')'
7266                                         { $$ = list_make2($2, $4); }
7267                         | '(' NONE ',' Typename ')'                                     /* left unary */
7268                                         { $$ = list_make2(NULL, $4); }
7269                         | '(' Typename ',' NONE ')'                                     /* right unary */
7270                                         { $$ = list_make2($2, NULL); }
7271                 ;
7272
7273 any_operator:
7274                         all_Op
7275                                         { $$ = list_make1(makeString($1)); }
7276                         | ColId '.' any_operator
7277                                         { $$ = lcons(makeString($1), $3); }
7278                 ;
7279
7280 /*****************************************************************************
7281  *
7282  *              DO <anonymous code block> [ LANGUAGE language ]
7283  *
7284  * We use a DefElem list for future extensibility, and to allow flexibility
7285  * in the clause order.
7286  *
7287  *****************************************************************************/
7288
7289 DoStmt: DO dostmt_opt_list
7290                                 {
7291                                         DoStmt *n = makeNode(DoStmt);
7292                                         n->args = $2;
7293                                         $$ = (Node *)n;
7294                                 }
7295                 ;
7296
7297 dostmt_opt_list:
7298                         dostmt_opt_item                                         { $$ = list_make1($1); }
7299                         | dostmt_opt_list dostmt_opt_item       { $$ = lappend($1, $2); }
7300                 ;
7301
7302 dostmt_opt_item:
7303                         Sconst
7304                                 {
7305                                         $$ = makeDefElem("as", (Node *)makeString($1));
7306                                 }
7307                         | LANGUAGE NonReservedWord_or_Sconst
7308                                 {
7309                                         $$ = makeDefElem("language", (Node *)makeString($2));
7310                                 }
7311                 ;
7312
7313 /*****************************************************************************
7314  *
7315  *              CREATE CAST / DROP CAST
7316  *
7317  *****************************************************************************/
7318
7319 CreateCastStmt: CREATE CAST '(' Typename AS Typename ')'
7320                                         WITH FUNCTION function_with_argtypes cast_context
7321                                 {
7322                                         CreateCastStmt *n = makeNode(CreateCastStmt);
7323                                         n->sourcetype = $4;
7324                                         n->targettype = $6;
7325                                         n->func = $10;
7326                                         n->context = (CoercionContext) $11;
7327                                         n->inout = false;
7328                                         $$ = (Node *)n;
7329                                 }
7330                         | CREATE CAST '(' Typename AS Typename ')'
7331                                         WITHOUT FUNCTION cast_context
7332                                 {
7333                                         CreateCastStmt *n = makeNode(CreateCastStmt);
7334                                         n->sourcetype = $4;
7335                                         n->targettype = $6;
7336                                         n->func = NULL;
7337                                         n->context = (CoercionContext) $10;
7338                                         n->inout = false;
7339                                         $$ = (Node *)n;
7340                                 }
7341                         | CREATE CAST '(' Typename AS Typename ')'
7342                                         WITH INOUT cast_context
7343                                 {
7344                                         CreateCastStmt *n = makeNode(CreateCastStmt);
7345                                         n->sourcetype = $4;
7346                                         n->targettype = $6;
7347                                         n->func = NULL;
7348                                         n->context = (CoercionContext) $10;
7349                                         n->inout = true;
7350                                         $$ = (Node *)n;
7351                                 }
7352                 ;
7353
7354 cast_context:  AS IMPLICIT_P                                    { $$ = COERCION_IMPLICIT; }
7355                 | AS ASSIGNMENT                                                 { $$ = COERCION_ASSIGNMENT; }
7356                 | /*EMPTY*/                                                             { $$ = COERCION_EXPLICIT; }
7357                 ;
7358
7359
7360 DropCastStmt: DROP CAST opt_if_exists '(' Typename AS Typename ')' opt_drop_behavior
7361                                 {
7362                                         DropStmt *n = makeNode(DropStmt);
7363                                         n->removeType = OBJECT_CAST;
7364                                         n->objects = list_make1(list_make1($5));
7365                                         n->arguments = list_make1(list_make1($7));
7366                                         n->behavior = $9;
7367                                         n->missing_ok = $3;
7368                                         n->concurrent = false;
7369                                         $$ = (Node *)n;
7370                                 }
7371                 ;
7372
7373 opt_if_exists: IF_P EXISTS                                              { $$ = TRUE; }
7374                 | /*EMPTY*/                                                             { $$ = FALSE; }
7375                 ;
7376
7377
7378 /*****************************************************************************
7379  *
7380  *              CREATE TRANSFORM / DROP TRANSFORM
7381  *
7382  *****************************************************************************/
7383
7384 CreateTransformStmt: CREATE opt_or_replace TRANSFORM FOR Typename LANGUAGE name '(' transform_element_list ')'
7385                                 {
7386                                         CreateTransformStmt *n = makeNode(CreateTransformStmt);
7387                                         n->replace = $2;
7388                                         n->type_name = $5;
7389                                         n->lang = $7;
7390                                         n->fromsql = linitial($9);
7391                                         n->tosql = lsecond($9);
7392                                         $$ = (Node *)n;
7393                                 }
7394                 ;
7395
7396 transform_element_list: FROM SQL_P WITH FUNCTION function_with_argtypes ',' TO SQL_P WITH FUNCTION function_with_argtypes
7397                                 {
7398                                         $$ = list_make2($5, $11);
7399                                 }
7400                                 | TO SQL_P WITH FUNCTION function_with_argtypes ',' FROM SQL_P WITH FUNCTION function_with_argtypes
7401                                 {
7402                                         $$ = list_make2($11, $5);
7403                                 }
7404                                 | FROM SQL_P WITH FUNCTION function_with_argtypes
7405                                 {
7406                                         $$ = list_make2($5, NULL);
7407                                 }
7408                                 | TO SQL_P WITH FUNCTION function_with_argtypes
7409                                 {
7410                                         $$ = list_make2(NULL, $5);
7411                                 }
7412                 ;
7413
7414
7415 DropTransformStmt: DROP TRANSFORM opt_if_exists FOR Typename LANGUAGE name opt_drop_behavior
7416                                 {
7417                                         DropStmt *n = makeNode(DropStmt);
7418                                         n->removeType = OBJECT_TRANSFORM;
7419                                         n->objects = list_make1(list_make1($5));
7420                                         n->arguments = list_make1(list_make1(makeString($7)));
7421                                         n->behavior = $8;
7422                                         n->missing_ok = $3;
7423                                         $$ = (Node *)n;
7424                                 }
7425                 ;
7426
7427
7428 /*****************************************************************************
7429  *
7430  *              QUERY:
7431  *
7432  *              REINDEX [ (options) ] type <name>
7433  *****************************************************************************/
7434
7435 ReindexStmt:
7436                         REINDEX reindex_target_type qualified_name
7437                                 {
7438                                         ReindexStmt *n = makeNode(ReindexStmt);
7439                                         n->kind = $2;
7440                                         n->relation = $3;
7441                                         n->name = NULL;
7442                                         n->options = 0;
7443                                         $$ = (Node *)n;
7444                                 }
7445                         | REINDEX reindex_target_multitable name
7446                                 {
7447                                         ReindexStmt *n = makeNode(ReindexStmt);
7448                                         n->kind = $2;
7449                                         n->name = $3;
7450                                         n->relation = NULL;
7451                                         n->options = 0;
7452                                         $$ = (Node *)n;
7453                                 }
7454                         | REINDEX '(' reindex_option_list ')' reindex_target_type qualified_name
7455                                 {
7456                                         ReindexStmt *n = makeNode(ReindexStmt);
7457                                         n->kind = $5;
7458                                         n->relation = $6;
7459                                         n->name = NULL;
7460                                         n->options = $3;
7461                                         $$ = (Node *)n;
7462                                 }
7463                         | REINDEX '(' reindex_option_list ')' reindex_target_multitable name
7464                                 {
7465                                         ReindexStmt *n = makeNode(ReindexStmt);
7466                                         n->kind = $5;
7467                                         n->name = $6;
7468                                         n->relation = NULL;
7469                                         n->options = $3;
7470                                         $$ = (Node *)n;
7471                                 }
7472                 ;
7473 reindex_target_type:
7474                         INDEX                                   { $$ = REINDEX_OBJECT_INDEX; }
7475                         | TABLE                                 { $$ = REINDEX_OBJECT_TABLE; }
7476                 ;
7477 reindex_target_multitable:
7478                         SCHEMA                                  { $$ = REINDEX_OBJECT_SCHEMA; }
7479                         | SYSTEM_P                              { $$ = REINDEX_OBJECT_SYSTEM; }
7480                         | DATABASE                              { $$ = REINDEX_OBJECT_DATABASE; }
7481                 ;
7482 reindex_option_list:
7483                         reindex_option_elem                                                             { $$ = $1; }
7484                         | reindex_option_list ',' reindex_option_elem   { $$ = $1 | $3; }
7485                 ;
7486 reindex_option_elem:
7487                         VERBOSE { $$ = REINDEXOPT_VERBOSE; }
7488                 ;
7489
7490 /*****************************************************************************
7491  *
7492  * ALTER TABLESPACE
7493  *
7494  *****************************************************************************/
7495
7496 AlterTblSpcStmt:
7497                         ALTER TABLESPACE name SET reloptions
7498                                 {
7499                                         AlterTableSpaceOptionsStmt *n =
7500                                                 makeNode(AlterTableSpaceOptionsStmt);
7501                                         n->tablespacename = $3;
7502                                         n->options = $5;
7503                                         n->isReset = FALSE;
7504                                         $$ = (Node *)n;
7505                                 }
7506                         | ALTER TABLESPACE name RESET reloptions
7507                                 {
7508                                         AlterTableSpaceOptionsStmt *n =
7509                                                 makeNode(AlterTableSpaceOptionsStmt);
7510                                         n->tablespacename = $3;
7511                                         n->options = $5;
7512                                         n->isReset = TRUE;
7513                                         $$ = (Node *)n;
7514                                 }
7515                 ;
7516
7517 /*****************************************************************************
7518  *
7519  * ALTER THING name RENAME TO newname
7520  *
7521  *****************************************************************************/
7522
7523 RenameStmt: ALTER AGGREGATE func_name aggr_args RENAME TO name
7524                                 {
7525                                         RenameStmt *n = makeNode(RenameStmt);
7526                                         n->renameType = OBJECT_AGGREGATE;
7527                                         n->object = $3;
7528                                         n->objarg = extractAggrArgTypes($4);
7529                                         n->newname = $7;
7530                                         n->missing_ok = false;
7531                                         $$ = (Node *)n;
7532                                 }
7533                         | ALTER COLLATION any_name RENAME TO name
7534                                 {
7535                                         RenameStmt *n = makeNode(RenameStmt);
7536                                         n->renameType = OBJECT_COLLATION;
7537                                         n->object = $3;
7538                                         n->newname = $6;
7539                                         n->missing_ok = false;
7540                                         $$ = (Node *)n;
7541                                 }
7542                         | ALTER CONVERSION_P any_name RENAME TO name
7543                                 {
7544                                         RenameStmt *n = makeNode(RenameStmt);
7545                                         n->renameType = OBJECT_CONVERSION;
7546                                         n->object = $3;
7547                                         n->newname = $6;
7548                                         n->missing_ok = false;
7549                                         $$ = (Node *)n;
7550                                 }
7551                         | ALTER DATABASE database_name RENAME TO database_name
7552                                 {
7553                                         RenameStmt *n = makeNode(RenameStmt);
7554                                         n->renameType = OBJECT_DATABASE;
7555                                         n->subname = $3;
7556                                         n->newname = $6;
7557                                         n->missing_ok = false;
7558                                         $$ = (Node *)n;
7559                                 }
7560                         | ALTER DOMAIN_P any_name RENAME TO name
7561                                 {
7562                                         RenameStmt *n = makeNode(RenameStmt);
7563                                         n->renameType = OBJECT_DOMAIN;
7564                                         n->object = $3;
7565                                         n->newname = $6;
7566                                         n->missing_ok = false;
7567                                         $$ = (Node *)n;
7568                                 }
7569                         | ALTER DOMAIN_P any_name RENAME CONSTRAINT name TO name
7570                                 {
7571                                         RenameStmt *n = makeNode(RenameStmt);
7572                                         n->renameType = OBJECT_DOMCONSTRAINT;
7573                                         n->object = $3;
7574                                         n->subname = $6;
7575                                         n->newname = $8;
7576                                         $$ = (Node *)n;
7577                                 }
7578                         | ALTER FOREIGN DATA_P WRAPPER name RENAME TO name
7579                                 {
7580                                         RenameStmt *n = makeNode(RenameStmt);
7581                                         n->renameType = OBJECT_FDW;
7582                                         n->object = list_make1(makeString($5));
7583                                         n->newname = $8;
7584                                         n->missing_ok = false;
7585                                         $$ = (Node *)n;
7586                                 }
7587                         | ALTER FUNCTION function_with_argtypes RENAME TO name
7588                                 {
7589                                         RenameStmt *n = makeNode(RenameStmt);
7590                                         n->renameType = OBJECT_FUNCTION;
7591                                         n->object = $3->funcname;
7592                                         n->objarg = $3->funcargs;
7593                                         n->newname = $6;
7594                                         n->missing_ok = false;
7595                                         $$ = (Node *)n;
7596                                 }
7597                         | ALTER GROUP_P RoleId RENAME TO RoleId
7598                                 {
7599                                         RenameStmt *n = makeNode(RenameStmt);
7600                                         n->renameType = OBJECT_ROLE;
7601                                         n->subname = $3;
7602                                         n->newname = $6;
7603                                         n->missing_ok = false;
7604                                         $$ = (Node *)n;
7605                                 }
7606                         | ALTER opt_procedural LANGUAGE name RENAME TO name
7607                                 {
7608                                         RenameStmt *n = makeNode(RenameStmt);
7609                                         n->renameType = OBJECT_LANGUAGE;
7610                                         n->object = list_make1(makeString($4));
7611                                         n->newname = $7;
7612                                         n->missing_ok = false;
7613                                         $$ = (Node *)n;
7614                                 }
7615                         | ALTER OPERATOR CLASS any_name USING access_method RENAME TO name
7616                                 {
7617                                         RenameStmt *n = makeNode(RenameStmt);
7618                                         n->renameType = OBJECT_OPCLASS;
7619                                         n->object = lcons(makeString($6), $4);
7620                                         n->newname = $9;
7621                                         n->missing_ok = false;
7622                                         $$ = (Node *)n;
7623                                 }
7624                         | ALTER OPERATOR FAMILY any_name USING access_method RENAME TO name
7625                                 {
7626                                         RenameStmt *n = makeNode(RenameStmt);
7627                                         n->renameType = OBJECT_OPFAMILY;
7628                                         n->object = lcons(makeString($6), $4);
7629                                         n->newname = $9;
7630                                         n->missing_ok = false;
7631                                         $$ = (Node *)n;
7632                                 }
7633                         | ALTER POLICY name ON qualified_name RENAME TO name
7634                                 {
7635                                         RenameStmt *n = makeNode(RenameStmt);
7636                                         n->renameType = OBJECT_POLICY;
7637                                         n->relation = $5;
7638                                         n->subname = $3;
7639                                         n->newname = $8;
7640                                         n->missing_ok = false;
7641                                         $$ = (Node *)n;
7642                                 }
7643                         | ALTER POLICY IF_P EXISTS name ON qualified_name RENAME TO name
7644                                 {
7645                                         RenameStmt *n = makeNode(RenameStmt);
7646                                         n->renameType = OBJECT_POLICY;
7647                                         n->relation = $7;
7648                                         n->subname = $5;
7649                                         n->newname = $10;
7650                                         n->missing_ok = true;
7651                                         $$ = (Node *)n;
7652                                 }
7653                         | ALTER SCHEMA name RENAME TO name
7654                                 {
7655                                         RenameStmt *n = makeNode(RenameStmt);
7656                                         n->renameType = OBJECT_SCHEMA;
7657                                         n->subname = $3;
7658                                         n->newname = $6;
7659                                         n->missing_ok = false;
7660                                         $$ = (Node *)n;
7661                                 }
7662                         | ALTER SERVER name RENAME TO name
7663                                 {
7664                                         RenameStmt *n = makeNode(RenameStmt);
7665                                         n->renameType = OBJECT_FOREIGN_SERVER;
7666                                         n->object = list_make1(makeString($3));
7667                                         n->newname = $6;
7668                                         n->missing_ok = false;
7669                                         $$ = (Node *)n;
7670                                 }
7671                         | ALTER TABLE relation_expr RENAME TO name
7672                                 {
7673                                         RenameStmt *n = makeNode(RenameStmt);
7674                                         n->renameType = OBJECT_TABLE;
7675                                         n->relation = $3;
7676                                         n->subname = NULL;
7677                                         n->newname = $6;
7678                                         n->missing_ok = false;
7679                                         $$ = (Node *)n;
7680                                 }
7681                         | ALTER TABLE IF_P EXISTS relation_expr RENAME TO name
7682                                 {
7683                                         RenameStmt *n = makeNode(RenameStmt);
7684                                         n->renameType = OBJECT_TABLE;
7685                                         n->relation = $5;
7686                                         n->subname = NULL;
7687                                         n->newname = $8;
7688                                         n->missing_ok = true;
7689                                         $$ = (Node *)n;
7690                                 }
7691                         | ALTER SEQUENCE qualified_name RENAME TO name
7692                                 {
7693                                         RenameStmt *n = makeNode(RenameStmt);
7694                                         n->renameType = OBJECT_SEQUENCE;
7695                                         n->relation = $3;
7696                                         n->subname = NULL;
7697                                         n->newname = $6;
7698                                         n->missing_ok = false;
7699                                         $$ = (Node *)n;
7700                                 }
7701                         | ALTER SEQUENCE IF_P EXISTS qualified_name RENAME TO name
7702                                 {
7703                                         RenameStmt *n = makeNode(RenameStmt);
7704                                         n->renameType = OBJECT_SEQUENCE;
7705                                         n->relation = $5;
7706                                         n->subname = NULL;
7707                                         n->newname = $8;
7708                                         n->missing_ok = true;
7709                                         $$ = (Node *)n;
7710                                 }
7711                         | ALTER VIEW qualified_name RENAME TO name
7712                                 {
7713                                         RenameStmt *n = makeNode(RenameStmt);
7714                                         n->renameType = OBJECT_VIEW;
7715                                         n->relation = $3;
7716                                         n->subname = NULL;
7717                                         n->newname = $6;
7718                                         n->missing_ok = false;
7719                                         $$ = (Node *)n;
7720                                 }
7721                         | ALTER VIEW IF_P EXISTS qualified_name RENAME TO name
7722                                 {
7723                                         RenameStmt *n = makeNode(RenameStmt);
7724                                         n->renameType = OBJECT_VIEW;
7725                                         n->relation = $5;
7726                                         n->subname = NULL;
7727                                         n->newname = $8;
7728                                         n->missing_ok = true;
7729                                         $$ = (Node *)n;
7730                                 }
7731                         | ALTER MATERIALIZED VIEW qualified_name RENAME TO name
7732                                 {
7733                                         RenameStmt *n = makeNode(RenameStmt);
7734                                         n->renameType = OBJECT_MATVIEW;
7735                                         n->relation = $4;
7736                                         n->subname = NULL;
7737                                         n->newname = $7;
7738                                         n->missing_ok = false;
7739                                         $$ = (Node *)n;
7740                                 }
7741                         | ALTER MATERIALIZED VIEW IF_P EXISTS qualified_name RENAME TO name
7742                                 {
7743                                         RenameStmt *n = makeNode(RenameStmt);
7744                                         n->renameType = OBJECT_MATVIEW;
7745                                         n->relation = $6;
7746                                         n->subname = NULL;
7747                                         n->newname = $9;
7748                                         n->missing_ok = true;
7749                                         $$ = (Node *)n;
7750                                 }
7751                         | ALTER INDEX qualified_name RENAME TO name
7752                                 {
7753                                         RenameStmt *n = makeNode(RenameStmt);
7754                                         n->renameType = OBJECT_INDEX;
7755                                         n->relation = $3;
7756                                         n->subname = NULL;
7757                                         n->newname = $6;
7758                                         n->missing_ok = false;
7759                                         $$ = (Node *)n;
7760                                 }
7761                         | ALTER INDEX IF_P EXISTS qualified_name RENAME TO name
7762                                 {
7763                                         RenameStmt *n = makeNode(RenameStmt);
7764                                         n->renameType = OBJECT_INDEX;
7765                                         n->relation = $5;
7766                                         n->subname = NULL;
7767                                         n->newname = $8;
7768                                         n->missing_ok = true;
7769                                         $$ = (Node *)n;
7770                                 }
7771                         | ALTER FOREIGN TABLE relation_expr RENAME TO name
7772                                 {
7773                                         RenameStmt *n = makeNode(RenameStmt);
7774                                         n->renameType = OBJECT_FOREIGN_TABLE;
7775                                         n->relation = $4;
7776                                         n->subname = NULL;
7777                                         n->newname = $7;
7778                                         n->missing_ok = false;
7779                                         $$ = (Node *)n;
7780                                 }
7781                         | ALTER FOREIGN TABLE IF_P EXISTS relation_expr RENAME TO name
7782                                 {
7783                                         RenameStmt *n = makeNode(RenameStmt);
7784                                         n->renameType = OBJECT_FOREIGN_TABLE;
7785                                         n->relation = $6;
7786                                         n->subname = NULL;
7787                                         n->newname = $9;
7788                                         n->missing_ok = true;
7789                                         $$ = (Node *)n;
7790                                 }
7791                         | ALTER TABLE relation_expr RENAME opt_column name TO name
7792                                 {
7793                                         RenameStmt *n = makeNode(RenameStmt);
7794                                         n->renameType = OBJECT_COLUMN;
7795                                         n->relationType = OBJECT_TABLE;
7796                                         n->relation = $3;
7797                                         n->subname = $6;
7798                                         n->newname = $8;
7799                                         n->missing_ok = false;
7800                                         $$ = (Node *)n;
7801                                 }
7802                         | ALTER TABLE IF_P EXISTS relation_expr RENAME opt_column name TO name
7803                                 {
7804                                         RenameStmt *n = makeNode(RenameStmt);
7805                                         n->renameType = OBJECT_COLUMN;
7806                                         n->relationType = OBJECT_TABLE;
7807                                         n->relation = $5;
7808                                         n->subname = $8;
7809                                         n->newname = $10;
7810                                         n->missing_ok = true;
7811                                         $$ = (Node *)n;
7812                                 }
7813                         | ALTER MATERIALIZED VIEW qualified_name RENAME opt_column name TO name
7814                                 {
7815                                         RenameStmt *n = makeNode(RenameStmt);
7816                                         n->renameType = OBJECT_COLUMN;
7817                                         n->relationType = OBJECT_MATVIEW;
7818                                         n->relation = $4;
7819                                         n->subname = $7;
7820                                         n->newname = $9;
7821                                         n->missing_ok = false;
7822                                         $$ = (Node *)n;
7823                                 }
7824                         | ALTER MATERIALIZED VIEW IF_P EXISTS qualified_name RENAME opt_column name TO name
7825                                 {
7826                                         RenameStmt *n = makeNode(RenameStmt);
7827                                         n->renameType = OBJECT_COLUMN;
7828                                         n->relationType = OBJECT_MATVIEW;
7829                                         n->relation = $6;
7830                                         n->subname = $9;
7831                                         n->newname = $11;
7832                                         n->missing_ok = true;
7833                                         $$ = (Node *)n;
7834                                 }
7835                         | ALTER TABLE relation_expr RENAME CONSTRAINT name TO name
7836                                 {
7837                                         RenameStmt *n = makeNode(RenameStmt);
7838                                         n->renameType = OBJECT_TABCONSTRAINT;
7839                                         n->relation = $3;
7840                                         n->subname = $6;
7841                                         n->newname = $8;
7842                                         n->missing_ok = false;
7843                                         $$ = (Node *)n;
7844                                 }
7845                         | ALTER TABLE IF_P EXISTS relation_expr RENAME CONSTRAINT name TO name
7846                                 {
7847                                         RenameStmt *n = makeNode(RenameStmt);
7848                                         n->renameType = OBJECT_TABCONSTRAINT;
7849                                         n->relation = $5;
7850                                         n->subname = $8;
7851                                         n->newname = $10;
7852                                         n->missing_ok = true;
7853                                         $$ = (Node *)n;
7854                                 }
7855                         | ALTER FOREIGN TABLE relation_expr RENAME opt_column name TO name
7856                                 {
7857                                         RenameStmt *n = makeNode(RenameStmt);
7858                                         n->renameType = OBJECT_COLUMN;
7859                                         n->relationType = OBJECT_FOREIGN_TABLE;
7860                                         n->relation = $4;
7861                                         n->subname = $7;
7862                                         n->newname = $9;
7863                                         n->missing_ok = false;
7864                                         $$ = (Node *)n;
7865                                 }
7866                         | ALTER FOREIGN TABLE IF_P EXISTS relation_expr RENAME opt_column name TO name
7867                                 {
7868                                         RenameStmt *n = makeNode(RenameStmt);
7869                                         n->renameType = OBJECT_COLUMN;
7870                                         n->relationType = OBJECT_FOREIGN_TABLE;
7871                                         n->relation = $6;
7872                                         n->subname = $9;
7873                                         n->newname = $11;
7874                                         n->missing_ok = true;
7875                                         $$ = (Node *)n;
7876                                 }
7877                         | ALTER RULE name ON qualified_name RENAME TO name
7878                                 {
7879                                         RenameStmt *n = makeNode(RenameStmt);
7880                                         n->renameType = OBJECT_RULE;
7881                                         n->relation = $5;
7882                                         n->subname = $3;
7883                                         n->newname = $8;
7884                                         n->missing_ok = false;
7885                                         $$ = (Node *)n;
7886                                 }
7887                         | ALTER TRIGGER name ON qualified_name RENAME TO name
7888                                 {
7889                                         RenameStmt *n = makeNode(RenameStmt);
7890                                         n->renameType = OBJECT_TRIGGER;
7891                                         n->relation = $5;
7892                                         n->subname = $3;
7893                                         n->newname = $8;
7894                                         n->missing_ok = false;
7895                                         $$ = (Node *)n;
7896                                 }
7897                         | ALTER EVENT TRIGGER name RENAME TO name
7898                                 {
7899                                         RenameStmt *n = makeNode(RenameStmt);
7900                                         n->renameType = OBJECT_EVENT_TRIGGER;
7901                                         n->object = list_make1(makeString($4));
7902                                         n->newname = $7;
7903                                         $$ = (Node *)n;
7904                                 }
7905                         | ALTER ROLE RoleId RENAME TO RoleId
7906                                 {
7907                                         RenameStmt *n = makeNode(RenameStmt);
7908                                         n->renameType = OBJECT_ROLE;
7909                                         n->subname = $3;
7910                                         n->newname = $6;
7911                                         n->missing_ok = false;
7912                                         $$ = (Node *)n;
7913                                 }
7914                         | ALTER USER RoleId RENAME TO RoleId
7915                                 {
7916                                         RenameStmt *n = makeNode(RenameStmt);
7917                                         n->renameType = OBJECT_ROLE;
7918                                         n->subname = $3;
7919                                         n->newname = $6;
7920                                         n->missing_ok = false;
7921                                         $$ = (Node *)n;
7922                                 }
7923                         | ALTER TABLESPACE name RENAME TO name
7924                                 {
7925                                         RenameStmt *n = makeNode(RenameStmt);
7926                                         n->renameType = OBJECT_TABLESPACE;
7927                                         n->subname = $3;
7928                                         n->newname = $6;
7929                                         n->missing_ok = false;
7930                                         $$ = (Node *)n;
7931                                 }
7932                         | ALTER TEXT_P SEARCH PARSER any_name RENAME TO name
7933                                 {
7934                                         RenameStmt *n = makeNode(RenameStmt);
7935                                         n->renameType = OBJECT_TSPARSER;
7936                                         n->object = $5;
7937                                         n->newname = $8;
7938                                         n->missing_ok = false;
7939                                         $$ = (Node *)n;
7940                                 }
7941                         | ALTER TEXT_P SEARCH DICTIONARY any_name RENAME TO name
7942                                 {
7943                                         RenameStmt *n = makeNode(RenameStmt);
7944                                         n->renameType = OBJECT_TSDICTIONARY;
7945                                         n->object = $5;
7946                                         n->newname = $8;
7947                                         n->missing_ok = false;
7948                                         $$ = (Node *)n;
7949                                 }
7950                         | ALTER TEXT_P SEARCH TEMPLATE any_name RENAME TO name
7951                                 {
7952                                         RenameStmt *n = makeNode(RenameStmt);
7953                                         n->renameType = OBJECT_TSTEMPLATE;
7954                                         n->object = $5;
7955                                         n->newname = $8;
7956                                         n->missing_ok = false;
7957                                         $$ = (Node *)n;
7958                                 }
7959                         | ALTER TEXT_P SEARCH CONFIGURATION any_name RENAME TO name
7960                                 {
7961                                         RenameStmt *n = makeNode(RenameStmt);
7962                                         n->renameType = OBJECT_TSCONFIGURATION;
7963                                         n->object = $5;
7964                                         n->newname = $8;
7965                                         n->missing_ok = false;
7966                                         $$ = (Node *)n;
7967                                 }
7968                         | ALTER TYPE_P any_name RENAME TO name
7969                                 {
7970                                         RenameStmt *n = makeNode(RenameStmt);
7971                                         n->renameType = OBJECT_TYPE;
7972                                         n->object = $3;
7973                                         n->newname = $6;
7974                                         n->missing_ok = false;
7975                                         $$ = (Node *)n;
7976                                 }
7977                         | ALTER TYPE_P any_name RENAME ATTRIBUTE name TO name opt_drop_behavior
7978                                 {
7979                                         RenameStmt *n = makeNode(RenameStmt);
7980                                         n->renameType = OBJECT_ATTRIBUTE;
7981                                         n->relationType = OBJECT_TYPE;
7982                                         n->relation = makeRangeVarFromAnyName($3, @3, yyscanner);
7983                                         n->subname = $6;
7984                                         n->newname = $8;
7985                                         n->behavior = $9;
7986                                         n->missing_ok = false;
7987                                         $$ = (Node *)n;
7988                                 }
7989                 ;
7990
7991 opt_column: COLUMN                                                                      { $$ = COLUMN; }
7992                         | /*EMPTY*/                                                             { $$ = 0; }
7993                 ;
7994
7995 opt_set_data: SET DATA_P                                                        { $$ = 1; }
7996                         | /*EMPTY*/                                                             { $$ = 0; }
7997                 ;
7998
7999 /*****************************************************************************
8000  *
8001  * ALTER THING name SET SCHEMA name
8002  *
8003  *****************************************************************************/
8004
8005 AlterObjectSchemaStmt:
8006                         ALTER AGGREGATE func_name aggr_args SET SCHEMA name
8007                                 {
8008                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8009                                         n->objectType = OBJECT_AGGREGATE;
8010                                         n->object = $3;
8011                                         n->objarg = extractAggrArgTypes($4);
8012                                         n->newschema = $7;
8013                                         n->missing_ok = false;
8014                                         $$ = (Node *)n;
8015                                 }
8016                         | ALTER COLLATION any_name SET SCHEMA name
8017                                 {
8018                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8019                                         n->objectType = OBJECT_COLLATION;
8020                                         n->object = $3;
8021                                         n->newschema = $6;
8022                                         n->missing_ok = false;
8023                                         $$ = (Node *)n;
8024                                 }
8025                         | ALTER CONVERSION_P any_name SET SCHEMA name
8026                                 {
8027                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8028                                         n->objectType = OBJECT_CONVERSION;
8029                                         n->object = $3;
8030                                         n->newschema = $6;
8031                                         n->missing_ok = false;
8032                                         $$ = (Node *)n;
8033                                 }
8034                         | ALTER DOMAIN_P any_name SET SCHEMA name
8035                                 {
8036                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8037                                         n->objectType = OBJECT_DOMAIN;
8038                                         n->object = $3;
8039                                         n->newschema = $6;
8040                                         n->missing_ok = false;
8041                                         $$ = (Node *)n;
8042                                 }
8043                         | ALTER EXTENSION any_name SET SCHEMA name
8044                                 {
8045                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8046                                         n->objectType = OBJECT_EXTENSION;
8047                                         n->object = $3;
8048                                         n->newschema = $6;
8049                                         n->missing_ok = false;
8050                                         $$ = (Node *)n;
8051                                 }
8052                         | ALTER FUNCTION function_with_argtypes SET SCHEMA name
8053                                 {
8054                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8055                                         n->objectType = OBJECT_FUNCTION;
8056                                         n->object = $3->funcname;
8057                                         n->objarg = $3->funcargs;
8058                                         n->newschema = $6;
8059                                         n->missing_ok = false;
8060                                         $$ = (Node *)n;
8061                                 }
8062                         | ALTER OPERATOR any_operator oper_argtypes SET SCHEMA name
8063                                 {
8064                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8065                                         n->objectType = OBJECT_OPERATOR;
8066                                         n->object = $3;
8067                                         n->objarg = $4;
8068                                         n->newschema = $7;
8069                                         n->missing_ok = false;
8070                                         $$ = (Node *)n;
8071                                 }
8072                         | ALTER OPERATOR CLASS any_name USING access_method SET SCHEMA name
8073                                 {
8074                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8075                                         n->objectType = OBJECT_OPCLASS;
8076                                         n->object = lcons(makeString($6), $4);
8077                                         n->newschema = $9;
8078                                         n->missing_ok = false;
8079                                         $$ = (Node *)n;
8080                                 }
8081                         | ALTER OPERATOR FAMILY any_name USING access_method SET SCHEMA name
8082                                 {
8083                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8084                                         n->objectType = OBJECT_OPFAMILY;
8085                                         n->object = lcons(makeString($6), $4);
8086                                         n->newschema = $9;
8087                                         n->missing_ok = false;
8088                                         $$ = (Node *)n;
8089                                 }
8090                         | ALTER TABLE relation_expr SET SCHEMA name
8091                                 {
8092                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8093                                         n->objectType = OBJECT_TABLE;
8094                                         n->relation = $3;
8095                                         n->newschema = $6;
8096                                         n->missing_ok = false;
8097                                         $$ = (Node *)n;
8098                                 }
8099                         | ALTER TABLE IF_P EXISTS relation_expr SET SCHEMA name
8100                                 {
8101                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8102                                         n->objectType = OBJECT_TABLE;
8103                                         n->relation = $5;
8104                                         n->newschema = $8;
8105                                         n->missing_ok = true;
8106                                         $$ = (Node *)n;
8107                                 }
8108                         | ALTER TEXT_P SEARCH PARSER any_name SET SCHEMA name
8109                                 {
8110                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8111                                         n->objectType = OBJECT_TSPARSER;
8112                                         n->object = $5;
8113                                         n->newschema = $8;
8114                                         n->missing_ok = false;
8115                                         $$ = (Node *)n;
8116                                 }
8117                         | ALTER TEXT_P SEARCH DICTIONARY any_name SET SCHEMA name
8118                                 {
8119                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8120                                         n->objectType = OBJECT_TSDICTIONARY;
8121                                         n->object = $5;
8122                                         n->newschema = $8;
8123                                         n->missing_ok = false;
8124                                         $$ = (Node *)n;
8125                                 }
8126                         | ALTER TEXT_P SEARCH TEMPLATE any_name SET SCHEMA name
8127                                 {
8128                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8129                                         n->objectType = OBJECT_TSTEMPLATE;
8130                                         n->object = $5;
8131                                         n->newschema = $8;
8132                                         n->missing_ok = false;
8133                                         $$ = (Node *)n;
8134                                 }
8135                         | ALTER TEXT_P SEARCH CONFIGURATION any_name SET SCHEMA name
8136                                 {
8137                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8138                                         n->objectType = OBJECT_TSCONFIGURATION;
8139                                         n->object = $5;
8140                                         n->newschema = $8;
8141                                         n->missing_ok = false;
8142                                         $$ = (Node *)n;
8143                                 }
8144                         | ALTER SEQUENCE qualified_name SET SCHEMA name
8145                                 {
8146                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8147                                         n->objectType = OBJECT_SEQUENCE;
8148                                         n->relation = $3;
8149                                         n->newschema = $6;
8150                                         n->missing_ok = false;
8151                                         $$ = (Node *)n;
8152                                 }
8153                         | ALTER SEQUENCE IF_P EXISTS qualified_name SET SCHEMA name
8154                                 {
8155                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8156                                         n->objectType = OBJECT_SEQUENCE;
8157                                         n->relation = $5;
8158                                         n->newschema = $8;
8159                                         n->missing_ok = true;
8160                                         $$ = (Node *)n;
8161                                 }
8162                         | ALTER VIEW qualified_name SET SCHEMA name
8163                                 {
8164                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8165                                         n->objectType = OBJECT_VIEW;
8166                                         n->relation = $3;
8167                                         n->newschema = $6;
8168                                         n->missing_ok = false;
8169                                         $$ = (Node *)n;
8170                                 }
8171                         | ALTER VIEW IF_P EXISTS qualified_name SET SCHEMA name
8172                                 {
8173                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8174                                         n->objectType = OBJECT_VIEW;
8175                                         n->relation = $5;
8176                                         n->newschema = $8;
8177                                         n->missing_ok = true;
8178                                         $$ = (Node *)n;
8179                                 }
8180                         | ALTER MATERIALIZED VIEW qualified_name SET SCHEMA name
8181                                 {
8182                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8183                                         n->objectType = OBJECT_MATVIEW;
8184                                         n->relation = $4;
8185                                         n->newschema = $7;
8186                                         n->missing_ok = false;
8187                                         $$ = (Node *)n;
8188                                 }
8189                         | ALTER MATERIALIZED VIEW IF_P EXISTS qualified_name SET SCHEMA name
8190                                 {
8191                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8192                                         n->objectType = OBJECT_MATVIEW;
8193                                         n->relation = $6;
8194                                         n->newschema = $9;
8195                                         n->missing_ok = true;
8196                                         $$ = (Node *)n;
8197                                 }
8198                         | ALTER FOREIGN TABLE relation_expr SET SCHEMA name
8199                                 {
8200                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8201                                         n->objectType = OBJECT_FOREIGN_TABLE;
8202                                         n->relation = $4;
8203                                         n->newschema = $7;
8204                                         n->missing_ok = false;
8205                                         $$ = (Node *)n;
8206                                 }
8207                         | ALTER FOREIGN TABLE IF_P EXISTS relation_expr SET SCHEMA name
8208                                 {
8209                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8210                                         n->objectType = OBJECT_FOREIGN_TABLE;
8211                                         n->relation = $6;
8212                                         n->newschema = $9;
8213                                         n->missing_ok = true;
8214                                         $$ = (Node *)n;
8215                                 }
8216                         | ALTER TYPE_P any_name SET SCHEMA name
8217                                 {
8218                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
8219                                         n->objectType = OBJECT_TYPE;
8220                                         n->object = $3;
8221                                         n->newschema = $6;
8222                                         n->missing_ok = false;
8223                                         $$ = (Node *)n;
8224                                 }
8225                 ;
8226
8227 /*****************************************************************************
8228  *
8229  * ALTER OPERATOR name SET define
8230  *
8231  *****************************************************************************/
8232
8233 AlterOperatorStmt:
8234                         ALTER OPERATOR any_operator oper_argtypes SET '(' operator_def_list ')'
8235                                 {
8236                                         AlterOperatorStmt *n = makeNode(AlterOperatorStmt);
8237                                         n->opername = $3;
8238                                         n->operargs = $4;
8239                                         n->options = $7;
8240                                         $$ = (Node *)n;
8241                                 }
8242                 ;
8243
8244 operator_def_list:      operator_def_elem                                                               { $$ = list_make1($1); }
8245                         | operator_def_list ',' operator_def_elem                               { $$ = lappend($1, $3); }
8246                 ;
8247
8248 operator_def_elem: ColLabel '=' NONE
8249                                                 { $$ = makeDefElem($1, NULL); }
8250                                    | ColLabel '=' def_arg
8251                                                 { $$ = makeDefElem($1, (Node *) $3); }
8252                 ;
8253
8254 /*****************************************************************************
8255  *
8256  * ALTER THING name OWNER TO newname
8257  *
8258  *****************************************************************************/
8259
8260 AlterOwnerStmt: ALTER AGGREGATE func_name aggr_args OWNER TO RoleSpec
8261                                 {
8262                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8263                                         n->objectType = OBJECT_AGGREGATE;
8264                                         n->object = $3;
8265                                         n->objarg = extractAggrArgTypes($4);
8266                                         n->newowner = $7;
8267                                         $$ = (Node *)n;
8268                                 }
8269                         | ALTER COLLATION any_name OWNER TO RoleSpec
8270                                 {
8271                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8272                                         n->objectType = OBJECT_COLLATION;
8273                                         n->object = $3;
8274                                         n->newowner = $6;
8275                                         $$ = (Node *)n;
8276                                 }
8277                         | ALTER CONVERSION_P any_name OWNER TO RoleSpec
8278                                 {
8279                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8280                                         n->objectType = OBJECT_CONVERSION;
8281                                         n->object = $3;
8282                                         n->newowner = $6;
8283                                         $$ = (Node *)n;
8284                                 }
8285                         | ALTER DATABASE database_name OWNER TO RoleSpec
8286                                 {
8287                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8288                                         n->objectType = OBJECT_DATABASE;
8289                                         n->object = list_make1(makeString($3));
8290                                         n->newowner = $6;
8291                                         $$ = (Node *)n;
8292                                 }
8293                         | ALTER DOMAIN_P any_name OWNER TO RoleSpec
8294                                 {
8295                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8296                                         n->objectType = OBJECT_DOMAIN;
8297                                         n->object = $3;
8298                                         n->newowner = $6;
8299                                         $$ = (Node *)n;
8300                                 }
8301                         | ALTER FUNCTION function_with_argtypes OWNER TO RoleSpec
8302                                 {
8303                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8304                                         n->objectType = OBJECT_FUNCTION;
8305                                         n->object = $3->funcname;
8306                                         n->objarg = $3->funcargs;
8307                                         n->newowner = $6;
8308                                         $$ = (Node *)n;
8309                                 }
8310                         | ALTER opt_procedural LANGUAGE name OWNER TO RoleSpec
8311                                 {
8312                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8313                                         n->objectType = OBJECT_LANGUAGE;
8314                                         n->object = list_make1(makeString($4));
8315                                         n->newowner = $7;
8316                                         $$ = (Node *)n;
8317                                 }
8318                         | ALTER LARGE_P OBJECT_P NumericOnly OWNER TO RoleSpec
8319                                 {
8320                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8321                                         n->objectType = OBJECT_LARGEOBJECT;
8322                                         n->object = list_make1($4);
8323                                         n->newowner = $7;
8324                                         $$ = (Node *)n;
8325                                 }
8326                         | ALTER OPERATOR any_operator oper_argtypes OWNER TO RoleSpec
8327                                 {
8328                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8329                                         n->objectType = OBJECT_OPERATOR;
8330                                         n->object = $3;
8331                                         n->objarg = $4;
8332                                         n->newowner = $7;
8333                                         $$ = (Node *)n;
8334                                 }
8335                         | ALTER OPERATOR CLASS any_name USING access_method OWNER TO RoleSpec
8336                                 {
8337                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8338                                         n->objectType = OBJECT_OPCLASS;
8339                                         n->object = lcons(makeString($6), $4);
8340                                         n->newowner = $9;
8341                                         $$ = (Node *)n;
8342                                 }
8343                         | ALTER OPERATOR FAMILY any_name USING access_method OWNER TO RoleSpec
8344                                 {
8345                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8346                                         n->objectType = OBJECT_OPFAMILY;
8347                                         n->object = lcons(makeString($6), $4);
8348                                         n->newowner = $9;
8349                                         $$ = (Node *)n;
8350                                 }
8351                         | ALTER SCHEMA name OWNER TO RoleSpec
8352                                 {
8353                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8354                                         n->objectType = OBJECT_SCHEMA;
8355                                         n->object = list_make1(makeString($3));
8356                                         n->newowner = $6;
8357                                         $$ = (Node *)n;
8358                                 }
8359                         | ALTER TYPE_P any_name OWNER TO RoleSpec
8360                                 {
8361                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8362                                         n->objectType = OBJECT_TYPE;
8363                                         n->object = $3;
8364                                         n->newowner = $6;
8365                                         $$ = (Node *)n;
8366                                 }
8367                         | ALTER TABLESPACE name OWNER TO RoleSpec
8368                                 {
8369                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8370                                         n->objectType = OBJECT_TABLESPACE;
8371                                         n->object = list_make1(makeString($3));
8372                                         n->newowner = $6;
8373                                         $$ = (Node *)n;
8374                                 }
8375                         | ALTER TEXT_P SEARCH DICTIONARY any_name OWNER TO RoleSpec
8376                                 {
8377                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8378                                         n->objectType = OBJECT_TSDICTIONARY;
8379                                         n->object = $5;
8380                                         n->newowner = $8;
8381                                         $$ = (Node *)n;
8382                                 }
8383                         | ALTER TEXT_P SEARCH CONFIGURATION any_name OWNER TO RoleSpec
8384                                 {
8385                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8386                                         n->objectType = OBJECT_TSCONFIGURATION;
8387                                         n->object = $5;
8388                                         n->newowner = $8;
8389                                         $$ = (Node *)n;
8390                                 }
8391                         | ALTER FOREIGN DATA_P WRAPPER name OWNER TO RoleSpec
8392                                 {
8393                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8394                                         n->objectType = OBJECT_FDW;
8395                                         n->object = list_make1(makeString($5));
8396                                         n->newowner = $8;
8397                                         $$ = (Node *)n;
8398                                 }
8399                         | ALTER SERVER name OWNER TO RoleSpec
8400                                 {
8401                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8402                                         n->objectType = OBJECT_FOREIGN_SERVER;
8403                                         n->object = list_make1(makeString($3));
8404                                         n->newowner = $6;
8405                                         $$ = (Node *)n;
8406                                 }
8407                         | ALTER EVENT TRIGGER name OWNER TO RoleSpec
8408                                 {
8409                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
8410                                         n->objectType = OBJECT_EVENT_TRIGGER;
8411                                         n->object = list_make1(makeString($4));
8412                                         n->newowner = $7;
8413                                         $$ = (Node *)n;
8414                                 }
8415                 ;
8416
8417
8418 /*****************************************************************************
8419  *
8420  *              QUERY:  Define Rewrite Rule
8421  *
8422  *****************************************************************************/
8423
8424 RuleStmt:       CREATE opt_or_replace RULE name AS
8425                         ON event TO qualified_name where_clause
8426                         DO opt_instead RuleActionList
8427                                 {
8428                                         RuleStmt *n = makeNode(RuleStmt);
8429                                         n->replace = $2;
8430                                         n->relation = $9;
8431                                         n->rulename = $4;
8432                                         n->whereClause = $10;
8433                                         n->event = $7;
8434                                         n->instead = $12;
8435                                         n->actions = $13;
8436                                         $$ = (Node *)n;
8437                                 }
8438                 ;
8439
8440 RuleActionList:
8441                         NOTHING                                                                 { $$ = NIL; }
8442                         | RuleActionStmt                                                { $$ = list_make1($1); }
8443                         | '(' RuleActionMulti ')'                               { $$ = $2; }
8444                 ;
8445
8446 /* the thrashing around here is to discard "empty" statements... */
8447 RuleActionMulti:
8448                         RuleActionMulti ';' RuleActionStmtOrEmpty
8449                                 { if ($3 != NULL)
8450                                         $$ = lappend($1, $3);
8451                                   else
8452                                         $$ = $1;
8453                                 }
8454                         | RuleActionStmtOrEmpty
8455                                 { if ($1 != NULL)
8456                                         $$ = list_make1($1);
8457                                   else
8458                                         $$ = NIL;
8459                                 }
8460                 ;
8461
8462 RuleActionStmt:
8463                         SelectStmt
8464                         | InsertStmt
8465                         | UpdateStmt
8466                         | DeleteStmt
8467                         | NotifyStmt
8468                 ;
8469
8470 RuleActionStmtOrEmpty:
8471                         RuleActionStmt                                                  { $$ = $1; }
8472                         |       /*EMPTY*/                                                       { $$ = NULL; }
8473                 ;
8474
8475 event:          SELECT                                                                  { $$ = CMD_SELECT; }
8476                         | UPDATE                                                                { $$ = CMD_UPDATE; }
8477                         | DELETE_P                                                              { $$ = CMD_DELETE; }
8478                         | INSERT                                                                { $$ = CMD_INSERT; }
8479                  ;
8480
8481 opt_instead:
8482                         INSTEAD                                                                 { $$ = TRUE; }
8483                         | ALSO                                                                  { $$ = FALSE; }
8484                         | /*EMPTY*/                                                             { $$ = FALSE; }
8485                 ;
8486
8487
8488 DropRuleStmt:
8489                         DROP RULE name ON any_name opt_drop_behavior
8490                                 {
8491                                         DropStmt *n = makeNode(DropStmt);
8492                                         n->removeType = OBJECT_RULE;
8493                                         n->objects = list_make1(lappend($5, makeString($3)));
8494                                         n->arguments = NIL;
8495                                         n->behavior = $6;
8496                                         n->missing_ok = false;
8497                                         n->concurrent = false;
8498                                         $$ = (Node *) n;
8499                                 }
8500                         | DROP RULE IF_P EXISTS name ON any_name opt_drop_behavior
8501                                 {
8502                                         DropStmt *n = makeNode(DropStmt);
8503                                         n->removeType = OBJECT_RULE;
8504                                         n->objects = list_make1(lappend($7, makeString($5)));
8505                                         n->arguments = NIL;
8506                                         n->behavior = $8;
8507                                         n->missing_ok = true;
8508                                         n->concurrent = false;
8509                                         $$ = (Node *) n;
8510                                 }
8511                 ;
8512
8513
8514 /*****************************************************************************
8515  *
8516  *              QUERY:
8517  *                              NOTIFY <identifier> can appear both in rule bodies and
8518  *                              as a query-level command
8519  *
8520  *****************************************************************************/
8521
8522 NotifyStmt: NOTIFY ColId notify_payload
8523                                 {
8524                                         NotifyStmt *n = makeNode(NotifyStmt);
8525                                         n->conditionname = $2;
8526                                         n->payload = $3;
8527                                         $$ = (Node *)n;
8528                                 }
8529                 ;
8530
8531 notify_payload:
8532                         ',' Sconst                                                      { $$ = $2; }
8533                         | /*EMPTY*/                                                     { $$ = NULL; }
8534                 ;
8535
8536 ListenStmt: LISTEN ColId
8537                                 {
8538                                         ListenStmt *n = makeNode(ListenStmt);
8539                                         n->conditionname = $2;
8540                                         $$ = (Node *)n;
8541                                 }
8542                 ;
8543
8544 UnlistenStmt:
8545                         UNLISTEN ColId
8546                                 {
8547                                         UnlistenStmt *n = makeNode(UnlistenStmt);
8548                                         n->conditionname = $2;
8549                                         $$ = (Node *)n;
8550                                 }
8551                         | UNLISTEN '*'
8552                                 {
8553                                         UnlistenStmt *n = makeNode(UnlistenStmt);
8554                                         n->conditionname = NULL;
8555                                         $$ = (Node *)n;
8556                                 }
8557                 ;
8558
8559
8560 /*****************************************************************************
8561  *
8562  *              Transactions:
8563  *
8564  *              BEGIN / COMMIT / ROLLBACK
8565  *              (also older versions END / ABORT)
8566  *
8567  *****************************************************************************/
8568
8569 TransactionStmt:
8570                         ABORT_P opt_transaction
8571                                 {
8572                                         TransactionStmt *n = makeNode(TransactionStmt);
8573                                         n->kind = TRANS_STMT_ROLLBACK;
8574                                         n->options = NIL;
8575                                         $$ = (Node *)n;
8576                                 }
8577                         | BEGIN_P opt_transaction transaction_mode_list_or_empty
8578                                 {
8579                                         TransactionStmt *n = makeNode(TransactionStmt);
8580                                         n->kind = TRANS_STMT_BEGIN;
8581                                         n->options = $3;
8582                                         $$ = (Node *)n;
8583                                 }
8584                         | START TRANSACTION transaction_mode_list_or_empty
8585                                 {
8586                                         TransactionStmt *n = makeNode(TransactionStmt);
8587                                         n->kind = TRANS_STMT_START;
8588                                         n->options = $3;
8589                                         $$ = (Node *)n;
8590                                 }
8591                         | COMMIT opt_transaction
8592                                 {
8593                                         TransactionStmt *n = makeNode(TransactionStmt);
8594                                         n->kind = TRANS_STMT_COMMIT;
8595                                         n->options = NIL;
8596                                         $$ = (Node *)n;
8597                                 }
8598                         | END_P opt_transaction
8599                                 {
8600                                         TransactionStmt *n = makeNode(TransactionStmt);
8601                                         n->kind = TRANS_STMT_COMMIT;
8602                                         n->options = NIL;
8603                                         $$ = (Node *)n;
8604                                 }
8605                         | ROLLBACK opt_transaction
8606                                 {
8607                                         TransactionStmt *n = makeNode(TransactionStmt);
8608                                         n->kind = TRANS_STMT_ROLLBACK;
8609                                         n->options = NIL;
8610                                         $$ = (Node *)n;
8611                                 }
8612                         | SAVEPOINT ColId
8613                                 {
8614                                         TransactionStmt *n = makeNode(TransactionStmt);
8615                                         n->kind = TRANS_STMT_SAVEPOINT;
8616                                         n->options = list_make1(makeDefElem("savepoint_name",
8617                                                                                                                 (Node *)makeString($2)));
8618                                         $$ = (Node *)n;
8619                                 }
8620                         | RELEASE SAVEPOINT ColId
8621                                 {
8622                                         TransactionStmt *n = makeNode(TransactionStmt);
8623                                         n->kind = TRANS_STMT_RELEASE;
8624                                         n->options = list_make1(makeDefElem("savepoint_name",
8625                                                                                                                 (Node *)makeString($3)));
8626                                         $$ = (Node *)n;
8627                                 }
8628                         | RELEASE ColId
8629                                 {
8630                                         TransactionStmt *n = makeNode(TransactionStmt);
8631                                         n->kind = TRANS_STMT_RELEASE;
8632                                         n->options = list_make1(makeDefElem("savepoint_name",
8633                                                                                                                 (Node *)makeString($2)));
8634                                         $$ = (Node *)n;
8635                                 }
8636                         | ROLLBACK opt_transaction TO SAVEPOINT ColId
8637                                 {
8638                                         TransactionStmt *n = makeNode(TransactionStmt);
8639                                         n->kind = TRANS_STMT_ROLLBACK_TO;
8640                                         n->options = list_make1(makeDefElem("savepoint_name",
8641                                                                                                                 (Node *)makeString($5)));
8642                                         $$ = (Node *)n;
8643                                 }
8644                         | ROLLBACK opt_transaction TO ColId
8645                                 {
8646                                         TransactionStmt *n = makeNode(TransactionStmt);
8647                                         n->kind = TRANS_STMT_ROLLBACK_TO;
8648                                         n->options = list_make1(makeDefElem("savepoint_name",
8649                                                                                                                 (Node *)makeString($4)));
8650                                         $$ = (Node *)n;
8651                                 }
8652                         | PREPARE TRANSACTION Sconst
8653                                 {
8654                                         TransactionStmt *n = makeNode(TransactionStmt);
8655                                         n->kind = TRANS_STMT_PREPARE;
8656                                         n->gid = $3;
8657                                         $$ = (Node *)n;
8658                                 }
8659                         | COMMIT PREPARED Sconst
8660                                 {
8661                                         TransactionStmt *n = makeNode(TransactionStmt);
8662                                         n->kind = TRANS_STMT_COMMIT_PREPARED;
8663                                         n->gid = $3;
8664                                         $$ = (Node *)n;
8665                                 }
8666                         | ROLLBACK PREPARED Sconst
8667                                 {
8668                                         TransactionStmt *n = makeNode(TransactionStmt);
8669                                         n->kind = TRANS_STMT_ROLLBACK_PREPARED;
8670                                         n->gid = $3;
8671                                         $$ = (Node *)n;
8672                                 }
8673                 ;
8674
8675 opt_transaction:        WORK                                                    {}
8676                         | TRANSACTION                                                   {}
8677                         | /*EMPTY*/                                                             {}
8678                 ;
8679
8680 transaction_mode_item:
8681                         ISOLATION LEVEL iso_level
8682                                         { $$ = makeDefElem("transaction_isolation",
8683                                                                            makeStringConst($3, @3)); }
8684                         | READ ONLY
8685                                         { $$ = makeDefElem("transaction_read_only",
8686                                                                            makeIntConst(TRUE, @1)); }
8687                         | READ WRITE
8688                                         { $$ = makeDefElem("transaction_read_only",
8689                                                                            makeIntConst(FALSE, @1)); }
8690                         | DEFERRABLE
8691                                         { $$ = makeDefElem("transaction_deferrable",
8692                                                                            makeIntConst(TRUE, @1)); }
8693                         | NOT DEFERRABLE
8694                                         { $$ = makeDefElem("transaction_deferrable",
8695                                                                            makeIntConst(FALSE, @1)); }
8696                 ;
8697
8698 /* Syntax with commas is SQL-spec, without commas is Postgres historical */
8699 transaction_mode_list:
8700                         transaction_mode_item
8701                                         { $$ = list_make1($1); }
8702                         | transaction_mode_list ',' transaction_mode_item
8703                                         { $$ = lappend($1, $3); }
8704                         | transaction_mode_list transaction_mode_item
8705                                         { $$ = lappend($1, $2); }
8706                 ;
8707
8708 transaction_mode_list_or_empty:
8709                         transaction_mode_list
8710                         | /* EMPTY */
8711                                         { $$ = NIL; }
8712                 ;
8713
8714
8715 /*****************************************************************************
8716  *
8717  *      QUERY:
8718  *              CREATE [ OR REPLACE ] [ TEMP ] VIEW <viewname> '('target-list ')'
8719  *                      AS <query> [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
8720  *
8721  *****************************************************************************/
8722
8723 ViewStmt: CREATE OptTemp VIEW qualified_name opt_column_list opt_reloptions
8724                                 AS SelectStmt opt_check_option
8725                                 {
8726                                         ViewStmt *n = makeNode(ViewStmt);
8727                                         n->view = $4;
8728                                         n->view->relpersistence = $2;
8729                                         n->aliases = $5;
8730                                         n->query = $8;
8731                                         n->replace = false;
8732                                         n->options = $6;
8733                                         n->withCheckOption = $9;
8734                                         $$ = (Node *) n;
8735                                 }
8736                 | CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list opt_reloptions
8737                                 AS SelectStmt opt_check_option
8738                                 {
8739                                         ViewStmt *n = makeNode(ViewStmt);
8740                                         n->view = $6;
8741                                         n->view->relpersistence = $4;
8742                                         n->aliases = $7;
8743                                         n->query = $10;
8744                                         n->replace = true;
8745                                         n->options = $8;
8746                                         n->withCheckOption = $11;
8747                                         $$ = (Node *) n;
8748                                 }
8749                 | CREATE OptTemp RECURSIVE VIEW qualified_name '(' columnList ')' opt_reloptions
8750                                 AS SelectStmt opt_check_option
8751                                 {
8752                                         ViewStmt *n = makeNode(ViewStmt);
8753                                         n->view = $5;
8754                                         n->view->relpersistence = $2;
8755                                         n->aliases = $7;
8756                                         n->query = makeRecursiveViewSelect(n->view->relname, n->aliases, $11);
8757                                         n->replace = false;
8758                                         n->options = $9;
8759                                         n->withCheckOption = $12;
8760                                         if (n->withCheckOption != NO_CHECK_OPTION)
8761                                                 ereport(ERROR,
8762                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8763                                                                  errmsg("WITH CHECK OPTION not supported on recursive views"),
8764                                                                  parser_errposition(@12)));
8765                                         $$ = (Node *) n;
8766                                 }
8767                 | CREATE OR REPLACE OptTemp RECURSIVE VIEW qualified_name '(' columnList ')' opt_reloptions
8768                                 AS SelectStmt opt_check_option
8769                                 {
8770                                         ViewStmt *n = makeNode(ViewStmt);
8771                                         n->view = $7;
8772                                         n->view->relpersistence = $4;
8773                                         n->aliases = $9;
8774                                         n->query = makeRecursiveViewSelect(n->view->relname, n->aliases, $13);
8775                                         n->replace = true;
8776                                         n->options = $11;
8777                                         n->withCheckOption = $14;
8778                                         if (n->withCheckOption != NO_CHECK_OPTION)
8779                                                 ereport(ERROR,
8780                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8781                                                                  errmsg("WITH CHECK OPTION not supported on recursive views"),
8782                                                                  parser_errposition(@14)));
8783                                         $$ = (Node *) n;
8784                                 }
8785                 ;
8786
8787 opt_check_option:
8788                 WITH CHECK OPTION                               { $$ = CASCADED_CHECK_OPTION; }
8789                 | WITH CASCADED CHECK OPTION    { $$ = CASCADED_CHECK_OPTION; }
8790                 | WITH LOCAL CHECK OPTION               { $$ = LOCAL_CHECK_OPTION; }
8791                 | /* EMPTY */                                   { $$ = NO_CHECK_OPTION; }
8792                 ;
8793
8794 /*****************************************************************************
8795  *
8796  *              QUERY:
8797  *                              LOAD "filename"
8798  *
8799  *****************************************************************************/
8800
8801 LoadStmt:       LOAD file_name
8802                                 {
8803                                         LoadStmt *n = makeNode(LoadStmt);
8804                                         n->filename = $2;
8805                                         $$ = (Node *)n;
8806                                 }
8807                 ;
8808
8809
8810 /*****************************************************************************
8811  *
8812  *              CREATE DATABASE
8813  *
8814  *****************************************************************************/
8815
8816 CreatedbStmt:
8817                         CREATE DATABASE database_name opt_with createdb_opt_list
8818                                 {
8819                                         CreatedbStmt *n = makeNode(CreatedbStmt);
8820                                         n->dbname = $3;
8821                                         n->options = $5;
8822                                         $$ = (Node *)n;
8823                                 }
8824                 ;
8825
8826 createdb_opt_list:
8827                         createdb_opt_items                                              { $$ = $1; }
8828                         | /* EMPTY */                                                   { $$ = NIL; }
8829                 ;
8830
8831 createdb_opt_items:
8832                         createdb_opt_item                                               { $$ = list_make1($1); }
8833                         | createdb_opt_items createdb_opt_item  { $$ = lappend($1, $2); }
8834                 ;
8835
8836 createdb_opt_item:
8837                         createdb_opt_name opt_equal SignedIconst
8838                                 {
8839                                         $$ = makeDefElem($1, (Node *)makeInteger($3));
8840                                 }
8841                         | createdb_opt_name opt_equal opt_boolean_or_string
8842                                 {
8843                                         $$ = makeDefElem($1, (Node *)makeString($3));
8844                                 }
8845                         | createdb_opt_name opt_equal DEFAULT
8846                                 {
8847                                         $$ = makeDefElem($1, NULL);
8848                                 }
8849                 ;
8850
8851 /*
8852  * Ideally we'd use ColId here, but that causes shift/reduce conflicts against
8853  * the ALTER DATABASE SET/RESET syntaxes.  Instead call out specific keywords
8854  * we need, and allow IDENT so that database option names don't have to be
8855  * parser keywords unless they are already keywords for other reasons.
8856  *
8857  * XXX this coding technique is fragile since if someone makes a formerly
8858  * non-keyword option name into a keyword and forgets to add it here, the
8859  * option will silently break.  Best defense is to provide a regression test
8860  * exercising every such option, at least at the syntax level.
8861  */
8862 createdb_opt_name:
8863                         IDENT                                                   { $$ = $1; }
8864                         | CONNECTION LIMIT                              { $$ = pstrdup("connection_limit"); }
8865                         | ENCODING                                              { $$ = pstrdup($1); }
8866                         | LOCATION                                              { $$ = pstrdup($1); }
8867                         | OWNER                                                 { $$ = pstrdup($1); }
8868                         | TABLESPACE                                    { $$ = pstrdup($1); }
8869                         | TEMPLATE                                              { $$ = pstrdup($1); }
8870                 ;
8871
8872 /*
8873  *      Though the equals sign doesn't match other WITH options, pg_dump uses
8874  *      equals for backward compatibility, and it doesn't seem worth removing it.
8875  */
8876 opt_equal:      '='                                                                             {}
8877                         | /*EMPTY*/                                                             {}
8878                 ;
8879
8880
8881 /*****************************************************************************
8882  *
8883  *              ALTER DATABASE
8884  *
8885  *****************************************************************************/
8886
8887 AlterDatabaseStmt:
8888                         ALTER DATABASE database_name WITH createdb_opt_list
8889                                  {
8890                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
8891                                         n->dbname = $3;
8892                                         n->options = $5;
8893                                         $$ = (Node *)n;
8894                                  }
8895                         | ALTER DATABASE database_name createdb_opt_list
8896                                  {
8897                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
8898                                         n->dbname = $3;
8899                                         n->options = $4;
8900                                         $$ = (Node *)n;
8901                                  }
8902                         | ALTER DATABASE database_name SET TABLESPACE name
8903                                  {
8904                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
8905                                         n->dbname = $3;
8906                                         n->options = list_make1(makeDefElem("tablespace",
8907                                                                                                         (Node *)makeString($6)));
8908                                         $$ = (Node *)n;
8909                                  }
8910                 ;
8911
8912 AlterDatabaseSetStmt:
8913                         ALTER DATABASE database_name SetResetClause
8914                                 {
8915                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
8916                                         n->dbname = $3;
8917                                         n->setstmt = $4;
8918                                         $$ = (Node *)n;
8919                                 }
8920                 ;
8921
8922
8923 /*****************************************************************************
8924  *
8925  *              DROP DATABASE [ IF EXISTS ]
8926  *
8927  * This is implicitly CASCADE, no need for drop behavior
8928  *****************************************************************************/
8929
8930 DropdbStmt: DROP DATABASE database_name
8931                                 {
8932                                         DropdbStmt *n = makeNode(DropdbStmt);
8933                                         n->dbname = $3;
8934                                         n->missing_ok = FALSE;
8935                                         $$ = (Node *)n;
8936                                 }
8937                         | DROP DATABASE IF_P EXISTS database_name
8938                                 {
8939                                         DropdbStmt *n = makeNode(DropdbStmt);
8940                                         n->dbname = $5;
8941                                         n->missing_ok = TRUE;
8942                                         $$ = (Node *)n;
8943                                 }
8944                 ;
8945
8946
8947 /*****************************************************************************
8948  *
8949  *              ALTER SYSTEM
8950  *
8951  * This is used to change configuration parameters persistently.
8952  *****************************************************************************/
8953
8954 AlterSystemStmt:
8955                         ALTER SYSTEM_P SET generic_set
8956                                 {
8957                                         AlterSystemStmt *n = makeNode(AlterSystemStmt);
8958                                         n->setstmt = $4;
8959                                         $$ = (Node *)n;
8960                                 }
8961                         | ALTER SYSTEM_P RESET generic_reset
8962                                 {
8963                                         AlterSystemStmt *n = makeNode(AlterSystemStmt);
8964                                         n->setstmt = $4;
8965                                         $$ = (Node *)n;
8966                                 }
8967                 ;
8968
8969
8970 /*****************************************************************************
8971  *
8972  * Manipulate a domain
8973  *
8974  *****************************************************************************/
8975
8976 CreateDomainStmt:
8977                         CREATE DOMAIN_P any_name opt_as Typename ColQualList
8978                                 {
8979                                         CreateDomainStmt *n = makeNode(CreateDomainStmt);
8980                                         n->domainname = $3;
8981                                         n->typeName = $5;
8982                                         SplitColQualList($6, &n->constraints, &n->collClause,
8983                                                                          yyscanner);
8984                                         $$ = (Node *)n;
8985                                 }
8986                 ;
8987
8988 AlterDomainStmt:
8989                         /* ALTER DOMAIN <domain> {SET DEFAULT <expr>|DROP DEFAULT} */
8990                         ALTER DOMAIN_P any_name alter_column_default
8991                                 {
8992                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
8993                                         n->subtype = 'T';
8994                                         n->typeName = $3;
8995                                         n->def = $4;
8996                                         $$ = (Node *)n;
8997                                 }
8998                         /* ALTER DOMAIN <domain> DROP NOT NULL */
8999                         | ALTER DOMAIN_P any_name DROP NOT NULL_P
9000                                 {
9001                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
9002                                         n->subtype = 'N';
9003                                         n->typeName = $3;
9004                                         $$ = (Node *)n;
9005                                 }
9006                         /* ALTER DOMAIN <domain> SET NOT NULL */
9007                         | ALTER DOMAIN_P any_name SET NOT NULL_P
9008                                 {
9009                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
9010                                         n->subtype = 'O';
9011                                         n->typeName = $3;
9012                                         $$ = (Node *)n;
9013                                 }
9014                         /* ALTER DOMAIN <domain> ADD CONSTRAINT ... */
9015                         | ALTER DOMAIN_P any_name ADD_P TableConstraint
9016                                 {
9017                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
9018                                         n->subtype = 'C';
9019                                         n->typeName = $3;
9020                                         n->def = $5;
9021                                         $$ = (Node *)n;
9022                                 }
9023                         /* ALTER DOMAIN <domain> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
9024                         | ALTER DOMAIN_P any_name DROP CONSTRAINT name opt_drop_behavior
9025                                 {
9026                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
9027                                         n->subtype = 'X';
9028                                         n->typeName = $3;
9029                                         n->name = $6;
9030                                         n->behavior = $7;
9031                                         n->missing_ok = false;
9032                                         $$ = (Node *)n;
9033                                 }
9034                         /* ALTER DOMAIN <domain> DROP CONSTRAINT IF EXISTS <name> [RESTRICT|CASCADE] */
9035                         | ALTER DOMAIN_P any_name DROP CONSTRAINT IF_P EXISTS name opt_drop_behavior
9036                                 {
9037                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
9038                                         n->subtype = 'X';
9039                                         n->typeName = $3;
9040                                         n->name = $8;
9041                                         n->behavior = $9;
9042                                         n->missing_ok = true;
9043                                         $$ = (Node *)n;
9044                                 }
9045                         /* ALTER DOMAIN <domain> VALIDATE CONSTRAINT <name> */
9046                         | ALTER DOMAIN_P any_name VALIDATE CONSTRAINT name
9047                                 {
9048                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
9049                                         n->subtype = 'V';
9050                                         n->typeName = $3;
9051                                         n->name = $6;
9052                                         $$ = (Node *)n;
9053                                 }
9054                         ;
9055
9056 opt_as:         AS                                                                              {}
9057                         | /* EMPTY */                                                   {}
9058                 ;
9059
9060
9061 /*****************************************************************************
9062  *
9063  * Manipulate a text search dictionary or configuration
9064  *
9065  *****************************************************************************/
9066
9067 AlterTSDictionaryStmt:
9068                         ALTER TEXT_P SEARCH DICTIONARY any_name definition
9069                                 {
9070                                         AlterTSDictionaryStmt *n = makeNode(AlterTSDictionaryStmt);
9071                                         n->dictname = $5;
9072                                         n->options = $6;
9073                                         $$ = (Node *)n;
9074                                 }
9075                 ;
9076
9077 AlterTSConfigurationStmt:
9078                         ALTER TEXT_P SEARCH CONFIGURATION any_name ADD_P MAPPING FOR name_list any_with any_name_list
9079                                 {
9080                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
9081                                         n->kind = ALTER_TSCONFIG_ADD_MAPPING;
9082                                         n->cfgname = $5;
9083                                         n->tokentype = $9;
9084                                         n->dicts = $11;
9085                                         n->override = false;
9086                                         n->replace = false;
9087                                         $$ = (Node*)n;
9088                                 }
9089                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list any_with any_name_list
9090                                 {
9091                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
9092                                         n->kind = ALTER_TSCONFIG_ALTER_MAPPING_FOR_TOKEN;
9093                                         n->cfgname = $5;
9094                                         n->tokentype = $9;
9095                                         n->dicts = $11;
9096                                         n->override = true;
9097                                         n->replace = false;
9098                                         $$ = (Node*)n;
9099                                 }
9100                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING REPLACE any_name any_with any_name
9101                                 {
9102                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
9103                                         n->kind = ALTER_TSCONFIG_REPLACE_DICT;
9104                                         n->cfgname = $5;
9105                                         n->tokentype = NIL;
9106                                         n->dicts = list_make2($9,$11);
9107                                         n->override = false;
9108                                         n->replace = true;
9109                                         $$ = (Node*)n;
9110                                 }
9111                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list REPLACE any_name any_with any_name
9112                                 {
9113                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
9114                                         n->kind = ALTER_TSCONFIG_REPLACE_DICT_FOR_TOKEN;
9115                                         n->cfgname = $5;
9116                                         n->tokentype = $9;
9117                                         n->dicts = list_make2($11,$13);
9118                                         n->override = false;
9119                                         n->replace = true;
9120                                         $$ = (Node*)n;
9121                                 }
9122                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING FOR name_list
9123                                 {
9124                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
9125                                         n->kind = ALTER_TSCONFIG_DROP_MAPPING;
9126                                         n->cfgname = $5;
9127                                         n->tokentype = $9;
9128                                         n->missing_ok = false;
9129                                         $$ = (Node*)n;
9130                                 }
9131                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING IF_P EXISTS FOR name_list
9132                                 {
9133                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
9134                                         n->kind = ALTER_TSCONFIG_DROP_MAPPING;
9135                                         n->cfgname = $5;
9136                                         n->tokentype = $11;
9137                                         n->missing_ok = true;
9138                                         $$ = (Node*)n;
9139                                 }
9140                 ;
9141
9142 /* Use this if TIME or ORDINALITY after WITH should be taken as an identifier */
9143 any_with:       WITH                                                                    {}
9144                         | WITH_LA                                                               {}
9145                 ;
9146
9147
9148 /*****************************************************************************
9149  *
9150  * Manipulate a conversion
9151  *
9152  *              CREATE [DEFAULT] CONVERSION <conversion_name>
9153  *              FOR <encoding_name> TO <encoding_name> FROM <func_name>
9154  *
9155  *****************************************************************************/
9156
9157 CreateConversionStmt:
9158                         CREATE opt_default CONVERSION_P any_name FOR Sconst
9159                         TO Sconst FROM any_name
9160                         {
9161                                 CreateConversionStmt *n = makeNode(CreateConversionStmt);
9162                                 n->conversion_name = $4;
9163                                 n->for_encoding_name = $6;
9164                                 n->to_encoding_name = $8;
9165                                 n->func_name = $10;
9166                                 n->def = $2;
9167                                 $$ = (Node *)n;
9168                         }
9169                 ;
9170
9171 /*****************************************************************************
9172  *
9173  *              QUERY:
9174  *                              CLUSTER [VERBOSE] <qualified_name> [ USING <index_name> ]
9175  *                              CLUSTER [VERBOSE]
9176  *                              CLUSTER [VERBOSE] <index_name> ON <qualified_name> (for pre-8.3)
9177  *
9178  *****************************************************************************/
9179
9180 ClusterStmt:
9181                         CLUSTER opt_verbose qualified_name cluster_index_specification
9182                                 {
9183                                         ClusterStmt *n = makeNode(ClusterStmt);
9184                                         n->relation = $3;
9185                                         n->indexname = $4;
9186                                         n->verbose = $2;
9187                                         $$ = (Node*)n;
9188                                 }
9189                         | CLUSTER opt_verbose
9190                                 {
9191                                         ClusterStmt *n = makeNode(ClusterStmt);
9192                                         n->relation = NULL;
9193                                         n->indexname = NULL;
9194                                         n->verbose = $2;
9195                                         $$ = (Node*)n;
9196                                 }
9197                         /* kept for pre-8.3 compatibility */
9198                         | CLUSTER opt_verbose index_name ON qualified_name
9199                                 {
9200                                         ClusterStmt *n = makeNode(ClusterStmt);
9201                                         n->relation = $5;
9202                                         n->indexname = $3;
9203                                         n->verbose = $2;
9204                                         $$ = (Node*)n;
9205                                 }
9206                 ;
9207
9208 cluster_index_specification:
9209                         USING index_name                { $$ = $2; }
9210                         | /*EMPTY*/                             { $$ = NULL; }
9211                 ;
9212
9213
9214 /*****************************************************************************
9215  *
9216  *              QUERY:
9217  *                              VACUUM
9218  *                              ANALYZE
9219  *
9220  *****************************************************************************/
9221
9222 VacuumStmt: VACUUM opt_full opt_freeze opt_verbose
9223                                 {
9224                                         VacuumStmt *n = makeNode(VacuumStmt);
9225                                         n->options = VACOPT_VACUUM;
9226                                         if ($2)
9227                                                 n->options |= VACOPT_FULL;
9228                                         if ($3)
9229                                                 n->options |= VACOPT_FREEZE;
9230                                         if ($4)
9231                                                 n->options |= VACOPT_VERBOSE;
9232                                         n->relation = NULL;
9233                                         n->va_cols = NIL;
9234                                         $$ = (Node *)n;
9235                                 }
9236                         | VACUUM opt_full opt_freeze opt_verbose qualified_name
9237                                 {
9238                                         VacuumStmt *n = makeNode(VacuumStmt);
9239                                         n->options = VACOPT_VACUUM;
9240                                         if ($2)
9241                                                 n->options |= VACOPT_FULL;
9242                                         if ($3)
9243                                                 n->options |= VACOPT_FREEZE;
9244                                         if ($4)
9245                                                 n->options |= VACOPT_VERBOSE;
9246                                         n->relation = $5;
9247                                         n->va_cols = NIL;
9248                                         $$ = (Node *)n;
9249                                 }
9250                         | VACUUM opt_full opt_freeze opt_verbose AnalyzeStmt
9251                                 {
9252                                         VacuumStmt *n = (VacuumStmt *) $5;
9253                                         n->options |= VACOPT_VACUUM;
9254                                         if ($2)
9255                                                 n->options |= VACOPT_FULL;
9256                                         if ($3)
9257                                                 n->options |= VACOPT_FREEZE;
9258                                         if ($4)
9259                                                 n->options |= VACOPT_VERBOSE;
9260                                         $$ = (Node *)n;
9261                                 }
9262                         | VACUUM '(' vacuum_option_list ')'
9263                                 {
9264                                         VacuumStmt *n = makeNode(VacuumStmt);
9265                                         n->options = VACOPT_VACUUM | $3;
9266                                         n->relation = NULL;
9267                                         n->va_cols = NIL;
9268                                         $$ = (Node *) n;
9269                                 }
9270                         | VACUUM '(' vacuum_option_list ')' qualified_name opt_name_list
9271                                 {
9272                                         VacuumStmt *n = makeNode(VacuumStmt);
9273                                         n->options = VACOPT_VACUUM | $3;
9274                                         n->relation = $5;
9275                                         n->va_cols = $6;
9276                                         if (n->va_cols != NIL)  /* implies analyze */
9277                                                 n->options |= VACOPT_ANALYZE;
9278                                         $$ = (Node *) n;
9279                                 }
9280                 ;
9281
9282 vacuum_option_list:
9283                         vacuum_option_elem                                                              { $$ = $1; }
9284                         | vacuum_option_list ',' vacuum_option_elem             { $$ = $1 | $3; }
9285                 ;
9286
9287 vacuum_option_elem:
9288                         analyze_keyword         { $$ = VACOPT_ANALYZE; }
9289                         | VERBOSE                       { $$ = VACOPT_VERBOSE; }
9290                         | FREEZE                        { $$ = VACOPT_FREEZE; }
9291                         | FULL                          { $$ = VACOPT_FULL; }
9292                 ;
9293
9294 AnalyzeStmt:
9295                         analyze_keyword opt_verbose
9296                                 {
9297                                         VacuumStmt *n = makeNode(VacuumStmt);
9298                                         n->options = VACOPT_ANALYZE;
9299                                         if ($2)
9300                                                 n->options |= VACOPT_VERBOSE;
9301                                         n->relation = NULL;
9302                                         n->va_cols = NIL;
9303                                         $$ = (Node *)n;
9304                                 }
9305                         | analyze_keyword opt_verbose qualified_name opt_name_list
9306                                 {
9307                                         VacuumStmt *n = makeNode(VacuumStmt);
9308                                         n->options = VACOPT_ANALYZE;
9309                                         if ($2)
9310                                                 n->options |= VACOPT_VERBOSE;
9311                                         n->relation = $3;
9312                                         n->va_cols = $4;
9313                                         $$ = (Node *)n;
9314                                 }
9315                 ;
9316
9317 analyze_keyword:
9318                         ANALYZE                                                                 {}
9319                         | ANALYSE /* British */                                 {}
9320                 ;
9321
9322 opt_verbose:
9323                         VERBOSE                                                                 { $$ = TRUE; }
9324                         | /*EMPTY*/                                                             { $$ = FALSE; }
9325                 ;
9326
9327 opt_full:       FULL                                                                    { $$ = TRUE; }
9328                         | /*EMPTY*/                                                             { $$ = FALSE; }
9329                 ;
9330
9331 opt_freeze: FREEZE                                                                      { $$ = TRUE; }
9332                         | /*EMPTY*/                                                             { $$ = FALSE; }
9333                 ;
9334
9335 opt_name_list:
9336                         '(' name_list ')'                                               { $$ = $2; }
9337                         | /*EMPTY*/                                                             { $$ = NIL; }
9338                 ;
9339
9340
9341 /*****************************************************************************
9342  *
9343  *              QUERY:
9344  *                              EXPLAIN [ANALYZE] [VERBOSE] query
9345  *                              EXPLAIN ( options ) query
9346  *
9347  *****************************************************************************/
9348
9349 ExplainStmt:
9350                 EXPLAIN ExplainableStmt
9351                                 {
9352                                         ExplainStmt *n = makeNode(ExplainStmt);
9353                                         n->query = $2;
9354                                         n->options = NIL;
9355                                         $$ = (Node *) n;
9356                                 }
9357                 | EXPLAIN analyze_keyword opt_verbose ExplainableStmt
9358                                 {
9359                                         ExplainStmt *n = makeNode(ExplainStmt);
9360                                         n->query = $4;
9361                                         n->options = list_make1(makeDefElem("analyze", NULL));
9362                                         if ($3)
9363                                                 n->options = lappend(n->options,
9364                                                                                          makeDefElem("verbose", NULL));
9365                                         $$ = (Node *) n;
9366                                 }
9367                 | EXPLAIN VERBOSE ExplainableStmt
9368                                 {
9369                                         ExplainStmt *n = makeNode(ExplainStmt);
9370                                         n->query = $3;
9371                                         n->options = list_make1(makeDefElem("verbose", NULL));
9372                                         $$ = (Node *) n;
9373                                 }
9374                 | EXPLAIN '(' explain_option_list ')' ExplainableStmt
9375                                 {
9376                                         ExplainStmt *n = makeNode(ExplainStmt);
9377                                         n->query = $5;
9378                                         n->options = $3;
9379                                         $$ = (Node *) n;
9380                                 }
9381                 ;
9382
9383 ExplainableStmt:
9384                         SelectStmt
9385                         | InsertStmt
9386                         | UpdateStmt
9387                         | DeleteStmt
9388                         | DeclareCursorStmt
9389                         | CreateAsStmt
9390                         | CreateMatViewStmt
9391                         | RefreshMatViewStmt
9392                         | ExecuteStmt                                   /* by default all are $$=$1 */
9393                 ;
9394
9395 explain_option_list:
9396                         explain_option_elem
9397                                 {
9398                                         $$ = list_make1($1);
9399                                 }
9400                         | explain_option_list ',' explain_option_elem
9401                                 {
9402                                         $$ = lappend($1, $3);
9403                                 }
9404                 ;
9405
9406 explain_option_elem:
9407                         explain_option_name explain_option_arg
9408                                 {
9409                                         $$ = makeDefElem($1, $2);
9410                                 }
9411                 ;
9412
9413 explain_option_name:
9414                         NonReservedWord                 { $$ = $1; }
9415                         | analyze_keyword               { $$ = "analyze"; }
9416                 ;
9417
9418 explain_option_arg:
9419                         opt_boolean_or_string   { $$ = (Node *) makeString($1); }
9420                         | NumericOnly                   { $$ = (Node *) $1; }
9421                         | /* EMPTY */                   { $$ = NULL; }
9422                 ;
9423
9424 /*****************************************************************************
9425  *
9426  *              QUERY:
9427  *                              PREPARE <plan_name> [(args, ...)] AS <query>
9428  *
9429  *****************************************************************************/
9430
9431 PrepareStmt: PREPARE name prep_type_clause AS PreparableStmt
9432                                 {
9433                                         PrepareStmt *n = makeNode(PrepareStmt);
9434                                         n->name = $2;
9435                                         n->argtypes = $3;
9436                                         n->query = $5;
9437                                         $$ = (Node *) n;
9438                                 }
9439                 ;
9440
9441 prep_type_clause: '(' type_list ')'                     { $$ = $2; }
9442                                 | /* EMPTY */                           { $$ = NIL; }
9443                 ;
9444
9445 PreparableStmt:
9446                         SelectStmt
9447                         | InsertStmt
9448                         | UpdateStmt
9449                         | DeleteStmt                                    /* by default all are $$=$1 */
9450                 ;
9451
9452 /*****************************************************************************
9453  *
9454  * EXECUTE <plan_name> [(params, ...)]
9455  * CREATE TABLE <name> AS EXECUTE <plan_name> [(params, ...)]
9456  *
9457  *****************************************************************************/
9458
9459 ExecuteStmt: EXECUTE name execute_param_clause
9460                                 {
9461                                         ExecuteStmt *n = makeNode(ExecuteStmt);
9462                                         n->name = $2;
9463                                         n->params = $3;
9464                                         $$ = (Node *) n;
9465                                 }
9466                         | CREATE OptTemp TABLE create_as_target AS
9467                                 EXECUTE name execute_param_clause opt_with_data
9468                                 {
9469                                         CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
9470                                         ExecuteStmt *n = makeNode(ExecuteStmt);
9471                                         n->name = $7;
9472                                         n->params = $8;
9473                                         ctas->query = (Node *) n;
9474                                         ctas->into = $4;
9475                                         ctas->relkind = OBJECT_TABLE;
9476                                         ctas->is_select_into = false;
9477                                         /* cram additional flags into the IntoClause */
9478                                         $4->rel->relpersistence = $2;
9479                                         $4->skipData = !($9);
9480                                         $$ = (Node *) ctas;
9481                                 }
9482                 ;
9483
9484 execute_param_clause: '(' expr_list ')'                         { $$ = $2; }
9485                                         | /* EMPTY */                                   { $$ = NIL; }
9486                                         ;
9487
9488 /*****************************************************************************
9489  *
9490  *              QUERY:
9491  *                              DEALLOCATE [PREPARE] <plan_name>
9492  *
9493  *****************************************************************************/
9494
9495 DeallocateStmt: DEALLOCATE name
9496                                         {
9497                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
9498                                                 n->name = $2;
9499                                                 $$ = (Node *) n;
9500                                         }
9501                                 | DEALLOCATE PREPARE name
9502                                         {
9503                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
9504                                                 n->name = $3;
9505                                                 $$ = (Node *) n;
9506                                         }
9507                                 | DEALLOCATE ALL
9508                                         {
9509                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
9510                                                 n->name = NULL;
9511                                                 $$ = (Node *) n;
9512                                         }
9513                                 | DEALLOCATE PREPARE ALL
9514                                         {
9515                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
9516                                                 n->name = NULL;
9517                                                 $$ = (Node *) n;
9518                                         }
9519                 ;
9520
9521 /*****************************************************************************
9522  *
9523  *              QUERY:
9524  *                              INSERT STATEMENTS
9525  *
9526  *****************************************************************************/
9527
9528 InsertStmt:
9529                         opt_with_clause INSERT INTO insert_target insert_rest
9530                         opt_on_conflict returning_clause
9531                                 {
9532                                         $5->relation = $4;
9533                                         $5->onConflictClause = $6;
9534                                         $5->returningList = $7;
9535                                         $5->withClause = $1;
9536                                         $$ = (Node *) $5;
9537                                 }
9538                 ;
9539
9540 /*
9541  * Can't easily make AS optional here, because VALUES in insert_rest would
9542  * have a shift/reduce conflict with VALUES as an optional alias.  We could
9543  * easily allow unreserved_keywords as optional aliases, but that'd be an odd
9544  * divergence from other places.  So just require AS for now.
9545  */
9546 insert_target:
9547                         qualified_name
9548                                 {
9549                                         $$ = $1;
9550                                 }
9551                         | qualified_name AS ColId
9552                                 {
9553                                         $1->alias = makeAlias($3, NIL);
9554                                         $$ = $1;
9555                                 }
9556                 ;
9557
9558 insert_rest:
9559                         SelectStmt
9560                                 {
9561                                         $$ = makeNode(InsertStmt);
9562                                         $$->cols = NIL;
9563                                         $$->selectStmt = $1;
9564                                 }
9565                         | '(' insert_column_list ')' SelectStmt
9566                                 {
9567                                         $$ = makeNode(InsertStmt);
9568                                         $$->cols = $2;
9569                                         $$->selectStmt = $4;
9570                                 }
9571                         | DEFAULT VALUES
9572                                 {
9573                                         $$ = makeNode(InsertStmt);
9574                                         $$->cols = NIL;
9575                                         $$->selectStmt = NULL;
9576                                 }
9577                 ;
9578
9579 insert_column_list:
9580                         insert_column_item
9581                                         { $$ = list_make1($1); }
9582                         | insert_column_list ',' insert_column_item
9583                                         { $$ = lappend($1, $3); }
9584                 ;
9585
9586 insert_column_item:
9587                         ColId opt_indirection
9588                                 {
9589                                         $$ = makeNode(ResTarget);
9590                                         $$->name = $1;
9591                                         $$->indirection = check_indirection($2, yyscanner);
9592                                         $$->val = NULL;
9593                                         $$->location = @1;
9594                                 }
9595                 ;
9596
9597 opt_on_conflict:
9598                         ON CONFLICT opt_conf_expr DO UPDATE SET set_clause_list where_clause
9599                                 {
9600                                         $$ = makeNode(OnConflictClause);
9601                                         $$->action = ONCONFLICT_UPDATE;
9602                                         $$->infer = $3;
9603                                         $$->targetList = $7;
9604                                         $$->whereClause = $8;
9605                                         $$->location = @1;
9606                                 }
9607                         |
9608                         ON CONFLICT opt_conf_expr DO NOTHING
9609                                 {
9610                                         $$ = makeNode(OnConflictClause);
9611                                         $$->action = ONCONFLICT_NOTHING;
9612                                         $$->infer = $3;
9613                                         $$->targetList = NIL;
9614                                         $$->whereClause = NULL;
9615                                         $$->location = @1;
9616                                 }
9617                         | /*EMPTY*/
9618                                 {
9619                                         $$ = NULL;
9620                                 }
9621                 ;
9622
9623 opt_conf_expr:
9624                         '(' index_params ')' where_clause
9625                                 {
9626                                         $$ = makeNode(InferClause);
9627                                         $$->indexElems = $2;
9628                                         $$->whereClause = $4;
9629                                         $$->conname = NULL;
9630                                         $$->location = @1;
9631                                 }
9632                         |
9633                         ON CONSTRAINT name
9634                                 {
9635                                         $$ = makeNode(InferClause);
9636                                         $$->indexElems = NIL;
9637                                         $$->whereClause = NULL;
9638                                         $$->conname = $3;
9639                                         $$->location = @1;
9640                                 }
9641                         | /*EMPTY*/
9642                                 {
9643                                         $$ = NULL;
9644                                 }
9645                 ;
9646
9647 returning_clause:
9648                         RETURNING target_list           { $$ = $2; }
9649                         | /* EMPTY */                           { $$ = NIL; }
9650                 ;
9651
9652
9653 /*****************************************************************************
9654  *
9655  *              QUERY:
9656  *                              DELETE STATEMENTS
9657  *
9658  *****************************************************************************/
9659
9660 DeleteStmt: opt_with_clause DELETE_P FROM relation_expr_opt_alias
9661                         using_clause where_or_current_clause returning_clause
9662                                 {
9663                                         DeleteStmt *n = makeNode(DeleteStmt);
9664                                         n->relation = $4;
9665                                         n->usingClause = $5;
9666                                         n->whereClause = $6;
9667                                         n->returningList = $7;
9668                                         n->withClause = $1;
9669                                         $$ = (Node *)n;
9670                                 }
9671                 ;
9672
9673 using_clause:
9674                                 USING from_list                                         { $$ = $2; }
9675                         | /*EMPTY*/                                                             { $$ = NIL; }
9676                 ;
9677
9678
9679 /*****************************************************************************
9680  *
9681  *              QUERY:
9682  *                              LOCK TABLE
9683  *
9684  *****************************************************************************/
9685
9686 LockStmt:       LOCK_P opt_table relation_expr_list opt_lock opt_nowait
9687                                 {
9688                                         LockStmt *n = makeNode(LockStmt);
9689
9690                                         n->relations = $3;
9691                                         n->mode = $4;
9692                                         n->nowait = $5;
9693                                         $$ = (Node *)n;
9694                                 }
9695                 ;
9696
9697 opt_lock:       IN_P lock_type MODE                             { $$ = $2; }
9698                         | /*EMPTY*/                                             { $$ = AccessExclusiveLock; }
9699                 ;
9700
9701 lock_type:      ACCESS SHARE                                    { $$ = AccessShareLock; }
9702                         | ROW SHARE                                             { $$ = RowShareLock; }
9703                         | ROW EXCLUSIVE                                 { $$ = RowExclusiveLock; }
9704                         | SHARE UPDATE EXCLUSIVE                { $$ = ShareUpdateExclusiveLock; }
9705                         | SHARE                                                 { $$ = ShareLock; }
9706                         | SHARE ROW EXCLUSIVE                   { $$ = ShareRowExclusiveLock; }
9707                         | EXCLUSIVE                                             { $$ = ExclusiveLock; }
9708                         | ACCESS EXCLUSIVE                              { $$ = AccessExclusiveLock; }
9709                 ;
9710
9711 opt_nowait:     NOWAIT                                                  { $$ = TRUE; }
9712                         | /*EMPTY*/                                             { $$ = FALSE; }
9713                 ;
9714
9715 opt_nowait_or_skip:
9716                         NOWAIT                                                  { $$ = LockWaitError; }
9717                         | SKIP LOCKED                                   { $$ = LockWaitSkip; }
9718                         | /*EMPTY*/                                             { $$ = LockWaitBlock; }
9719                 ;
9720
9721
9722 /*****************************************************************************
9723  *
9724  *              QUERY:
9725  *                              UpdateStmt (UPDATE)
9726  *
9727  *****************************************************************************/
9728
9729 UpdateStmt: opt_with_clause UPDATE relation_expr_opt_alias
9730                         SET set_clause_list
9731                         from_clause
9732                         where_or_current_clause
9733                         returning_clause
9734                                 {
9735                                         UpdateStmt *n = makeNode(UpdateStmt);
9736                                         n->relation = $3;
9737                                         n->targetList = $5;
9738                                         n->fromClause = $6;
9739                                         n->whereClause = $7;
9740                                         n->returningList = $8;
9741                                         n->withClause = $1;
9742                                         $$ = (Node *)n;
9743                                 }
9744                 ;
9745
9746 set_clause_list:
9747                         set_clause                                                      { $$ = $1; }
9748                         | set_clause_list ',' set_clause        { $$ = list_concat($1,$3); }
9749                 ;
9750
9751 set_clause:
9752                         single_set_clause                                               { $$ = list_make1($1); }
9753                         | multiple_set_clause                                   { $$ = $1; }
9754                 ;
9755
9756 single_set_clause:
9757                         set_target '=' ctext_expr
9758                                 {
9759                                         $$ = $1;
9760                                         $$->val = (Node *) $3;
9761                                 }
9762                 ;
9763
9764 /*
9765  * Ideally, we'd accept any row-valued a_expr as RHS of a multiple_set_clause.
9766  * However, per SQL spec the row-constructor case must allow DEFAULT as a row
9767  * member, and it's pretty unclear how to do that (unless perhaps we allow
9768  * DEFAULT in any a_expr and let parse analysis sort it out later?).  For the
9769  * moment, the planner/executor only support a subquery as a multiassignment
9770  * source anyhow, so we need only accept ctext_row and subqueries here.
9771  */
9772 multiple_set_clause:
9773                         '(' set_target_list ')' '=' ctext_row
9774                                 {
9775                                         ListCell *col_cell;
9776                                         ListCell *val_cell;
9777
9778                                         /*
9779                                          * Break the ctext_row apart, merge individual expressions
9780                                          * into the destination ResTargets.  This is semantically
9781                                          * equivalent to, and much cheaper to process than, the
9782                                          * general case.
9783                                          */
9784                                         if (list_length($2) != list_length($5))
9785                                                 ereport(ERROR,
9786                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
9787                                                                  errmsg("number of columns does not match number of values"),
9788                                                                  parser_errposition(@5)));
9789                                         forboth(col_cell, $2, val_cell, $5)
9790                                         {
9791                                                 ResTarget *res_col = (ResTarget *) lfirst(col_cell);
9792                                                 Node *res_val = (Node *) lfirst(val_cell);
9793
9794                                                 res_col->val = res_val;
9795                                         }
9796
9797                                         $$ = $2;
9798                                 }
9799                         | '(' set_target_list ')' '=' select_with_parens
9800                                 {
9801                                         SubLink *sl = makeNode(SubLink);
9802                                         int ncolumns = list_length($2);
9803                                         int i = 1;
9804                                         ListCell *col_cell;
9805
9806                                         /* First, convert bare SelectStmt into a SubLink */
9807                                         sl->subLinkType = MULTIEXPR_SUBLINK;
9808                                         sl->subLinkId = 0;              /* will be assigned later */
9809                                         sl->testexpr = NULL;
9810                                         sl->operName = NIL;
9811                                         sl->subselect = $5;
9812                                         sl->location = @5;
9813
9814                                         /* Create a MultiAssignRef source for each target */
9815                                         foreach(col_cell, $2)
9816                                         {
9817                                                 ResTarget *res_col = (ResTarget *) lfirst(col_cell);
9818                                                 MultiAssignRef *r = makeNode(MultiAssignRef);
9819
9820                                                 r->source = (Node *) sl;
9821                                                 r->colno = i;
9822                                                 r->ncolumns = ncolumns;
9823                                                 res_col->val = (Node *) r;
9824                                                 i++;
9825                                         }
9826
9827                                         $$ = $2;
9828                                 }
9829                 ;
9830
9831 set_target:
9832                         ColId opt_indirection
9833                                 {
9834                                         $$ = makeNode(ResTarget);
9835                                         $$->name = $1;
9836                                         $$->indirection = check_indirection($2, yyscanner);
9837                                         $$->val = NULL; /* upper production sets this */
9838                                         $$->location = @1;
9839                                 }
9840                 ;
9841
9842 set_target_list:
9843                         set_target                                                              { $$ = list_make1($1); }
9844                         | set_target_list ',' set_target                { $$ = lappend($1,$3); }
9845                 ;
9846
9847
9848 /*****************************************************************************
9849  *
9850  *              QUERY:
9851  *                              CURSOR STATEMENTS
9852  *
9853  *****************************************************************************/
9854 DeclareCursorStmt: DECLARE cursor_name cursor_options CURSOR opt_hold FOR SelectStmt
9855                                 {
9856                                         DeclareCursorStmt *n = makeNode(DeclareCursorStmt);
9857                                         n->portalname = $2;
9858                                         /* currently we always set FAST_PLAN option */
9859                                         n->options = $3 | $5 | CURSOR_OPT_FAST_PLAN;
9860                                         n->query = $7;
9861                                         $$ = (Node *)n;
9862                                 }
9863                 ;
9864
9865 cursor_name:    name                                            { $$ = $1; }
9866                 ;
9867
9868 cursor_options: /*EMPTY*/                                       { $$ = 0; }
9869                         | cursor_options NO SCROLL              { $$ = $1 | CURSOR_OPT_NO_SCROLL; }
9870                         | cursor_options SCROLL                 { $$ = $1 | CURSOR_OPT_SCROLL; }
9871                         | cursor_options BINARY                 { $$ = $1 | CURSOR_OPT_BINARY; }
9872                         | cursor_options INSENSITIVE    { $$ = $1 | CURSOR_OPT_INSENSITIVE; }
9873                 ;
9874
9875 opt_hold: /* EMPTY */                                           { $$ = 0; }
9876                         | WITH HOLD                                             { $$ = CURSOR_OPT_HOLD; }
9877                         | WITHOUT HOLD                                  { $$ = 0; }
9878                 ;
9879
9880 /*****************************************************************************
9881  *
9882  *              QUERY:
9883  *                              SELECT STATEMENTS
9884  *
9885  *****************************************************************************/
9886
9887 /* A complete SELECT statement looks like this.
9888  *
9889  * The rule returns either a single SelectStmt node or a tree of them,
9890  * representing a set-operation tree.
9891  *
9892  * There is an ambiguity when a sub-SELECT is within an a_expr and there
9893  * are excess parentheses: do the parentheses belong to the sub-SELECT or
9894  * to the surrounding a_expr?  We don't really care, but bison wants to know.
9895  * To resolve the ambiguity, we are careful to define the grammar so that
9896  * the decision is staved off as long as possible: as long as we can keep
9897  * absorbing parentheses into the sub-SELECT, we will do so, and only when
9898  * it's no longer possible to do that will we decide that parens belong to
9899  * the expression.      For example, in "SELECT (((SELECT 2)) + 3)" the extra
9900  * parentheses are treated as part of the sub-select.  The necessity of doing
9901  * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)".      Had we
9902  * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
9903  * SELECT viewpoint when we see the UNION.
9904  *
9905  * This approach is implemented by defining a nonterminal select_with_parens,
9906  * which represents a SELECT with at least one outer layer of parentheses,
9907  * and being careful to use select_with_parens, never '(' SelectStmt ')',
9908  * in the expression grammar.  We will then have shift-reduce conflicts
9909  * which we can resolve in favor of always treating '(' <select> ')' as
9910  * a select_with_parens.  To resolve the conflicts, the productions that
9911  * conflict with the select_with_parens productions are manually given
9912  * precedences lower than the precedence of ')', thereby ensuring that we
9913  * shift ')' (and then reduce to select_with_parens) rather than trying to
9914  * reduce the inner <select> nonterminal to something else.  We use UMINUS
9915  * precedence for this, which is a fairly arbitrary choice.
9916  *
9917  * To be able to define select_with_parens itself without ambiguity, we need
9918  * a nonterminal select_no_parens that represents a SELECT structure with no
9919  * outermost parentheses.  This is a little bit tedious, but it works.
9920  *
9921  * In non-expression contexts, we use SelectStmt which can represent a SELECT
9922  * with or without outer parentheses.
9923  */
9924
9925 SelectStmt: select_no_parens                    %prec UMINUS
9926                         | select_with_parens            %prec UMINUS
9927                 ;
9928
9929 select_with_parens:
9930                         '(' select_no_parens ')'                                { $$ = $2; }
9931                         | '(' select_with_parens ')'                    { $$ = $2; }
9932                 ;
9933
9934 /*
9935  * This rule parses the equivalent of the standard's <query expression>.
9936  * The duplicative productions are annoying, but hard to get rid of without
9937  * creating shift/reduce conflicts.
9938  *
9939  *      The locking clause (FOR UPDATE etc) may be before or after LIMIT/OFFSET.
9940  *      In <=7.2.X, LIMIT/OFFSET had to be after FOR UPDATE
9941  *      We now support both orderings, but prefer LIMIT/OFFSET before the locking
9942  * clause.
9943  *      2002-08-28 bjm
9944  */
9945 select_no_parens:
9946                         simple_select                                           { $$ = $1; }
9947                         | select_clause sort_clause
9948                                 {
9949                                         insertSelectOptions((SelectStmt *) $1, $2, NIL,
9950                                                                                 NULL, NULL, NULL,
9951                                                                                 yyscanner);
9952                                         $$ = $1;
9953                                 }
9954                         | select_clause opt_sort_clause for_locking_clause opt_select_limit
9955                                 {
9956                                         insertSelectOptions((SelectStmt *) $1, $2, $3,
9957                                                                                 list_nth($4, 0), list_nth($4, 1),
9958                                                                                 NULL,
9959                                                                                 yyscanner);
9960                                         $$ = $1;
9961                                 }
9962                         | select_clause opt_sort_clause select_limit opt_for_locking_clause
9963                                 {
9964                                         insertSelectOptions((SelectStmt *) $1, $2, $4,
9965                                                                                 list_nth($3, 0), list_nth($3, 1),
9966                                                                                 NULL,
9967                                                                                 yyscanner);
9968                                         $$ = $1;
9969                                 }
9970                         | with_clause select_clause
9971                                 {
9972                                         insertSelectOptions((SelectStmt *) $2, NULL, NIL,
9973                                                                                 NULL, NULL,
9974                                                                                 $1,
9975                                                                                 yyscanner);
9976                                         $$ = $2;
9977                                 }
9978                         | with_clause select_clause sort_clause
9979                                 {
9980                                         insertSelectOptions((SelectStmt *) $2, $3, NIL,
9981                                                                                 NULL, NULL,
9982                                                                                 $1,
9983                                                                                 yyscanner);
9984                                         $$ = $2;
9985                                 }
9986                         | with_clause select_clause opt_sort_clause for_locking_clause opt_select_limit
9987                                 {
9988                                         insertSelectOptions((SelectStmt *) $2, $3, $4,
9989                                                                                 list_nth($5, 0), list_nth($5, 1),
9990                                                                                 $1,
9991                                                                                 yyscanner);
9992                                         $$ = $2;
9993                                 }
9994                         | with_clause select_clause opt_sort_clause select_limit opt_for_locking_clause
9995                                 {
9996                                         insertSelectOptions((SelectStmt *) $2, $3, $5,
9997                                                                                 list_nth($4, 0), list_nth($4, 1),
9998                                                                                 $1,
9999                                                                                 yyscanner);
10000                                         $$ = $2;
10001                                 }
10002                 ;
10003
10004 select_clause:
10005                         simple_select                                                   { $$ = $1; }
10006                         | select_with_parens                                    { $$ = $1; }
10007                 ;
10008
10009 /*
10010  * This rule parses SELECT statements that can appear within set operations,
10011  * including UNION, INTERSECT and EXCEPT.  '(' and ')' can be used to specify
10012  * the ordering of the set operations.  Without '(' and ')' we want the
10013  * operations to be ordered per the precedence specs at the head of this file.
10014  *
10015  * As with select_no_parens, simple_select cannot have outer parentheses,
10016  * but can have parenthesized subclauses.
10017  *
10018  * Note that sort clauses cannot be included at this level --- SQL requires
10019  *              SELECT foo UNION SELECT bar ORDER BY baz
10020  * to be parsed as
10021  *              (SELECT foo UNION SELECT bar) ORDER BY baz
10022  * not
10023  *              SELECT foo UNION (SELECT bar ORDER BY baz)
10024  * Likewise for WITH, FOR UPDATE and LIMIT.  Therefore, those clauses are
10025  * described as part of the select_no_parens production, not simple_select.
10026  * This does not limit functionality, because you can reintroduce these
10027  * clauses inside parentheses.
10028  *
10029  * NOTE: only the leftmost component SelectStmt should have INTO.
10030  * However, this is not checked by the grammar; parse analysis must check it.
10031  */
10032 simple_select:
10033                         SELECT opt_all_clause opt_target_list
10034                         into_clause from_clause where_clause
10035                         group_clause having_clause window_clause
10036                                 {
10037                                         SelectStmt *n = makeNode(SelectStmt);
10038                                         n->targetList = $3;
10039                                         n->intoClause = $4;
10040                                         n->fromClause = $5;
10041                                         n->whereClause = $6;
10042                                         n->groupClause = $7;
10043                                         n->havingClause = $8;
10044                                         n->windowClause = $9;
10045                                         $$ = (Node *)n;
10046                                 }
10047                         | SELECT distinct_clause target_list
10048                         into_clause from_clause where_clause
10049                         group_clause having_clause window_clause
10050                                 {
10051                                         SelectStmt *n = makeNode(SelectStmt);
10052                                         n->distinctClause = $2;
10053                                         n->targetList = $3;
10054                                         n->intoClause = $4;
10055                                         n->fromClause = $5;
10056                                         n->whereClause = $6;
10057                                         n->groupClause = $7;
10058                                         n->havingClause = $8;
10059                                         n->windowClause = $9;
10060                                         $$ = (Node *)n;
10061                                 }
10062                         | values_clause                                                 { $$ = $1; }
10063                         | TABLE relation_expr
10064                                 {
10065                                         /* same as SELECT * FROM relation_expr */
10066                                         ColumnRef *cr = makeNode(ColumnRef);
10067                                         ResTarget *rt = makeNode(ResTarget);
10068                                         SelectStmt *n = makeNode(SelectStmt);
10069
10070                                         cr->fields = list_make1(makeNode(A_Star));
10071                                         cr->location = -1;
10072
10073                                         rt->name = NULL;
10074                                         rt->indirection = NIL;
10075                                         rt->val = (Node *)cr;
10076                                         rt->location = -1;
10077
10078                                         n->targetList = list_make1(rt);
10079                                         n->fromClause = list_make1($2);
10080                                         $$ = (Node *)n;
10081                                 }
10082                         | select_clause UNION all_or_distinct select_clause
10083                                 {
10084                                         $$ = makeSetOp(SETOP_UNION, $3, $1, $4);
10085                                 }
10086                         | select_clause INTERSECT all_or_distinct select_clause
10087                                 {
10088                                         $$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
10089                                 }
10090                         | select_clause EXCEPT all_or_distinct select_clause
10091                                 {
10092                                         $$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
10093                                 }
10094                 ;
10095
10096 /*
10097  * SQL standard WITH clause looks like:
10098  *
10099  * WITH [ RECURSIVE ] <query name> [ (<column>,...) ]
10100  *              AS (query) [ SEARCH or CYCLE clause ]
10101  *
10102  * We don't currently support the SEARCH or CYCLE clause.
10103  *
10104  * Recognizing WITH_LA here allows a CTE to be named TIME or ORDINALITY.
10105  */
10106 with_clause:
10107                 WITH cte_list
10108                         {
10109                                 $$ = makeNode(WithClause);
10110                                 $$->ctes = $2;
10111                                 $$->recursive = false;
10112                                 $$->location = @1;
10113                         }
10114                 | WITH_LA cte_list
10115                         {
10116                                 $$ = makeNode(WithClause);
10117                                 $$->ctes = $2;
10118                                 $$->recursive = false;
10119                                 $$->location = @1;
10120                         }
10121                 | WITH RECURSIVE cte_list
10122                         {
10123                                 $$ = makeNode(WithClause);
10124                                 $$->ctes = $3;
10125                                 $$->recursive = true;
10126                                 $$->location = @1;
10127                         }
10128                 ;
10129
10130 cte_list:
10131                 common_table_expr                                               { $$ = list_make1($1); }
10132                 | cte_list ',' common_table_expr                { $$ = lappend($1, $3); }
10133                 ;
10134
10135 common_table_expr:  name opt_name_list AS '(' PreparableStmt ')'
10136                         {
10137                                 CommonTableExpr *n = makeNode(CommonTableExpr);
10138                                 n->ctename = $1;
10139                                 n->aliascolnames = $2;
10140                                 n->ctequery = $5;
10141                                 n->location = @1;
10142                                 $$ = (Node *) n;
10143                         }
10144                 ;
10145
10146 opt_with_clause:
10147                 with_clause                                                             { $$ = $1; }
10148                 | /*EMPTY*/                                                             { $$ = NULL; }
10149                 ;
10150
10151 into_clause:
10152                         INTO OptTempTableName
10153                                 {
10154                                         $$ = makeNode(IntoClause);
10155                                         $$->rel = $2;
10156                                         $$->colNames = NIL;
10157                                         $$->options = NIL;
10158                                         $$->onCommit = ONCOMMIT_NOOP;
10159                                         $$->tableSpaceName = NULL;
10160                                         $$->viewQuery = NULL;
10161                                         $$->skipData = false;
10162                                 }
10163                         | /*EMPTY*/
10164                                 { $$ = NULL; }
10165                 ;
10166
10167 /*
10168  * Redundancy here is needed to avoid shift/reduce conflicts,
10169  * since TEMP is not a reserved word.  See also OptTemp.
10170  */
10171 OptTempTableName:
10172                         TEMPORARY opt_table qualified_name
10173                                 {
10174                                         $$ = $3;
10175                                         $$->relpersistence = RELPERSISTENCE_TEMP;
10176                                 }
10177                         | TEMP opt_table qualified_name
10178                                 {
10179                                         $$ = $3;
10180                                         $$->relpersistence = RELPERSISTENCE_TEMP;
10181                                 }
10182                         | LOCAL TEMPORARY opt_table qualified_name
10183                                 {
10184                                         $$ = $4;
10185                                         $$->relpersistence = RELPERSISTENCE_TEMP;
10186                                 }
10187                         | LOCAL TEMP opt_table qualified_name
10188                                 {
10189                                         $$ = $4;
10190                                         $$->relpersistence = RELPERSISTENCE_TEMP;
10191                                 }
10192                         | GLOBAL TEMPORARY opt_table qualified_name
10193                                 {
10194                                         ereport(WARNING,
10195                                                         (errmsg("GLOBAL is deprecated in temporary table creation"),
10196                                                          parser_errposition(@1)));
10197                                         $$ = $4;
10198                                         $$->relpersistence = RELPERSISTENCE_TEMP;
10199                                 }
10200                         | GLOBAL TEMP opt_table qualified_name
10201                                 {
10202                                         ereport(WARNING,
10203                                                         (errmsg("GLOBAL is deprecated in temporary table creation"),
10204                                                          parser_errposition(@1)));
10205                                         $$ = $4;
10206                                         $$->relpersistence = RELPERSISTENCE_TEMP;
10207                                 }
10208                         | UNLOGGED opt_table qualified_name
10209                                 {
10210                                         $$ = $3;
10211                                         $$->relpersistence = RELPERSISTENCE_UNLOGGED;
10212                                 }
10213                         | TABLE qualified_name
10214                                 {
10215                                         $$ = $2;
10216                                         $$->relpersistence = RELPERSISTENCE_PERMANENT;
10217                                 }
10218                         | qualified_name
10219                                 {
10220                                         $$ = $1;
10221                                         $$->relpersistence = RELPERSISTENCE_PERMANENT;
10222                                 }
10223                 ;
10224
10225 opt_table:      TABLE                                                                   {}
10226                         | /*EMPTY*/                                                             {}
10227                 ;
10228
10229 all_or_distinct:
10230                         ALL                                                                             { $$ = TRUE; }
10231                         | DISTINCT                                                              { $$ = FALSE; }
10232                         | /*EMPTY*/                                                             { $$ = FALSE; }
10233                 ;
10234
10235 /* We use (NIL) as a placeholder to indicate that all target expressions
10236  * should be placed in the DISTINCT list during parsetree analysis.
10237  */
10238 distinct_clause:
10239                         DISTINCT                                                                { $$ = list_make1(NIL); }
10240                         | DISTINCT ON '(' expr_list ')'                 { $$ = $4; }
10241                 ;
10242
10243 opt_all_clause:
10244                         ALL                                                                             { $$ = NIL;}
10245                         | /*EMPTY*/                                                             { $$ = NIL; }
10246                 ;
10247
10248 opt_sort_clause:
10249                         sort_clause                                                             { $$ = $1;}
10250                         | /*EMPTY*/                                                             { $$ = NIL; }
10251                 ;
10252
10253 sort_clause:
10254                         ORDER BY sortby_list                                    { $$ = $3; }
10255                 ;
10256
10257 sortby_list:
10258                         sortby                                                                  { $$ = list_make1($1); }
10259                         | sortby_list ',' sortby                                { $$ = lappend($1, $3); }
10260                 ;
10261
10262 sortby:         a_expr USING qual_all_Op opt_nulls_order
10263                                 {
10264                                         $$ = makeNode(SortBy);
10265                                         $$->node = $1;
10266                                         $$->sortby_dir = SORTBY_USING;
10267                                         $$->sortby_nulls = $4;
10268                                         $$->useOp = $3;
10269                                         $$->location = @3;
10270                                 }
10271                         | a_expr opt_asc_desc opt_nulls_order
10272                                 {
10273                                         $$ = makeNode(SortBy);
10274                                         $$->node = $1;
10275                                         $$->sortby_dir = $2;
10276                                         $$->sortby_nulls = $3;
10277                                         $$->useOp = NIL;
10278                                         $$->location = -1;              /* no operator */
10279                                 }
10280                 ;
10281
10282
10283 select_limit:
10284                         limit_clause offset_clause                      { $$ = list_make2($2, $1); }
10285                         | offset_clause limit_clause            { $$ = list_make2($1, $2); }
10286                         | limit_clause                                          { $$ = list_make2(NULL, $1); }
10287                         | offset_clause                                         { $$ = list_make2($1, NULL); }
10288                 ;
10289
10290 opt_select_limit:
10291                         select_limit                                            { $$ = $1; }
10292                         | /* EMPTY */                                           { $$ = list_make2(NULL,NULL); }
10293                 ;
10294
10295 limit_clause:
10296                         LIMIT select_limit_value
10297                                 { $$ = $2; }
10298                         | LIMIT select_limit_value ',' select_offset_value
10299                                 {
10300                                         /* Disabled because it was too confusing, bjm 2002-02-18 */
10301                                         ereport(ERROR,
10302                                                         (errcode(ERRCODE_SYNTAX_ERROR),
10303                                                          errmsg("LIMIT #,# syntax is not supported"),
10304                                                          errhint("Use separate LIMIT and OFFSET clauses."),
10305                                                          parser_errposition(@1)));
10306                                 }
10307                         /* SQL:2008 syntax */
10308                         | FETCH first_or_next opt_select_fetch_first_value row_or_rows ONLY
10309                                 { $$ = $3; }
10310                 ;
10311
10312 offset_clause:
10313                         OFFSET select_offset_value
10314                                 { $$ = $2; }
10315                         /* SQL:2008 syntax */
10316                         | OFFSET select_offset_value2 row_or_rows
10317                                 { $$ = $2; }
10318                 ;
10319
10320 select_limit_value:
10321                         a_expr                                                                  { $$ = $1; }
10322                         | ALL
10323                                 {
10324                                         /* LIMIT ALL is represented as a NULL constant */
10325                                         $$ = makeNullAConst(@1);
10326                                 }
10327                 ;
10328
10329 select_offset_value:
10330                         a_expr                                                                  { $$ = $1; }
10331                 ;
10332
10333 /*
10334  * Allowing full expressions without parentheses causes various parsing
10335  * problems with the trailing ROW/ROWS key words.  SQL only calls for
10336  * constants, so we allow the rest only with parentheses.  If omitted,
10337  * default to 1.
10338  */
10339 opt_select_fetch_first_value:
10340                         SignedIconst                                            { $$ = makeIntConst($1, @1); }
10341                         | '(' a_expr ')'                                        { $$ = $2; }
10342                         | /*EMPTY*/                                                     { $$ = makeIntConst(1, -1); }
10343                 ;
10344
10345 /*
10346  * Again, the trailing ROW/ROWS in this case prevent the full expression
10347  * syntax.  c_expr is the best we can do.
10348  */
10349 select_offset_value2:
10350                         c_expr                                                                  { $$ = $1; }
10351                 ;
10352
10353 /* noise words */
10354 row_or_rows: ROW                                                                        { $$ = 0; }
10355                         | ROWS                                                                  { $$ = 0; }
10356                 ;
10357
10358 first_or_next: FIRST_P                                                          { $$ = 0; }
10359                         | NEXT                                                                  { $$ = 0; }
10360                 ;
10361
10362
10363 /*
10364  * This syntax for group_clause tries to follow the spec quite closely.
10365  * However, the spec allows only column references, not expressions,
10366  * which introduces an ambiguity between implicit row constructors
10367  * (a,b) and lists of column references.
10368  *
10369  * We handle this by using the a_expr production for what the spec calls
10370  * <ordinary grouping set>, which in the spec represents either one column
10371  * reference or a parenthesized list of column references. Then, we check the
10372  * top node of the a_expr to see if it's an implicit RowExpr, and if so, just
10373  * grab and use the list, discarding the node. (this is done in parse analysis,
10374  * not here)
10375  *
10376  * (we abuse the row_format field of RowExpr to distinguish implicit and
10377  * explicit row constructors; it's debatable if anyone sanely wants to use them
10378  * in a group clause, but if they have a reason to, we make it possible.)
10379  *
10380  * Each item in the group_clause list is either an expression tree or a
10381  * GroupingSet node of some type.
10382  */
10383 group_clause:
10384                         GROUP_P BY group_by_list                                { $$ = $3; }
10385                         | /*EMPTY*/                                                             { $$ = NIL; }
10386                 ;
10387
10388 group_by_list:
10389                         group_by_item                                                   { $$ = list_make1($1); }
10390                         | group_by_list ',' group_by_item               { $$ = lappend($1,$3); }
10391                 ;
10392
10393 group_by_item:
10394                         a_expr                                                                  { $$ = $1; }
10395                         | empty_grouping_set                                    { $$ = $1; }
10396                         | cube_clause                                                   { $$ = $1; }
10397                         | rollup_clause                                                 { $$ = $1; }
10398                         | grouping_sets_clause                                  { $$ = $1; }
10399                 ;
10400
10401 empty_grouping_set:
10402                         '(' ')'
10403                                 {
10404                                         $$ = (Node *) makeGroupingSet(GROUPING_SET_EMPTY, NIL, @1);
10405                                 }
10406                 ;
10407
10408 /*
10409  * These hacks rely on setting precedence of CUBE and ROLLUP below that of '(',
10410  * so that they shift in these rules rather than reducing the conflicting
10411  * unreserved_keyword rule.
10412  */
10413
10414 rollup_clause:
10415                         ROLLUP '(' expr_list ')'
10416                                 {
10417                                         $$ = (Node *) makeGroupingSet(GROUPING_SET_ROLLUP, $3, @1);
10418                                 }
10419                 ;
10420
10421 cube_clause:
10422                         CUBE '(' expr_list ')'
10423                                 {
10424                                         $$ = (Node *) makeGroupingSet(GROUPING_SET_CUBE, $3, @1);
10425                                 }
10426                 ;
10427
10428 grouping_sets_clause:
10429                         GROUPING SETS '(' group_by_list ')'
10430                                 {
10431                                         $$ = (Node *) makeGroupingSet(GROUPING_SET_SETS, $4, @1);
10432                                 }
10433                 ;
10434
10435 having_clause:
10436                         HAVING a_expr                                                   { $$ = $2; }
10437                         | /*EMPTY*/                                                             { $$ = NULL; }
10438                 ;
10439
10440 for_locking_clause:
10441                         for_locking_items                                               { $$ = $1; }
10442                         | FOR READ ONLY                                                 { $$ = NIL; }
10443                 ;
10444
10445 opt_for_locking_clause:
10446                         for_locking_clause                                              { $$ = $1; }
10447                         | /* EMPTY */                                                   { $$ = NIL; }
10448                 ;
10449
10450 for_locking_items:
10451                         for_locking_item                                                { $$ = list_make1($1); }
10452                         | for_locking_items for_locking_item    { $$ = lappend($1, $2); }
10453                 ;
10454
10455 for_locking_item:
10456                         for_locking_strength locked_rels_list opt_nowait_or_skip
10457                                 {
10458                                         LockingClause *n = makeNode(LockingClause);
10459                                         n->lockedRels = $2;
10460                                         n->strength = $1;
10461                                         n->waitPolicy = $3;
10462                                         $$ = (Node *) n;
10463                                 }
10464                 ;
10465
10466 for_locking_strength:
10467                         FOR UPDATE                                                      { $$ = LCS_FORUPDATE; }
10468                         | FOR NO KEY UPDATE                             { $$ = LCS_FORNOKEYUPDATE; }
10469                         | FOR SHARE                                             { $$ = LCS_FORSHARE; }
10470                         | FOR KEY SHARE                                         { $$ = LCS_FORKEYSHARE; }
10471                 ;
10472
10473 locked_rels_list:
10474                         OF qualified_name_list                                  { $$ = $2; }
10475                         | /* EMPTY */                                                   { $$ = NIL; }
10476                 ;
10477
10478
10479 values_clause:
10480                         VALUES ctext_row
10481                                 {
10482                                         SelectStmt *n = makeNode(SelectStmt);
10483                                         n->valuesLists = list_make1($2);
10484                                         $$ = (Node *) n;
10485                                 }
10486                         | values_clause ',' ctext_row
10487                                 {
10488                                         SelectStmt *n = (SelectStmt *) $1;
10489                                         n->valuesLists = lappend(n->valuesLists, $3);
10490                                         $$ = (Node *) n;
10491                                 }
10492                 ;
10493
10494
10495 /*****************************************************************************
10496  *
10497  *      clauses common to all Optimizable Stmts:
10498  *              from_clause             - allow list of both JOIN expressions and table names
10499  *              where_clause    - qualifications for joins or restrictions
10500  *
10501  *****************************************************************************/
10502
10503 from_clause:
10504                         FROM from_list                                                  { $$ = $2; }
10505                         | /*EMPTY*/                                                             { $$ = NIL; }
10506                 ;
10507
10508 from_list:
10509                         table_ref                                                               { $$ = list_make1($1); }
10510                         | from_list ',' table_ref                               { $$ = lappend($1, $3); }
10511                 ;
10512
10513 /*
10514  * table_ref is where an alias clause can be attached.
10515  */
10516 table_ref:      relation_expr opt_alias_clause
10517                                 {
10518                                         $1->alias = $2;
10519                                         $$ = (Node *) $1;
10520                                 }
10521                         | relation_expr opt_alias_clause tablesample_clause
10522                                 {
10523                                         RangeTableSample *n = (RangeTableSample *) $3;
10524                                         $1->alias = $2;
10525                                         /* relation_expr goes inside the RangeTableSample node */
10526                                         n->relation = (Node *) $1;
10527                                         $$ = (Node *) n;
10528                                 }
10529                         | func_table func_alias_clause
10530                                 {
10531                                         RangeFunction *n = (RangeFunction *) $1;
10532                                         n->alias = linitial($2);
10533                                         n->coldeflist = lsecond($2);
10534                                         $$ = (Node *) n;
10535                                 }
10536                         | LATERAL_P func_table func_alias_clause
10537                                 {
10538                                         RangeFunction *n = (RangeFunction *) $2;
10539                                         n->lateral = true;
10540                                         n->alias = linitial($3);
10541                                         n->coldeflist = lsecond($3);
10542                                         $$ = (Node *) n;
10543                                 }
10544                         | select_with_parens opt_alias_clause
10545                                 {
10546                                         RangeSubselect *n = makeNode(RangeSubselect);
10547                                         n->lateral = false;
10548                                         n->subquery = $1;
10549                                         n->alias = $2;
10550                                         /*
10551                                          * The SQL spec does not permit a subselect
10552                                          * (<derived_table>) without an alias clause,
10553                                          * so we don't either.  This avoids the problem
10554                                          * of needing to invent a unique refname for it.
10555                                          * That could be surmounted if there's sufficient
10556                                          * popular demand, but for now let's just implement
10557                                          * the spec and see if anyone complains.
10558                                          * However, it does seem like a good idea to emit
10559                                          * an error message that's better than "syntax error".
10560                                          */
10561                                         if ($2 == NULL)
10562                                         {
10563                                                 if (IsA($1, SelectStmt) &&
10564                                                         ((SelectStmt *) $1)->valuesLists)
10565                                                         ereport(ERROR,
10566                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
10567                                                                          errmsg("VALUES in FROM must have an alias"),
10568                                                                          errhint("For example, FROM (VALUES ...) [AS] foo."),
10569                                                                          parser_errposition(@1)));
10570                                                 else
10571                                                         ereport(ERROR,
10572                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
10573                                                                          errmsg("subquery in FROM must have an alias"),
10574                                                                          errhint("For example, FROM (SELECT ...) [AS] foo."),
10575                                                                          parser_errposition(@1)));
10576                                         }
10577                                         $$ = (Node *) n;
10578                                 }
10579                         | LATERAL_P select_with_parens opt_alias_clause
10580                                 {
10581                                         RangeSubselect *n = makeNode(RangeSubselect);
10582                                         n->lateral = true;
10583                                         n->subquery = $2;
10584                                         n->alias = $3;
10585                                         /* same coment as above */
10586                                         if ($3 == NULL)
10587                                         {
10588                                                 if (IsA($2, SelectStmt) &&
10589                                                         ((SelectStmt *) $2)->valuesLists)
10590                                                         ereport(ERROR,
10591                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
10592                                                                          errmsg("VALUES in FROM must have an alias"),
10593                                                                          errhint("For example, FROM (VALUES ...) [AS] foo."),
10594                                                                          parser_errposition(@2)));
10595                                                 else
10596                                                         ereport(ERROR,
10597                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
10598                                                                          errmsg("subquery in FROM must have an alias"),
10599                                                                          errhint("For example, FROM (SELECT ...) [AS] foo."),
10600                                                                          parser_errposition(@2)));
10601                                         }
10602                                         $$ = (Node *) n;
10603                                 }
10604                         | joined_table
10605                                 {
10606                                         $$ = (Node *) $1;
10607                                 }
10608                         | '(' joined_table ')' alias_clause
10609                                 {
10610                                         $2->alias = $4;
10611                                         $$ = (Node *) $2;
10612                                 }
10613                 ;
10614
10615
10616 /*
10617  * It may seem silly to separate joined_table from table_ref, but there is
10618  * method in SQL's madness: if you don't do it this way you get reduce-
10619  * reduce conflicts, because it's not clear to the parser generator whether
10620  * to expect alias_clause after ')' or not.  For the same reason we must
10621  * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
10622  * join_type to expand to empty; if we try it, the parser generator can't
10623  * figure out when to reduce an empty join_type right after table_ref.
10624  *
10625  * Note that a CROSS JOIN is the same as an unqualified
10626  * INNER JOIN, and an INNER JOIN/ON has the same shape
10627  * but a qualification expression to limit membership.
10628  * A NATURAL JOIN implicitly matches column names between
10629  * tables and the shape is determined by which columns are
10630  * in common. We'll collect columns during the later transformations.
10631  */
10632
10633 joined_table:
10634                         '(' joined_table ')'
10635                                 {
10636                                         $$ = $2;
10637                                 }
10638                         | table_ref CROSS JOIN table_ref
10639                                 {
10640                                         /* CROSS JOIN is same as unqualified inner join */
10641                                         JoinExpr *n = makeNode(JoinExpr);
10642                                         n->jointype = JOIN_INNER;
10643                                         n->isNatural = FALSE;
10644                                         n->larg = $1;
10645                                         n->rarg = $4;
10646                                         n->usingClause = NIL;
10647                                         n->quals = NULL;
10648                                         $$ = n;
10649                                 }
10650                         | table_ref join_type JOIN table_ref join_qual
10651                                 {
10652                                         JoinExpr *n = makeNode(JoinExpr);
10653                                         n->jointype = $2;
10654                                         n->isNatural = FALSE;
10655                                         n->larg = $1;
10656                                         n->rarg = $4;
10657                                         if ($5 != NULL && IsA($5, List))
10658                                                 n->usingClause = (List *) $5; /* USING clause */
10659                                         else
10660                                                 n->quals = $5; /* ON clause */
10661                                         $$ = n;
10662                                 }
10663                         | table_ref JOIN table_ref join_qual
10664                                 {
10665                                         /* letting join_type reduce to empty doesn't work */
10666                                         JoinExpr *n = makeNode(JoinExpr);
10667                                         n->jointype = JOIN_INNER;
10668                                         n->isNatural = FALSE;
10669                                         n->larg = $1;
10670                                         n->rarg = $3;
10671                                         if ($4 != NULL && IsA($4, List))
10672                                                 n->usingClause = (List *) $4; /* USING clause */
10673                                         else
10674                                                 n->quals = $4; /* ON clause */
10675                                         $$ = n;
10676                                 }
10677                         | table_ref NATURAL join_type JOIN table_ref
10678                                 {
10679                                         JoinExpr *n = makeNode(JoinExpr);
10680                                         n->jointype = $3;
10681                                         n->isNatural = TRUE;
10682                                         n->larg = $1;
10683                                         n->rarg = $5;
10684                                         n->usingClause = NIL; /* figure out which columns later... */
10685                                         n->quals = NULL; /* fill later */
10686                                         $$ = n;
10687                                 }
10688                         | table_ref NATURAL JOIN table_ref
10689                                 {
10690                                         /* letting join_type reduce to empty doesn't work */
10691                                         JoinExpr *n = makeNode(JoinExpr);
10692                                         n->jointype = JOIN_INNER;
10693                                         n->isNatural = TRUE;
10694                                         n->larg = $1;
10695                                         n->rarg = $4;
10696                                         n->usingClause = NIL; /* figure out which columns later... */
10697                                         n->quals = NULL; /* fill later */
10698                                         $$ = n;
10699                                 }
10700                 ;
10701
10702 alias_clause:
10703                         AS ColId '(' name_list ')'
10704                                 {
10705                                         $$ = makeNode(Alias);
10706                                         $$->aliasname = $2;
10707                                         $$->colnames = $4;
10708                                 }
10709                         | AS ColId
10710                                 {
10711                                         $$ = makeNode(Alias);
10712                                         $$->aliasname = $2;
10713                                 }
10714                         | ColId '(' name_list ')'
10715                                 {
10716                                         $$ = makeNode(Alias);
10717                                         $$->aliasname = $1;
10718                                         $$->colnames = $3;
10719                                 }
10720                         | ColId
10721                                 {
10722                                         $$ = makeNode(Alias);
10723                                         $$->aliasname = $1;
10724                                 }
10725                 ;
10726
10727 opt_alias_clause: alias_clause                                          { $$ = $1; }
10728                         | /*EMPTY*/                                                             { $$ = NULL; }
10729                 ;
10730
10731 /*
10732  * func_alias_clause can include both an Alias and a coldeflist, so we make it
10733  * return a 2-element list that gets disassembled by calling production.
10734  */
10735 func_alias_clause:
10736                         alias_clause
10737                                 {
10738                                         $$ = list_make2($1, NIL);
10739                                 }
10740                         | AS '(' TableFuncElementList ')'
10741                                 {
10742                                         $$ = list_make2(NULL, $3);
10743                                 }
10744                         | AS ColId '(' TableFuncElementList ')'
10745                                 {
10746                                         Alias *a = makeNode(Alias);
10747                                         a->aliasname = $2;
10748                                         $$ = list_make2(a, $4);
10749                                 }
10750                         | ColId '(' TableFuncElementList ')'
10751                                 {
10752                                         Alias *a = makeNode(Alias);
10753                                         a->aliasname = $1;
10754                                         $$ = list_make2(a, $3);
10755                                 }
10756                         | /*EMPTY*/
10757                                 {
10758                                         $$ = list_make2(NULL, NIL);
10759                                 }
10760                 ;
10761
10762 join_type:      FULL join_outer                                                 { $$ = JOIN_FULL; }
10763                         | LEFT join_outer                                               { $$ = JOIN_LEFT; }
10764                         | RIGHT join_outer                                              { $$ = JOIN_RIGHT; }
10765                         | INNER_P                                                               { $$ = JOIN_INNER; }
10766                 ;
10767
10768 /* OUTER is just noise... */
10769 join_outer: OUTER_P                                                                     { $$ = NULL; }
10770                         | /*EMPTY*/                                                             { $$ = NULL; }
10771                 ;
10772
10773 /* JOIN qualification clauses
10774  * Possibilities are:
10775  *      USING ( column list ) allows only unqualified column names,
10776  *                                                which must match between tables.
10777  *      ON expr allows more general qualifications.
10778  *
10779  * We return USING as a List node, while an ON-expr will not be a List.
10780  */
10781
10782 join_qual:      USING '(' name_list ')'                                 { $$ = (Node *) $3; }
10783                         | ON a_expr                                                             { $$ = $2; }
10784                 ;
10785
10786
10787 relation_expr:
10788                         qualified_name
10789                                 {
10790                                         /* default inheritance */
10791                                         $$ = $1;
10792                                         $$->inhOpt = INH_DEFAULT;
10793                                         $$->alias = NULL;
10794                                 }
10795                         | qualified_name '*'
10796                                 {
10797                                         /* inheritance query */
10798                                         $$ = $1;
10799                                         $$->inhOpt = INH_YES;
10800                                         $$->alias = NULL;
10801                                 }
10802                         | ONLY qualified_name
10803                                 {
10804                                         /* no inheritance */
10805                                         $$ = $2;
10806                                         $$->inhOpt = INH_NO;
10807                                         $$->alias = NULL;
10808                                 }
10809                         | ONLY '(' qualified_name ')'
10810                                 {
10811                                         /* no inheritance, SQL99-style syntax */
10812                                         $$ = $3;
10813                                         $$->inhOpt = INH_NO;
10814                                         $$->alias = NULL;
10815                                 }
10816                 ;
10817
10818
10819 relation_expr_list:
10820                         relation_expr                                                   { $$ = list_make1($1); }
10821                         | relation_expr_list ',' relation_expr  { $$ = lappend($1, $3); }
10822                 ;
10823
10824
10825 /*
10826  * Given "UPDATE foo set set ...", we have to decide without looking any
10827  * further ahead whether the first "set" is an alias or the UPDATE's SET
10828  * keyword.  Since "set" is allowed as a column name both interpretations
10829  * are feasible.  We resolve the shift/reduce conflict by giving the first
10830  * relation_expr_opt_alias production a higher precedence than the SET token
10831  * has, causing the parser to prefer to reduce, in effect assuming that the
10832  * SET is not an alias.
10833  */
10834 relation_expr_opt_alias: relation_expr                                  %prec UMINUS
10835                                 {
10836                                         $$ = $1;
10837                                 }
10838                         | relation_expr ColId
10839                                 {
10840                                         Alias *alias = makeNode(Alias);
10841                                         alias->aliasname = $2;
10842                                         $1->alias = alias;
10843                                         $$ = $1;
10844                                 }
10845                         | relation_expr AS ColId
10846                                 {
10847                                         Alias *alias = makeNode(Alias);
10848                                         alias->aliasname = $3;
10849                                         $1->alias = alias;
10850                                         $$ = $1;
10851                                 }
10852                 ;
10853
10854 /*
10855  * TABLESAMPLE decoration in a FROM item
10856  */
10857 tablesample_clause:
10858                         TABLESAMPLE func_name '(' expr_list ')' opt_repeatable_clause
10859                                 {
10860                                         RangeTableSample *n = makeNode(RangeTableSample);
10861                                         /* n->relation will be filled in later */
10862                                         n->method = $2;
10863                                         n->args = $4;
10864                                         n->repeatable = $6;
10865                                         n->location = @2;
10866                                         $$ = (Node *) n;
10867                                 }
10868                 ;
10869
10870 opt_repeatable_clause:
10871                         REPEATABLE '(' a_expr ')'       { $$ = (Node *) $3; }
10872                         | /*EMPTY*/                                     { $$ = NULL; }
10873                 ;
10874
10875 /*
10876  * func_table represents a function invocation in a FROM list. It can be
10877  * a plain function call, like "foo(...)", or a ROWS FROM expression with
10878  * one or more function calls, "ROWS FROM (foo(...), bar(...))",
10879  * optionally with WITH ORDINALITY attached.
10880  * In the ROWS FROM syntax, a column definition list can be given for each
10881  * function, for example:
10882  *     ROWS FROM (foo() AS (foo_res_a text, foo_res_b text),
10883  *                bar() AS (bar_res_a text, bar_res_b text))
10884  * It's also possible to attach a column definition list to the RangeFunction
10885  * as a whole, but that's handled by the table_ref production.
10886  */
10887 func_table: func_expr_windowless opt_ordinality
10888                                 {
10889                                         RangeFunction *n = makeNode(RangeFunction);
10890                                         n->lateral = false;
10891                                         n->ordinality = $2;
10892                                         n->is_rowsfrom = false;
10893                                         n->functions = list_make1(list_make2($1, NIL));
10894                                         /* alias and coldeflist are set by table_ref production */
10895                                         $$ = (Node *) n;
10896                                 }
10897                         | ROWS FROM '(' rowsfrom_list ')' opt_ordinality
10898                                 {
10899                                         RangeFunction *n = makeNode(RangeFunction);
10900                                         n->lateral = false;
10901                                         n->ordinality = $6;
10902                                         n->is_rowsfrom = true;
10903                                         n->functions = $4;
10904                                         /* alias and coldeflist are set by table_ref production */
10905                                         $$ = (Node *) n;
10906                                 }
10907                 ;
10908
10909 rowsfrom_item: func_expr_windowless opt_col_def_list
10910                                 { $$ = list_make2($1, $2); }
10911                 ;
10912
10913 rowsfrom_list:
10914                         rowsfrom_item                                           { $$ = list_make1($1); }
10915                         | rowsfrom_list ',' rowsfrom_item       { $$ = lappend($1, $3); }
10916                 ;
10917
10918 opt_col_def_list: AS '(' TableFuncElementList ')'       { $$ = $3; }
10919                         | /*EMPTY*/                                                             { $$ = NIL; }
10920                 ;
10921
10922 opt_ordinality: WITH_LA ORDINALITY                                      { $$ = true; }
10923                         | /*EMPTY*/                                                             { $$ = false; }
10924                 ;
10925
10926
10927 where_clause:
10928                         WHERE a_expr                                                    { $$ = $2; }
10929                         | /*EMPTY*/                                                             { $$ = NULL; }
10930                 ;
10931
10932 /* variant for UPDATE and DELETE */
10933 where_or_current_clause:
10934                         WHERE a_expr                                                    { $$ = $2; }
10935                         | WHERE CURRENT_P OF cursor_name
10936                                 {
10937                                         CurrentOfExpr *n = makeNode(CurrentOfExpr);
10938                                         /* cvarno is filled in by parse analysis */
10939                                         n->cursor_name = $4;
10940                                         n->cursor_param = 0;
10941                                         $$ = (Node *) n;
10942                                 }
10943                         | /*EMPTY*/                                                             { $$ = NULL; }
10944                 ;
10945
10946
10947 OptTableFuncElementList:
10948                         TableFuncElementList                            { $$ = $1; }
10949                         | /*EMPTY*/                                                     { $$ = NIL; }
10950                 ;
10951
10952 TableFuncElementList:
10953                         TableFuncElement
10954                                 {
10955                                         $$ = list_make1($1);
10956                                 }
10957                         | TableFuncElementList ',' TableFuncElement
10958                                 {
10959                                         $$ = lappend($1, $3);
10960                                 }
10961                 ;
10962
10963 TableFuncElement:       ColId Typename opt_collate_clause
10964                                 {
10965                                         ColumnDef *n = makeNode(ColumnDef);
10966                                         n->colname = $1;
10967                                         n->typeName = $2;
10968                                         n->inhcount = 0;
10969                                         n->is_local = true;
10970                                         n->is_not_null = false;
10971                                         n->is_from_type = false;
10972                                         n->storage = 0;
10973                                         n->raw_default = NULL;
10974                                         n->cooked_default = NULL;
10975                                         n->collClause = (CollateClause *) $3;
10976                                         n->collOid = InvalidOid;
10977                                         n->constraints = NIL;
10978                                         n->location = @1;
10979                                         $$ = (Node *)n;
10980                                 }
10981                 ;
10982
10983 /*****************************************************************************
10984  *
10985  *      Type syntax
10986  *              SQL introduces a large amount of type-specific syntax.
10987  *              Define individual clauses to handle these cases, and use
10988  *               the generic case to handle regular type-extensible Postgres syntax.
10989  *              - thomas 1997-10-10
10990  *
10991  *****************************************************************************/
10992
10993 Typename:       SimpleTypename opt_array_bounds
10994                                 {
10995                                         $$ = $1;
10996                                         $$->arrayBounds = $2;
10997                                 }
10998                         | SETOF SimpleTypename opt_array_bounds
10999                                 {
11000                                         $$ = $2;
11001                                         $$->arrayBounds = $3;
11002                                         $$->setof = TRUE;
11003                                 }
11004                         /* SQL standard syntax, currently only one-dimensional */
11005                         | SimpleTypename ARRAY '[' Iconst ']'
11006                                 {
11007                                         $$ = $1;
11008                                         $$->arrayBounds = list_make1(makeInteger($4));
11009                                 }
11010                         | SETOF SimpleTypename ARRAY '[' Iconst ']'
11011                                 {
11012                                         $$ = $2;
11013                                         $$->arrayBounds = list_make1(makeInteger($5));
11014                                         $$->setof = TRUE;
11015                                 }
11016                         | SimpleTypename ARRAY
11017                                 {
11018                                         $$ = $1;
11019                                         $$->arrayBounds = list_make1(makeInteger(-1));
11020                                 }
11021                         | SETOF SimpleTypename ARRAY
11022                                 {
11023                                         $$ = $2;
11024                                         $$->arrayBounds = list_make1(makeInteger(-1));
11025                                         $$->setof = TRUE;
11026                                 }
11027                 ;
11028
11029 opt_array_bounds:
11030                         opt_array_bounds '[' ']'
11031                                         {  $$ = lappend($1, makeInteger(-1)); }
11032                         | opt_array_bounds '[' Iconst ']'
11033                                         {  $$ = lappend($1, makeInteger($3)); }
11034                         | /*EMPTY*/
11035                                         {  $$ = NIL; }
11036                 ;
11037
11038 SimpleTypename:
11039                         GenericType                                                             { $$ = $1; }
11040                         | Numeric                                                               { $$ = $1; }
11041                         | Bit                                                                   { $$ = $1; }
11042                         | Character                                                             { $$ = $1; }
11043                         | ConstDatetime                                                 { $$ = $1; }
11044                         | ConstInterval opt_interval
11045                                 {
11046                                         $$ = $1;
11047                                         $$->typmods = $2;
11048                                 }
11049                         | ConstInterval '(' Iconst ')'
11050                                 {
11051                                         $$ = $1;
11052                                         $$->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
11053                                                                                          makeIntConst($3, @3));
11054                                 }
11055                 ;
11056
11057 /* We have a separate ConstTypename to allow defaulting fixed-length
11058  * types such as CHAR() and BIT() to an unspecified length.
11059  * SQL9x requires that these default to a length of one, but this
11060  * makes no sense for constructs like CHAR 'hi' and BIT '0101',
11061  * where there is an obvious better choice to make.
11062  * Note that ConstInterval is not included here since it must
11063  * be pushed up higher in the rules to accommodate the postfix
11064  * options (e.g. INTERVAL '1' YEAR). Likewise, we have to handle
11065  * the generic-type-name case in AExprConst to avoid premature
11066  * reduce/reduce conflicts against function names.
11067  */
11068 ConstTypename:
11069                         Numeric                                                                 { $$ = $1; }
11070                         | ConstBit                                                              { $$ = $1; }
11071                         | ConstCharacter                                                { $$ = $1; }
11072                         | ConstDatetime                                                 { $$ = $1; }
11073                 ;
11074
11075 /*
11076  * GenericType covers all type names that don't have special syntax mandated
11077  * by the standard, including qualified names.  We also allow type modifiers.
11078  * To avoid parsing conflicts against function invocations, the modifiers
11079  * have to be shown as expr_list here, but parse analysis will only accept
11080  * constants for them.
11081  */
11082 GenericType:
11083                         type_function_name opt_type_modifiers
11084                                 {
11085                                         $$ = makeTypeName($1);
11086                                         $$->typmods = $2;
11087                                         $$->location = @1;
11088                                 }
11089                         | type_function_name attrs opt_type_modifiers
11090                                 {
11091                                         $$ = makeTypeNameFromNameList(lcons(makeString($1), $2));
11092                                         $$->typmods = $3;
11093                                         $$->location = @1;
11094                                 }
11095                 ;
11096
11097 opt_type_modifiers: '(' expr_list ')'                           { $$ = $2; }
11098                                         | /* EMPTY */                                   { $$ = NIL; }
11099                 ;
11100
11101 /*
11102  * SQL numeric data types
11103  */
11104 Numeric:        INT_P
11105                                 {
11106                                         $$ = SystemTypeName("int4");
11107                                         $$->location = @1;
11108                                 }
11109                         | INTEGER
11110                                 {
11111                                         $$ = SystemTypeName("int4");
11112                                         $$->location = @1;
11113                                 }
11114                         | SMALLINT
11115                                 {
11116                                         $$ = SystemTypeName("int2");
11117                                         $$->location = @1;
11118                                 }
11119                         | BIGINT
11120                                 {
11121                                         $$ = SystemTypeName("int8");
11122                                         $$->location = @1;
11123                                 }
11124                         | REAL
11125                                 {
11126                                         $$ = SystemTypeName("float4");
11127                                         $$->location = @1;
11128                                 }
11129                         | FLOAT_P opt_float
11130                                 {
11131                                         $$ = $2;
11132                                         $$->location = @1;
11133                                 }
11134                         | DOUBLE_P PRECISION
11135                                 {
11136                                         $$ = SystemTypeName("float8");
11137                                         $$->location = @1;
11138                                 }
11139                         | DECIMAL_P opt_type_modifiers
11140                                 {
11141                                         $$ = SystemTypeName("numeric");
11142                                         $$->typmods = $2;
11143                                         $$->location = @1;
11144                                 }
11145                         | DEC opt_type_modifiers
11146                                 {
11147                                         $$ = SystemTypeName("numeric");
11148                                         $$->typmods = $2;
11149                                         $$->location = @1;
11150                                 }
11151                         | NUMERIC opt_type_modifiers
11152                                 {
11153                                         $$ = SystemTypeName("numeric");
11154                                         $$->typmods = $2;
11155                                         $$->location = @1;
11156                                 }
11157                         | BOOLEAN_P
11158                                 {
11159                                         $$ = SystemTypeName("bool");
11160                                         $$->location = @1;
11161                                 }
11162                 ;
11163
11164 opt_float:      '(' Iconst ')'
11165                                 {
11166                                         /*
11167                                          * Check FLOAT() precision limits assuming IEEE floating
11168                                          * types - thomas 1997-09-18
11169                                          */
11170                                         if ($2 < 1)
11171                                                 ereport(ERROR,
11172                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
11173                                                                  errmsg("precision for type float must be at least 1 bit"),
11174                                                                  parser_errposition(@2)));
11175                                         else if ($2 <= 24)
11176                                                 $$ = SystemTypeName("float4");
11177                                         else if ($2 <= 53)
11178                                                 $$ = SystemTypeName("float8");
11179                                         else
11180                                                 ereport(ERROR,
11181                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
11182                                                                  errmsg("precision for type float must be less than 54 bits"),
11183                                                                  parser_errposition(@2)));
11184                                 }
11185                         | /*EMPTY*/
11186                                 {
11187                                         $$ = SystemTypeName("float8");
11188                                 }
11189                 ;
11190
11191 /*
11192  * SQL bit-field data types
11193  * The following implements BIT() and BIT VARYING().
11194  */
11195 Bit:            BitWithLength
11196                                 {
11197                                         $$ = $1;
11198                                 }
11199                         | BitWithoutLength
11200                                 {
11201                                         $$ = $1;
11202                                 }
11203                 ;
11204
11205 /* ConstBit is like Bit except "BIT" defaults to unspecified length */
11206 /* See notes for ConstCharacter, which addresses same issue for "CHAR" */
11207 ConstBit:       BitWithLength
11208                                 {
11209                                         $$ = $1;
11210                                 }
11211                         | BitWithoutLength
11212                                 {
11213                                         $$ = $1;
11214                                         $$->typmods = NIL;
11215                                 }
11216                 ;
11217
11218 BitWithLength:
11219                         BIT opt_varying '(' expr_list ')'
11220                                 {
11221                                         char *typname;
11222
11223                                         typname = $2 ? "varbit" : "bit";
11224                                         $$ = SystemTypeName(typname);
11225                                         $$->typmods = $4;
11226                                         $$->location = @1;
11227                                 }
11228                 ;
11229
11230 BitWithoutLength:
11231                         BIT opt_varying
11232                                 {
11233                                         /* bit defaults to bit(1), varbit to no limit */
11234                                         if ($2)
11235                                         {
11236                                                 $$ = SystemTypeName("varbit");
11237                                         }
11238                                         else
11239                                         {
11240                                                 $$ = SystemTypeName("bit");
11241                                                 $$->typmods = list_make1(makeIntConst(1, -1));
11242                                         }
11243                                         $$->location = @1;
11244                                 }
11245                 ;
11246
11247
11248 /*
11249  * SQL character data types
11250  * The following implements CHAR() and VARCHAR().
11251  */
11252 Character:  CharacterWithLength
11253                                 {
11254                                         $$ = $1;
11255                                 }
11256                         | CharacterWithoutLength
11257                                 {
11258                                         $$ = $1;
11259                                 }
11260                 ;
11261
11262 ConstCharacter:  CharacterWithLength
11263                                 {
11264                                         $$ = $1;
11265                                 }
11266                         | CharacterWithoutLength
11267                                 {
11268                                         /* Length was not specified so allow to be unrestricted.
11269                                          * This handles problems with fixed-length (bpchar) strings
11270                                          * which in column definitions must default to a length
11271                                          * of one, but should not be constrained if the length
11272                                          * was not specified.
11273                                          */
11274                                         $$ = $1;
11275                                         $$->typmods = NIL;
11276                                 }
11277                 ;
11278
11279 CharacterWithLength:  character '(' Iconst ')' opt_charset
11280                                 {
11281                                         if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
11282                                                 $1 = psprintf("%s_%s", $1, $5);
11283
11284                                         $$ = SystemTypeName($1);
11285                                         $$->typmods = list_make1(makeIntConst($3, @3));
11286                                         $$->location = @1;
11287                                 }
11288                 ;
11289
11290 CharacterWithoutLength:  character opt_charset
11291                                 {
11292                                         if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
11293                                                 $1 = psprintf("%s_%s", $1, $2);
11294
11295                                         $$ = SystemTypeName($1);
11296
11297                                         /* char defaults to char(1), varchar to no limit */
11298                                         if (strcmp($1, "bpchar") == 0)
11299                                                 $$->typmods = list_make1(makeIntConst(1, -1));
11300
11301                                         $$->location = @1;
11302                                 }
11303                 ;
11304
11305 character:      CHARACTER opt_varying
11306                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
11307                         | CHAR_P opt_varying
11308                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
11309                         | VARCHAR
11310                                                                                 { $$ = "varchar"; }
11311                         | NATIONAL CHARACTER opt_varying
11312                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
11313                         | NATIONAL CHAR_P opt_varying
11314                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
11315                         | NCHAR opt_varying
11316                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
11317                 ;
11318
11319 opt_varying:
11320                         VARYING                                                                 { $$ = TRUE; }
11321                         | /*EMPTY*/                                                             { $$ = FALSE; }
11322                 ;
11323
11324 opt_charset:
11325                         CHARACTER SET ColId                                             { $$ = $3; }
11326                         | /*EMPTY*/                                                             { $$ = NULL; }
11327                 ;
11328
11329 /*
11330  * SQL date/time types
11331  */
11332 ConstDatetime:
11333                         TIMESTAMP '(' Iconst ')' opt_timezone
11334                                 {
11335                                         if ($5)
11336                                                 $$ = SystemTypeName("timestamptz");
11337                                         else
11338                                                 $$ = SystemTypeName("timestamp");
11339                                         $$->typmods = list_make1(makeIntConst($3, @3));
11340                                         $$->location = @1;
11341                                 }
11342                         | TIMESTAMP opt_timezone
11343                                 {
11344                                         if ($2)
11345                                                 $$ = SystemTypeName("timestamptz");
11346                                         else
11347                                                 $$ = SystemTypeName("timestamp");
11348                                         $$->location = @1;
11349                                 }
11350                         | TIME '(' Iconst ')' opt_timezone
11351                                 {
11352                                         if ($5)
11353                                                 $$ = SystemTypeName("timetz");
11354                                         else
11355                                                 $$ = SystemTypeName("time");
11356                                         $$->typmods = list_make1(makeIntConst($3, @3));
11357                                         $$->location = @1;
11358                                 }
11359                         | TIME opt_timezone
11360                                 {
11361                                         if ($2)
11362                                                 $$ = SystemTypeName("timetz");
11363                                         else
11364                                                 $$ = SystemTypeName("time");
11365                                         $$->location = @1;
11366                                 }
11367                 ;
11368
11369 ConstInterval:
11370                         INTERVAL
11371                                 {
11372                                         $$ = SystemTypeName("interval");
11373                                         $$->location = @1;
11374                                 }
11375                 ;
11376
11377 opt_timezone:
11378                         WITH_LA TIME ZONE                                               { $$ = TRUE; }
11379                         | WITHOUT TIME ZONE                                             { $$ = FALSE; }
11380                         | /*EMPTY*/                                                             { $$ = FALSE; }
11381                 ;
11382
11383 opt_interval:
11384                         YEAR_P
11385                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR), @1)); }
11386                         | MONTH_P
11387                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MONTH), @1)); }
11388                         | DAY_P
11389                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY), @1)); }
11390                         | HOUR_P
11391                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR), @1)); }
11392                         | MINUTE_P
11393                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MINUTE), @1)); }
11394                         | interval_second
11395                                 { $$ = $1; }
11396                         | YEAR_P TO MONTH_P
11397                                 {
11398                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR) |
11399                                                                                                  INTERVAL_MASK(MONTH), @1));
11400                                 }
11401                         | DAY_P TO HOUR_P
11402                                 {
11403                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
11404                                                                                                  INTERVAL_MASK(HOUR), @1));
11405                                 }
11406                         | DAY_P TO MINUTE_P
11407                                 {
11408                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
11409                                                                                                  INTERVAL_MASK(HOUR) |
11410                                                                                                  INTERVAL_MASK(MINUTE), @1));
11411                                 }
11412                         | DAY_P TO interval_second
11413                                 {
11414                                         $$ = $3;
11415                                         linitial($$) = makeIntConst(INTERVAL_MASK(DAY) |
11416                                                                                                 INTERVAL_MASK(HOUR) |
11417                                                                                                 INTERVAL_MASK(MINUTE) |
11418                                                                                                 INTERVAL_MASK(SECOND), @1);
11419                                 }
11420                         | HOUR_P TO MINUTE_P
11421                                 {
11422                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR) |
11423                                                                                                  INTERVAL_MASK(MINUTE), @1));
11424                                 }
11425                         | HOUR_P TO interval_second
11426                                 {
11427                                         $$ = $3;
11428                                         linitial($$) = makeIntConst(INTERVAL_MASK(HOUR) |
11429                                                                                                 INTERVAL_MASK(MINUTE) |
11430                                                                                                 INTERVAL_MASK(SECOND), @1);
11431                                 }
11432                         | MINUTE_P TO interval_second
11433                                 {
11434                                         $$ = $3;
11435                                         linitial($$) = makeIntConst(INTERVAL_MASK(MINUTE) |
11436                                                                                                 INTERVAL_MASK(SECOND), @1);
11437                                 }
11438                         | /*EMPTY*/
11439                                 { $$ = NIL; }
11440                 ;
11441
11442 interval_second:
11443                         SECOND_P
11444                                 {
11445                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(SECOND), @1));
11446                                 }
11447                         | SECOND_P '(' Iconst ')'
11448                                 {
11449                                         $$ = list_make2(makeIntConst(INTERVAL_MASK(SECOND), @1),
11450                                                                         makeIntConst($3, @3));
11451                                 }
11452                 ;
11453
11454
11455 /*****************************************************************************
11456  *
11457  *      expression grammar
11458  *
11459  *****************************************************************************/
11460
11461 /*
11462  * General expressions
11463  * This is the heart of the expression syntax.
11464  *
11465  * We have two expression types: a_expr is the unrestricted kind, and
11466  * b_expr is a subset that must be used in some places to avoid shift/reduce
11467  * conflicts.  For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
11468  * because that use of AND conflicts with AND as a boolean operator.  So,
11469  * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
11470  *
11471  * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
11472  * always be used by surrounding it with parens.
11473  *
11474  * c_expr is all the productions that are common to a_expr and b_expr;
11475  * it's factored out just to eliminate redundant coding.
11476  *
11477  * Be careful of productions involving more than one terminal token.
11478  * By default, bison will assign such productions the precedence of their
11479  * last terminal, but in nearly all cases you want it to be the precedence
11480  * of the first terminal instead; otherwise you will not get the behavior
11481  * you expect!  So we use %prec annotations freely to set precedences.
11482  */
11483 a_expr:         c_expr                                                                  { $$ = $1; }
11484                         | a_expr TYPECAST Typename
11485                                         { $$ = makeTypeCast($1, $3, @2); }
11486                         | a_expr COLLATE any_name
11487                                 {
11488                                         CollateClause *n = makeNode(CollateClause);
11489                                         n->arg = $1;
11490                                         n->collname = $3;
11491                                         n->location = @2;
11492                                         $$ = (Node *) n;
11493                                 }
11494                         | a_expr AT TIME ZONE a_expr                    %prec AT
11495                                 {
11496                                         $$ = (Node *) makeFuncCall(SystemFuncName("timezone"),
11497                                                                                            list_make2($5, $1),
11498                                                                                            @2);
11499                                 }
11500                 /*
11501                  * These operators must be called out explicitly in order to make use
11502                  * of bison's automatic operator-precedence handling.  All other
11503                  * operator names are handled by the generic productions using "Op",
11504                  * below; and all those operators will have the same precedence.
11505                  *
11506                  * If you add more explicitly-known operators, be sure to add them
11507                  * also to b_expr and to the MathOp list below.
11508                  */
11509                         | '+' a_expr                                    %prec UMINUS
11510                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
11511                         | '-' a_expr                                    %prec UMINUS
11512                                 { $$ = doNegate($2, @1); }
11513                         | a_expr '+' a_expr
11514                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", $1, $3, @2); }
11515                         | a_expr '-' a_expr
11516                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "-", $1, $3, @2); }
11517                         | a_expr '*' a_expr
11518                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", $1, $3, @2); }
11519                         | a_expr '/' a_expr
11520                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "/", $1, $3, @2); }
11521                         | a_expr '%' a_expr
11522                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "%", $1, $3, @2); }
11523                         | a_expr '^' a_expr
11524                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "^", $1, $3, @2); }
11525                         | a_expr '<' a_expr
11526                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $3, @2); }
11527                         | a_expr '>' a_expr
11528                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $3, @2); }
11529                         | a_expr '=' a_expr
11530                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "=", $1, $3, @2); }
11531                         | a_expr LESS_EQUALS a_expr
11532                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $3, @2); }
11533                         | a_expr GREATER_EQUALS a_expr
11534                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $3, @2); }
11535                         | a_expr NOT_EQUALS a_expr
11536                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<>", $1, $3, @2); }
11537
11538                         | a_expr qual_Op a_expr                         %prec Op
11539                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
11540                         | qual_Op a_expr                                        %prec Op
11541                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
11542                         | a_expr qual_Op                                        %prec POSTFIXOP
11543                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
11544
11545                         | a_expr AND a_expr
11546                                 { $$ = makeAndExpr($1, $3, @2); }
11547                         | a_expr OR a_expr
11548                                 { $$ = makeOrExpr($1, $3, @2); }
11549                         | NOT a_expr
11550                                 { $$ = makeNotExpr($2, @1); }
11551                         | NOT_LA a_expr                                         %prec NOT
11552                                 { $$ = makeNotExpr($2, @1); }
11553
11554                         | a_expr LIKE a_expr
11555                                 {
11556                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_LIKE, "~~",
11557                                                                                                    $1, $3, @2);
11558                                 }
11559                         | a_expr LIKE a_expr ESCAPE a_expr                                      %prec LIKE
11560                                 {
11561                                         FuncCall *n = makeFuncCall(SystemFuncName("like_escape"),
11562                                                                                            list_make2($3, $5),
11563                                                                                            @2);
11564                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_LIKE, "~~",
11565                                                                                                    $1, (Node *) n, @2);
11566                                 }
11567                         | a_expr NOT_LA LIKE a_expr                                                     %prec NOT_LA
11568                                 {
11569                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_LIKE, "!~~",
11570                                                                                                    $1, $4, @2);
11571                                 }
11572                         | a_expr NOT_LA LIKE a_expr ESCAPE a_expr                       %prec NOT_LA
11573                                 {
11574                                         FuncCall *n = makeFuncCall(SystemFuncName("like_escape"),
11575                                                                                            list_make2($4, $6),
11576                                                                                            @2);
11577                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_LIKE, "!~~",
11578                                                                                                    $1, (Node *) n, @2);
11579                                 }
11580                         | a_expr ILIKE a_expr
11581                                 {
11582                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_ILIKE, "~~*",
11583                                                                                                    $1, $3, @2);
11584                                 }
11585                         | a_expr ILIKE a_expr ESCAPE a_expr                                     %prec ILIKE
11586                                 {
11587                                         FuncCall *n = makeFuncCall(SystemFuncName("like_escape"),
11588                                                                                            list_make2($3, $5),
11589                                                                                            @2);
11590                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_ILIKE, "~~*",
11591                                                                                                    $1, (Node *) n, @2);
11592                                 }
11593                         | a_expr NOT_LA ILIKE a_expr                                            %prec NOT_LA
11594                                 {
11595                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_ILIKE, "!~~*",
11596                                                                                                    $1, $4, @2);
11597                                 }
11598                         | a_expr NOT_LA ILIKE a_expr ESCAPE a_expr                      %prec NOT_LA
11599                                 {
11600                                         FuncCall *n = makeFuncCall(SystemFuncName("like_escape"),
11601                                                                                            list_make2($4, $6),
11602                                                                                            @2);
11603                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_ILIKE, "!~~*",
11604                                                                                                    $1, (Node *) n, @2);
11605                                 }
11606
11607                         | a_expr SIMILAR TO a_expr                                                      %prec SIMILAR
11608                                 {
11609                                         FuncCall *n = makeFuncCall(SystemFuncName("similar_escape"),
11610                                                                                            list_make2($4, makeNullAConst(-1)),
11611                                                                                            @2);
11612                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_SIMILAR, "~",
11613                                                                                                    $1, (Node *) n, @2);
11614                                 }
11615                         | a_expr SIMILAR TO a_expr ESCAPE a_expr                        %prec SIMILAR
11616                                 {
11617                                         FuncCall *n = makeFuncCall(SystemFuncName("similar_escape"),
11618                                                                                            list_make2($4, $6),
11619                                                                                            @2);
11620                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_SIMILAR, "~",
11621                                                                                                    $1, (Node *) n, @2);
11622                                 }
11623                         | a_expr NOT_LA SIMILAR TO a_expr                                       %prec NOT_LA
11624                                 {
11625                                         FuncCall *n = makeFuncCall(SystemFuncName("similar_escape"),
11626                                                                                            list_make2($5, makeNullAConst(-1)),
11627                                                                                            @2);
11628                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_SIMILAR, "!~",
11629                                                                                                    $1, (Node *) n, @2);
11630                                 }
11631                         | a_expr NOT_LA SIMILAR TO a_expr ESCAPE a_expr         %prec NOT_LA
11632                                 {
11633                                         FuncCall *n = makeFuncCall(SystemFuncName("similar_escape"),
11634                                                                                            list_make2($5, $7),
11635                                                                                            @2);
11636                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_SIMILAR, "!~",
11637                                                                                                    $1, (Node *) n, @2);
11638                                 }
11639
11640                         /* NullTest clause
11641                          * Define SQL-style Null test clause.
11642                          * Allow two forms described in the standard:
11643                          *      a IS NULL
11644                          *      a IS NOT NULL
11645                          * Allow two SQL extensions
11646                          *      a ISNULL
11647                          *      a NOTNULL
11648                          */
11649                         | a_expr IS NULL_P                                                      %prec IS
11650                                 {
11651                                         NullTest *n = makeNode(NullTest);
11652                                         n->arg = (Expr *) $1;
11653                                         n->nulltesttype = IS_NULL;
11654                                         n->location = @2;
11655                                         $$ = (Node *)n;
11656                                 }
11657                         | a_expr ISNULL
11658                                 {
11659                                         NullTest *n = makeNode(NullTest);
11660                                         n->arg = (Expr *) $1;
11661                                         n->nulltesttype = IS_NULL;
11662                                         n->location = @2;
11663                                         $$ = (Node *)n;
11664                                 }
11665                         | a_expr IS NOT NULL_P                                          %prec IS
11666                                 {
11667                                         NullTest *n = makeNode(NullTest);
11668                                         n->arg = (Expr *) $1;
11669                                         n->nulltesttype = IS_NOT_NULL;
11670                                         n->location = @2;
11671                                         $$ = (Node *)n;
11672                                 }
11673                         | a_expr NOTNULL
11674                                 {
11675                                         NullTest *n = makeNode(NullTest);
11676                                         n->arg = (Expr *) $1;
11677                                         n->nulltesttype = IS_NOT_NULL;
11678                                         n->location = @2;
11679                                         $$ = (Node *)n;
11680                                 }
11681                         | row OVERLAPS row
11682                                 {
11683                                         if (list_length($1) != 2)
11684                                                 ereport(ERROR,
11685                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
11686                                                                  errmsg("wrong number of parameters on left side of OVERLAPS expression"),
11687                                                                  parser_errposition(@1)));
11688                                         if (list_length($3) != 2)
11689                                                 ereport(ERROR,
11690                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
11691                                                                  errmsg("wrong number of parameters on right side of OVERLAPS expression"),
11692                                                                  parser_errposition(@3)));
11693                                         $$ = (Node *) makeFuncCall(SystemFuncName("overlaps"),
11694                                                                                            list_concat($1, $3),
11695                                                                                            @2);
11696                                 }
11697                         | a_expr IS TRUE_P                                                      %prec IS
11698                                 {
11699                                         BooleanTest *b = makeNode(BooleanTest);
11700                                         b->arg = (Expr *) $1;
11701                                         b->booltesttype = IS_TRUE;
11702                                         b->location = @2;
11703                                         $$ = (Node *)b;
11704                                 }
11705                         | a_expr IS NOT TRUE_P                                          %prec IS
11706                                 {
11707                                         BooleanTest *b = makeNode(BooleanTest);
11708                                         b->arg = (Expr *) $1;
11709                                         b->booltesttype = IS_NOT_TRUE;
11710                                         b->location = @2;
11711                                         $$ = (Node *)b;
11712                                 }
11713                         | a_expr IS FALSE_P                                                     %prec IS
11714                                 {
11715                                         BooleanTest *b = makeNode(BooleanTest);
11716                                         b->arg = (Expr *) $1;
11717                                         b->booltesttype = IS_FALSE;
11718                                         b->location = @2;
11719                                         $$ = (Node *)b;
11720                                 }
11721                         | a_expr IS NOT FALSE_P                                         %prec IS
11722                                 {
11723                                         BooleanTest *b = makeNode(BooleanTest);
11724                                         b->arg = (Expr *) $1;
11725                                         b->booltesttype = IS_NOT_FALSE;
11726                                         b->location = @2;
11727                                         $$ = (Node *)b;
11728                                 }
11729                         | a_expr IS UNKNOWN                                                     %prec IS
11730                                 {
11731                                         BooleanTest *b = makeNode(BooleanTest);
11732                                         b->arg = (Expr *) $1;
11733                                         b->booltesttype = IS_UNKNOWN;
11734                                         b->location = @2;
11735                                         $$ = (Node *)b;
11736                                 }
11737                         | a_expr IS NOT UNKNOWN                                         %prec IS
11738                                 {
11739                                         BooleanTest *b = makeNode(BooleanTest);
11740                                         b->arg = (Expr *) $1;
11741                                         b->booltesttype = IS_NOT_UNKNOWN;
11742                                         b->location = @2;
11743                                         $$ = (Node *)b;
11744                                 }
11745                         | a_expr IS DISTINCT FROM a_expr                        %prec IS
11746                                 {
11747                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
11748                                 }
11749                         | a_expr IS NOT DISTINCT FROM a_expr            %prec IS
11750                                 {
11751                                         $$ = makeNotExpr((Node *) makeSimpleA_Expr(AEXPR_DISTINCT,
11752                                                                                                                            "=", $1, $6, @2),
11753                                                                          @2);
11754                                 }
11755                         | a_expr IS OF '(' type_list ')'                        %prec IS
11756                                 {
11757                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
11758                                 }
11759                         | a_expr IS NOT OF '(' type_list ')'            %prec IS
11760                                 {
11761                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
11762                                 }
11763                         | a_expr BETWEEN opt_asymmetric b_expr AND a_expr               %prec BETWEEN
11764                                 {
11765                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_BETWEEN,
11766                                                                                                    "BETWEEN",
11767                                                                                                    $1,
11768                                                                                                    (Node *) list_make2($4, $6),
11769                                                                                                    @2);
11770                                 }
11771                         | a_expr NOT_LA BETWEEN opt_asymmetric b_expr AND a_expr %prec NOT_LA
11772                                 {
11773                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_NOT_BETWEEN,
11774                                                                                                    "NOT BETWEEN",
11775                                                                                                    $1,
11776                                                                                                    (Node *) list_make2($5, $7),
11777                                                                                                    @2);
11778                                 }
11779                         | a_expr BETWEEN SYMMETRIC b_expr AND a_expr                    %prec BETWEEN
11780                                 {
11781                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_BETWEEN_SYM,
11782                                                                                                    "BETWEEN SYMMETRIC",
11783                                                                                                    $1,
11784                                                                                                    (Node *) list_make2($4, $6),
11785                                                                                                    @2);
11786                                 }
11787                         | a_expr NOT_LA BETWEEN SYMMETRIC b_expr AND a_expr             %prec NOT_LA
11788                                 {
11789                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_NOT_BETWEEN_SYM,
11790                                                                                                    "NOT BETWEEN SYMMETRIC",
11791                                                                                                    $1,
11792                                                                                                    (Node *) list_make2($5, $7),
11793                                                                                                    @2);
11794                                 }
11795                         | a_expr IN_P in_expr
11796                                 {
11797                                         /* in_expr returns a SubLink or a list of a_exprs */
11798                                         if (IsA($3, SubLink))
11799                                         {
11800                                                 /* generate foo = ANY (subquery) */
11801                                                 SubLink *n = (SubLink *) $3;
11802                                                 n->subLinkType = ANY_SUBLINK;
11803                                                 n->subLinkId = 0;
11804                                                 n->testexpr = $1;
11805                                                 n->operName = NIL;              /* show it's IN not = ANY */
11806                                                 n->location = @2;
11807                                                 $$ = (Node *)n;
11808                                         }
11809                                         else
11810                                         {
11811                                                 /* generate scalar IN expression */
11812                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "=", $1, $3, @2);
11813                                         }
11814                                 }
11815                         | a_expr NOT_LA IN_P in_expr                                            %prec NOT_LA
11816                                 {
11817                                         /* in_expr returns a SubLink or a list of a_exprs */
11818                                         if (IsA($4, SubLink))
11819                                         {
11820                                                 /* generate NOT (foo = ANY (subquery)) */
11821                                                 /* Make an = ANY node */
11822                                                 SubLink *n = (SubLink *) $4;
11823                                                 n->subLinkType = ANY_SUBLINK;
11824                                                 n->subLinkId = 0;
11825                                                 n->testexpr = $1;
11826                                                 n->operName = NIL;              /* show it's IN not = ANY */
11827                                                 n->location = @2;
11828                                                 /* Stick a NOT on top; must have same parse location */
11829                                                 $$ = makeNotExpr((Node *) n, @2);
11830                                         }
11831                                         else
11832                                         {
11833                                                 /* generate scalar NOT IN expression */
11834                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "<>", $1, $4, @2);
11835                                         }
11836                                 }
11837                         | a_expr subquery_Op sub_type select_with_parens        %prec Op
11838                                 {
11839                                         SubLink *n = makeNode(SubLink);
11840                                         n->subLinkType = $3;
11841                                         n->subLinkId = 0;
11842                                         n->testexpr = $1;
11843                                         n->operName = $2;
11844                                         n->subselect = $4;
11845                                         n->location = @2;
11846                                         $$ = (Node *)n;
11847                                 }
11848                         | a_expr subquery_Op sub_type '(' a_expr ')'            %prec Op
11849                                 {
11850                                         if ($3 == ANY_SUBLINK)
11851                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ANY, $2, $1, $5, @2);
11852                                         else
11853                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ALL, $2, $1, $5, @2);
11854                                 }
11855                         | UNIQUE select_with_parens
11856                                 {
11857                                         /* Not sure how to get rid of the parentheses
11858                                          * but there are lots of shift/reduce errors without them.
11859                                          *
11860                                          * Should be able to implement this by plopping the entire
11861                                          * select into a node, then transforming the target expressions
11862                                          * from whatever they are into count(*), and testing the
11863                                          * entire result equal to one.
11864                                          * But, will probably implement a separate node in the executor.
11865                                          */
11866                                         ereport(ERROR,
11867                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
11868                                                          errmsg("UNIQUE predicate is not yet implemented"),
11869                                                          parser_errposition(@1)));
11870                                 }
11871                         | a_expr IS DOCUMENT_P                                  %prec IS
11872                                 {
11873                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
11874                                                                          list_make1($1), @2);
11875                                 }
11876                         | a_expr IS NOT DOCUMENT_P                              %prec IS
11877                                 {
11878                                         $$ = makeNotExpr(makeXmlExpr(IS_DOCUMENT, NULL, NIL,
11879                                                                                                  list_make1($1), @2),
11880                                                                          @2);
11881                                 }
11882                 ;
11883
11884 /*
11885  * Restricted expressions
11886  *
11887  * b_expr is a subset of the complete expression syntax defined by a_expr.
11888  *
11889  * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
11890  * cause trouble in the places where b_expr is used.  For simplicity, we
11891  * just eliminate all the boolean-keyword-operator productions from b_expr.
11892  */
11893 b_expr:         c_expr
11894                                 { $$ = $1; }
11895                         | b_expr TYPECAST Typename
11896                                 { $$ = makeTypeCast($1, $3, @2); }
11897                         | '+' b_expr                                    %prec UMINUS
11898                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
11899                         | '-' b_expr                                    %prec UMINUS
11900                                 { $$ = doNegate($2, @1); }
11901                         | b_expr '+' b_expr
11902                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", $1, $3, @2); }
11903                         | b_expr '-' b_expr
11904                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "-", $1, $3, @2); }
11905                         | b_expr '*' b_expr
11906                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", $1, $3, @2); }
11907                         | b_expr '/' b_expr
11908                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "/", $1, $3, @2); }
11909                         | b_expr '%' b_expr
11910                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "%", $1, $3, @2); }
11911                         | b_expr '^' b_expr
11912                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "^", $1, $3, @2); }
11913                         | b_expr '<' b_expr
11914                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $3, @2); }
11915                         | b_expr '>' b_expr
11916                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $3, @2); }
11917                         | b_expr '=' b_expr
11918                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "=", $1, $3, @2); }
11919                         | b_expr LESS_EQUALS b_expr
11920                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $3, @2); }
11921                         | b_expr GREATER_EQUALS b_expr
11922                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $3, @2); }
11923                         | b_expr NOT_EQUALS b_expr
11924                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<>", $1, $3, @2); }
11925                         | b_expr qual_Op b_expr                         %prec Op
11926                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
11927                         | qual_Op b_expr                                        %prec Op
11928                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
11929                         | b_expr qual_Op                                        %prec POSTFIXOP
11930                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
11931                         | b_expr IS DISTINCT FROM b_expr                %prec IS
11932                                 {
11933                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
11934                                 }
11935                         | b_expr IS NOT DISTINCT FROM b_expr    %prec IS
11936                                 {
11937                                         $$ = makeNotExpr((Node *) makeSimpleA_Expr(AEXPR_DISTINCT,
11938                                                                                                                            "=", $1, $6, @2),
11939                                                                          @2);
11940                                 }
11941                         | b_expr IS OF '(' type_list ')'                %prec IS
11942                                 {
11943                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
11944                                 }
11945                         | b_expr IS NOT OF '(' type_list ')'    %prec IS
11946                                 {
11947                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
11948                                 }
11949                         | b_expr IS DOCUMENT_P                                  %prec IS
11950                                 {
11951                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
11952                                                                          list_make1($1), @2);
11953                                 }
11954                         | b_expr IS NOT DOCUMENT_P                              %prec IS
11955                                 {
11956                                         $$ = makeNotExpr(makeXmlExpr(IS_DOCUMENT, NULL, NIL,
11957                                                                                                  list_make1($1), @2),
11958                                                                          @2);
11959                                 }
11960                 ;
11961
11962 /*
11963  * Productions that can be used in both a_expr and b_expr.
11964  *
11965  * Note: productions that refer recursively to a_expr or b_expr mostly
11966  * cannot appear here.  However, it's OK to refer to a_exprs that occur
11967  * inside parentheses, such as function arguments; that cannot introduce
11968  * ambiguity to the b_expr syntax.
11969  */
11970 c_expr:         columnref                                                               { $$ = $1; }
11971                         | AexprConst                                                    { $$ = $1; }
11972                         | PARAM opt_indirection
11973                                 {
11974                                         ParamRef *p = makeNode(ParamRef);
11975                                         p->number = $1;
11976                                         p->location = @1;
11977                                         if ($2)
11978                                         {
11979                                                 A_Indirection *n = makeNode(A_Indirection);
11980                                                 n->arg = (Node *) p;
11981                                                 n->indirection = check_indirection($2, yyscanner);
11982                                                 $$ = (Node *) n;
11983                                         }
11984                                         else
11985                                                 $$ = (Node *) p;
11986                                 }
11987                         | '(' a_expr ')' opt_indirection
11988                                 {
11989                                         if ($4)
11990                                         {
11991                                                 A_Indirection *n = makeNode(A_Indirection);
11992                                                 n->arg = $2;
11993                                                 n->indirection = check_indirection($4, yyscanner);
11994                                                 $$ = (Node *)n;
11995                                         }
11996                                         else if (operator_precedence_warning)
11997                                         {
11998                                                 /*
11999                                                  * If precedence warnings are enabled, insert
12000                                                  * AEXPR_PAREN nodes wrapping all explicitly
12001                                                  * parenthesized subexpressions; this prevents bogus
12002                                                  * warnings from being issued when the ordering has
12003                                                  * been forced by parentheses.
12004                                                  *
12005                                                  * In principle we should not be relying on a GUC to
12006                                                  * decide whether to insert AEXPR_PAREN nodes.
12007                                                  * However, since they have no effect except to
12008                                                  * suppress warnings, it's probably safe enough; and
12009                                                  * we'd just as soon not waste cycles on dummy parse
12010                                                  * nodes if we don't have to.
12011                                                  */
12012                                                 $$ = (Node *) makeA_Expr(AEXPR_PAREN, NIL, $2, NULL, @1);
12013                                         }
12014                                         else
12015                                                 $$ = $2;
12016                                 }
12017                         | case_expr
12018                                 { $$ = $1; }
12019                         | func_expr
12020                                 { $$ = $1; }
12021                         | select_with_parens                    %prec UMINUS
12022                                 {
12023                                         SubLink *n = makeNode(SubLink);
12024                                         n->subLinkType = EXPR_SUBLINK;
12025                                         n->subLinkId = 0;
12026                                         n->testexpr = NULL;
12027                                         n->operName = NIL;
12028                                         n->subselect = $1;
12029                                         n->location = @1;
12030                                         $$ = (Node *)n;
12031                                 }
12032                         | select_with_parens indirection
12033                                 {
12034                                         /*
12035                                          * Because the select_with_parens nonterminal is designed
12036                                          * to "eat" as many levels of parens as possible, the
12037                                          * '(' a_expr ')' opt_indirection production above will
12038                                          * fail to match a sub-SELECT with indirection decoration;
12039                                          * the sub-SELECT won't be regarded as an a_expr as long
12040                                          * as there are parens around it.  To support applying
12041                                          * subscripting or field selection to a sub-SELECT result,
12042                                          * we need this redundant-looking production.
12043                                          */
12044                                         SubLink *n = makeNode(SubLink);
12045                                         A_Indirection *a = makeNode(A_Indirection);
12046                                         n->subLinkType = EXPR_SUBLINK;
12047                                         n->subLinkId = 0;
12048                                         n->testexpr = NULL;
12049                                         n->operName = NIL;
12050                                         n->subselect = $1;
12051                                         n->location = @1;
12052                                         a->arg = (Node *)n;
12053                                         a->indirection = check_indirection($2, yyscanner);
12054                                         $$ = (Node *)a;
12055                                 }
12056                         | EXISTS select_with_parens
12057                                 {
12058                                         SubLink *n = makeNode(SubLink);
12059                                         n->subLinkType = EXISTS_SUBLINK;
12060                                         n->subLinkId = 0;
12061                                         n->testexpr = NULL;
12062                                         n->operName = NIL;
12063                                         n->subselect = $2;
12064                                         n->location = @1;
12065                                         $$ = (Node *)n;
12066                                 }
12067                         | ARRAY select_with_parens
12068                                 {
12069                                         SubLink *n = makeNode(SubLink);
12070                                         n->subLinkType = ARRAY_SUBLINK;
12071                                         n->subLinkId = 0;
12072                                         n->testexpr = NULL;
12073                                         n->operName = NIL;
12074                                         n->subselect = $2;
12075                                         n->location = @1;
12076                                         $$ = (Node *)n;
12077                                 }
12078                         | ARRAY array_expr
12079                                 {
12080                                         A_ArrayExpr *n = (A_ArrayExpr *) $2;
12081                                         Assert(IsA(n, A_ArrayExpr));
12082                                         /* point outermost A_ArrayExpr to the ARRAY keyword */
12083                                         n->location = @1;
12084                                         $$ = (Node *)n;
12085                                 }
12086                         | explicit_row
12087                                 {
12088                                         RowExpr *r = makeNode(RowExpr);
12089                                         r->args = $1;
12090                                         r->row_typeid = InvalidOid;     /* not analyzed yet */
12091                                         r->colnames = NIL;      /* to be filled in during analysis */
12092                                         r->row_format = COERCE_EXPLICIT_CALL; /* abuse */
12093                                         r->location = @1;
12094                                         $$ = (Node *)r;
12095                                 }
12096                         | implicit_row
12097                                 {
12098                                         RowExpr *r = makeNode(RowExpr);
12099                                         r->args = $1;
12100                                         r->row_typeid = InvalidOid;     /* not analyzed yet */
12101                                         r->colnames = NIL;      /* to be filled in during analysis */
12102                                         r->row_format = COERCE_IMPLICIT_CAST; /* abuse */
12103                                         r->location = @1;
12104                                         $$ = (Node *)r;
12105                                 }
12106                         | GROUPING '(' expr_list ')'
12107                           {
12108                                   GroupingFunc *g = makeNode(GroupingFunc);
12109                                   g->args = $3;
12110                                   g->location = @1;
12111                                   $$ = (Node *)g;
12112                           }
12113                 ;
12114
12115 func_application: func_name '(' ')'
12116                                 {
12117                                         $$ = (Node *) makeFuncCall($1, NIL, @1);
12118                                 }
12119                         | func_name '(' func_arg_list opt_sort_clause ')'
12120                                 {
12121                                         FuncCall *n = makeFuncCall($1, $3, @1);
12122                                         n->agg_order = $4;
12123                                         $$ = (Node *)n;
12124                                 }
12125                         | func_name '(' VARIADIC func_arg_expr opt_sort_clause ')'
12126                                 {
12127                                         FuncCall *n = makeFuncCall($1, list_make1($4), @1);
12128                                         n->func_variadic = TRUE;
12129                                         n->agg_order = $5;
12130                                         $$ = (Node *)n;
12131                                 }
12132                         | func_name '(' func_arg_list ',' VARIADIC func_arg_expr opt_sort_clause ')'
12133                                 {
12134                                         FuncCall *n = makeFuncCall($1, lappend($3, $6), @1);
12135                                         n->func_variadic = TRUE;
12136                                         n->agg_order = $7;
12137                                         $$ = (Node *)n;
12138                                 }
12139                         | func_name '(' ALL func_arg_list opt_sort_clause ')'
12140                                 {
12141                                         FuncCall *n = makeFuncCall($1, $4, @1);
12142                                         n->agg_order = $5;
12143                                         /* Ideally we'd mark the FuncCall node to indicate
12144                                          * "must be an aggregate", but there's no provision
12145                                          * for that in FuncCall at the moment.
12146                                          */
12147                                         $$ = (Node *)n;
12148                                 }
12149                         | func_name '(' DISTINCT func_arg_list opt_sort_clause ')'
12150                                 {
12151                                         FuncCall *n = makeFuncCall($1, $4, @1);
12152                                         n->agg_order = $5;
12153                                         n->agg_distinct = TRUE;
12154                                         $$ = (Node *)n;
12155                                 }
12156                         | func_name '(' '*' ')'
12157                                 {
12158                                         /*
12159                                          * We consider AGGREGATE(*) to invoke a parameterless
12160                                          * aggregate.  This does the right thing for COUNT(*),
12161                                          * and there are no other aggregates in SQL that accept
12162                                          * '*' as parameter.
12163                                          *
12164                                          * The FuncCall node is also marked agg_star = true,
12165                                          * so that later processing can detect what the argument
12166                                          * really was.
12167                                          */
12168                                         FuncCall *n = makeFuncCall($1, NIL, @1);
12169                                         n->agg_star = TRUE;
12170                                         $$ = (Node *)n;
12171                                 }
12172                 ;
12173
12174
12175 /*
12176  * func_expr and its cousin func_expr_windowless are split out from c_expr just
12177  * so that we have classifications for "everything that is a function call or
12178  * looks like one".  This isn't very important, but it saves us having to
12179  * document which variants are legal in places like "FROM function()" or the
12180  * backwards-compatible functional-index syntax for CREATE INDEX.
12181  * (Note that many of the special SQL functions wouldn't actually make any
12182  * sense as functional index entries, but we ignore that consideration here.)
12183  */
12184 func_expr: func_application within_group_clause filter_clause over_clause
12185                                 {
12186                                         FuncCall *n = (FuncCall *) $1;
12187                                         /*
12188                                          * The order clause for WITHIN GROUP and the one for
12189                                          * plain-aggregate ORDER BY share a field, so we have to
12190                                          * check here that at most one is present.  We also check
12191                                          * for DISTINCT and VARIADIC here to give a better error
12192                                          * location.  Other consistency checks are deferred to
12193                                          * parse analysis.
12194                                          */
12195                                         if ($2 != NIL)
12196                                         {
12197                                                 if (n->agg_order != NIL)
12198                                                         ereport(ERROR,
12199                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
12200                                                                          errmsg("cannot use multiple ORDER BY clauses with WITHIN GROUP"),
12201                                                                          parser_errposition(@2)));
12202                                                 if (n->agg_distinct)
12203                                                         ereport(ERROR,
12204                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
12205                                                                          errmsg("cannot use DISTINCT with WITHIN GROUP"),
12206                                                                          parser_errposition(@2)));
12207                                                 if (n->func_variadic)
12208                                                         ereport(ERROR,
12209                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
12210                                                                          errmsg("cannot use VARIADIC with WITHIN GROUP"),
12211                                                                          parser_errposition(@2)));
12212                                                 n->agg_order = $2;
12213                                                 n->agg_within_group = TRUE;
12214                                         }
12215                                         n->agg_filter = $3;
12216                                         n->over = $4;
12217                                         $$ = (Node *) n;
12218                                 }
12219                         | func_expr_common_subexpr
12220                                 { $$ = $1; }
12221                 ;
12222
12223 /*
12224  * As func_expr but does not accept WINDOW functions directly
12225  * (but they can still be contained in arguments for functions etc).
12226  * Use this when window expressions are not allowed, where needed to
12227  * disambiguate the grammar (e.g. in CREATE INDEX).
12228  */
12229 func_expr_windowless:
12230                         func_application                                                { $$ = $1; }
12231                         | func_expr_common_subexpr                              { $$ = $1; }
12232                 ;
12233
12234 /*
12235  * Special expressions that are considered to be functions.
12236  */
12237 func_expr_common_subexpr:
12238                         COLLATION FOR '(' a_expr ')'
12239                                 {
12240                                         $$ = (Node *) makeFuncCall(SystemFuncName("pg_collation_for"),
12241                                                                                            list_make1($4),
12242                                                                                            @1);
12243                                 }
12244                         | CURRENT_DATE
12245                                 {
12246                                         /*
12247                                          * Translate as "'now'::text::date".
12248                                          *
12249                                          * We cannot use "'now'::date" because coerce_type() will
12250                                          * immediately reduce that to a constant representing
12251                                          * today's date.  We need to delay the conversion until
12252                                          * runtime, else the wrong things will happen when
12253                                          * CURRENT_DATE is used in a column default value or rule.
12254                                          *
12255                                          * This could be simplified if we had a way to generate
12256                                          * an expression tree representing runtime application
12257                                          * of type-input conversion functions.  (As of PG 7.3
12258                                          * that is actually possible, but not clear that we want
12259                                          * to rely on it.)
12260                                          *
12261                                          * The token location is attached to the run-time
12262                                          * typecast, not to the Const, for the convenience of
12263                                          * pg_stat_statements (which doesn't want these constructs
12264                                          * to appear to be replaceable constants).
12265                                          */
12266                                         Node *n;
12267                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12268                                         $$ = makeTypeCast(n, SystemTypeName("date"), @1);
12269                                 }
12270                         | CURRENT_TIME
12271                                 {
12272                                         /*
12273                                          * Translate as "'now'::text::timetz".
12274                                          * See comments for CURRENT_DATE.
12275                                          */
12276                                         Node *n;
12277                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12278                                         $$ = makeTypeCast(n, SystemTypeName("timetz"), @1);
12279                                 }
12280                         | CURRENT_TIME '(' Iconst ')'
12281                                 {
12282                                         /*
12283                                          * Translate as "'now'::text::timetz(n)".
12284                                          * See comments for CURRENT_DATE.
12285                                          */
12286                                         Node *n;
12287                                         TypeName *d;
12288                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12289                                         d = SystemTypeName("timetz");
12290                                         d->typmods = list_make1(makeIntConst($3, @3));
12291                                         $$ = makeTypeCast(n, d, @1);
12292                                 }
12293                         | CURRENT_TIMESTAMP
12294                                 {
12295                                         /*
12296                                          * Translate as "now()", since we have a function that
12297                                          * does exactly what is needed.
12298                                          */
12299                                         $$ = (Node *) makeFuncCall(SystemFuncName("now"), NIL, @1);
12300                                 }
12301                         | CURRENT_TIMESTAMP '(' Iconst ')'
12302                                 {
12303                                         /*
12304                                          * Translate as "'now'::text::timestamptz(n)".
12305                                          * See comments for CURRENT_DATE.
12306                                          */
12307                                         Node *n;
12308                                         TypeName *d;
12309                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12310                                         d = SystemTypeName("timestamptz");
12311                                         d->typmods = list_make1(makeIntConst($3, @3));
12312                                         $$ = makeTypeCast(n, d, @1);
12313                                 }
12314                         | LOCALTIME
12315                                 {
12316                                         /*
12317                                          * Translate as "'now'::text::time".
12318                                          * See comments for CURRENT_DATE.
12319                                          */
12320                                         Node *n;
12321                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12322                                         $$ = makeTypeCast((Node *)n, SystemTypeName("time"), @1);
12323                                 }
12324                         | LOCALTIME '(' Iconst ')'
12325                                 {
12326                                         /*
12327                                          * Translate as "'now'::text::time(n)".
12328                                          * See comments for CURRENT_DATE.
12329                                          */
12330                                         Node *n;
12331                                         TypeName *d;
12332                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12333                                         d = SystemTypeName("time");
12334                                         d->typmods = list_make1(makeIntConst($3, @3));
12335                                         $$ = makeTypeCast((Node *)n, d, @1);
12336                                 }
12337                         | LOCALTIMESTAMP
12338                                 {
12339                                         /*
12340                                          * Translate as "'now'::text::timestamp".
12341                                          * See comments for CURRENT_DATE.
12342                                          */
12343                                         Node *n;
12344                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12345                                         $$ = makeTypeCast(n, SystemTypeName("timestamp"), @1);
12346                                 }
12347                         | LOCALTIMESTAMP '(' Iconst ')'
12348                                 {
12349                                         /*
12350                                          * Translate as "'now'::text::timestamp(n)".
12351                                          * See comments for CURRENT_DATE.
12352                                          */
12353                                         Node *n;
12354                                         TypeName *d;
12355                                         n = makeStringConstCast("now", -1, SystemTypeName("text"));
12356                                         d = SystemTypeName("timestamp");
12357                                         d->typmods = list_make1(makeIntConst($3, @3));
12358                                         $$ = makeTypeCast(n, d, @1);
12359                                 }
12360                         | CURRENT_ROLE
12361                                 {
12362                                         $$ = (Node *) makeFuncCall(SystemFuncName("current_user"), NIL, @1);
12363                                 }
12364                         | CURRENT_USER
12365                                 {
12366                                         $$ = (Node *) makeFuncCall(SystemFuncName("current_user"), NIL, @1);
12367                                 }
12368                         | SESSION_USER
12369                                 {
12370                                         $$ = (Node *) makeFuncCall(SystemFuncName("session_user"), NIL, @1);
12371                                 }
12372                         | USER
12373                                 {
12374                                         $$ = (Node *) makeFuncCall(SystemFuncName("current_user"), NIL, @1);
12375                                 }
12376                         | CURRENT_CATALOG
12377                                 {
12378                                         $$ = (Node *) makeFuncCall(SystemFuncName("current_database"), NIL, @1);
12379                                 }
12380                         | CURRENT_SCHEMA
12381                                 {
12382                                         $$ = (Node *) makeFuncCall(SystemFuncName("current_schema"), NIL, @1);
12383                                 }
12384                         | CAST '(' a_expr AS Typename ')'
12385                                 { $$ = makeTypeCast($3, $5, @1); }
12386                         | EXTRACT '(' extract_list ')'
12387                                 {
12388                                         $$ = (Node *) makeFuncCall(SystemFuncName("date_part"), $3, @1);
12389                                 }
12390                         | OVERLAY '(' overlay_list ')'
12391                                 {
12392                                         /* overlay(A PLACING B FROM C FOR D) is converted to
12393                                          * overlay(A, B, C, D)
12394                                          * overlay(A PLACING B FROM C) is converted to
12395                                          * overlay(A, B, C)
12396                                          */
12397                                         $$ = (Node *) makeFuncCall(SystemFuncName("overlay"), $3, @1);
12398                                 }
12399                         | POSITION '(' position_list ')'
12400                                 {
12401                                         /* position(A in B) is converted to position(B, A) */
12402                                         $$ = (Node *) makeFuncCall(SystemFuncName("position"), $3, @1);
12403                                 }
12404                         | SUBSTRING '(' substr_list ')'
12405                                 {
12406                                         /* substring(A from B for C) is converted to
12407                                          * substring(A, B, C) - thomas 2000-11-28
12408                                          */
12409                                         $$ = (Node *) makeFuncCall(SystemFuncName("substring"), $3, @1);
12410                                 }
12411                         | TREAT '(' a_expr AS Typename ')'
12412                                 {
12413                                         /* TREAT(expr AS target) converts expr of a particular type to target,
12414                                          * which is defined to be a subtype of the original expression.
12415                                          * In SQL99, this is intended for use with structured UDTs,
12416                                          * but let's make this a generally useful form allowing stronger
12417                                          * coercions than are handled by implicit casting.
12418                                          *
12419                                          * Convert SystemTypeName() to SystemFuncName() even though
12420                                          * at the moment they result in the same thing.
12421                                          */
12422                                         $$ = (Node *) makeFuncCall(SystemFuncName(((Value *)llast($5->names))->val.str),
12423                                                                                                 list_make1($3),
12424                                                                                                 @1);
12425                                 }
12426                         | TRIM '(' BOTH trim_list ')'
12427                                 {
12428                                         /* various trim expressions are defined in SQL
12429                                          * - thomas 1997-07-19
12430                                          */
12431                                         $$ = (Node *) makeFuncCall(SystemFuncName("btrim"), $4, @1);
12432                                 }
12433                         | TRIM '(' LEADING trim_list ')'
12434                                 {
12435                                         $$ = (Node *) makeFuncCall(SystemFuncName("ltrim"), $4, @1);
12436                                 }
12437                         | TRIM '(' TRAILING trim_list ')'
12438                                 {
12439                                         $$ = (Node *) makeFuncCall(SystemFuncName("rtrim"), $4, @1);
12440                                 }
12441                         | TRIM '(' trim_list ')'
12442                                 {
12443                                         $$ = (Node *) makeFuncCall(SystemFuncName("btrim"), $3, @1);
12444                                 }
12445                         | NULLIF '(' a_expr ',' a_expr ')'
12446                                 {
12447                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_NULLIF, "=", $3, $5, @1);
12448                                 }
12449                         | COALESCE '(' expr_list ')'
12450                                 {
12451                                         CoalesceExpr *c = makeNode(CoalesceExpr);
12452                                         c->args = $3;
12453                                         c->location = @1;
12454                                         $$ = (Node *)c;
12455                                 }
12456                         | GREATEST '(' expr_list ')'
12457                                 {
12458                                         MinMaxExpr *v = makeNode(MinMaxExpr);
12459                                         v->args = $3;
12460                                         v->op = IS_GREATEST;
12461                                         v->location = @1;
12462                                         $$ = (Node *)v;
12463                                 }
12464                         | LEAST '(' expr_list ')'
12465                                 {
12466                                         MinMaxExpr *v = makeNode(MinMaxExpr);
12467                                         v->args = $3;
12468                                         v->op = IS_LEAST;
12469                                         v->location = @1;
12470                                         $$ = (Node *)v;
12471                                 }
12472                         | XMLCONCAT '(' expr_list ')'
12473                                 {
12474                                         $$ = makeXmlExpr(IS_XMLCONCAT, NULL, NIL, $3, @1);
12475                                 }
12476                         | XMLELEMENT '(' NAME_P ColLabel ')'
12477                                 {
12478                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, NIL, @1);
12479                                 }
12480                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ')'
12481                                 {
12482                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, NIL, @1);
12483                                 }
12484                         | XMLELEMENT '(' NAME_P ColLabel ',' expr_list ')'
12485                                 {
12486                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, $6, @1);
12487                                 }
12488                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ',' expr_list ')'
12489                                 {
12490                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, $8, @1);
12491                                 }
12492                         | XMLEXISTS '(' c_expr xmlexists_argument ')'
12493                                 {
12494                                         /* xmlexists(A PASSING [BY REF] B [BY REF]) is
12495                                          * converted to xmlexists(A, B)*/
12496                                         $$ = (Node *) makeFuncCall(SystemFuncName("xmlexists"), list_make2($3, $4), @1);
12497                                 }
12498                         | XMLFOREST '(' xml_attribute_list ')'
12499                                 {
12500                                         $$ = makeXmlExpr(IS_XMLFOREST, NULL, $3, NIL, @1);
12501                                 }
12502                         | XMLPARSE '(' document_or_content a_expr xml_whitespace_option ')'
12503                                 {
12504                                         XmlExpr *x = (XmlExpr *)
12505                                                 makeXmlExpr(IS_XMLPARSE, NULL, NIL,
12506                                                                         list_make2($4, makeBoolAConst($5, -1)),
12507                                                                         @1);
12508                                         x->xmloption = $3;
12509                                         $$ = (Node *)x;
12510                                 }
12511                         | XMLPI '(' NAME_P ColLabel ')'
12512                                 {
12513                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, NIL, @1);
12514                                 }
12515                         | XMLPI '(' NAME_P ColLabel ',' a_expr ')'
12516                                 {
12517                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, list_make1($6), @1);
12518                                 }
12519                         | XMLROOT '(' a_expr ',' xml_root_version opt_xml_root_standalone ')'
12520                                 {
12521                                         $$ = makeXmlExpr(IS_XMLROOT, NULL, NIL,
12522                                                                          list_make3($3, $5, $6), @1);
12523                                 }
12524                         | XMLSERIALIZE '(' document_or_content a_expr AS SimpleTypename ')'
12525                                 {
12526                                         XmlSerialize *n = makeNode(XmlSerialize);
12527                                         n->xmloption = $3;
12528                                         n->expr = $4;
12529                                         n->typeName = $6;
12530                                         n->location = @1;
12531                                         $$ = (Node *)n;
12532                                 }
12533                 ;
12534
12535 /*
12536  * SQL/XML support
12537  */
12538 xml_root_version: VERSION_P a_expr
12539                                 { $$ = $2; }
12540                         | VERSION_P NO VALUE_P
12541                                 { $$ = makeNullAConst(-1); }
12542                 ;
12543
12544 opt_xml_root_standalone: ',' STANDALONE_P YES_P
12545                                 { $$ = makeIntConst(XML_STANDALONE_YES, -1); }
12546                         | ',' STANDALONE_P NO
12547                                 { $$ = makeIntConst(XML_STANDALONE_NO, -1); }
12548                         | ',' STANDALONE_P NO VALUE_P
12549                                 { $$ = makeIntConst(XML_STANDALONE_NO_VALUE, -1); }
12550                         | /*EMPTY*/
12551                                 { $$ = makeIntConst(XML_STANDALONE_OMITTED, -1); }
12552                 ;
12553
12554 xml_attributes: XMLATTRIBUTES '(' xml_attribute_list ')'        { $$ = $3; }
12555                 ;
12556
12557 xml_attribute_list:     xml_attribute_el                                        { $$ = list_make1($1); }
12558                         | xml_attribute_list ',' xml_attribute_el       { $$ = lappend($1, $3); }
12559                 ;
12560
12561 xml_attribute_el: a_expr AS ColLabel
12562                                 {
12563                                         $$ = makeNode(ResTarget);
12564                                         $$->name = $3;
12565                                         $$->indirection = NIL;
12566                                         $$->val = (Node *) $1;
12567                                         $$->location = @1;
12568                                 }
12569                         | a_expr
12570                                 {
12571                                         $$ = makeNode(ResTarget);
12572                                         $$->name = NULL;
12573                                         $$->indirection = NIL;
12574                                         $$->val = (Node *) $1;
12575                                         $$->location = @1;
12576                                 }
12577                 ;
12578
12579 document_or_content: DOCUMENT_P                                         { $$ = XMLOPTION_DOCUMENT; }
12580                         | CONTENT_P                                                             { $$ = XMLOPTION_CONTENT; }
12581                 ;
12582
12583 xml_whitespace_option: PRESERVE WHITESPACE_P            { $$ = TRUE; }
12584                         | STRIP_P WHITESPACE_P                                  { $$ = FALSE; }
12585                         | /*EMPTY*/                                                             { $$ = FALSE; }
12586                 ;
12587
12588 /* We allow several variants for SQL and other compatibility. */
12589 xmlexists_argument:
12590                         PASSING c_expr
12591                                 {
12592                                         $$ = $2;
12593                                 }
12594                         | PASSING c_expr BY REF
12595                                 {
12596                                         $$ = $2;
12597                                 }
12598                         | PASSING BY REF c_expr
12599                                 {
12600                                         $$ = $4;
12601                                 }
12602                         | PASSING BY REF c_expr BY REF
12603                                 {
12604                                         $$ = $4;
12605                                 }
12606                 ;
12607
12608
12609 /*
12610  * Aggregate decoration clauses
12611  */
12612 within_group_clause:
12613                         WITHIN GROUP_P '(' sort_clause ')'              { $$ = $4; }
12614                         | /*EMPTY*/                                                             { $$ = NIL; }
12615                 ;
12616
12617 filter_clause:
12618                         FILTER '(' WHERE a_expr ')'                             { $$ = $4; }
12619                         | /*EMPTY*/                                                             { $$ = NULL; }
12620                 ;
12621
12622
12623 /*
12624  * Window Definitions
12625  */
12626 window_clause:
12627                         WINDOW window_definition_list                   { $$ = $2; }
12628                         | /*EMPTY*/                                                             { $$ = NIL; }
12629                 ;
12630
12631 window_definition_list:
12632                         window_definition                                               { $$ = list_make1($1); }
12633                         | window_definition_list ',' window_definition
12634                                                                                                         { $$ = lappend($1, $3); }
12635                 ;
12636
12637 window_definition:
12638                         ColId AS window_specification
12639                                 {
12640                                         WindowDef *n = $3;
12641                                         n->name = $1;
12642                                         $$ = n;
12643                                 }
12644                 ;
12645
12646 over_clause: OVER window_specification
12647                                 { $$ = $2; }
12648                         | OVER ColId
12649                                 {
12650                                         WindowDef *n = makeNode(WindowDef);
12651                                         n->name = $2;
12652                                         n->refname = NULL;
12653                                         n->partitionClause = NIL;
12654                                         n->orderClause = NIL;
12655                                         n->frameOptions = FRAMEOPTION_DEFAULTS;
12656                                         n->startOffset = NULL;
12657                                         n->endOffset = NULL;
12658                                         n->location = @2;
12659                                         $$ = n;
12660                                 }
12661                         | /*EMPTY*/
12662                                 { $$ = NULL; }
12663                 ;
12664
12665 window_specification: '(' opt_existing_window_name opt_partition_clause
12666                                                 opt_sort_clause opt_frame_clause ')'
12667                                 {
12668                                         WindowDef *n = makeNode(WindowDef);
12669                                         n->name = NULL;
12670                                         n->refname = $2;
12671                                         n->partitionClause = $3;
12672                                         n->orderClause = $4;
12673                                         /* copy relevant fields of opt_frame_clause */
12674                                         n->frameOptions = $5->frameOptions;
12675                                         n->startOffset = $5->startOffset;
12676                                         n->endOffset = $5->endOffset;
12677                                         n->location = @1;
12678                                         $$ = n;
12679                                 }
12680                 ;
12681
12682 /*
12683  * If we see PARTITION, RANGE, or ROWS as the first token after the '('
12684  * of a window_specification, we want the assumption to be that there is
12685  * no existing_window_name; but those keywords are unreserved and so could
12686  * be ColIds.  We fix this by making them have the same precedence as IDENT
12687  * and giving the empty production here a slightly higher precedence, so
12688  * that the shift/reduce conflict is resolved in favor of reducing the rule.
12689  * These keywords are thus precluded from being an existing_window_name but
12690  * are not reserved for any other purpose.
12691  */
12692 opt_existing_window_name: ColId                                         { $$ = $1; }
12693                         | /*EMPTY*/                             %prec Op                { $$ = NULL; }
12694                 ;
12695
12696 opt_partition_clause: PARTITION BY expr_list            { $$ = $3; }
12697                         | /*EMPTY*/                                                             { $$ = NIL; }
12698                 ;
12699
12700 /*
12701  * For frame clauses, we return a WindowDef, but only some fields are used:
12702  * frameOptions, startOffset, and endOffset.
12703  *
12704  * This is only a subset of the full SQL:2008 frame_clause grammar.
12705  * We don't support <window frame exclusion> yet.
12706  */
12707 opt_frame_clause:
12708                         RANGE frame_extent
12709                                 {
12710                                         WindowDef *n = $2;
12711                                         n->frameOptions |= FRAMEOPTION_NONDEFAULT | FRAMEOPTION_RANGE;
12712                                         if (n->frameOptions & (FRAMEOPTION_START_VALUE_PRECEDING |
12713                                                                                    FRAMEOPTION_END_VALUE_PRECEDING))
12714                                                 ereport(ERROR,
12715                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12716                                                                  errmsg("RANGE PRECEDING is only supported with UNBOUNDED"),
12717                                                                  parser_errposition(@1)));
12718                                         if (n->frameOptions & (FRAMEOPTION_START_VALUE_FOLLOWING |
12719                                                                                    FRAMEOPTION_END_VALUE_FOLLOWING))
12720                                                 ereport(ERROR,
12721                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
12722                                                                  errmsg("RANGE FOLLOWING is only supported with UNBOUNDED"),
12723                                                                  parser_errposition(@1)));
12724                                         $$ = n;
12725                                 }
12726                         | ROWS frame_extent
12727                                 {
12728                                         WindowDef *n = $2;
12729                                         n->frameOptions |= FRAMEOPTION_NONDEFAULT | FRAMEOPTION_ROWS;
12730                                         $$ = n;
12731                                 }
12732                         | /*EMPTY*/
12733                                 {
12734                                         WindowDef *n = makeNode(WindowDef);
12735                                         n->frameOptions = FRAMEOPTION_DEFAULTS;
12736                                         n->startOffset = NULL;
12737                                         n->endOffset = NULL;
12738                                         $$ = n;
12739                                 }
12740                 ;
12741
12742 frame_extent: frame_bound
12743                                 {
12744                                         WindowDef *n = $1;
12745                                         /* reject invalid cases */
12746                                         if (n->frameOptions & FRAMEOPTION_START_UNBOUNDED_FOLLOWING)
12747                                                 ereport(ERROR,
12748                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
12749                                                                  errmsg("frame start cannot be UNBOUNDED FOLLOWING"),
12750                                                                  parser_errposition(@1)));
12751                                         if (n->frameOptions & FRAMEOPTION_START_VALUE_FOLLOWING)
12752                                                 ereport(ERROR,
12753                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
12754                                                                  errmsg("frame starting from following row cannot end with current row"),
12755                                                                  parser_errposition(@1)));
12756                                         n->frameOptions |= FRAMEOPTION_END_CURRENT_ROW;
12757                                         $$ = n;
12758                                 }
12759                         | BETWEEN frame_bound AND frame_bound
12760                                 {
12761                                         WindowDef *n1 = $2;
12762                                         WindowDef *n2 = $4;
12763                                         /* form merged options */
12764                                         int             frameOptions = n1->frameOptions;
12765                                         /* shift converts START_ options to END_ options */
12766                                         frameOptions |= n2->frameOptions << 1;
12767                                         frameOptions |= FRAMEOPTION_BETWEEN;
12768                                         /* reject invalid cases */
12769                                         if (frameOptions & FRAMEOPTION_START_UNBOUNDED_FOLLOWING)
12770                                                 ereport(ERROR,
12771                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
12772                                                                  errmsg("frame start cannot be UNBOUNDED FOLLOWING"),
12773                                                                  parser_errposition(@2)));
12774                                         if (frameOptions & FRAMEOPTION_END_UNBOUNDED_PRECEDING)
12775                                                 ereport(ERROR,
12776                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
12777                                                                  errmsg("frame end cannot be UNBOUNDED PRECEDING"),
12778                                                                  parser_errposition(@4)));
12779                                         if ((frameOptions & FRAMEOPTION_START_CURRENT_ROW) &&
12780                                                 (frameOptions & FRAMEOPTION_END_VALUE_PRECEDING))
12781                                                 ereport(ERROR,
12782                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
12783                                                                  errmsg("frame starting from current row cannot have preceding rows"),
12784                                                                  parser_errposition(@4)));
12785                                         if ((frameOptions & FRAMEOPTION_START_VALUE_FOLLOWING) &&
12786                                                 (frameOptions & (FRAMEOPTION_END_VALUE_PRECEDING |
12787                                                                                  FRAMEOPTION_END_CURRENT_ROW)))
12788                                                 ereport(ERROR,
12789                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
12790                                                                  errmsg("frame starting from following row cannot have preceding rows"),
12791                                                                  parser_errposition(@4)));
12792                                         n1->frameOptions = frameOptions;
12793                                         n1->endOffset = n2->startOffset;
12794                                         $$ = n1;
12795                                 }
12796                 ;
12797
12798 /*
12799  * This is used for both frame start and frame end, with output set up on
12800  * the assumption it's frame start; the frame_extent productions must reject
12801  * invalid cases.
12802  */
12803 frame_bound:
12804                         UNBOUNDED PRECEDING
12805                                 {
12806                                         WindowDef *n = makeNode(WindowDef);
12807                                         n->frameOptions = FRAMEOPTION_START_UNBOUNDED_PRECEDING;
12808                                         n->startOffset = NULL;
12809                                         n->endOffset = NULL;
12810                                         $$ = n;
12811                                 }
12812                         | UNBOUNDED FOLLOWING
12813                                 {
12814                                         WindowDef *n = makeNode(WindowDef);
12815                                         n->frameOptions = FRAMEOPTION_START_UNBOUNDED_FOLLOWING;
12816                                         n->startOffset = NULL;
12817                                         n->endOffset = NULL;
12818                                         $$ = n;
12819                                 }
12820                         | CURRENT_P ROW
12821                                 {
12822                                         WindowDef *n = makeNode(WindowDef);
12823                                         n->frameOptions = FRAMEOPTION_START_CURRENT_ROW;
12824                                         n->startOffset = NULL;
12825                                         n->endOffset = NULL;
12826                                         $$ = n;
12827                                 }
12828                         | a_expr PRECEDING
12829                                 {
12830                                         WindowDef *n = makeNode(WindowDef);
12831                                         n->frameOptions = FRAMEOPTION_START_VALUE_PRECEDING;
12832                                         n->startOffset = $1;
12833                                         n->endOffset = NULL;
12834                                         $$ = n;
12835                                 }
12836                         | a_expr FOLLOWING
12837                                 {
12838                                         WindowDef *n = makeNode(WindowDef);
12839                                         n->frameOptions = FRAMEOPTION_START_VALUE_FOLLOWING;
12840                                         n->startOffset = $1;
12841                                         n->endOffset = NULL;
12842                                         $$ = n;
12843                                 }
12844                 ;
12845
12846
12847 /*
12848  * Supporting nonterminals for expressions.
12849  */
12850
12851 /* Explicit row production.
12852  *
12853  * SQL99 allows an optional ROW keyword, so we can now do single-element rows
12854  * without conflicting with the parenthesized a_expr production.  Without the
12855  * ROW keyword, there must be more than one a_expr inside the parens.
12856  */
12857 row:            ROW '(' expr_list ')'                                   { $$ = $3; }
12858                         | ROW '(' ')'                                                   { $$ = NIL; }
12859                         | '(' expr_list ',' a_expr ')'                  { $$ = lappend($2, $4); }
12860                 ;
12861
12862 explicit_row:   ROW '(' expr_list ')'                           { $$ = $3; }
12863                         | ROW '(' ')'                                                   { $$ = NIL; }
12864                 ;
12865
12866 implicit_row:   '(' expr_list ',' a_expr ')'            { $$ = lappend($2, $4); }
12867                 ;
12868
12869 sub_type:       ANY                                                                             { $$ = ANY_SUBLINK; }
12870                         | SOME                                                                  { $$ = ANY_SUBLINK; }
12871                         | ALL                                                                   { $$ = ALL_SUBLINK; }
12872                 ;
12873
12874 all_Op:         Op                                                                              { $$ = $1; }
12875                         | MathOp                                                                { $$ = $1; }
12876                 ;
12877
12878 MathOp:          '+'                                                                    { $$ = "+"; }
12879                         | '-'                                                                   { $$ = "-"; }
12880                         | '*'                                                                   { $$ = "*"; }
12881                         | '/'                                                                   { $$ = "/"; }
12882                         | '%'                                                                   { $$ = "%"; }
12883                         | '^'                                                                   { $$ = "^"; }
12884                         | '<'                                                                   { $$ = "<"; }
12885                         | '>'                                                                   { $$ = ">"; }
12886                         | '='                                                                   { $$ = "="; }
12887                         | LESS_EQUALS                                                   { $$ = "<="; }
12888                         | GREATER_EQUALS                                                { $$ = ">="; }
12889                         | NOT_EQUALS                                                    { $$ = "<>"; }
12890                 ;
12891
12892 qual_Op:        Op
12893                                         { $$ = list_make1(makeString($1)); }
12894                         | OPERATOR '(' any_operator ')'
12895                                         { $$ = $3; }
12896                 ;
12897
12898 qual_all_Op:
12899                         all_Op
12900                                         { $$ = list_make1(makeString($1)); }
12901                         | OPERATOR '(' any_operator ')'
12902                                         { $$ = $3; }
12903                 ;
12904
12905 subquery_Op:
12906                         all_Op
12907                                         { $$ = list_make1(makeString($1)); }
12908                         | OPERATOR '(' any_operator ')'
12909                                         { $$ = $3; }
12910                         | LIKE
12911                                         { $$ = list_make1(makeString("~~")); }
12912                         | NOT_LA LIKE
12913                                         { $$ = list_make1(makeString("!~~")); }
12914                         | ILIKE
12915                                         { $$ = list_make1(makeString("~~*")); }
12916                         | NOT_LA ILIKE
12917                                         { $$ = list_make1(makeString("!~~*")); }
12918 /* cannot put SIMILAR TO here, because SIMILAR TO is a hack.
12919  * the regular expression is preprocessed by a function (similar_escape),
12920  * and the ~ operator for posix regular expressions is used.
12921  *        x SIMILAR TO y     ->    x ~ similar_escape(y)
12922  * this transformation is made on the fly by the parser upwards.
12923  * however the SubLink structure which handles any/some/all stuff
12924  * is not ready for such a thing.
12925  */
12926                         ;
12927
12928 expr_list:      a_expr
12929                                 {
12930                                         $$ = list_make1($1);
12931                                 }
12932                         | expr_list ',' a_expr
12933                                 {
12934                                         $$ = lappend($1, $3);
12935                                 }
12936                 ;
12937
12938 /* function arguments can have names */
12939 func_arg_list:  func_arg_expr
12940                                 {
12941                                         $$ = list_make1($1);
12942                                 }
12943                         | func_arg_list ',' func_arg_expr
12944                                 {
12945                                         $$ = lappend($1, $3);
12946                                 }
12947                 ;
12948
12949 func_arg_expr:  a_expr
12950                                 {
12951                                         $$ = $1;
12952                                 }
12953                         | param_name COLON_EQUALS a_expr
12954                                 {
12955                                         NamedArgExpr *na = makeNode(NamedArgExpr);
12956                                         na->name = $1;
12957                                         na->arg = (Expr *) $3;
12958                                         na->argnumber = -1;             /* until determined */
12959                                         na->location = @1;
12960                                         $$ = (Node *) na;
12961                                 }
12962                         | param_name EQUALS_GREATER a_expr
12963                                 {
12964                                         NamedArgExpr *na = makeNode(NamedArgExpr);
12965                                         na->name = $1;
12966                                         na->arg = (Expr *) $3;
12967                                         na->argnumber = -1;             /* until determined */
12968                                         na->location = @1;
12969                                         $$ = (Node *) na;
12970                                 }
12971                 ;
12972
12973 type_list:      Typename                                                                { $$ = list_make1($1); }
12974                         | type_list ',' Typename                                { $$ = lappend($1, $3); }
12975                 ;
12976
12977 array_expr: '[' expr_list ']'
12978                                 {
12979                                         $$ = makeAArrayExpr($2, @1);
12980                                 }
12981                         | '[' array_expr_list ']'
12982                                 {
12983                                         $$ = makeAArrayExpr($2, @1);
12984                                 }
12985                         | '[' ']'
12986                                 {
12987                                         $$ = makeAArrayExpr(NIL, @1);
12988                                 }
12989                 ;
12990
12991 array_expr_list: array_expr                                                     { $$ = list_make1($1); }
12992                         | array_expr_list ',' array_expr                { $$ = lappend($1, $3); }
12993                 ;
12994
12995
12996 extract_list:
12997                         extract_arg FROM a_expr
12998                                 {
12999                                         $$ = list_make2(makeStringConst($1, @1), $3);
13000                                 }
13001                         | /*EMPTY*/                                                             { $$ = NIL; }
13002                 ;
13003
13004 /* Allow delimited string Sconst in extract_arg as an SQL extension.
13005  * - thomas 2001-04-12
13006  */
13007 extract_arg:
13008                         IDENT                                                                   { $$ = $1; }
13009                         | YEAR_P                                                                { $$ = "year"; }
13010                         | MONTH_P                                                               { $$ = "month"; }
13011                         | DAY_P                                                                 { $$ = "day"; }
13012                         | HOUR_P                                                                { $$ = "hour"; }
13013                         | MINUTE_P                                                              { $$ = "minute"; }
13014                         | SECOND_P                                                              { $$ = "second"; }
13015                         | Sconst                                                                { $$ = $1; }
13016                 ;
13017
13018 /* OVERLAY() arguments
13019  * SQL99 defines the OVERLAY() function:
13020  * o overlay(text placing text from int for int)
13021  * o overlay(text placing text from int)
13022  * and similarly for binary strings
13023  */
13024 overlay_list:
13025                         a_expr overlay_placing substr_from substr_for
13026                                 {
13027                                         $$ = list_make4($1, $2, $3, $4);
13028                                 }
13029                         | a_expr overlay_placing substr_from
13030                                 {
13031                                         $$ = list_make3($1, $2, $3);
13032                                 }
13033                 ;
13034
13035 overlay_placing:
13036                         PLACING a_expr
13037                                 { $$ = $2; }
13038                 ;
13039
13040 /* position_list uses b_expr not a_expr to avoid conflict with general IN */
13041
13042 position_list:
13043                         b_expr IN_P b_expr                                              { $$ = list_make2($3, $1); }
13044                         | /*EMPTY*/                                                             { $$ = NIL; }
13045                 ;
13046
13047 /* SUBSTRING() arguments
13048  * SQL9x defines a specific syntax for arguments to SUBSTRING():
13049  * o substring(text from int for int)
13050  * o substring(text from int) get entire string from starting point "int"
13051  * o substring(text for int) get first "int" characters of string
13052  * o substring(text from pattern) get entire string matching pattern
13053  * o substring(text from pattern for escape) same with specified escape char
13054  * We also want to support generic substring functions which accept
13055  * the usual generic list of arguments. So we will accept both styles
13056  * here, and convert the SQL9x style to the generic list for further
13057  * processing. - thomas 2000-11-28
13058  */
13059 substr_list:
13060                         a_expr substr_from substr_for
13061                                 {
13062                                         $$ = list_make3($1, $2, $3);
13063                                 }
13064                         | a_expr substr_for substr_from
13065                                 {
13066                                         /* not legal per SQL99, but might as well allow it */
13067                                         $$ = list_make3($1, $3, $2);
13068                                 }
13069                         | a_expr substr_from
13070                                 {
13071                                         $$ = list_make2($1, $2);
13072                                 }
13073                         | a_expr substr_for
13074                                 {
13075                                         /*
13076                                          * Since there are no cases where this syntax allows
13077                                          * a textual FOR value, we forcibly cast the argument
13078                                          * to int4.  The possible matches in pg_proc are
13079                                          * substring(text,int4) and substring(text,text),
13080                                          * and we don't want the parser to choose the latter,
13081                                          * which it is likely to do if the second argument
13082                                          * is unknown or doesn't have an implicit cast to int4.
13083                                          */
13084                                         $$ = list_make3($1, makeIntConst(1, -1),
13085                                                                         makeTypeCast($2,
13086                                                                                                  SystemTypeName("int4"), -1));
13087                                 }
13088                         | expr_list
13089                                 {
13090                                         $$ = $1;
13091                                 }
13092                         | /*EMPTY*/
13093                                 { $$ = NIL; }
13094                 ;
13095
13096 substr_from:
13097                         FROM a_expr                                                             { $$ = $2; }
13098                 ;
13099
13100 substr_for: FOR a_expr                                                          { $$ = $2; }
13101                 ;
13102
13103 trim_list:      a_expr FROM expr_list                                   { $$ = lappend($3, $1); }
13104                         | FROM expr_list                                                { $$ = $2; }
13105                         | expr_list                                                             { $$ = $1; }
13106                 ;
13107
13108 in_expr:        select_with_parens
13109                                 {
13110                                         SubLink *n = makeNode(SubLink);
13111                                         n->subselect = $1;
13112                                         /* other fields will be filled later */
13113                                         $$ = (Node *)n;
13114                                 }
13115                         | '(' expr_list ')'                                             { $$ = (Node *)$2; }
13116                 ;
13117
13118 /*
13119  * Define SQL-style CASE clause.
13120  * - Full specification
13121  *      CASE WHEN a = b THEN c ... ELSE d END
13122  * - Implicit argument
13123  *      CASE a WHEN b THEN c ... ELSE d END
13124  */
13125 case_expr:      CASE case_arg when_clause_list case_default END_P
13126                                 {
13127                                         CaseExpr *c = makeNode(CaseExpr);
13128                                         c->casetype = InvalidOid; /* not analyzed yet */
13129                                         c->arg = (Expr *) $2;
13130                                         c->args = $3;
13131                                         c->defresult = (Expr *) $4;
13132                                         c->location = @1;
13133                                         $$ = (Node *)c;
13134                                 }
13135                 ;
13136
13137 when_clause_list:
13138                         /* There must be at least one */
13139                         when_clause                                                             { $$ = list_make1($1); }
13140                         | when_clause_list when_clause                  { $$ = lappend($1, $2); }
13141                 ;
13142
13143 when_clause:
13144                         WHEN a_expr THEN a_expr
13145                                 {
13146                                         CaseWhen *w = makeNode(CaseWhen);
13147                                         w->expr = (Expr *) $2;
13148                                         w->result = (Expr *) $4;
13149                                         w->location = @1;
13150                                         $$ = (Node *)w;
13151                                 }
13152                 ;
13153
13154 case_default:
13155                         ELSE a_expr                                                             { $$ = $2; }
13156                         | /*EMPTY*/                                                             { $$ = NULL; }
13157                 ;
13158
13159 case_arg:       a_expr                                                                  { $$ = $1; }
13160                         | /*EMPTY*/                                                             { $$ = NULL; }
13161                 ;
13162
13163 columnref:      ColId
13164                                 {
13165                                         $$ = makeColumnRef($1, NIL, @1, yyscanner);
13166                                 }
13167                         | ColId indirection
13168                                 {
13169                                         $$ = makeColumnRef($1, $2, @1, yyscanner);
13170                                 }
13171                 ;
13172
13173 indirection_el:
13174                         '.' attr_name
13175                                 {
13176                                         $$ = (Node *) makeString($2);
13177                                 }
13178                         | '.' '*'
13179                                 {
13180                                         $$ = (Node *) makeNode(A_Star);
13181                                 }
13182                         | '[' a_expr ']'
13183                                 {
13184                                         A_Indices *ai = makeNode(A_Indices);
13185                                         ai->lidx = NULL;
13186                                         ai->uidx = $2;
13187                                         $$ = (Node *) ai;
13188                                 }
13189                         | '[' a_expr ':' a_expr ']'
13190                                 {
13191                                         A_Indices *ai = makeNode(A_Indices);
13192                                         ai->lidx = $2;
13193                                         ai->uidx = $4;
13194                                         $$ = (Node *) ai;
13195                                 }
13196                 ;
13197
13198 indirection:
13199                         indirection_el                                                  { $$ = list_make1($1); }
13200                         | indirection indirection_el                    { $$ = lappend($1, $2); }
13201                 ;
13202
13203 opt_indirection:
13204                         /*EMPTY*/                                                               { $$ = NIL; }
13205                         | opt_indirection indirection_el                { $$ = lappend($1, $2); }
13206                 ;
13207
13208 opt_asymmetric: ASYMMETRIC
13209                         | /*EMPTY*/
13210                 ;
13211
13212 /*
13213  * The SQL spec defines "contextually typed value expressions" and
13214  * "contextually typed row value constructors", which for our purposes
13215  * are the same as "a_expr" and "row" except that DEFAULT can appear at
13216  * the top level.
13217  */
13218
13219 ctext_expr:
13220                         a_expr                                  { $$ = (Node *) $1; }
13221                         | DEFAULT
13222                                 {
13223                                         SetToDefault *n = makeNode(SetToDefault);
13224                                         n->location = @1;
13225                                         $$ = (Node *) n;
13226                                 }
13227                 ;
13228
13229 ctext_expr_list:
13230                         ctext_expr                                                              { $$ = list_make1($1); }
13231                         | ctext_expr_list ',' ctext_expr                { $$ = lappend($1, $3); }
13232                 ;
13233
13234 /*
13235  * We should allow ROW '(' ctext_expr_list ')' too, but that seems to require
13236  * making VALUES a fully reserved word, which will probably break more apps
13237  * than allowing the noise-word is worth.
13238  */
13239 ctext_row: '(' ctext_expr_list ')'                                      { $$ = $2; }
13240                 ;
13241
13242
13243 /*****************************************************************************
13244  *
13245  *      target list for SELECT
13246  *
13247  *****************************************************************************/
13248
13249 opt_target_list: target_list                                            { $$ = $1; }
13250                         | /* EMPTY */                                                   { $$ = NIL; }
13251                 ;
13252
13253 target_list:
13254                         target_el                                                               { $$ = list_make1($1); }
13255                         | target_list ',' target_el                             { $$ = lappend($1, $3); }
13256                 ;
13257
13258 target_el:      a_expr AS ColLabel
13259                                 {
13260                                         $$ = makeNode(ResTarget);
13261                                         $$->name = $3;
13262                                         $$->indirection = NIL;
13263                                         $$->val = (Node *)$1;
13264                                         $$->location = @1;
13265                                 }
13266                         /*
13267                          * We support omitting AS only for column labels that aren't
13268                          * any known keyword.  There is an ambiguity against postfix
13269                          * operators: is "a ! b" an infix expression, or a postfix
13270                          * expression and a column label?  We prefer to resolve this
13271                          * as an infix expression, which we accomplish by assigning
13272                          * IDENT a precedence higher than POSTFIXOP.
13273                          */
13274                         | a_expr IDENT
13275                                 {
13276                                         $$ = makeNode(ResTarget);
13277                                         $$->name = $2;
13278                                         $$->indirection = NIL;
13279                                         $$->val = (Node *)$1;
13280                                         $$->location = @1;
13281                                 }
13282                         | a_expr
13283                                 {
13284                                         $$ = makeNode(ResTarget);
13285                                         $$->name = NULL;
13286                                         $$->indirection = NIL;
13287                                         $$->val = (Node *)$1;
13288                                         $$->location = @1;
13289                                 }
13290                         | '*'
13291                                 {
13292                                         ColumnRef *n = makeNode(ColumnRef);
13293                                         n->fields = list_make1(makeNode(A_Star));
13294                                         n->location = @1;
13295
13296                                         $$ = makeNode(ResTarget);
13297                                         $$->name = NULL;
13298                                         $$->indirection = NIL;
13299                                         $$->val = (Node *)n;
13300                                         $$->location = @1;
13301                                 }
13302                 ;
13303
13304
13305 /*****************************************************************************
13306  *
13307  *      Names and constants
13308  *
13309  *****************************************************************************/
13310
13311 qualified_name_list:
13312                         qualified_name                                                  { $$ = list_make1($1); }
13313                         | qualified_name_list ',' qualified_name { $$ = lappend($1, $3); }
13314                 ;
13315
13316 /*
13317  * The production for a qualified relation name has to exactly match the
13318  * production for a qualified func_name, because in a FROM clause we cannot
13319  * tell which we are parsing until we see what comes after it ('(' for a
13320  * func_name, something else for a relation). Therefore we allow 'indirection'
13321  * which may contain subscripts, and reject that case in the C code.
13322  */
13323 qualified_name:
13324                         ColId
13325                                 {
13326                                         $$ = makeRangeVar(NULL, $1, @1);
13327                                 }
13328                         | ColId indirection
13329                                 {
13330                                         check_qualified_name($2, yyscanner);
13331                                         $$ = makeRangeVar(NULL, NULL, @1);
13332                                         switch (list_length($2))
13333                                         {
13334                                                 case 1:
13335                                                         $$->catalogname = NULL;
13336                                                         $$->schemaname = $1;
13337                                                         $$->relname = strVal(linitial($2));
13338                                                         break;
13339                                                 case 2:
13340                                                         $$->catalogname = $1;
13341                                                         $$->schemaname = strVal(linitial($2));
13342                                                         $$->relname = strVal(lsecond($2));
13343                                                         break;
13344                                                 default:
13345                                                         ereport(ERROR,
13346                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
13347                                                                          errmsg("improper qualified name (too many dotted names): %s",
13348                                                                                         NameListToString(lcons(makeString($1), $2))),
13349                                                                          parser_errposition(@1)));
13350                                                         break;
13351                                         }
13352                                 }
13353                 ;
13354
13355 name_list:      name
13356                                         { $$ = list_make1(makeString($1)); }
13357                         | name_list ',' name
13358                                         { $$ = lappend($1, makeString($3)); }
13359                 ;
13360
13361
13362 name:           ColId                                                                   { $$ = $1; };
13363
13364 database_name:
13365                         ColId                                                                   { $$ = $1; };
13366
13367 access_method:
13368                         ColId                                                                   { $$ = $1; };
13369
13370 attr_name:      ColLabel                                                                { $$ = $1; };
13371
13372 index_name: ColId                                                                       { $$ = $1; };
13373
13374 file_name:      Sconst                                                                  { $$ = $1; };
13375
13376 /*
13377  * The production for a qualified func_name has to exactly match the
13378  * production for a qualified columnref, because we cannot tell which we
13379  * are parsing until we see what comes after it ('(' or Sconst for a func_name,
13380  * anything else for a columnref).  Therefore we allow 'indirection' which
13381  * may contain subscripts, and reject that case in the C code.  (If we
13382  * ever implement SQL99-like methods, such syntax may actually become legal!)
13383  */
13384 func_name:      type_function_name
13385                                         { $$ = list_make1(makeString($1)); }
13386                         | ColId indirection
13387                                         {
13388                                                 $$ = check_func_name(lcons(makeString($1), $2),
13389                                                                                          yyscanner);
13390                                         }
13391                 ;
13392
13393
13394 /*
13395  * Constants
13396  */
13397 AexprConst: Iconst
13398                                 {
13399                                         $$ = makeIntConst($1, @1);
13400                                 }
13401                         | FCONST
13402                                 {
13403                                         $$ = makeFloatConst($1, @1);
13404                                 }
13405                         | Sconst
13406                                 {
13407                                         $$ = makeStringConst($1, @1);
13408                                 }
13409                         | BCONST
13410                                 {
13411                                         $$ = makeBitStringConst($1, @1);
13412                                 }
13413                         | XCONST
13414                                 {
13415                                         /* This is a bit constant per SQL99:
13416                                          * Without Feature F511, "BIT data type",
13417                                          * a <general literal> shall not be a
13418                                          * <bit string literal> or a <hex string literal>.
13419                                          */
13420                                         $$ = makeBitStringConst($1, @1);
13421                                 }
13422                         | func_name Sconst
13423                                 {
13424                                         /* generic type 'literal' syntax */
13425                                         TypeName *t = makeTypeNameFromNameList($1);
13426                                         t->location = @1;
13427                                         $$ = makeStringConstCast($2, @2, t);
13428                                 }
13429                         | func_name '(' func_arg_list opt_sort_clause ')' Sconst
13430                                 {
13431                                         /* generic syntax with a type modifier */
13432                                         TypeName *t = makeTypeNameFromNameList($1);
13433                                         ListCell *lc;
13434
13435                                         /*
13436                                          * We must use func_arg_list and opt_sort_clause in the
13437                                          * production to avoid reduce/reduce conflicts, but we
13438                                          * don't actually wish to allow NamedArgExpr in this
13439                                          * context, nor ORDER BY.
13440                                          */
13441                                         foreach(lc, $3)
13442                                         {
13443                                                 NamedArgExpr *arg = (NamedArgExpr *) lfirst(lc);
13444
13445                                                 if (IsA(arg, NamedArgExpr))
13446                                                         ereport(ERROR,
13447                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
13448                                                                          errmsg("type modifier cannot have parameter name"),
13449                                                                          parser_errposition(arg->location)));
13450                                         }
13451                                         if ($4 != NIL)
13452                                                         ereport(ERROR,
13453                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
13454                                                                          errmsg("type modifier cannot have ORDER BY"),
13455                                                                          parser_errposition(@4)));
13456
13457                                         t->typmods = $3;
13458                                         t->location = @1;
13459                                         $$ = makeStringConstCast($6, @6, t);
13460                                 }
13461                         | ConstTypename Sconst
13462                                 {
13463                                         $$ = makeStringConstCast($2, @2, $1);
13464                                 }
13465                         | ConstInterval Sconst opt_interval
13466                                 {
13467                                         TypeName *t = $1;
13468                                         t->typmods = $3;
13469                                         $$ = makeStringConstCast($2, @2, t);
13470                                 }
13471                         | ConstInterval '(' Iconst ')' Sconst
13472                                 {
13473                                         TypeName *t = $1;
13474                                         t->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
13475                                                                                         makeIntConst($3, @3));
13476                                         $$ = makeStringConstCast($5, @5, t);
13477                                 }
13478                         | TRUE_P
13479                                 {
13480                                         $$ = makeBoolAConst(TRUE, @1);
13481                                 }
13482                         | FALSE_P
13483                                 {
13484                                         $$ = makeBoolAConst(FALSE, @1);
13485                                 }
13486                         | NULL_P
13487                                 {
13488                                         $$ = makeNullAConst(@1);
13489                                 }
13490                 ;
13491
13492 Iconst:         ICONST                                                                  { $$ = $1; };
13493 Sconst:         SCONST                                                                  { $$ = $1; };
13494
13495 SignedIconst: Iconst                                                            { $$ = $1; }
13496                         | '+' Iconst                                                    { $$ = + $2; }
13497                         | '-' Iconst                                                    { $$ = - $2; }
13498                 ;
13499
13500 /* Role specifications */
13501 RoleId:         RoleSpec
13502                                 {
13503                                         RoleSpec *spc = (RoleSpec *) $1;
13504                                         switch (spc->roletype)
13505                                         {
13506                                                 case ROLESPEC_CSTRING:
13507                                                         $$ = spc->rolename;
13508                                                         break;
13509                                                 case ROLESPEC_PUBLIC:
13510                                                         ereport(ERROR,
13511                                                                         (errcode(ERRCODE_RESERVED_NAME),
13512                                                                          errmsg("role name \"%s\" is reserved",
13513                                                                                         "public"),
13514                                                                          parser_errposition(@1)));
13515                                                 case ROLESPEC_SESSION_USER:
13516                                                         ereport(ERROR,
13517                                                                         (errcode(ERRCODE_RESERVED_NAME),
13518                                                                          errmsg("%s cannot be used as a role name here",
13519                                                                                         "SESSION_USER"),
13520                                                                          parser_errposition(@1)));
13521                                                 case ROLESPEC_CURRENT_USER:
13522                                                         ereport(ERROR,
13523                                                                         (errcode(ERRCODE_RESERVED_NAME),
13524                                                                          errmsg("%s cannot be used as a role name here",
13525                                                                                         "CURRENT_USER"),
13526                                                                          parser_errposition(@1)));
13527                                         }
13528                                 }
13529                         ;
13530
13531 RoleSpec:       NonReservedWord
13532                                         {
13533                                                 /*
13534                                                  * "public" and "none" are not keywords, but they must
13535                                                  * be treated specially here.
13536                                                  */
13537                                                 RoleSpec *n;
13538                                                 if (strcmp($1, "public") == 0)
13539                                                 {
13540                                                         n = (RoleSpec *) makeRoleSpec(ROLESPEC_PUBLIC, @1);
13541                                                         n->roletype = ROLESPEC_PUBLIC;
13542                                                 }
13543                                                 else if (strcmp($1, "none") == 0)
13544                                                 {
13545                                                         ereport(ERROR,
13546                                                                         (errcode(ERRCODE_RESERVED_NAME),
13547                                                                          errmsg("role name \"%s\" is reserved",
13548                                                                                         "none"),
13549                                                                          parser_errposition(@1)));
13550                                                 }
13551                                                 else
13552                                                 {
13553                                                         n = (RoleSpec *) makeRoleSpec(ROLESPEC_CSTRING, @1);
13554                                                         n->rolename = pstrdup($1);
13555                                                 }
13556                                                 $$ = (Node *) n;
13557                                         }
13558                         | CURRENT_USER
13559                                         {
13560                                                 $$ = makeRoleSpec(ROLESPEC_CURRENT_USER, @1);
13561                                         }
13562                         | SESSION_USER
13563                                         {
13564                                                 $$ = makeRoleSpec(ROLESPEC_SESSION_USER, @1);
13565                                         }
13566                 ;
13567
13568 role_list:      RoleSpec
13569                                         { $$ = list_make1($1); }
13570                         | role_list ',' RoleSpec
13571                                         { $$ = lappend($1, $3); }
13572                 ;
13573
13574 /*
13575  * Name classification hierarchy.
13576  *
13577  * IDENT is the lexeme returned by the lexer for identifiers that match
13578  * no known keyword.  In most cases, we can accept certain keywords as
13579  * names, not only IDENTs.      We prefer to accept as many such keywords
13580  * as possible to minimize the impact of "reserved words" on programmers.
13581  * So, we divide names into several possible classes.  The classification
13582  * is chosen in part to make keywords acceptable as names wherever possible.
13583  */
13584
13585 /* Column identifier --- names that can be column, table, etc names.
13586  */
13587 ColId:          IDENT                                                                   { $$ = $1; }
13588                         | unreserved_keyword                                    { $$ = pstrdup($1); }
13589                         | col_name_keyword                                              { $$ = pstrdup($1); }
13590                 ;
13591
13592 /* Type/function identifier --- names that can be type or function names.
13593  */
13594 type_function_name:     IDENT                                                   { $$ = $1; }
13595                         | unreserved_keyword                                    { $$ = pstrdup($1); }
13596                         | type_func_name_keyword                                { $$ = pstrdup($1); }
13597                 ;
13598
13599 /* Any not-fully-reserved word --- these names can be, eg, role names.
13600  */
13601 NonReservedWord:        IDENT                                                   { $$ = $1; }
13602                         | unreserved_keyword                                    { $$ = pstrdup($1); }
13603                         | col_name_keyword                                              { $$ = pstrdup($1); }
13604                         | type_func_name_keyword                                { $$ = pstrdup($1); }
13605                 ;
13606
13607 /* Column label --- allowed labels in "AS" clauses.
13608  * This presently includes *all* Postgres keywords.
13609  */
13610 ColLabel:       IDENT                                                                   { $$ = $1; }
13611                         | unreserved_keyword                                    { $$ = pstrdup($1); }
13612                         | col_name_keyword                                              { $$ = pstrdup($1); }
13613                         | type_func_name_keyword                                { $$ = pstrdup($1); }
13614                         | reserved_keyword                                              { $$ = pstrdup($1); }
13615                 ;
13616
13617
13618 /*
13619  * Keyword category lists.  Generally, every keyword present in
13620  * the Postgres grammar should appear in exactly one of these lists.
13621  *
13622  * Put a new keyword into the first list that it can go into without causing
13623  * shift or reduce conflicts.  The earlier lists define "less reserved"
13624  * categories of keywords.
13625  *
13626  * Make sure that each keyword's category in kwlist.h matches where
13627  * it is listed here.  (Someday we may be able to generate these lists and
13628  * kwlist.h's table from a common master list.)
13629  */
13630
13631 /* "Unreserved" keywords --- available for use as any kind of name.
13632  */
13633 unreserved_keyword:
13634                           ABORT_P
13635                         | ABSOLUTE_P
13636                         | ACCESS
13637                         | ACTION
13638                         | ADD_P
13639                         | ADMIN
13640                         | AFTER
13641                         | AGGREGATE
13642                         | ALSO
13643                         | ALTER
13644                         | ALWAYS
13645                         | ASSERTION
13646                         | ASSIGNMENT
13647                         | AT
13648                         | ATTRIBUTE
13649                         | BACKWARD
13650                         | BEFORE
13651                         | BEGIN_P
13652                         | BY
13653                         | CACHE
13654                         | CALLED
13655                         | CASCADE
13656                         | CASCADED
13657                         | CATALOG_P
13658                         | CHAIN
13659                         | CHARACTERISTICS
13660                         | CHECKPOINT
13661                         | CLASS
13662                         | CLOSE
13663                         | CLUSTER
13664                         | COMMENT
13665                         | COMMENTS
13666                         | COMMIT
13667                         | COMMITTED
13668                         | CONFIGURATION
13669                         | CONFLICT
13670                         | CONNECTION
13671                         | CONSTRAINTS
13672                         | CONTENT_P
13673                         | CONTINUE_P
13674                         | CONVERSION_P
13675                         | COPY
13676                         | COST
13677                         | CSV
13678                         | CUBE
13679                         | CURRENT_P
13680                         | CURSOR
13681                         | CYCLE
13682                         | DATA_P
13683                         | DATABASE
13684                         | DAY_P
13685                         | DEALLOCATE
13686                         | DECLARE
13687                         | DEFAULTS
13688                         | DEFERRED
13689                         | DEFINER
13690                         | DELETE_P
13691                         | DELIMITER
13692                         | DELIMITERS
13693                         | DICTIONARY
13694                         | DISABLE_P
13695                         | DISCARD
13696                         | DOCUMENT_P
13697                         | DOMAIN_P
13698                         | DOUBLE_P
13699                         | DROP
13700                         | EACH
13701                         | ENABLE_P
13702                         | ENCODING
13703                         | ENCRYPTED
13704                         | ENUM_P
13705                         | ESCAPE
13706                         | EVENT
13707                         | EXCLUDE
13708                         | EXCLUDING
13709                         | EXCLUSIVE
13710                         | EXECUTE
13711                         | EXPLAIN
13712                         | EXTENSION
13713                         | EXTERNAL
13714                         | FAMILY
13715                         | FILTER
13716                         | FIRST_P
13717                         | FOLLOWING
13718                         | FORCE
13719                         | FORWARD
13720                         | FUNCTION
13721                         | FUNCTIONS
13722                         | GLOBAL
13723                         | GRANTED
13724                         | HANDLER
13725                         | HEADER_P
13726                         | HOLD
13727                         | HOUR_P
13728                         | IDENTITY_P
13729                         | IF_P
13730                         | IMMEDIATE
13731                         | IMMUTABLE
13732                         | IMPLICIT_P
13733                         | IMPORT_P
13734                         | INCLUDING
13735                         | INCREMENT
13736                         | INDEX
13737                         | INDEXES
13738                         | INHERIT
13739                         | INHERITS
13740                         | INLINE_P
13741                         | INPUT_P
13742                         | INSENSITIVE
13743                         | INSERT
13744                         | INSTEAD
13745                         | INVOKER
13746                         | ISOLATION
13747                         | KEY
13748                         | LABEL
13749                         | LANGUAGE
13750                         | LARGE_P
13751                         | LAST_P
13752                         | LEAKPROOF
13753                         | LEVEL
13754                         | LISTEN
13755                         | LOAD
13756                         | LOCAL
13757                         | LOCATION
13758                         | LOCK_P
13759                         | LOCKED
13760                         | LOGGED
13761                         | MAPPING
13762                         | MATCH
13763                         | MATERIALIZED
13764                         | MAXVALUE
13765                         | MINUTE_P
13766                         | MINVALUE
13767                         | MODE
13768                         | MONTH_P
13769                         | MOVE
13770                         | NAME_P
13771                         | NAMES
13772                         | NEXT
13773                         | NO
13774                         | NOTHING
13775                         | NOTIFY
13776                         | NOWAIT
13777                         | NULLS_P
13778                         | OBJECT_P
13779                         | OF
13780                         | OFF
13781                         | OIDS
13782                         | OPERATOR
13783                         | OPTION
13784                         | OPTIONS
13785                         | ORDINALITY
13786                         | OVER
13787                         | OWNED
13788                         | OWNER
13789                         | PARALLEL
13790                         | PARSER
13791                         | PARTIAL
13792                         | PARTITION
13793                         | PASSING
13794                         | PASSWORD
13795                         | PLANS
13796                         | POLICY
13797                         | PRECEDING
13798                         | PREPARE
13799                         | PREPARED
13800                         | PRESERVE
13801                         | PRIOR
13802                         | PRIVILEGES
13803                         | PROCEDURAL
13804                         | PROCEDURE
13805                         | PROGRAM
13806                         | QUOTE
13807                         | RANGE
13808                         | READ
13809                         | REASSIGN
13810                         | RECHECK
13811                         | RECURSIVE
13812                         | REF
13813                         | REFRESH
13814                         | REINDEX
13815                         | RELATIVE_P
13816                         | RELEASE
13817                         | RENAME
13818                         | REPEATABLE
13819                         | REPLACE
13820                         | REPLICA
13821                         | RESET
13822                         | RESTART
13823                         | RESTRICT
13824                         | RETURNS
13825                         | REVOKE
13826                         | ROLE
13827                         | ROLLBACK
13828                         | ROLLUP
13829                         | ROWS
13830                         | RULE
13831                         | SAVEPOINT
13832                         | SCHEMA
13833                         | SCROLL
13834                         | SEARCH
13835                         | SECOND_P
13836                         | SECURITY
13837                         | SEQUENCE
13838                         | SEQUENCES
13839                         | SERIALIZABLE
13840                         | SERVER
13841                         | SESSION
13842                         | SET
13843                         | SETS
13844                         | SHARE
13845                         | SHOW
13846                         | SIMPLE
13847                         | SKIP
13848                         | SNAPSHOT
13849                         | SQL_P
13850                         | STABLE
13851                         | STANDALONE_P
13852                         | START
13853                         | STATEMENT
13854                         | STATISTICS
13855                         | STDIN
13856                         | STDOUT
13857                         | STORAGE
13858                         | STRICT_P
13859                         | STRIP_P
13860                         | SYSID
13861                         | SYSTEM_P
13862                         | TABLES
13863                         | TABLESPACE
13864                         | TEMP
13865                         | TEMPLATE
13866                         | TEMPORARY
13867                         | TEXT_P
13868                         | TRANSACTION
13869                         | TRANSFORM
13870                         | TRIGGER
13871                         | TRUNCATE
13872                         | TRUSTED
13873                         | TYPE_P
13874                         | TYPES_P
13875                         | UNBOUNDED
13876                         | UNCOMMITTED
13877                         | UNENCRYPTED
13878                         | UNKNOWN
13879                         | UNLISTEN
13880                         | UNLOGGED
13881                         | UNTIL
13882                         | UPDATE
13883                         | VACUUM
13884                         | VALID
13885                         | VALIDATE
13886                         | VALIDATOR
13887                         | VALUE_P
13888                         | VARYING
13889                         | VERSION_P
13890                         | VIEW
13891                         | VIEWS
13892                         | VOLATILE
13893                         | WHITESPACE_P
13894                         | WITHIN
13895                         | WITHOUT
13896                         | WORK
13897                         | WRAPPER
13898                         | WRITE
13899                         | XML_P
13900                         | YEAR_P
13901                         | YES_P
13902                         | ZONE
13903                 ;
13904
13905 /* Column identifier --- keywords that can be column, table, etc names.
13906  *
13907  * Many of these keywords will in fact be recognized as type or function
13908  * names too; but they have special productions for the purpose, and so
13909  * can't be treated as "generic" type or function names.
13910  *
13911  * The type names appearing here are not usable as function names
13912  * because they can be followed by '(' in typename productions, which
13913  * looks too much like a function call for an LR(1) parser.
13914  */
13915 col_name_keyword:
13916                           BETWEEN
13917                         | BIGINT
13918                         | BIT
13919                         | BOOLEAN_P
13920                         | CHAR_P
13921                         | CHARACTER
13922                         | COALESCE
13923                         | DEC
13924                         | DECIMAL_P
13925                         | EXISTS
13926                         | EXTRACT
13927                         | FLOAT_P
13928                         | GREATEST
13929                         | GROUPING
13930                         | INOUT
13931                         | INT_P
13932                         | INTEGER
13933                         | INTERVAL
13934                         | LEAST
13935                         | NATIONAL
13936                         | NCHAR
13937                         | NONE
13938                         | NULLIF
13939                         | NUMERIC
13940                         | OUT_P
13941                         | OVERLAY
13942                         | POSITION
13943                         | PRECISION
13944                         | REAL
13945                         | ROW
13946                         | SETOF
13947                         | SMALLINT
13948                         | SUBSTRING
13949                         | TIME
13950                         | TIMESTAMP
13951                         | TREAT
13952                         | TRIM
13953                         | VALUES
13954                         | VARCHAR
13955                         | XMLATTRIBUTES
13956                         | XMLCONCAT
13957                         | XMLELEMENT
13958                         | XMLEXISTS
13959                         | XMLFOREST
13960                         | XMLPARSE
13961                         | XMLPI
13962                         | XMLROOT
13963                         | XMLSERIALIZE
13964                 ;
13965
13966 /* Type/function identifier --- keywords that can be type or function names.
13967  *
13968  * Most of these are keywords that are used as operators in expressions;
13969  * in general such keywords can't be column names because they would be
13970  * ambiguous with variables, but they are unambiguous as function identifiers.
13971  *
13972  * Do not include POSITION, SUBSTRING, etc here since they have explicit
13973  * productions in a_expr to support the goofy SQL9x argument syntax.
13974  * - thomas 2000-11-28
13975  */
13976 type_func_name_keyword:
13977                           AUTHORIZATION
13978                         | BINARY
13979                         | COLLATION
13980                         | CONCURRENTLY
13981                         | CROSS
13982                         | CURRENT_SCHEMA
13983                         | FREEZE
13984                         | FULL
13985                         | ILIKE
13986                         | INNER_P
13987                         | IS
13988                         | ISNULL
13989                         | JOIN
13990                         | LEFT
13991                         | LIKE
13992                         | NATURAL
13993                         | NOTNULL
13994                         | OUTER_P
13995                         | OVERLAPS
13996                         | RIGHT
13997                         | SIMILAR
13998                         | TABLESAMPLE
13999                         | VERBOSE
14000                 ;
14001
14002 /* Reserved keyword --- these keywords are usable only as a ColLabel.
14003  *
14004  * Keywords appear here if they could not be distinguished from variable,
14005  * type, or function names in some contexts.  Don't put things here unless
14006  * forced to.
14007  */
14008 reserved_keyword:
14009                           ALL
14010                         | ANALYSE
14011                         | ANALYZE
14012                         | AND
14013                         | ANY
14014                         | ARRAY
14015                         | AS
14016                         | ASC
14017                         | ASYMMETRIC
14018                         | BOTH
14019                         | CASE
14020                         | CAST
14021                         | CHECK
14022                         | COLLATE
14023                         | COLUMN
14024                         | CONSTRAINT
14025                         | CREATE
14026                         | CURRENT_CATALOG
14027                         | CURRENT_DATE
14028                         | CURRENT_ROLE
14029                         | CURRENT_TIME
14030                         | CURRENT_TIMESTAMP
14031                         | CURRENT_USER
14032                         | DEFAULT
14033                         | DEFERRABLE
14034                         | DESC
14035                         | DISTINCT
14036                         | DO
14037                         | ELSE
14038                         | END_P
14039                         | EXCEPT
14040                         | FALSE_P
14041                         | FETCH
14042                         | FOR
14043                         | FOREIGN
14044                         | FROM
14045                         | GRANT
14046                         | GROUP_P
14047                         | HAVING
14048                         | IN_P
14049                         | INITIALLY
14050                         | INTERSECT
14051                         | INTO
14052                         | LATERAL_P
14053                         | LEADING
14054                         | LIMIT
14055                         | LOCALTIME
14056                         | LOCALTIMESTAMP
14057                         | NOT
14058                         | NULL_P
14059                         | OFFSET
14060                         | ON
14061                         | ONLY
14062                         | OR
14063                         | ORDER
14064                         | PLACING
14065                         | PRIMARY
14066                         | REFERENCES
14067                         | RETURNING
14068                         | SELECT
14069                         | SESSION_USER
14070                         | SOME
14071                         | SYMMETRIC
14072                         | TABLE
14073                         | THEN
14074                         | TO
14075                         | TRAILING
14076                         | TRUE_P
14077                         | UNION
14078                         | UNIQUE
14079                         | USER
14080                         | USING
14081                         | VARIADIC
14082                         | WHEN
14083                         | WHERE
14084                         | WINDOW
14085                         | WITH
14086                 ;
14087
14088 %%
14089
14090 /*
14091  * The signature of this function is required by bison.  However, we
14092  * ignore the passed yylloc and instead use the last token position
14093  * available from the scanner.
14094  */
14095 static void
14096 base_yyerror(YYLTYPE *yylloc, core_yyscan_t yyscanner, const char *msg)
14097 {
14098         parser_yyerror(msg);
14099 }
14100
14101 static Node *
14102 makeColumnRef(char *colname, List *indirection,
14103                           int location, core_yyscan_t yyscanner)
14104 {
14105         /*
14106          * Generate a ColumnRef node, with an A_Indirection node added if there
14107          * is any subscripting in the specified indirection list.  However,
14108          * any field selection at the start of the indirection list must be
14109          * transposed into the "fields" part of the ColumnRef node.
14110          */
14111         ColumnRef  *c = makeNode(ColumnRef);
14112         int             nfields = 0;
14113         ListCell *l;
14114
14115         c->location = location;
14116         foreach(l, indirection)
14117         {
14118                 if (IsA(lfirst(l), A_Indices))
14119                 {
14120                         A_Indirection *i = makeNode(A_Indirection);
14121
14122                         if (nfields == 0)
14123                         {
14124                                 /* easy case - all indirection goes to A_Indirection */
14125                                 c->fields = list_make1(makeString(colname));
14126                                 i->indirection = check_indirection(indirection, yyscanner);
14127                         }
14128                         else
14129                         {
14130                                 /* got to split the list in two */
14131                                 i->indirection = check_indirection(list_copy_tail(indirection,
14132                                                                                                                                   nfields),
14133                                                                                                    yyscanner);
14134                                 indirection = list_truncate(indirection, nfields);
14135                                 c->fields = lcons(makeString(colname), indirection);
14136                         }
14137                         i->arg = (Node *) c;
14138                         return (Node *) i;
14139                 }
14140                 else if (IsA(lfirst(l), A_Star))
14141                 {
14142                         /* We only allow '*' at the end of a ColumnRef */
14143                         if (lnext(l) != NULL)
14144                                 parser_yyerror("improper use of \"*\"");
14145                 }
14146                 nfields++;
14147         }
14148         /* No subscripting, so all indirection gets added to field list */
14149         c->fields = lcons(makeString(colname), indirection);
14150         return (Node *) c;
14151 }
14152
14153 static Node *
14154 makeTypeCast(Node *arg, TypeName *typename, int location)
14155 {
14156         TypeCast *n = makeNode(TypeCast);
14157         n->arg = arg;
14158         n->typeName = typename;
14159         n->location = location;
14160         return (Node *) n;
14161 }
14162
14163 static Node *
14164 makeStringConst(char *str, int location)
14165 {
14166         A_Const *n = makeNode(A_Const);
14167
14168         n->val.type = T_String;
14169         n->val.val.str = str;
14170         n->location = location;
14171
14172         return (Node *)n;
14173 }
14174
14175 static Node *
14176 makeStringConstCast(char *str, int location, TypeName *typename)
14177 {
14178         Node *s = makeStringConst(str, location);
14179
14180         return makeTypeCast(s, typename, -1);
14181 }
14182
14183 static Node *
14184 makeIntConst(int val, int location)
14185 {
14186         A_Const *n = makeNode(A_Const);
14187
14188         n->val.type = T_Integer;
14189         n->val.val.ival = val;
14190         n->location = location;
14191
14192         return (Node *)n;
14193 }
14194
14195 static Node *
14196 makeFloatConst(char *str, int location)
14197 {
14198         A_Const *n = makeNode(A_Const);
14199
14200         n->val.type = T_Float;
14201         n->val.val.str = str;
14202         n->location = location;
14203
14204         return (Node *)n;
14205 }
14206
14207 static Node *
14208 makeBitStringConst(char *str, int location)
14209 {
14210         A_Const *n = makeNode(A_Const);
14211
14212         n->val.type = T_BitString;
14213         n->val.val.str = str;
14214         n->location = location;
14215
14216         return (Node *)n;
14217 }
14218
14219 static Node *
14220 makeNullAConst(int location)
14221 {
14222         A_Const *n = makeNode(A_Const);
14223
14224         n->val.type = T_Null;
14225         n->location = location;
14226
14227         return (Node *)n;
14228 }
14229
14230 static Node *
14231 makeAConst(Value *v, int location)
14232 {
14233         Node *n;
14234
14235         switch (v->type)
14236         {
14237                 case T_Float:
14238                         n = makeFloatConst(v->val.str, location);
14239                         break;
14240
14241                 case T_Integer:
14242                         n = makeIntConst(v->val.ival, location);
14243                         break;
14244
14245                 case T_String:
14246                 default:
14247                         n = makeStringConst(v->val.str, location);
14248                         break;
14249         }
14250
14251         return n;
14252 }
14253
14254 /* makeBoolAConst()
14255  * Create an A_Const string node and put it inside a boolean cast.
14256  */
14257 static Node *
14258 makeBoolAConst(bool state, int location)
14259 {
14260         A_Const *n = makeNode(A_Const);
14261
14262         n->val.type = T_String;
14263         n->val.val.str = (state ? "t" : "f");
14264         n->location = location;
14265
14266         return makeTypeCast((Node *)n, SystemTypeName("bool"), -1);
14267 }
14268
14269 /* makeRoleSpec
14270  * Create a RoleSpec with the given type
14271  */
14272 static Node *
14273 makeRoleSpec(RoleSpecType type, int location)
14274 {
14275         RoleSpec *spec = makeNode(RoleSpec);
14276
14277         spec->roletype = type;
14278         spec->location = location;
14279
14280         return (Node *) spec;
14281 }
14282
14283 /* check_qualified_name --- check the result of qualified_name production
14284  *
14285  * It's easiest to let the grammar production for qualified_name allow
14286  * subscripts and '*', which we then must reject here.
14287  */
14288 static void
14289 check_qualified_name(List *names, core_yyscan_t yyscanner)
14290 {
14291         ListCell   *i;
14292
14293         foreach(i, names)
14294         {
14295                 if (!IsA(lfirst(i), String))
14296                         parser_yyerror("syntax error");
14297         }
14298 }
14299
14300 /* check_func_name --- check the result of func_name production
14301  *
14302  * It's easiest to let the grammar production for func_name allow subscripts
14303  * and '*', which we then must reject here.
14304  */
14305 static List *
14306 check_func_name(List *names, core_yyscan_t yyscanner)
14307 {
14308         ListCell   *i;
14309
14310         foreach(i, names)
14311         {
14312                 if (!IsA(lfirst(i), String))
14313                         parser_yyerror("syntax error");
14314         }
14315         return names;
14316 }
14317
14318 /* check_indirection --- check the result of indirection production
14319  *
14320  * We only allow '*' at the end of the list, but it's hard to enforce that
14321  * in the grammar, so do it here.
14322  */
14323 static List *
14324 check_indirection(List *indirection, core_yyscan_t yyscanner)
14325 {
14326         ListCell *l;
14327
14328         foreach(l, indirection)
14329         {
14330                 if (IsA(lfirst(l), A_Star))
14331                 {
14332                         if (lnext(l) != NULL)
14333                                 parser_yyerror("improper use of \"*\"");
14334                 }
14335         }
14336         return indirection;
14337 }
14338
14339 /* extractArgTypes()
14340  * Given a list of FunctionParameter nodes, extract a list of just the
14341  * argument types (TypeNames) for input parameters only.  This is what
14342  * is needed to look up an existing function, which is what is wanted by
14343  * the productions that use this call.
14344  */
14345 static List *
14346 extractArgTypes(List *parameters)
14347 {
14348         List       *result = NIL;
14349         ListCell   *i;
14350
14351         foreach(i, parameters)
14352         {
14353                 FunctionParameter *p = (FunctionParameter *) lfirst(i);
14354
14355                 if (p->mode != FUNC_PARAM_OUT && p->mode != FUNC_PARAM_TABLE)
14356                         result = lappend(result, p->argType);
14357         }
14358         return result;
14359 }
14360
14361 /* extractAggrArgTypes()
14362  * As above, but work from the output of the aggr_args production.
14363  */
14364 static List *
14365 extractAggrArgTypes(List *aggrargs)
14366 {
14367         Assert(list_length(aggrargs) == 2);
14368         return extractArgTypes((List *) linitial(aggrargs));
14369 }
14370
14371 /* makeOrderedSetArgs()
14372  * Build the result of the aggr_args production (which see the comments for).
14373  * This handles only the case where both given lists are nonempty, so that
14374  * we have to deal with multiple VARIADIC arguments.
14375  */
14376 static List *
14377 makeOrderedSetArgs(List *directargs, List *orderedargs,
14378                                    core_yyscan_t yyscanner)
14379 {
14380         FunctionParameter *lastd = (FunctionParameter *) llast(directargs);
14381         int                     ndirectargs;
14382
14383         /* No restriction unless last direct arg is VARIADIC */
14384         if (lastd->mode == FUNC_PARAM_VARIADIC)
14385         {
14386                 FunctionParameter *firsto = (FunctionParameter *) linitial(orderedargs);
14387
14388                 /*
14389                  * We ignore the names, though the aggr_arg production allows them;
14390                  * it doesn't allow default values, so those need not be checked.
14391                  */
14392                 if (list_length(orderedargs) != 1 ||
14393                         firsto->mode != FUNC_PARAM_VARIADIC ||
14394                         !equal(lastd->argType, firsto->argType))
14395                         ereport(ERROR,
14396                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14397                                          errmsg("an ordered-set aggregate with a VARIADIC direct argument must have one VARIADIC aggregated argument of the same data type"),
14398                                          parser_errposition(exprLocation((Node *) firsto))));
14399
14400                 /* OK, drop the duplicate VARIADIC argument from the internal form */
14401                 orderedargs = NIL;
14402         }
14403
14404         /* don't merge into the next line, as list_concat changes directargs */
14405         ndirectargs = list_length(directargs);
14406
14407         return list_make2(list_concat(directargs, orderedargs),
14408                                           makeInteger(ndirectargs));
14409 }
14410
14411 /* insertSelectOptions()
14412  * Insert ORDER BY, etc into an already-constructed SelectStmt.
14413  *
14414  * This routine is just to avoid duplicating code in SelectStmt productions.
14415  */
14416 static void
14417 insertSelectOptions(SelectStmt *stmt,
14418                                         List *sortClause, List *lockingClause,
14419                                         Node *limitOffset, Node *limitCount,
14420                                         WithClause *withClause,
14421                                         core_yyscan_t yyscanner)
14422 {
14423         Assert(IsA(stmt, SelectStmt));
14424
14425         /*
14426          * Tests here are to reject constructs like
14427          *      (SELECT foo ORDER BY bar) ORDER BY baz
14428          */
14429         if (sortClause)
14430         {
14431                 if (stmt->sortClause)
14432                         ereport(ERROR,
14433                                         (errcode(ERRCODE_SYNTAX_ERROR),
14434                                          errmsg("multiple ORDER BY clauses not allowed"),
14435                                          parser_errposition(exprLocation((Node *) sortClause))));
14436                 stmt->sortClause = sortClause;
14437         }
14438         /* We can handle multiple locking clauses, though */
14439         stmt->lockingClause = list_concat(stmt->lockingClause, lockingClause);
14440         if (limitOffset)
14441         {
14442                 if (stmt->limitOffset)
14443                         ereport(ERROR,
14444                                         (errcode(ERRCODE_SYNTAX_ERROR),
14445                                          errmsg("multiple OFFSET clauses not allowed"),
14446                                          parser_errposition(exprLocation(limitOffset))));
14447                 stmt->limitOffset = limitOffset;
14448         }
14449         if (limitCount)
14450         {
14451                 if (stmt->limitCount)
14452                         ereport(ERROR,
14453                                         (errcode(ERRCODE_SYNTAX_ERROR),
14454                                          errmsg("multiple LIMIT clauses not allowed"),
14455                                          parser_errposition(exprLocation(limitCount))));
14456                 stmt->limitCount = limitCount;
14457         }
14458         if (withClause)
14459         {
14460                 if (stmt->withClause)
14461                         ereport(ERROR,
14462                                         (errcode(ERRCODE_SYNTAX_ERROR),
14463                                          errmsg("multiple WITH clauses not allowed"),
14464                                          parser_errposition(exprLocation((Node *) withClause))));
14465                 stmt->withClause = withClause;
14466         }
14467 }
14468
14469 static Node *
14470 makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
14471 {
14472         SelectStmt *n = makeNode(SelectStmt);
14473
14474         n->op = op;
14475         n->all = all;
14476         n->larg = (SelectStmt *) larg;
14477         n->rarg = (SelectStmt *) rarg;
14478         return (Node *) n;
14479 }
14480
14481 /* SystemFuncName()
14482  * Build a properly-qualified reference to a built-in function.
14483  */
14484 List *
14485 SystemFuncName(char *name)
14486 {
14487         return list_make2(makeString("pg_catalog"), makeString(name));
14488 }
14489
14490 /* SystemTypeName()
14491  * Build a properly-qualified reference to a built-in type.
14492  *
14493  * typmod is defaulted, but may be changed afterwards by caller.
14494  * Likewise for the location.
14495  */
14496 TypeName *
14497 SystemTypeName(char *name)
14498 {
14499         return makeTypeNameFromNameList(list_make2(makeString("pg_catalog"),
14500                                                                                            makeString(name)));
14501 }
14502
14503 /* doNegate()
14504  * Handle negation of a numeric constant.
14505  *
14506  * Formerly, we did this here because the optimizer couldn't cope with
14507  * indexquals that looked like "var = -4" --- it wants "var = const"
14508  * and a unary minus operator applied to a constant didn't qualify.
14509  * As of Postgres 7.0, that problem doesn't exist anymore because there
14510  * is a constant-subexpression simplifier in the optimizer.  However,
14511  * there's still a good reason for doing this here, which is that we can
14512  * postpone committing to a particular internal representation for simple
14513  * negative constants.  It's better to leave "-123.456" in string form
14514  * until we know what the desired type is.
14515  */
14516 static Node *
14517 doNegate(Node *n, int location)
14518 {
14519         if (IsA(n, A_Const))
14520         {
14521                 A_Const *con = (A_Const *)n;
14522
14523                 /* report the constant's location as that of the '-' sign */
14524                 con->location = location;
14525
14526                 if (con->val.type == T_Integer)
14527                 {
14528                         con->val.val.ival = -con->val.val.ival;
14529                         return n;
14530                 }
14531                 if (con->val.type == T_Float)
14532                 {
14533                         doNegateFloat(&con->val);
14534                         return n;
14535                 }
14536         }
14537
14538         return (Node *) makeSimpleA_Expr(AEXPR_OP, "-", NULL, n, location);
14539 }
14540
14541 static void
14542 doNegateFloat(Value *v)
14543 {
14544         char   *oldval = v->val.str;
14545
14546         Assert(IsA(v, Float));
14547         if (*oldval == '+')
14548                 oldval++;
14549         if (*oldval == '-')
14550                 v->val.str = oldval+1;  /* just strip the '-' */
14551         else
14552                 v->val.str = psprintf("-%s", oldval);
14553 }
14554
14555 static Node *
14556 makeAndExpr(Node *lexpr, Node *rexpr, int location)
14557 {
14558         /* Flatten "a AND b AND c ..." to a single BoolExpr on sight */
14559         if (IsA(lexpr, BoolExpr))
14560         {
14561                 BoolExpr *blexpr = (BoolExpr *) lexpr;
14562
14563                 if (blexpr->boolop == AND_EXPR)
14564                 {
14565                         blexpr->args = lappend(blexpr->args, rexpr);
14566                         return (Node *) blexpr;
14567                 }
14568         }
14569         return (Node *) makeBoolExpr(AND_EXPR, list_make2(lexpr, rexpr), location);
14570 }
14571
14572 static Node *
14573 makeOrExpr(Node *lexpr, Node *rexpr, int location)
14574 {
14575         /* Flatten "a OR b OR c ..." to a single BoolExpr on sight */
14576         if (IsA(lexpr, BoolExpr))
14577         {
14578                 BoolExpr *blexpr = (BoolExpr *) lexpr;
14579
14580                 if (blexpr->boolop == OR_EXPR)
14581                 {
14582                         blexpr->args = lappend(blexpr->args, rexpr);
14583                         return (Node *) blexpr;
14584                 }
14585         }
14586         return (Node *) makeBoolExpr(OR_EXPR, list_make2(lexpr, rexpr), location);
14587 }
14588
14589 static Node *
14590 makeNotExpr(Node *expr, int location)
14591 {
14592         return (Node *) makeBoolExpr(NOT_EXPR, list_make1(expr), location);
14593 }
14594
14595 static Node *
14596 makeAArrayExpr(List *elements, int location)
14597 {
14598         A_ArrayExpr *n = makeNode(A_ArrayExpr);
14599
14600         n->elements = elements;
14601         n->location = location;
14602         return (Node *) n;
14603 }
14604
14605 static Node *
14606 makeXmlExpr(XmlExprOp op, char *name, List *named_args, List *args,
14607                         int location)
14608 {
14609         XmlExpr         *x = makeNode(XmlExpr);
14610
14611         x->op = op;
14612         x->name = name;
14613         /*
14614          * named_args is a list of ResTarget; it'll be split apart into separate
14615          * expression and name lists in transformXmlExpr().
14616          */
14617         x->named_args = named_args;
14618         x->arg_names = NIL;
14619         x->args = args;
14620         /* xmloption, if relevant, must be filled in by caller */
14621         /* type and typmod will be filled in during parse analysis */
14622         x->type = InvalidOid;                   /* marks the node as not analyzed */
14623         x->location = location;
14624         return (Node *) x;
14625 }
14626
14627 /*
14628  * Merge the input and output parameters of a table function.
14629  */
14630 static List *
14631 mergeTableFuncParameters(List *func_args, List *columns)
14632 {
14633         ListCell   *lc;
14634
14635         /* Explicit OUT and INOUT parameters shouldn't be used in this syntax */
14636         foreach(lc, func_args)
14637         {
14638                 FunctionParameter *p = (FunctionParameter *) lfirst(lc);
14639
14640                 if (p->mode != FUNC_PARAM_IN && p->mode != FUNC_PARAM_VARIADIC)
14641                         ereport(ERROR,
14642                                         (errcode(ERRCODE_SYNTAX_ERROR),
14643                                          errmsg("OUT and INOUT arguments aren't allowed in TABLE functions")));
14644         }
14645
14646         return list_concat(func_args, columns);
14647 }
14648
14649 /*
14650  * Determine return type of a TABLE function.  A single result column
14651  * returns setof that column's type; otherwise return setof record.
14652  */
14653 static TypeName *
14654 TableFuncTypeName(List *columns)
14655 {
14656         TypeName *result;
14657
14658         if (list_length(columns) == 1)
14659         {
14660                 FunctionParameter *p = (FunctionParameter *) linitial(columns);
14661
14662                 result = (TypeName *) copyObject(p->argType);
14663         }
14664         else
14665                 result = SystemTypeName("record");
14666
14667         result->setof = true;
14668
14669         return result;
14670 }
14671
14672 /*
14673  * Convert a list of (dotted) names to a RangeVar (like
14674  * makeRangeVarFromNameList, but with position support).  The
14675  * "AnyName" refers to the any_name production in the grammar.
14676  */
14677 static RangeVar *
14678 makeRangeVarFromAnyName(List *names, int position, core_yyscan_t yyscanner)
14679 {
14680         RangeVar *r = makeNode(RangeVar);
14681
14682         switch (list_length(names))
14683         {
14684                 case 1:
14685                         r->catalogname = NULL;
14686                         r->schemaname = NULL;
14687                         r->relname = strVal(linitial(names));
14688                         break;
14689                 case 2:
14690                         r->catalogname = NULL;
14691                         r->schemaname = strVal(linitial(names));
14692                         r->relname = strVal(lsecond(names));
14693                         break;
14694                 case 3:
14695                         r->catalogname = strVal(linitial(names));
14696                         r->schemaname = strVal(lsecond(names));
14697                         r->relname = strVal(lthird(names));
14698                         break;
14699                 default:
14700                         ereport(ERROR,
14701                                         (errcode(ERRCODE_SYNTAX_ERROR),
14702                                          errmsg("improper qualified name (too many dotted names): %s",
14703                                                         NameListToString(names)),
14704                                          parser_errposition(position)));
14705                         break;
14706         }
14707
14708         r->relpersistence = RELPERSISTENCE_PERMANENT;
14709         r->location = position;
14710
14711         return r;
14712 }
14713
14714 /* Separate Constraint nodes from COLLATE clauses in a ColQualList */
14715 static void
14716 SplitColQualList(List *qualList,
14717                                  List **constraintList, CollateClause **collClause,
14718                                  core_yyscan_t yyscanner)
14719 {
14720         ListCell   *cell;
14721         ListCell   *prev;
14722         ListCell   *next;
14723
14724         *collClause = NULL;
14725         prev = NULL;
14726         for (cell = list_head(qualList); cell; cell = next)
14727         {
14728                 Node   *n = (Node *) lfirst(cell);
14729
14730                 next = lnext(cell);
14731                 if (IsA(n, Constraint))
14732                 {
14733                         /* keep it in list */
14734                         prev = cell;
14735                         continue;
14736                 }
14737                 if (IsA(n, CollateClause))
14738                 {
14739                         CollateClause *c = (CollateClause *) n;
14740
14741                         if (*collClause)
14742                                 ereport(ERROR,
14743                                                 (errcode(ERRCODE_SYNTAX_ERROR),
14744                                                  errmsg("multiple COLLATE clauses not allowed"),
14745                                                  parser_errposition(c->location)));
14746                         *collClause = c;
14747                 }
14748                 else
14749                         elog(ERROR, "unexpected node type %d", (int) n->type);
14750                 /* remove non-Constraint nodes from qualList */
14751                 qualList = list_delete_cell(qualList, cell, prev);
14752         }
14753         *constraintList = qualList;
14754 }
14755
14756 /*
14757  * Process result of ConstraintAttributeSpec, and set appropriate bool flags
14758  * in the output command node.  Pass NULL for any flags the particular
14759  * command doesn't support.
14760  */
14761 static void
14762 processCASbits(int cas_bits, int location, const char *constrType,
14763                            bool *deferrable, bool *initdeferred, bool *not_valid,
14764                            bool *no_inherit, core_yyscan_t yyscanner)
14765 {
14766         /* defaults */
14767         if (deferrable)
14768                 *deferrable = false;
14769         if (initdeferred)
14770                 *initdeferred = false;
14771         if (not_valid)
14772                 *not_valid = false;
14773
14774         if (cas_bits & (CAS_DEFERRABLE | CAS_INITIALLY_DEFERRED))
14775         {
14776                 if (deferrable)
14777                         *deferrable = true;
14778                 else
14779                         ereport(ERROR,
14780                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14781                                          /* translator: %s is CHECK, UNIQUE, or similar */
14782                                          errmsg("%s constraints cannot be marked DEFERRABLE",
14783                                                         constrType),
14784                                          parser_errposition(location)));
14785         }
14786
14787         if (cas_bits & CAS_INITIALLY_DEFERRED)
14788         {
14789                 if (initdeferred)
14790                         *initdeferred = true;
14791                 else
14792                         ereport(ERROR,
14793                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14794                                          /* translator: %s is CHECK, UNIQUE, or similar */
14795                                          errmsg("%s constraints cannot be marked DEFERRABLE",
14796                                                         constrType),
14797                                          parser_errposition(location)));
14798         }
14799
14800         if (cas_bits & CAS_NOT_VALID)
14801         {
14802                 if (not_valid)
14803                         *not_valid = true;
14804                 else
14805                         ereport(ERROR,
14806                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14807                                          /* translator: %s is CHECK, UNIQUE, or similar */
14808                                          errmsg("%s constraints cannot be marked NOT VALID",
14809                                                         constrType),
14810                                          parser_errposition(location)));
14811         }
14812
14813         if (cas_bits & CAS_NO_INHERIT)
14814         {
14815                 if (no_inherit)
14816                         *no_inherit = true;
14817                 else
14818                         ereport(ERROR,
14819                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
14820                                          /* translator: %s is CHECK, UNIQUE, or similar */
14821                                          errmsg("%s constraints cannot be marked NO INHERIT",
14822                                                         constrType),
14823                                          parser_errposition(location)));
14824         }
14825 }
14826
14827 /*----------
14828  * Recursive view transformation
14829  *
14830  * Convert
14831  *
14832  *     CREATE RECURSIVE VIEW relname (aliases) AS query
14833  *
14834  * to
14835  *
14836  *     CREATE VIEW relname (aliases) AS
14837  *         WITH RECURSIVE relname (aliases) AS (query)
14838  *         SELECT aliases FROM relname
14839  *
14840  * Actually, just the WITH ... part, which is then inserted into the original
14841  * view definition as the query.
14842  * ----------
14843  */
14844 static Node *
14845 makeRecursiveViewSelect(char *relname, List *aliases, Node *query)
14846 {
14847         SelectStmt *s = makeNode(SelectStmt);
14848         WithClause *w = makeNode(WithClause);
14849         CommonTableExpr *cte = makeNode(CommonTableExpr);
14850         List       *tl = NIL;
14851         ListCell   *lc;
14852
14853         /* create common table expression */
14854         cte->ctename = relname;
14855         cte->aliascolnames = aliases;
14856         cte->ctequery = query;
14857         cte->location = -1;
14858
14859         /* create WITH clause and attach CTE */
14860         w->recursive = true;
14861         w->ctes = list_make1(cte);
14862         w->location = -1;
14863
14864         /* create target list for the new SELECT from the alias list of the
14865          * recursive view specification */
14866         foreach (lc, aliases)
14867         {
14868                 ResTarget *rt = makeNode(ResTarget);
14869
14870                 rt->name = NULL;
14871                 rt->indirection = NIL;
14872                 rt->val = makeColumnRef(strVal(lfirst(lc)), NIL, -1, 0);
14873                 rt->location = -1;
14874
14875                 tl = lappend(tl, rt);
14876         }
14877
14878         /* create new SELECT combining WITH clause, target list, and fake FROM
14879          * clause */
14880         s->withClause = w;
14881         s->targetList = tl;
14882         s->fromClause = list_make1(makeRangeVar(NULL, relname, -1));
14883
14884         return (Node *) s;
14885 }
14886
14887 /* parser_init()
14888  * Initialize to parse one query string
14889  */
14890 void
14891 parser_init(base_yy_extra_type *yyext)
14892 {
14893         yyext->parsetree = NIL;         /* in case grammar forgets to set it */
14894 }
14895
14896 /*
14897  * Must undefine this stuff before including scan.c, since it has different
14898  * definitions for these macros.
14899  */
14900 #undef yyerror
14901 #undef yylval
14902 #undef yylloc
14903
14904 #include "scan.c"