]> granicus.if.org Git - postgresql/blob - src/backend/parser/gram.y
Add comment about why BETWEEN uses operator strings and not opclasses,
[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-2009, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $PostgreSQL: pgsql/src/backend/parser/gram.y,v 2.652 2009/01/07 22:54:45 momjian 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                         | WINDOW
4805                                 {
4806                                         $$ = makeDefElem("window", (Node *)makeInteger(TRUE));
4807                                 }
4808                         | common_func_opt_item
4809                                 {
4810                                         $$ = $1;
4811                                 }
4812                 ;
4813
4814 func_as:        Sconst                                          { $$ = list_make1(makeString($1)); }
4815                         | Sconst ',' Sconst
4816                                 {
4817                                         $$ = list_make2(makeString($1), makeString($3));
4818                                 }
4819                 ;
4820
4821 opt_definition:
4822                         WITH definition                                                 { $$ = $2; }
4823                         | /*EMPTY*/                                                             { $$ = NIL; }
4824                 ;
4825
4826 table_func_column:      param_name func_type
4827                                 {
4828                                         FunctionParameter *n = makeNode(FunctionParameter);
4829                                         n->name = $1;
4830                                         n->argType = $2;
4831                                         n->mode = FUNC_PARAM_TABLE;
4832                                         n->defexpr = NULL;
4833                                         $$ = n;
4834                                 }
4835                 ;
4836
4837 table_func_column_list:
4838                         table_func_column
4839                                 {
4840                                         $$ = list_make1($1);
4841                                 }
4842                         | table_func_column_list ',' table_func_column
4843                                 {
4844                                         $$ = lappend($1, $3);
4845                                 }
4846                 ;
4847
4848 /*****************************************************************************
4849  * ALTER FUNCTION
4850  *
4851  * RENAME and OWNER subcommands are already provided by the generic
4852  * ALTER infrastructure, here we just specify alterations that can
4853  * only be applied to functions.
4854  *
4855  *****************************************************************************/
4856 AlterFunctionStmt:
4857                         ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
4858                                 {
4859                                         AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
4860                                         n->func = $3;
4861                                         n->actions = $4;
4862                                         $$ = (Node *) n;
4863                                 }
4864                 ;
4865
4866 alterfunc_opt_list:
4867                         /* At least one option must be specified */
4868                         common_func_opt_item                                    { $$ = list_make1($1); }
4869                         | alterfunc_opt_list common_func_opt_item { $$ = lappend($1, $2); }
4870                 ;
4871
4872 /* Ignored, merely for SQL compliance */
4873 opt_restrict:
4874                         RESTRICT
4875                         | /* EMPTY */
4876                 ;
4877
4878
4879 /*****************************************************************************
4880  *
4881  *              QUERY:
4882  *
4883  *              DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
4884  *              DROP AGGREGATE aggname (arg1, ...) [ RESTRICT | CASCADE ]
4885  *              DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
4886  *
4887  *****************************************************************************/
4888
4889 RemoveFuncStmt:
4890                         DROP FUNCTION func_name func_args opt_drop_behavior
4891                                 {
4892                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4893                                         n->kind = OBJECT_FUNCTION;
4894                                         n->name = $3;
4895                                         n->args = extractArgTypes($4);
4896                                         n->behavior = $5;
4897                                         n->missing_ok = false;
4898                                         $$ = (Node *)n;
4899                                 }
4900                         | DROP FUNCTION IF_P EXISTS func_name func_args opt_drop_behavior
4901                                 {
4902                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4903                                         n->kind = OBJECT_FUNCTION;
4904                                         n->name = $5;
4905                                         n->args = extractArgTypes($6);
4906                                         n->behavior = $7;
4907                                         n->missing_ok = true;
4908                                         $$ = (Node *)n;
4909                                 }
4910                 ;
4911
4912 RemoveAggrStmt:
4913                         DROP AGGREGATE func_name aggr_args opt_drop_behavior
4914                                 {
4915                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4916                                         n->kind = OBJECT_AGGREGATE;
4917                                         n->name = $3;
4918                                         n->args = $4;
4919                                         n->behavior = $5;
4920                                         n->missing_ok = false;
4921                                         $$ = (Node *)n;
4922                                 }
4923                         | DROP AGGREGATE IF_P EXISTS func_name aggr_args opt_drop_behavior
4924                                 {
4925                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4926                                         n->kind = OBJECT_AGGREGATE;
4927                                         n->name = $5;
4928                                         n->args = $6;
4929                                         n->behavior = $7;
4930                                         n->missing_ok = true;
4931                                         $$ = (Node *)n;
4932                                 }
4933                 ;
4934
4935 RemoveOperStmt:
4936                         DROP OPERATOR any_operator oper_argtypes opt_drop_behavior
4937                                 {
4938                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4939                                         n->kind = OBJECT_OPERATOR;
4940                                         n->name = $3;
4941                                         n->args = $4;
4942                                         n->behavior = $5;
4943                                         n->missing_ok = false;
4944                                         $$ = (Node *)n;
4945                                 }
4946                         | DROP OPERATOR IF_P EXISTS any_operator oper_argtypes opt_drop_behavior
4947                                 {
4948                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4949                                         n->kind = OBJECT_OPERATOR;
4950                                         n->name = $5;
4951                                         n->args = $6;
4952                                         n->behavior = $7;
4953                                         n->missing_ok = true;
4954                                         $$ = (Node *)n;
4955                                 }
4956                 ;
4957
4958 oper_argtypes:
4959                         '(' Typename ')'
4960                                 {
4961                                    ereport(ERROR,
4962                                                    (errcode(ERRCODE_SYNTAX_ERROR),
4963                                                         errmsg("missing argument"),
4964                                                         errhint("Use NONE to denote the missing argument of a unary operator."),
4965                                                         scanner_errposition(@3)));
4966                                 }
4967                         | '(' Typename ',' Typename ')'
4968                                         { $$ = list_make2($2, $4); }
4969                         | '(' NONE ',' Typename ')'                                     /* left unary */
4970                                         { $$ = list_make2(NULL, $4); }
4971                         | '(' Typename ',' NONE ')'                                     /* right unary */
4972                                         { $$ = list_make2($2, NULL); }
4973                 ;
4974
4975 any_operator:
4976                         all_Op
4977                                         { $$ = list_make1(makeString($1)); }
4978                         | ColId '.' any_operator
4979                                         { $$ = lcons(makeString($1), $3); }
4980                 ;
4981
4982
4983 /*****************************************************************************
4984  *
4985  *              CREATE CAST / DROP CAST
4986  *
4987  *****************************************************************************/
4988
4989 CreateCastStmt: CREATE CAST '(' Typename AS Typename ')'
4990                                         WITH FUNCTION function_with_argtypes cast_context
4991                                 {
4992                                         CreateCastStmt *n = makeNode(CreateCastStmt);
4993                                         n->sourcetype = $4;
4994                                         n->targettype = $6;
4995                                         n->func = $10;
4996                                         n->context = (CoercionContext) $11;
4997                                         n->inout = false;
4998                                         $$ = (Node *)n;
4999                                 }
5000                         | CREATE CAST '(' Typename AS Typename ')'
5001                                         WITHOUT FUNCTION cast_context
5002                                 {
5003                                         CreateCastStmt *n = makeNode(CreateCastStmt);
5004                                         n->sourcetype = $4;
5005                                         n->targettype = $6;
5006                                         n->func = NULL;
5007                                         n->context = (CoercionContext) $10;
5008                                         n->inout = false;
5009                                         $$ = (Node *)n;
5010                                 }
5011                         | CREATE CAST '(' Typename AS Typename ')'
5012                                         WITH INOUT cast_context
5013                                 {
5014                                         CreateCastStmt *n = makeNode(CreateCastStmt);
5015                                         n->sourcetype = $4;
5016                                         n->targettype = $6;
5017                                         n->func = NULL;
5018                                         n->context = (CoercionContext) $10;
5019                                         n->inout = true;
5020                                         $$ = (Node *)n;
5021                                 }
5022                 ;
5023
5024 cast_context:  AS IMPLICIT_P                                    { $$ = COERCION_IMPLICIT; }
5025                 | AS ASSIGNMENT                                                 { $$ = COERCION_ASSIGNMENT; }
5026                 | /*EMPTY*/                                                             { $$ = COERCION_EXPLICIT; }
5027                 ;
5028
5029
5030 DropCastStmt: DROP CAST opt_if_exists '(' Typename AS Typename ')' opt_drop_behavior
5031                                 {
5032                                         DropCastStmt *n = makeNode(DropCastStmt);
5033                                         n->sourcetype = $5;
5034                                         n->targettype = $7;
5035                                         n->behavior = $9;
5036                                         n->missing_ok = $3;
5037                                         $$ = (Node *)n;
5038                                 }
5039                 ;
5040
5041 opt_if_exists: IF_P EXISTS                                              { $$ = TRUE; }
5042                 | /*EMPTY*/                                                             { $$ = FALSE; }
5043                 ;
5044
5045
5046 /*****************************************************************************
5047  *
5048  *              QUERY:
5049  *
5050  *              REINDEX type <name> [FORCE]
5051  *
5052  * FORCE no longer does anything, but we accept it for backwards compatibility
5053  *****************************************************************************/
5054
5055 ReindexStmt:
5056                         REINDEX reindex_type qualified_name opt_force
5057                                 {
5058                                         ReindexStmt *n = makeNode(ReindexStmt);
5059                                         n->kind = $2;
5060                                         n->relation = $3;
5061                                         n->name = NULL;
5062                                         $$ = (Node *)n;
5063                                 }
5064                         | REINDEX SYSTEM_P name opt_force
5065                                 {
5066                                         ReindexStmt *n = makeNode(ReindexStmt);
5067                                         n->kind = OBJECT_DATABASE;
5068                                         n->name = $3;
5069                                         n->relation = NULL;
5070                                         n->do_system = true;
5071                                         n->do_user = false;
5072                                         $$ = (Node *)n;
5073                                 }
5074                         | REINDEX DATABASE name opt_force
5075                                 {
5076                                         ReindexStmt *n = makeNode(ReindexStmt);
5077                                         n->kind = OBJECT_DATABASE;
5078                                         n->name = $3;
5079                                         n->relation = NULL;
5080                                         n->do_system = true;
5081                                         n->do_user = true;
5082                                         $$ = (Node *)n;
5083                                 }
5084                 ;
5085
5086 reindex_type:
5087                         INDEX                                                                   { $$ = OBJECT_INDEX; }
5088                         | TABLE                                                                 { $$ = OBJECT_TABLE; }
5089                 ;
5090
5091 opt_force:      FORCE                                                                   {  $$ = TRUE; }
5092                         | /* EMPTY */                                                   {  $$ = FALSE; }
5093                 ;
5094
5095
5096 /*****************************************************************************
5097  *
5098  * ALTER THING name RENAME TO newname
5099  *
5100  *****************************************************************************/
5101
5102 RenameStmt: ALTER AGGREGATE func_name aggr_args RENAME TO name
5103                                 {
5104                                         RenameStmt *n = makeNode(RenameStmt);
5105                                         n->renameType = OBJECT_AGGREGATE;
5106                                         n->object = $3;
5107                                         n->objarg = $4;
5108                                         n->newname = $7;
5109                                         $$ = (Node *)n;
5110                                 }
5111                         | ALTER CONVERSION_P any_name RENAME TO name
5112                                 {
5113                                         RenameStmt *n = makeNode(RenameStmt);
5114                                         n->renameType = OBJECT_CONVERSION;
5115                                         n->object = $3;
5116                                         n->newname = $6;
5117                                         $$ = (Node *)n;
5118                                 }
5119                         | ALTER DATABASE database_name RENAME TO database_name
5120                                 {
5121                                         RenameStmt *n = makeNode(RenameStmt);
5122                                         n->renameType = OBJECT_DATABASE;
5123                                         n->subname = $3;
5124                                         n->newname = $6;
5125                                         $$ = (Node *)n;
5126                                 }
5127                         | ALTER FUNCTION function_with_argtypes RENAME TO name
5128                                 {
5129                                         RenameStmt *n = makeNode(RenameStmt);
5130                                         n->renameType = OBJECT_FUNCTION;
5131                                         n->object = $3->funcname;
5132                                         n->objarg = $3->funcargs;
5133                                         n->newname = $6;
5134                                         $$ = (Node *)n;
5135                                 }
5136                         | ALTER GROUP_P RoleId RENAME TO RoleId
5137                                 {
5138                                         RenameStmt *n = makeNode(RenameStmt);
5139                                         n->renameType = OBJECT_ROLE;
5140                                         n->subname = $3;
5141                                         n->newname = $6;
5142                                         $$ = (Node *)n;
5143                                 }
5144                         | ALTER opt_procedural LANGUAGE name RENAME TO name
5145                                 {
5146                                         RenameStmt *n = makeNode(RenameStmt);
5147                                         n->renameType = OBJECT_LANGUAGE;
5148                                         n->subname = $4;
5149                                         n->newname = $7;
5150                                         $$ = (Node *)n;
5151                                 }
5152                         | ALTER OPERATOR CLASS any_name USING access_method RENAME TO name
5153                                 {
5154                                         RenameStmt *n = makeNode(RenameStmt);
5155                                         n->renameType = OBJECT_OPCLASS;
5156                                         n->object = $4;
5157                                         n->subname = $6;
5158                                         n->newname = $9;
5159                                         $$ = (Node *)n;
5160                                 }
5161                         | ALTER OPERATOR FAMILY any_name USING access_method RENAME TO name
5162                                 {
5163                                         RenameStmt *n = makeNode(RenameStmt);
5164                                         n->renameType = OBJECT_OPFAMILY;
5165                                         n->object = $4;
5166                                         n->subname = $6;
5167                                         n->newname = $9;
5168                                         $$ = (Node *)n;
5169                                 }
5170                         | ALTER SCHEMA name RENAME TO name
5171                                 {
5172                                         RenameStmt *n = makeNode(RenameStmt);
5173                                         n->renameType = OBJECT_SCHEMA;
5174                                         n->subname = $3;
5175                                         n->newname = $6;
5176                                         $$ = (Node *)n;
5177                                 }
5178                         | ALTER TABLE relation_expr RENAME TO name
5179                                 {
5180                                         RenameStmt *n = makeNode(RenameStmt);
5181                                         n->renameType = OBJECT_TABLE;
5182                                         n->relation = $3;
5183                                         n->subname = NULL;
5184                                         n->newname = $6;
5185                                         $$ = (Node *)n;
5186                                 }
5187                         | ALTER SEQUENCE relation_expr RENAME TO name
5188                                 {
5189                                         RenameStmt *n = makeNode(RenameStmt);
5190                                         n->renameType = OBJECT_SEQUENCE;
5191                                         n->relation = $3;
5192                                         n->subname = NULL;
5193                                         n->newname = $6;
5194                                         $$ = (Node *)n;
5195                                 }
5196                         | ALTER VIEW relation_expr RENAME TO name
5197                                 {
5198                                         RenameStmt *n = makeNode(RenameStmt);
5199                                         n->renameType = OBJECT_VIEW;
5200                                         n->relation = $3;
5201                                         n->subname = NULL;
5202                                         n->newname = $6;
5203                                         $$ = (Node *)n;
5204                                 }
5205                         | ALTER INDEX relation_expr RENAME TO name
5206                                 {
5207                                         RenameStmt *n = makeNode(RenameStmt);
5208                                         n->renameType = OBJECT_INDEX;
5209                                         n->relation = $3;
5210                                         n->subname = NULL;
5211                                         n->newname = $6;
5212                                         $$ = (Node *)n;
5213                                 }
5214                         | ALTER TABLE relation_expr RENAME opt_column name TO name
5215                                 {
5216                                         RenameStmt *n = makeNode(RenameStmt);
5217                                         n->renameType = OBJECT_COLUMN;
5218                                         n->relation = $3;
5219                                         n->subname = $6;
5220                                         n->newname = $8;
5221                                         $$ = (Node *)n;
5222                                 }
5223                         | ALTER TRIGGER name ON relation_expr RENAME TO name
5224                                 {
5225                                         RenameStmt *n = makeNode(RenameStmt);
5226                                         n->renameType = OBJECT_TRIGGER;
5227                                         n->relation = $5;
5228                                         n->subname = $3;
5229                                         n->newname = $8;
5230                                         $$ = (Node *)n;
5231                                 }
5232                         | ALTER ROLE RoleId RENAME TO RoleId
5233                                 {
5234                                         RenameStmt *n = makeNode(RenameStmt);
5235                                         n->renameType = OBJECT_ROLE;
5236                                         n->subname = $3;
5237                                         n->newname = $6;
5238                                         $$ = (Node *)n;
5239                                 }
5240                         | ALTER USER RoleId RENAME TO RoleId
5241                                 {
5242                                         RenameStmt *n = makeNode(RenameStmt);
5243                                         n->renameType = OBJECT_ROLE;
5244                                         n->subname = $3;
5245                                         n->newname = $6;
5246                                         $$ = (Node *)n;
5247                                 }
5248                         | ALTER TABLESPACE name RENAME TO name
5249                                 {
5250                                         RenameStmt *n = makeNode(RenameStmt);
5251                                         n->renameType = OBJECT_TABLESPACE;
5252                                         n->subname = $3;
5253                                         n->newname = $6;
5254                                         $$ = (Node *)n;
5255                                 }
5256                         | ALTER TEXT_P SEARCH PARSER any_name RENAME TO name
5257                                 {
5258                                         RenameStmt *n = makeNode(RenameStmt);
5259                                         n->renameType = OBJECT_TSPARSER;
5260                                         n->object = $5;
5261                                         n->newname = $8;
5262                                         $$ = (Node *)n;
5263                                 }
5264                         | ALTER TEXT_P SEARCH DICTIONARY any_name RENAME TO name
5265                                 {
5266                                         RenameStmt *n = makeNode(RenameStmt);
5267                                         n->renameType = OBJECT_TSDICTIONARY;
5268                                         n->object = $5;
5269                                         n->newname = $8;
5270                                         $$ = (Node *)n;
5271                                 }
5272                         | ALTER TEXT_P SEARCH TEMPLATE any_name RENAME TO name
5273                                 {
5274                                         RenameStmt *n = makeNode(RenameStmt);
5275                                         n->renameType = OBJECT_TSTEMPLATE;
5276                                         n->object = $5;
5277                                         n->newname = $8;
5278                                         $$ = (Node *)n;
5279                                 }
5280                         | ALTER TEXT_P SEARCH CONFIGURATION any_name RENAME TO name
5281                                 {
5282                                         RenameStmt *n = makeNode(RenameStmt);
5283                                         n->renameType = OBJECT_TSCONFIGURATION;
5284                                         n->object = $5;
5285                                         n->newname = $8;
5286                                         $$ = (Node *)n;
5287                                 }
5288                         | ALTER TYPE_P any_name RENAME TO name
5289                                 {
5290                                         RenameStmt *n = makeNode(RenameStmt);
5291                                         n->renameType = OBJECT_TYPE;
5292                                         n->object = $3;
5293                                         n->newname = $6;
5294                                         $$ = (Node *)n;
5295                                 }
5296                 ;
5297
5298 opt_column: COLUMN                                                                      { $$ = COLUMN; }
5299                         | /*EMPTY*/                                                             { $$ = 0; }
5300                 ;
5301
5302 opt_set_data: SET DATA_P                                                                        { $$ = 1; }
5303                         | /*EMPTY*/                                                             { $$ = 0; }
5304                 ;
5305
5306 /*****************************************************************************
5307  *
5308  * ALTER THING name SET SCHEMA name
5309  *
5310  *****************************************************************************/
5311
5312 AlterObjectSchemaStmt:
5313                         ALTER AGGREGATE func_name aggr_args SET SCHEMA name
5314                                 {
5315                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5316                                         n->objectType = OBJECT_AGGREGATE;
5317                                         n->object = $3;
5318                                         n->objarg = $4;
5319                                         n->newschema = $7;
5320                                         $$ = (Node *)n;
5321                                 }
5322                         | ALTER DOMAIN_P any_name SET SCHEMA name
5323                                 {
5324                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5325                                         n->objectType = OBJECT_DOMAIN;
5326                                         n->object = $3;
5327                                         n->newschema = $6;
5328                                         $$ = (Node *)n;
5329                                 }
5330                         | ALTER FUNCTION function_with_argtypes SET SCHEMA name
5331                                 {
5332                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5333                                         n->objectType = OBJECT_FUNCTION;
5334                                         n->object = $3->funcname;
5335                                         n->objarg = $3->funcargs;
5336                                         n->newschema = $6;
5337                                         $$ = (Node *)n;
5338                                 }
5339                         | ALTER TABLE relation_expr SET SCHEMA name
5340                                 {
5341                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5342                                         n->objectType = OBJECT_TABLE;
5343                                         n->relation = $3;
5344                                         n->newschema = $6;
5345                                         $$ = (Node *)n;
5346                                 }
5347                         | ALTER SEQUENCE relation_expr SET SCHEMA name
5348                                 {
5349                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5350                                         n->objectType = OBJECT_SEQUENCE;
5351                                         n->relation = $3;
5352                                         n->newschema = $6;
5353                                         $$ = (Node *)n;
5354                                 }
5355                         | ALTER VIEW relation_expr SET SCHEMA name
5356                                 {
5357                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5358                                         n->objectType = OBJECT_VIEW;
5359                                         n->relation = $3;
5360                                         n->newschema = $6;
5361                                         $$ = (Node *)n;
5362                                 }
5363                         | ALTER TYPE_P any_name SET SCHEMA name
5364                                 {
5365                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
5366                                         n->objectType = OBJECT_TYPE;
5367                                         n->object = $3;
5368                                         n->newschema = $6;
5369                                         $$ = (Node *)n;
5370                                 }
5371                 ;
5372
5373 /*****************************************************************************
5374  *
5375  * ALTER THING name OWNER TO newname
5376  *
5377  *****************************************************************************/
5378
5379 AlterOwnerStmt: ALTER AGGREGATE func_name aggr_args OWNER TO RoleId
5380                                 {
5381                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5382                                         n->objectType = OBJECT_AGGREGATE;
5383                                         n->object = $3;
5384                                         n->objarg = $4;
5385                                         n->newowner = $7;
5386                                         $$ = (Node *)n;
5387                                 }
5388                         | ALTER CONVERSION_P any_name OWNER TO RoleId
5389                                 {
5390                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5391                                         n->objectType = OBJECT_CONVERSION;
5392                                         n->object = $3;
5393                                         n->newowner = $6;
5394                                         $$ = (Node *)n;
5395                                 }
5396                         | ALTER DATABASE database_name OWNER TO RoleId
5397                                 {
5398                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5399                                         n->objectType = OBJECT_DATABASE;
5400                                         n->object = list_make1(makeString($3));
5401                                         n->newowner = $6;
5402                                         $$ = (Node *)n;
5403                                 }
5404                         | ALTER DOMAIN_P any_name OWNER TO RoleId
5405                                 {
5406                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5407                                         n->objectType = OBJECT_DOMAIN;
5408                                         n->object = $3;
5409                                         n->newowner = $6;
5410                                         $$ = (Node *)n;
5411                                 }
5412                         | ALTER FUNCTION function_with_argtypes OWNER TO RoleId
5413                                 {
5414                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5415                                         n->objectType = OBJECT_FUNCTION;
5416                                         n->object = $3->funcname;
5417                                         n->objarg = $3->funcargs;
5418                                         n->newowner = $6;
5419                                         $$ = (Node *)n;
5420                                 }
5421                         | ALTER opt_procedural LANGUAGE name OWNER TO RoleId
5422                                 {
5423                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5424                                         n->objectType = OBJECT_LANGUAGE;
5425                                         n->object = list_make1(makeString($4));
5426                                         n->newowner = $7;
5427                                         $$ = (Node *)n;
5428                                 }
5429                         | ALTER OPERATOR any_operator oper_argtypes OWNER TO RoleId
5430                                 {
5431                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5432                                         n->objectType = OBJECT_OPERATOR;
5433                                         n->object = $3;
5434                                         n->objarg = $4;
5435                                         n->newowner = $7;
5436                                         $$ = (Node *)n;
5437                                 }
5438                         | ALTER OPERATOR CLASS any_name USING access_method OWNER TO RoleId
5439                                 {
5440                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5441                                         n->objectType = OBJECT_OPCLASS;
5442                                         n->object = $4;
5443                                         n->addname = $6;
5444                                         n->newowner = $9;
5445                                         $$ = (Node *)n;
5446                                 }
5447                         | ALTER OPERATOR FAMILY any_name USING access_method OWNER TO RoleId
5448                                 {
5449                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5450                                         n->objectType = OBJECT_OPFAMILY;
5451                                         n->object = $4;
5452                                         n->addname = $6;
5453                                         n->newowner = $9;
5454                                         $$ = (Node *)n;
5455                                 }
5456                         | ALTER SCHEMA name OWNER TO RoleId
5457                                 {
5458                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5459                                         n->objectType = OBJECT_SCHEMA;
5460                                         n->object = list_make1(makeString($3));
5461                                         n->newowner = $6;
5462                                         $$ = (Node *)n;
5463                                 }
5464                         | ALTER TYPE_P any_name OWNER TO RoleId
5465                                 {
5466                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5467                                         n->objectType = OBJECT_TYPE;
5468                                         n->object = $3;
5469                                         n->newowner = $6;
5470                                         $$ = (Node *)n;
5471                                 }
5472                         | ALTER TABLESPACE name OWNER TO RoleId
5473                                 {
5474                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5475                                         n->objectType = OBJECT_TABLESPACE;
5476                                         n->object = list_make1(makeString($3));
5477                                         n->newowner = $6;
5478                                         $$ = (Node *)n;
5479                                 }
5480                         | ALTER TEXT_P SEARCH DICTIONARY any_name OWNER TO RoleId
5481                                 {
5482                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5483                                         n->objectType = OBJECT_TSDICTIONARY;
5484                                         n->object = $5;
5485                                         n->newowner = $8;
5486                                         $$ = (Node *)n;
5487                                 }
5488                         | ALTER TEXT_P SEARCH CONFIGURATION any_name OWNER TO RoleId
5489                                 {
5490                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5491                                         n->objectType = OBJECT_TSCONFIGURATION;
5492                                         n->object = $5;
5493                                         n->newowner = $8;
5494                                         $$ = (Node *)n;
5495                                 }
5496                         | ALTER FOREIGN DATA_P WRAPPER name OWNER TO RoleId
5497                                 {
5498                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5499                                         n->objectType = OBJECT_FDW;
5500                                         n->object = list_make1(makeString($5));
5501                                         n->newowner = $8;
5502                                         $$ = (Node *)n;
5503                                 }
5504                         | ALTER SERVER name OWNER TO RoleId
5505                                 {
5506                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5507                                         n->objectType = OBJECT_FOREIGN_SERVER;
5508                                         n->object = list_make1(makeString($3));
5509                                         n->newowner = $6;
5510                                         $$ = (Node *)n;
5511                                 }
5512                 ;
5513
5514
5515 /*****************************************************************************
5516  *
5517  *              QUERY:  Define Rewrite Rule
5518  *
5519  *****************************************************************************/
5520
5521 RuleStmt:       CREATE opt_or_replace RULE name AS
5522                         { QueryIsRule=TRUE; }
5523                         ON event TO qualified_name where_clause
5524                         DO opt_instead RuleActionList
5525                                 {
5526                                         RuleStmt *n = makeNode(RuleStmt);
5527                                         n->replace = $2;
5528                                         n->relation = $10;
5529                                         n->rulename = $4;
5530                                         n->whereClause = $11;
5531                                         n->event = $8;
5532                                         n->instead = $13;
5533                                         n->actions = $14;
5534                                         $$ = (Node *)n;
5535                                         QueryIsRule=FALSE;
5536                                 }
5537                 ;
5538
5539 RuleActionList:
5540                         NOTHING                                                                 { $$ = NIL; }
5541                         | RuleActionStmt                                                { $$ = list_make1($1); }
5542                         | '(' RuleActionMulti ')'                               { $$ = $2; }
5543                 ;
5544
5545 /* the thrashing around here is to discard "empty" statements... */
5546 RuleActionMulti:
5547                         RuleActionMulti ';' RuleActionStmtOrEmpty
5548                                 { if ($3 != NULL)
5549                                         $$ = lappend($1, $3);
5550                                   else
5551                                         $$ = $1;
5552                                 }
5553                         | RuleActionStmtOrEmpty
5554                                 { if ($1 != NULL)
5555                                         $$ = list_make1($1);
5556                                   else
5557                                         $$ = NIL;
5558                                 }
5559                 ;
5560
5561 RuleActionStmt:
5562                         SelectStmt
5563                         | InsertStmt
5564                         | UpdateStmt
5565                         | DeleteStmt
5566                         | NotifyStmt
5567                 ;
5568
5569 RuleActionStmtOrEmpty:
5570                         RuleActionStmt                                                  { $$ = $1; }
5571                         |       /*EMPTY*/                                                       { $$ = NULL; }
5572                 ;
5573
5574 event:          SELECT                                                                  { $$ = CMD_SELECT; }
5575                         | UPDATE                                                                { $$ = CMD_UPDATE; }
5576                         | DELETE_P                                                              { $$ = CMD_DELETE; }
5577                         | INSERT                                                                { $$ = CMD_INSERT; }
5578                  ;
5579
5580 opt_instead:
5581                         INSTEAD                                                                 { $$ = TRUE; }
5582                         | ALSO                                                                  { $$ = FALSE; }
5583                         | /*EMPTY*/                                                             { $$ = FALSE; }
5584                 ;
5585
5586
5587 DropRuleStmt:
5588                         DROP RULE name ON qualified_name opt_drop_behavior
5589                                 {
5590                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
5591                                         n->relation = $5;
5592                                         n->property = $3;
5593                                         n->behavior = $6;
5594                                         n->removeType = OBJECT_RULE;
5595                                         n->missing_ok = false;
5596                                         $$ = (Node *) n;
5597                                 }
5598                         | DROP RULE IF_P EXISTS name ON qualified_name opt_drop_behavior
5599                                 {
5600                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
5601                                         n->relation = $7;
5602                                         n->property = $5;
5603                                         n->behavior = $8;
5604                                         n->removeType = OBJECT_RULE;
5605                                         n->missing_ok = true;
5606                                         $$ = (Node *) n;
5607                                 }
5608                 ;
5609
5610
5611 /*****************************************************************************
5612  *
5613  *              QUERY:
5614  *                              NOTIFY <identifier> can appear both in rule bodies and
5615  *                              as a query-level command
5616  *
5617  *****************************************************************************/
5618
5619 NotifyStmt: NOTIFY ColId
5620                                 {
5621                                         NotifyStmt *n = makeNode(NotifyStmt);
5622                                         n->conditionname = $2;
5623                                         $$ = (Node *)n;
5624                                 }
5625                 ;
5626
5627 ListenStmt: LISTEN ColId
5628                                 {
5629                                         ListenStmt *n = makeNode(ListenStmt);
5630                                         n->conditionname = $2;
5631                                         $$ = (Node *)n;
5632                                 }
5633                 ;
5634
5635 UnlistenStmt:
5636                         UNLISTEN ColId
5637                                 {
5638                                         UnlistenStmt *n = makeNode(UnlistenStmt);
5639                                         n->conditionname = $2;
5640                                         $$ = (Node *)n;
5641                                 }
5642                         | UNLISTEN '*'
5643                                 {
5644                                         UnlistenStmt *n = makeNode(UnlistenStmt);
5645                                         n->conditionname = NULL;
5646                                         $$ = (Node *)n;
5647                                 }
5648                 ;
5649
5650
5651 /*****************************************************************************
5652  *
5653  *              Transactions:
5654  *
5655  *              BEGIN / COMMIT / ROLLBACK
5656  *              (also older versions END / ABORT)
5657  *
5658  *****************************************************************************/
5659
5660 TransactionStmt:
5661                         ABORT_P opt_transaction
5662                                 {
5663                                         TransactionStmt *n = makeNode(TransactionStmt);
5664                                         n->kind = TRANS_STMT_ROLLBACK;
5665                                         n->options = NIL;
5666                                         $$ = (Node *)n;
5667                                 }
5668                         | BEGIN_P opt_transaction transaction_mode_list_or_empty
5669                                 {
5670                                         TransactionStmt *n = makeNode(TransactionStmt);
5671                                         n->kind = TRANS_STMT_BEGIN;
5672                                         n->options = $3;
5673                                         $$ = (Node *)n;
5674                                 }
5675                         | START TRANSACTION transaction_mode_list_or_empty
5676                                 {
5677                                         TransactionStmt *n = makeNode(TransactionStmt);
5678                                         n->kind = TRANS_STMT_START;
5679                                         n->options = $3;
5680                                         $$ = (Node *)n;
5681                                 }
5682                         | COMMIT opt_transaction
5683                                 {
5684                                         TransactionStmt *n = makeNode(TransactionStmt);
5685                                         n->kind = TRANS_STMT_COMMIT;
5686                                         n->options = NIL;
5687                                         $$ = (Node *)n;
5688                                 }
5689                         | END_P opt_transaction
5690                                 {
5691                                         TransactionStmt *n = makeNode(TransactionStmt);
5692                                         n->kind = TRANS_STMT_COMMIT;
5693                                         n->options = NIL;
5694                                         $$ = (Node *)n;
5695                                 }
5696                         | ROLLBACK opt_transaction
5697                                 {
5698                                         TransactionStmt *n = makeNode(TransactionStmt);
5699                                         n->kind = TRANS_STMT_ROLLBACK;
5700                                         n->options = NIL;
5701                                         $$ = (Node *)n;
5702                                 }
5703                         | SAVEPOINT ColId
5704                                 {
5705                                         TransactionStmt *n = makeNode(TransactionStmt);
5706                                         n->kind = TRANS_STMT_SAVEPOINT;
5707                                         n->options = list_make1(makeDefElem("savepoint_name",
5708                                                                                                                 (Node *)makeString($2)));
5709                                         $$ = (Node *)n;
5710                                 }
5711                         | RELEASE SAVEPOINT ColId
5712                                 {
5713                                         TransactionStmt *n = makeNode(TransactionStmt);
5714                                         n->kind = TRANS_STMT_RELEASE;
5715                                         n->options = list_make1(makeDefElem("savepoint_name",
5716                                                                                                                 (Node *)makeString($3)));
5717                                         $$ = (Node *)n;
5718                                 }
5719                         | RELEASE ColId
5720                                 {
5721                                         TransactionStmt *n = makeNode(TransactionStmt);
5722                                         n->kind = TRANS_STMT_RELEASE;
5723                                         n->options = list_make1(makeDefElem("savepoint_name",
5724                                                                                                                 (Node *)makeString($2)));
5725                                         $$ = (Node *)n;
5726                                 }
5727                         | ROLLBACK opt_transaction TO SAVEPOINT ColId
5728                                 {
5729                                         TransactionStmt *n = makeNode(TransactionStmt);
5730                                         n->kind = TRANS_STMT_ROLLBACK_TO;
5731                                         n->options = list_make1(makeDefElem("savepoint_name",
5732                                                                                                                 (Node *)makeString($5)));
5733                                         $$ = (Node *)n;
5734                                 }
5735                         | ROLLBACK opt_transaction TO ColId
5736                                 {
5737                                         TransactionStmt *n = makeNode(TransactionStmt);
5738                                         n->kind = TRANS_STMT_ROLLBACK_TO;
5739                                         n->options = list_make1(makeDefElem("savepoint_name",
5740                                                                                                                 (Node *)makeString($4)));
5741                                         $$ = (Node *)n;
5742                                 }
5743                         | PREPARE TRANSACTION Sconst
5744                                 {
5745                                         TransactionStmt *n = makeNode(TransactionStmt);
5746                                         n->kind = TRANS_STMT_PREPARE;
5747                                         n->gid = $3;
5748                                         $$ = (Node *)n;
5749                                 }
5750                         | COMMIT PREPARED Sconst
5751                                 {
5752                                         TransactionStmt *n = makeNode(TransactionStmt);
5753                                         n->kind = TRANS_STMT_COMMIT_PREPARED;
5754                                         n->gid = $3;
5755                                         $$ = (Node *)n;
5756                                 }
5757                         | ROLLBACK PREPARED Sconst
5758                                 {
5759                                         TransactionStmt *n = makeNode(TransactionStmt);
5760                                         n->kind = TRANS_STMT_ROLLBACK_PREPARED;
5761                                         n->gid = $3;
5762                                         $$ = (Node *)n;
5763                                 }
5764                 ;
5765
5766 opt_transaction:        WORK                                                    {}
5767                         | TRANSACTION                                                   {}
5768                         | /*EMPTY*/                                                             {}
5769                 ;
5770
5771 transaction_mode_item:
5772                         ISOLATION LEVEL iso_level
5773                                         { $$ = makeDefElem("transaction_isolation",
5774                                                                            makeStringConst($3, @3)); }
5775                         | READ ONLY
5776                                         { $$ = makeDefElem("transaction_read_only",
5777                                                                            makeIntConst(TRUE, @1)); }
5778                         | READ WRITE
5779                                         { $$ = makeDefElem("transaction_read_only",
5780                                                                            makeIntConst(FALSE, @1)); }
5781                 ;
5782
5783 /* Syntax with commas is SQL-spec, without commas is Postgres historical */
5784 transaction_mode_list:
5785                         transaction_mode_item
5786                                         { $$ = list_make1($1); }
5787                         | transaction_mode_list ',' transaction_mode_item
5788                                         { $$ = lappend($1, $3); }
5789                         | transaction_mode_list transaction_mode_item
5790                                         { $$ = lappend($1, $2); }
5791                 ;
5792
5793 transaction_mode_list_or_empty:
5794                         transaction_mode_list
5795                         | /* EMPTY */
5796                                         { $$ = NIL; }
5797                 ;
5798
5799
5800 /*****************************************************************************
5801  *
5802  *      QUERY:
5803  *              CREATE [ OR REPLACE ] [ TEMP ] VIEW <viewname> '('target-list ')'
5804  *                      AS <query> [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
5805  *
5806  *****************************************************************************/
5807
5808 ViewStmt: CREATE OptTemp VIEW qualified_name opt_column_list
5809                                 AS SelectStmt opt_check_option
5810                                 {
5811                                         ViewStmt *n = makeNode(ViewStmt);
5812                                         n->view = $4;
5813                                         n->view->istemp = $2;
5814                                         n->aliases = $5;
5815                                         n->query = $7;
5816                                         n->replace = false;
5817                                         $$ = (Node *) n;
5818                                 }
5819                 | CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list
5820                                 AS SelectStmt opt_check_option
5821                                 {
5822                                         ViewStmt *n = makeNode(ViewStmt);
5823                                         n->view = $6;
5824                                         n->view->istemp = $4;
5825                                         n->aliases = $7;
5826                                         n->query = $9;
5827                                         n->replace = true;
5828                                         $$ = (Node *) n;
5829                                 }
5830                 ;
5831
5832 opt_check_option:
5833                 WITH CHECK OPTION
5834                                 {
5835                                         ereport(ERROR,
5836                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5837                                                          errmsg("WITH CHECK OPTION is not implemented")));
5838                                 }
5839                 | WITH CASCADED CHECK OPTION
5840                                 {
5841                                         ereport(ERROR,
5842                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5843                                                          errmsg("WITH CHECK OPTION is not implemented")));
5844                                 }
5845                 | WITH LOCAL CHECK OPTION
5846                                 {
5847                                         ereport(ERROR,
5848                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5849                                                          errmsg("WITH CHECK OPTION is not implemented")));
5850                                 }
5851                 | /* EMPTY */                                                   { $$ = NIL; }
5852                 ;
5853
5854 /*****************************************************************************
5855  *
5856  *              QUERY:
5857  *                              LOAD "filename"
5858  *
5859  *****************************************************************************/
5860
5861 LoadStmt:       LOAD file_name
5862                                 {
5863                                         LoadStmt *n = makeNode(LoadStmt);
5864                                         n->filename = $2;
5865                                         $$ = (Node *)n;
5866                                 }
5867                 ;
5868
5869
5870 /*****************************************************************************
5871  *
5872  *              CREATE DATABASE
5873  *
5874  *****************************************************************************/
5875
5876 CreatedbStmt:
5877                         CREATE DATABASE database_name opt_with createdb_opt_list
5878                                 {
5879                                         CreatedbStmt *n = makeNode(CreatedbStmt);
5880                                         n->dbname = $3;
5881                                         n->options = $5;
5882                                         $$ = (Node *)n;
5883                                 }
5884                 ;
5885
5886 createdb_opt_list:
5887                         createdb_opt_list createdb_opt_item             { $$ = lappend($1, $2); }
5888                         | /* EMPTY */                                                   { $$ = NIL; }
5889                 ;
5890
5891 createdb_opt_item:
5892                         TABLESPACE opt_equal name
5893                                 {
5894                                         $$ = makeDefElem("tablespace", (Node *)makeString($3));
5895                                 }
5896                         | TABLESPACE opt_equal DEFAULT
5897                                 {
5898                                         $$ = makeDefElem("tablespace", NULL);
5899                                 }
5900                         | LOCATION opt_equal Sconst
5901                                 {
5902                                         $$ = makeDefElem("location", (Node *)makeString($3));
5903                                 }
5904                         | LOCATION opt_equal DEFAULT
5905                                 {
5906                                         $$ = makeDefElem("location", NULL);
5907                                 }
5908                         | TEMPLATE opt_equal name
5909                                 {
5910                                         $$ = makeDefElem("template", (Node *)makeString($3));
5911                                 }
5912                         | TEMPLATE opt_equal DEFAULT
5913                                 {
5914                                         $$ = makeDefElem("template", NULL);
5915                                 }
5916                         | ENCODING opt_equal Sconst
5917                                 {
5918                                         $$ = makeDefElem("encoding", (Node *)makeString($3));
5919                                 }
5920                         | ENCODING opt_equal Iconst
5921                                 {
5922                                         $$ = makeDefElem("encoding", (Node *)makeInteger($3));
5923                                 }
5924                         | ENCODING opt_equal DEFAULT
5925                                 {
5926                                         $$ = makeDefElem("encoding", NULL);
5927                                 }
5928                         | COLLATE opt_equal Sconst
5929                                 {
5930                                         $$ = makeDefElem("collate", (Node *)makeString($3));
5931                                 }
5932                         | COLLATE opt_equal DEFAULT
5933                                 {
5934                                         $$ = makeDefElem("collate", NULL);
5935                                 }
5936                         | CTYPE opt_equal Sconst
5937                                 {
5938                                         $$ = makeDefElem("ctype", (Node *)makeString($3));
5939                                 }
5940                         | CTYPE opt_equal DEFAULT
5941                                 {
5942                                         $$ = makeDefElem("ctype", NULL);
5943                                 }
5944                         | CONNECTION LIMIT opt_equal SignedIconst
5945                                 {
5946                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($4));
5947                                 }
5948                         | OWNER opt_equal name
5949                                 {
5950                                         $$ = makeDefElem("owner", (Node *)makeString($3));
5951                                 }
5952                         | OWNER opt_equal DEFAULT
5953                                 {
5954                                         $$ = makeDefElem("owner", NULL);
5955                                 }
5956                 ;
5957
5958 /*
5959  *      Though the equals sign doesn't match other WITH options, pg_dump uses
5960  *      equals for backward compatibility, and it doesn't seem worth removing it.
5961  */
5962 opt_equal:      '='                                                                             {}
5963                         | /*EMPTY*/                                                             {}
5964                 ;
5965
5966
5967 /*****************************************************************************
5968  *
5969  *              ALTER DATABASE
5970  *
5971  *****************************************************************************/
5972
5973 AlterDatabaseStmt:
5974                         ALTER DATABASE database_name opt_with alterdb_opt_list
5975                                  {
5976                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
5977                                         n->dbname = $3;
5978                                         n->options = $5;
5979                                         $$ = (Node *)n;
5980                                  }
5981                         | ALTER DATABASE database_name SET TABLESPACE name
5982                                  {
5983                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
5984                                         n->dbname = $3;
5985                                         n->options = list_make1(makeDefElem("tablespace",
5986                                                                                                         (Node *)makeString($6)));
5987                                         $$ = (Node *)n;
5988                                  }
5989                 ;
5990
5991 AlterDatabaseSetStmt:
5992                         ALTER DATABASE database_name SetResetClause
5993                                 {
5994                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
5995                                         n->dbname = $3;
5996                                         n->setstmt = $4;
5997                                         $$ = (Node *)n;
5998                                 }
5999                 ;
6000
6001
6002 alterdb_opt_list:
6003                         alterdb_opt_list alterdb_opt_item               { $$ = lappend($1, $2); }
6004                         | /* EMPTY */                                                   { $$ = NIL; }
6005                 ;
6006
6007 alterdb_opt_item:
6008                         CONNECTION LIMIT opt_equal SignedIconst
6009                                 {
6010                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($4));
6011                                 }
6012                 ;
6013
6014
6015 /*****************************************************************************
6016  *
6017  *              DROP DATABASE [ IF EXISTS ]
6018  *
6019  * This is implicitly CASCADE, no need for drop behavior
6020  *****************************************************************************/
6021
6022 DropdbStmt: DROP DATABASE database_name
6023                                 {
6024                                         DropdbStmt *n = makeNode(DropdbStmt);
6025                                         n->dbname = $3;
6026                                         n->missing_ok = FALSE;
6027                                         $$ = (Node *)n;
6028                                 }
6029                         | DROP DATABASE IF_P EXISTS database_name
6030                                 {
6031                                         DropdbStmt *n = makeNode(DropdbStmt);
6032                                         n->dbname = $5;
6033                                         n->missing_ok = TRUE;
6034                                         $$ = (Node *)n;
6035                                 }
6036                 ;
6037
6038
6039 /*****************************************************************************
6040  *
6041  * Manipulate a domain
6042  *
6043  *****************************************************************************/
6044
6045 CreateDomainStmt:
6046                         CREATE DOMAIN_P any_name opt_as Typename ColQualList
6047                                 {
6048                                         CreateDomainStmt *n = makeNode(CreateDomainStmt);
6049                                         n->domainname = $3;
6050                                         n->typename = $5;
6051                                         n->constraints = $6;
6052                                         $$ = (Node *)n;
6053                                 }
6054                 ;
6055
6056 AlterDomainStmt:
6057                         /* ALTER DOMAIN <domain> {SET DEFAULT <expr>|DROP DEFAULT} */
6058                         ALTER DOMAIN_P any_name alter_column_default
6059                                 {
6060                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6061                                         n->subtype = 'T';
6062                                         n->typename = $3;
6063                                         n->def = $4;
6064                                         $$ = (Node *)n;
6065                                 }
6066                         /* ALTER DOMAIN <domain> DROP NOT NULL */
6067                         | ALTER DOMAIN_P any_name DROP NOT NULL_P
6068                                 {
6069                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6070                                         n->subtype = 'N';
6071                                         n->typename = $3;
6072                                         $$ = (Node *)n;
6073                                 }
6074                         /* ALTER DOMAIN <domain> SET NOT NULL */
6075                         | ALTER DOMAIN_P any_name SET NOT NULL_P
6076                                 {
6077                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6078                                         n->subtype = 'O';
6079                                         n->typename = $3;
6080                                         $$ = (Node *)n;
6081                                 }
6082                         /* ALTER DOMAIN <domain> ADD CONSTRAINT ... */
6083                         | ALTER DOMAIN_P any_name ADD_P TableConstraint
6084                                 {
6085                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6086                                         n->subtype = 'C';
6087                                         n->typename = $3;
6088                                         n->def = $5;
6089                                         $$ = (Node *)n;
6090                                 }
6091                         /* ALTER DOMAIN <domain> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
6092                         | ALTER DOMAIN_P any_name DROP CONSTRAINT name opt_drop_behavior
6093                                 {
6094                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
6095                                         n->subtype = 'X';
6096                                         n->typename = $3;
6097                                         n->name = $6;
6098                                         n->behavior = $7;
6099                                         $$ = (Node *)n;
6100                                 }
6101                         ;
6102
6103 opt_as:         AS                                                                              {}
6104                         | /* EMPTY */                                                   {}
6105                 ;
6106
6107
6108 /*****************************************************************************
6109  *
6110  * Manipulate a text search dictionary or configuration
6111  *
6112  *****************************************************************************/
6113
6114 AlterTSDictionaryStmt:
6115                         ALTER TEXT_P SEARCH DICTIONARY any_name definition
6116                                 {
6117                                         AlterTSDictionaryStmt *n = makeNode(AlterTSDictionaryStmt);
6118                                         n->dictname = $5;
6119                                         n->options = $6;
6120                                         $$ = (Node *)n;
6121                                 }
6122                 ;
6123
6124 AlterTSConfigurationStmt:
6125                         ALTER TEXT_P SEARCH CONFIGURATION any_name ADD_P MAPPING FOR name_list WITH any_name_list
6126                                 {
6127                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6128                                         n->cfgname = $5;
6129                                         n->tokentype = $9;
6130                                         n->dicts = $11;
6131                                         n->override = false;
6132                                         n->replace = false;
6133                                         $$ = (Node*)n;
6134                                 }
6135                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list WITH any_name_list
6136                                 {
6137                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6138                                         n->cfgname = $5;
6139                                         n->tokentype = $9;
6140                                         n->dicts = $11;
6141                                         n->override = true;
6142                                         n->replace = false;
6143                                         $$ = (Node*)n;
6144                                 }
6145                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING REPLACE any_name WITH any_name
6146                                 {
6147                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6148                                         n->cfgname = $5;
6149                                         n->tokentype = NIL;
6150                                         n->dicts = list_make2($9,$11);
6151                                         n->override = false;
6152                                         n->replace = true;
6153                                         $$ = (Node*)n;
6154                                 }
6155                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list REPLACE any_name WITH any_name
6156                                 {
6157                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6158                                         n->cfgname = $5;
6159                                         n->tokentype = $9;
6160                                         n->dicts = list_make2($11,$13);
6161                                         n->override = false;
6162                                         n->replace = true;
6163                                         $$ = (Node*)n;
6164                                 }
6165                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING FOR name_list
6166                                 {
6167                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6168                                         n->cfgname = $5;
6169                                         n->tokentype = $9;
6170                                         n->missing_ok = false;
6171                                         $$ = (Node*)n;
6172                                 }
6173                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING IF_P EXISTS FOR name_list
6174                                 {
6175                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
6176                                         n->cfgname = $5;
6177                                         n->tokentype = $11;
6178                                         n->missing_ok = true;
6179                                         $$ = (Node*)n;
6180                                 }
6181                 ;
6182
6183
6184 /*****************************************************************************
6185  *
6186  * Manipulate a conversion
6187  *
6188  *              CREATE [DEFAULT] CONVERSION <conversion_name>
6189  *              FOR <encoding_name> TO <encoding_name> FROM <func_name>
6190  *
6191  *****************************************************************************/
6192
6193 CreateConversionStmt:
6194                         CREATE opt_default CONVERSION_P any_name FOR Sconst
6195                         TO Sconst FROM any_name
6196                         {
6197                           CreateConversionStmt *n = makeNode(CreateConversionStmt);
6198                           n->conversion_name = $4;
6199                           n->for_encoding_name = $6;
6200                           n->to_encoding_name = $8;
6201                           n->func_name = $10;
6202                           n->def = $2;
6203                           $$ = (Node *)n;
6204                         }
6205                 ;
6206
6207 /*****************************************************************************
6208  *
6209  *              QUERY:
6210  *                              CLUSTER [VERBOSE] <qualified_name> [ USING <index_name> ]
6211  *                              CLUSTER [VERBOSE]
6212  *                              CLUSTER [VERBOSE] <index_name> ON <qualified_name> (for pre-8.3)
6213  *
6214  *****************************************************************************/
6215
6216 ClusterStmt:
6217                         CLUSTER opt_verbose qualified_name cluster_index_specification
6218                                 {
6219                                ClusterStmt *n = makeNode(ClusterStmt);
6220                                    n->relation = $3;
6221                                    n->indexname = $4;
6222                                    n->verbose = $2;
6223                                    $$ = (Node*)n;
6224                                 }
6225                         | CLUSTER opt_verbose
6226                             {
6227                                    ClusterStmt *n = makeNode(ClusterStmt);
6228                                    n->relation = NULL;
6229                                    n->indexname = NULL;
6230                                    n->verbose = $2;
6231                                    $$ = (Node*)n;
6232                                 }
6233                         /* kept for pre-8.3 compatibility */
6234                         | CLUSTER opt_verbose index_name ON qualified_name
6235                                 {
6236                                    ClusterStmt *n = makeNode(ClusterStmt);
6237                                    n->relation = $5;
6238                                    n->indexname = $3;
6239                                    n->verbose = $2;
6240                                    $$ = (Node*)n;
6241                                 }
6242                 ;
6243
6244 cluster_index_specification:
6245                         USING index_name                { $$ = $2; }
6246                         | /*EMPTY*/                             { $$ = NULL; }
6247                 ;
6248
6249
6250 /*****************************************************************************
6251  *
6252  *              QUERY:
6253  *                              VACUUM
6254  *                              ANALYZE
6255  *
6256  *****************************************************************************/
6257
6258 VacuumStmt: VACUUM opt_full opt_freeze opt_verbose
6259                                 {
6260                                         VacuumStmt *n = makeNode(VacuumStmt);
6261                                         n->vacuum = true;
6262                                         n->analyze = false;
6263                                         n->full = $2;
6264                                         n->freeze_min_age = $3 ? 0 : -1;
6265                                         n->scan_all = $2 || $3;
6266                                         n->verbose = $4;
6267                                         n->relation = NULL;
6268                                         n->va_cols = NIL;
6269                                         $$ = (Node *)n;
6270                                 }
6271                         | VACUUM opt_full opt_freeze opt_verbose qualified_name
6272                                 {
6273                                         VacuumStmt *n = makeNode(VacuumStmt);
6274                                         n->vacuum = true;
6275                                         n->analyze = false;
6276                                         n->full = $2;
6277                                         n->freeze_min_age = $3 ? 0 : -1;
6278                                         n->scan_all = $2 || $3;
6279                                         n->verbose = $4;
6280                                         n->relation = $5;
6281                                         n->va_cols = NIL;
6282                                         $$ = (Node *)n;
6283                                 }
6284                         | VACUUM opt_full opt_freeze opt_verbose AnalyzeStmt
6285                                 {
6286                                         VacuumStmt *n = (VacuumStmt *) $5;
6287                                         n->vacuum = true;
6288                                         n->full = $2;
6289                                         n->freeze_min_age = $3 ? 0 : -1;
6290                                         n->scan_all = $2 || $3;
6291                                         n->verbose |= $4;
6292                                         $$ = (Node *)n;
6293                                 }
6294                 ;
6295
6296 AnalyzeStmt:
6297                         analyze_keyword opt_verbose
6298                                 {
6299                                         VacuumStmt *n = makeNode(VacuumStmt);
6300                                         n->vacuum = false;
6301                                         n->analyze = true;
6302                                         n->full = false;
6303                                         n->freeze_min_age = -1;
6304                                         n->verbose = $2;
6305                                         n->relation = NULL;
6306                                         n->va_cols = NIL;
6307                                         $$ = (Node *)n;
6308                                 }
6309                         | analyze_keyword opt_verbose qualified_name opt_name_list
6310                                 {
6311                                         VacuumStmt *n = makeNode(VacuumStmt);
6312                                         n->vacuum = false;
6313                                         n->analyze = true;
6314                                         n->full = false;
6315                                         n->freeze_min_age = -1;
6316                                         n->verbose = $2;
6317                                         n->relation = $3;
6318                                         n->va_cols = $4;
6319                                         $$ = (Node *)n;
6320                                 }
6321                 ;
6322
6323 analyze_keyword:
6324                         ANALYZE                                                                 {}
6325                         | ANALYSE /* British */                                 {}
6326                 ;
6327
6328 opt_verbose:
6329                         VERBOSE                                                                 { $$ = TRUE; }
6330                         | /*EMPTY*/                                                             { $$ = FALSE; }
6331                 ;
6332
6333 opt_full:       FULL                                                                    { $$ = TRUE; }
6334                         | /*EMPTY*/                                                             { $$ = FALSE; }
6335                 ;
6336
6337 opt_freeze: FREEZE                                                                      { $$ = TRUE; }
6338                         | /*EMPTY*/                                                             { $$ = FALSE; }
6339                 ;
6340
6341 opt_name_list:
6342                         '(' name_list ')'                                               { $$ = $2; }
6343                         | /*EMPTY*/                                                             { $$ = NIL; }
6344                 ;
6345
6346
6347 /*****************************************************************************
6348  *
6349  *              QUERY:
6350  *                              EXPLAIN [ANALYZE] [VERBOSE] query
6351  *
6352  *****************************************************************************/
6353
6354 ExplainStmt: EXPLAIN opt_analyze opt_verbose ExplainableStmt
6355                                 {
6356                                         ExplainStmt *n = makeNode(ExplainStmt);
6357                                         n->analyze = $2;
6358                                         n->verbose = $3;
6359                                         n->query = $4;
6360                                         $$ = (Node *)n;
6361                                 }
6362                 ;
6363
6364 ExplainableStmt:
6365                         SelectStmt
6366                         | InsertStmt
6367                         | UpdateStmt
6368                         | DeleteStmt
6369                         | DeclareCursorStmt
6370                         | CreateAsStmt
6371                         | ExecuteStmt                                   /* by default all are $$=$1 */
6372                 ;
6373
6374 opt_analyze:
6375                         analyze_keyword                 { $$ = TRUE; }
6376                         | /* EMPTY */                   { $$ = FALSE; }
6377                 ;
6378
6379 /*****************************************************************************
6380  *
6381  *              QUERY:
6382  *                              PREPARE <plan_name> [(args, ...)] AS <query>
6383  *
6384  *****************************************************************************/
6385
6386 PrepareStmt: PREPARE name prep_type_clause AS PreparableStmt
6387                                 {
6388                                         PrepareStmt *n = makeNode(PrepareStmt);
6389                                         n->name = $2;
6390                                         n->argtypes = $3;
6391                                         n->query = $5;
6392                                         $$ = (Node *) n;
6393                                 }
6394                 ;
6395
6396 prep_type_clause: '(' type_list ')'                     { $$ = $2; }
6397                                 | /* EMPTY */                           { $$ = NIL; }
6398                 ;
6399
6400 PreparableStmt:
6401                         SelectStmt
6402                         | InsertStmt
6403                         | UpdateStmt
6404                         | DeleteStmt                                    /* by default all are $$=$1 */
6405                 ;
6406
6407 /*****************************************************************************
6408  *
6409  * EXECUTE <plan_name> [(params, ...)]
6410  * CREATE TABLE <name> AS EXECUTE <plan_name> [(params, ...)]
6411  *
6412  *****************************************************************************/
6413
6414 ExecuteStmt: EXECUTE name execute_param_clause
6415                                 {
6416                                         ExecuteStmt *n = makeNode(ExecuteStmt);
6417                                         n->name = $2;
6418                                         n->params = $3;
6419                                         n->into = NULL;
6420                                         $$ = (Node *) n;
6421                                 }
6422                         | CREATE OptTemp TABLE create_as_target AS
6423                                 EXECUTE name execute_param_clause
6424                                 {
6425                                         ExecuteStmt *n = makeNode(ExecuteStmt);
6426                                         n->name = $7;
6427                                         n->params = $8;
6428                                         $4->rel->istemp = $2;
6429                                         n->into = $4;
6430                                         if ($4->colNames)
6431                                                 ereport(ERROR,
6432                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6433                                                                  errmsg("column name list not allowed in CREATE TABLE / AS EXECUTE")));
6434                                         /* ... because it's not implemented, but it could be */
6435                                         $$ = (Node *) n;
6436                                 }
6437                 ;
6438
6439 execute_param_clause: '(' expr_list ')'                         { $$ = $2; }
6440                                         | /* EMPTY */                                   { $$ = NIL; }
6441                                         ;
6442
6443 /*****************************************************************************
6444  *
6445  *              QUERY:
6446  *                              DEALLOCATE [PREPARE] <plan_name>
6447  *
6448  *****************************************************************************/
6449
6450 DeallocateStmt: DEALLOCATE name
6451                                         {
6452                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6453                                                 n->name = $2;
6454                                                 $$ = (Node *) n;
6455                                         }
6456                                 | DEALLOCATE PREPARE name
6457                                         {
6458                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6459                                                 n->name = $3;
6460                                                 $$ = (Node *) n;
6461                                         }
6462                                 | DEALLOCATE ALL
6463                                         {
6464                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6465                                                 n->name = NULL;
6466                                                 $$ = (Node *) n;
6467                                         }
6468                                 | DEALLOCATE PREPARE ALL
6469                                         {
6470                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6471                                                 n->name = NULL;
6472                                                 $$ = (Node *) n;
6473                                         }
6474                 ;
6475
6476 /*****************************************************************************
6477  *
6478  *              QUERY:
6479  *                              INSERT STATEMENTS
6480  *
6481  *****************************************************************************/
6482
6483 InsertStmt:
6484                         INSERT INTO qualified_name insert_rest returning_clause
6485                                 {
6486                                         $4->relation = $3;
6487                                         $4->returningList = $5;
6488                                         $$ = (Node *) $4;
6489                                 }
6490                 ;
6491
6492 insert_rest:
6493                         SelectStmt
6494                                 {
6495                                         $$ = makeNode(InsertStmt);
6496                                         $$->cols = NIL;
6497                                         $$->selectStmt = $1;
6498                                 }
6499                         | '(' insert_column_list ')' SelectStmt
6500                                 {
6501                                         $$ = makeNode(InsertStmt);
6502                                         $$->cols = $2;
6503                                         $$->selectStmt = $4;
6504                                 }
6505                         | DEFAULT VALUES
6506                                 {
6507                                         $$ = makeNode(InsertStmt);
6508                                         $$->cols = NIL;
6509                                         $$->selectStmt = NULL;
6510                                 }
6511                 ;
6512
6513 insert_column_list:
6514                         insert_column_item
6515                                         { $$ = list_make1($1); }
6516                         | insert_column_list ',' insert_column_item
6517                                         { $$ = lappend($1, $3); }
6518                 ;
6519
6520 insert_column_item:
6521                         ColId opt_indirection
6522                                 {
6523                                         $$ = makeNode(ResTarget);
6524                                         $$->name = $1;
6525                                         $$->indirection = check_indirection($2);
6526                                         $$->val = NULL;
6527                                         $$->location = @1;
6528                                 }
6529                 ;
6530
6531 returning_clause:
6532                         RETURNING target_list           { $$ = $2; }
6533                         | /* EMPTY */                           { $$ = NIL; }
6534                 ;
6535
6536
6537 /*****************************************************************************
6538  *
6539  *              QUERY:
6540  *                              DELETE STATEMENTS
6541  *
6542  *****************************************************************************/
6543
6544 DeleteStmt: DELETE_P FROM relation_expr_opt_alias
6545                         using_clause where_or_current_clause returning_clause
6546                                 {
6547                                         DeleteStmt *n = makeNode(DeleteStmt);
6548                                         n->relation = $3;
6549                                         n->usingClause = $4;
6550                                         n->whereClause = $5;
6551                                         n->returningList = $6;
6552                                         $$ = (Node *)n;
6553                                 }
6554                 ;
6555
6556 using_clause:
6557                         USING from_list                                         { $$ = $2; }
6558                         | /*EMPTY*/                                                             { $$ = NIL; }
6559                 ;
6560
6561 LockStmt:       LOCK_P opt_table qualified_name_list opt_lock opt_nowait
6562                                 {
6563                                         LockStmt *n = makeNode(LockStmt);
6564
6565                                         n->relations = $3;
6566                                         n->mode = $4;
6567                                         n->nowait = $5;
6568                                         $$ = (Node *)n;
6569                                 }
6570                 ;
6571
6572 opt_lock:       IN_P lock_type MODE                     { $$ = $2; }
6573                         | /*EMPTY*/                                             { $$ = AccessExclusiveLock; }
6574                 ;
6575
6576 lock_type:      ACCESS SHARE                                    { $$ = AccessShareLock; }
6577                         | ROW SHARE                                             { $$ = RowShareLock; }
6578                         | ROW EXCLUSIVE                                 { $$ = RowExclusiveLock; }
6579                         | SHARE UPDATE EXCLUSIVE                { $$ = ShareUpdateExclusiveLock; }
6580                         | SHARE                                                 { $$ = ShareLock; }
6581                         | SHARE ROW EXCLUSIVE                   { $$ = ShareRowExclusiveLock; }
6582                         | EXCLUSIVE                                             { $$ = ExclusiveLock; }
6583                         | ACCESS EXCLUSIVE                              { $$ = AccessExclusiveLock; }
6584                 ;
6585
6586 opt_nowait:     NOWAIT                                                  { $$ = TRUE; }
6587                         | /*EMPTY*/                                             { $$ = FALSE; }
6588                 ;
6589
6590
6591 /*****************************************************************************
6592  *
6593  *              QUERY:
6594  *                              UpdateStmt (UPDATE)
6595  *
6596  *****************************************************************************/
6597
6598 UpdateStmt: UPDATE relation_expr_opt_alias
6599                         SET set_clause_list
6600                         from_clause
6601                         where_or_current_clause
6602                         returning_clause
6603                                 {
6604                                         UpdateStmt *n = makeNode(UpdateStmt);
6605                                         n->relation = $2;
6606                                         n->targetList = $4;
6607                                         n->fromClause = $5;
6608                                         n->whereClause = $6;
6609                                         n->returningList = $7;
6610                                         $$ = (Node *)n;
6611                                 }
6612                 ;
6613
6614 set_clause_list:
6615                         set_clause                                                      { $$ = $1; }
6616                         | set_clause_list ',' set_clause        { $$ = list_concat($1,$3); }
6617                 ;
6618
6619 set_clause:
6620                         single_set_clause                                               { $$ = list_make1($1); }
6621                         | multiple_set_clause                                   { $$ = $1; }
6622                 ;
6623
6624 single_set_clause:
6625                         set_target '=' ctext_expr
6626                                 {
6627                                         $$ = $1;
6628                                         $$->val = (Node *) $3;
6629                                 }
6630                 ;
6631
6632 multiple_set_clause:
6633                         '(' set_target_list ')' '=' ctext_row
6634                                 {
6635                                         ListCell *col_cell;
6636                                         ListCell *val_cell;
6637
6638                                         /*
6639                                          * Break the ctext_row apart, merge individual expressions
6640                                          * into the destination ResTargets.  XXX this approach
6641                                          * cannot work for general row expressions as sources.
6642                                          */
6643                                         if (list_length($2) != list_length($5))
6644                                                 ereport(ERROR,
6645                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
6646                                                                  errmsg("number of columns does not match number of values"),
6647                                                                  scanner_errposition(@1)));
6648                                         forboth(col_cell, $2, val_cell, $5)
6649                                         {
6650                                                 ResTarget *res_col = (ResTarget *) lfirst(col_cell);
6651                                                 Node *res_val = (Node *) lfirst(val_cell);
6652
6653                                                 res_col->val = res_val;
6654                                         }
6655
6656                                         $$ = $2;
6657                                 }
6658                 ;
6659
6660 set_target:
6661                         ColId opt_indirection
6662                                 {
6663                                         $$ = makeNode(ResTarget);
6664                                         $$->name = $1;
6665                                         $$->indirection = check_indirection($2);
6666                                         $$->val = NULL; /* upper production sets this */
6667                                         $$->location = @1;
6668                                 }
6669                 ;
6670
6671 set_target_list:
6672                         set_target                                                              { $$ = list_make1($1); }
6673                         | set_target_list ',' set_target                { $$ = lappend($1,$3); }
6674                 ;
6675
6676
6677 /*****************************************************************************
6678  *
6679  *              QUERY:
6680  *                              CURSOR STATEMENTS
6681  *
6682  *****************************************************************************/
6683 DeclareCursorStmt: DECLARE name cursor_options CURSOR opt_hold FOR SelectStmt
6684                                 {
6685                                         DeclareCursorStmt *n = makeNode(DeclareCursorStmt);
6686                                         n->portalname = $2;
6687                                         /* currently we always set FAST_PLAN option */
6688                                         n->options = $3 | $5 | CURSOR_OPT_FAST_PLAN;
6689                                         n->query = $7;
6690                                         $$ = (Node *)n;
6691                                 }
6692                 ;
6693
6694 cursor_options: /*EMPTY*/                                       { $$ = 0; }
6695                         | cursor_options NO SCROLL              { $$ = $1 | CURSOR_OPT_NO_SCROLL; }
6696                         | cursor_options SCROLL                 { $$ = $1 | CURSOR_OPT_SCROLL; }
6697                         | cursor_options BINARY                 { $$ = $1 | CURSOR_OPT_BINARY; }
6698                         | cursor_options INSENSITIVE    { $$ = $1 | CURSOR_OPT_INSENSITIVE; }
6699                 ;
6700
6701 opt_hold: /* EMPTY */                                           { $$ = 0; }
6702                         | WITH HOLD                                             { $$ = CURSOR_OPT_HOLD; }
6703                         | WITHOUT HOLD                                  { $$ = 0; }
6704                 ;
6705
6706 /*****************************************************************************
6707  *
6708  *              QUERY:
6709  *                              SELECT STATEMENTS
6710  *
6711  *****************************************************************************/
6712
6713 /* A complete SELECT statement looks like this.
6714  *
6715  * The rule returns either a single SelectStmt node or a tree of them,
6716  * representing a set-operation tree.
6717  *
6718  * There is an ambiguity when a sub-SELECT is within an a_expr and there
6719  * are excess parentheses: do the parentheses belong to the sub-SELECT or
6720  * to the surrounding a_expr?  We don't really care, but yacc wants to know.
6721  * To resolve the ambiguity, we are careful to define the grammar so that
6722  * the decision is staved off as long as possible: as long as we can keep
6723  * absorbing parentheses into the sub-SELECT, we will do so, and only when
6724  * it's no longer possible to do that will we decide that parens belong to
6725  * the expression.      For example, in "SELECT (((SELECT 2)) + 3)" the extra
6726  * parentheses are treated as part of the sub-select.  The necessity of doing
6727  * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)".      Had we
6728  * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
6729  * SELECT viewpoint when we see the UNION.
6730  *
6731  * This approach is implemented by defining a nonterminal select_with_parens,
6732  * which represents a SELECT with at least one outer layer of parentheses,
6733  * and being careful to use select_with_parens, never '(' SelectStmt ')',
6734  * in the expression grammar.  We will then have shift-reduce conflicts
6735  * which we can resolve in favor of always treating '(' <select> ')' as
6736  * a select_with_parens.  To resolve the conflicts, the productions that
6737  * conflict with the select_with_parens productions are manually given
6738  * precedences lower than the precedence of ')', thereby ensuring that we
6739  * shift ')' (and then reduce to select_with_parens) rather than trying to
6740  * reduce the inner <select> nonterminal to something else.  We use UMINUS
6741  * precedence for this, which is a fairly arbitrary choice.
6742  *
6743  * To be able to define select_with_parens itself without ambiguity, we need
6744  * a nonterminal select_no_parens that represents a SELECT structure with no
6745  * outermost parentheses.  This is a little bit tedious, but it works.
6746  *
6747  * In non-expression contexts, we use SelectStmt which can represent a SELECT
6748  * with or without outer parentheses.
6749  */
6750
6751 SelectStmt: select_no_parens                    %prec UMINUS
6752                         | select_with_parens            %prec UMINUS
6753                 ;
6754
6755 select_with_parens:
6756                         '(' select_no_parens ')'                                { $$ = $2; }
6757                         | '(' select_with_parens ')'                    { $$ = $2; }
6758                 ;
6759
6760 /*
6761  * This rule parses the equivalent of the standard's <query expression>.
6762  * The duplicative productions are annoying, but hard to get rid of without
6763  * creating shift/reduce conflicts.
6764  *
6765  *      FOR UPDATE/SHARE may be before or after LIMIT/OFFSET.
6766  *      In <=7.2.X, LIMIT/OFFSET had to be after FOR UPDATE
6767  *      We now support both orderings, but prefer LIMIT/OFFSET before FOR UPDATE/SHARE
6768  *      2002-08-28 bjm
6769  */
6770 select_no_parens:
6771                         simple_select                                           { $$ = $1; }
6772                         | select_clause sort_clause
6773                                 {
6774                                         insertSelectOptions((SelectStmt *) $1, $2, NIL,
6775                                                                                 NULL, NULL, NULL);
6776                                         $$ = $1;
6777                                 }
6778                         | select_clause opt_sort_clause for_locking_clause opt_select_limit
6779                                 {
6780                                         insertSelectOptions((SelectStmt *) $1, $2, $3,
6781                                                                                 list_nth($4, 0), list_nth($4, 1),
6782                                                                                 NULL);
6783                                         $$ = $1;
6784                                 }
6785                         | select_clause opt_sort_clause select_limit opt_for_locking_clause
6786                                 {
6787                                         insertSelectOptions((SelectStmt *) $1, $2, $4,
6788                                                                                 list_nth($3, 0), list_nth($3, 1),
6789                                                                                 NULL);
6790                                         $$ = $1;
6791                                 }
6792                         | with_clause simple_select
6793                                 {
6794                                         insertSelectOptions((SelectStmt *) $2, NULL, NIL,
6795                                                                                 NULL, NULL,
6796                                                                                 $1);
6797                                         $$ = $2;
6798                                 }
6799                         | with_clause select_clause sort_clause
6800                                 {
6801                                         insertSelectOptions((SelectStmt *) $2, $3, NIL,
6802                                                                                 NULL, NULL,
6803                                                                                 $1);
6804                                         $$ = $2;
6805                                 }
6806                         | with_clause select_clause opt_sort_clause for_locking_clause opt_select_limit
6807                                 {
6808                                         insertSelectOptions((SelectStmt *) $2, $3, $4,
6809                                                                                 list_nth($5, 0), list_nth($5, 1),
6810                                                                                 $1);
6811                                         $$ = $2;
6812                                 }
6813                         | with_clause select_clause opt_sort_clause select_limit opt_for_locking_clause
6814                                 {
6815                                         insertSelectOptions((SelectStmt *) $2, $3, $5,
6816                                                                                 list_nth($4, 0), list_nth($4, 1),
6817                                                                                 $1);
6818                                         $$ = $2;
6819                                 }
6820                 ;
6821
6822 select_clause:
6823                         simple_select                                                   { $$ = $1; }
6824                         | select_with_parens                                    { $$ = $1; }
6825                 ;
6826
6827 /*
6828  * This rule parses SELECT statements that can appear within set operations,
6829  * including UNION, INTERSECT and EXCEPT.  '(' and ')' can be used to specify
6830  * the ordering of the set operations.  Without '(' and ')' we want the
6831  * operations to be ordered per the precedence specs at the head of this file.
6832  *
6833  * As with select_no_parens, simple_select cannot have outer parentheses,
6834  * but can have parenthesized subclauses.
6835  *
6836  * Note that sort clauses cannot be included at this level --- SQL92 requires
6837  *              SELECT foo UNION SELECT bar ORDER BY baz
6838  * to be parsed as
6839  *              (SELECT foo UNION SELECT bar) ORDER BY baz
6840  * not
6841  *              SELECT foo UNION (SELECT bar ORDER BY baz)
6842  * Likewise for WITH, FOR UPDATE and LIMIT.  Therefore, those clauses are
6843  * described as part of the select_no_parens production, not simple_select.
6844  * This does not limit functionality, because you can reintroduce these
6845  * clauses inside parentheses.
6846  *
6847  * NOTE: only the leftmost component SelectStmt should have INTO.
6848  * However, this is not checked by the grammar; parse analysis must check it.
6849  */
6850 simple_select:
6851                         SELECT opt_distinct target_list
6852                         into_clause from_clause where_clause
6853                         group_clause having_clause window_clause
6854                                 {
6855                                         SelectStmt *n = makeNode(SelectStmt);
6856                                         n->distinctClause = $2;
6857                                         n->targetList = $3;
6858                                         n->intoClause = $4;
6859                                         n->fromClause = $5;
6860                                         n->whereClause = $6;
6861                                         n->groupClause = $7;
6862                                         n->havingClause = $8;
6863                                         n->windowClause = $9;
6864                                         $$ = (Node *)n;
6865                                 }
6866                         | values_clause                                                 { $$ = $1; }
6867                         | TABLE relation_expr
6868                                 {
6869                                         /* same as SELECT * FROM relation_expr */
6870                                         ColumnRef *cr = makeNode(ColumnRef);
6871                                         ResTarget *rt = makeNode(ResTarget);
6872                                         SelectStmt *n = makeNode(SelectStmt);
6873
6874                                         cr->fields = list_make1(makeNode(A_Star));
6875                                         cr->location = -1;
6876
6877                                         rt->name = NULL;
6878                                         rt->indirection = NIL;
6879                                         rt->val = (Node *)cr;
6880                                         rt->location = -1;
6881
6882                                         n->targetList = list_make1(rt);
6883                                         n->fromClause = list_make1($2);
6884                                         $$ = (Node *)n;
6885                                 }
6886                         | select_clause UNION opt_all select_clause
6887                                 {
6888                                         $$ = makeSetOp(SETOP_UNION, $3, $1, $4);
6889                                 }
6890                         | select_clause INTERSECT opt_all select_clause
6891                                 {
6892                                         $$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
6893                                 }
6894                         | select_clause EXCEPT opt_all select_clause
6895                                 {
6896                                         $$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
6897                                 }
6898                 ;
6899
6900 /*
6901  * SQL standard WITH clause looks like:
6902  *
6903  * WITH [ RECURSIVE ] <query name> [ (<column>,...) ]
6904  *              AS (query) [ SEARCH or CYCLE clause ]
6905  *
6906  * We don't currently support the SEARCH or CYCLE clause.
6907  */
6908 with_clause:
6909                 WITH cte_list
6910                         {
6911                                 $$ = makeNode(WithClause);
6912                                 $$->ctes = $2;
6913                                 $$->recursive = false;
6914                                 $$->location = @1;
6915                         }
6916                 | WITH RECURSIVE cte_list
6917                         {
6918                                 $$ = makeNode(WithClause);
6919                                 $$->ctes = $3;
6920                                 $$->recursive = true;
6921                                 $$->location = @1;
6922                         }
6923                 ;
6924
6925 cte_list:
6926                 common_table_expr                                               { $$ = list_make1($1); }
6927                 | cte_list ',' common_table_expr                { $$ = lappend($1, $3); }
6928                 ;
6929
6930 common_table_expr:  name opt_name_list AS select_with_parens
6931                         {
6932                                 CommonTableExpr *n = makeNode(CommonTableExpr);
6933                                 n->ctename = $1;
6934                                 n->aliascolnames = $2;
6935                                 n->ctequery = $4;
6936                                 n->location = @1;
6937                                 $$ = (Node *) n;
6938                         }
6939                 ;
6940
6941 into_clause:
6942                         INTO OptTempTableName
6943                                 {
6944                                         $$ = makeNode(IntoClause);
6945                                         $$->rel = $2;
6946                                         $$->colNames = NIL;
6947                                         $$->options = NIL;
6948                                         $$->onCommit = ONCOMMIT_NOOP;
6949                                         $$->tableSpaceName = NULL;
6950                                 }
6951                         | /*EMPTY*/
6952                                 { $$ = NULL; }
6953                 ;
6954
6955 /*
6956  * Redundancy here is needed to avoid shift/reduce conflicts,
6957  * since TEMP is not a reserved word.  See also OptTemp.
6958  */
6959 OptTempTableName:
6960                         TEMPORARY opt_table qualified_name
6961                                 {
6962                                         $$ = $3;
6963                                         $$->istemp = true;
6964                                 }
6965                         | TEMP opt_table qualified_name
6966                                 {
6967                                         $$ = $3;
6968                                         $$->istemp = true;
6969                                 }
6970                         | LOCAL TEMPORARY opt_table qualified_name
6971                                 {
6972                                         $$ = $4;
6973                                         $$->istemp = true;
6974                                 }
6975                         | LOCAL TEMP opt_table qualified_name
6976                                 {
6977                                         $$ = $4;
6978                                         $$->istemp = true;
6979                                 }
6980                         | GLOBAL TEMPORARY opt_table qualified_name
6981                                 {
6982                                         $$ = $4;
6983                                         $$->istemp = true;
6984                                 }
6985                         | GLOBAL TEMP opt_table qualified_name
6986                                 {
6987                                         $$ = $4;
6988                                         $$->istemp = true;
6989                                 }
6990                         | TABLE qualified_name
6991                                 {
6992                                         $$ = $2;
6993                                         $$->istemp = false;
6994                                 }
6995                         | qualified_name
6996                                 {
6997                                         $$ = $1;
6998                                         $$->istemp = false;
6999                                 }
7000                 ;
7001
7002 opt_table:      TABLE                                                                   {}
7003                         | /*EMPTY*/                                                             {}
7004                 ;
7005
7006 opt_all:        ALL                                                                             { $$ = TRUE; }
7007                         | DISTINCT                                                              { $$ = FALSE; }
7008                         | /*EMPTY*/                                                             { $$ = FALSE; }
7009                 ;
7010
7011 /* We use (NIL) as a placeholder to indicate that all target expressions
7012  * should be placed in the DISTINCT list during parsetree analysis.
7013  */
7014 opt_distinct:
7015                         DISTINCT                                                                { $$ = list_make1(NIL); }
7016                         | DISTINCT ON '(' expr_list ')'                 { $$ = $4; }
7017                         | ALL                                                                   { $$ = NIL; }
7018                         | /*EMPTY*/                                                             { $$ = NIL; }
7019                 ;
7020
7021 opt_sort_clause:
7022                         sort_clause                                                             { $$ = $1;}
7023                         | /*EMPTY*/                                                             { $$ = NIL; }
7024                 ;
7025
7026 sort_clause:
7027                         ORDER BY sortby_list                                    { $$ = $3; }
7028                 ;
7029
7030 sortby_list:
7031                         sortby                                                                  { $$ = list_make1($1); }
7032                         | sortby_list ',' sortby                                { $$ = lappend($1, $3); }
7033                 ;
7034
7035 sortby:         a_expr USING qual_all_Op opt_nulls_order
7036                                 {
7037                                         $$ = makeNode(SortBy);
7038                                         $$->node = $1;
7039                                         $$->sortby_dir = SORTBY_USING;
7040                                         $$->sortby_nulls = $4;
7041                                         $$->useOp = $3;
7042                                         $$->location = @3;
7043                                 }
7044                         | a_expr opt_asc_desc opt_nulls_order
7045                                 {
7046                                         $$ = makeNode(SortBy);
7047                                         $$->node = $1;
7048                                         $$->sortby_dir = $2;
7049                                         $$->sortby_nulls = $3;
7050                                         $$->useOp = NIL;
7051                                         $$->location = -1;              /* no operator */
7052                                 }
7053                 ;
7054
7055
7056 select_limit:
7057                         LIMIT select_limit_value OFFSET select_offset_value
7058                                 { $$ = list_make2($4, $2); }
7059                         | OFFSET select_offset_value LIMIT select_limit_value
7060                                 { $$ = list_make2($2, $4); }
7061                         | LIMIT select_limit_value
7062                                 { $$ = list_make2(NULL, $2); }
7063                         | OFFSET select_offset_value
7064                                 { $$ = list_make2($2, NULL); }
7065                         | LIMIT select_limit_value ',' select_offset_value
7066                                 {
7067                                         /* Disabled because it was too confusing, bjm 2002-02-18 */
7068                                         ereport(ERROR,
7069                                                         (errcode(ERRCODE_SYNTAX_ERROR),
7070                                                          errmsg("LIMIT #,# syntax is not supported"),
7071                                                          errhint("Use separate LIMIT and OFFSET clauses."),
7072                                                          scanner_errposition(@1)));
7073                                 }
7074                         /* SQL:2008 syntax variants */
7075                         | OFFSET select_offset_value2 row_or_rows
7076                                 { $$ = list_make2($2, NULL); }
7077                         | FETCH first_or_next opt_select_fetch_first_value row_or_rows ONLY
7078                                 { $$ = list_make2(NULL, $3); }
7079                         | OFFSET select_offset_value2 row_or_rows FETCH first_or_next opt_select_fetch_first_value row_or_rows ONLY
7080                                 { $$ = list_make2($2, $6); }
7081                 ;
7082
7083 opt_select_limit:
7084                         select_limit                                                    { $$ = $1; }
7085                         | /* EMPTY */
7086                                         { $$ = list_make2(NULL,NULL); }
7087                 ;
7088
7089 select_limit_value:
7090                         a_expr                                                                  { $$ = $1; }
7091                         | ALL
7092                                 {
7093                                         /* LIMIT ALL is represented as a NULL constant */
7094                                         $$ = makeNullAConst(@1);
7095                                 }
7096                 ;
7097
7098 /*
7099  * Allowing full expressions without parentheses causes various parsing
7100  * problems with the trailing ROW/ROWS key words.  SQL only calls for
7101  * constants, so we allow the rest only with parentheses.
7102  */
7103 opt_select_fetch_first_value:
7104                         SignedIconst            { $$ = makeIntConst($1, @1); }
7105                         | '(' a_expr ')'        { $$ = $2; }
7106                         | /*EMPTY*/             { $$ = makeIntConst(1, -1); }
7107                 ;
7108
7109 select_offset_value:
7110                         a_expr                                                                  { $$ = $1; }
7111                 ;
7112
7113 /*
7114  * Again, the trailing ROW/ROWS in this case prevent the full expression
7115  * syntax.  c_expr is the best we can do.
7116  */
7117 select_offset_value2:
7118                         c_expr                                                                  { $$ = $1; }
7119                 ;
7120
7121 /* noise words */
7122 row_or_rows:
7123                         ROW             { $$ = 0; }
7124                         | ROWS          { $$ = 0; }
7125                         ;
7126
7127 /* noise words */
7128 first_or_next:
7129                         FIRST_P         { $$ = 0; }
7130                         | NEXT          { $$ = 0; }
7131                         ;
7132
7133 group_clause:
7134                         GROUP_P BY expr_list                                    { $$ = $3; }
7135                         | /*EMPTY*/                                                             { $$ = NIL; }
7136                 ;
7137
7138 having_clause:
7139                         HAVING a_expr                                                   { $$ = $2; }
7140                         | /*EMPTY*/                                                             { $$ = NULL; }
7141                 ;
7142
7143 for_locking_clause:
7144                         for_locking_items                                               { $$ = $1; }
7145                         | FOR READ ONLY                                                 { $$ = NIL; }
7146                 ;
7147
7148 opt_for_locking_clause:
7149                         for_locking_clause                                              { $$ = $1; }
7150                         | /* EMPTY */                                                   { $$ = NIL; }
7151                 ;
7152
7153 for_locking_items:
7154                         for_locking_item                                                { $$ = list_make1($1); }
7155                         | for_locking_items for_locking_item    { $$ = lappend($1, $2); }
7156                 ;
7157
7158 for_locking_item:
7159                         FOR UPDATE locked_rels_list opt_nowait
7160                                 {
7161                                         LockingClause *n = makeNode(LockingClause);
7162                                         n->lockedRels = $3;
7163                                         n->forUpdate = TRUE;
7164                                         n->noWait = $4;
7165                                         $$ = (Node *) n;
7166                                 }
7167                         | FOR SHARE locked_rels_list opt_nowait
7168                                 {
7169                                         LockingClause *n = makeNode(LockingClause);
7170                                         n->lockedRels = $3;
7171                                         n->forUpdate = FALSE;
7172                                         n->noWait = $4;
7173                                         $$ = (Node *) n;
7174                                 }
7175                 ;
7176
7177 locked_rels_list:
7178                         OF qualified_name_list                                  { $$ = $2; }
7179                         | /* EMPTY */                                                   { $$ = NIL; }
7180                 ;
7181
7182
7183 values_clause:
7184                         VALUES ctext_row
7185                                 {
7186                                         SelectStmt *n = makeNode(SelectStmt);
7187                                         n->valuesLists = list_make1($2);
7188                                         $$ = (Node *) n;
7189                                 }
7190                         | values_clause ',' ctext_row
7191                                 {
7192                                         SelectStmt *n = (SelectStmt *) $1;
7193                                         n->valuesLists = lappend(n->valuesLists, $3);
7194                                         $$ = (Node *) n;
7195                                 }
7196                 ;
7197
7198
7199 /*****************************************************************************
7200  *
7201  *      clauses common to all Optimizable Stmts:
7202  *              from_clause             - allow list of both JOIN expressions and table names
7203  *              where_clause    - qualifications for joins or restrictions
7204  *
7205  *****************************************************************************/
7206
7207 from_clause:
7208                         FROM from_list                                                  { $$ = $2; }
7209                         | /*EMPTY*/                                                             { $$ = NIL; }
7210                 ;
7211
7212 from_list:
7213                         table_ref                                                               { $$ = list_make1($1); }
7214                         | from_list ',' table_ref                               { $$ = lappend($1, $3); }
7215                 ;
7216
7217 /*
7218  * table_ref is where an alias clause can be attached.  Note we cannot make
7219  * alias_clause have an empty production because that causes parse conflicts
7220  * between table_ref := '(' joined_table ')' alias_clause
7221  * and joined_table := '(' joined_table ')'.  So, we must have the
7222  * redundant-looking productions here instead.
7223  */
7224 table_ref:      relation_expr
7225                                 {
7226                                         $$ = (Node *) $1;
7227                                 }
7228                         | relation_expr alias_clause
7229                                 {
7230                                         $1->alias = $2;
7231                                         $$ = (Node *) $1;
7232                                 }
7233                         | func_table
7234                                 {
7235                                         RangeFunction *n = makeNode(RangeFunction);
7236                                         n->funccallnode = $1;
7237                                         n->coldeflist = NIL;
7238                                         $$ = (Node *) n;
7239                                 }
7240                         | func_table alias_clause
7241                                 {
7242                                         RangeFunction *n = makeNode(RangeFunction);
7243                                         n->funccallnode = $1;
7244                                         n->alias = $2;
7245                                         n->coldeflist = NIL;
7246                                         $$ = (Node *) n;
7247                                 }
7248                         | func_table AS '(' TableFuncElementList ')'
7249                                 {
7250                                         RangeFunction *n = makeNode(RangeFunction);
7251                                         n->funccallnode = $1;
7252                                         n->coldeflist = $4;
7253                                         $$ = (Node *) n;
7254                                 }
7255                         | func_table AS ColId '(' TableFuncElementList ')'
7256                                 {
7257                                         RangeFunction *n = makeNode(RangeFunction);
7258                                         Alias *a = makeNode(Alias);
7259                                         n->funccallnode = $1;
7260                                         a->aliasname = $3;
7261                                         n->alias = a;
7262                                         n->coldeflist = $5;
7263                                         $$ = (Node *) n;
7264                                 }
7265                         | func_table ColId '(' TableFuncElementList ')'
7266                                 {
7267                                         RangeFunction *n = makeNode(RangeFunction);
7268                                         Alias *a = makeNode(Alias);
7269                                         n->funccallnode = $1;
7270                                         a->aliasname = $2;
7271                                         n->alias = a;
7272                                         n->coldeflist = $4;
7273                                         $$ = (Node *) n;
7274                                 }
7275                         | select_with_parens
7276                                 {
7277                                         /*
7278                                          * The SQL spec does not permit a subselect
7279                                          * (<derived_table>) without an alias clause,
7280                                          * so we don't either.  This avoids the problem
7281                                          * of needing to invent a unique refname for it.
7282                                          * That could be surmounted if there's sufficient
7283                                          * popular demand, but for now let's just implement
7284                                          * the spec and see if anyone complains.
7285                                          * However, it does seem like a good idea to emit
7286                                          * an error message that's better than "syntax error".
7287                                          */
7288                                         if (IsA($1, SelectStmt) &&
7289                                                 ((SelectStmt *) $1)->valuesLists)
7290                                                 ereport(ERROR,
7291                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
7292                                                                  errmsg("VALUES in FROM must have an alias"),
7293                                                                  errhint("For example, FROM (VALUES ...) [AS] foo."),
7294                                                                  scanner_errposition(@1)));
7295                                         else
7296                                                 ereport(ERROR,
7297                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
7298                                                                  errmsg("subquery in FROM must have an alias"),
7299                                                                  errhint("For example, FROM (SELECT ...) [AS] foo."),
7300                                                                  scanner_errposition(@1)));
7301                                         $$ = NULL;
7302                                 }
7303                         | select_with_parens alias_clause
7304                                 {
7305                                         RangeSubselect *n = makeNode(RangeSubselect);
7306                                         n->subquery = $1;
7307                                         n->alias = $2;
7308                                         $$ = (Node *) n;
7309                                 }
7310                         | joined_table
7311                                 {
7312                                         $$ = (Node *) $1;
7313                                 }
7314                         | '(' joined_table ')' alias_clause
7315                                 {
7316                                         $2->alias = $4;
7317                                         $$ = (Node *) $2;
7318                                 }
7319                 ;
7320
7321
7322 /*
7323  * It may seem silly to separate joined_table from table_ref, but there is
7324  * method in SQL92's madness: if you don't do it this way you get reduce-
7325  * reduce conflicts, because it's not clear to the parser generator whether
7326  * to expect alias_clause after ')' or not.  For the same reason we must
7327  * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
7328  * join_type to expand to empty; if we try it, the parser generator can't
7329  * figure out when to reduce an empty join_type right after table_ref.
7330  *
7331  * Note that a CROSS JOIN is the same as an unqualified
7332  * INNER JOIN, and an INNER JOIN/ON has the same shape
7333  * but a qualification expression to limit membership.
7334  * A NATURAL JOIN implicitly matches column names between
7335  * tables and the shape is determined by which columns are
7336  * in common. We'll collect columns during the later transformations.
7337  */
7338
7339 joined_table:
7340                         '(' joined_table ')'
7341                                 {
7342                                         $$ = $2;
7343                                 }
7344                         | table_ref CROSS JOIN table_ref
7345                                 {
7346                                         /* CROSS JOIN is same as unqualified inner join */
7347                                         JoinExpr *n = makeNode(JoinExpr);
7348                                         n->jointype = JOIN_INNER;
7349                                         n->isNatural = FALSE;
7350                                         n->larg = $1;
7351                                         n->rarg = $4;
7352                                         n->using = NIL;
7353                                         n->quals = NULL;
7354                                         $$ = n;
7355                                 }
7356                         | table_ref join_type JOIN table_ref join_qual
7357                                 {
7358                                         JoinExpr *n = makeNode(JoinExpr);
7359                                         n->jointype = $2;
7360                                         n->isNatural = FALSE;
7361                                         n->larg = $1;
7362                                         n->rarg = $4;
7363                                         if ($5 != NULL && IsA($5, List))
7364                                                 n->using = (List *) $5; /* USING clause */
7365                                         else
7366                                                 n->quals = $5; /* ON clause */
7367                                         $$ = n;
7368                                 }
7369                         | table_ref JOIN table_ref join_qual
7370                                 {
7371                                         /* letting join_type reduce to empty doesn't work */
7372                                         JoinExpr *n = makeNode(JoinExpr);
7373                                         n->jointype = JOIN_INNER;
7374                                         n->isNatural = FALSE;
7375                                         n->larg = $1;
7376                                         n->rarg = $3;
7377                                         if ($4 != NULL && IsA($4, List))
7378                                                 n->using = (List *) $4; /* USING clause */
7379                                         else
7380                                                 n->quals = $4; /* ON clause */
7381                                         $$ = n;
7382                                 }
7383                         | table_ref NATURAL join_type JOIN table_ref
7384                                 {
7385                                         JoinExpr *n = makeNode(JoinExpr);
7386                                         n->jointype = $3;
7387                                         n->isNatural = TRUE;
7388                                         n->larg = $1;
7389                                         n->rarg = $5;
7390                                         n->using = NIL; /* figure out which columns later... */
7391                                         n->quals = NULL; /* fill later */
7392                                         $$ = n;
7393                                 }
7394                         | table_ref NATURAL JOIN table_ref
7395                                 {
7396                                         /* letting join_type reduce to empty doesn't work */
7397                                         JoinExpr *n = makeNode(JoinExpr);
7398                                         n->jointype = JOIN_INNER;
7399                                         n->isNatural = TRUE;
7400                                         n->larg = $1;
7401                                         n->rarg = $4;
7402                                         n->using = NIL; /* figure out which columns later... */
7403                                         n->quals = NULL; /* fill later */
7404                                         $$ = n;
7405                                 }
7406                 ;
7407
7408 alias_clause:
7409                         AS ColId '(' name_list ')'
7410                                 {
7411                                         $$ = makeNode(Alias);
7412                                         $$->aliasname = $2;
7413                                         $$->colnames = $4;
7414                                 }
7415                         | AS ColId
7416                                 {
7417                                         $$ = makeNode(Alias);
7418                                         $$->aliasname = $2;
7419                                 }
7420                         | ColId '(' name_list ')'
7421                                 {
7422                                         $$ = makeNode(Alias);
7423                                         $$->aliasname = $1;
7424                                         $$->colnames = $3;
7425                                 }
7426                         | ColId
7427                                 {
7428                                         $$ = makeNode(Alias);
7429                                         $$->aliasname = $1;
7430                                 }
7431                 ;
7432
7433 join_type:      FULL join_outer                                                 { $$ = JOIN_FULL; }
7434                         | LEFT join_outer                                               { $$ = JOIN_LEFT; }
7435                         | RIGHT join_outer                                              { $$ = JOIN_RIGHT; }
7436                         | INNER_P                                                               { $$ = JOIN_INNER; }
7437                 ;
7438
7439 /* OUTER is just noise... */
7440 join_outer: OUTER_P                                                                     { $$ = NULL; }
7441                         | /*EMPTY*/                                                             { $$ = NULL; }
7442                 ;
7443
7444 /* JOIN qualification clauses
7445  * Possibilities are:
7446  *      USING ( column list ) allows only unqualified column names,
7447  *                                                which must match between tables.
7448  *      ON expr allows more general qualifications.
7449  *
7450  * We return USING as a List node, while an ON-expr will not be a List.
7451  */
7452
7453 join_qual:      USING '(' name_list ')'                                 { $$ = (Node *) $3; }
7454                         | ON a_expr                                                             { $$ = $2; }
7455                 ;
7456
7457
7458 relation_expr:
7459                         qualified_name
7460                                 {
7461                                         /* default inheritance */
7462                                         $$ = $1;
7463                                         $$->inhOpt = INH_DEFAULT;
7464                                         $$->alias = NULL;
7465                                 }
7466                         | qualified_name '*'
7467                                 {
7468                                         /* inheritance query */
7469                                         $$ = $1;
7470                                         $$->inhOpt = INH_YES;
7471                                         $$->alias = NULL;
7472                                 }
7473                         | ONLY qualified_name
7474                                 {
7475                                         /* no inheritance */
7476                                         $$ = $2;
7477                                         $$->inhOpt = INH_NO;
7478                                         $$->alias = NULL;
7479                                 }
7480                         | ONLY '(' qualified_name ')'
7481                                 {
7482                                         /* no inheritance, SQL99-style syntax */
7483                                         $$ = $3;
7484                                         $$->inhOpt = INH_NO;
7485                                         $$->alias = NULL;
7486                                 }
7487                 ;
7488
7489
7490 /*
7491  * Given "UPDATE foo set set ...", we have to decide without looking any
7492  * further ahead whether the first "set" is an alias or the UPDATE's SET
7493  * keyword.  Since "set" is allowed as a column name both interpretations
7494  * are feasible.  We resolve the shift/reduce conflict by giving the first
7495  * relation_expr_opt_alias production a higher precedence than the SET token
7496  * has, causing the parser to prefer to reduce, in effect assuming that the
7497  * SET is not an alias.
7498  */
7499 relation_expr_opt_alias: relation_expr                                  %prec UMINUS
7500                                 {
7501                                         $$ = $1;
7502                                 }
7503                         | relation_expr ColId
7504                                 {
7505                                         Alias *alias = makeNode(Alias);
7506                                         alias->aliasname = $2;
7507                                         $1->alias = alias;
7508                                         $$ = $1;
7509                                 }
7510                         | relation_expr AS ColId
7511                                 {
7512                                         Alias *alias = makeNode(Alias);
7513                                         alias->aliasname = $3;
7514                                         $1->alias = alias;
7515                                         $$ = $1;
7516                                 }
7517                 ;
7518
7519
7520 func_table: func_expr                                                           { $$ = $1; }
7521                 ;
7522
7523
7524 where_clause:
7525                         WHERE a_expr                                                    { $$ = $2; }
7526                         | /*EMPTY*/                                                             { $$ = NULL; }
7527                 ;
7528
7529 /* variant for UPDATE and DELETE */
7530 where_or_current_clause:
7531                         WHERE a_expr                                                    { $$ = $2; }
7532                         | WHERE CURRENT_P OF name
7533                                 {
7534                                         CurrentOfExpr *n = makeNode(CurrentOfExpr);
7535                                         /* cvarno is filled in by parse analysis */
7536                                         n->cursor_name = $4;
7537                                         n->cursor_param = 0;
7538                                         $$ = (Node *) n;
7539                                 }
7540                         | WHERE CURRENT_P OF PARAM
7541                                 {
7542                                         CurrentOfExpr *n = makeNode(CurrentOfExpr);
7543                                         /* cvarno is filled in by parse analysis */
7544                                         n->cursor_name = NULL;
7545                                         n->cursor_param = $4;
7546                                         $$ = (Node *) n;
7547                                 }
7548                         | /*EMPTY*/                                                             { $$ = NULL; }
7549                 ;
7550
7551
7552 TableFuncElementList:
7553                         TableFuncElement
7554                                 {
7555                                         $$ = list_make1($1);
7556                                 }
7557                         | TableFuncElementList ',' TableFuncElement
7558                                 {
7559                                         $$ = lappend($1, $3);
7560                                 }
7561                 ;
7562
7563 TableFuncElement:       ColId Typename
7564                                 {
7565                                         ColumnDef *n = makeNode(ColumnDef);
7566                                         n->colname = $1;
7567                                         n->typename = $2;
7568                                         n->constraints = NIL;
7569                                         n->is_local = true;
7570                                         $$ = (Node *)n;
7571                                 }
7572                 ;
7573
7574 /*****************************************************************************
7575  *
7576  *      Type syntax
7577  *              SQL92 introduces a large amount of type-specific syntax.
7578  *              Define individual clauses to handle these cases, and use
7579  *               the generic case to handle regular type-extensible Postgres syntax.
7580  *              - thomas 1997-10-10
7581  *
7582  *****************************************************************************/
7583
7584 Typename:       SimpleTypename opt_array_bounds
7585                                 {
7586                                         $$ = $1;
7587                                         $$->arrayBounds = $2;
7588                                 }
7589                         | SETOF SimpleTypename opt_array_bounds
7590                                 {
7591                                         $$ = $2;
7592                                         $$->arrayBounds = $3;
7593                                         $$->setof = TRUE;
7594                                 }
7595                         /* SQL standard syntax, currently only one-dimensional */
7596                         | SimpleTypename ARRAY '[' Iconst ']'
7597                                 {
7598                                         $$ = $1;
7599                                         $$->arrayBounds = list_make1(makeInteger($4));
7600                                 }
7601                         | SETOF SimpleTypename ARRAY '[' Iconst ']'
7602                                 {
7603                                         $$ = $2;
7604                                         $$->arrayBounds = list_make1(makeInteger($5));
7605                                         $$->setof = TRUE;
7606                                 }
7607                         | SimpleTypename ARRAY
7608                                 {
7609                                         $$ = $1;
7610                                         $$->arrayBounds = list_make1(makeInteger(-1));
7611                                 }
7612                         | SETOF SimpleTypename ARRAY
7613                                 {
7614                                         $$ = $2;
7615                                         $$->arrayBounds = list_make1(makeInteger(-1));
7616                                         $$->setof = TRUE;
7617                                 }
7618                 ;
7619
7620 opt_array_bounds:
7621                         opt_array_bounds '[' ']'
7622                                         {  $$ = lappend($1, makeInteger(-1)); }
7623                         | opt_array_bounds '[' Iconst ']'
7624                                         {  $$ = lappend($1, makeInteger($3)); }
7625                         | /*EMPTY*/
7626                                         {  $$ = NIL; }
7627                 ;
7628
7629 SimpleTypename:
7630                         GenericType                                                             { $$ = $1; }
7631                         | Numeric                                                               { $$ = $1; }
7632                         | Bit                                                                   { $$ = $1; }
7633                         | Character                                                             { $$ = $1; }
7634                         | ConstDatetime                                                 { $$ = $1; }
7635                         | ConstInterval opt_interval
7636                                 {
7637                                         $$ = $1;
7638                                         $$->typmods = $2;
7639                                 }
7640                         | ConstInterval '(' Iconst ')' opt_interval
7641                                 {
7642                                         $$ = $1;
7643                                         if ($5 != NIL)
7644                                         {
7645                                                 if (list_length($5) != 1)
7646                                                         ereport(ERROR,
7647                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
7648                                                                          errmsg("interval precision specified twice"),
7649                                                                          scanner_errposition(@1)));
7650                                                 $$->typmods = lappend($5, makeIntConst($3, @3));
7651                                         }
7652                                         else
7653                                                 $$->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
7654                                                                                                  makeIntConst($3, @3));
7655                                 }
7656                 ;
7657
7658 /* We have a separate ConstTypename to allow defaulting fixed-length
7659  * types such as CHAR() and BIT() to an unspecified length.
7660  * SQL9x requires that these default to a length of one, but this
7661  * makes no sense for constructs like CHAR 'hi' and BIT '0101',
7662  * where there is an obvious better choice to make.
7663  * Note that ConstInterval is not included here since it must
7664  * be pushed up higher in the rules to accomodate the postfix
7665  * options (e.g. INTERVAL '1' YEAR). Likewise, we have to handle
7666  * the generic-type-name case in AExprConst to avoid premature
7667  * reduce/reduce conflicts against function names.
7668  */
7669 ConstTypename:
7670                         Numeric                                                                 { $$ = $1; }
7671                         | ConstBit                                                              { $$ = $1; }
7672                         | ConstCharacter                                                { $$ = $1; }
7673                         | ConstDatetime                                                 { $$ = $1; }
7674                 ;
7675
7676 /*
7677  * GenericType covers all type names that don't have special syntax mandated
7678  * by the standard, including qualified names.  We also allow type modifiers.
7679  * To avoid parsing conflicts against function invocations, the modifiers
7680  * have to be shown as expr_list here, but parse analysis will only accept
7681  * constants for them.
7682  */
7683 GenericType:
7684                         type_function_name opt_type_modifiers
7685                                 {
7686                                         $$ = makeTypeName($1);
7687                                         $$->typmods = $2;
7688                                         $$->location = @1;
7689                                 }
7690                         | type_function_name attrs opt_type_modifiers
7691                                 {
7692                                         $$ = makeTypeNameFromNameList(lcons(makeString($1), $2));
7693                                         $$->typmods = $3;
7694                                         $$->location = @1;
7695                                 }
7696                 ;
7697
7698 opt_type_modifiers: '(' expr_list ')'                           { $$ = $2; }
7699                                         | /* EMPTY */                                   { $$ = NIL; }
7700                 ;
7701
7702 /*
7703  * SQL92 numeric data types
7704  */
7705 Numeric:        INT_P
7706                                 {
7707                                         $$ = SystemTypeName("int4");
7708                                         $$->location = @1;
7709                                 }
7710                         | INTEGER
7711                                 {
7712                                         $$ = SystemTypeName("int4");
7713                                         $$->location = @1;
7714                                 }
7715                         | SMALLINT
7716                                 {
7717                                         $$ = SystemTypeName("int2");
7718                                         $$->location = @1;
7719                                 }
7720                         | BIGINT
7721                                 {
7722                                         $$ = SystemTypeName("int8");
7723                                         $$->location = @1;
7724                                 }
7725                         | REAL
7726                                 {
7727                                         $$ = SystemTypeName("float4");
7728                                         $$->location = @1;
7729                                 }
7730                         | FLOAT_P opt_float
7731                                 {
7732                                         $$ = $2;
7733                                         $$->location = @1;
7734                                 }
7735                         | DOUBLE_P PRECISION
7736                                 {
7737                                         $$ = SystemTypeName("float8");
7738                                         $$->location = @1;
7739                                 }
7740                         | DECIMAL_P opt_type_modifiers
7741                                 {
7742                                         $$ = SystemTypeName("numeric");
7743                                         $$->typmods = $2;
7744                                         $$->location = @1;
7745                                 }
7746                         | DEC opt_type_modifiers
7747                                 {
7748                                         $$ = SystemTypeName("numeric");
7749                                         $$->typmods = $2;
7750                                         $$->location = @1;
7751                                 }
7752                         | NUMERIC opt_type_modifiers
7753                                 {
7754                                         $$ = SystemTypeName("numeric");
7755                                         $$->typmods = $2;
7756                                         $$->location = @1;
7757                                 }
7758                         | BOOLEAN_P
7759                                 {
7760                                         $$ = SystemTypeName("bool");
7761                                         $$->location = @1;
7762                                 }
7763                 ;
7764
7765 opt_float:      '(' Iconst ')'
7766                                 {
7767                                         /*
7768                                          * Check FLOAT() precision limits assuming IEEE floating
7769                                          * types - thomas 1997-09-18
7770                                          */
7771                                         if ($2 < 1)
7772                                                 ereport(ERROR,
7773                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7774                                                                  errmsg("precision for type float must be at least 1 bit"),
7775                                                                  scanner_errposition(@2)));
7776                                         else if ($2 <= 24)
7777                                                 $$ = SystemTypeName("float4");
7778                                         else if ($2 <= 53)
7779                                                 $$ = SystemTypeName("float8");
7780                                         else
7781                                                 ereport(ERROR,
7782                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7783                                                                  errmsg("precision for type float must be less than 54 bits"),
7784                                                                  scanner_errposition(@2)));
7785                                 }
7786                         | /*EMPTY*/
7787                                 {
7788                                         $$ = SystemTypeName("float8");
7789                                 }
7790                 ;
7791
7792 /*
7793  * SQL92 bit-field data types
7794  * The following implements BIT() and BIT VARYING().
7795  */
7796 Bit:            BitWithLength
7797                                 {
7798                                         $$ = $1;
7799                                 }
7800                         | BitWithoutLength
7801                                 {
7802                                         $$ = $1;
7803                                 }
7804                 ;
7805
7806 /* ConstBit is like Bit except "BIT" defaults to unspecified length */
7807 /* See notes for ConstCharacter, which addresses same issue for "CHAR" */
7808 ConstBit:       BitWithLength
7809                                 {
7810                                         $$ = $1;
7811                                 }
7812                         | BitWithoutLength
7813                                 {
7814                                         $$ = $1;
7815                                         $$->typmods = NIL;
7816                                 }
7817                 ;
7818
7819 BitWithLength:
7820                         BIT opt_varying '(' expr_list ')'
7821                                 {
7822                                         char *typname;
7823
7824                                         typname = $2 ? "varbit" : "bit";
7825                                         $$ = SystemTypeName(typname);
7826                                         $$->typmods = $4;
7827                                         $$->location = @1;
7828                                 }
7829                 ;
7830
7831 BitWithoutLength:
7832                         BIT opt_varying
7833                                 {
7834                                         /* bit defaults to bit(1), varbit to no limit */
7835                                         if ($2)
7836                                         {
7837                                                 $$ = SystemTypeName("varbit");
7838                                         }
7839                                         else
7840                                         {
7841                                                 $$ = SystemTypeName("bit");
7842                                                 $$->typmods = list_make1(makeIntConst(1, -1));
7843                                         }
7844                                         $$->location = @1;
7845                                 }
7846                 ;
7847
7848
7849 /*
7850  * SQL92 character data types
7851  * The following implements CHAR() and VARCHAR().
7852  */
7853 Character:  CharacterWithLength
7854                                 {
7855                                         $$ = $1;
7856                                 }
7857                         | CharacterWithoutLength
7858                                 {
7859                                         $$ = $1;
7860                                 }
7861                 ;
7862
7863 ConstCharacter:  CharacterWithLength
7864                                 {
7865                                         $$ = $1;
7866                                 }
7867                         | CharacterWithoutLength
7868                                 {
7869                                         /* Length was not specified so allow to be unrestricted.
7870                                          * This handles problems with fixed-length (bpchar) strings
7871                                          * which in column definitions must default to a length
7872                                          * of one, but should not be constrained if the length
7873                                          * was not specified.
7874                                          */
7875                                         $$ = $1;
7876                                         $$->typmods = NIL;
7877                                 }
7878                 ;
7879
7880 CharacterWithLength:  character '(' Iconst ')' opt_charset
7881                                 {
7882                                         if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
7883                                         {
7884                                                 char *type;
7885
7886                                                 type = palloc(strlen($1) + 1 + strlen($5) + 1);
7887                                                 strcpy(type, $1);
7888                                                 strcat(type, "_");
7889                                                 strcat(type, $5);
7890                                                 $1 = type;
7891                                         }
7892
7893                                         $$ = SystemTypeName($1);
7894                                         $$->typmods = list_make1(makeIntConst($3, @3));
7895                                         $$->location = @1;
7896                                 }
7897                 ;
7898
7899 CharacterWithoutLength:  character opt_charset
7900                                 {
7901                                         if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
7902                                         {
7903                                                 char *type;
7904
7905                                                 type = palloc(strlen($1) + 1 + strlen($2) + 1);
7906                                                 strcpy(type, $1);
7907                                                 strcat(type, "_");
7908                                                 strcat(type, $2);
7909                                                 $1 = type;
7910                                         }
7911
7912                                         $$ = SystemTypeName($1);
7913
7914                                         /* char defaults to char(1), varchar to no limit */
7915                                         if (strcmp($1, "bpchar") == 0)
7916                                                 $$->typmods = list_make1(makeIntConst(1, -1));
7917
7918                                         $$->location = @1;
7919                                 }
7920                 ;
7921
7922 character:      CHARACTER opt_varying
7923                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
7924                         | CHAR_P opt_varying
7925                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
7926                         | VARCHAR
7927                                                                                 { $$ = "varchar"; }
7928                         | NATIONAL CHARACTER opt_varying
7929                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
7930                         | NATIONAL CHAR_P opt_varying
7931                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
7932                         | NCHAR opt_varying
7933                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
7934                 ;
7935
7936 opt_varying:
7937                         VARYING                                                                 { $$ = TRUE; }
7938                         | /*EMPTY*/                                                             { $$ = FALSE; }
7939                 ;
7940
7941 opt_charset:
7942                         CHARACTER SET ColId                                             { $$ = $3; }
7943                         | /*EMPTY*/                                                             { $$ = NULL; }
7944                 ;
7945
7946 /*
7947  * SQL92 date/time types
7948  */
7949 ConstDatetime:
7950                         TIMESTAMP '(' Iconst ')' opt_timezone
7951                                 {
7952                                         if ($5)
7953                                                 $$ = SystemTypeName("timestamptz");
7954                                         else
7955                                                 $$ = SystemTypeName("timestamp");
7956                                         $$->typmods = list_make1(makeIntConst($3, @3));
7957                                         $$->location = @1;
7958                                 }
7959                         | TIMESTAMP opt_timezone
7960                                 {
7961                                         if ($2)
7962                                                 $$ = SystemTypeName("timestamptz");
7963                                         else
7964                                                 $$ = SystemTypeName("timestamp");
7965                                         $$->location = @1;
7966                                 }
7967                         | TIME '(' Iconst ')' opt_timezone
7968                                 {
7969                                         if ($5)
7970                                                 $$ = SystemTypeName("timetz");
7971                                         else
7972                                                 $$ = SystemTypeName("time");
7973                                         $$->typmods = list_make1(makeIntConst($3, @3));
7974                                         $$->location = @1;
7975                                 }
7976                         | TIME opt_timezone
7977                                 {
7978                                         if ($2)
7979                                                 $$ = SystemTypeName("timetz");
7980                                         else
7981                                                 $$ = SystemTypeName("time");
7982                                         $$->location = @1;
7983                                 }
7984                 ;
7985
7986 ConstInterval:
7987                         INTERVAL
7988                                 {
7989                                         $$ = SystemTypeName("interval");
7990                                         $$->location = @1;
7991                                 }
7992                 ;
7993
7994 opt_timezone:
7995                         WITH_TIME ZONE                                                  { $$ = TRUE; }
7996                         | WITHOUT TIME ZONE                                             { $$ = FALSE; }
7997                         | /*EMPTY*/                                                             { $$ = FALSE; }
7998                 ;
7999
8000 opt_interval:
8001                         YEAR_P
8002                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR), @1)); }
8003                         | MONTH_P
8004                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MONTH), @1)); }
8005                         | DAY_P
8006                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY), @1)); }
8007                         | HOUR_P
8008                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR), @1)); }
8009                         | MINUTE_P
8010                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MINUTE), @1)); }
8011                         | interval_second
8012                                 { $$ = $1; }
8013                         | YEAR_P TO MONTH_P
8014                                 {
8015                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR) |
8016                                                                                                  INTERVAL_MASK(MONTH), @1));
8017                                 }
8018                         | DAY_P TO HOUR_P
8019                                 {
8020                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
8021                                                                                                  INTERVAL_MASK(HOUR), @1));
8022                                 }
8023                         | DAY_P TO MINUTE_P
8024                                 {
8025                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
8026                                                                                                  INTERVAL_MASK(HOUR) |
8027                                                                                                  INTERVAL_MASK(MINUTE), @1));
8028                                 }
8029                         | DAY_P TO interval_second
8030                                 {
8031                                         $$ = $3;
8032                                         linitial($$) = makeIntConst(INTERVAL_MASK(DAY) |
8033                                                                                                 INTERVAL_MASK(HOUR) |
8034                                                                                                 INTERVAL_MASK(MINUTE) |
8035                                                                                                 INTERVAL_MASK(SECOND), @1);
8036                                 }
8037                         | HOUR_P TO MINUTE_P
8038                                 {
8039                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR) |
8040                                                                                                  INTERVAL_MASK(MINUTE), @1));
8041                                 }
8042                         | HOUR_P TO interval_second
8043                                 {
8044                                         $$ = $3;
8045                                         linitial($$) = makeIntConst(INTERVAL_MASK(HOUR) |
8046                                                                                                 INTERVAL_MASK(MINUTE) |
8047                                                                                                 INTERVAL_MASK(SECOND), @1);
8048                                 }
8049                         | MINUTE_P TO interval_second
8050                                 {
8051                                         $$ = $3;
8052                                         linitial($$) = makeIntConst(INTERVAL_MASK(MINUTE) |
8053                                                                                                 INTERVAL_MASK(SECOND), @1);
8054                                 }
8055                         | /*EMPTY*/
8056                                 { $$ = NIL; }
8057                 ;
8058
8059 interval_second:
8060                         SECOND_P
8061                                 {
8062                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(SECOND), @1));
8063                                 }
8064                         | SECOND_P '(' Iconst ')'
8065                                 {
8066                                         $$ = list_make2(makeIntConst(INTERVAL_MASK(SECOND), @1),
8067                                                                         makeIntConst($3, @3));
8068                                 }
8069                 ;
8070
8071
8072 /*****************************************************************************
8073  *
8074  *      expression grammar
8075  *
8076  *****************************************************************************/
8077
8078 /*
8079  * General expressions
8080  * This is the heart of the expression syntax.
8081  *
8082  * We have two expression types: a_expr is the unrestricted kind, and
8083  * b_expr is a subset that must be used in some places to avoid shift/reduce
8084  * conflicts.  For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
8085  * because that use of AND conflicts with AND as a boolean operator.  So,
8086  * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
8087  *
8088  * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
8089  * always be used by surrounding it with parens.
8090  *
8091  * c_expr is all the productions that are common to a_expr and b_expr;
8092  * it's factored out just to eliminate redundant coding.
8093  */
8094 a_expr:         c_expr                                                                  { $$ = $1; }
8095                         | a_expr TYPECAST Typename
8096                                         { $$ = makeTypeCast($1, $3, @2); }
8097                         | a_expr AT TIME ZONE a_expr
8098                                 {
8099                                         FuncCall *n = makeNode(FuncCall);
8100                                         n->funcname = SystemFuncName("timezone");
8101                                         n->args = list_make2($5, $1);
8102                                         n->agg_star = FALSE;
8103                                         n->agg_distinct = FALSE;
8104                                         n->func_variadic = FALSE;
8105                                         n->over = NULL;
8106                                         n->location = @2;
8107                                         $$ = (Node *) n;
8108                                 }
8109                 /*
8110                  * These operators must be called out explicitly in order to make use
8111                  * of yacc/bison's automatic operator-precedence handling.  All other
8112                  * operator names are handled by the generic productions using "Op",
8113                  * below; and all those operators will have the same precedence.
8114                  *
8115                  * If you add more explicitly-known operators, be sure to add them
8116                  * also to b_expr and to the MathOp list above.
8117                  */
8118                         | '+' a_expr                                    %prec UMINUS
8119                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
8120                         | '-' a_expr                                    %prec UMINUS
8121                                 { $$ = doNegate($2, @1); }
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                         | a_expr '>' a_expr
8137                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $3, @2); }
8138                         | a_expr '=' a_expr
8139                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "=", $1, $3, @2); }
8140
8141                         | a_expr qual_Op a_expr                         %prec Op
8142                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
8143                         | qual_Op a_expr                                        %prec Op
8144                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
8145                         | a_expr qual_Op                                        %prec POSTFIXOP
8146                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
8147
8148                         | a_expr AND a_expr
8149                                 { $$ = (Node *) makeA_Expr(AEXPR_AND, NIL, $1, $3, @2); }
8150                         | a_expr OR a_expr
8151                                 { $$ = (Node *) makeA_Expr(AEXPR_OR, NIL, $1, $3, @2); }
8152                         | NOT a_expr
8153                                 { $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL, $2, @1); }
8154
8155                         | a_expr LIKE a_expr
8156                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~", $1, $3, @2); }
8157                         | a_expr LIKE a_expr ESCAPE a_expr
8158                                 {
8159                                         FuncCall *n = makeNode(FuncCall);
8160                                         n->funcname = SystemFuncName("like_escape");
8161                                         n->args = list_make2($3, $5);
8162                                         n->agg_star = FALSE;
8163                                         n->agg_distinct = FALSE;
8164                                         n->func_variadic = FALSE;
8165                                         n->over = NULL;
8166                                         n->location = @4;
8167                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~", $1, (Node *) n, @2);
8168                                 }
8169                         | a_expr NOT LIKE a_expr
8170                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~", $1, $4, @2); }
8171                         | a_expr NOT LIKE a_expr ESCAPE a_expr
8172                                 {
8173                                         FuncCall *n = makeNode(FuncCall);
8174                                         n->funcname = SystemFuncName("like_escape");
8175                                         n->args = list_make2($4, $6);
8176                                         n->agg_star = FALSE;
8177                                         n->agg_distinct = FALSE;
8178                                         n->func_variadic = FALSE;
8179                                         n->over = NULL;
8180                                         n->location = @5;
8181                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~", $1, (Node *) n, @2);
8182                                 }
8183                         | a_expr ILIKE a_expr
8184                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~*", $1, $3, @2); }
8185                         | a_expr ILIKE a_expr ESCAPE a_expr
8186                                 {
8187                                         FuncCall *n = makeNode(FuncCall);
8188                                         n->funcname = SystemFuncName("like_escape");
8189                                         n->args = list_make2($3, $5);
8190                                         n->agg_star = FALSE;
8191                                         n->agg_distinct = FALSE;
8192                                         n->func_variadic = FALSE;
8193                                         n->over = NULL;
8194                                         n->location = @4;
8195                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~*", $1, (Node *) n, @2);
8196                                 }
8197                         | a_expr NOT ILIKE a_expr
8198                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~*", $1, $4, @2); }
8199                         | a_expr NOT ILIKE a_expr ESCAPE a_expr
8200                                 {
8201                                         FuncCall *n = makeNode(FuncCall);
8202                                         n->funcname = SystemFuncName("like_escape");
8203                                         n->args = list_make2($4, $6);
8204                                         n->agg_star = FALSE;
8205                                         n->agg_distinct = FALSE;
8206                                         n->func_variadic = FALSE;
8207                                         n->over = NULL;
8208                                         n->location = @5;
8209                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~*", $1, (Node *) n, @2);
8210                                 }
8211
8212                         | a_expr SIMILAR TO a_expr                              %prec SIMILAR
8213                                 {
8214                                         FuncCall *n = makeNode(FuncCall);
8215                                         n->funcname = SystemFuncName("similar_escape");
8216                                         n->args = list_make2($4, makeNullAConst(-1));
8217                                         n->agg_star = FALSE;
8218                                         n->agg_distinct = FALSE;
8219                                         n->func_variadic = FALSE;
8220                                         n->over = NULL;
8221                                         n->location = @2;
8222                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~", $1, (Node *) n, @2);
8223                                 }
8224                         | a_expr SIMILAR TO a_expr ESCAPE a_expr
8225                                 {
8226                                         FuncCall *n = makeNode(FuncCall);
8227                                         n->funcname = SystemFuncName("similar_escape");
8228                                         n->args = list_make2($4, $6);
8229                                         n->agg_star = FALSE;
8230                                         n->agg_distinct = FALSE;
8231                                         n->func_variadic = FALSE;
8232                                         n->over = NULL;
8233                                         n->location = @5;
8234                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~", $1, (Node *) n, @2);
8235                                 }
8236                         | a_expr NOT SIMILAR TO a_expr                  %prec SIMILAR
8237                                 {
8238                                         FuncCall *n = makeNode(FuncCall);
8239                                         n->funcname = SystemFuncName("similar_escape");
8240                                         n->args = list_make2($5, makeNullAConst(-1));
8241                                         n->agg_star = FALSE;
8242                                         n->agg_distinct = FALSE;
8243                                         n->func_variadic = FALSE;
8244                                         n->over = NULL;
8245                                         n->location = @5;
8246                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~", $1, (Node *) n, @2);
8247                                 }
8248                         | a_expr NOT SIMILAR TO a_expr ESCAPE a_expr
8249                                 {
8250                                         FuncCall *n = makeNode(FuncCall);
8251                                         n->funcname = SystemFuncName("similar_escape");
8252                                         n->args = list_make2($5, $7);
8253                                         n->agg_star = FALSE;
8254                                         n->agg_distinct = FALSE;
8255                                         n->func_variadic = FALSE;
8256                                         n->over = NULL;
8257                                         n->location = @6;
8258                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~", $1, (Node *) n, @2);
8259                                 }
8260
8261                         /* NullTest clause
8262                          * Define SQL92-style Null test clause.
8263                          * Allow two forms described in the standard:
8264                          *      a IS NULL
8265                          *      a IS NOT NULL
8266                          * Allow two SQL extensions
8267                          *      a ISNULL
8268                          *      a NOTNULL
8269                          */
8270                         | a_expr IS NULL_P
8271                                 {
8272                                         NullTest *n = makeNode(NullTest);
8273                                         n->arg = (Expr *) $1;
8274                                         n->nulltesttype = IS_NULL;
8275                                         $$ = (Node *)n;
8276                                 }
8277                         | a_expr ISNULL
8278                                 {
8279                                         NullTest *n = makeNode(NullTest);
8280                                         n->arg = (Expr *) $1;
8281                                         n->nulltesttype = IS_NULL;
8282                                         $$ = (Node *)n;
8283                                 }
8284                         | a_expr IS NOT NULL_P
8285                                 {
8286                                         NullTest *n = makeNode(NullTest);
8287                                         n->arg = (Expr *) $1;
8288                                         n->nulltesttype = IS_NOT_NULL;
8289                                         $$ = (Node *)n;
8290                                 }
8291                         | a_expr NOTNULL
8292                                 {
8293                                         NullTest *n = makeNode(NullTest);
8294                                         n->arg = (Expr *) $1;
8295                                         n->nulltesttype = IS_NOT_NULL;
8296                                         $$ = (Node *)n;
8297                                 }
8298                         | row OVERLAPS row
8299                                 {
8300                                         $$ = (Node *)makeOverlaps($1, $3, @2);
8301                                 }
8302                         | a_expr IS TRUE_P
8303                                 {
8304                                         BooleanTest *b = makeNode(BooleanTest);
8305                                         b->arg = (Expr *) $1;
8306                                         b->booltesttype = IS_TRUE;
8307                                         $$ = (Node *)b;
8308                                 }
8309                         | a_expr IS NOT TRUE_P
8310                                 {
8311                                         BooleanTest *b = makeNode(BooleanTest);
8312                                         b->arg = (Expr *) $1;
8313                                         b->booltesttype = IS_NOT_TRUE;
8314                                         $$ = (Node *)b;
8315                                 }
8316                         | a_expr IS FALSE_P
8317                                 {
8318                                         BooleanTest *b = makeNode(BooleanTest);
8319                                         b->arg = (Expr *) $1;
8320                                         b->booltesttype = IS_FALSE;
8321                                         $$ = (Node *)b;
8322                                 }
8323                         | a_expr IS NOT FALSE_P
8324                                 {
8325                                         BooleanTest *b = makeNode(BooleanTest);
8326                                         b->arg = (Expr *) $1;
8327                                         b->booltesttype = IS_NOT_FALSE;
8328                                         $$ = (Node *)b;
8329                                 }
8330                         | a_expr IS UNKNOWN
8331                                 {
8332                                         BooleanTest *b = makeNode(BooleanTest);
8333                                         b->arg = (Expr *) $1;
8334                                         b->booltesttype = IS_UNKNOWN;
8335                                         $$ = (Node *)b;
8336                                 }
8337                         | a_expr IS NOT UNKNOWN
8338                                 {
8339                                         BooleanTest *b = makeNode(BooleanTest);
8340                                         b->arg = (Expr *) $1;
8341                                         b->booltesttype = IS_NOT_UNKNOWN;
8342                                         $$ = (Node *)b;
8343                                 }
8344                         | a_expr IS DISTINCT FROM a_expr                        %prec IS
8345                                 {
8346                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
8347                                 }
8348                         | a_expr IS NOT DISTINCT FROM a_expr            %prec IS
8349                                 {
8350                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
8351                                                                         (Node *) makeSimpleA_Expr(AEXPR_DISTINCT,
8352                                                                                                                           "=", $1, $6, @2),
8353                                                                                          @2);
8354
8355                                 }
8356                         | a_expr IS OF '(' type_list ')'                        %prec IS
8357                                 {
8358                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
8359                                 }
8360                         | a_expr IS NOT OF '(' type_list ')'            %prec IS
8361                                 {
8362                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
8363                                 }
8364                         /*
8365                          *      Ideally we would not use hard-wired operators below but instead use
8366                          *      opclasses.  However, mixed data types and other issues make this
8367                          *      difficult:  http://archives.postgresql.org/pgsql-hackers/2008-08/msg01142.php
8368                          */                     
8369                         | a_expr BETWEEN opt_asymmetric b_expr AND b_expr               %prec BETWEEN
8370                                 {
8371                                         $$ = (Node *) makeA_Expr(AEXPR_AND, NIL,
8372                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $4, @2),
8373                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $6, @2),
8374                                                                                          @2);
8375                                 }
8376                         | a_expr NOT BETWEEN opt_asymmetric b_expr AND b_expr   %prec BETWEEN
8377                                 {
8378                                         $$ = (Node *) makeA_Expr(AEXPR_OR, NIL,
8379                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $5, @2),
8380                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $7, @2),
8381                                                                                          @2);
8382                                 }
8383                         | a_expr BETWEEN SYMMETRIC b_expr AND b_expr                    %prec BETWEEN
8384                                 {
8385                                         $$ = (Node *) makeA_Expr(AEXPR_OR, NIL,
8386                                                 (Node *) makeA_Expr(AEXPR_AND, NIL,
8387                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $4, @2),
8388                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $6, @2),
8389                                                                                         @2),
8390                                                 (Node *) makeA_Expr(AEXPR_AND, NIL,
8391                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $6, @2),
8392                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $4, @2),
8393                                                                                         @2),
8394                                                                                          @2);
8395                                 }
8396                         | a_expr NOT BETWEEN SYMMETRIC b_expr AND b_expr                %prec BETWEEN
8397                                 {
8398                                         $$ = (Node *) makeA_Expr(AEXPR_AND, NIL,
8399                                                 (Node *) makeA_Expr(AEXPR_OR, NIL,
8400                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $5, @2),
8401                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $7, @2),
8402                                                                                         @2),
8403                                                 (Node *) makeA_Expr(AEXPR_OR, NIL,
8404                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $7, @2),
8405                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $5, @2),
8406                                                                                         @2),
8407                                                                                          @2);
8408                                 }
8409                         | a_expr IN_P in_expr
8410                                 {
8411                                         /* in_expr returns a SubLink or a list of a_exprs */
8412                                         if (IsA($3, SubLink))
8413                                         {
8414                                                 /* generate foo = ANY (subquery) */
8415                                                 SubLink *n = (SubLink *) $3;
8416                                                 n->subLinkType = ANY_SUBLINK;
8417                                                 n->testexpr = $1;
8418                                                 n->operName = list_make1(makeString("="));
8419                                                 n->location = @2;
8420                                                 $$ = (Node *)n;
8421                                         }
8422                                         else
8423                                         {
8424                                                 /* generate scalar IN expression */
8425                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "=", $1, $3, @2);
8426                                         }
8427                                 }
8428                         | a_expr NOT IN_P in_expr
8429                                 {
8430                                         /* in_expr returns a SubLink or a list of a_exprs */
8431                                         if (IsA($4, SubLink))
8432                                         {
8433                                                 /* generate NOT (foo = ANY (subquery)) */
8434                                                 /* Make an = ANY node */
8435                                                 SubLink *n = (SubLink *) $4;
8436                                                 n->subLinkType = ANY_SUBLINK;
8437                                                 n->testexpr = $1;
8438                                                 n->operName = list_make1(makeString("="));
8439                                                 n->location = @3;
8440                                                 /* Stick a NOT on top */
8441                                                 $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL, (Node *) n, @2);
8442                                         }
8443                                         else
8444                                         {
8445                                                 /* generate scalar NOT IN expression */
8446                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "<>", $1, $4, @2);
8447                                         }
8448                                 }
8449                         | a_expr subquery_Op sub_type select_with_parens        %prec Op
8450                                 {
8451                                         SubLink *n = makeNode(SubLink);
8452                                         n->subLinkType = $3;
8453                                         n->testexpr = $1;
8454                                         n->operName = $2;
8455                                         n->subselect = $4;
8456                                         n->location = @2;
8457                                         $$ = (Node *)n;
8458                                 }
8459                         | a_expr subquery_Op sub_type '(' a_expr ')'            %prec Op
8460                                 {
8461                                         if ($3 == ANY_SUBLINK)
8462                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ANY, $2, $1, $5, @2);
8463                                         else
8464                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ALL, $2, $1, $5, @2);
8465                                 }
8466                         | UNIQUE select_with_parens
8467                                 {
8468                                         /* Not sure how to get rid of the parentheses
8469                                          * but there are lots of shift/reduce errors without them.
8470                                          *
8471                                          * Should be able to implement this by plopping the entire
8472                                          * select into a node, then transforming the target expressions
8473                                          * from whatever they are into count(*), and testing the
8474                                          * entire result equal to one.
8475                                          * But, will probably implement a separate node in the executor.
8476                                          */
8477                                         ereport(ERROR,
8478                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8479                                                          errmsg("UNIQUE predicate is not yet implemented"),
8480                                                          scanner_errposition(@1)));
8481                                 }
8482                         | a_expr IS DOCUMENT_P                                  %prec IS
8483                                 {
8484                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8485                                                                          list_make1($1), @2);
8486                                 }
8487                         | a_expr IS NOT DOCUMENT_P                              %prec IS
8488                                 {
8489                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
8490                                                                                          makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8491                                                                                                                  list_make1($1), @2),
8492                                                                                          @2);
8493                                 }
8494                 ;
8495
8496 /*
8497  * Restricted expressions
8498  *
8499  * b_expr is a subset of the complete expression syntax defined by a_expr.
8500  *
8501  * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
8502  * cause trouble in the places where b_expr is used.  For simplicity, we
8503  * just eliminate all the boolean-keyword-operator productions from b_expr.
8504  */
8505 b_expr:         c_expr
8506                                 { $$ = $1; }
8507                         | b_expr TYPECAST Typename
8508                                 { $$ = makeTypeCast($1, $3, @2); }
8509                         | '+' b_expr                                    %prec UMINUS
8510                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
8511                         | '-' b_expr                                    %prec UMINUS
8512                                 { $$ = doNegate($2, @1); }
8513                         | b_expr '+' b_expr
8514                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", $1, $3, @2); }
8515                         | b_expr '-' b_expr
8516                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "-", $1, $3, @2); }
8517                         | b_expr '*' b_expr
8518                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", $1, $3, @2); }
8519                         | b_expr '/' b_expr
8520                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "/", $1, $3, @2); }
8521                         | b_expr '%' b_expr
8522                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "%", $1, $3, @2); }
8523                         | b_expr '^' b_expr
8524                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "^", $1, $3, @2); }
8525                         | b_expr '<' b_expr
8526                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $3, @2); }
8527                         | b_expr '>' b_expr
8528                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $3, @2); }
8529                         | b_expr '=' b_expr
8530                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "=", $1, $3, @2); }
8531                         | b_expr qual_Op b_expr                         %prec Op
8532                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
8533                         | qual_Op b_expr                                        %prec Op
8534                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
8535                         | b_expr qual_Op                                        %prec POSTFIXOP
8536                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
8537                         | b_expr IS DISTINCT FROM b_expr                %prec IS
8538                                 {
8539                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
8540                                 }
8541                         | b_expr IS NOT DISTINCT FROM b_expr    %prec IS
8542                                 {
8543                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL,
8544                                                 NULL, (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $6, @2), @2);
8545                                 }
8546                         | b_expr IS OF '(' type_list ')'                %prec IS
8547                                 {
8548                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
8549                                 }
8550                         | b_expr IS NOT OF '(' type_list ')'    %prec IS
8551                                 {
8552                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
8553                                 }
8554                         | b_expr IS DOCUMENT_P                                  %prec IS
8555                                 {
8556                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8557                                                                          list_make1($1), @2);
8558                                 }
8559                         | b_expr IS NOT DOCUMENT_P                              %prec IS
8560                                 {
8561                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
8562                                                                                          makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8563                                                                                                                  list_make1($1), @2),
8564                                                                                          @2);
8565                                 }
8566                 ;
8567
8568 /*
8569  * Productions that can be used in both a_expr and b_expr.
8570  *
8571  * Note: productions that refer recursively to a_expr or b_expr mostly
8572  * cannot appear here.  However, it's OK to refer to a_exprs that occur
8573  * inside parentheses, such as function arguments; that cannot introduce
8574  * ambiguity to the b_expr syntax.
8575  */
8576 c_expr:         columnref                                                               { $$ = $1; }
8577                         | AexprConst                                                    { $$ = $1; }
8578                         | PARAM opt_indirection
8579                                 {
8580                                         ParamRef *p = makeNode(ParamRef);
8581                                         p->number = $1;
8582                                         p->location = @1;
8583                                         if ($2)
8584                                         {
8585                                                 A_Indirection *n = makeNode(A_Indirection);
8586                                                 n->arg = (Node *) p;
8587                                                 n->indirection = check_indirection($2);
8588                                                 $$ = (Node *) n;
8589                                         }
8590                                         else
8591                                                 $$ = (Node *) p;
8592                                 }
8593                         | '(' a_expr ')' opt_indirection
8594                                 {
8595                                         if ($4)
8596                                         {
8597                                                 A_Indirection *n = makeNode(A_Indirection);
8598                                                 n->arg = $2;
8599                                                 n->indirection = check_indirection($4);
8600                                                 $$ = (Node *)n;
8601                                         }
8602                                         else
8603                                                 $$ = $2;
8604                                 }
8605                         | case_expr
8606                                 { $$ = $1; }
8607                         | func_expr
8608                                 { $$ = $1; }
8609                         | select_with_parens                    %prec UMINUS
8610                                 {
8611                                         SubLink *n = makeNode(SubLink);
8612                                         n->subLinkType = EXPR_SUBLINK;
8613                                         n->testexpr = NULL;
8614                                         n->operName = NIL;
8615                                         n->subselect = $1;
8616                                         n->location = @1;
8617                                         $$ = (Node *)n;
8618                                 }
8619                         | EXISTS select_with_parens
8620                                 {
8621                                         SubLink *n = makeNode(SubLink);
8622                                         n->subLinkType = EXISTS_SUBLINK;
8623                                         n->testexpr = NULL;
8624                                         n->operName = NIL;
8625                                         n->subselect = $2;
8626                                         n->location = @1;
8627                                         $$ = (Node *)n;
8628                                 }
8629                         | ARRAY select_with_parens
8630                                 {
8631                                         SubLink *n = makeNode(SubLink);
8632                                         n->subLinkType = ARRAY_SUBLINK;
8633                                         n->testexpr = NULL;
8634                                         n->operName = NIL;
8635                                         n->subselect = $2;
8636                                         n->location = @1;
8637                                         $$ = (Node *)n;
8638                                 }
8639                         | ARRAY array_expr
8640                                 {
8641                                         A_ArrayExpr *n = (A_ArrayExpr *) $2;
8642                                         Assert(IsA(n, A_ArrayExpr));
8643                                         /* point outermost A_ArrayExpr to the ARRAY keyword */
8644                                         n->location = @1;
8645                                         $$ = (Node *)n;
8646                                 }
8647                         | row
8648                                 {
8649                                         RowExpr *r = makeNode(RowExpr);
8650                                         r->args = $1;
8651                                         r->row_typeid = InvalidOid;     /* not analyzed yet */
8652                                         r->location = @1;
8653                                         $$ = (Node *)r;
8654                                 }
8655                 ;
8656
8657 /*
8658  * func_expr is split out from c_expr just so that we have a classification
8659  * for "everything that is a function call or looks like one".  This isn't
8660  * very important, but it saves us having to document which variants are
8661  * legal in the backwards-compatible functional-index syntax for CREATE INDEX.
8662  * (Note that many of the special SQL functions wouldn't actually make any
8663  * sense as functional index entries, but we ignore that consideration here.)
8664  */
8665 func_expr:      func_name '(' ')' over_clause
8666                                 {
8667                                         FuncCall *n = makeNode(FuncCall);
8668                                         n->funcname = $1;
8669                                         n->args = NIL;
8670                                         n->agg_star = FALSE;
8671                                         n->agg_distinct = FALSE;
8672                                         n->func_variadic = FALSE;
8673                                         n->over = $4;
8674                                         n->location = @1;
8675                                         $$ = (Node *)n;
8676                                 }
8677                         | func_name '(' expr_list ')' over_clause
8678                                 {
8679                                         FuncCall *n = makeNode(FuncCall);
8680                                         n->funcname = $1;
8681                                         n->args = $3;
8682                                         n->agg_star = FALSE;
8683                                         n->agg_distinct = FALSE;
8684                                         n->func_variadic = FALSE;
8685                                         n->over = $5;
8686                                         n->location = @1;
8687                                         $$ = (Node *)n;
8688                                 }
8689                         | func_name '(' VARIADIC a_expr ')' over_clause
8690                                 {
8691                                         FuncCall *n = makeNode(FuncCall);
8692                                         n->funcname = $1;
8693                                         n->args = list_make1($4);
8694                                         n->agg_star = FALSE;
8695                                         n->agg_distinct = FALSE;
8696                                         n->func_variadic = TRUE;
8697                                         n->over = $6;
8698                                         n->location = @1;
8699                                         $$ = (Node *)n;
8700                                 }
8701                         | func_name '(' expr_list ',' VARIADIC a_expr ')' over_clause
8702                                 {
8703                                         FuncCall *n = makeNode(FuncCall);
8704                                         n->funcname = $1;
8705                                         n->args = lappend($3, $6);
8706                                         n->agg_star = FALSE;
8707                                         n->agg_distinct = FALSE;
8708                                         n->func_variadic = TRUE;
8709                                         n->over = $8;
8710                                         n->location = @1;
8711                                         $$ = (Node *)n;
8712                                 }
8713                         | func_name '(' ALL expr_list ')' over_clause
8714                                 {
8715                                         FuncCall *n = makeNode(FuncCall);
8716                                         n->funcname = $1;
8717                                         n->args = $4;
8718                                         n->agg_star = FALSE;
8719                                         n->agg_distinct = FALSE;
8720                                         /* Ideally we'd mark the FuncCall node to indicate
8721                                          * "must be an aggregate", but there's no provision
8722                                          * for that in FuncCall at the moment.
8723                                          */
8724                                         n->func_variadic = FALSE;
8725                                         n->over = $6;
8726                                         n->location = @1;
8727                                         $$ = (Node *)n;
8728                                 }
8729                         | func_name '(' DISTINCT expr_list ')' over_clause
8730                                 {
8731                                         FuncCall *n = makeNode(FuncCall);
8732                                         n->funcname = $1;
8733                                         n->args = $4;
8734                                         n->agg_star = FALSE;
8735                                         n->agg_distinct = TRUE;
8736                                         n->func_variadic = FALSE;
8737                                         n->over = $6;
8738                                         n->location = @1;
8739                                         $$ = (Node *)n;
8740                                 }
8741                         | func_name '(' '*' ')' over_clause
8742                                 {
8743                                         /*
8744                                          * We consider AGGREGATE(*) to invoke a parameterless
8745                                          * aggregate.  This does the right thing for COUNT(*),
8746                                          * and there are no other aggregates in SQL92 that accept
8747                                          * '*' as parameter.
8748                                          *
8749                                          * The FuncCall node is also marked agg_star = true,
8750                                          * so that later processing can detect what the argument
8751                                          * really was.
8752                                          */
8753                                         FuncCall *n = makeNode(FuncCall);
8754                                         n->funcname = $1;
8755                                         n->args = NIL;
8756                                         n->agg_star = TRUE;
8757                                         n->agg_distinct = FALSE;
8758                                         n->func_variadic = FALSE;
8759                                         n->over = $5;
8760                                         n->location = @1;
8761                                         $$ = (Node *)n;
8762                                 }
8763                         | CURRENT_DATE
8764                                 {
8765                                         /*
8766                                          * Translate as "'now'::text::date".
8767                                          *
8768                                          * We cannot use "'now'::date" because coerce_type() will
8769                                          * immediately reduce that to a constant representing
8770                                          * today's date.  We need to delay the conversion until
8771                                          * runtime, else the wrong things will happen when
8772                                          * CURRENT_DATE is used in a column default value or rule.
8773                                          *
8774                                          * This could be simplified if we had a way to generate
8775                                          * an expression tree representing runtime application
8776                                          * of type-input conversion functions.  (As of PG 7.3
8777                                          * that is actually possible, but not clear that we want
8778                                          * to rely on it.)
8779                                          */
8780                                         Node *n;
8781                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8782                                         $$ = makeTypeCast(n, SystemTypeName("date"), -1);
8783                                 }
8784                         | CURRENT_TIME
8785                                 {
8786                                         /*
8787                                          * Translate as "'now'::text::timetz".
8788                                          * See comments for CURRENT_DATE.
8789                                          */
8790                                         Node *n;
8791                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8792                                         $$ = makeTypeCast(n, SystemTypeName("timetz"), -1);
8793                                 }
8794                         | CURRENT_TIME '(' Iconst ')'
8795                                 {
8796                                         /*
8797                                          * Translate as "'now'::text::timetz(n)".
8798                                          * See comments for CURRENT_DATE.
8799                                          */
8800                                         Node *n;
8801                                         TypeName *d;
8802                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8803                                         d = SystemTypeName("timetz");
8804                                         d->typmods = list_make1(makeIntConst($3, @3));
8805                                         $$ = makeTypeCast(n, d, -1);
8806                                 }
8807                         | CURRENT_TIMESTAMP
8808                                 {
8809                                         /*
8810                                          * Translate as "now()", since we have a function that
8811                                          * does exactly what is needed.
8812                                          */
8813                                         FuncCall *n = makeNode(FuncCall);
8814                                         n->funcname = SystemFuncName("now");
8815                                         n->args = NIL;
8816                                         n->agg_star = FALSE;
8817                                         n->agg_distinct = FALSE;
8818                                         n->func_variadic = FALSE;
8819                                         n->over = NULL;
8820                                         n->location = @1;
8821                                         $$ = (Node *)n;
8822                                 }
8823                         | CURRENT_TIMESTAMP '(' Iconst ')'
8824                                 {
8825                                         /*
8826                                          * Translate as "'now'::text::timestamptz(n)".
8827                                          * See comments for CURRENT_DATE.
8828                                          */
8829                                         Node *n;
8830                                         TypeName *d;
8831                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8832                                         d = SystemTypeName("timestamptz");
8833                                         d->typmods = list_make1(makeIntConst($3, @3));
8834                                         $$ = makeTypeCast(n, d, -1);
8835                                 }
8836                         | LOCALTIME
8837                                 {
8838                                         /*
8839                                          * Translate as "'now'::text::time".
8840                                          * See comments for CURRENT_DATE.
8841                                          */
8842                                         Node *n;
8843                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8844                                         $$ = makeTypeCast((Node *)n, SystemTypeName("time"), -1);
8845                                 }
8846                         | LOCALTIME '(' Iconst ')'
8847                                 {
8848                                         /*
8849                                          * Translate as "'now'::text::time(n)".
8850                                          * See comments for CURRENT_DATE.
8851                                          */
8852                                         Node *n;
8853                                         TypeName *d;
8854                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8855                                         d = SystemTypeName("time");
8856                                         d->typmods = list_make1(makeIntConst($3, @3));
8857                                         $$ = makeTypeCast((Node *)n, d, -1);
8858                                 }
8859                         | LOCALTIMESTAMP
8860                                 {
8861                                         /*
8862                                          * Translate as "'now'::text::timestamp".
8863                                          * See comments for CURRENT_DATE.
8864                                          */
8865                                         Node *n;
8866                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8867                                         $$ = makeTypeCast(n, SystemTypeName("timestamp"), -1);
8868                                 }
8869                         | LOCALTIMESTAMP '(' Iconst ')'
8870                                 {
8871                                         /*
8872                                          * Translate as "'now'::text::timestamp(n)".
8873                                          * See comments for CURRENT_DATE.
8874                                          */
8875                                         Node *n;
8876                                         TypeName *d;
8877                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8878                                         d = SystemTypeName("timestamp");
8879                                         d->typmods = list_make1(makeIntConst($3, @3));
8880                                         $$ = makeTypeCast(n, d, -1);
8881                                 }
8882                         | CURRENT_ROLE
8883                                 {
8884                                         FuncCall *n = makeNode(FuncCall);
8885                                         n->funcname = SystemFuncName("current_user");
8886                                         n->args = NIL;
8887                                         n->agg_star = FALSE;
8888                                         n->agg_distinct = FALSE;
8889                                         n->func_variadic = FALSE;
8890                                         n->over = NULL;
8891                                         n->location = @1;
8892                                         $$ = (Node *)n;
8893                                 }
8894                         | CURRENT_USER
8895                                 {
8896                                         FuncCall *n = makeNode(FuncCall);
8897                                         n->funcname = SystemFuncName("current_user");
8898                                         n->args = NIL;
8899                                         n->agg_star = FALSE;
8900                                         n->agg_distinct = FALSE;
8901                                         n->func_variadic = FALSE;
8902                                         n->over = NULL;
8903                                         n->location = @1;
8904                                         $$ = (Node *)n;
8905                                 }
8906                         | SESSION_USER
8907                                 {
8908                                         FuncCall *n = makeNode(FuncCall);
8909                                         n->funcname = SystemFuncName("session_user");
8910                                         n->args = NIL;
8911                                         n->agg_star = FALSE;
8912                                         n->agg_distinct = FALSE;
8913                                         n->func_variadic = FALSE;
8914                                         n->over = NULL;
8915                                         n->location = @1;
8916                                         $$ = (Node *)n;
8917                                 }
8918                         | USER
8919                                 {
8920                                         FuncCall *n = makeNode(FuncCall);
8921                                         n->funcname = SystemFuncName("current_user");
8922                                         n->args = NIL;
8923                                         n->agg_star = FALSE;
8924                                         n->agg_distinct = FALSE;
8925                                         n->func_variadic = FALSE;
8926                                         n->over = NULL;
8927                                         n->location = @1;
8928                                         $$ = (Node *)n;
8929                                 }
8930                         | CURRENT_CATALOG
8931                                 {
8932                                         FuncCall *n = makeNode(FuncCall);
8933                                         n->funcname = SystemFuncName("current_database");
8934                                         n->args = NIL;
8935                                         n->agg_star = FALSE;
8936                                         n->agg_distinct = FALSE;
8937                                         n->func_variadic = FALSE;
8938                                         n->over = NULL;
8939                                         n->location = @1;
8940                                         $$ = (Node *)n;
8941                                 }
8942                         | CURRENT_SCHEMA
8943                                 {
8944                                         FuncCall *n = makeNode(FuncCall);
8945                                         n->funcname = SystemFuncName("current_schema");
8946                                         n->args = NIL;
8947                                         n->agg_star = FALSE;
8948                                         n->agg_distinct = FALSE;
8949                                         n->func_variadic = FALSE;
8950                                         n->over = NULL;
8951                                         n->location = @1;
8952                                         $$ = (Node *)n;
8953                                 }
8954                         | CAST '(' a_expr AS Typename ')'
8955                                 { $$ = makeTypeCast($3, $5, @1); }
8956                         | EXTRACT '(' extract_list ')'
8957                                 {
8958                                         FuncCall *n = makeNode(FuncCall);
8959                                         n->funcname = SystemFuncName("date_part");
8960                                         n->args = $3;
8961                                         n->agg_star = FALSE;
8962                                         n->agg_distinct = FALSE;
8963                                         n->func_variadic = FALSE;
8964                                         n->over = NULL;
8965                                         n->location = @1;
8966                                         $$ = (Node *)n;
8967                                 }
8968                         | OVERLAY '(' overlay_list ')'
8969                                 {
8970                                         /* overlay(A PLACING B FROM C FOR D) is converted to
8971                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+D)
8972                                          * overlay(A PLACING B FROM C) is converted to
8973                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+char_length(B))
8974                                          */
8975                                         FuncCall *n = makeNode(FuncCall);
8976                                         n->funcname = SystemFuncName("overlay");
8977                                         n->args = $3;
8978                                         n->agg_star = FALSE;
8979                                         n->agg_distinct = FALSE;
8980                                         n->func_variadic = FALSE;
8981                                         n->over = NULL;
8982                                         n->location = @1;
8983                                         $$ = (Node *)n;
8984                                 }
8985                         | POSITION '(' position_list ')'
8986                                 {
8987                                         /* position(A in B) is converted to position(B, A) */
8988                                         FuncCall *n = makeNode(FuncCall);
8989                                         n->funcname = SystemFuncName("position");
8990                                         n->args = $3;
8991                                         n->agg_star = FALSE;
8992                                         n->agg_distinct = FALSE;
8993                                         n->func_variadic = FALSE;
8994                                         n->over = NULL;
8995                                         n->location = @1;
8996                                         $$ = (Node *)n;
8997                                 }
8998                         | SUBSTRING '(' substr_list ')'
8999                                 {
9000                                         /* substring(A from B for C) is converted to
9001                                          * substring(A, B, C) - thomas 2000-11-28
9002                                          */
9003                                         FuncCall *n = makeNode(FuncCall);
9004                                         n->funcname = SystemFuncName("substring");
9005                                         n->args = $3;
9006                                         n->agg_star = FALSE;
9007                                         n->agg_distinct = FALSE;
9008                                         n->func_variadic = FALSE;
9009                                         n->over = NULL;
9010                                         n->location = @1;
9011                                         $$ = (Node *)n;
9012                                 }
9013                         | TREAT '(' a_expr AS Typename ')'
9014                                 {
9015                                         /* TREAT(expr AS target) converts expr of a particular type to target,
9016                                          * which is defined to be a subtype of the original expression.
9017                                          * In SQL99, this is intended for use with structured UDTs,
9018                                          * but let's make this a generally useful form allowing stronger
9019                                          * coercions than are handled by implicit casting.
9020                                          */
9021                                         FuncCall *n = makeNode(FuncCall);
9022                                         /* Convert SystemTypeName() to SystemFuncName() even though
9023                                          * at the moment they result in the same thing.
9024                                          */
9025                                         n->funcname = SystemFuncName(((Value *)llast($5->names))->val.str);
9026                                         n->args = list_make1($3);
9027                                         n->agg_star = FALSE;
9028                                         n->agg_distinct = FALSE;
9029                                         n->func_variadic = FALSE;
9030                                         n->over = NULL;
9031                                         n->location = @1;
9032                                         $$ = (Node *)n;
9033                                 }
9034                         | TRIM '(' BOTH trim_list ')'
9035                                 {
9036                                         /* various trim expressions are defined in SQL92
9037                                          * - thomas 1997-07-19
9038                                          */
9039                                         FuncCall *n = makeNode(FuncCall);
9040                                         n->funcname = SystemFuncName("btrim");
9041                                         n->args = $4;
9042                                         n->agg_star = FALSE;
9043                                         n->agg_distinct = FALSE;
9044                                         n->func_variadic = FALSE;
9045                                         n->over = NULL;
9046                                         n->location = @1;
9047                                         $$ = (Node *)n;
9048                                 }
9049                         | TRIM '(' LEADING trim_list ')'
9050                                 {
9051                                         FuncCall *n = makeNode(FuncCall);
9052                                         n->funcname = SystemFuncName("ltrim");
9053                                         n->args = $4;
9054                                         n->agg_star = FALSE;
9055                                         n->agg_distinct = FALSE;
9056                                         n->func_variadic = FALSE;
9057                                         n->over = NULL;
9058                                         n->location = @1;
9059                                         $$ = (Node *)n;
9060                                 }
9061                         | TRIM '(' TRAILING trim_list ')'
9062                                 {
9063                                         FuncCall *n = makeNode(FuncCall);
9064                                         n->funcname = SystemFuncName("rtrim");
9065                                         n->args = $4;
9066                                         n->agg_star = FALSE;
9067                                         n->agg_distinct = FALSE;
9068                                         n->func_variadic = FALSE;
9069                                         n->over = NULL;
9070                                         n->location = @1;
9071                                         $$ = (Node *)n;
9072                                 }
9073                         | TRIM '(' trim_list ')'
9074                                 {
9075                                         FuncCall *n = makeNode(FuncCall);
9076                                         n->funcname = SystemFuncName("btrim");
9077                                         n->args = $3;
9078                                         n->agg_star = FALSE;
9079                                         n->agg_distinct = FALSE;
9080                                         n->func_variadic = FALSE;
9081                                         n->over = NULL;
9082                                         n->location = @1;
9083                                         $$ = (Node *)n;
9084                                 }
9085                         | NULLIF '(' a_expr ',' a_expr ')'
9086                                 {
9087                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_NULLIF, "=", $3, $5, @1);
9088                                 }
9089                         | COALESCE '(' expr_list ')'
9090                                 {
9091                                         CoalesceExpr *c = makeNode(CoalesceExpr);
9092                                         c->args = $3;
9093                                         c->location = @1;
9094                                         $$ = (Node *)c;
9095                                 }
9096                         | GREATEST '(' expr_list ')'
9097                                 {
9098                                         MinMaxExpr *v = makeNode(MinMaxExpr);
9099                                         v->args = $3;
9100                                         v->op = IS_GREATEST;
9101                                         v->location = @1;
9102                                         $$ = (Node *)v;
9103                                 }
9104                         | LEAST '(' expr_list ')'
9105                                 {
9106                                         MinMaxExpr *v = makeNode(MinMaxExpr);
9107                                         v->args = $3;
9108                                         v->op = IS_LEAST;
9109                                         v->location = @1;
9110                                         $$ = (Node *)v;
9111                                 }
9112                         | XMLCONCAT '(' expr_list ')'
9113                                 {
9114                                         $$ = makeXmlExpr(IS_XMLCONCAT, NULL, NIL, $3, @1);
9115                                 }
9116                         | XMLELEMENT '(' NAME_P ColLabel ')'
9117                                 {
9118                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, NIL, @1);
9119                                 }
9120                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ')'
9121                                 {
9122                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, NIL, @1);
9123                                 }
9124                         | XMLELEMENT '(' NAME_P ColLabel ',' expr_list ')'
9125                                 {
9126                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, $6, @1);
9127                                 }
9128                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ',' expr_list ')'
9129                                 {
9130                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, $8, @1);
9131                                 }
9132                         | XMLFOREST '(' xml_attribute_list ')'
9133                                 {
9134                                         $$ = makeXmlExpr(IS_XMLFOREST, NULL, $3, NIL, @1);
9135                                 }
9136                         | XMLPARSE '(' document_or_content a_expr xml_whitespace_option ')'
9137                                 {
9138                                         XmlExpr *x = (XmlExpr *)
9139                                                 makeXmlExpr(IS_XMLPARSE, NULL, NIL,
9140                                                                         list_make2($4, makeBoolAConst($5, -1)),
9141                                                                         @1);
9142                                         x->xmloption = $3;
9143                                         $$ = (Node *)x;
9144                                 }
9145                         | XMLPI '(' NAME_P ColLabel ')'
9146                                 {
9147                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, NIL, @1);
9148                                 }
9149                         | XMLPI '(' NAME_P ColLabel ',' a_expr ')'
9150                                 {
9151                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, list_make1($6), @1);
9152                                 }
9153                         | XMLROOT '(' a_expr ',' xml_root_version opt_xml_root_standalone ')'
9154                                 {
9155                                         $$ = makeXmlExpr(IS_XMLROOT, NULL, NIL,
9156                                                                          list_make3($3, $5, $6), @1);
9157                                 }
9158                         | XMLSERIALIZE '(' document_or_content a_expr AS SimpleTypename ')'
9159                                 {
9160                                         XmlSerialize *n = makeNode(XmlSerialize);
9161                                         n->xmloption = $3;
9162                                         n->expr = $4;
9163                                         n->typename = $6;
9164                                         n->location = @1;
9165                                         $$ = (Node *)n;
9166                                 }
9167                 ;
9168
9169 /*
9170  * SQL/XML support
9171  */
9172 xml_root_version: VERSION_P a_expr
9173                                 { $$ = $2; }
9174                         | VERSION_P NO VALUE_P
9175                                 { $$ = makeNullAConst(-1); }
9176                 ;
9177
9178 opt_xml_root_standalone: ',' STANDALONE_P YES_P
9179                                 { $$ = makeIntConst(XML_STANDALONE_YES, -1); }
9180                         | ',' STANDALONE_P NO
9181                                 { $$ = makeIntConst(XML_STANDALONE_NO, -1); }
9182                         | ',' STANDALONE_P NO VALUE_P
9183                                 { $$ = makeIntConst(XML_STANDALONE_NO_VALUE, -1); }
9184                         | /*EMPTY*/
9185                                 { $$ = makeIntConst(XML_STANDALONE_OMITTED, -1); }
9186                 ;
9187
9188 xml_attributes: XMLATTRIBUTES '(' xml_attribute_list ')'        { $$ = $3; }
9189                 ;
9190
9191 xml_attribute_list:     xml_attribute_el                                        { $$ = list_make1($1); }
9192                         | xml_attribute_list ',' xml_attribute_el       { $$ = lappend($1, $3); }
9193                 ;
9194
9195 xml_attribute_el: a_expr AS ColLabel
9196                                 {
9197                                         $$ = makeNode(ResTarget);
9198                                         $$->name = $3;
9199                                         $$->indirection = NIL;
9200                                         $$->val = (Node *) $1;
9201                                         $$->location = @1;
9202                                 }
9203                         | a_expr
9204                                 {
9205                                         $$ = makeNode(ResTarget);
9206                                         $$->name = NULL;
9207                                         $$->indirection = NIL;
9208                                         $$->val = (Node *) $1;
9209                                         $$->location = @1;
9210                                 }
9211                 ;
9212
9213 document_or_content: DOCUMENT_P                                         { $$ = XMLOPTION_DOCUMENT; }
9214                         | CONTENT_P                                                             { $$ = XMLOPTION_CONTENT; }
9215                 ;
9216
9217 xml_whitespace_option: PRESERVE WHITESPACE_P            { $$ = TRUE; }
9218                         | STRIP_P WHITESPACE_P                                  { $$ = FALSE; }
9219                         | /*EMPTY*/                                                             { $$ = FALSE; }
9220                 ;
9221
9222 /*
9223  * Window Definitions
9224  */
9225 window_clause:
9226                         WINDOW window_definition_list                   { $$ = $2; }
9227                         | /*EMPTY*/                                                             { $$ = NIL; }
9228                 ;
9229
9230 window_definition_list:
9231                         window_definition                                               { $$ = list_make1($1); }
9232                         | window_definition_list ',' window_definition
9233                                                                                                         { $$ = lappend($1, $3); }
9234                 ;
9235
9236 window_definition:
9237                         ColId AS window_specification
9238                                 {
9239                                         WindowDef *n = $3;
9240                                         n->name = $1;
9241                                         $$ = n;
9242                                 }
9243                 ;
9244
9245 over_clause: OVER window_specification
9246                                 { $$ = $2; }
9247                         | OVER ColId
9248                                 {
9249                                         WindowDef *n = makeNode(WindowDef);
9250                                         n->name = $2;
9251                                         n->refname = NULL;
9252                                         n->partitionClause = NIL;
9253                                         n->orderClause = NIL;
9254                                         n->frameOptions = FRAMEOPTION_DEFAULTS;
9255                                         n->location = @2;
9256                                         $$ = n;
9257                                 }
9258                         | /*EMPTY*/
9259                                 { $$ = NULL; }
9260                 ;
9261
9262 window_specification: '(' opt_existing_window_name opt_partition_clause
9263                                                 opt_sort_clause opt_frame_clause ')'
9264                                 {
9265                                         WindowDef *n = makeNode(WindowDef);
9266                                         n->name = NULL;
9267                                         n->refname = $2;
9268                                         n->partitionClause = $3;
9269                                         n->orderClause = $4;
9270                                         n->frameOptions = $5;
9271                                         n->location = @1;
9272                                         $$ = n;
9273                                 }
9274                 ;
9275
9276 /*
9277  * If we see PARTITION, RANGE, or ROWS as the first token after the '('
9278  * of a window_specification, we want the assumption to be that there is
9279  * no existing_window_name; but those keywords are unreserved and so could
9280  * be ColIds.  We fix this by making them have the same precedence as IDENT
9281  * and giving the empty production here a slightly higher precedence, so
9282  * that the shift/reduce conflict is resolved in favor of reducing the rule.
9283  * These keywords are thus precluded from being an existing_window_name but
9284  * are not reserved for any other purpose.
9285  */
9286 opt_existing_window_name: ColId                                         { $$ = $1; }
9287                         | /*EMPTY*/                             %prec Op                { $$ = NULL; }
9288                 ;
9289
9290 opt_partition_clause: PARTITION BY expr_list            { $$ = $3; }
9291                         | /*EMPTY*/                                                             { $$ = NIL; }
9292                 ;
9293
9294 /*
9295  * This is only a subset of the full SQL:2008 frame_clause grammar.
9296  * We don't support <expression> PRECEDING, <expression> FOLLOWING,
9297  * nor <window frame exclusion> yet.
9298  */
9299 opt_frame_clause:
9300                         RANGE frame_extent
9301                                 {
9302                                         $$ = FRAMEOPTION_NONDEFAULT | FRAMEOPTION_RANGE | $2;
9303                                 }
9304                         | ROWS frame_extent
9305                                 {
9306                                         $$ = FRAMEOPTION_NONDEFAULT | FRAMEOPTION_ROWS | $2;
9307                                 }
9308                         | /*EMPTY*/
9309                                 { $$ = FRAMEOPTION_DEFAULTS; }
9310                 ;
9311
9312 frame_extent: frame_bound
9313                                 {
9314                                         /* reject invalid cases */
9315                                         if ($1 & FRAMEOPTION_START_UNBOUNDED_FOLLOWING)
9316                                                 ereport(ERROR,
9317                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
9318                                                                  errmsg("frame start cannot be UNBOUNDED FOLLOWING"),
9319                                                                  scanner_errposition(@1)));
9320                                         if ($1 & FRAMEOPTION_START_CURRENT_ROW)
9321                                                 ereport(ERROR,
9322                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9323                                                                  errmsg("frame start at CURRENT ROW is not implemented"),
9324                                                                  scanner_errposition(@1)));
9325                                         $$ = $1 | FRAMEOPTION_END_CURRENT_ROW;
9326                                 }
9327                         | BETWEEN frame_bound AND frame_bound
9328                                 {
9329                                         /* reject invalid cases */
9330                                         if ($2 & FRAMEOPTION_START_UNBOUNDED_FOLLOWING)
9331                                                 ereport(ERROR,
9332                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
9333                                                                  errmsg("frame start cannot be UNBOUNDED FOLLOWING"),
9334                                                                  scanner_errposition(@2)));
9335                                         if ($2 & FRAMEOPTION_START_CURRENT_ROW)
9336                                                 ereport(ERROR,
9337                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
9338                                                                  errmsg("frame start at CURRENT ROW is not implemented"),
9339                                                                  scanner_errposition(@2)));
9340                                         if ($4 & FRAMEOPTION_START_UNBOUNDED_PRECEDING)
9341                                                 ereport(ERROR,
9342                                                                 (errcode(ERRCODE_WINDOWING_ERROR),
9343                                                                  errmsg("frame end cannot be UNBOUNDED PRECEDING"),
9344                                                                  scanner_errposition(@4)));
9345                                         /* shift converts START_ options to END_ options */
9346                                         $$ = FRAMEOPTION_BETWEEN | $2 | ($4 << 1);
9347                                 }
9348                 ;
9349
9350 /*
9351  * This is used for both frame start and frame end, with output set up on
9352  * the assumption it's frame start; the frame_extent productions must reject
9353  * invalid cases.
9354  */
9355 frame_bound:
9356                         UNBOUNDED PRECEDING
9357                                 {
9358                                         $$ = FRAMEOPTION_START_UNBOUNDED_PRECEDING;
9359                                 }
9360                         | UNBOUNDED FOLLOWING
9361                                 {
9362                                         $$ = FRAMEOPTION_START_UNBOUNDED_FOLLOWING;
9363                                 }
9364                         | CURRENT_P ROW
9365                                 {
9366                                         $$ = FRAMEOPTION_START_CURRENT_ROW;
9367                                 }
9368                 ;
9369
9370
9371 /*
9372  * Supporting nonterminals for expressions.
9373  */
9374
9375 /* Explicit row production.
9376  *
9377  * SQL99 allows an optional ROW keyword, so we can now do single-element rows
9378  * without conflicting with the parenthesized a_expr production.  Without the
9379  * ROW keyword, there must be more than one a_expr inside the parens.
9380  */
9381 row:            ROW '(' expr_list ')'                                   { $$ = $3; }
9382                         | ROW '(' ')'                                                   { $$ = NIL; }
9383                         | '(' expr_list ',' a_expr ')'                  { $$ = lappend($2, $4); }
9384                 ;
9385
9386 sub_type:       ANY                                                                             { $$ = ANY_SUBLINK; }
9387                         | SOME                                                                  { $$ = ANY_SUBLINK; }
9388                         | ALL                                                                   { $$ = ALL_SUBLINK; }
9389                 ;
9390
9391 all_Op:         Op                                                                              { $$ = $1; }
9392                         | MathOp                                                                { $$ = $1; }
9393                 ;
9394
9395 MathOp:          '+'                                                                    { $$ = "+"; }
9396                         | '-'                                                                   { $$ = "-"; }
9397                         | '*'                                                                   { $$ = "*"; }
9398                         | '/'                                                                   { $$ = "/"; }
9399                         | '%'                                                                   { $$ = "%"; }
9400                         | '^'                                                                   { $$ = "^"; }
9401                         | '<'                                                                   { $$ = "<"; }
9402                         | '>'                                                                   { $$ = ">"; }
9403                         | '='                                                                   { $$ = "="; }
9404                 ;
9405
9406 qual_Op:        Op
9407                                         { $$ = list_make1(makeString($1)); }
9408                         | OPERATOR '(' any_operator ')'
9409                                         { $$ = $3; }
9410                 ;
9411
9412 qual_all_Op:
9413                         all_Op
9414                                         { $$ = list_make1(makeString($1)); }
9415                         | OPERATOR '(' any_operator ')'
9416                                         { $$ = $3; }
9417                 ;
9418
9419 subquery_Op:
9420                         all_Op
9421                                         { $$ = list_make1(makeString($1)); }
9422                         | OPERATOR '(' any_operator ')'
9423                                         { $$ = $3; }
9424                         | LIKE
9425                                         { $$ = list_make1(makeString("~~")); }
9426                         | NOT LIKE
9427                                         { $$ = list_make1(makeString("!~~")); }
9428                         | ILIKE
9429                                         { $$ = list_make1(makeString("~~*")); }
9430                         | NOT ILIKE
9431                                         { $$ = list_make1(makeString("!~~*")); }
9432 /* cannot put SIMILAR TO here, because SIMILAR TO is a hack.
9433  * the regular expression is preprocessed by a function (similar_escape),
9434  * and the ~ operator for posix regular expressions is used.
9435  *        x SIMILAR TO y     ->    x ~ similar_escape(y)
9436  * this transformation is made on the fly by the parser upwards.
9437  * however the SubLink structure which handles any/some/all stuff
9438  * is not ready for such a thing.
9439  */
9440                         ;
9441
9442 expr_list:      a_expr
9443                                 {
9444                                         $$ = list_make1($1);
9445                                 }
9446                         | expr_list ',' a_expr
9447                                 {
9448                                         $$ = lappend($1, $3);
9449                                 }
9450                 ;
9451
9452 type_list:      Typename                                                                { $$ = list_make1($1); }
9453                         | type_list ',' Typename                                { $$ = lappend($1, $3); }
9454                 ;
9455
9456 array_expr: '[' expr_list ']'
9457                                 {
9458                                         $$ = makeAArrayExpr($2, @1);
9459                                 }
9460                         | '[' array_expr_list ']'
9461                                 {
9462                                         $$ = makeAArrayExpr($2, @1);
9463                                 }
9464                         | '[' ']'
9465                                 {
9466                                         $$ = makeAArrayExpr(NIL, @1);
9467                                 }
9468                 ;
9469
9470 array_expr_list: array_expr                                                     { $$ = list_make1($1); }
9471                         | array_expr_list ',' array_expr                { $$ = lappend($1, $3); }
9472                 ;
9473
9474
9475 extract_list:
9476                         extract_arg FROM a_expr
9477                                 {
9478                                         $$ = list_make2(makeStringConst($1, @1), $3);
9479                                 }
9480                         | /*EMPTY*/                                                             { $$ = NIL; }
9481                 ;
9482
9483 /* Allow delimited string Sconst in extract_arg as an SQL extension.
9484  * - thomas 2001-04-12
9485  */
9486 extract_arg:
9487                         IDENT                                                                   { $$ = $1; }
9488                         | YEAR_P                                                                { $$ = "year"; }
9489                         | MONTH_P                                                               { $$ = "month"; }
9490                         | DAY_P                                                                 { $$ = "day"; }
9491                         | HOUR_P                                                                { $$ = "hour"; }
9492                         | MINUTE_P                                                              { $$ = "minute"; }
9493                         | SECOND_P                                                              { $$ = "second"; }
9494                         | Sconst                                                                { $$ = $1; }
9495                 ;
9496
9497 /* OVERLAY() arguments
9498  * SQL99 defines the OVERLAY() function:
9499  * o overlay(text placing text from int for int)
9500  * o overlay(text placing text from int)
9501  */
9502 overlay_list:
9503                         a_expr overlay_placing substr_from substr_for
9504                                 {
9505                                         $$ = list_make4($1, $2, $3, $4);
9506                                 }
9507                         | a_expr overlay_placing substr_from
9508                                 {
9509                                         $$ = list_make3($1, $2, $3);
9510                                 }
9511                 ;
9512
9513 overlay_placing:
9514                         PLACING a_expr
9515                                 { $$ = $2; }
9516                 ;
9517
9518 /* position_list uses b_expr not a_expr to avoid conflict with general IN */
9519
9520 position_list:
9521                         b_expr IN_P b_expr                                              { $$ = list_make2($3, $1); }
9522                         | /*EMPTY*/                                                             { $$ = NIL; }
9523                 ;
9524
9525 /* SUBSTRING() arguments
9526  * SQL9x defines a specific syntax for arguments to SUBSTRING():
9527  * o substring(text from int for int)
9528  * o substring(text from int) get entire string from starting point "int"
9529  * o substring(text for int) get first "int" characters of string
9530  * o substring(text from pattern) get entire string matching pattern
9531  * o substring(text from pattern for escape) same with specified escape char
9532  * We also want to support generic substring functions which accept
9533  * the usual generic list of arguments. So we will accept both styles
9534  * here, and convert the SQL9x style to the generic list for further
9535  * processing. - thomas 2000-11-28
9536  */
9537 substr_list:
9538                         a_expr substr_from substr_for
9539                                 {
9540                                         $$ = list_make3($1, $2, $3);
9541                                 }
9542                         | a_expr substr_for substr_from
9543                                 {
9544                                         /* not legal per SQL99, but might as well allow it */
9545                                         $$ = list_make3($1, $3, $2);
9546                                 }
9547                         | a_expr substr_from
9548                                 {
9549                                         $$ = list_make2($1, $2);
9550                                 }
9551                         | a_expr substr_for
9552                                 {
9553                                         /*
9554                                          * Since there are no cases where this syntax allows
9555                                          * a textual FOR value, we forcibly cast the argument
9556                                          * to int4.  The possible matches in pg_proc are
9557                                          * substring(text,int4) and substring(text,text),
9558                                          * and we don't want the parser to choose the latter,
9559                                          * which it is likely to do if the second argument
9560                                          * is unknown or doesn't have an implicit cast to int4.
9561                                          */
9562                                         $$ = list_make3($1, makeIntConst(1, -1),
9563                                                                         makeTypeCast($2,
9564                                                                                                  SystemTypeName("int4"), -1));
9565                                 }
9566                         | expr_list
9567                                 {
9568                                         $$ = $1;
9569                                 }
9570                         | /*EMPTY*/
9571                                 { $$ = NIL; }
9572                 ;
9573
9574 substr_from:
9575                         FROM a_expr                                                             { $$ = $2; }
9576                 ;
9577
9578 substr_for: FOR a_expr                                                          { $$ = $2; }
9579                 ;
9580
9581 trim_list:      a_expr FROM expr_list                                   { $$ = lappend($3, $1); }
9582                         | FROM expr_list                                                { $$ = $2; }
9583                         | expr_list                                                             { $$ = $1; }
9584                 ;
9585
9586 in_expr:        select_with_parens
9587                                 {
9588                                         SubLink *n = makeNode(SubLink);
9589                                         n->subselect = $1;
9590                                         /* other fields will be filled later */
9591                                         $$ = (Node *)n;
9592                                 }
9593                         | '(' expr_list ')'                                             { $$ = (Node *)$2; }
9594                 ;
9595
9596 /*
9597  * Define SQL92-style case clause.
9598  * - Full specification
9599  *      CASE WHEN a = b THEN c ... ELSE d END
9600  * - Implicit argument
9601  *      CASE a WHEN b THEN c ... ELSE d END
9602  */
9603 case_expr:      CASE case_arg when_clause_list case_default END_P
9604                                 {
9605                                         CaseExpr *c = makeNode(CaseExpr);
9606                                         c->casetype = InvalidOid; /* not analyzed yet */
9607                                         c->arg = (Expr *) $2;
9608                                         c->args = $3;
9609                                         c->defresult = (Expr *) $4;
9610                                         c->location = @1;
9611                                         $$ = (Node *)c;
9612                                 }
9613                 ;
9614
9615 when_clause_list:
9616                         /* There must be at least one */
9617                         when_clause                                                             { $$ = list_make1($1); }
9618                         | when_clause_list when_clause                  { $$ = lappend($1, $2); }
9619                 ;
9620
9621 when_clause:
9622                         WHEN a_expr THEN a_expr
9623                                 {
9624                                         CaseWhen *w = makeNode(CaseWhen);
9625                                         w->expr = (Expr *) $2;
9626                                         w->result = (Expr *) $4;
9627                                         w->location = @1;
9628                                         $$ = (Node *)w;
9629                                 }
9630                 ;
9631
9632 case_default:
9633                         ELSE a_expr                                                             { $$ = $2; }
9634                         | /*EMPTY*/                                                             { $$ = NULL; }
9635                 ;
9636
9637 case_arg:       a_expr                                                                  { $$ = $1; }
9638                         | /*EMPTY*/                                                             { $$ = NULL; }
9639                 ;
9640
9641 /*
9642  * columnref starts with relation_name not ColId, so that OLD and NEW
9643  * references can be accepted.  Note that when there are more than two
9644  * dotted names, the first name is not actually a relation name...
9645  */
9646 columnref:      relation_name
9647                                 {
9648                                         $$ = makeColumnRef($1, NIL, @1);
9649                                 }
9650                         | relation_name indirection
9651                                 {
9652                                         $$ = makeColumnRef($1, $2, @1);
9653                                 }
9654                 ;
9655
9656 indirection_el:
9657                         '.' attr_name
9658                                 {
9659                                         $$ = (Node *) makeString($2);
9660                                 }
9661                         | '.' '*'
9662                                 {
9663                                         $$ = (Node *) makeNode(A_Star);
9664                                 }
9665                         | '[' a_expr ']'
9666                                 {
9667                                         A_Indices *ai = makeNode(A_Indices);
9668                                         ai->lidx = NULL;
9669                                         ai->uidx = $2;
9670                                         $$ = (Node *) ai;
9671                                 }
9672                         | '[' a_expr ':' a_expr ']'
9673                                 {
9674                                         A_Indices *ai = makeNode(A_Indices);
9675                                         ai->lidx = $2;
9676                                         ai->uidx = $4;
9677                                         $$ = (Node *) ai;
9678                                 }
9679                 ;
9680
9681 indirection:
9682                         indirection_el                                                  { $$ = list_make1($1); }
9683                         | indirection indirection_el                    { $$ = lappend($1, $2); }
9684                 ;
9685
9686 opt_indirection:
9687                         /*EMPTY*/                                                               { $$ = NIL; }
9688                         | opt_indirection indirection_el                { $$ = lappend($1, $2); }
9689                 ;
9690
9691 opt_asymmetric: ASYMMETRIC
9692                         | /*EMPTY*/
9693                 ;
9694
9695 /*
9696  * The SQL spec defines "contextually typed value expressions" and
9697  * "contextually typed row value constructors", which for our purposes
9698  * are the same as "a_expr" and "row" except that DEFAULT can appear at
9699  * the top level.
9700  */
9701
9702 ctext_expr:
9703                         a_expr                                  { $$ = (Node *) $1; }
9704                         | DEFAULT
9705                                 {
9706                                         SetToDefault *n = makeNode(SetToDefault);
9707                                         n->location = @1;
9708                                         $$ = (Node *) n;
9709                                 }
9710                 ;
9711
9712 ctext_expr_list:
9713                         ctext_expr                                                              { $$ = list_make1($1); }
9714                         | ctext_expr_list ',' ctext_expr                { $$ = lappend($1, $3); }
9715                 ;
9716
9717 /*
9718  * We should allow ROW '(' ctext_expr_list ')' too, but that seems to require
9719  * making VALUES a fully reserved word, which will probably break more apps
9720  * than allowing the noise-word is worth.
9721  */
9722 ctext_row: '(' ctext_expr_list ')'                                      { $$ = $2; }
9723                 ;
9724
9725
9726 /*****************************************************************************
9727  *
9728  *      target list for SELECT
9729  *
9730  *****************************************************************************/
9731
9732 target_list:
9733                         target_el                                                               { $$ = list_make1($1); }
9734                         | target_list ',' target_el                             { $$ = lappend($1, $3); }
9735                 ;
9736
9737 target_el:      a_expr AS ColLabel
9738                                 {
9739                                         $$ = makeNode(ResTarget);
9740                                         $$->name = $3;
9741                                         $$->indirection = NIL;
9742                                         $$->val = (Node *)$1;
9743                                         $$->location = @1;
9744                                 }
9745                         /*
9746                          * We support omitting AS only for column labels that aren't
9747                          * any known keyword.  There is an ambiguity against postfix
9748                          * operators: is "a ! b" an infix expression, or a postfix
9749                          * expression and a column label?  We prefer to resolve this
9750                          * as an infix expression, which we accomplish by assigning
9751                          * IDENT a precedence higher than POSTFIXOP.
9752                          */
9753                         | a_expr IDENT
9754                                 {
9755                                         $$ = makeNode(ResTarget);
9756                                         $$->name = $2;
9757                                         $$->indirection = NIL;
9758                                         $$->val = (Node *)$1;
9759                                         $$->location = @1;
9760                                 }
9761                         | a_expr
9762                                 {
9763                                         $$ = makeNode(ResTarget);
9764                                         $$->name = NULL;
9765                                         $$->indirection = NIL;
9766                                         $$->val = (Node *)$1;
9767                                         $$->location = @1;
9768                                 }
9769                         | '*'
9770                                 {
9771                                         ColumnRef *n = makeNode(ColumnRef);
9772                                         n->fields = list_make1(makeNode(A_Star));
9773                                         n->location = @1;
9774
9775                                         $$ = makeNode(ResTarget);
9776                                         $$->name = NULL;
9777                                         $$->indirection = NIL;
9778                                         $$->val = (Node *)n;
9779                                         $$->location = @1;
9780                                 }
9781                 ;
9782
9783
9784 /*****************************************************************************
9785  *
9786  *      Names and constants
9787  *
9788  *****************************************************************************/
9789
9790 relation_name:
9791                         SpecialRuleRelation                                             { $$ = $1; }
9792                         | ColId                                                                 { $$ = $1; }
9793                 ;
9794
9795 qualified_name_list:
9796                         qualified_name                                                  { $$ = list_make1($1); }
9797                         | qualified_name_list ',' qualified_name { $$ = lappend($1, $3); }
9798                 ;
9799
9800 /*
9801  * The production for a qualified relation name has to exactly match the
9802  * production for a qualified func_name, because in a FROM clause we cannot
9803  * tell which we are parsing until we see what comes after it ('(' for a
9804  * func_name, something else for a relation). Therefore we allow 'indirection'
9805  * which may contain subscripts, and reject that case in the C code.
9806  */
9807 qualified_name:
9808                         relation_name
9809                                 {
9810                                         $$ = makeNode(RangeVar);
9811                                         $$->catalogname = NULL;
9812                                         $$->schemaname = NULL;
9813                                         $$->relname = $1;
9814                                         $$->location = @1;
9815                                 }
9816                         | relation_name indirection
9817                                 {
9818                                         check_qualified_name($2);
9819                                         $$ = makeNode(RangeVar);
9820                                         switch (list_length($2))
9821                                         {
9822                                                 case 1:
9823                                                         $$->catalogname = NULL;
9824                                                         $$->schemaname = $1;
9825                                                         $$->relname = strVal(linitial($2));
9826                                                         break;
9827                                                 case 2:
9828                                                         $$->catalogname = $1;
9829                                                         $$->schemaname = strVal(linitial($2));
9830                                                         $$->relname = strVal(lsecond($2));
9831                                                         break;
9832                                                 default:
9833                                                         ereport(ERROR,
9834                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
9835                                                                          errmsg("improper qualified name (too many dotted names): %s",
9836                                                                                         NameListToString(lcons(makeString($1), $2))),
9837                                                                          scanner_errposition(@1)));
9838                                                         break;
9839                                         }
9840                                         $$->location = @1;
9841                                 }
9842                 ;
9843
9844 name_list:      name
9845                                         { $$ = list_make1(makeString($1)); }
9846                         | name_list ',' name
9847                                         { $$ = lappend($1, makeString($3)); }
9848                 ;
9849
9850
9851 name:           ColId                                                                   { $$ = $1; };
9852
9853 database_name:
9854                         ColId                                                                   { $$ = $1; };
9855
9856 access_method:
9857                         ColId                                                                   { $$ = $1; };
9858
9859 attr_name:      ColLabel                                                                { $$ = $1; };
9860
9861 index_name: ColId                                                                       { $$ = $1; };
9862
9863 file_name:      Sconst                                                                  { $$ = $1; };
9864
9865 /*
9866  * The production for a qualified func_name has to exactly match the
9867  * production for a qualified columnref, because we cannot tell which we
9868  * are parsing until we see what comes after it ('(' or Sconst for a func_name,
9869  * anything else for a columnref).  Therefore we allow 'indirection' which
9870  * may contain subscripts, and reject that case in the C code.  (If we
9871  * ever implement SQL99-like methods, such syntax may actually become legal!)
9872  */
9873 func_name:      type_function_name
9874                                         { $$ = list_make1(makeString($1)); }
9875                         | relation_name indirection
9876                                         { $$ = check_func_name(lcons(makeString($1), $2)); }
9877                 ;
9878
9879
9880 /*
9881  * Constants
9882  */
9883 AexprConst: Iconst
9884                                 {
9885                                         $$ = makeIntConst($1, @1);
9886                                 }
9887                         | FCONST
9888                                 {
9889                                         $$ = makeFloatConst($1, @1);
9890                                 }
9891                         | Sconst
9892                                 {
9893                                         $$ = makeStringConst($1, @1);
9894                                 }
9895                         | BCONST
9896                                 {
9897                                         $$ = makeBitStringConst($1, @1);
9898                                 }
9899                         | XCONST
9900                                 {
9901                                         /* This is a bit constant per SQL99:
9902                                          * Without Feature F511, "BIT data type",
9903                                          * a <general literal> shall not be a
9904                                          * <bit string literal> or a <hex string literal>.
9905                                          */
9906                                         $$ = makeBitStringConst($1, @1);
9907                                 }
9908                         | func_name Sconst
9909                                 {
9910                                         /* generic type 'literal' syntax */
9911                                         TypeName *t = makeTypeNameFromNameList($1);
9912                                         t->location = @1;
9913                                         $$ = makeStringConstCast($2, @2, t);
9914                                 }
9915                         | func_name '(' expr_list ')' Sconst
9916                                 {
9917                                         /* generic syntax with a type modifier */
9918                                         TypeName *t = makeTypeNameFromNameList($1);
9919                                         t->typmods = $3;
9920                                         t->location = @1;
9921                                         $$ = makeStringConstCast($5, @5, t);
9922                                 }
9923                         | ConstTypename Sconst
9924                                 {
9925                                         $$ = makeStringConstCast($2, @2, $1);
9926                                 }
9927                         | ConstInterval Sconst opt_interval
9928                                 {
9929                                         TypeName *t = $1;
9930                                         t->typmods = $3;
9931                                         $$ = makeStringConstCast($2, @2, t);
9932                                 }
9933                         | ConstInterval '(' Iconst ')' Sconst opt_interval
9934                                 {
9935                                         TypeName *t = $1;
9936                                         if ($6 != NIL)
9937                                         {
9938                                                 if (list_length($6) != 1)
9939                                                         ereport(ERROR,
9940                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
9941                                                                          errmsg("interval precision specified twice"),
9942                                                                          scanner_errposition(@1)));
9943                                                 t->typmods = lappend($6, makeIntConst($3, @3));
9944                                         }
9945                                         else
9946                                                 t->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
9947                                                                                                 makeIntConst($3, @3));
9948                                         $$ = makeStringConstCast($5, @5, t);
9949                                 }
9950                         | TRUE_P
9951                                 {
9952                                         $$ = makeBoolAConst(TRUE, @1);
9953                                 }
9954                         | FALSE_P
9955                                 {
9956                                         $$ = makeBoolAConst(FALSE, @1);
9957                                 }
9958                         | NULL_P
9959                                 {
9960                                         $$ = makeNullAConst(@1);
9961                                 }
9962                 ;
9963
9964 Iconst:         ICONST                                                                  { $$ = $1; };
9965 Sconst:         SCONST                                                                  { $$ = $1; };
9966 RoleId:         ColId                                                                   { $$ = $1; };
9967
9968 SignedIconst: Iconst                                                            { $$ = $1; }
9969                         | '+' Iconst                                                    { $$ = + $2; }
9970                         | '-' Iconst                                                    { $$ = - $2; }
9971                 ;
9972
9973 /*
9974  * Name classification hierarchy.
9975  *
9976  * IDENT is the lexeme returned by the lexer for identifiers that match
9977  * no known keyword.  In most cases, we can accept certain keywords as
9978  * names, not only IDENTs.      We prefer to accept as many such keywords
9979  * as possible to minimize the impact of "reserved words" on programmers.
9980  * So, we divide names into several possible classes.  The classification
9981  * is chosen in part to make keywords acceptable as names wherever possible.
9982  */
9983
9984 /* Column identifier --- names that can be column, table, etc names.
9985  */
9986 ColId:          IDENT                                                                   { $$ = $1; }
9987                         | unreserved_keyword                                    { $$ = pstrdup($1); }
9988                         | col_name_keyword                                              { $$ = pstrdup($1); }
9989                 ;
9990
9991 /* Type/function identifier --- names that can be type or function names.
9992  */
9993 type_function_name:     IDENT                                                   { $$ = $1; }
9994                         | unreserved_keyword                                    { $$ = pstrdup($1); }
9995                         | type_func_name_keyword                                { $$ = pstrdup($1); }
9996                 ;
9997
9998 /* Column label --- allowed labels in "AS" clauses.
9999  * This presently includes *all* Postgres keywords.
10000  */
10001 ColLabel:       IDENT                                                                   { $$ = $1; }
10002                         | unreserved_keyword                                    { $$ = pstrdup($1); }
10003                         | col_name_keyword                                              { $$ = pstrdup($1); }
10004                         | type_func_name_keyword                                { $$ = pstrdup($1); }
10005                         | reserved_keyword                                              { $$ = pstrdup($1); }
10006                 ;
10007
10008
10009 /*
10010  * Keyword category lists.  Generally, every keyword present in
10011  * the Postgres grammar should appear in exactly one of these lists.
10012  *
10013  * Put a new keyword into the first list that it can go into without causing
10014  * shift or reduce conflicts.  The earlier lists define "less reserved"
10015  * categories of keywords.
10016  *
10017  * Make sure that each keyword's category in keywords.c matches where
10018  * it is listed here.  (Someday we may be able to generate these lists and
10019  * keywords.c's table from a common master list.)
10020  */
10021
10022 /* "Unreserved" keywords --- available for use as any kind of name.
10023  */
10024 unreserved_keyword:
10025                           ABORT_P
10026                         | ABSOLUTE_P
10027                         | ACCESS
10028                         | ACTION
10029                         | ADD_P
10030                         | ADMIN
10031                         | AFTER
10032                         | AGGREGATE
10033                         | ALSO
10034                         | ALTER
10035                         | ALWAYS
10036                         | ASSERTION
10037                         | ASSIGNMENT
10038                         | AT
10039                         | BACKWARD
10040                         | BEFORE
10041                         | BEGIN_P
10042                         | BY
10043                         | CACHE
10044                         | CALLED
10045                         | CASCADE
10046                         | CASCADED
10047                         | CATALOG_P
10048                         | CHAIN
10049                         | CHARACTERISTICS
10050                         | CHECKPOINT
10051                         | CLASS
10052                         | CLOSE
10053                         | CLUSTER
10054                         | COMMENT
10055                         | COMMIT
10056                         | COMMITTED
10057                         | CONCURRENTLY
10058                         | CONFIGURATION
10059                         | CONNECTION
10060                         | CONSTRAINTS
10061                         | CONTENT_P
10062                         | CONTINUE_P
10063                         | CONVERSION_P
10064                         | COPY
10065                         | COST
10066                         | CREATEDB
10067                         | CREATEROLE
10068                         | CREATEUSER
10069                         | CSV
10070                         | CTYPE
10071                         | CURRENT_P
10072                         | CURSOR
10073                         | CYCLE
10074                         | DATA_P
10075                         | DATABASE
10076                         | DAY_P
10077                         | DEALLOCATE
10078                         | DECLARE
10079                         | DEFAULTS
10080                         | DEFERRED
10081                         | DEFINER
10082                         | DELETE_P
10083                         | DELIMITER
10084                         | DELIMITERS
10085                         | DICTIONARY
10086                         | DISABLE_P
10087                         | DISCARD
10088                         | DOCUMENT_P
10089                         | DOMAIN_P
10090                         | DOUBLE_P
10091                         | DROP
10092                         | EACH
10093                         | ENABLE_P
10094                         | ENCODING
10095                         | ENCRYPTED
10096                         | ENUM_P
10097                         | ESCAPE
10098                         | EXCLUDING
10099                         | EXCLUSIVE
10100                         | EXECUTE
10101                         | EXPLAIN
10102                         | EXTERNAL
10103                         | FAMILY
10104                         | FIRST_P
10105                         | FOLLOWING
10106                         | FORCE
10107                         | FORWARD
10108                         | FUNCTION
10109                         | GLOBAL
10110                         | GRANTED
10111                         | HANDLER
10112                         | HEADER_P
10113                         | HOLD
10114                         | HOUR_P
10115                         | IDENTITY_P
10116                         | IF_P
10117                         | IMMEDIATE
10118                         | IMMUTABLE
10119                         | IMPLICIT_P
10120                         | INCLUDING
10121                         | INCREMENT
10122                         | INDEX
10123                         | INDEXES
10124                         | INHERIT
10125                         | INHERITS
10126                         | INPUT_P
10127                         | INSENSITIVE
10128                         | INSERT
10129                         | INSTEAD
10130                         | INVOKER
10131                         | ISOLATION
10132                         | KEY
10133                         | LIBRARY
10134                         | LANCOMPILER
10135                         | LANGUAGE
10136                         | LARGE_P
10137                         | LAST_P
10138                         | LEVEL
10139                         | LISTEN
10140                         | LOAD
10141                         | LOCAL
10142                         | LOCATION
10143                         | LOCK_P
10144                         | LOGIN_P
10145                         | MAPPING
10146                         | MATCH
10147                         | MAXVALUE
10148                         | MINUTE_P
10149                         | MINVALUE
10150                         | MODE
10151                         | MONTH_P
10152                         | MOVE
10153                         | NAME_P
10154                         | NAMES
10155                         | NEXT
10156                         | NO
10157                         | NOCREATEDB
10158                         | NOCREATEROLE
10159                         | NOCREATEUSER
10160                         | NOINHERIT
10161                         | NOLOGIN_P
10162                         | NOSUPERUSER
10163                         | NOTHING
10164                         | NOTIFY
10165                         | NOWAIT
10166                         | NULLS_P
10167                         | OBJECT_P
10168                         | OF
10169                         | OIDS
10170                         | OPERATOR
10171                         | OPTION
10172                         | OPTIONS
10173                         | OWNED
10174                         | OWNER
10175                         | PARSER
10176                         | PARTIAL
10177                         | PARTITION
10178                         | PASSWORD
10179                         | PLANS
10180                         | PRECEDING
10181                         | PREPARE
10182                         | PREPARED
10183                         | PRESERVE
10184                         | PRIOR
10185                         | PRIVILEGES
10186                         | PROCEDURAL
10187                         | PROCEDURE
10188                         | QUOTE
10189                         | RANGE
10190                         | READ
10191                         | REASSIGN
10192                         | RECHECK
10193                         | RECURSIVE
10194                         | REINDEX
10195                         | RELATIVE_P
10196                         | RELEASE
10197                         | RENAME
10198                         | REPEATABLE
10199                         | REPLACE
10200                         | REPLICA
10201                         | RESET
10202                         | RESTART
10203                         | RESTRICT
10204                         | RETURNS
10205                         | REVOKE
10206                         | ROLE
10207                         | ROLLBACK
10208                         | ROWS
10209                         | RULE
10210                         | SAVEPOINT
10211                         | SERVER
10212                         | SCHEMA
10213                         | SCROLL
10214                         | SEARCH
10215                         | SECOND_P
10216                         | SECURITY
10217                         | SEQUENCE
10218                         | SERIALIZABLE
10219                         | SESSION
10220                         | SET
10221                         | SHARE
10222                         | SHOW
10223                         | SIMPLE
10224                         | STABLE
10225                         | STANDALONE_P
10226                         | START
10227                         | STATEMENT
10228                         | STATISTICS
10229                         | STDIN
10230                         | STDOUT
10231                         | STORAGE
10232                         | STRICT_P
10233                         | STRIP_P
10234                         | SUPERUSER_P
10235                         | SYSID
10236                         | SYSTEM_P
10237                         | TABLESPACE
10238                         | TEMP
10239                         | TEMPLATE
10240                         | TEMPORARY
10241                         | TEXT_P
10242                         | TRANSACTION
10243                         | TRIGGER
10244                         | TRUNCATE
10245                         | TRUSTED
10246                         | TYPE_P
10247                         | UNBOUNDED
10248                         | UNCOMMITTED
10249                         | UNENCRYPTED
10250                         | UNKNOWN
10251                         | UNLISTEN
10252                         | UNTIL
10253                         | UPDATE
10254                         | VACUUM
10255                         | VALID
10256                         | VALIDATOR
10257                         | VALUE_P
10258                         | VARYING
10259                         | VERSION_P
10260                         | VIEW
10261                         | VOLATILE
10262                         | WHITESPACE_P
10263                         | WITHOUT
10264                         | WORK
10265                         | WRAPPER
10266                         | WRITE
10267                         | XML_P
10268                         | YEAR_P
10269                         | YES_P
10270                         | ZONE
10271                 ;
10272
10273 /* Column identifier --- keywords that can be column, table, etc names.
10274  *
10275  * Many of these keywords will in fact be recognized as type or function
10276  * names too; but they have special productions for the purpose, and so
10277  * can't be treated as "generic" type or function names.
10278  *
10279  * The type names appearing here are not usable as function names
10280  * because they can be followed by '(' in typename productions, which
10281  * looks too much like a function call for an LR(1) parser.
10282  */
10283 col_name_keyword:
10284                           BIGINT
10285                         | BIT
10286                         | BOOLEAN_P
10287                         | CHAR_P
10288                         | CHARACTER
10289                         | COALESCE
10290                         | DEC
10291                         | DECIMAL_P
10292                         | EXISTS
10293                         | EXTRACT
10294                         | FLOAT_P
10295                         | GREATEST
10296                         | INOUT
10297                         | INT_P
10298                         | INTEGER
10299                         | INTERVAL
10300                         | LEAST
10301                         | NATIONAL
10302                         | NCHAR
10303                         | NONE
10304                         | NULLIF
10305                         | NUMERIC
10306                         | OUT_P
10307                         | OVERLAY
10308                         | POSITION
10309                         | PRECISION
10310                         | REAL
10311                         | ROW
10312                         | SETOF
10313                         | SMALLINT
10314                         | SUBSTRING
10315                         | TIME
10316                         | TIMESTAMP
10317                         | TREAT
10318                         | TRIM
10319                         | VALUES
10320                         | VARCHAR
10321                         | XMLATTRIBUTES
10322                         | XMLCONCAT
10323                         | XMLELEMENT
10324                         | XMLFOREST
10325                         | XMLPARSE
10326                         | XMLPI
10327                         | XMLROOT
10328                         | XMLSERIALIZE
10329                 ;
10330
10331 /* Type/function identifier --- keywords that can be type or function names.
10332  *
10333  * Most of these are keywords that are used as operators in expressions;
10334  * in general such keywords can't be column names because they would be
10335  * ambiguous with variables, but they are unambiguous as function identifiers.
10336  *
10337  * Do not include POSITION, SUBSTRING, etc here since they have explicit
10338  * productions in a_expr to support the goofy SQL9x argument syntax.
10339  * - thomas 2000-11-28
10340  */
10341 type_func_name_keyword:
10342                           AUTHORIZATION
10343                         | BETWEEN
10344                         | BINARY
10345                         | CROSS
10346                         | CURRENT_SCHEMA
10347                         | FREEZE
10348                         | FULL
10349                         | ILIKE
10350                         | INNER_P
10351                         | IS
10352                         | ISNULL
10353                         | JOIN
10354                         | LEFT
10355                         | LIKE
10356                         | NATURAL
10357                         | NOTNULL
10358                         | OUTER_P
10359                         | OVER
10360                         | OVERLAPS
10361                         | RIGHT
10362                         | SIMILAR
10363                         | VERBOSE
10364                 ;
10365
10366 /* Reserved keyword --- these keywords are usable only as a ColLabel.
10367  *
10368  * Keywords appear here if they could not be distinguished from variable,
10369  * type, or function names in some contexts.  Don't put things here unless
10370  * forced to.
10371  */
10372 reserved_keyword:
10373                           ALL
10374                         | ANALYSE
10375                         | ANALYZE
10376                         | AND
10377                         | ANY
10378                         | ARRAY
10379                         | AS
10380                         | ASC
10381                         | ASYMMETRIC
10382                         | BOTH
10383                         | CASE
10384                         | CAST
10385                         | CHECK
10386                         | COLLATE
10387                         | COLUMN
10388                         | CONSTRAINT
10389                         | CREATE
10390                         | CURRENT_CATALOG
10391                         | CURRENT_DATE
10392                         | CURRENT_ROLE
10393                         | CURRENT_TIME
10394                         | CURRENT_TIMESTAMP
10395                         | CURRENT_USER
10396                         | DEFAULT
10397                         | DEFERRABLE
10398                         | DESC
10399                         | DISTINCT
10400                         | DO
10401                         | ELSE
10402                         | END_P
10403                         | EXCEPT
10404                         | FALSE_P
10405                         | FETCH
10406                         | FOR
10407                         | FOREIGN
10408                         | FROM
10409                         | GRANT
10410                         | GROUP_P
10411                         | HAVING
10412                         | IN_P
10413                         | INITIALLY
10414                         | INTERSECT
10415                         | INTO
10416                         | LEADING
10417                         | LIMIT
10418                         | LOCALTIME
10419                         | LOCALTIMESTAMP
10420                         | NEW
10421                         | NOT
10422                         | NULL_P
10423                         | OFF
10424                         | OFFSET
10425                         | OLD
10426                         | ON
10427                         | ONLY
10428                         | OR
10429                         | ORDER
10430                         | PLACING
10431                         | PRIMARY
10432                         | REFERENCES
10433                         | RETURNING
10434                         | SELECT
10435                         | SESSION_USER
10436                         | SOME
10437                         | SYMMETRIC
10438                         | TABLE
10439                         | THEN
10440                         | TO
10441                         | TRAILING
10442                         | TRUE_P
10443                         | UNION
10444                         | UNIQUE
10445                         | USER
10446                         | USING
10447                         | VARIADIC
10448                         | WHEN
10449                         | WHERE
10450                         | WINDOW
10451                         | WITH
10452                 ;
10453
10454
10455 SpecialRuleRelation:
10456                         OLD
10457                                 {
10458                                         if (QueryIsRule)
10459                                                 $$ = "*OLD*";
10460                                         else
10461                                                 ereport(ERROR,
10462                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
10463                                                                  errmsg("OLD used in query that is not in a rule"),
10464                                                                  scanner_errposition(@1)));
10465                                 }
10466                         | NEW
10467                                 {
10468                                         if (QueryIsRule)
10469                                                 $$ = "*NEW*";
10470                                         else
10471                                                 ereport(ERROR,
10472                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
10473                                                                  errmsg("NEW used in query that is not in a rule"),
10474                                                                  scanner_errposition(@1)));
10475                                 }
10476                 ;
10477
10478 %%
10479
10480 static Node *
10481 makeColumnRef(char *colname, List *indirection, int location)
10482 {
10483         /*
10484          * Generate a ColumnRef node, with an A_Indirection node added if there
10485          * is any subscripting in the specified indirection list.  However,
10486          * any field selection at the start of the indirection list must be
10487          * transposed into the "fields" part of the ColumnRef node.
10488          */
10489         ColumnRef  *c = makeNode(ColumnRef);
10490         int             nfields = 0;
10491         ListCell *l;
10492
10493         c->location = location;
10494         foreach(l, indirection)
10495         {
10496                 if (IsA(lfirst(l), A_Indices))
10497                 {
10498                         A_Indirection *i = makeNode(A_Indirection);
10499
10500                         if (nfields == 0)
10501                         {
10502                                 /* easy case - all indirection goes to A_Indirection */
10503                                 c->fields = list_make1(makeString(colname));
10504                                 i->indirection = check_indirection(indirection);
10505                         }
10506                         else
10507                         {
10508                                 /* got to split the list in two */
10509                                 i->indirection = check_indirection(list_copy_tail(indirection,
10510                                                                                                                                   nfields));
10511                                 indirection = list_truncate(indirection, nfields);
10512                                 c->fields = lcons(makeString(colname), indirection);
10513                         }
10514                         i->arg = (Node *) c;
10515                         return (Node *) i;
10516                 }
10517                 else if (IsA(lfirst(l), A_Star))
10518                 {
10519                         /* We only allow '*' at the end of a ColumnRef */
10520                         if (lnext(l) != NULL)
10521                                 yyerror("improper use of \"*\"");
10522                 }
10523                 nfields++;
10524         }
10525         /* No subscripting, so all indirection gets added to field list */
10526         c->fields = lcons(makeString(colname), indirection);
10527         return (Node *) c;
10528 }
10529
10530 static Node *
10531 makeTypeCast(Node *arg, TypeName *typename, int location)
10532 {
10533         TypeCast *n = makeNode(TypeCast);
10534         n->arg = arg;
10535         n->typename = typename;
10536         n->location = location;
10537         return (Node *) n;
10538 }
10539
10540 static Node *
10541 makeStringConst(char *str, int location)
10542 {
10543         A_Const *n = makeNode(A_Const);
10544
10545         n->val.type = T_String;
10546         n->val.val.str = str;
10547         n->location = location;
10548
10549         return (Node *)n;
10550 }
10551
10552 static Node *
10553 makeStringConstCast(char *str, int location, TypeName *typename)
10554 {
10555         Node *s = makeStringConst(str, location);
10556
10557         return makeTypeCast(s, typename, -1);
10558 }
10559
10560 static Node *
10561 makeIntConst(int val, int location)
10562 {
10563         A_Const *n = makeNode(A_Const);
10564
10565         n->val.type = T_Integer;
10566         n->val.val.ival = val;
10567         n->location = location;
10568
10569         return (Node *)n;
10570 }
10571
10572 static Node *
10573 makeFloatConst(char *str, int location)
10574 {
10575         A_Const *n = makeNode(A_Const);
10576
10577         n->val.type = T_Float;
10578         n->val.val.str = str;
10579         n->location = location;
10580
10581         return (Node *)n;
10582 }
10583
10584 static Node *
10585 makeBitStringConst(char *str, int location)
10586 {
10587         A_Const *n = makeNode(A_Const);
10588
10589         n->val.type = T_BitString;
10590         n->val.val.str = str;
10591         n->location = location;
10592
10593         return (Node *)n;
10594 }
10595
10596 static Node *
10597 makeNullAConst(int location)
10598 {
10599         A_Const *n = makeNode(A_Const);
10600
10601         n->val.type = T_Null;
10602         n->location = location;
10603
10604         return (Node *)n;
10605 }
10606
10607 static Node *
10608 makeAConst(Value *v, int location)
10609 {
10610         Node *n;
10611
10612         switch (v->type)
10613         {
10614                 case T_Float:
10615                         n = makeFloatConst(v->val.str, location);
10616                         break;
10617
10618                 case T_Integer:
10619                         n = makeIntConst(v->val.ival, location);
10620                         break;
10621
10622                 case T_String:
10623                 default:
10624                         n = makeStringConst(v->val.str, location);
10625                         break;
10626         }
10627
10628         return n;
10629 }
10630
10631 /* makeBoolAConst()
10632  * Create an A_Const string node and put it inside a boolean cast.
10633  */
10634 static Node *
10635 makeBoolAConst(bool state, int location)
10636 {
10637         A_Const *n = makeNode(A_Const);
10638
10639         n->val.type = T_String;
10640         n->val.val.str = (state ? "t" : "f");
10641         n->location = location;
10642
10643         return makeTypeCast((Node *)n, SystemTypeName("bool"), -1);
10644 }
10645
10646 /* makeOverlaps()
10647  * Create and populate a FuncCall node to support the OVERLAPS operator.
10648  */
10649 static FuncCall *
10650 makeOverlaps(List *largs, List *rargs, int location)
10651 {
10652         FuncCall *n = makeNode(FuncCall);
10653
10654         n->funcname = SystemFuncName("overlaps");
10655         if (list_length(largs) == 1)
10656                 largs = lappend(largs, largs);
10657         else if (list_length(largs) != 2)
10658                 ereport(ERROR,
10659                                 (errcode(ERRCODE_SYNTAX_ERROR),
10660                                  errmsg("wrong number of parameters on left side of OVERLAPS expression"),
10661                                  scanner_errposition(location)));
10662         if (list_length(rargs) == 1)
10663                 rargs = lappend(rargs, rargs);
10664         else if (list_length(rargs) != 2)
10665                 ereport(ERROR,
10666                                 (errcode(ERRCODE_SYNTAX_ERROR),
10667                                  errmsg("wrong number of parameters on right side of OVERLAPS expression"),
10668                                  scanner_errposition(location)));
10669         n->args = list_concat(largs, rargs);
10670         n->agg_star = FALSE;
10671         n->agg_distinct = FALSE;
10672         n->func_variadic = FALSE;
10673         n->over = NULL;
10674         n->location = location;
10675         return n;
10676 }
10677
10678 /* check_qualified_name --- check the result of qualified_name production
10679  *
10680  * It's easiest to let the grammar production for qualified_name allow
10681  * subscripts and '*', which we then must reject here.
10682  */
10683 static void
10684 check_qualified_name(List *names)
10685 {
10686         ListCell   *i;
10687
10688         foreach(i, names)
10689         {
10690                 if (!IsA(lfirst(i), String))
10691                         yyerror("syntax error");
10692         }
10693 }
10694
10695 /* check_func_name --- check the result of func_name production
10696  *
10697  * It's easiest to let the grammar production for func_name allow subscripts
10698  * and '*', which we then must reject here.
10699  */
10700 static List *
10701 check_func_name(List *names)
10702 {
10703         ListCell   *i;
10704
10705         foreach(i, names)
10706         {
10707                 if (!IsA(lfirst(i), String))
10708                         yyerror("syntax error");
10709         }
10710         return names;
10711 }
10712
10713 /* check_indirection --- check the result of indirection production
10714  *
10715  * We only allow '*' at the end of the list, but it's hard to enforce that
10716  * in the grammar, so do it here.
10717  */
10718 static List *
10719 check_indirection(List *indirection)
10720 {
10721         ListCell *l;
10722
10723         foreach(l, indirection)
10724         {
10725                 if (IsA(lfirst(l), A_Star))
10726                 {
10727                         if (lnext(l) != NULL)
10728                                 yyerror("improper use of \"*\"");
10729                 }
10730         }
10731         return indirection;
10732 }
10733
10734 /* extractArgTypes()
10735  * Given a list of FunctionParameter nodes, extract a list of just the
10736  * argument types (TypeNames) for input parameters only.  This is what
10737  * is needed to look up an existing function, which is what is wanted by
10738  * the productions that use this call.
10739  */
10740 static List *
10741 extractArgTypes(List *parameters)
10742 {
10743         List       *result = NIL;
10744         ListCell   *i;
10745
10746         foreach(i, parameters)
10747         {
10748                 FunctionParameter *p = (FunctionParameter *) lfirst(i);
10749
10750                 if (p->mode != FUNC_PARAM_OUT && p->mode != FUNC_PARAM_TABLE)
10751                         result = lappend(result, p->argType);
10752         }
10753         return result;
10754 }
10755
10756 /* findLeftmostSelect()
10757  * Find the leftmost component SelectStmt in a set-operation parsetree.
10758  */
10759 static SelectStmt *
10760 findLeftmostSelect(SelectStmt *node)
10761 {
10762         while (node && node->op != SETOP_NONE)
10763                 node = node->larg;
10764         Assert(node && IsA(node, SelectStmt) && node->larg == NULL);
10765         return node;
10766 }
10767
10768 /* insertSelectOptions()
10769  * Insert ORDER BY, etc into an already-constructed SelectStmt.
10770  *
10771  * This routine is just to avoid duplicating code in SelectStmt productions.
10772  */
10773 static void
10774 insertSelectOptions(SelectStmt *stmt,
10775                                         List *sortClause, List *lockingClause,
10776                                         Node *limitOffset, Node *limitCount,
10777                                         WithClause *withClause)
10778 {
10779         Assert(IsA(stmt, SelectStmt));
10780
10781         /*
10782          * Tests here are to reject constructs like
10783          *      (SELECT foo ORDER BY bar) ORDER BY baz
10784          */
10785         if (sortClause)
10786         {
10787                 if (stmt->sortClause)
10788                         ereport(ERROR,
10789                                         (errcode(ERRCODE_SYNTAX_ERROR),
10790                                          errmsg("multiple ORDER BY clauses not allowed"),
10791                                          scanner_errposition(exprLocation((Node *) sortClause))));
10792                 stmt->sortClause = sortClause;
10793         }
10794         /* We can handle multiple locking clauses, though */
10795         stmt->lockingClause = list_concat(stmt->lockingClause, lockingClause);
10796         if (limitOffset)
10797         {
10798                 if (stmt->limitOffset)
10799                         ereport(ERROR,
10800                                         (errcode(ERRCODE_SYNTAX_ERROR),
10801                                          errmsg("multiple OFFSET clauses not allowed"),
10802                                          scanner_errposition(exprLocation(limitOffset))));
10803                 stmt->limitOffset = limitOffset;
10804         }
10805         if (limitCount)
10806         {
10807                 if (stmt->limitCount)
10808                         ereport(ERROR,
10809                                         (errcode(ERRCODE_SYNTAX_ERROR),
10810                                          errmsg("multiple LIMIT clauses not allowed"),
10811                                          scanner_errposition(exprLocation(limitCount))));
10812                 stmt->limitCount = limitCount;
10813         }
10814         if (withClause)
10815         {
10816                 if (stmt->withClause)
10817                         ereport(ERROR,
10818                                         (errcode(ERRCODE_SYNTAX_ERROR),
10819                                          errmsg("multiple WITH clauses not allowed"),
10820                                          scanner_errposition(exprLocation((Node *) withClause))));
10821                 stmt->withClause = withClause;
10822         }
10823 }
10824
10825 static Node *
10826 makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
10827 {
10828         SelectStmt *n = makeNode(SelectStmt);
10829
10830         n->op = op;
10831         n->all = all;
10832         n->larg = (SelectStmt *) larg;
10833         n->rarg = (SelectStmt *) rarg;
10834         return (Node *) n;
10835 }
10836
10837 /* SystemFuncName()
10838  * Build a properly-qualified reference to a built-in function.
10839  */
10840 List *
10841 SystemFuncName(char *name)
10842 {
10843         return list_make2(makeString("pg_catalog"), makeString(name));
10844 }
10845
10846 /* SystemTypeName()
10847  * Build a properly-qualified reference to a built-in type.
10848  *
10849  * typmod is defaulted, but may be changed afterwards by caller.
10850  * Likewise for the location.
10851  */
10852 TypeName *
10853 SystemTypeName(char *name)
10854 {
10855         return makeTypeNameFromNameList(list_make2(makeString("pg_catalog"),
10856                                                                                            makeString(name)));
10857 }
10858
10859 /* doNegate()
10860  * Handle negation of a numeric constant.
10861  *
10862  * Formerly, we did this here because the optimizer couldn't cope with
10863  * indexquals that looked like "var = -4" --- it wants "var = const"
10864  * and a unary minus operator applied to a constant didn't qualify.
10865  * As of Postgres 7.0, that problem doesn't exist anymore because there
10866  * is a constant-subexpression simplifier in the optimizer.  However,
10867  * there's still a good reason for doing this here, which is that we can
10868  * postpone committing to a particular internal representation for simple
10869  * negative constants.  It's better to leave "-123.456" in string form
10870  * until we know what the desired type is.
10871  */
10872 static Node *
10873 doNegate(Node *n, int location)
10874 {
10875         if (IsA(n, A_Const))
10876         {
10877                 A_Const *con = (A_Const *)n;
10878
10879                 /* report the constant's location as that of the '-' sign */
10880                 con->location = location;
10881
10882                 if (con->val.type == T_Integer)
10883                 {
10884                         con->val.val.ival = -con->val.val.ival;
10885                         return n;
10886                 }
10887                 if (con->val.type == T_Float)
10888                 {
10889                         doNegateFloat(&con->val);
10890                         return n;
10891                 }
10892         }
10893
10894         return (Node *) makeSimpleA_Expr(AEXPR_OP, "-", NULL, n, location);
10895 }
10896
10897 static void
10898 doNegateFloat(Value *v)
10899 {
10900         char   *oldval = v->val.str;
10901
10902         Assert(IsA(v, Float));
10903         if (*oldval == '+')
10904                 oldval++;
10905         if (*oldval == '-')
10906                 v->val.str = oldval+1;  /* just strip the '-' */
10907         else
10908         {
10909                 char   *newval = (char *) palloc(strlen(oldval) + 2);
10910
10911                 *newval = '-';
10912                 strcpy(newval+1, oldval);
10913                 v->val.str = newval;
10914         }
10915 }
10916
10917 static Node *
10918 makeAArrayExpr(List *elements, int location)
10919 {
10920         A_ArrayExpr *n = makeNode(A_ArrayExpr);
10921
10922         n->elements = elements;
10923         n->location = location;
10924         return (Node *) n;
10925 }
10926
10927 static Node *
10928 makeXmlExpr(XmlExprOp op, char *name, List *named_args, List *args,
10929                         int location)
10930 {
10931         XmlExpr    *x = makeNode(XmlExpr);
10932
10933         x->op = op;
10934         x->name = name;
10935         /*
10936          * named_args is a list of ResTarget; it'll be split apart into separate
10937          * expression and name lists in transformXmlExpr().
10938          */
10939         x->named_args = named_args;
10940         x->arg_names = NIL;
10941         x->args = args;
10942         /* xmloption, if relevant, must be filled in by caller */
10943         /* type and typmod will be filled in during parse analysis */
10944         x->location = location;
10945         return (Node *) x;
10946 }
10947
10948 /* parser_init()
10949  * Initialize to parse one query string
10950  */
10951 void
10952 parser_init(void)
10953 {
10954         QueryIsRule = FALSE;
10955 }
10956
10957 /*
10958  * Merge the input and output parameters of a table function.
10959  */
10960 static List *
10961 mergeTableFuncParameters(List *func_args, List *columns)
10962 {
10963         ListCell   *lc;
10964
10965         /* Explicit OUT and INOUT parameters shouldn't be used in this syntax */
10966         foreach(lc, func_args)
10967         {
10968                 FunctionParameter *p = (FunctionParameter *) lfirst(lc);
10969
10970                 if (p->mode != FUNC_PARAM_IN && p->mode != FUNC_PARAM_VARIADIC)
10971                         ereport(ERROR,
10972                                         (errcode(ERRCODE_SYNTAX_ERROR),
10973                                          errmsg("OUT and INOUT arguments aren't allowed in TABLE functions")));
10974         }
10975
10976         return list_concat(func_args, columns);
10977 }
10978
10979 /*
10980  * Determine return type of a TABLE function.  A single result column
10981  * returns setof that column's type; otherwise return setof record.
10982  */
10983 static TypeName *
10984 TableFuncTypeName(List *columns)
10985 {
10986         TypeName *result;
10987
10988         if (list_length(columns) == 1)
10989         {
10990                 FunctionParameter *p = (FunctionParameter *) linitial(columns);
10991
10992                 result = (TypeName *) copyObject(p->argType);
10993         }
10994         else
10995                 result = SystemTypeName("record");
10996
10997         result->setof = true;
10998
10999         return result;
11000 }
11001
11002 /*
11003  * Must undefine base_yylex before including scan.c, since we want it
11004  * to create the function base_yylex not filtered_base_yylex.
11005  */
11006 #undef base_yylex
11007
11008 #include "scan.c"