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