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