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