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