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