]> granicus.if.org Git - postgresql/blob - src/backend/parser/gram.y
Removed two non-terminals:
[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.637 2008/11/13 11:10:06 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
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 <SignedIconst> */
1529                         | ALTER opt_column ColId SET STATISTICS SignedIconst
1530                                 {
1531                                         AlterTableCmd *n = makeNode(AlterTableCmd);
1532                                         n->subtype = AT_SetStatistics;
1533                                         n->name = $3;
1534                                         n->def = (Node *) makeInteger($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                 FCONST                                                                  { $$ = makeFloat($1); }
2581                         | '-' FCONST
2582                                 {
2583                                         $$ = makeFloat($2);
2584                                         doNegateFloat($$);
2585                                 }
2586                         | SignedIconst                                                  { $$ = makeInteger($1); };
2587                 ;
2588
2589 /*****************************************************************************
2590  *
2591  *              QUERIES :
2592  *                              CREATE PROCEDURAL LANGUAGE ...
2593  *                              DROP PROCEDURAL LANGUAGE ...
2594  *
2595  *****************************************************************************/
2596
2597 CreatePLangStmt:
2598                         CREATE opt_trusted opt_procedural LANGUAGE ColId_or_Sconst
2599                         {
2600                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
2601                                 n->plname = $5;
2602                                 /* parameters are all to be supplied by system */
2603                                 n->plhandler = NIL;
2604                                 n->plvalidator = NIL;
2605                                 n->pltrusted = false;
2606                                 $$ = (Node *)n;
2607                         }
2608                         | CREATE opt_trusted opt_procedural LANGUAGE ColId_or_Sconst
2609                           HANDLER handler_name opt_validator opt_lancompiler
2610                         {
2611                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
2612                                 n->plname = $5;
2613                                 n->plhandler = $7;
2614                                 n->plvalidator = $8;
2615                                 n->pltrusted = $2;
2616                                 /* LANCOMPILER is now ignored entirely */
2617                                 $$ = (Node *)n;
2618                         }
2619                 ;
2620
2621 opt_trusted:
2622                         TRUSTED                                                                 { $$ = TRUE; }
2623                         | /*EMPTY*/                                                             { $$ = FALSE; }
2624                 ;
2625
2626 /* This ought to be just func_name, but that causes reduce/reduce conflicts
2627  * (CREATE LANGUAGE is the only place where func_name isn't followed by '(').
2628  * Work around by using simple names, instead.
2629  */
2630 handler_name:
2631                         name                                            { $$ = list_make1(makeString($1)); }
2632                         | name attrs                            { $$ = lcons(makeString($1), $2); }
2633                 ;
2634
2635 opt_validator:
2636                         VALIDATOR handler_name                                  { $$ = $2; }
2637                         | /*EMPTY*/                                                             { $$ = NIL; }
2638                 ;
2639
2640 opt_lancompiler:
2641                         LANCOMPILER Sconst                                              { $$ = $2; }
2642                         | /*EMPTY*/                                                             { $$ = NULL; }
2643                 ;
2644
2645 DropPLangStmt:
2646                         DROP opt_procedural LANGUAGE ColId_or_Sconst opt_drop_behavior
2647                                 {
2648                                         DropPLangStmt *n = makeNode(DropPLangStmt);
2649                                         n->plname = $4;
2650                                         n->behavior = $5;
2651                                         n->missing_ok = false;
2652                                         $$ = (Node *)n;
2653                                 }
2654                         | DROP opt_procedural LANGUAGE IF_P EXISTS ColId_or_Sconst opt_drop_behavior
2655                                 {
2656                                         DropPLangStmt *n = makeNode(DropPLangStmt);
2657                                         n->plname = $6;
2658                                         n->behavior = $7;
2659                                         n->missing_ok = true;
2660                                         $$ = (Node *)n;
2661                                 }
2662                 ;
2663
2664 opt_procedural:
2665                         PROCEDURAL                                                              {}
2666                         | /*EMPTY*/                                                             {}
2667                 ;
2668
2669 /*****************************************************************************
2670  *
2671  *              QUERY:
2672  *             CREATE TABLESPACE tablespace LOCATION '/path/to/tablespace/'
2673  *
2674  *****************************************************************************/
2675
2676 CreateTableSpaceStmt: CREATE TABLESPACE name OptTableSpaceOwner LOCATION Sconst
2677                                 {
2678                                         CreateTableSpaceStmt *n = makeNode(CreateTableSpaceStmt);
2679                                         n->tablespacename = $3;
2680                                         n->owner = $4;
2681                                         n->location = $6;
2682                                         $$ = (Node *) n;
2683                                 }
2684                 ;
2685
2686 OptTableSpaceOwner: OWNER name                  { $$ = $2; }
2687                         | /*EMPTY */                            { $$ = NULL; }
2688                 ;
2689
2690 /*****************************************************************************
2691  *
2692  *              QUERY :
2693  *                              DROP TABLESPACE <tablespace>
2694  *
2695  *              No need for drop behaviour as we cannot implement dependencies for
2696  *              objects in other databases; we can only support RESTRICT.
2697  *
2698  ****************************************************************************/
2699
2700 DropTableSpaceStmt: DROP TABLESPACE name
2701                                 {
2702                                         DropTableSpaceStmt *n = makeNode(DropTableSpaceStmt);
2703                                         n->tablespacename = $3;
2704                                         n->missing_ok = false;
2705                                         $$ = (Node *) n;
2706                                 }
2707                                 |  DROP TABLESPACE IF_P EXISTS name
2708                 {
2709                                         DropTableSpaceStmt *n = makeNode(DropTableSpaceStmt);
2710                                         n->tablespacename = $5;
2711                                         n->missing_ok = true;
2712                                         $$ = (Node *) n;
2713                                 }
2714                 ;
2715
2716 /*****************************************************************************
2717  *
2718  *              QUERIES :
2719  *                              CREATE TRIGGER ...
2720  *                              DROP TRIGGER ...
2721  *
2722  *****************************************************************************/
2723
2724 CreateTrigStmt:
2725                         CREATE TRIGGER name TriggerActionTime TriggerEvents ON
2726                         qualified_name TriggerForSpec EXECUTE PROCEDURE
2727                         func_name '(' TriggerFuncArgs ')'
2728                                 {
2729                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
2730                                         n->trigname = $3;
2731                                         n->relation = $7;
2732                                         n->funcname = $11;
2733                                         n->args = $13;
2734                                         n->before = $4;
2735                                         n->row = $8;
2736                                         memcpy(n->actions, $5, 4);
2737                                         n->isconstraint  = FALSE;
2738                                         n->deferrable    = FALSE;
2739                                         n->initdeferred  = FALSE;
2740                                         n->constrrel = NULL;
2741                                         $$ = (Node *)n;
2742                                 }
2743                         | CREATE CONSTRAINT TRIGGER name AFTER TriggerEvents ON
2744                         qualified_name OptConstrFromTable
2745                         ConstraintAttributeSpec
2746                         FOR EACH ROW EXECUTE PROCEDURE
2747                         func_name '(' TriggerFuncArgs ')'
2748                                 {
2749                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
2750                                         n->trigname = $4;
2751                                         n->relation = $8;
2752                                         n->funcname = $16;
2753                                         n->args = $18;
2754                                         n->before = FALSE;
2755                                         n->row = TRUE;
2756                                         memcpy(n->actions, $6, 4);
2757                                         n->isconstraint  = TRUE;
2758                                         n->deferrable = ($10 & 1) != 0;
2759                                         n->initdeferred = ($10 & 2) != 0;
2760
2761                                         n->constrrel = $9;
2762                                         $$ = (Node *)n;
2763                                 }
2764                 ;
2765
2766 TriggerActionTime:
2767                         BEFORE                                                                  { $$ = TRUE; }
2768                         | AFTER                                                                 { $$ = FALSE; }
2769                 ;
2770
2771 TriggerEvents:
2772                         TriggerOneEvent
2773                                 {
2774                                         char *e = palloc(4);
2775                                         e[0] = $1; e[1] = '\0';
2776                                         $$ = e;
2777                                 }
2778                         | TriggerOneEvent OR TriggerOneEvent
2779                                 {
2780                                         char *e = palloc(4);
2781                                         e[0] = $1; e[1] = $3; e[2] = '\0';
2782                                         $$ = e;
2783                                 }
2784                         | TriggerOneEvent OR TriggerOneEvent OR TriggerOneEvent
2785                                 {
2786                                         char *e = palloc(4);
2787                                         e[0] = $1; e[1] = $3; e[2] = $5; e[3] = '\0';
2788                                         $$ = e;
2789                                 }
2790                 ;
2791
2792 TriggerOneEvent:
2793                         INSERT                                                                  { $$ = 'i'; }
2794                         | DELETE_P                                                              { $$ = 'd'; }
2795                         | UPDATE                                                                { $$ = 'u'; }
2796                         | TRUNCATE                                                              { $$ = 't'; }
2797                 ;
2798
2799 TriggerForSpec:
2800                         FOR TriggerForOpt TriggerForType
2801                                 {
2802                                         $$ = $3;
2803                                 }
2804                         | /* EMPTY */
2805                                 {
2806                                         /*
2807                                          * If ROW/STATEMENT not specified, default to
2808                                          * STATEMENT, per SQL
2809                                          */
2810                                         $$ = FALSE;
2811                                 }
2812                 ;
2813
2814 TriggerForOpt:
2815                         EACH                                                                    {}
2816                         | /*EMPTY*/                                                             {}
2817                 ;
2818
2819 TriggerForType:
2820                         ROW                                                                             { $$ = TRUE; }
2821                         | STATEMENT                                                             { $$ = FALSE; }
2822                 ;
2823
2824 TriggerFuncArgs:
2825                         TriggerFuncArg                                                  { $$ = list_make1($1); }
2826                         | TriggerFuncArgs ',' TriggerFuncArg    { $$ = lappend($1, $3); }
2827                         | /*EMPTY*/                                                             { $$ = NIL; }
2828                 ;
2829
2830 TriggerFuncArg:
2831                         Iconst
2832                                 {
2833                                         char buf[64];
2834                                         snprintf(buf, sizeof(buf), "%d", $1);
2835                                         $$ = makeString(pstrdup(buf));
2836                                 }
2837                         | FCONST                                                                { $$ = makeString($1); }
2838                         | Sconst                                                                { $$ = makeString($1); }
2839                         | BCONST                                                                { $$ = makeString($1); }
2840                         | XCONST                                                                { $$ = makeString($1); }
2841                         | ColId                                                                 { $$ = makeString($1); }
2842                 ;
2843
2844 OptConstrFromTable:
2845                         FROM qualified_name                                             { $$ = $2; }
2846                         | /*EMPTY*/                                                             { $$ = NULL; }
2847                 ;
2848
2849 ConstraintAttributeSpec:
2850                         ConstraintDeferrabilitySpec
2851                                 { $$ = $1; }
2852                         | ConstraintDeferrabilitySpec ConstraintTimeSpec
2853                                 {
2854                                         if ($1 == 0 && $2 != 0)
2855                                                 ereport(ERROR,
2856                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2857                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2858                                                                  scanner_errposition(@1)));
2859                                         $$ = $1 | $2;
2860                                 }
2861                         | ConstraintTimeSpec
2862                                 {
2863                                         if ($1 != 0)
2864                                                 $$ = 3;
2865                                         else
2866                                                 $$ = 0;
2867                                 }
2868                         | ConstraintTimeSpec ConstraintDeferrabilitySpec
2869                                 {
2870                                         if ($2 == 0 && $1 != 0)
2871                                                 ereport(ERROR,
2872                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2873                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE"),
2874                                                                  scanner_errposition(@1)));
2875                                         $$ = $1 | $2;
2876                                 }
2877                         | /*EMPTY*/
2878                                 { $$ = 0; }
2879                 ;
2880
2881 ConstraintDeferrabilitySpec:
2882                         NOT DEFERRABLE                                                  { $$ = 0; }
2883                         | DEFERRABLE                                                    { $$ = 1; }
2884                 ;
2885
2886 ConstraintTimeSpec:
2887                         INITIALLY IMMEDIATE                                             { $$ = 0; }
2888                         | INITIALLY DEFERRED                                    { $$ = 2; }
2889                 ;
2890
2891
2892 DropTrigStmt:
2893                         DROP TRIGGER name ON qualified_name opt_drop_behavior
2894                                 {
2895                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
2896                                         n->relation = $5;
2897                                         n->property = $3;
2898                                         n->behavior = $6;
2899                                         n->removeType = OBJECT_TRIGGER;
2900                                         n->missing_ok = false;
2901                                         $$ = (Node *) n;
2902                                 }
2903                         | DROP TRIGGER IF_P EXISTS name ON qualified_name opt_drop_behavior
2904                                 {
2905                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
2906                                         n->relation = $7;
2907                                         n->property = $5;
2908                                         n->behavior = $8;
2909                                         n->removeType = OBJECT_TRIGGER;
2910                                         n->missing_ok = true;
2911                                         $$ = (Node *) n;
2912                                 }
2913                 ;
2914
2915
2916 /*****************************************************************************
2917  *
2918  *              QUERIES :
2919  *                              CREATE ASSERTION ...
2920  *                              DROP ASSERTION ...
2921  *
2922  *****************************************************************************/
2923
2924 CreateAssertStmt:
2925                         CREATE ASSERTION name CHECK '(' a_expr ')'
2926                         ConstraintAttributeSpec
2927                                 {
2928                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
2929                                         n->trigname = $3;
2930                                         n->args = list_make1($6);
2931                                         n->isconstraint  = TRUE;
2932                                         n->deferrable = ($8 & 1) != 0;
2933                                         n->initdeferred = ($8 & 2) != 0;
2934
2935                                         ereport(ERROR,
2936                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2937                                                          errmsg("CREATE ASSERTION is not yet implemented")));
2938
2939                                         $$ = (Node *)n;
2940                                 }
2941                 ;
2942
2943 DropAssertStmt:
2944                         DROP ASSERTION name opt_drop_behavior
2945                                 {
2946                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
2947                                         n->relation = NULL;
2948                                         n->property = $3;
2949                                         n->behavior = $4;
2950                                         n->removeType = OBJECT_TRIGGER; /* XXX */
2951                                         ereport(ERROR,
2952                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2953                                                          errmsg("DROP ASSERTION is not yet implemented")));
2954                                         $$ = (Node *) n;
2955                                 }
2956                 ;
2957
2958
2959 /*****************************************************************************
2960  *
2961  *              QUERY :
2962  *                              define (aggregate,operator,type)
2963  *
2964  *****************************************************************************/
2965
2966 DefineStmt:
2967                         CREATE AGGREGATE func_name aggr_args definition
2968                                 {
2969                                         DefineStmt *n = makeNode(DefineStmt);
2970                                         n->kind = OBJECT_AGGREGATE;
2971                                         n->oldstyle = false;
2972                                         n->defnames = $3;
2973                                         n->args = $4;
2974                                         n->definition = $5;
2975                                         $$ = (Node *)n;
2976                                 }
2977                         | CREATE AGGREGATE func_name old_aggr_definition
2978                                 {
2979                                         /* old-style (pre-8.2) syntax for CREATE AGGREGATE */
2980                                         DefineStmt *n = makeNode(DefineStmt);
2981                                         n->kind = OBJECT_AGGREGATE;
2982                                         n->oldstyle = true;
2983                                         n->defnames = $3;
2984                                         n->args = NIL;
2985                                         n->definition = $4;
2986                                         $$ = (Node *)n;
2987                                 }
2988                         | CREATE OPERATOR any_operator definition
2989                                 {
2990                                         DefineStmt *n = makeNode(DefineStmt);
2991                                         n->kind = OBJECT_OPERATOR;
2992                                         n->oldstyle = false;
2993                                         n->defnames = $3;
2994                                         n->args = NIL;
2995                                         n->definition = $4;
2996                                         $$ = (Node *)n;
2997                                 }
2998                         | CREATE TYPE_P any_name definition
2999                                 {
3000                                         DefineStmt *n = makeNode(DefineStmt);
3001                                         n->kind = OBJECT_TYPE;
3002                                         n->oldstyle = false;
3003                                         n->defnames = $3;
3004                                         n->args = NIL;
3005                                         n->definition = $4;
3006                                         $$ = (Node *)n;
3007                                 }
3008                         | CREATE TYPE_P any_name
3009                                 {
3010                                         /* Shell type (identified by lack of definition) */
3011                                         DefineStmt *n = makeNode(DefineStmt);
3012                                         n->kind = OBJECT_TYPE;
3013                                         n->oldstyle = false;
3014                                         n->defnames = $3;
3015                                         n->args = NIL;
3016                                         n->definition = NIL;
3017                                         $$ = (Node *)n;
3018                                 }
3019                         | CREATE TYPE_P any_name AS '(' TableFuncElementList ')'
3020                                 {
3021                                         CompositeTypeStmt *n = makeNode(CompositeTypeStmt);
3022                                         RangeVar *r = makeNode(RangeVar);
3023
3024                                         /* can't use qualified_name, sigh */
3025                                         switch (list_length($3))
3026                                         {
3027                                                 case 1:
3028                                                         r->catalogname = NULL;
3029                                                         r->schemaname = NULL;
3030                                                         r->relname = strVal(linitial($3));
3031                                                         break;
3032                                                 case 2:
3033                                                         r->catalogname = NULL;
3034                                                         r->schemaname = strVal(linitial($3));
3035                                                         r->relname = strVal(lsecond($3));
3036                                                         break;
3037                                                 case 3:
3038                                                         r->catalogname = strVal(linitial($3));
3039                                                         r->schemaname = strVal(lsecond($3));
3040                                                         r->relname = strVal(lthird($3));
3041                                                         break;
3042                                                 default:
3043                                                         ereport(ERROR,
3044                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
3045                                                                          errmsg("improper qualified name (too many dotted names): %s",
3046                                                                                         NameListToString($3)),
3047                                                                                         scanner_errposition(@3)));
3048                                                         break;
3049                                         }
3050                                         r->location = @3;
3051                                         n->typevar = r;
3052                                         n->coldeflist = $6;
3053                                         $$ = (Node *)n;
3054                                 }
3055                         | CREATE TYPE_P any_name AS ENUM_P '(' enum_val_list ')'
3056                                 {
3057                                         CreateEnumStmt *n = makeNode(CreateEnumStmt);
3058                                         n->typename = $3;
3059                                         n->vals = $7;
3060                                         $$ = (Node *)n;
3061                                 }
3062                         | CREATE TEXT_P SEARCH PARSER any_name definition
3063                                 {
3064                                         DefineStmt *n = makeNode(DefineStmt);
3065                                         n->kind = OBJECT_TSPARSER;
3066                                         n->args = NIL;
3067                                         n->defnames = $5;
3068                                         n->definition = $6;
3069                                         $$ = (Node *)n;
3070                                 }
3071                         | CREATE TEXT_P SEARCH DICTIONARY any_name definition
3072                                 {
3073                                         DefineStmt *n = makeNode(DefineStmt);
3074                                         n->kind = OBJECT_TSDICTIONARY;
3075                                         n->args = NIL;
3076                                         n->defnames = $5;
3077                                         n->definition = $6;
3078                                         $$ = (Node *)n;
3079                                 }
3080                         | CREATE TEXT_P SEARCH TEMPLATE any_name definition
3081                                 {
3082                                         DefineStmt *n = makeNode(DefineStmt);
3083                                         n->kind = OBJECT_TSTEMPLATE;
3084                                         n->args = NIL;
3085                                         n->defnames = $5;
3086                                         n->definition = $6;
3087                                         $$ = (Node *)n;
3088                                 }
3089                         | CREATE TEXT_P SEARCH CONFIGURATION any_name definition
3090                                 {
3091                                         DefineStmt *n = makeNode(DefineStmt);
3092                                         n->kind = OBJECT_TSCONFIGURATION;
3093                                         n->args = NIL;
3094                                         n->defnames = $5;
3095                                         n->definition = $6;
3096                                         $$ = (Node *)n;
3097                                 }
3098                 ;
3099
3100 definition: '(' def_list ')'                                            { $$ = $2; }
3101                 ;
3102
3103 def_list:       def_elem                                                                { $$ = list_make1($1); }
3104                         | def_list ',' def_elem                                 { $$ = lappend($1, $3); }
3105                 ;
3106
3107 def_elem:  ColLabel '=' def_arg
3108                                 {
3109                                         $$ = makeDefElem($1, (Node *)$3);
3110                                 }
3111                         | ColLabel
3112                                 {
3113                                         $$ = makeDefElem($1, NULL);
3114                                 }
3115                 ;
3116
3117 /* Note: any simple identifier will be returned as a type name! */
3118 def_arg:        func_type                                               { $$ = (Node *)$1; }
3119                         | reserved_keyword                              { $$ = (Node *)makeString(pstrdup($1)); }
3120                         | qual_all_Op                                   { $$ = (Node *)$1; }
3121                         | NumericOnly                                   { $$ = (Node *)$1; }
3122                         | Sconst                                                { $$ = (Node *)makeString($1); }
3123                 ;
3124
3125 aggr_args:      '(' type_list ')'                                               { $$ = $2; }
3126                         | '(' '*' ')'                                                   { $$ = NIL; }
3127                 ;
3128
3129 old_aggr_definition: '(' old_aggr_list ')'                      { $$ = $2; }
3130                 ;
3131
3132 old_aggr_list: old_aggr_elem                                            { $$ = list_make1($1); }
3133                         | old_aggr_list ',' old_aggr_elem               { $$ = lappend($1, $3); }
3134                 ;
3135
3136 old_aggr_elem:  IDENT '=' def_arg
3137                                 {
3138                                         $$ = makeDefElem($1, (Node *)$3);
3139                                 }
3140                 ;
3141
3142 enum_val_list:  Sconst
3143                                 { $$ = list_make1(makeString($1)); }
3144                         | enum_val_list ',' Sconst
3145                                 { $$ = lappend($1, makeString($3)); }
3146                 ;
3147
3148
3149 /*****************************************************************************
3150  *
3151  *              QUERIES :
3152  *                              CREATE OPERATOR CLASS ...
3153  *                              CREATE OPERATOR FAMILY ...
3154  *                              ALTER OPERATOR FAMILY ...
3155  *                              DROP OPERATOR CLASS ...
3156  *                              DROP OPERATOR FAMILY ...
3157  *
3158  *****************************************************************************/
3159
3160 CreateOpClassStmt:
3161                         CREATE OPERATOR CLASS any_name opt_default FOR TYPE_P Typename
3162                         USING access_method opt_opfamily AS opclass_item_list
3163                                 {
3164                                         CreateOpClassStmt *n = makeNode(CreateOpClassStmt);
3165                                         n->opclassname = $4;
3166                                         n->isDefault = $5;
3167                                         n->datatype = $8;
3168                                         n->amname = $10;
3169                                         n->opfamilyname = $11;
3170                                         n->items = $13;
3171                                         $$ = (Node *) n;
3172                                 }
3173                 ;
3174
3175 opclass_item_list:
3176                         opclass_item                                                    { $$ = list_make1($1); }
3177                         | opclass_item_list ',' opclass_item    { $$ = lappend($1, $3); }
3178                 ;
3179
3180 opclass_item:
3181                         OPERATOR Iconst any_operator opt_recheck
3182                                 {
3183                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3184                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
3185                                         n->name = $3;
3186                                         n->args = NIL;
3187                                         n->number = $2;
3188                                         $$ = (Node *) n;
3189                                 }
3190                         | OPERATOR Iconst any_operator oper_argtypes opt_recheck
3191                                 {
3192                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3193                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
3194                                         n->name = $3;
3195                                         n->args = $4;
3196                                         n->number = $2;
3197                                         $$ = (Node *) n;
3198                                 }
3199                         | FUNCTION Iconst func_name func_args
3200                                 {
3201                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3202                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
3203                                         n->name = $3;
3204                                         n->args = extractArgTypes($4);
3205                                         n->number = $2;
3206                                         $$ = (Node *) n;
3207                                 }
3208                         | FUNCTION Iconst '(' type_list ')' func_name func_args
3209                                 {
3210                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3211                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
3212                                         n->name = $6;
3213                                         n->args = extractArgTypes($7);
3214                                         n->number = $2;
3215                                         n->class_args = $4;
3216                                         $$ = (Node *) n;
3217                                 }
3218                         | STORAGE Typename
3219                                 {
3220                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3221                                         n->itemtype = OPCLASS_ITEM_STORAGETYPE;
3222                                         n->storedtype = $2;
3223                                         $$ = (Node *) n;
3224                                 }
3225                 ;
3226
3227 opt_default:    DEFAULT                                         { $$ = TRUE; }
3228                         | /*EMPTY*/                                             { $$ = FALSE; }
3229                 ;
3230
3231 opt_opfamily:   FAMILY any_name                         { $$ = $2; }
3232                         | /*EMPTY*/                                             { $$ = NIL; }
3233                 ;
3234
3235 opt_recheck:    RECHECK
3236                                 {
3237                                         ereport(ERROR,
3238                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3239                                                          errmsg("RECHECK is no longer supported"),
3240                                                          errhint("Update your data type."),
3241                                                          scanner_errposition(@1)));
3242                                         $$ = TRUE;
3243                                 }
3244                         | /*EMPTY*/                                             { $$ = FALSE; }
3245                 ;
3246
3247
3248 CreateOpFamilyStmt:
3249                         CREATE OPERATOR FAMILY any_name USING access_method
3250                                 {
3251                                         CreateOpFamilyStmt *n = makeNode(CreateOpFamilyStmt);
3252                                         n->opfamilyname = $4;
3253                                         n->amname = $6;
3254                                         $$ = (Node *) n;
3255                                 }
3256                 ;
3257
3258 AlterOpFamilyStmt:
3259                         ALTER OPERATOR FAMILY any_name USING access_method ADD_P opclass_item_list
3260                                 {
3261                                         AlterOpFamilyStmt *n = makeNode(AlterOpFamilyStmt);
3262                                         n->opfamilyname = $4;
3263                                         n->amname = $6;
3264                                         n->isDrop = false;
3265                                         n->items = $8;
3266                                         $$ = (Node *) n;
3267                                 }
3268                         | ALTER OPERATOR FAMILY any_name USING access_method DROP opclass_drop_list
3269                                 {
3270                                         AlterOpFamilyStmt *n = makeNode(AlterOpFamilyStmt);
3271                                         n->opfamilyname = $4;
3272                                         n->amname = $6;
3273                                         n->isDrop = true;
3274                                         n->items = $8;
3275                                         $$ = (Node *) n;
3276                                 }
3277                 ;
3278
3279 opclass_drop_list:
3280                         opclass_drop                                                    { $$ = list_make1($1); }
3281                         | opclass_drop_list ',' opclass_drop    { $$ = lappend($1, $3); }
3282                 ;
3283
3284 opclass_drop:
3285                         OPERATOR Iconst '(' type_list ')'
3286                                 {
3287                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3288                                         n->itemtype = OPCLASS_ITEM_OPERATOR;
3289                                         n->number = $2;
3290                                         n->args = $4;
3291                                         $$ = (Node *) n;
3292                                 }
3293                         | FUNCTION Iconst '(' type_list ')'
3294                                 {
3295                                         CreateOpClassItem *n = makeNode(CreateOpClassItem);
3296                                         n->itemtype = OPCLASS_ITEM_FUNCTION;
3297                                         n->number = $2;
3298                                         n->args = $4;
3299                                         $$ = (Node *) n;
3300                                 }
3301                 ;
3302
3303
3304 DropOpClassStmt:
3305                         DROP OPERATOR CLASS any_name USING access_method opt_drop_behavior
3306                                 {
3307                                         RemoveOpClassStmt *n = makeNode(RemoveOpClassStmt);
3308                                         n->opclassname = $4;
3309                                         n->amname = $6;
3310                                         n->behavior = $7;
3311                                         n->missing_ok = false;
3312                                         $$ = (Node *) n;
3313                                 }
3314                         | DROP OPERATOR CLASS IF_P EXISTS any_name USING access_method opt_drop_behavior
3315                                 {
3316                                         RemoveOpClassStmt *n = makeNode(RemoveOpClassStmt);
3317                                         n->opclassname = $6;
3318                                         n->amname = $8;
3319                                         n->behavior = $9;
3320                                         n->missing_ok = true;
3321                                         $$ = (Node *) n;
3322                                 }
3323                 ;
3324
3325 DropOpFamilyStmt:
3326                         DROP OPERATOR FAMILY any_name USING access_method opt_drop_behavior
3327                                 {
3328                                         RemoveOpFamilyStmt *n = makeNode(RemoveOpFamilyStmt);
3329                                         n->opfamilyname = $4;
3330                                         n->amname = $6;
3331                                         n->behavior = $7;
3332                                         n->missing_ok = false;
3333                                         $$ = (Node *) n;
3334                                 }
3335                         | DROP OPERATOR FAMILY IF_P EXISTS any_name USING access_method opt_drop_behavior
3336                                 {
3337                                         RemoveOpFamilyStmt *n = makeNode(RemoveOpFamilyStmt);
3338                                         n->opfamilyname = $6;
3339                                         n->amname = $8;
3340                                         n->behavior = $9;
3341                                         n->missing_ok = true;
3342                                         $$ = (Node *) n;
3343                                 }
3344                 ;
3345
3346
3347 /*****************************************************************************
3348  *
3349  *              QUERY:
3350  *
3351  *              DROP OWNED BY username [, username ...] [ RESTRICT | CASCADE ]
3352  *              REASSIGN OWNED BY username [, username ...] TO username
3353  *
3354  *****************************************************************************/
3355 DropOwnedStmt:
3356                         DROP OWNED BY name_list opt_drop_behavior
3357                                 {
3358                                         DropOwnedStmt *n = makeNode(DropOwnedStmt);
3359                                         n->roles = $4;
3360                                         n->behavior = $5;
3361                                         $$ = (Node *)n;
3362                                 }
3363                 ;
3364
3365 ReassignOwnedStmt:
3366                         REASSIGN OWNED BY name_list TO name
3367                                 {
3368                                         ReassignOwnedStmt *n = makeNode(ReassignOwnedStmt);
3369                                         n->roles = $4;
3370                                         n->newrole = $6;
3371                                         $$ = (Node *)n;
3372                                 }
3373                 ;
3374
3375 /*****************************************************************************
3376  *
3377  *              QUERY:
3378  *
3379  *              DROP itemtype [ IF EXISTS ] itemname [, itemname ...]
3380  *           [ RESTRICT | CASCADE ]
3381  *
3382  *****************************************************************************/
3383
3384 DropStmt:       DROP drop_type IF_P EXISTS any_name_list opt_drop_behavior
3385                                 {
3386                                         DropStmt *n = makeNode(DropStmt);
3387                                         n->removeType = $2;
3388                                         n->missing_ok = TRUE;
3389                                         n->objects = $5;
3390                                         n->behavior = $6;
3391                                         $$ = (Node *)n;
3392                                 }
3393                         | DROP drop_type any_name_list opt_drop_behavior
3394                                 {
3395                                         DropStmt *n = makeNode(DropStmt);
3396                                         n->removeType = $2;
3397                                         n->missing_ok = FALSE;
3398                                         n->objects = $3;
3399                                         n->behavior = $4;
3400                                         $$ = (Node *)n;
3401                                 }
3402                 ;
3403
3404
3405 drop_type:      TABLE                                                                   { $$ = OBJECT_TABLE; }
3406                         | SEQUENCE                                                              { $$ = OBJECT_SEQUENCE; }
3407                         | VIEW                                                                  { $$ = OBJECT_VIEW; }
3408                         | INDEX                                                                 { $$ = OBJECT_INDEX; }
3409                         | TYPE_P                                                                { $$ = OBJECT_TYPE; }
3410                         | DOMAIN_P                                                              { $$ = OBJECT_DOMAIN; }
3411                         | CONVERSION_P                                                  { $$ = OBJECT_CONVERSION; }
3412                         | SCHEMA                                                                { $$ = OBJECT_SCHEMA; }
3413                         | TEXT_P SEARCH PARSER                                  { $$ = OBJECT_TSPARSER; }
3414                         | TEXT_P SEARCH DICTIONARY                              { $$ = OBJECT_TSDICTIONARY; }
3415                         | TEXT_P SEARCH TEMPLATE                                { $$ = OBJECT_TSTEMPLATE; }
3416                         | TEXT_P SEARCH CONFIGURATION                   { $$ = OBJECT_TSCONFIGURATION; }
3417                 ;
3418
3419 any_name_list:
3420                         any_name                                                                { $$ = list_make1($1); }
3421                         | any_name_list ',' any_name                    { $$ = lappend($1, $3); }
3422                 ;
3423
3424 any_name:       ColId                                           { $$ = list_make1(makeString($1)); }
3425                         | ColId attrs                           { $$ = lcons(makeString($1), $2); }
3426                 ;
3427
3428 attrs:          '.' attr_name
3429                                         { $$ = list_make1(makeString($2)); }
3430                         | attrs '.' attr_name
3431                                         { $$ = lappend($1, makeString($3)); }
3432                 ;
3433
3434
3435 /*****************************************************************************
3436  *
3437  *              QUERY:
3438  *                              truncate table relname1, relname2, ...
3439  *
3440  *****************************************************************************/
3441
3442 TruncateStmt:
3443                         TRUNCATE opt_table qualified_name_list opt_restart_seqs opt_drop_behavior
3444                                 {
3445                                         TruncateStmt *n = makeNode(TruncateStmt);
3446                                         n->relations = $3;
3447                                         n->restart_seqs = $4;
3448                                         n->behavior = $5;
3449                                         $$ = (Node *)n;
3450                                 }
3451                 ;
3452
3453 opt_restart_seqs:
3454                         CONTINUE_P IDENTITY_P           { $$ = false; }
3455                         | RESTART IDENTITY_P            { $$ = true; }
3456                         | /* EMPTY */                           { $$ = false; }
3457                 ;
3458
3459 /*****************************************************************************
3460  *
3461  *      The COMMENT ON statement can take different forms based upon the type of
3462  *      the object associated with the comment. The form of the statement is:
3463  *
3464  *      COMMENT ON [ [ DATABASE | DOMAIN | INDEX | SEQUENCE | TABLE | TYPE | VIEW |
3465  *                                 CONVERSION | LANGUAGE | OPERATOR CLASS | LARGE OBJECT |
3466  *                                 CAST | COLUMN | SCHEMA | TABLESPACE | ROLE | 
3467  *                                 TEXT SEARCH PARSER | TEXT SEARCH DICTIONARY |
3468  *                                 TEXT SEARCH TEMPLATE |
3469  *                                 TEXT SEARCH CONFIGURATION ] <objname> |
3470  *                               AGGREGATE <aggname> (arg1, ...) |
3471  *                               FUNCTION <funcname> (arg1, arg2, ...) |
3472  *                               OPERATOR <op> (leftoperand_typ, rightoperand_typ) |
3473  *                               TRIGGER <triggername> ON <relname> |
3474  *                               CONSTRAINT <constraintname> ON <relname> |
3475  *                               RULE <rulename> ON <relname> ]
3476  *                         IS 'text'
3477  *
3478  *****************************************************************************/
3479
3480 CommentStmt:
3481                         COMMENT ON comment_type any_name IS comment_text
3482                                 {
3483                                         CommentStmt *n = makeNode(CommentStmt);
3484                                         n->objtype = $3;
3485                                         n->objname = $4;
3486                                         n->objargs = NIL;
3487                                         n->comment = $6;
3488                                         $$ = (Node *) n;
3489                                 }
3490                         | COMMENT ON AGGREGATE func_name aggr_args IS comment_text
3491                                 {
3492                                         CommentStmt *n = makeNode(CommentStmt);
3493                                         n->objtype = OBJECT_AGGREGATE;
3494                                         n->objname = $4;
3495                                         n->objargs = $5;
3496                                         n->comment = $7;
3497                                         $$ = (Node *) n;
3498                                 }
3499                         | COMMENT ON FUNCTION func_name func_args IS comment_text
3500                                 {
3501                                         CommentStmt *n = makeNode(CommentStmt);
3502                                         n->objtype = OBJECT_FUNCTION;
3503                                         n->objname = $4;
3504                                         n->objargs = extractArgTypes($5);
3505                                         n->comment = $7;
3506                                         $$ = (Node *) n;
3507                                 }
3508                         | COMMENT ON OPERATOR any_operator oper_argtypes IS comment_text
3509                                 {
3510                                         CommentStmt *n = makeNode(CommentStmt);
3511                                         n->objtype = OBJECT_OPERATOR;
3512                                         n->objname = $4;
3513                                         n->objargs = $5;
3514                                         n->comment = $7;
3515                                         $$ = (Node *) n;
3516                                 }
3517                         | COMMENT ON CONSTRAINT name ON any_name IS comment_text
3518                                 {
3519                                         CommentStmt *n = makeNode(CommentStmt);
3520                                         n->objtype = OBJECT_CONSTRAINT;
3521                                         n->objname = lappend($6, makeString($4));
3522                                         n->objargs = NIL;
3523                                         n->comment = $8;
3524                                         $$ = (Node *) n;
3525                                 }
3526                         | COMMENT ON RULE name ON any_name IS comment_text
3527                                 {
3528                                         CommentStmt *n = makeNode(CommentStmt);
3529                                         n->objtype = OBJECT_RULE;
3530                                         n->objname = lappend($6, makeString($4));
3531                                         n->objargs = NIL;
3532                                         n->comment = $8;
3533                                         $$ = (Node *) n;
3534                                 }
3535                         | COMMENT ON RULE name IS comment_text
3536                                 {
3537                                         /* Obsolete syntax supported for awhile for compatibility */
3538                                         CommentStmt *n = makeNode(CommentStmt);
3539                                         n->objtype = OBJECT_RULE;
3540                                         n->objname = list_make1(makeString($4));
3541                                         n->objargs = NIL;
3542                                         n->comment = $6;
3543                                         $$ = (Node *) n;
3544                                 }
3545                         | COMMENT ON TRIGGER name ON any_name IS comment_text
3546                                 {
3547                                         CommentStmt *n = makeNode(CommentStmt);
3548                                         n->objtype = OBJECT_TRIGGER;
3549                                         n->objname = lappend($6, makeString($4));
3550                                         n->objargs = NIL;
3551                                         n->comment = $8;
3552                                         $$ = (Node *) n;
3553                                 }
3554                         | COMMENT ON OPERATOR CLASS any_name USING access_method IS comment_text
3555                                 {
3556                                         CommentStmt *n = makeNode(CommentStmt);
3557                                         n->objtype = OBJECT_OPCLASS;
3558                                         n->objname = $5;
3559                                         n->objargs = list_make1(makeString($7));
3560                                         n->comment = $9;
3561                                         $$ = (Node *) n;
3562                                 }
3563                         | COMMENT ON OPERATOR FAMILY any_name USING access_method IS comment_text
3564                                 {
3565                                         CommentStmt *n = makeNode(CommentStmt);
3566                                         n->objtype = OBJECT_OPFAMILY;
3567                                         n->objname = $5;
3568                                         n->objargs = list_make1(makeString($7));
3569                                         n->comment = $9;
3570                                         $$ = (Node *) n;
3571                                 }
3572                         | COMMENT ON LARGE_P OBJECT_P NumericOnly IS comment_text
3573                                 {
3574                                         CommentStmt *n = makeNode(CommentStmt);
3575                                         n->objtype = OBJECT_LARGEOBJECT;
3576                                         n->objname = list_make1($5);
3577                                         n->objargs = NIL;
3578                                         n->comment = $7;
3579                                         $$ = (Node *) n;
3580                                 }
3581                         | COMMENT ON CAST '(' Typename AS Typename ')' IS comment_text
3582                                 {
3583                                         CommentStmt *n = makeNode(CommentStmt);
3584                                         n->objtype = OBJECT_CAST;
3585                                         n->objname = list_make1($5);
3586                                         n->objargs = list_make1($7);
3587                                         n->comment = $10;
3588                                         $$ = (Node *) n;
3589                                 }
3590                         | COMMENT ON opt_procedural LANGUAGE any_name IS comment_text
3591                                 {
3592                                         CommentStmt *n = makeNode(CommentStmt);
3593                                         n->objtype = OBJECT_LANGUAGE;
3594                                         n->objname = $5;
3595                                         n->objargs = NIL;
3596                                         n->comment = $7;
3597                                         $$ = (Node *) n;
3598                                 }
3599                         | COMMENT ON TEXT_P SEARCH PARSER any_name IS comment_text
3600                                 {
3601                                         CommentStmt *n = makeNode(CommentStmt);
3602                                         n->objtype = OBJECT_TSPARSER;
3603                                         n->objname = $6;
3604                                         n->comment = $8;
3605                                         $$ = (Node *) n;
3606                                 }
3607                         | COMMENT ON TEXT_P SEARCH DICTIONARY any_name IS comment_text
3608                                 {
3609                                         CommentStmt *n = makeNode(CommentStmt);
3610                                         n->objtype = OBJECT_TSDICTIONARY;
3611                                         n->objname = $6;
3612                                         n->comment = $8;
3613                                         $$ = (Node *) n;
3614                                 }
3615                         | COMMENT ON TEXT_P SEARCH TEMPLATE any_name IS comment_text
3616                                 {
3617                                         CommentStmt *n = makeNode(CommentStmt);
3618                                         n->objtype = OBJECT_TSTEMPLATE;
3619                                         n->objname = $6;
3620                                         n->comment = $8;
3621                                         $$ = (Node *) n;
3622                                 }
3623                         | COMMENT ON TEXT_P SEARCH CONFIGURATION any_name IS comment_text
3624                                 {
3625                                         CommentStmt *n = makeNode(CommentStmt);
3626                                         n->objtype = OBJECT_TSCONFIGURATION;
3627                                         n->objname = $6;
3628                                         n->comment = $8;
3629                                         $$ = (Node *) n;
3630                                 }
3631                 ;
3632
3633 comment_type:
3634                         COLUMN                                                          { $$ = OBJECT_COLUMN; }
3635                         | DATABASE                                                      { $$ = OBJECT_DATABASE; }
3636                         | SCHEMA                                                        { $$ = OBJECT_SCHEMA; }
3637                         | INDEX                                                         { $$ = OBJECT_INDEX; }
3638                         | SEQUENCE                                                      { $$ = OBJECT_SEQUENCE; }
3639                         | TABLE                                                         { $$ = OBJECT_TABLE; }
3640                         | DOMAIN_P                                                      { $$ = OBJECT_TYPE; }
3641                         | TYPE_P                                                        { $$ = OBJECT_TYPE; }
3642                         | VIEW                                                          { $$ = OBJECT_VIEW; }
3643                         | CONVERSION_P                                          { $$ = OBJECT_CONVERSION; }
3644                         | TABLESPACE                                            { $$ = OBJECT_TABLESPACE; }
3645                         | ROLE                                                          { $$ = OBJECT_ROLE; }
3646                 ;
3647
3648 comment_text:
3649                         Sconst                                                          { $$ = $1; }
3650                         | NULL_P                                                        { $$ = NULL; }
3651                 ;
3652
3653 /*****************************************************************************
3654  *
3655  *              QUERY:
3656  *                      fetch/move
3657  *
3658  *****************************************************************************/
3659
3660 FetchStmt:      FETCH fetch_direction from_in name
3661                                 {
3662                                         FetchStmt *n = (FetchStmt *) $2;
3663                                         n->portalname = $4;
3664                                         n->ismove = FALSE;
3665                                         $$ = (Node *)n;
3666                                 }
3667                         | FETCH name
3668                                 {
3669                                         FetchStmt *n = makeNode(FetchStmt);
3670                                         n->direction = FETCH_FORWARD;
3671                                         n->howMany = 1;
3672                                         n->portalname = $2;
3673                                         n->ismove = FALSE;
3674                                         $$ = (Node *)n;
3675                                 }
3676                         | MOVE fetch_direction from_in name
3677                                 {
3678                                         FetchStmt *n = (FetchStmt *) $2;
3679                                         n->portalname = $4;
3680                                         n->ismove = TRUE;
3681                                         $$ = (Node *)n;
3682                                 }
3683                         | MOVE name
3684                                 {
3685                                         FetchStmt *n = makeNode(FetchStmt);
3686                                         n->direction = FETCH_FORWARD;
3687                                         n->howMany = 1;
3688                                         n->portalname = $2;
3689                                         n->ismove = TRUE;
3690                                         $$ = (Node *)n;
3691                                 }
3692                 ;
3693
3694 fetch_direction:
3695                         /*EMPTY*/
3696                                 {
3697                                         FetchStmt *n = makeNode(FetchStmt);
3698                                         n->direction = FETCH_FORWARD;
3699                                         n->howMany = 1;
3700                                         $$ = (Node *)n;
3701                                 }
3702                         | NEXT
3703                                 {
3704                                         FetchStmt *n = makeNode(FetchStmt);
3705                                         n->direction = FETCH_FORWARD;
3706                                         n->howMany = 1;
3707                                         $$ = (Node *)n;
3708                                 }
3709                         | PRIOR
3710                                 {
3711                                         FetchStmt *n = makeNode(FetchStmt);
3712                                         n->direction = FETCH_BACKWARD;
3713                                         n->howMany = 1;
3714                                         $$ = (Node *)n;
3715                                 }
3716                         | FIRST_P
3717                                 {
3718                                         FetchStmt *n = makeNode(FetchStmt);
3719                                         n->direction = FETCH_ABSOLUTE;
3720                                         n->howMany = 1;
3721                                         $$ = (Node *)n;
3722                                 }
3723                         | LAST_P
3724                                 {
3725                                         FetchStmt *n = makeNode(FetchStmt);
3726                                         n->direction = FETCH_ABSOLUTE;
3727                                         n->howMany = -1;
3728                                         $$ = (Node *)n;
3729                                 }
3730                         | ABSOLUTE_P SignedIconst
3731                                 {
3732                                         FetchStmt *n = makeNode(FetchStmt);
3733                                         n->direction = FETCH_ABSOLUTE;
3734                                         n->howMany = $2;
3735                                         $$ = (Node *)n;
3736                                 }
3737                         | RELATIVE_P SignedIconst
3738                                 {
3739                                         FetchStmt *n = makeNode(FetchStmt);
3740                                         n->direction = FETCH_RELATIVE;
3741                                         n->howMany = $2;
3742                                         $$ = (Node *)n;
3743                                 }
3744                         | SignedIconst
3745                                 {
3746                                         FetchStmt *n = makeNode(FetchStmt);
3747                                         n->direction = FETCH_FORWARD;
3748                                         n->howMany = $1;
3749                                         $$ = (Node *)n;
3750                                 }
3751                         | ALL
3752                                 {
3753                                         FetchStmt *n = makeNode(FetchStmt);
3754                                         n->direction = FETCH_FORWARD;
3755                                         n->howMany = FETCH_ALL;
3756                                         $$ = (Node *)n;
3757                                 }
3758                         | FORWARD
3759                                 {
3760                                         FetchStmt *n = makeNode(FetchStmt);
3761                                         n->direction = FETCH_FORWARD;
3762                                         n->howMany = 1;
3763                                         $$ = (Node *)n;
3764                                 }
3765                         | FORWARD SignedIconst
3766                                 {
3767                                         FetchStmt *n = makeNode(FetchStmt);
3768                                         n->direction = FETCH_FORWARD;
3769                                         n->howMany = $2;
3770                                         $$ = (Node *)n;
3771                                 }
3772                         | FORWARD ALL
3773                                 {
3774                                         FetchStmt *n = makeNode(FetchStmt);
3775                                         n->direction = FETCH_FORWARD;
3776                                         n->howMany = FETCH_ALL;
3777                                         $$ = (Node *)n;
3778                                 }
3779                         | BACKWARD
3780                                 {
3781                                         FetchStmt *n = makeNode(FetchStmt);
3782                                         n->direction = FETCH_BACKWARD;
3783                                         n->howMany = 1;
3784                                         $$ = (Node *)n;
3785                                 }
3786                         | BACKWARD SignedIconst
3787                                 {
3788                                         FetchStmt *n = makeNode(FetchStmt);
3789                                         n->direction = FETCH_BACKWARD;
3790                                         n->howMany = $2;
3791                                         $$ = (Node *)n;
3792                                 }
3793                         | BACKWARD ALL
3794                                 {
3795                                         FetchStmt *n = makeNode(FetchStmt);
3796                                         n->direction = FETCH_BACKWARD;
3797                                         n->howMany = FETCH_ALL;
3798                                         $$ = (Node *)n;
3799                                 }
3800                 ;
3801
3802 from_in:        FROM                                                                    {}
3803                         | IN_P                                                                  {}
3804                 ;
3805
3806
3807 /*****************************************************************************
3808  *
3809  * GRANT and REVOKE statements
3810  *
3811  *****************************************************************************/
3812
3813 GrantStmt:      GRANT privileges ON privilege_target TO grantee_list
3814                         opt_grant_grant_option
3815                                 {
3816                                         GrantStmt *n = makeNode(GrantStmt);
3817                                         n->is_grant = true;
3818                                         n->privileges = $2;
3819                                         n->objtype = ($4)->objtype;
3820                                         n->objects = ($4)->objs;
3821                                         n->grantees = $6;
3822                                         n->grant_option = $7;
3823                                         $$ = (Node*)n;
3824                                 }
3825                 ;
3826
3827 RevokeStmt:
3828                         REVOKE privileges ON privilege_target
3829                         FROM grantee_list opt_drop_behavior
3830                                 {
3831                                         GrantStmt *n = makeNode(GrantStmt);
3832                                         n->is_grant = false;
3833                                         n->grant_option = false;
3834                                         n->privileges = $2;
3835                                         n->objtype = ($4)->objtype;
3836                                         n->objects = ($4)->objs;
3837                                         n->grantees = $6;
3838                                         n->behavior = $7;
3839                                         $$ = (Node *)n;
3840                                 }
3841                         | REVOKE GRANT OPTION FOR privileges ON privilege_target
3842                         FROM grantee_list opt_drop_behavior
3843                                 {
3844                                         GrantStmt *n = makeNode(GrantStmt);
3845                                         n->is_grant = false;
3846                                         n->grant_option = true;
3847                                         n->privileges = $5;
3848                                         n->objtype = ($7)->objtype;
3849                                         n->objects = ($7)->objs;
3850                                         n->grantees = $9;
3851                                         n->behavior = $10;
3852                                         $$ = (Node *)n;
3853                                 }
3854                 ;
3855
3856
3857 /*
3858  * A privilege list is represented as a list of strings; the validity of
3859  * the privilege names gets checked at execution.  This is a bit annoying
3860  * but we have little choice because of the syntactic conflict with lists
3861  * of role names in GRANT/REVOKE.  What's more, we have to call out in
3862  * the "privilege" production any reserved keywords that need to be usable
3863  * as privilege names.
3864  */
3865
3866 /* either ALL [PRIVILEGES] or a list of individual privileges */
3867 privileges: privilege_list
3868                                 { $$ = $1; }
3869                         | ALL
3870                                 { $$ = NIL; }
3871                         | ALL PRIVILEGES
3872                                 { $$ = NIL; }
3873                 ;
3874
3875 privilege_list: privilege
3876                                         { $$ = list_make1(makeString($1)); }
3877                         | privilege_list ',' privilege
3878                                         { $$ = lappend($1, makeString($3)); }
3879                 ;
3880
3881 privilege:      SELECT                                                                  { $$ = pstrdup($1); }
3882                         | REFERENCES                                                    { $$ = pstrdup($1); }
3883                         | CREATE                                                                { $$ = pstrdup($1); }
3884                         | ColId                                                                 { $$ = $1; }
3885                 ;
3886
3887
3888 /* Don't bother trying to fold the first two rules into one using
3889  * opt_table.  You're going to get conflicts.
3890  */
3891 privilege_target:
3892                         qualified_name_list
3893                                 {
3894                                         PrivTarget *n = makeNode(PrivTarget);
3895                                         n->objtype = ACL_OBJECT_RELATION;
3896                                         n->objs = $1;
3897                                         $$ = n;
3898                                 }
3899                         | TABLE qualified_name_list
3900                                 {
3901                                         PrivTarget *n = makeNode(PrivTarget);
3902                                         n->objtype = ACL_OBJECT_RELATION;
3903                                         n->objs = $2;
3904                                         $$ = n;
3905                                 }
3906                         | SEQUENCE qualified_name_list
3907                                 {
3908                                         PrivTarget *n = makeNode(PrivTarget);
3909                                         n->objtype = ACL_OBJECT_SEQUENCE;
3910                                         n->objs = $2;
3911                                         $$ = n;
3912                                 }
3913                         | FUNCTION function_with_argtypes_list
3914                                 {
3915                                         PrivTarget *n = makeNode(PrivTarget);
3916                                         n->objtype = ACL_OBJECT_FUNCTION;
3917                                         n->objs = $2;
3918                                         $$ = n;
3919                                 }
3920                         | DATABASE name_list
3921                                 {
3922                                         PrivTarget *n = makeNode(PrivTarget);
3923                                         n->objtype = ACL_OBJECT_DATABASE;
3924                                         n->objs = $2;
3925                                         $$ = n;
3926                                 }
3927                         | LANGUAGE name_list
3928                                 {
3929                                         PrivTarget *n = makeNode(PrivTarget);
3930                                         n->objtype = ACL_OBJECT_LANGUAGE;
3931                                         n->objs = $2;
3932                                         $$ = n;
3933                                 }
3934                         | SCHEMA name_list
3935                                 {
3936                                         PrivTarget *n = makeNode(PrivTarget);
3937                                         n->objtype = ACL_OBJECT_NAMESPACE;
3938                                         n->objs = $2;
3939                                         $$ = n;
3940                                 }
3941                         | TABLESPACE name_list
3942                                 {
3943                                         PrivTarget *n = makeNode(PrivTarget);
3944                                         n->objtype = ACL_OBJECT_TABLESPACE;
3945                                         n->objs = $2;
3946                                         $$ = n;
3947                                 }
3948                 ;
3949
3950
3951 grantee_list:
3952                         grantee                                                                 { $$ = list_make1($1); }
3953                         | grantee_list ',' grantee                              { $$ = lappend($1, $3); }
3954                 ;
3955
3956 grantee:        RoleId
3957                                 {
3958                                         PrivGrantee *n = makeNode(PrivGrantee);
3959                                         /* This hack lets us avoid reserving PUBLIC as a keyword*/
3960                                         if (strcmp($1, "public") == 0)
3961                                                 n->rolname = NULL;
3962                                         else
3963                                                 n->rolname = $1;
3964                                         $$ = (Node *)n;
3965                                 }
3966                         | GROUP_P RoleId
3967                                 {
3968                                         PrivGrantee *n = makeNode(PrivGrantee);
3969                                         /* Treat GROUP PUBLIC as a synonym for PUBLIC */
3970                                         if (strcmp($2, "public") == 0)
3971                                                 n->rolname = NULL;
3972                                         else
3973                                                 n->rolname = $2;
3974                                         $$ = (Node *)n;
3975                                 }
3976                 ;
3977
3978
3979 opt_grant_grant_option:
3980                         WITH GRANT OPTION { $$ = TRUE; }
3981                         | /*EMPTY*/ { $$ = FALSE; }
3982                 ;
3983
3984 function_with_argtypes_list:
3985                         function_with_argtypes                                  { $$ = list_make1($1); }
3986                         | function_with_argtypes_list ',' function_with_argtypes
3987                                                                                                         { $$ = lappend($1, $3); }
3988                 ;
3989
3990 function_with_argtypes:
3991                         func_name func_args
3992                                 {
3993                                         FuncWithArgs *n = makeNode(FuncWithArgs);
3994                                         n->funcname = $1;
3995                                         n->funcargs = extractArgTypes($2);
3996                                         $$ = n;
3997                                 }
3998                 ;
3999
4000 /*****************************************************************************
4001  *
4002  * GRANT and REVOKE ROLE statements
4003  *
4004  *****************************************************************************/
4005
4006 GrantRoleStmt:
4007                         GRANT privilege_list TO name_list opt_grant_admin_option opt_granted_by
4008                                 {
4009                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
4010                                         n->is_grant = true;
4011                                         n->granted_roles = $2;
4012                                         n->grantee_roles = $4;
4013                                         n->admin_opt = $5;
4014                                         n->grantor = $6;
4015                                         $$ = (Node*)n;
4016                                 }
4017                 ;
4018
4019 RevokeRoleStmt:
4020                         REVOKE privilege_list FROM name_list opt_granted_by opt_drop_behavior
4021                                 {
4022                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
4023                                         n->is_grant = false;
4024                                         n->admin_opt = false;
4025                                         n->granted_roles = $2;
4026                                         n->grantee_roles = $4;
4027                                         n->behavior = $6;
4028                                         $$ = (Node*)n;
4029                                 }
4030                         | REVOKE ADMIN OPTION FOR privilege_list FROM name_list opt_granted_by opt_drop_behavior
4031                                 {
4032                                         GrantRoleStmt *n = makeNode(GrantRoleStmt);
4033                                         n->is_grant = false;
4034                                         n->admin_opt = true;
4035                                         n->granted_roles = $5;
4036                                         n->grantee_roles = $7;
4037                                         n->behavior = $9;
4038                                         $$ = (Node*)n;
4039                                 }
4040                 ;
4041
4042 opt_grant_admin_option: WITH ADMIN OPTION                               { $$ = TRUE; }
4043                         | /*EMPTY*/                                                                     { $$ = FALSE; }
4044                 ;
4045
4046 opt_granted_by: GRANTED BY RoleId                                               { $$ = $3; }
4047                         | /*EMPTY*/                                                                     { $$ = NULL; }
4048                 ;
4049
4050
4051 /*****************************************************************************
4052  *
4053  *              QUERY: CREATE INDEX
4054  *
4055  * Note: we can't factor CONCURRENTLY into a separate production without
4056  * making it a reserved word.
4057  *
4058  * Note: we cannot put TABLESPACE clause after WHERE clause unless we are
4059  * willing to make TABLESPACE a fully reserved word.
4060  *****************************************************************************/
4061
4062 IndexStmt:      CREATE index_opt_unique INDEX index_name
4063                         ON qualified_name access_method_clause '(' index_params ')'
4064                         opt_definition OptTableSpace where_clause
4065                                 {
4066                                         IndexStmt *n = makeNode(IndexStmt);
4067                                         n->unique = $2;
4068                                         n->concurrent = false;
4069                                         n->idxname = $4;
4070                                         n->relation = $6;
4071                                         n->accessMethod = $7;
4072                                         n->indexParams = $9;
4073                                         n->options = $11;
4074                                         n->tableSpace = $12;
4075                                         n->whereClause = $13;
4076                                         $$ = (Node *)n;
4077                                 }
4078                         | CREATE index_opt_unique INDEX CONCURRENTLY index_name
4079                         ON qualified_name access_method_clause '(' index_params ')'
4080                         opt_definition OptTableSpace where_clause
4081                                 {
4082                                         IndexStmt *n = makeNode(IndexStmt);
4083                                         n->unique = $2;
4084                                         n->concurrent = true;
4085                                         n->idxname = $5;
4086                                         n->relation = $7;
4087                                         n->accessMethod = $8;
4088                                         n->indexParams = $10;
4089                                         n->options = $12;
4090                                         n->tableSpace = $13;
4091                                         n->whereClause = $14;
4092                                         $$ = (Node *)n;
4093                                 }
4094                 ;
4095
4096 index_opt_unique:
4097                         UNIQUE                                                                  { $$ = TRUE; }
4098                         | /*EMPTY*/                                                             { $$ = FALSE; }
4099                 ;
4100
4101 access_method_clause:
4102                         USING access_method                                             { $$ = $2; }
4103                         | /*EMPTY*/                                                             { $$ = DEFAULT_INDEX_TYPE; }
4104                 ;
4105
4106 index_params:   index_elem                                                      { $$ = list_make1($1); }
4107                         | index_params ',' index_elem                   { $$ = lappend($1, $3); }
4108                 ;
4109
4110 /*
4111  * Index attributes can be either simple column references, or arbitrary
4112  * expressions in parens.  For backwards-compatibility reasons, we allow
4113  * an expression that's just a function call to be written without parens.
4114  */
4115 index_elem:     ColId opt_class opt_asc_desc opt_nulls_order
4116                                 {
4117                                         $$ = makeNode(IndexElem);
4118                                         $$->name = $1;
4119                                         $$->expr = NULL;
4120                                         $$->opclass = $2;
4121                                         $$->ordering = $3;
4122                                         $$->nulls_ordering = $4;
4123                                 }
4124                         | func_expr opt_class opt_asc_desc opt_nulls_order
4125                                 {
4126                                         $$ = makeNode(IndexElem);
4127                                         $$->name = NULL;
4128                                         $$->expr = $1;
4129                                         $$->opclass = $2;
4130                                         $$->ordering = $3;
4131                                         $$->nulls_ordering = $4;
4132                                 }
4133                         | '(' a_expr ')' opt_class opt_asc_desc opt_nulls_order
4134                                 {
4135                                         $$ = makeNode(IndexElem);
4136                                         $$->name = NULL;
4137                                         $$->expr = $2;
4138                                         $$->opclass = $4;
4139                                         $$->ordering = $5;
4140                                         $$->nulls_ordering = $6;
4141                                 }
4142                 ;
4143
4144 opt_class:      any_name                                                                { $$ = $1; }
4145                         | USING any_name                                                { $$ = $2; }
4146                         | /*EMPTY*/                                                             { $$ = NIL; }
4147                 ;
4148
4149 opt_asc_desc: ASC                                                       { $$ = SORTBY_ASC; }
4150                         | DESC                                                  { $$ = SORTBY_DESC; }
4151                         | /*EMPTY*/                                             { $$ = SORTBY_DEFAULT; }
4152                 ;
4153
4154 opt_nulls_order: NULLS_FIRST                            { $$ = SORTBY_NULLS_FIRST; }
4155                         | NULLS_LAST                                    { $$ = SORTBY_NULLS_LAST; }
4156                         | /*EMPTY*/                                             { $$ = SORTBY_NULLS_DEFAULT; }
4157                 ;
4158
4159
4160 /*****************************************************************************
4161  *
4162  *              QUERY:
4163  *                              create [or replace] function <fname>
4164  *                                              [(<type-1> { , <type-n>})]
4165  *                                              returns <type-r>
4166  *                                              as <filename or code in language as appropriate>
4167  *                                              language <lang> [with parameters]
4168  *
4169  *****************************************************************************/
4170
4171 CreateFunctionStmt:
4172                         CREATE opt_or_replace FUNCTION func_name func_args
4173                         RETURNS func_return createfunc_opt_list opt_definition
4174                                 {
4175                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
4176                                         n->replace = $2;
4177                                         n->funcname = $4;
4178                                         n->parameters = $5;
4179                                         n->returnType = $7;
4180                                         n->options = $8;
4181                                         n->withClause = $9;
4182                                         $$ = (Node *)n;
4183                                 }
4184                         | CREATE opt_or_replace FUNCTION func_name func_args
4185                           RETURNS TABLE '(' table_func_column_list ')' createfunc_opt_list opt_definition
4186                                 {
4187                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
4188                                         n->replace = $2;
4189                                         n->funcname = $4;
4190                                         n->parameters = mergeTableFuncParameters($5, $9);
4191                                         n->returnType = TableFuncTypeName($9);
4192                                         n->returnType->location = @7;
4193                                         n->options = $11;
4194                                         n->withClause = $12;
4195                                         $$ = (Node *)n;
4196                                 }
4197                         | CREATE opt_or_replace FUNCTION func_name func_args
4198                           createfunc_opt_list opt_definition
4199                                 {
4200                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
4201                                         n->replace = $2;
4202                                         n->funcname = $4;
4203                                         n->parameters = $5;
4204                                         n->returnType = NULL;
4205                                         n->options = $6;
4206                                         n->withClause = $7;
4207                                         $$ = (Node *)n;
4208                                 }
4209                 ;
4210
4211 opt_or_replace:
4212                         OR REPLACE                                                              { $$ = TRUE; }
4213                         | /*EMPTY*/                                                             { $$ = FALSE; }
4214                 ;
4215
4216 func_args:      '(' func_args_list ')'                                  { $$ = $2; }
4217                         | '(' ')'                                                               { $$ = NIL; }
4218                 ;
4219
4220 func_args_list:
4221                         func_arg                                                                { $$ = list_make1($1); }
4222                         | func_args_list ',' func_arg                   { $$ = lappend($1, $3); }
4223                 ;
4224
4225 /*
4226  * The style with arg_class first is SQL99 standard, but Oracle puts
4227  * param_name first; accept both since it's likely people will try both
4228  * anyway.  Don't bother trying to save productions by letting arg_class
4229  * have an empty alternative ... you'll get shift/reduce conflicts.
4230  *
4231  * We can catch over-specified arguments here if we want to,
4232  * but for now better to silently swallow typmod, etc.
4233  * - thomas 2000-03-22
4234  */
4235 func_arg:
4236                         arg_class param_name func_type
4237                                 {
4238                                         FunctionParameter *n = makeNode(FunctionParameter);
4239                                         n->name = $2;
4240                                         n->argType = $3;
4241                                         n->mode = $1;
4242                                         $$ = n;
4243                                 }
4244                         | param_name arg_class func_type
4245                                 {
4246                                         FunctionParameter *n = makeNode(FunctionParameter);
4247                                         n->name = $1;
4248                                         n->argType = $3;
4249                                         n->mode = $2;
4250                                         $$ = n;
4251                                 }
4252                         | param_name func_type
4253                                 {
4254                                         FunctionParameter *n = makeNode(FunctionParameter);
4255                                         n->name = $1;
4256                                         n->argType = $2;
4257                                         n->mode = FUNC_PARAM_IN;
4258                                         $$ = n;
4259                                 }
4260                         | arg_class func_type
4261                                 {
4262                                         FunctionParameter *n = makeNode(FunctionParameter);
4263                                         n->name = NULL;
4264                                         n->argType = $2;
4265                                         n->mode = $1;
4266                                         $$ = n;
4267                                 }
4268                         | func_type
4269                                 {
4270                                         FunctionParameter *n = makeNode(FunctionParameter);
4271                                         n->name = NULL;
4272                                         n->argType = $1;
4273                                         n->mode = FUNC_PARAM_IN;
4274                                         $$ = n;
4275                                 }
4276                 ;
4277
4278 /* INOUT is SQL99 standard, IN OUT is for Oracle compatibility */
4279 arg_class:      IN_P                                                            { $$ = FUNC_PARAM_IN; }
4280                         | OUT_P                                                         { $$ = FUNC_PARAM_OUT; }
4281                         | INOUT                                                         { $$ = FUNC_PARAM_INOUT; }
4282                         | IN_P OUT_P                                            { $$ = FUNC_PARAM_INOUT; }
4283                         | VARIADIC                                                      { $$ = FUNC_PARAM_VARIADIC; }
4284                 ;
4285
4286 /*
4287  * Ideally param_name should be ColId, but that causes too many conflicts.
4288  */
4289 param_name:     type_function_name
4290                 ;
4291
4292 func_return:
4293                         func_type
4294                                 {
4295                                         /* We can catch over-specified results here if we want to,
4296                                          * but for now better to silently swallow typmod, etc.
4297                                          * - thomas 2000-03-22
4298                                          */
4299                                         $$ = $1;
4300                                 }
4301                 ;
4302
4303 /*
4304  * We would like to make the %TYPE productions here be ColId attrs etc,
4305  * but that causes reduce/reduce conflicts.  type_function_name
4306  * is next best choice.
4307  */
4308 func_type:      Typename                                                                { $$ = $1; }
4309                         | type_function_name attrs '%' TYPE_P
4310                                 {
4311                                         $$ = makeTypeNameFromNameList(lcons(makeString($1), $2));
4312                                         $$->pct_type = true;
4313                                         $$->location = @1;
4314                                 }
4315                         | SETOF type_function_name attrs '%' TYPE_P
4316                                 {
4317                                         $$ = makeTypeNameFromNameList(lcons(makeString($2), $3));
4318                                         $$->pct_type = true;
4319                                         $$->setof = TRUE;
4320                                         $$->location = @2;
4321                                 }
4322                 ;
4323
4324
4325 createfunc_opt_list:
4326                         /* Must be at least one to prevent conflict */
4327                         createfunc_opt_item                     { $$ = list_make1($1); }
4328                         | createfunc_opt_list createfunc_opt_item { $$ = lappend($1, $2); }
4329         ;
4330
4331 /*
4332  * Options common to both CREATE FUNCTION and ALTER FUNCTION
4333  */
4334 common_func_opt_item:
4335                         CALLED ON NULL_P INPUT_P
4336                                 {
4337                                         $$ = makeDefElem("strict", (Node *)makeInteger(FALSE));
4338                                 }
4339                         | RETURNS NULL_P ON NULL_P INPUT_P
4340                                 {
4341                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
4342                                 }
4343                         | STRICT_P
4344                                 {
4345                                         $$ = makeDefElem("strict", (Node *)makeInteger(TRUE));
4346                                 }
4347                         | IMMUTABLE
4348                                 {
4349                                         $$ = makeDefElem("volatility", (Node *)makeString("immutable"));
4350                                 }
4351                         | STABLE
4352                                 {
4353                                         $$ = makeDefElem("volatility", (Node *)makeString("stable"));
4354                                 }
4355                         | VOLATILE
4356                                 {
4357                                         $$ = makeDefElem("volatility", (Node *)makeString("volatile"));
4358                                 }
4359                         | EXTERNAL SECURITY DEFINER
4360                                 {
4361                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
4362                                 }
4363                         | EXTERNAL SECURITY INVOKER
4364                                 {
4365                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
4366                                 }
4367                         | SECURITY DEFINER
4368                                 {
4369                                         $$ = makeDefElem("security", (Node *)makeInteger(TRUE));
4370                                 }
4371                         | SECURITY INVOKER
4372                                 {
4373                                         $$ = makeDefElem("security", (Node *)makeInteger(FALSE));
4374                                 }
4375                         | COST NumericOnly
4376                                 {
4377                                         $$ = makeDefElem("cost", (Node *)$2);
4378                                 }
4379                         | ROWS NumericOnly
4380                                 {
4381                                         $$ = makeDefElem("rows", (Node *)$2);
4382                                 }
4383                         | SetResetClause
4384                                 {
4385                                         /* we abuse the normal content of a DefElem here */
4386                                         $$ = makeDefElem("set", (Node *)$1);
4387                                 }
4388                 ;
4389
4390 createfunc_opt_item:
4391                         AS func_as
4392                                 {
4393                                         $$ = makeDefElem("as", (Node *)$2);
4394                                 }
4395                         | LANGUAGE ColId_or_Sconst
4396                                 {
4397                                         $$ = makeDefElem("language", (Node *)makeString($2));
4398                                 }
4399                         | common_func_opt_item
4400                                 {
4401                                         $$ = $1;
4402                                 }
4403                 ;
4404
4405 func_as:        Sconst                                          { $$ = list_make1(makeString($1)); }
4406                         | Sconst ',' Sconst
4407                                 {
4408                                         $$ = list_make2(makeString($1), makeString($3));
4409                                 }
4410                 ;
4411
4412 opt_definition:
4413                         WITH definition                                                 { $$ = $2; }
4414                         | /*EMPTY*/                                                             { $$ = NIL; }
4415                 ;
4416
4417 table_func_column:      param_name func_type
4418                                 {
4419                                         FunctionParameter *n = makeNode(FunctionParameter);
4420                                         n->name = $1;
4421                                         n->argType = $2;
4422                                         n->mode = FUNC_PARAM_TABLE;
4423                                         $$ = n;
4424                                 }
4425                 ;
4426
4427 table_func_column_list:
4428                         table_func_column
4429                                 {
4430                                         $$ = list_make1($1);
4431                                 }
4432                         | table_func_column_list ',' table_func_column
4433                                 {
4434                                         $$ = lappend($1, $3);
4435                                 }
4436                 ;
4437
4438 /*****************************************************************************
4439  * ALTER FUNCTION
4440  *
4441  * RENAME and OWNER subcommands are already provided by the generic
4442  * ALTER infrastructure, here we just specify alterations that can
4443  * only be applied to functions.
4444  *
4445  *****************************************************************************/
4446 AlterFunctionStmt:
4447                         ALTER FUNCTION function_with_argtypes alterfunc_opt_list opt_restrict
4448                                 {
4449                                         AlterFunctionStmt *n = makeNode(AlterFunctionStmt);
4450                                         n->func = $3;
4451                                         n->actions = $4;
4452                                         $$ = (Node *) n;
4453                                 }
4454                 ;
4455
4456 alterfunc_opt_list:
4457                         /* At least one option must be specified */
4458                         common_func_opt_item                                    { $$ = list_make1($1); }
4459                         | alterfunc_opt_list common_func_opt_item { $$ = lappend($1, $2); }
4460                 ;
4461
4462 /* Ignored, merely for SQL compliance */
4463 opt_restrict:
4464                         RESTRICT
4465                         | /* EMPTY */
4466                 ;
4467
4468
4469 /*****************************************************************************
4470  *
4471  *              QUERY:
4472  *
4473  *              DROP FUNCTION funcname (arg1, arg2, ...) [ RESTRICT | CASCADE ]
4474  *              DROP AGGREGATE aggname (arg1, ...) [ RESTRICT | CASCADE ]
4475  *              DROP OPERATOR opname (leftoperand_typ, rightoperand_typ) [ RESTRICT | CASCADE ]
4476  *
4477  *****************************************************************************/
4478
4479 RemoveFuncStmt:
4480                         DROP FUNCTION func_name func_args opt_drop_behavior
4481                                 {
4482                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4483                                         n->kind = OBJECT_FUNCTION;
4484                                         n->name = $3;
4485                                         n->args = extractArgTypes($4);
4486                                         n->behavior = $5;
4487                                         n->missing_ok = false;
4488                                         $$ = (Node *)n;
4489                                 }
4490                         | DROP FUNCTION IF_P EXISTS func_name func_args opt_drop_behavior
4491                                 {
4492                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4493                                         n->kind = OBJECT_FUNCTION;
4494                                         n->name = $5;
4495                                         n->args = extractArgTypes($6);
4496                                         n->behavior = $7;
4497                                         n->missing_ok = true;
4498                                         $$ = (Node *)n;
4499                                 }
4500                 ;
4501
4502 RemoveAggrStmt:
4503                         DROP AGGREGATE func_name aggr_args opt_drop_behavior
4504                                 {
4505                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4506                                         n->kind = OBJECT_AGGREGATE;
4507                                         n->name = $3;
4508                                         n->args = $4;
4509                                         n->behavior = $5;
4510                                         n->missing_ok = false;
4511                                         $$ = (Node *)n;
4512                                 }
4513                         | DROP AGGREGATE IF_P EXISTS func_name aggr_args opt_drop_behavior
4514                                 {
4515                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4516                                         n->kind = OBJECT_AGGREGATE;
4517                                         n->name = $5;
4518                                         n->args = $6;
4519                                         n->behavior = $7;
4520                                         n->missing_ok = true;
4521                                         $$ = (Node *)n;
4522                                 }
4523                 ;
4524
4525 RemoveOperStmt:
4526                         DROP OPERATOR any_operator oper_argtypes opt_drop_behavior
4527                                 {
4528                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4529                                         n->kind = OBJECT_OPERATOR;
4530                                         n->name = $3;
4531                                         n->args = $4;
4532                                         n->behavior = $5;
4533                                         n->missing_ok = false;
4534                                         $$ = (Node *)n;
4535                                 }
4536                         | DROP OPERATOR IF_P EXISTS any_operator oper_argtypes opt_drop_behavior
4537                                 {
4538                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
4539                                         n->kind = OBJECT_OPERATOR;
4540                                         n->name = $5;
4541                                         n->args = $6;
4542                                         n->behavior = $7;
4543                                         n->missing_ok = true;
4544                                         $$ = (Node *)n;
4545                                 }
4546                 ;
4547
4548 oper_argtypes:
4549                         '(' Typename ')'
4550                                 {
4551                                    ereport(ERROR,
4552                                                    (errcode(ERRCODE_SYNTAX_ERROR),
4553                                                         errmsg("missing argument"),
4554                                                         errhint("Use NONE to denote the missing argument of a unary operator."),
4555                                                         scanner_errposition(@3)));
4556                                 }
4557                         | '(' Typename ',' Typename ')'
4558                                         { $$ = list_make2($2, $4); }
4559                         | '(' NONE ',' Typename ')'                                     /* left unary */
4560                                         { $$ = list_make2(NULL, $4); }
4561                         | '(' Typename ',' NONE ')'                                     /* right unary */
4562                                         { $$ = list_make2($2, NULL); }
4563                 ;
4564
4565 any_operator:
4566                         all_Op
4567                                         { $$ = list_make1(makeString($1)); }
4568                         | ColId '.' any_operator
4569                                         { $$ = lcons(makeString($1), $3); }
4570                 ;
4571
4572
4573 /*****************************************************************************
4574  *
4575  *              CREATE CAST / DROP CAST
4576  *
4577  *****************************************************************************/
4578
4579 CreateCastStmt: CREATE CAST '(' Typename AS Typename ')'
4580                                         WITH FUNCTION function_with_argtypes cast_context
4581                                 {
4582                                         CreateCastStmt *n = makeNode(CreateCastStmt);
4583                                         n->sourcetype = $4;
4584                                         n->targettype = $6;
4585                                         n->func = $10;
4586                                         n->context = (CoercionContext) $11;
4587                                         n->inout = false;
4588                                         $$ = (Node *)n;
4589                                 }
4590                         | CREATE CAST '(' Typename AS Typename ')'
4591                                         WITHOUT FUNCTION cast_context
4592                                 {
4593                                         CreateCastStmt *n = makeNode(CreateCastStmt);
4594                                         n->sourcetype = $4;
4595                                         n->targettype = $6;
4596                                         n->func = NULL;
4597                                         n->context = (CoercionContext) $10;
4598                                         n->inout = false;
4599                                         $$ = (Node *)n;
4600                                 }
4601                         | CREATE CAST '(' Typename AS Typename ')'
4602                                         WITH INOUT cast_context
4603                                 {
4604                                         CreateCastStmt *n = makeNode(CreateCastStmt);
4605                                         n->sourcetype = $4;
4606                                         n->targettype = $6;
4607                                         n->func = NULL;
4608                                         n->context = (CoercionContext) $10;
4609                                         n->inout = true;
4610                                         $$ = (Node *)n;
4611                                 }
4612                 ;
4613
4614 cast_context:  AS IMPLICIT_P                                    { $$ = COERCION_IMPLICIT; }
4615                 | AS ASSIGNMENT                                                 { $$ = COERCION_ASSIGNMENT; }
4616                 | /*EMPTY*/                                                             { $$ = COERCION_EXPLICIT; }
4617                 ;
4618
4619
4620 DropCastStmt: DROP CAST opt_if_exists '(' Typename AS Typename ')' opt_drop_behavior
4621                                 {
4622                                         DropCastStmt *n = makeNode(DropCastStmt);
4623                                         n->sourcetype = $5;
4624                                         n->targettype = $7;
4625                                         n->behavior = $9;
4626                                         n->missing_ok = $3;
4627                                         $$ = (Node *)n;
4628                                 }
4629                 ;
4630
4631 opt_if_exists: IF_P EXISTS                                              { $$ = TRUE; }
4632                 | /*EMPTY*/                                                             { $$ = FALSE; }
4633                 ;
4634
4635
4636 /*****************************************************************************
4637  *
4638  *              QUERY:
4639  *
4640  *              REINDEX type <name> [FORCE]
4641  *
4642  * FORCE no longer does anything, but we accept it for backwards compatibility
4643  *****************************************************************************/
4644
4645 ReindexStmt:
4646                         REINDEX reindex_type qualified_name opt_force
4647                                 {
4648                                         ReindexStmt *n = makeNode(ReindexStmt);
4649                                         n->kind = $2;
4650                                         n->relation = $3;
4651                                         n->name = NULL;
4652                                         $$ = (Node *)n;
4653                                 }
4654                         | REINDEX SYSTEM_P name opt_force
4655                                 {
4656                                         ReindexStmt *n = makeNode(ReindexStmt);
4657                                         n->kind = OBJECT_DATABASE;
4658                                         n->name = $3;
4659                                         n->relation = NULL;
4660                                         n->do_system = true;
4661                                         n->do_user = false;
4662                                         $$ = (Node *)n;
4663                                 }
4664                         | REINDEX DATABASE name opt_force
4665                                 {
4666                                         ReindexStmt *n = makeNode(ReindexStmt);
4667                                         n->kind = OBJECT_DATABASE;
4668                                         n->name = $3;
4669                                         n->relation = NULL;
4670                                         n->do_system = true;
4671                                         n->do_user = true;
4672                                         $$ = (Node *)n;
4673                                 }
4674                 ;
4675
4676 reindex_type:
4677                         INDEX                                                                   { $$ = OBJECT_INDEX; }
4678                         | TABLE                                                                 { $$ = OBJECT_TABLE; }
4679                 ;
4680
4681 opt_force:      FORCE                                                                   {  $$ = TRUE; }
4682                         | /* EMPTY */                                                   {  $$ = FALSE; }
4683                 ;
4684
4685
4686 /*****************************************************************************
4687  *
4688  * ALTER THING name RENAME TO newname
4689  *
4690  *****************************************************************************/
4691
4692 RenameStmt: ALTER AGGREGATE func_name aggr_args RENAME TO name
4693                                 {
4694                                         RenameStmt *n = makeNode(RenameStmt);
4695                                         n->renameType = OBJECT_AGGREGATE;
4696                                         n->object = $3;
4697                                         n->objarg = $4;
4698                                         n->newname = $7;
4699                                         $$ = (Node *)n;
4700                                 }
4701                         | ALTER CONVERSION_P any_name RENAME TO name
4702                                 {
4703                                         RenameStmt *n = makeNode(RenameStmt);
4704                                         n->renameType = OBJECT_CONVERSION;
4705                                         n->object = $3;
4706                                         n->newname = $6;
4707                                         $$ = (Node *)n;
4708                                 }
4709                         | ALTER DATABASE database_name RENAME TO database_name
4710                                 {
4711                                         RenameStmt *n = makeNode(RenameStmt);
4712                                         n->renameType = OBJECT_DATABASE;
4713                                         n->subname = $3;
4714                                         n->newname = $6;
4715                                         $$ = (Node *)n;
4716                                 }
4717                         | ALTER FUNCTION function_with_argtypes RENAME TO name
4718                                 {
4719                                         RenameStmt *n = makeNode(RenameStmt);
4720                                         n->renameType = OBJECT_FUNCTION;
4721                                         n->object = $3->funcname;
4722                                         n->objarg = $3->funcargs;
4723                                         n->newname = $6;
4724                                         $$ = (Node *)n;
4725                                 }
4726                         | ALTER GROUP_P RoleId RENAME TO RoleId
4727                                 {
4728                                         RenameStmt *n = makeNode(RenameStmt);
4729                                         n->renameType = OBJECT_ROLE;
4730                                         n->subname = $3;
4731                                         n->newname = $6;
4732                                         $$ = (Node *)n;
4733                                 }
4734                         | ALTER opt_procedural LANGUAGE name RENAME TO name
4735                                 {
4736                                         RenameStmt *n = makeNode(RenameStmt);
4737                                         n->renameType = OBJECT_LANGUAGE;
4738                                         n->subname = $4;
4739                                         n->newname = $7;
4740                                         $$ = (Node *)n;
4741                                 }
4742                         | ALTER OPERATOR CLASS any_name USING access_method RENAME TO name
4743                                 {
4744                                         RenameStmt *n = makeNode(RenameStmt);
4745                                         n->renameType = OBJECT_OPCLASS;
4746                                         n->object = $4;
4747                                         n->subname = $6;
4748                                         n->newname = $9;
4749                                         $$ = (Node *)n;
4750                                 }
4751                         | ALTER OPERATOR FAMILY any_name USING access_method RENAME TO name
4752                                 {
4753                                         RenameStmt *n = makeNode(RenameStmt);
4754                                         n->renameType = OBJECT_OPFAMILY;
4755                                         n->object = $4;
4756                                         n->subname = $6;
4757                                         n->newname = $9;
4758                                         $$ = (Node *)n;
4759                                 }
4760                         | ALTER SCHEMA name RENAME TO name
4761                                 {
4762                                         RenameStmt *n = makeNode(RenameStmt);
4763                                         n->renameType = OBJECT_SCHEMA;
4764                                         n->subname = $3;
4765                                         n->newname = $6;
4766                                         $$ = (Node *)n;
4767                                 }
4768                         | ALTER TABLE relation_expr RENAME TO name
4769                                 {
4770                                         RenameStmt *n = makeNode(RenameStmt);
4771                                         n->renameType = OBJECT_TABLE;
4772                                         n->relation = $3;
4773                                         n->subname = NULL;
4774                                         n->newname = $6;
4775                                         $$ = (Node *)n;
4776                                 }
4777                         | ALTER SEQUENCE relation_expr RENAME TO name
4778                                 {
4779                                         RenameStmt *n = makeNode(RenameStmt);
4780                                         n->renameType = OBJECT_SEQUENCE;
4781                                         n->relation = $3;
4782                                         n->subname = NULL;
4783                                         n->newname = $6;
4784                                         $$ = (Node *)n;
4785                                 }
4786                         | ALTER VIEW relation_expr RENAME TO name
4787                                 {
4788                                         RenameStmt *n = makeNode(RenameStmt);
4789                                         n->renameType = OBJECT_VIEW;
4790                                         n->relation = $3;
4791                                         n->subname = NULL;
4792                                         n->newname = $6;
4793                                         $$ = (Node *)n;
4794                                 }
4795                         | ALTER INDEX relation_expr RENAME TO name
4796                                 {
4797                                         RenameStmt *n = makeNode(RenameStmt);
4798                                         n->renameType = OBJECT_INDEX;
4799                                         n->relation = $3;
4800                                         n->subname = NULL;
4801                                         n->newname = $6;
4802                                         $$ = (Node *)n;
4803                                 }
4804                         | ALTER TABLE relation_expr RENAME opt_column name TO name
4805                                 {
4806                                         RenameStmt *n = makeNode(RenameStmt);
4807                                         n->renameType = OBJECT_COLUMN;
4808                                         n->relation = $3;
4809                                         n->subname = $6;
4810                                         n->newname = $8;
4811                                         $$ = (Node *)n;
4812                                 }
4813                         | ALTER TRIGGER name ON relation_expr RENAME TO name
4814                                 {
4815                                         RenameStmt *n = makeNode(RenameStmt);
4816                                         n->renameType = OBJECT_TRIGGER;
4817                                         n->relation = $5;
4818                                         n->subname = $3;
4819                                         n->newname = $8;
4820                                         $$ = (Node *)n;
4821                                 }
4822                         | ALTER ROLE RoleId RENAME TO RoleId
4823                                 {
4824                                         RenameStmt *n = makeNode(RenameStmt);
4825                                         n->renameType = OBJECT_ROLE;
4826                                         n->subname = $3;
4827                                         n->newname = $6;
4828                                         $$ = (Node *)n;
4829                                 }
4830                         | ALTER USER RoleId RENAME TO RoleId
4831                                 {
4832                                         RenameStmt *n = makeNode(RenameStmt);
4833                                         n->renameType = OBJECT_ROLE;
4834                                         n->subname = $3;
4835                                         n->newname = $6;
4836                                         $$ = (Node *)n;
4837                                 }
4838                         | ALTER TABLESPACE name RENAME TO name
4839                                 {
4840                                         RenameStmt *n = makeNode(RenameStmt);
4841                                         n->renameType = OBJECT_TABLESPACE;
4842                                         n->subname = $3;
4843                                         n->newname = $6;
4844                                         $$ = (Node *)n;
4845                                 }
4846                         | ALTER TEXT_P SEARCH PARSER any_name RENAME TO name
4847                                 {
4848                                         RenameStmt *n = makeNode(RenameStmt);
4849                                         n->renameType = OBJECT_TSPARSER;
4850                                         n->object = $5;
4851                                         n->newname = $8;
4852                                         $$ = (Node *)n;
4853                                 }
4854                         | ALTER TEXT_P SEARCH DICTIONARY any_name RENAME TO name
4855                                 {
4856                                         RenameStmt *n = makeNode(RenameStmt);
4857                                         n->renameType = OBJECT_TSDICTIONARY;
4858                                         n->object = $5;
4859                                         n->newname = $8;
4860                                         $$ = (Node *)n;
4861                                 }
4862                         | ALTER TEXT_P SEARCH TEMPLATE any_name RENAME TO name
4863                                 {
4864                                         RenameStmt *n = makeNode(RenameStmt);
4865                                         n->renameType = OBJECT_TSTEMPLATE;
4866                                         n->object = $5;
4867                                         n->newname = $8;
4868                                         $$ = (Node *)n;
4869                                 }
4870                         | ALTER TEXT_P SEARCH CONFIGURATION any_name RENAME TO name
4871                                 {
4872                                         RenameStmt *n = makeNode(RenameStmt);
4873                                         n->renameType = OBJECT_TSCONFIGURATION;
4874                                         n->object = $5;
4875                                         n->newname = $8;
4876                                         $$ = (Node *)n;
4877                                 }
4878                         | ALTER TYPE_P any_name RENAME TO name
4879                                 {
4880                                         RenameStmt *n = makeNode(RenameStmt);
4881                                         n->renameType = OBJECT_TYPE;
4882                                         n->object = $3;
4883                                         n->newname = $6;
4884                                         $$ = (Node *)n;
4885                                 }
4886                 ;
4887
4888 opt_column: COLUMN                                                                      { $$ = COLUMN; }
4889                         | /*EMPTY*/                                                             { $$ = 0; }
4890                 ;
4891
4892 opt_set_data: SET DATA_P                                                                        { $$ = 1; }
4893                         | /*EMPTY*/                                                             { $$ = 0; }
4894                 ;
4895
4896 /*****************************************************************************
4897  *
4898  * ALTER THING name SET SCHEMA name
4899  *
4900  *****************************************************************************/
4901
4902 AlterObjectSchemaStmt:
4903                         ALTER AGGREGATE func_name aggr_args SET SCHEMA name
4904                                 {
4905                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
4906                                         n->objectType = OBJECT_AGGREGATE;
4907                                         n->object = $3;
4908                                         n->objarg = $4;
4909                                         n->newschema = $7;
4910                                         $$ = (Node *)n;
4911                                 }
4912                         | ALTER DOMAIN_P any_name SET SCHEMA name
4913                                 {
4914                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
4915                                         n->objectType = OBJECT_DOMAIN;
4916                                         n->object = $3;
4917                                         n->newschema = $6;
4918                                         $$ = (Node *)n;
4919                                 }
4920                         | ALTER FUNCTION function_with_argtypes SET SCHEMA name
4921                                 {
4922                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
4923                                         n->objectType = OBJECT_FUNCTION;
4924                                         n->object = $3->funcname;
4925                                         n->objarg = $3->funcargs;
4926                                         n->newschema = $6;
4927                                         $$ = (Node *)n;
4928                                 }
4929                         | ALTER TABLE relation_expr SET SCHEMA name
4930                                 {
4931                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
4932                                         n->objectType = OBJECT_TABLE;
4933                                         n->relation = $3;
4934                                         n->newschema = $6;
4935                                         $$ = (Node *)n;
4936                                 }
4937                         | ALTER SEQUENCE relation_expr SET SCHEMA name
4938                                 {
4939                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
4940                                         n->objectType = OBJECT_SEQUENCE;
4941                                         n->relation = $3;
4942                                         n->newschema = $6;
4943                                         $$ = (Node *)n;
4944                                 }
4945                         | ALTER VIEW relation_expr SET SCHEMA name
4946                                 {
4947                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
4948                                         n->objectType = OBJECT_VIEW;
4949                                         n->relation = $3;
4950                                         n->newschema = $6;
4951                                         $$ = (Node *)n;
4952                                 }
4953                         | ALTER TYPE_P any_name SET SCHEMA name
4954                                 {
4955                                         AlterObjectSchemaStmt *n = makeNode(AlterObjectSchemaStmt);
4956                                         n->objectType = OBJECT_TYPE;
4957                                         n->object = $3;
4958                                         n->newschema = $6;
4959                                         $$ = (Node *)n;
4960                                 }
4961                 ;
4962
4963 /*****************************************************************************
4964  *
4965  * ALTER THING name OWNER TO newname
4966  *
4967  *****************************************************************************/
4968
4969 AlterOwnerStmt: ALTER AGGREGATE func_name aggr_args OWNER TO RoleId
4970                                 {
4971                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
4972                                         n->objectType = OBJECT_AGGREGATE;
4973                                         n->object = $3;
4974                                         n->objarg = $4;
4975                                         n->newowner = $7;
4976                                         $$ = (Node *)n;
4977                                 }
4978                         | ALTER CONVERSION_P any_name OWNER TO RoleId
4979                                 {
4980                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
4981                                         n->objectType = OBJECT_CONVERSION;
4982                                         n->object = $3;
4983                                         n->newowner = $6;
4984                                         $$ = (Node *)n;
4985                                 }
4986                         | ALTER DATABASE database_name OWNER TO RoleId
4987                                 {
4988                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
4989                                         n->objectType = OBJECT_DATABASE;
4990                                         n->object = list_make1(makeString($3));
4991                                         n->newowner = $6;
4992                                         $$ = (Node *)n;
4993                                 }
4994                         | ALTER DOMAIN_P any_name OWNER TO RoleId
4995                                 {
4996                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
4997                                         n->objectType = OBJECT_DOMAIN;
4998                                         n->object = $3;
4999                                         n->newowner = $6;
5000                                         $$ = (Node *)n;
5001                                 }
5002                         | ALTER FUNCTION function_with_argtypes OWNER TO RoleId
5003                                 {
5004                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5005                                         n->objectType = OBJECT_FUNCTION;
5006                                         n->object = $3->funcname;
5007                                         n->objarg = $3->funcargs;
5008                                         n->newowner = $6;
5009                                         $$ = (Node *)n;
5010                                 }
5011                         | ALTER opt_procedural LANGUAGE name OWNER TO RoleId
5012                                 {
5013                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5014                                         n->objectType = OBJECT_LANGUAGE;
5015                                         n->object = list_make1(makeString($4));
5016                                         n->newowner = $7;
5017                                         $$ = (Node *)n;
5018                                 }
5019                         | ALTER OPERATOR any_operator oper_argtypes OWNER TO RoleId
5020                                 {
5021                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5022                                         n->objectType = OBJECT_OPERATOR;
5023                                         n->object = $3;
5024                                         n->objarg = $4;
5025                                         n->newowner = $7;
5026                                         $$ = (Node *)n;
5027                                 }
5028                         | ALTER OPERATOR CLASS any_name USING access_method OWNER TO RoleId
5029                                 {
5030                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5031                                         n->objectType = OBJECT_OPCLASS;
5032                                         n->object = $4;
5033                                         n->addname = $6;
5034                                         n->newowner = $9;
5035                                         $$ = (Node *)n;
5036                                 }
5037                         | ALTER OPERATOR FAMILY any_name USING access_method OWNER TO RoleId
5038                                 {
5039                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5040                                         n->objectType = OBJECT_OPFAMILY;
5041                                         n->object = $4;
5042                                         n->addname = $6;
5043                                         n->newowner = $9;
5044                                         $$ = (Node *)n;
5045                                 }
5046                         | ALTER SCHEMA name OWNER TO RoleId
5047                                 {
5048                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5049                                         n->objectType = OBJECT_SCHEMA;
5050                                         n->object = list_make1(makeString($3));
5051                                         n->newowner = $6;
5052                                         $$ = (Node *)n;
5053                                 }
5054                         | ALTER TYPE_P any_name OWNER TO RoleId
5055                                 {
5056                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5057                                         n->objectType = OBJECT_TYPE;
5058                                         n->object = $3;
5059                                         n->newowner = $6;
5060                                         $$ = (Node *)n;
5061                                 }
5062                         | ALTER TABLESPACE name OWNER TO RoleId
5063                                 {
5064                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5065                                         n->objectType = OBJECT_TABLESPACE;
5066                                         n->object = list_make1(makeString($3));
5067                                         n->newowner = $6;
5068                                         $$ = (Node *)n;
5069                                 }
5070                         | ALTER TEXT_P SEARCH DICTIONARY any_name OWNER TO RoleId
5071                                 {
5072                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5073                                         n->objectType = OBJECT_TSDICTIONARY;
5074                                         n->object = $5;
5075                                         n->newowner = $8;
5076                                         $$ = (Node *)n;
5077                                 }
5078                         | ALTER TEXT_P SEARCH CONFIGURATION any_name OWNER TO RoleId
5079                                 {
5080                                         AlterOwnerStmt *n = makeNode(AlterOwnerStmt);
5081                                         n->objectType = OBJECT_TSCONFIGURATION;
5082                                         n->object = $5;
5083                                         n->newowner = $8;
5084                                         $$ = (Node *)n;
5085                                 }
5086                 ;
5087
5088
5089 /*****************************************************************************
5090  *
5091  *              QUERY:  Define Rewrite Rule
5092  *
5093  *****************************************************************************/
5094
5095 RuleStmt:       CREATE opt_or_replace RULE name AS
5096                         { QueryIsRule=TRUE; }
5097                         ON event TO qualified_name where_clause
5098                         DO opt_instead RuleActionList
5099                                 {
5100                                         RuleStmt *n = makeNode(RuleStmt);
5101                                         n->replace = $2;
5102                                         n->relation = $10;
5103                                         n->rulename = $4;
5104                                         n->whereClause = $11;
5105                                         n->event = $8;
5106                                         n->instead = $13;
5107                                         n->actions = $14;
5108                                         $$ = (Node *)n;
5109                                         QueryIsRule=FALSE;
5110                                 }
5111                 ;
5112
5113 RuleActionList:
5114                         NOTHING                                                                 { $$ = NIL; }
5115                         | RuleActionStmt                                                { $$ = list_make1($1); }
5116                         | '(' RuleActionMulti ')'                               { $$ = $2; }
5117                 ;
5118
5119 /* the thrashing around here is to discard "empty" statements... */
5120 RuleActionMulti:
5121                         RuleActionMulti ';' RuleActionStmtOrEmpty
5122                                 { if ($3 != NULL)
5123                                         $$ = lappend($1, $3);
5124                                   else
5125                                         $$ = $1;
5126                                 }
5127                         | RuleActionStmtOrEmpty
5128                                 { if ($1 != NULL)
5129                                         $$ = list_make1($1);
5130                                   else
5131                                         $$ = NIL;
5132                                 }
5133                 ;
5134
5135 RuleActionStmt:
5136                         SelectStmt
5137                         | InsertStmt
5138                         | UpdateStmt
5139                         | DeleteStmt
5140                         | NotifyStmt
5141                 ;
5142
5143 RuleActionStmtOrEmpty:
5144                         RuleActionStmt                                                  { $$ = $1; }
5145                         |       /*EMPTY*/                                                       { $$ = NULL; }
5146                 ;
5147
5148 event:          SELECT                                                                  { $$ = CMD_SELECT; }
5149                         | UPDATE                                                                { $$ = CMD_UPDATE; }
5150                         | DELETE_P                                                              { $$ = CMD_DELETE; }
5151                         | INSERT                                                                { $$ = CMD_INSERT; }
5152                  ;
5153
5154 opt_instead:
5155                         INSTEAD                                                                 { $$ = TRUE; }
5156                         | ALSO                                                                  { $$ = FALSE; }
5157                         | /*EMPTY*/                                                             { $$ = FALSE; }
5158                 ;
5159
5160
5161 DropRuleStmt:
5162                         DROP RULE name ON qualified_name opt_drop_behavior
5163                                 {
5164                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
5165                                         n->relation = $5;
5166                                         n->property = $3;
5167                                         n->behavior = $6;
5168                                         n->removeType = OBJECT_RULE;
5169                                         n->missing_ok = false;
5170                                         $$ = (Node *) n;
5171                                 }
5172                         | DROP RULE IF_P EXISTS name ON qualified_name opt_drop_behavior
5173                                 {
5174                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
5175                                         n->relation = $7;
5176                                         n->property = $5;
5177                                         n->behavior = $8;
5178                                         n->removeType = OBJECT_RULE;
5179                                         n->missing_ok = true;
5180                                         $$ = (Node *) n;
5181                                 }
5182                 ;
5183
5184
5185 /*****************************************************************************
5186  *
5187  *              QUERY:
5188  *                              NOTIFY <identifier> can appear both in rule bodies and
5189  *                              as a query-level command
5190  *
5191  *****************************************************************************/
5192
5193 NotifyStmt: NOTIFY ColId
5194                                 {
5195                                         NotifyStmt *n = makeNode(NotifyStmt);
5196                                         n->conditionname = $2;
5197                                         $$ = (Node *)n;
5198                                 }
5199                 ;
5200
5201 ListenStmt: LISTEN ColId
5202                                 {
5203                                         ListenStmt *n = makeNode(ListenStmt);
5204                                         n->conditionname = $2;
5205                                         $$ = (Node *)n;
5206                                 }
5207                 ;
5208
5209 UnlistenStmt:
5210                         UNLISTEN ColId
5211                                 {
5212                                         UnlistenStmt *n = makeNode(UnlistenStmt);
5213                                         n->conditionname = $2;
5214                                         $$ = (Node *)n;
5215                                 }
5216                         | UNLISTEN '*'
5217                                 {
5218                                         UnlistenStmt *n = makeNode(UnlistenStmt);
5219                                         n->conditionname = NULL;
5220                                         $$ = (Node *)n;
5221                                 }
5222                 ;
5223
5224
5225 /*****************************************************************************
5226  *
5227  *              Transactions:
5228  *
5229  *              BEGIN / COMMIT / ROLLBACK
5230  *              (also older versions END / ABORT)
5231  *
5232  *****************************************************************************/
5233
5234 TransactionStmt:
5235                         ABORT_P opt_transaction
5236                                 {
5237                                         TransactionStmt *n = makeNode(TransactionStmt);
5238                                         n->kind = TRANS_STMT_ROLLBACK;
5239                                         n->options = NIL;
5240                                         $$ = (Node *)n;
5241                                 }
5242                         | BEGIN_P opt_transaction transaction_mode_list_or_empty
5243                                 {
5244                                         TransactionStmt *n = makeNode(TransactionStmt);
5245                                         n->kind = TRANS_STMT_BEGIN;
5246                                         n->options = $3;
5247                                         $$ = (Node *)n;
5248                                 }
5249                         | START TRANSACTION transaction_mode_list_or_empty
5250                                 {
5251                                         TransactionStmt *n = makeNode(TransactionStmt);
5252                                         n->kind = TRANS_STMT_START;
5253                                         n->options = $3;
5254                                         $$ = (Node *)n;
5255                                 }
5256                         | COMMIT opt_transaction
5257                                 {
5258                                         TransactionStmt *n = makeNode(TransactionStmt);
5259                                         n->kind = TRANS_STMT_COMMIT;
5260                                         n->options = NIL;
5261                                         $$ = (Node *)n;
5262                                 }
5263                         | END_P opt_transaction
5264                                 {
5265                                         TransactionStmt *n = makeNode(TransactionStmt);
5266                                         n->kind = TRANS_STMT_COMMIT;
5267                                         n->options = NIL;
5268                                         $$ = (Node *)n;
5269                                 }
5270                         | ROLLBACK opt_transaction
5271                                 {
5272                                         TransactionStmt *n = makeNode(TransactionStmt);
5273                                         n->kind = TRANS_STMT_ROLLBACK;
5274                                         n->options = NIL;
5275                                         $$ = (Node *)n;
5276                                 }
5277                         | SAVEPOINT ColId
5278                                 {
5279                                         TransactionStmt *n = makeNode(TransactionStmt);
5280                                         n->kind = TRANS_STMT_SAVEPOINT;
5281                                         n->options = list_make1(makeDefElem("savepoint_name",
5282                                                                                                                 (Node *)makeString($2)));
5283                                         $$ = (Node *)n;
5284                                 }
5285                         | RELEASE SAVEPOINT ColId
5286                                 {
5287                                         TransactionStmt *n = makeNode(TransactionStmt);
5288                                         n->kind = TRANS_STMT_RELEASE;
5289                                         n->options = list_make1(makeDefElem("savepoint_name",
5290                                                                                                                 (Node *)makeString($3)));
5291                                         $$ = (Node *)n;
5292                                 }
5293                         | RELEASE ColId
5294                                 {
5295                                         TransactionStmt *n = makeNode(TransactionStmt);
5296                                         n->kind = TRANS_STMT_RELEASE;
5297                                         n->options = list_make1(makeDefElem("savepoint_name",
5298                                                                                                                 (Node *)makeString($2)));
5299                                         $$ = (Node *)n;
5300                                 }
5301                         | ROLLBACK opt_transaction TO SAVEPOINT ColId
5302                                 {
5303                                         TransactionStmt *n = makeNode(TransactionStmt);
5304                                         n->kind = TRANS_STMT_ROLLBACK_TO;
5305                                         n->options = list_make1(makeDefElem("savepoint_name",
5306                                                                                                                 (Node *)makeString($5)));
5307                                         $$ = (Node *)n;
5308                                 }
5309                         | ROLLBACK opt_transaction TO ColId
5310                                 {
5311                                         TransactionStmt *n = makeNode(TransactionStmt);
5312                                         n->kind = TRANS_STMT_ROLLBACK_TO;
5313                                         n->options = list_make1(makeDefElem("savepoint_name",
5314                                                                                                                 (Node *)makeString($4)));
5315                                         $$ = (Node *)n;
5316                                 }
5317                         | PREPARE TRANSACTION Sconst
5318                                 {
5319                                         TransactionStmt *n = makeNode(TransactionStmt);
5320                                         n->kind = TRANS_STMT_PREPARE;
5321                                         n->gid = $3;
5322                                         $$ = (Node *)n;
5323                                 }
5324                         | COMMIT PREPARED Sconst
5325                                 {
5326                                         TransactionStmt *n = makeNode(TransactionStmt);
5327                                         n->kind = TRANS_STMT_COMMIT_PREPARED;
5328                                         n->gid = $3;
5329                                         $$ = (Node *)n;
5330                                 }
5331                         | ROLLBACK PREPARED Sconst
5332                                 {
5333                                         TransactionStmt *n = makeNode(TransactionStmt);
5334                                         n->kind = TRANS_STMT_ROLLBACK_PREPARED;
5335                                         n->gid = $3;
5336                                         $$ = (Node *)n;
5337                                 }
5338                 ;
5339
5340 opt_transaction:        WORK                                                    {}
5341                         | TRANSACTION                                                   {}
5342                         | /*EMPTY*/                                                             {}
5343                 ;
5344
5345 transaction_mode_item:
5346                         ISOLATION LEVEL iso_level
5347                                         { $$ = makeDefElem("transaction_isolation",
5348                                                                            makeStringConst($3, @3)); }
5349                         | READ ONLY
5350                                         { $$ = makeDefElem("transaction_read_only",
5351                                                                            makeIntConst(TRUE, @1)); }
5352                         | READ WRITE
5353                                         { $$ = makeDefElem("transaction_read_only",
5354                                                                            makeIntConst(FALSE, @1)); }
5355                 ;
5356
5357 /* Syntax with commas is SQL-spec, without commas is Postgres historical */
5358 transaction_mode_list:
5359                         transaction_mode_item
5360                                         { $$ = list_make1($1); }
5361                         | transaction_mode_list ',' transaction_mode_item
5362                                         { $$ = lappend($1, $3); }
5363                         | transaction_mode_list transaction_mode_item
5364                                         { $$ = lappend($1, $2); }
5365                 ;
5366
5367 transaction_mode_list_or_empty:
5368                         transaction_mode_list
5369                         | /* EMPTY */
5370                                         { $$ = NIL; }
5371                 ;
5372
5373
5374 /*****************************************************************************
5375  *
5376  *      QUERY:
5377  *              CREATE [ OR REPLACE ] [ TEMP ] VIEW <viewname> '('target-list ')'
5378  *                      AS <query> [ WITH [ CASCADED | LOCAL ] CHECK OPTION ]
5379  *
5380  *****************************************************************************/
5381
5382 ViewStmt: CREATE OptTemp VIEW qualified_name opt_column_list
5383                                 AS SelectStmt opt_check_option
5384                                 {
5385                                         ViewStmt *n = makeNode(ViewStmt);
5386                                         n->view = $4;
5387                                         n->view->istemp = $2;
5388                                         n->aliases = $5;
5389                                         n->query = $7;
5390                                         n->replace = false;
5391                                         $$ = (Node *) n;
5392                                 }
5393                 | CREATE OR REPLACE OptTemp VIEW qualified_name opt_column_list
5394                                 AS SelectStmt opt_check_option
5395                                 {
5396                                         ViewStmt *n = makeNode(ViewStmt);
5397                                         n->view = $6;
5398                                         n->view->istemp = $4;
5399                                         n->aliases = $7;
5400                                         n->query = $9;
5401                                         n->replace = true;
5402                                         $$ = (Node *) n;
5403                                 }
5404                 ;
5405
5406 opt_check_option:
5407                 WITH CHECK OPTION
5408                                 {
5409                                         ereport(ERROR,
5410                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5411                                                          errmsg("WITH CHECK OPTION is not implemented")));
5412                                 }
5413                 | WITH CASCADED CHECK OPTION
5414                                 {
5415                                         ereport(ERROR,
5416                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5417                                                          errmsg("WITH CHECK OPTION is not implemented")));
5418                                 }
5419                 | WITH LOCAL CHECK OPTION
5420                                 {
5421                                         ereport(ERROR,
5422                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5423                                                          errmsg("WITH CHECK OPTION is not implemented")));
5424                                 }
5425                 | /* EMPTY */                                                   { $$ = NIL; }
5426                 ;
5427
5428 /*****************************************************************************
5429  *
5430  *              QUERY:
5431  *                              LOAD "filename"
5432  *
5433  *****************************************************************************/
5434
5435 LoadStmt:       LOAD file_name
5436                                 {
5437                                         LoadStmt *n = makeNode(LoadStmt);
5438                                         n->filename = $2;
5439                                         $$ = (Node *)n;
5440                                 }
5441                 ;
5442
5443
5444 /*****************************************************************************
5445  *
5446  *              CREATE DATABASE
5447  *
5448  *****************************************************************************/
5449
5450 CreatedbStmt:
5451                         CREATE DATABASE database_name opt_with createdb_opt_list
5452                                 {
5453                                         CreatedbStmt *n = makeNode(CreatedbStmt);
5454                                         n->dbname = $3;
5455                                         n->options = $5;
5456                                         $$ = (Node *)n;
5457                                 }
5458                 ;
5459
5460 createdb_opt_list:
5461                         createdb_opt_list createdb_opt_item             { $$ = lappend($1, $2); }
5462                         | /* EMPTY */                                                   { $$ = NIL; }
5463                 ;
5464
5465 createdb_opt_item:
5466                         TABLESPACE opt_equal name
5467                                 {
5468                                         $$ = makeDefElem("tablespace", (Node *)makeString($3));
5469                                 }
5470                         | TABLESPACE opt_equal DEFAULT
5471                                 {
5472                                         $$ = makeDefElem("tablespace", NULL);
5473                                 }
5474                         | LOCATION opt_equal Sconst
5475                                 {
5476                                         $$ = makeDefElem("location", (Node *)makeString($3));
5477                                 }
5478                         | LOCATION opt_equal DEFAULT
5479                                 {
5480                                         $$ = makeDefElem("location", NULL);
5481                                 }
5482                         | TEMPLATE opt_equal name
5483                                 {
5484                                         $$ = makeDefElem("template", (Node *)makeString($3));
5485                                 }
5486                         | TEMPLATE opt_equal DEFAULT
5487                                 {
5488                                         $$ = makeDefElem("template", NULL);
5489                                 }
5490                         | ENCODING opt_equal Sconst
5491                                 {
5492                                         $$ = makeDefElem("encoding", (Node *)makeString($3));
5493                                 }
5494                         | ENCODING opt_equal Iconst
5495                                 {
5496                                         $$ = makeDefElem("encoding", (Node *)makeInteger($3));
5497                                 }
5498                         | ENCODING opt_equal DEFAULT
5499                                 {
5500                                         $$ = makeDefElem("encoding", NULL);
5501                                 }
5502                         | COLLATE opt_equal Sconst
5503                                 {
5504                                         $$ = makeDefElem("collate", (Node *)makeString($3));
5505                                 }
5506                         | COLLATE opt_equal DEFAULT
5507                                 {
5508                                         $$ = makeDefElem("collate", NULL);
5509                                 }
5510                         | CTYPE opt_equal Sconst
5511                                 {
5512                                         $$ = makeDefElem("ctype", (Node *)makeString($3));
5513                                 }
5514                         | CTYPE opt_equal DEFAULT
5515                                 {
5516                                         $$ = makeDefElem("ctype", NULL);
5517                                 }
5518                         | CONNECTION LIMIT opt_equal SignedIconst
5519                                 {
5520                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($4));
5521                                 }
5522                         | OWNER opt_equal name
5523                                 {
5524                                         $$ = makeDefElem("owner", (Node *)makeString($3));
5525                                 }
5526                         | OWNER opt_equal DEFAULT
5527                                 {
5528                                         $$ = makeDefElem("owner", NULL);
5529                                 }
5530                 ;
5531
5532 /*
5533  *      Though the equals sign doesn't match other WITH options, pg_dump uses
5534  *      equals for backward compatibility, and it doesn't seem worth removing it.
5535  */
5536 opt_equal:      '='                                                                             {}
5537                         | /*EMPTY*/                                                             {}
5538                 ;
5539
5540
5541 /*****************************************************************************
5542  *
5543  *              ALTER DATABASE
5544  *
5545  *****************************************************************************/
5546
5547 AlterDatabaseStmt:
5548                         ALTER DATABASE database_name opt_with alterdb_opt_list
5549                                  {
5550                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
5551                                         n->dbname = $3;
5552                                         n->options = $5;
5553                                         $$ = (Node *)n;
5554                                  }
5555                         | ALTER DATABASE database_name SET TABLESPACE name
5556                                  {
5557                                         AlterDatabaseStmt *n = makeNode(AlterDatabaseStmt);
5558                                         n->dbname = $3;
5559                                         n->options = list_make1(makeDefElem("tablespace",
5560                                                                                                         (Node *)makeString($6)));
5561                                         $$ = (Node *)n;
5562                                  }
5563                 ;
5564
5565 AlterDatabaseSetStmt:
5566                         ALTER DATABASE database_name SetResetClause
5567                                 {
5568                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
5569                                         n->dbname = $3;
5570                                         n->setstmt = $4;
5571                                         $$ = (Node *)n;
5572                                 }
5573                 ;
5574
5575
5576 alterdb_opt_list:
5577                         alterdb_opt_list alterdb_opt_item               { $$ = lappend($1, $2); }
5578                         | /* EMPTY */                                                   { $$ = NIL; }
5579                 ;
5580
5581 alterdb_opt_item:
5582                         CONNECTION LIMIT opt_equal SignedIconst
5583                                 {
5584                                         $$ = makeDefElem("connectionlimit", (Node *)makeInteger($4));
5585                                 }
5586                 ;
5587
5588
5589 /*****************************************************************************
5590  *
5591  *              DROP DATABASE [ IF EXISTS ]
5592  *
5593  * This is implicitly CASCADE, no need for drop behavior
5594  *****************************************************************************/
5595
5596 DropdbStmt: DROP DATABASE database_name
5597                                 {
5598                                         DropdbStmt *n = makeNode(DropdbStmt);
5599                                         n->dbname = $3;
5600                                         n->missing_ok = FALSE;
5601                                         $$ = (Node *)n;
5602                                 }
5603                         | DROP DATABASE IF_P EXISTS database_name
5604                                 {
5605                                         DropdbStmt *n = makeNode(DropdbStmt);
5606                                         n->dbname = $5;
5607                                         n->missing_ok = TRUE;
5608                                         $$ = (Node *)n;
5609                                 }
5610                 ;
5611
5612
5613 /*****************************************************************************
5614  *
5615  * Manipulate a domain
5616  *
5617  *****************************************************************************/
5618
5619 CreateDomainStmt:
5620                         CREATE DOMAIN_P any_name opt_as Typename ColQualList
5621                                 {
5622                                         CreateDomainStmt *n = makeNode(CreateDomainStmt);
5623                                         n->domainname = $3;
5624                                         n->typename = $5;
5625                                         n->constraints = $6;
5626                                         $$ = (Node *)n;
5627                                 }
5628                 ;
5629
5630 AlterDomainStmt:
5631                         /* ALTER DOMAIN <domain> {SET DEFAULT <expr>|DROP DEFAULT} */
5632                         ALTER DOMAIN_P any_name alter_column_default
5633                                 {
5634                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
5635                                         n->subtype = 'T';
5636                                         n->typename = $3;
5637                                         n->def = $4;
5638                                         $$ = (Node *)n;
5639                                 }
5640                         /* ALTER DOMAIN <domain> DROP NOT NULL */
5641                         | ALTER DOMAIN_P any_name DROP NOT NULL_P
5642                                 {
5643                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
5644                                         n->subtype = 'N';
5645                                         n->typename = $3;
5646                                         $$ = (Node *)n;
5647                                 }
5648                         /* ALTER DOMAIN <domain> SET NOT NULL */
5649                         | ALTER DOMAIN_P any_name SET NOT NULL_P
5650                                 {
5651                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
5652                                         n->subtype = 'O';
5653                                         n->typename = $3;
5654                                         $$ = (Node *)n;
5655                                 }
5656                         /* ALTER DOMAIN <domain> ADD CONSTRAINT ... */
5657                         | ALTER DOMAIN_P any_name ADD_P TableConstraint
5658                                 {
5659                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
5660                                         n->subtype = 'C';
5661                                         n->typename = $3;
5662                                         n->def = $5;
5663                                         $$ = (Node *)n;
5664                                 }
5665                         /* ALTER DOMAIN <domain> DROP CONSTRAINT <name> [RESTRICT|CASCADE] */
5666                         | ALTER DOMAIN_P any_name DROP CONSTRAINT name opt_drop_behavior
5667                                 {
5668                                         AlterDomainStmt *n = makeNode(AlterDomainStmt);
5669                                         n->subtype = 'X';
5670                                         n->typename = $3;
5671                                         n->name = $6;
5672                                         n->behavior = $7;
5673                                         $$ = (Node *)n;
5674                                 }
5675                         ;
5676
5677 opt_as:         AS                                                                              {}
5678                         | /* EMPTY */                                                   {}
5679                 ;
5680
5681
5682 /*****************************************************************************
5683  *
5684  * Manipulate a text search dictionary or configuration
5685  *
5686  *****************************************************************************/
5687
5688 AlterTSDictionaryStmt:
5689                         ALTER TEXT_P SEARCH DICTIONARY any_name definition
5690                                 {
5691                                         AlterTSDictionaryStmt *n = makeNode(AlterTSDictionaryStmt);
5692                                         n->dictname = $5;
5693                                         n->options = $6;
5694                                         $$ = (Node *)n;
5695                                 }
5696                 ;
5697
5698 AlterTSConfigurationStmt:
5699                         ALTER TEXT_P SEARCH CONFIGURATION any_name ADD_P MAPPING FOR name_list WITH any_name_list
5700                                 {
5701                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
5702                                         n->cfgname = $5;
5703                                         n->tokentype = $9;
5704                                         n->dicts = $11;
5705                                         n->override = false;
5706                                         n->replace = false;
5707                                         $$ = (Node*)n;
5708                                 }
5709                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list WITH any_name_list
5710                                 {
5711                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
5712                                         n->cfgname = $5;
5713                                         n->tokentype = $9;
5714                                         n->dicts = $11;
5715                                         n->override = true;
5716                                         n->replace = false;
5717                                         $$ = (Node*)n;
5718                                 }
5719                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING REPLACE any_name WITH any_name 
5720                                 {
5721                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
5722                                         n->cfgname = $5;
5723                                         n->tokentype = NIL;
5724                                         n->dicts = list_make2($9,$11);
5725                                         n->override = false;
5726                                         n->replace = true;
5727                                         $$ = (Node*)n;
5728                                 }
5729                         | ALTER TEXT_P SEARCH CONFIGURATION any_name ALTER MAPPING FOR name_list REPLACE any_name WITH any_name 
5730                                 {
5731                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
5732                                         n->cfgname = $5;
5733                                         n->tokentype = $9;
5734                                         n->dicts = list_make2($11,$13);
5735                                         n->override = false;
5736                                         n->replace = true;
5737                                         $$ = (Node*)n;
5738                                 }
5739                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING FOR name_list 
5740                                 {
5741                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
5742                                         n->cfgname = $5;
5743                                         n->tokentype = $9;
5744                                         n->missing_ok = false;
5745                                         $$ = (Node*)n;
5746                                 }
5747                         | ALTER TEXT_P SEARCH CONFIGURATION any_name DROP MAPPING IF_P EXISTS FOR name_list 
5748                                 {
5749                                         AlterTSConfigurationStmt *n = makeNode(AlterTSConfigurationStmt);
5750                                         n->cfgname = $5;
5751                                         n->tokentype = $11;
5752                                         n->missing_ok = true;
5753                                         $$ = (Node*)n;
5754                                 }
5755                 ;
5756
5757
5758 /*****************************************************************************
5759  *
5760  * Manipulate a conversion
5761  *
5762  *              CREATE [DEFAULT] CONVERSION <conversion_name>
5763  *              FOR <encoding_name> TO <encoding_name> FROM <func_name>
5764  *
5765  *****************************************************************************/
5766
5767 CreateConversionStmt:
5768                         CREATE opt_default CONVERSION_P any_name FOR Sconst
5769                         TO Sconst FROM any_name
5770                         {
5771                           CreateConversionStmt *n = makeNode(CreateConversionStmt);
5772                           n->conversion_name = $4;
5773                           n->for_encoding_name = $6;
5774                           n->to_encoding_name = $8;
5775                           n->func_name = $10;
5776                           n->def = $2;
5777                           $$ = (Node *)n;
5778                         }
5779                 ;
5780
5781 /*****************************************************************************
5782  *
5783  *              QUERY:
5784  *                              CLUSTER <qualified_name> [ USING <index_name> ]
5785  *                              CLUSTER
5786  *                              CLUSTER <index_name> ON <qualified_name> (for pre-8.3)
5787  *
5788  *****************************************************************************/
5789
5790 ClusterStmt:
5791                         CLUSTER qualified_name cluster_index_specification
5792                                 {
5793                                ClusterStmt *n = makeNode(ClusterStmt);
5794                                    n->relation = $2;
5795                                    n->indexname = $3;
5796                                    $$ = (Node*)n;
5797                                 }
5798                         | CLUSTER
5799                             {
5800                                    ClusterStmt *n = makeNode(ClusterStmt);
5801                                    n->relation = NULL;
5802                                    n->indexname = NULL;
5803                                    $$ = (Node*)n;
5804                                 }
5805                         /* kept for pre-8.3 compatibility */
5806                         | CLUSTER index_name ON qualified_name
5807                                 {
5808                                    ClusterStmt *n = makeNode(ClusterStmt);
5809                                    n->relation = $4;
5810                                    n->indexname = $2;
5811                                    $$ = (Node*)n;
5812                                 }
5813                 ;
5814
5815 cluster_index_specification:
5816                         USING index_name                { $$ = $2; }
5817                         | /*EMPTY*/                             { $$ = NULL; }
5818                 ;
5819
5820
5821 /*****************************************************************************
5822  *
5823  *              QUERY:
5824  *                              VACUUM
5825  *                              ANALYZE
5826  *
5827  *****************************************************************************/
5828
5829 VacuumStmt: VACUUM opt_full opt_freeze opt_verbose
5830                                 {
5831                                         VacuumStmt *n = makeNode(VacuumStmt);
5832                                         n->vacuum = true;
5833                                         n->analyze = false;
5834                                         n->full = $2;
5835                                         n->freeze_min_age = $3 ? 0 : -1;
5836                                         n->verbose = $4;
5837                                         n->relation = NULL;
5838                                         n->va_cols = NIL;
5839                                         $$ = (Node *)n;
5840                                 }
5841                         | VACUUM opt_full opt_freeze opt_verbose qualified_name
5842                                 {
5843                                         VacuumStmt *n = makeNode(VacuumStmt);
5844                                         n->vacuum = true;
5845                                         n->analyze = false;
5846                                         n->full = $2;
5847                                         n->freeze_min_age = $3 ? 0 : -1;
5848                                         n->verbose = $4;
5849                                         n->relation = $5;
5850                                         n->va_cols = NIL;
5851                                         $$ = (Node *)n;
5852                                 }
5853                         | VACUUM opt_full opt_freeze opt_verbose AnalyzeStmt
5854                                 {
5855                                         VacuumStmt *n = (VacuumStmt *) $5;
5856                                         n->vacuum = true;
5857                                         n->full = $2;
5858                                         n->freeze_min_age = $3 ? 0 : -1;
5859                                         n->verbose |= $4;
5860                                         $$ = (Node *)n;
5861                                 }
5862                 ;
5863
5864 AnalyzeStmt:
5865                         analyze_keyword opt_verbose
5866                                 {
5867                                         VacuumStmt *n = makeNode(VacuumStmt);
5868                                         n->vacuum = false;
5869                                         n->analyze = true;
5870                                         n->full = false;
5871                                         n->freeze_min_age = -1;
5872                                         n->verbose = $2;
5873                                         n->relation = NULL;
5874                                         n->va_cols = NIL;
5875                                         $$ = (Node *)n;
5876                                 }
5877                         | analyze_keyword opt_verbose qualified_name opt_name_list
5878                                 {
5879                                         VacuumStmt *n = makeNode(VacuumStmt);
5880                                         n->vacuum = false;
5881                                         n->analyze = true;
5882                                         n->full = false;
5883                                         n->freeze_min_age = -1;
5884                                         n->verbose = $2;
5885                                         n->relation = $3;
5886                                         n->va_cols = $4;
5887                                         $$ = (Node *)n;
5888                                 }
5889                 ;
5890
5891 analyze_keyword:
5892                         ANALYZE                                                                 {}
5893                         | ANALYSE /* British */                                 {}
5894                 ;
5895
5896 opt_verbose:
5897                         VERBOSE                                                                 { $$ = TRUE; }
5898                         | /*EMPTY*/                                                             { $$ = FALSE; }
5899                 ;
5900
5901 opt_full:       FULL                                                                    { $$ = TRUE; }
5902                         | /*EMPTY*/                                                             { $$ = FALSE; }
5903                 ;
5904
5905 opt_freeze: FREEZE                                                                      { $$ = TRUE; }
5906                         | /*EMPTY*/                                                             { $$ = FALSE; }
5907                 ;
5908
5909 opt_name_list:
5910                         '(' name_list ')'                                               { $$ = $2; }
5911                         | /*EMPTY*/                                                             { $$ = NIL; }
5912                 ;
5913
5914
5915 /*****************************************************************************
5916  *
5917  *              QUERY:
5918  *                              EXPLAIN [ANALYZE] [VERBOSE] query
5919  *
5920  *****************************************************************************/
5921
5922 ExplainStmt: EXPLAIN opt_analyze opt_verbose ExplainableStmt
5923                                 {
5924                                         ExplainStmt *n = makeNode(ExplainStmt);
5925                                         n->analyze = $2;
5926                                         n->verbose = $3;
5927                                         n->query = $4;
5928                                         $$ = (Node *)n;
5929                                 }
5930                 ;
5931
5932 ExplainableStmt:
5933                         SelectStmt
5934                         | InsertStmt
5935                         | UpdateStmt
5936                         | DeleteStmt
5937                         | DeclareCursorStmt
5938                         | CreateAsStmt
5939                         | ExecuteStmt                                   /* by default all are $$=$1 */
5940                 ;
5941
5942 opt_analyze:
5943                         analyze_keyword                 { $$ = TRUE; }
5944                         | /* EMPTY */                   { $$ = FALSE; }
5945                 ;
5946
5947 /*****************************************************************************
5948  *
5949  *              QUERY:
5950  *                              PREPARE <plan_name> [(args, ...)] AS <query>
5951  *
5952  *****************************************************************************/
5953
5954 PrepareStmt: PREPARE name prep_type_clause AS PreparableStmt
5955                                 {
5956                                         PrepareStmt *n = makeNode(PrepareStmt);
5957                                         n->name = $2;
5958                                         n->argtypes = $3;
5959                                         n->query = $5;
5960                                         $$ = (Node *) n;
5961                                 }
5962                 ;
5963
5964 prep_type_clause: '(' type_list ')'                     { $$ = $2; }
5965                                 | /* EMPTY */                           { $$ = NIL; }
5966                 ;
5967
5968 PreparableStmt:
5969                         SelectStmt
5970                         | InsertStmt
5971                         | UpdateStmt
5972                         | DeleteStmt                                    /* by default all are $$=$1 */
5973                 ;
5974
5975 /*****************************************************************************
5976  *
5977  * EXECUTE <plan_name> [(params, ...)]
5978  * CREATE TABLE <name> AS EXECUTE <plan_name> [(params, ...)]
5979  *
5980  *****************************************************************************/
5981
5982 ExecuteStmt: EXECUTE name execute_param_clause
5983                                 {
5984                                         ExecuteStmt *n = makeNode(ExecuteStmt);
5985                                         n->name = $2;
5986                                         n->params = $3;
5987                                         n->into = NULL;
5988                                         $$ = (Node *) n;
5989                                 }
5990                         | CREATE OptTemp TABLE create_as_target AS
5991                                 EXECUTE name execute_param_clause
5992                                 {
5993                                         ExecuteStmt *n = makeNode(ExecuteStmt);
5994                                         n->name = $7;
5995                                         n->params = $8;
5996                                         $4->rel->istemp = $2;
5997                                         n->into = $4;
5998                                         if ($4->colNames)
5999                                                 ereport(ERROR,
6000                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
6001                                                                  errmsg("column name list not allowed in CREATE TABLE / AS EXECUTE")));
6002                                         /* ... because it's not implemented, but it could be */
6003                                         $$ = (Node *) n;
6004                                 }
6005                 ;
6006
6007 execute_param_clause: '(' expr_list ')'                         { $$ = $2; }
6008                                         | /* EMPTY */                                   { $$ = NIL; }
6009                                         ;
6010
6011 /*****************************************************************************
6012  *
6013  *              QUERY:
6014  *                              DEALLOCATE [PREPARE] <plan_name>
6015  *
6016  *****************************************************************************/
6017
6018 DeallocateStmt: DEALLOCATE name
6019                                         {
6020                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6021                                                 n->name = $2;
6022                                                 $$ = (Node *) n;
6023                                         }
6024                                 | DEALLOCATE PREPARE name
6025                                         {
6026                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6027                                                 n->name = $3;
6028                                                 $$ = (Node *) n;
6029                                         }
6030                                 | DEALLOCATE ALL
6031                                         {
6032                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6033                                                 n->name = NULL;
6034                                                 $$ = (Node *) n;
6035                                         }
6036                                 | DEALLOCATE PREPARE ALL
6037                                         {
6038                                                 DeallocateStmt *n = makeNode(DeallocateStmt);
6039                                                 n->name = NULL;
6040                                                 $$ = (Node *) n;
6041                                         }
6042                 ;
6043
6044 /*****************************************************************************
6045  *
6046  *              QUERY:
6047  *                              INSERT STATEMENTS
6048  *
6049  *****************************************************************************/
6050
6051 InsertStmt:
6052                         INSERT INTO qualified_name insert_rest returning_clause
6053                                 {
6054                                         $4->relation = $3;
6055                                         $4->returningList = $5;
6056                                         $$ = (Node *) $4;
6057                                 }
6058                 ;
6059
6060 insert_rest:
6061                         SelectStmt
6062                                 {
6063                                         $$ = makeNode(InsertStmt);
6064                                         $$->cols = NIL;
6065                                         $$->selectStmt = $1;
6066                                 }
6067                         | '(' insert_column_list ')' SelectStmt
6068                                 {
6069                                         $$ = makeNode(InsertStmt);
6070                                         $$->cols = $2;
6071                                         $$->selectStmt = $4;
6072                                 }
6073                         | DEFAULT VALUES
6074                                 {
6075                                         $$ = makeNode(InsertStmt);
6076                                         $$->cols = NIL;
6077                                         $$->selectStmt = NULL;
6078                                 }
6079                 ;
6080
6081 insert_column_list:
6082                         insert_column_item
6083                                         { $$ = list_make1($1); }
6084                         | insert_column_list ',' insert_column_item
6085                                         { $$ = lappend($1, $3); }
6086                 ;
6087
6088 insert_column_item:
6089                         ColId opt_indirection
6090                                 {
6091                                         $$ = makeNode(ResTarget);
6092                                         $$->name = $1;
6093                                         $$->indirection = check_indirection($2);
6094                                         $$->val = NULL;
6095                                         $$->location = @1;
6096                                 }
6097                 ;
6098
6099 returning_clause:
6100                         RETURNING target_list           { $$ = $2; }
6101                         | /* EMPTY */                           { $$ = NIL; }
6102                 ;
6103
6104
6105 /*****************************************************************************
6106  *
6107  *              QUERY:
6108  *                              DELETE STATEMENTS
6109  *
6110  *****************************************************************************/
6111
6112 DeleteStmt: DELETE_P FROM relation_expr_opt_alias
6113                         using_clause where_or_current_clause returning_clause
6114                                 {
6115                                         DeleteStmt *n = makeNode(DeleteStmt);
6116                                         n->relation = $3;
6117                                         n->usingClause = $4;
6118                                         n->whereClause = $5;
6119                                         n->returningList = $6;
6120                                         $$ = (Node *)n;
6121                                 }
6122                 ;
6123
6124 using_clause:
6125                         USING from_list                                         { $$ = $2; }
6126                         | /*EMPTY*/                                                             { $$ = NIL; }
6127                 ;
6128
6129 LockStmt:       LOCK_P opt_table qualified_name_list opt_lock opt_nowait
6130                                 {
6131                                         LockStmt *n = makeNode(LockStmt);
6132
6133                                         n->relations = $3;
6134                                         n->mode = $4;
6135                                         n->nowait = $5;
6136                                         $$ = (Node *)n;
6137                                 }
6138                 ;
6139
6140 opt_lock:       IN_P lock_type MODE                     { $$ = $2; }
6141                         | /*EMPTY*/                                             { $$ = AccessExclusiveLock; }
6142                 ;
6143
6144 lock_type:      ACCESS SHARE                                    { $$ = AccessShareLock; }
6145                         | ROW SHARE                                             { $$ = RowShareLock; }
6146                         | ROW EXCLUSIVE                                 { $$ = RowExclusiveLock; }
6147                         | SHARE UPDATE EXCLUSIVE                { $$ = ShareUpdateExclusiveLock; }
6148                         | SHARE                                                 { $$ = ShareLock; }
6149                         | SHARE ROW EXCLUSIVE                   { $$ = ShareRowExclusiveLock; }
6150                         | EXCLUSIVE                                             { $$ = ExclusiveLock; }
6151                         | ACCESS EXCLUSIVE                              { $$ = AccessExclusiveLock; }
6152                 ;
6153
6154 opt_nowait:     NOWAIT                                                  { $$ = TRUE; }
6155                         | /*EMPTY*/                                             { $$ = FALSE; }
6156                 ;
6157
6158
6159 /*****************************************************************************
6160  *
6161  *              QUERY:
6162  *                              UpdateStmt (UPDATE)
6163  *
6164  *****************************************************************************/
6165
6166 UpdateStmt: UPDATE relation_expr_opt_alias
6167                         SET set_clause_list
6168                         from_clause
6169                         where_or_current_clause
6170                         returning_clause
6171                                 {
6172                                         UpdateStmt *n = makeNode(UpdateStmt);
6173                                         n->relation = $2;
6174                                         n->targetList = $4;
6175                                         n->fromClause = $5;
6176                                         n->whereClause = $6;
6177                                         n->returningList = $7;
6178                                         $$ = (Node *)n;
6179                                 }
6180                 ;
6181
6182 set_clause_list:
6183                         set_clause                                                      { $$ = $1; }
6184                         | set_clause_list ',' set_clause        { $$ = list_concat($1,$3); }
6185                 ;
6186
6187 set_clause:
6188                         single_set_clause                                               { $$ = list_make1($1); }
6189                         | multiple_set_clause                                   { $$ = $1; }
6190                 ;
6191
6192 single_set_clause:
6193                         set_target '=' ctext_expr
6194                                 {
6195                                         $$ = $1;
6196                                         $$->val = (Node *) $3;
6197                                 }
6198                 ;
6199
6200 multiple_set_clause:
6201                         '(' set_target_list ')' '=' ctext_row
6202                                 {
6203                                         ListCell *col_cell;
6204                                         ListCell *val_cell;
6205
6206                                         /*
6207                                          * Break the ctext_row apart, merge individual expressions
6208                                          * into the destination ResTargets.  XXX this approach
6209                                          * cannot work for general row expressions as sources.
6210                                          */
6211                                         if (list_length($2) != list_length($5))
6212                                                 ereport(ERROR,
6213                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
6214                                                                  errmsg("number of columns does not match number of values"),
6215                                                                  scanner_errposition(@1)));
6216                                         forboth(col_cell, $2, val_cell, $5)
6217                                         {
6218                                                 ResTarget *res_col = (ResTarget *) lfirst(col_cell);
6219                                                 Node *res_val = (Node *) lfirst(val_cell);
6220
6221                                                 res_col->val = res_val;
6222                                         }
6223
6224                                         $$ = $2;
6225                                 }
6226                 ;
6227
6228 set_target:
6229                         ColId opt_indirection
6230                                 {
6231                                         $$ = makeNode(ResTarget);
6232                                         $$->name = $1;
6233                                         $$->indirection = check_indirection($2);
6234                                         $$->val = NULL; /* upper production sets this */
6235                                         $$->location = @1;
6236                                 }
6237                 ;
6238
6239 set_target_list:
6240                         set_target                                                              { $$ = list_make1($1); }
6241                         | set_target_list ',' set_target                { $$ = lappend($1,$3); }
6242                 ;
6243
6244
6245 /*****************************************************************************
6246  *
6247  *              QUERY:
6248  *                              CURSOR STATEMENTS
6249  *
6250  *****************************************************************************/
6251 DeclareCursorStmt: DECLARE name cursor_options CURSOR opt_hold FOR SelectStmt
6252                                 {
6253                                         DeclareCursorStmt *n = makeNode(DeclareCursorStmt);
6254                                         n->portalname = $2;
6255                                         /* currently we always set FAST_PLAN option */
6256                                         n->options = $3 | $5 | CURSOR_OPT_FAST_PLAN;
6257                                         n->query = $7;
6258                                         $$ = (Node *)n;
6259                                 }
6260                 ;
6261
6262 cursor_options: /*EMPTY*/                                       { $$ = 0; }
6263                         | cursor_options NO SCROLL              { $$ = $1 | CURSOR_OPT_NO_SCROLL; }
6264                         | cursor_options SCROLL                 { $$ = $1 | CURSOR_OPT_SCROLL; }
6265                         | cursor_options BINARY                 { $$ = $1 | CURSOR_OPT_BINARY; }
6266                         | cursor_options INSENSITIVE    { $$ = $1 | CURSOR_OPT_INSENSITIVE; }
6267                 ;
6268
6269 opt_hold: /* EMPTY */                                           { $$ = 0; }
6270                         | WITH HOLD                                             { $$ = CURSOR_OPT_HOLD; }
6271                         | WITHOUT HOLD                                  { $$ = 0; }
6272                 ;
6273
6274 /*****************************************************************************
6275  *
6276  *              QUERY:
6277  *                              SELECT STATEMENTS
6278  *
6279  *****************************************************************************/
6280
6281 /* A complete SELECT statement looks like this.
6282  *
6283  * The rule returns either a single SelectStmt node or a tree of them,
6284  * representing a set-operation tree.
6285  *
6286  * There is an ambiguity when a sub-SELECT is within an a_expr and there
6287  * are excess parentheses: do the parentheses belong to the sub-SELECT or
6288  * to the surrounding a_expr?  We don't really care, but yacc wants to know.
6289  * To resolve the ambiguity, we are careful to define the grammar so that
6290  * the decision is staved off as long as possible: as long as we can keep
6291  * absorbing parentheses into the sub-SELECT, we will do so, and only when
6292  * it's no longer possible to do that will we decide that parens belong to
6293  * the expression.      For example, in "SELECT (((SELECT 2)) + 3)" the extra
6294  * parentheses are treated as part of the sub-select.  The necessity of doing
6295  * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)".      Had we
6296  * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
6297  * SELECT viewpoint when we see the UNION.
6298  *
6299  * This approach is implemented by defining a nonterminal select_with_parens,
6300  * which represents a SELECT with at least one outer layer of parentheses,
6301  * and being careful to use select_with_parens, never '(' SelectStmt ')',
6302  * in the expression grammar.  We will then have shift-reduce conflicts
6303  * which we can resolve in favor of always treating '(' <select> ')' as
6304  * a select_with_parens.  To resolve the conflicts, the productions that
6305  * conflict with the select_with_parens productions are manually given
6306  * precedences lower than the precedence of ')', thereby ensuring that we
6307  * shift ')' (and then reduce to select_with_parens) rather than trying to
6308  * reduce the inner <select> nonterminal to something else.  We use UMINUS
6309  * precedence for this, which is a fairly arbitrary choice.
6310  *
6311  * To be able to define select_with_parens itself without ambiguity, we need
6312  * a nonterminal select_no_parens that represents a SELECT structure with no
6313  * outermost parentheses.  This is a little bit tedious, but it works.
6314  *
6315  * In non-expression contexts, we use SelectStmt which can represent a SELECT
6316  * with or without outer parentheses.
6317  */
6318
6319 SelectStmt: select_no_parens                    %prec UMINUS
6320                         | select_with_parens            %prec UMINUS
6321                 ;
6322
6323 select_with_parens:
6324                         '(' select_no_parens ')'                                { $$ = $2; }
6325                         | '(' select_with_parens ')'                    { $$ = $2; }
6326                 ;
6327
6328 /*
6329  * This rule parses the equivalent of the standard's <query expression>.
6330  * The duplicative productions are annoying, but hard to get rid of without
6331  * creating shift/reduce conflicts.
6332  *
6333  *      FOR UPDATE/SHARE may be before or after LIMIT/OFFSET.
6334  *      In <=7.2.X, LIMIT/OFFSET had to be after FOR UPDATE
6335  *      We now support both orderings, but prefer LIMIT/OFFSET before FOR UPDATE/SHARE
6336  *      2002-08-28 bjm
6337  */
6338 select_no_parens:
6339                         simple_select                                           { $$ = $1; }
6340                         | select_clause sort_clause
6341                                 {
6342                                         insertSelectOptions((SelectStmt *) $1, $2, NIL,
6343                                                                                 NULL, NULL, NULL);
6344                                         $$ = $1;
6345                                 }
6346                         | select_clause opt_sort_clause for_locking_clause opt_select_limit
6347                                 {
6348                                         insertSelectOptions((SelectStmt *) $1, $2, $3,
6349                                                                                 list_nth($4, 0), list_nth($4, 1),
6350                                                                                 NULL);
6351                                         $$ = $1;
6352                                 }
6353                         | select_clause opt_sort_clause select_limit opt_for_locking_clause
6354                                 {
6355                                         insertSelectOptions((SelectStmt *) $1, $2, $4,
6356                                                                                 list_nth($3, 0), list_nth($3, 1),
6357                                                                                 NULL);
6358                                         $$ = $1;
6359                                 }
6360                         | with_clause simple_select
6361                                 {
6362                                         insertSelectOptions((SelectStmt *) $2, NULL, NIL,
6363                                                                                 NULL, NULL,
6364                                                                                 $1);
6365                                         $$ = $2;
6366                                 }
6367                         | with_clause select_clause sort_clause
6368                                 {
6369                                         insertSelectOptions((SelectStmt *) $2, $3, NIL,
6370                                                                                 NULL, NULL,
6371                                                                                 $1);
6372                                         $$ = $2;
6373                                 }
6374                         | with_clause select_clause opt_sort_clause for_locking_clause opt_select_limit
6375                                 {
6376                                         insertSelectOptions((SelectStmt *) $2, $3, $4,
6377                                                                                 list_nth($5, 0), list_nth($5, 1),
6378                                                                                 $1);
6379                                         $$ = $2;
6380                                 }
6381                         | with_clause select_clause opt_sort_clause select_limit opt_for_locking_clause
6382                                 {
6383                                         insertSelectOptions((SelectStmt *) $2, $3, $5,
6384                                                                                 list_nth($4, 0), list_nth($4, 1),
6385                                                                                 $1);
6386                                         $$ = $2;
6387                                 }
6388                 ;
6389
6390 select_clause:
6391                         simple_select                                                   { $$ = $1; }
6392                         | select_with_parens                                    { $$ = $1; }
6393                 ;
6394
6395 /*
6396  * This rule parses SELECT statements that can appear within set operations,
6397  * including UNION, INTERSECT and EXCEPT.  '(' and ')' can be used to specify
6398  * the ordering of the set operations.  Without '(' and ')' we want the
6399  * operations to be ordered per the precedence specs at the head of this file.
6400  *
6401  * As with select_no_parens, simple_select cannot have outer parentheses,
6402  * but can have parenthesized subclauses.
6403  *
6404  * Note that sort clauses cannot be included at this level --- SQL92 requires
6405  *              SELECT foo UNION SELECT bar ORDER BY baz
6406  * to be parsed as
6407  *              (SELECT foo UNION SELECT bar) ORDER BY baz
6408  * not
6409  *              SELECT foo UNION (SELECT bar ORDER BY baz)
6410  * Likewise for WITH, FOR UPDATE and LIMIT.  Therefore, those clauses are
6411  * described as part of the select_no_parens production, not simple_select.
6412  * This does not limit functionality, because you can reintroduce these
6413  * clauses inside parentheses.
6414  *
6415  * NOTE: only the leftmost component SelectStmt should have INTO.
6416  * However, this is not checked by the grammar; parse analysis must check it.
6417  */
6418 simple_select:
6419                         SELECT opt_distinct target_list
6420                         into_clause from_clause where_clause
6421                         group_clause having_clause
6422                                 {
6423                                         SelectStmt *n = makeNode(SelectStmt);
6424                                         n->distinctClause = $2;
6425                                         n->targetList = $3;
6426                                         n->intoClause = $4;
6427                                         n->fromClause = $5;
6428                                         n->whereClause = $6;
6429                                         n->groupClause = $7;
6430                                         n->havingClause = $8;
6431                                         $$ = (Node *)n;
6432                                 }
6433                         | values_clause                                                 { $$ = $1; }
6434                         | select_clause UNION opt_all select_clause
6435                                 {
6436                                         $$ = makeSetOp(SETOP_UNION, $3, $1, $4);
6437                                 }
6438                         | select_clause INTERSECT opt_all select_clause
6439                                 {
6440                                         $$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
6441                                 }
6442                         | select_clause EXCEPT opt_all select_clause
6443                                 {
6444                                         $$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
6445                                 }
6446                 ;
6447
6448 /*
6449  * SQL standard WITH clause looks like:
6450  *
6451  * WITH [ RECURSIVE ] <query name> [ (<column>,...) ]
6452  *              AS (query) [ SEARCH or CYCLE clause ]
6453  *
6454  * We don't currently support the SEARCH or CYCLE clause.
6455  */
6456 with_clause:
6457                 WITH cte_list
6458                         {
6459                                 $$ = makeNode(WithClause);
6460                                 $$->ctes = $2;
6461                                 $$->recursive = false;
6462                                 $$->location = @1;
6463                         }
6464                 | WITH RECURSIVE cte_list
6465                         {
6466                                 $$ = makeNode(WithClause);
6467                                 $$->ctes = $3;
6468                                 $$->recursive = true;
6469                                 $$->location = @1;
6470                         }
6471                 ;
6472
6473 cte_list:
6474                 common_table_expr                                               { $$ = list_make1($1); }
6475                 | cte_list ',' common_table_expr                { $$ = lappend($1, $3); }
6476                 ;
6477
6478 common_table_expr:  name opt_name_list AS select_with_parens
6479                         {
6480                                 CommonTableExpr *n = makeNode(CommonTableExpr);
6481                                 n->ctename = $1;
6482                                 n->aliascolnames = $2;
6483                                 n->ctequery = $4;
6484                                 n->location = @1;
6485                                 $$ = (Node *) n;
6486                         }
6487                 ;
6488
6489 into_clause:
6490                         INTO OptTempTableName
6491                                 {
6492                                         $$ = makeNode(IntoClause);
6493                                         $$->rel = $2;
6494                                         $$->colNames = NIL;
6495                                         $$->options = NIL;
6496                                         $$->onCommit = ONCOMMIT_NOOP;
6497                                         $$->tableSpaceName = NULL;
6498                                 }
6499                         | /*EMPTY*/
6500                                 { $$ = NULL; }
6501                 ;
6502
6503 /*
6504  * Redundancy here is needed to avoid shift/reduce conflicts,
6505  * since TEMP is not a reserved word.  See also OptTemp.
6506  */
6507 OptTempTableName:
6508                         TEMPORARY opt_table qualified_name
6509                                 {
6510                                         $$ = $3;
6511                                         $$->istemp = true;
6512                                 }
6513                         | TEMP opt_table qualified_name
6514                                 {
6515                                         $$ = $3;
6516                                         $$->istemp = true;
6517                                 }
6518                         | LOCAL TEMPORARY opt_table qualified_name
6519                                 {
6520                                         $$ = $4;
6521                                         $$->istemp = true;
6522                                 }
6523                         | LOCAL TEMP opt_table qualified_name
6524                                 {
6525                                         $$ = $4;
6526                                         $$->istemp = true;
6527                                 }
6528                         | GLOBAL TEMPORARY opt_table qualified_name
6529                                 {
6530                                         $$ = $4;
6531                                         $$->istemp = true;
6532                                 }
6533                         | GLOBAL TEMP opt_table qualified_name
6534                                 {
6535                                         $$ = $4;
6536                                         $$->istemp = true;
6537                                 }
6538                         | TABLE qualified_name
6539                                 {
6540                                         $$ = $2;
6541                                         $$->istemp = false;
6542                                 }
6543                         | qualified_name
6544                                 {
6545                                         $$ = $1;
6546                                         $$->istemp = false;
6547                                 }
6548                 ;
6549
6550 opt_table:      TABLE                                                                   {}
6551                         | /*EMPTY*/                                                             {}
6552                 ;
6553
6554 opt_all:        ALL                                                                             { $$ = TRUE; }
6555                         | DISTINCT                                                              { $$ = FALSE; }
6556                         | /*EMPTY*/                                                             { $$ = FALSE; }
6557                 ;
6558
6559 /* We use (NIL) as a placeholder to indicate that all target expressions
6560  * should be placed in the DISTINCT list during parsetree analysis.
6561  */
6562 opt_distinct:
6563                         DISTINCT                                                                { $$ = list_make1(NIL); }
6564                         | DISTINCT ON '(' expr_list ')'                 { $$ = $4; }
6565                         | ALL                                                                   { $$ = NIL; }
6566                         | /*EMPTY*/                                                             { $$ = NIL; }
6567                 ;
6568
6569 opt_sort_clause:
6570                         sort_clause                                                             { $$ = $1;}
6571                         | /*EMPTY*/                                                             { $$ = NIL; }
6572                 ;
6573
6574 sort_clause:
6575                         ORDER BY sortby_list                                    { $$ = $3; }
6576                 ;
6577
6578 sortby_list:
6579                         sortby                                                                  { $$ = list_make1($1); }
6580                         | sortby_list ',' sortby                                { $$ = lappend($1, $3); }
6581                 ;
6582
6583 sortby:         a_expr USING qual_all_Op opt_nulls_order
6584                                 {
6585                                         $$ = makeNode(SortBy);
6586                                         $$->node = $1;
6587                                         $$->sortby_dir = SORTBY_USING;
6588                                         $$->sortby_nulls = $4;
6589                                         $$->useOp = $3;
6590                                         $$->location = @3;
6591                                 }
6592                         | a_expr opt_asc_desc opt_nulls_order
6593                                 {
6594                                         $$ = makeNode(SortBy);
6595                                         $$->node = $1;
6596                                         $$->sortby_dir = $2;
6597                                         $$->sortby_nulls = $3;
6598                                         $$->useOp = NIL;
6599                                         $$->location = -1;              /* no operator */
6600                                 }
6601                 ;
6602
6603
6604 select_limit:
6605                         LIMIT select_limit_value OFFSET select_offset_value
6606                                 { $$ = list_make2($4, $2); }
6607                         | OFFSET select_offset_value LIMIT select_limit_value
6608                                 { $$ = list_make2($2, $4); }
6609                         | LIMIT select_limit_value
6610                                 { $$ = list_make2(NULL, $2); }
6611                         | OFFSET select_offset_value
6612                                 { $$ = list_make2($2, NULL); }
6613                         | LIMIT select_limit_value ',' select_offset_value
6614                                 {
6615                                         /* Disabled because it was too confusing, bjm 2002-02-18 */
6616                                         ereport(ERROR,
6617                                                         (errcode(ERRCODE_SYNTAX_ERROR),
6618                                                          errmsg("LIMIT #,# syntax is not supported"),
6619                                                          errhint("Use separate LIMIT and OFFSET clauses."),
6620                                                          scanner_errposition(@1)));
6621                                 }
6622                         /* SQL:2008 syntax variants */
6623                         | OFFSET select_offset_value2 row_or_rows
6624                                 { $$ = list_make2($2, NULL); }
6625                         | FETCH first_or_next opt_select_fetch_first_value row_or_rows ONLY
6626                                 { $$ = list_make2(NULL, $3); }
6627                         | OFFSET select_offset_value2 row_or_rows FETCH first_or_next opt_select_fetch_first_value row_or_rows ONLY
6628                                 { $$ = list_make2($2, $6); }
6629                 ;
6630
6631 opt_select_limit:
6632                         select_limit                                                    { $$ = $1; }
6633                         | /* EMPTY */
6634                                         { $$ = list_make2(NULL,NULL); }
6635                 ;
6636
6637 select_limit_value:
6638                         a_expr                                                                  { $$ = $1; }
6639                         | ALL
6640                                 {
6641                                         /* LIMIT ALL is represented as a NULL constant */
6642                                         $$ = makeNullAConst(@1);
6643                                 }
6644                 ;
6645
6646 /*
6647  * Allowing full expressions without parentheses causes various parsing
6648  * problems with the trailing ROW/ROWS key words.  SQL only calls for
6649  * constants, so we allow the rest only with parentheses.
6650  */
6651 opt_select_fetch_first_value:
6652                         SignedIconst            { $$ = makeIntConst($1, @1); }
6653                         | '(' a_expr ')'        { $$ = $2; }
6654                         | /*EMPTY*/             { $$ = makeIntConst(1, -1); }
6655                 ;
6656
6657 select_offset_value:
6658                         a_expr                                                                  { $$ = $1; }
6659                 ;
6660
6661 /*
6662  * Again, the trailing ROW/ROWS in this case prevent the full expression
6663  * syntax.  c_expr is the best we can do.
6664  */
6665 select_offset_value2:
6666                         c_expr                                                                  { $$ = $1; }
6667                 ;
6668
6669 /* noise words */
6670 row_or_rows:
6671                         ROW             { $$ = 0; }
6672                         | ROWS          { $$ = 0; }
6673                         ;
6674
6675 /* noise words */
6676 first_or_next:
6677                         FIRST_P         { $$ = 0; }
6678                         | NEXT          { $$ = 0; }
6679                         ;
6680
6681 group_clause:
6682                         GROUP_P BY expr_list                                    { $$ = $3; }
6683                         | /*EMPTY*/                                                             { $$ = NIL; }
6684                 ;
6685
6686 having_clause:
6687                         HAVING a_expr                                                   { $$ = $2; }
6688                         | /*EMPTY*/                                                             { $$ = NULL; }
6689                 ;
6690
6691 for_locking_clause:
6692                         for_locking_items                                               { $$ = $1; }
6693                         | FOR READ ONLY                                                 { $$ = NIL; }
6694                 ;
6695
6696 opt_for_locking_clause:
6697                         for_locking_clause                                              { $$ = $1; }
6698                         | /* EMPTY */                                                   { $$ = NIL; }
6699                 ;
6700
6701 for_locking_items:
6702                         for_locking_item                                                { $$ = list_make1($1); }
6703                         | for_locking_items for_locking_item    { $$ = lappend($1, $2); }
6704                 ;
6705
6706 for_locking_item:
6707                         FOR UPDATE locked_rels_list opt_nowait
6708                                 {
6709                                         LockingClause *n = makeNode(LockingClause);
6710                                         n->lockedRels = $3;
6711                                         n->forUpdate = TRUE;
6712                                         n->noWait = $4;
6713                                         $$ = (Node *) n;
6714                                 }
6715                         | FOR SHARE locked_rels_list opt_nowait
6716                                 {
6717                                         LockingClause *n = makeNode(LockingClause);
6718                                         n->lockedRels = $3;
6719                                         n->forUpdate = FALSE;
6720                                         n->noWait = $4;
6721                                         $$ = (Node *) n;
6722                                 }
6723                 ;
6724
6725 locked_rels_list:
6726                         OF qualified_name_list                                  { $$ = $2; }
6727                         | /* EMPTY */                                                   { $$ = NIL; }
6728                 ;
6729
6730
6731 values_clause:
6732                         VALUES ctext_row
6733                                 {
6734                                         SelectStmt *n = makeNode(SelectStmt);
6735                                         n->valuesLists = list_make1($2);
6736                                         $$ = (Node *) n;
6737                                 }
6738                         | values_clause ',' ctext_row
6739                                 {
6740                                         SelectStmt *n = (SelectStmt *) $1;
6741                                         n->valuesLists = lappend(n->valuesLists, $3);
6742                                         $$ = (Node *) n;
6743                                 }
6744                 ;
6745
6746
6747 /*****************************************************************************
6748  *
6749  *      clauses common to all Optimizable Stmts:
6750  *              from_clause             - allow list of both JOIN expressions and table names
6751  *              where_clause    - qualifications for joins or restrictions
6752  *
6753  *****************************************************************************/
6754
6755 from_clause:
6756                         FROM from_list                                                  { $$ = $2; }
6757                         | /*EMPTY*/                                                             { $$ = NIL; }
6758                 ;
6759
6760 from_list:
6761                         table_ref                                                               { $$ = list_make1($1); }
6762                         | from_list ',' table_ref                               { $$ = lappend($1, $3); }
6763                 ;
6764
6765 /*
6766  * table_ref is where an alias clause can be attached.  Note we cannot make
6767  * alias_clause have an empty production because that causes parse conflicts
6768  * between table_ref := '(' joined_table ')' alias_clause
6769  * and joined_table := '(' joined_table ')'.  So, we must have the
6770  * redundant-looking productions here instead.
6771  */
6772 table_ref:      relation_expr
6773                                 {
6774                                         $$ = (Node *) $1;
6775                                 }
6776                         | relation_expr alias_clause
6777                                 {
6778                                         $1->alias = $2;
6779                                         $$ = (Node *) $1;
6780                                 }
6781                         | func_table
6782                                 {
6783                                         RangeFunction *n = makeNode(RangeFunction);
6784                                         n->funccallnode = $1;
6785                                         n->coldeflist = NIL;
6786                                         $$ = (Node *) n;
6787                                 }
6788                         | func_table alias_clause
6789                                 {
6790                                         RangeFunction *n = makeNode(RangeFunction);
6791                                         n->funccallnode = $1;
6792                                         n->alias = $2;
6793                                         n->coldeflist = NIL;
6794                                         $$ = (Node *) n;
6795                                 }
6796                         | func_table AS '(' TableFuncElementList ')'
6797                                 {
6798                                         RangeFunction *n = makeNode(RangeFunction);
6799                                         n->funccallnode = $1;
6800                                         n->coldeflist = $4;
6801                                         $$ = (Node *) n;
6802                                 }
6803                         | func_table AS ColId '(' TableFuncElementList ')'
6804                                 {
6805                                         RangeFunction *n = makeNode(RangeFunction);
6806                                         Alias *a = makeNode(Alias);
6807                                         n->funccallnode = $1;
6808                                         a->aliasname = $3;
6809                                         n->alias = a;
6810                                         n->coldeflist = $5;
6811                                         $$ = (Node *) n;
6812                                 }
6813                         | func_table ColId '(' TableFuncElementList ')'
6814                                 {
6815                                         RangeFunction *n = makeNode(RangeFunction);
6816                                         Alias *a = makeNode(Alias);
6817                                         n->funccallnode = $1;
6818                                         a->aliasname = $2;
6819                                         n->alias = a;
6820                                         n->coldeflist = $4;
6821                                         $$ = (Node *) n;
6822                                 }
6823                         | select_with_parens
6824                                 {
6825                                         /*
6826                                          * The SQL spec does not permit a subselect
6827                                          * (<derived_table>) without an alias clause,
6828                                          * so we don't either.  This avoids the problem
6829                                          * of needing to invent a unique refname for it.
6830                                          * That could be surmounted if there's sufficient
6831                                          * popular demand, but for now let's just implement
6832                                          * the spec and see if anyone complains.
6833                                          * However, it does seem like a good idea to emit
6834                                          * an error message that's better than "syntax error".
6835                                          */
6836                                         if (IsA($1, SelectStmt) &&
6837                                                 ((SelectStmt *) $1)->valuesLists)
6838                                                 ereport(ERROR,
6839                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
6840                                                                  errmsg("VALUES in FROM must have an alias"),
6841                                                                  errhint("For example, FROM (VALUES ...) [AS] foo."),
6842                                                                  scanner_errposition(@1)));
6843                                         else
6844                                                 ereport(ERROR,
6845                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
6846                                                                  errmsg("subquery in FROM must have an alias"),
6847                                                                  errhint("For example, FROM (SELECT ...) [AS] foo."),
6848                                                                  scanner_errposition(@1)));
6849                                         $$ = NULL;
6850                                 }
6851                         | select_with_parens alias_clause
6852                                 {
6853                                         RangeSubselect *n = makeNode(RangeSubselect);
6854                                         n->subquery = $1;
6855                                         n->alias = $2;
6856                                         $$ = (Node *) n;
6857                                 }
6858                         | joined_table
6859                                 {
6860                                         $$ = (Node *) $1;
6861                                 }
6862                         | '(' joined_table ')' alias_clause
6863                                 {
6864                                         $2->alias = $4;
6865                                         $$ = (Node *) $2;
6866                                 }
6867                 ;
6868
6869
6870 /*
6871  * It may seem silly to separate joined_table from table_ref, but there is
6872  * method in SQL92's madness: if you don't do it this way you get reduce-
6873  * reduce conflicts, because it's not clear to the parser generator whether
6874  * to expect alias_clause after ')' or not.  For the same reason we must
6875  * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
6876  * join_type to expand to empty; if we try it, the parser generator can't
6877  * figure out when to reduce an empty join_type right after table_ref.
6878  *
6879  * Note that a CROSS JOIN is the same as an unqualified
6880  * INNER JOIN, and an INNER JOIN/ON has the same shape
6881  * but a qualification expression to limit membership.
6882  * A NATURAL JOIN implicitly matches column names between
6883  * tables and the shape is determined by which columns are
6884  * in common. We'll collect columns during the later transformations.
6885  */
6886
6887 joined_table:
6888                         '(' joined_table ')'
6889                                 {
6890                                         $$ = $2;
6891                                 }
6892                         | table_ref CROSS JOIN table_ref
6893                                 {
6894                                         /* CROSS JOIN is same as unqualified inner join */
6895                                         JoinExpr *n = makeNode(JoinExpr);
6896                                         n->jointype = JOIN_INNER;
6897                                         n->isNatural = FALSE;
6898                                         n->larg = $1;
6899                                         n->rarg = $4;
6900                                         n->using = NIL;
6901                                         n->quals = NULL;
6902                                         $$ = n;
6903                                 }
6904                         | table_ref join_type JOIN table_ref join_qual
6905                                 {
6906                                         JoinExpr *n = makeNode(JoinExpr);
6907                                         n->jointype = $2;
6908                                         n->isNatural = FALSE;
6909                                         n->larg = $1;
6910                                         n->rarg = $4;
6911                                         if ($5 != NULL && IsA($5, List))
6912                                                 n->using = (List *) $5; /* USING clause */
6913                                         else
6914                                                 n->quals = $5; /* ON clause */
6915                                         $$ = n;
6916                                 }
6917                         | table_ref JOIN table_ref join_qual
6918                                 {
6919                                         /* letting join_type reduce to empty doesn't work */
6920                                         JoinExpr *n = makeNode(JoinExpr);
6921                                         n->jointype = JOIN_INNER;
6922                                         n->isNatural = FALSE;
6923                                         n->larg = $1;
6924                                         n->rarg = $3;
6925                                         if ($4 != NULL && IsA($4, List))
6926                                                 n->using = (List *) $4; /* USING clause */
6927                                         else
6928                                                 n->quals = $4; /* ON clause */
6929                                         $$ = n;
6930                                 }
6931                         | table_ref NATURAL join_type JOIN table_ref
6932                                 {
6933                                         JoinExpr *n = makeNode(JoinExpr);
6934                                         n->jointype = $3;
6935                                         n->isNatural = TRUE;
6936                                         n->larg = $1;
6937                                         n->rarg = $5;
6938                                         n->using = NIL; /* figure out which columns later... */
6939                                         n->quals = NULL; /* fill later */
6940                                         $$ = n;
6941                                 }
6942                         | table_ref NATURAL JOIN table_ref
6943                                 {
6944                                         /* letting join_type reduce to empty doesn't work */
6945                                         JoinExpr *n = makeNode(JoinExpr);
6946                                         n->jointype = JOIN_INNER;
6947                                         n->isNatural = TRUE;
6948                                         n->larg = $1;
6949                                         n->rarg = $4;
6950                                         n->using = NIL; /* figure out which columns later... */
6951                                         n->quals = NULL; /* fill later */
6952                                         $$ = n;
6953                                 }
6954                 ;
6955
6956 alias_clause:
6957                         AS ColId '(' name_list ')'
6958                                 {
6959                                         $$ = makeNode(Alias);
6960                                         $$->aliasname = $2;
6961                                         $$->colnames = $4;
6962                                 }
6963                         | AS ColId
6964                                 {
6965                                         $$ = makeNode(Alias);
6966                                         $$->aliasname = $2;
6967                                 }
6968                         | ColId '(' name_list ')'
6969                                 {
6970                                         $$ = makeNode(Alias);
6971                                         $$->aliasname = $1;
6972                                         $$->colnames = $3;
6973                                 }
6974                         | ColId
6975                                 {
6976                                         $$ = makeNode(Alias);
6977                                         $$->aliasname = $1;
6978                                 }
6979                 ;
6980
6981 join_type:      FULL join_outer                                                 { $$ = JOIN_FULL; }
6982                         | LEFT join_outer                                               { $$ = JOIN_LEFT; }
6983                         | RIGHT join_outer                                              { $$ = JOIN_RIGHT; }
6984                         | INNER_P                                                               { $$ = JOIN_INNER; }
6985                 ;
6986
6987 /* OUTER is just noise... */
6988 join_outer: OUTER_P                                                                     { $$ = NULL; }
6989                         | /*EMPTY*/                                                             { $$ = NULL; }
6990                 ;
6991
6992 /* JOIN qualification clauses
6993  * Possibilities are:
6994  *      USING ( column list ) allows only unqualified column names,
6995  *                                                which must match between tables.
6996  *      ON expr allows more general qualifications.
6997  *
6998  * We return USING as a List node, while an ON-expr will not be a List.
6999  */
7000
7001 join_qual:      USING '(' name_list ')'                                 { $$ = (Node *) $3; }
7002                         | ON a_expr                                                             { $$ = $2; }
7003                 ;
7004
7005
7006 relation_expr:
7007                         qualified_name
7008                                 {
7009                                         /* default inheritance */
7010                                         $$ = $1;
7011                                         $$->inhOpt = INH_DEFAULT;
7012                                         $$->alias = NULL;
7013                                 }
7014                         | qualified_name '*'
7015                                 {
7016                                         /* inheritance query */
7017                                         $$ = $1;
7018                                         $$->inhOpt = INH_YES;
7019                                         $$->alias = NULL;
7020                                 }
7021                         | ONLY qualified_name
7022                                 {
7023                                         /* no inheritance */
7024                                         $$ = $2;
7025                                         $$->inhOpt = INH_NO;
7026                                         $$->alias = NULL;
7027                                 }
7028                         | ONLY '(' qualified_name ')'
7029                                 {
7030                                         /* no inheritance, SQL99-style syntax */
7031                                         $$ = $3;
7032                                         $$->inhOpt = INH_NO;
7033                                         $$->alias = NULL;
7034                                 }
7035                 ;
7036
7037
7038 /*
7039  * Given "UPDATE foo set set ...", we have to decide without looking any
7040  * further ahead whether the first "set" is an alias or the UPDATE's SET
7041  * keyword.  Since "set" is allowed as a column name both interpretations
7042  * are feasible.  We resolve the shift/reduce conflict by giving the first
7043  * relation_expr_opt_alias production a higher precedence than the SET token
7044  * has, causing the parser to prefer to reduce, in effect assuming that the
7045  * SET is not an alias.
7046  */
7047 relation_expr_opt_alias: relation_expr                                  %prec UMINUS
7048                                 {
7049                                         $$ = $1;
7050                                 }
7051                         | relation_expr ColId
7052                                 {
7053                                         Alias *alias = makeNode(Alias);
7054                                         alias->aliasname = $2;
7055                                         $1->alias = alias;
7056                                         $$ = $1;
7057                                 }
7058                         | relation_expr AS ColId
7059                                 {
7060                                         Alias *alias = makeNode(Alias);
7061                                         alias->aliasname = $3;
7062                                         $1->alias = alias;
7063                                         $$ = $1;
7064                                 }
7065                 ;
7066
7067
7068 func_table: func_expr                                                           { $$ = $1; }
7069                 ;
7070
7071
7072 where_clause:
7073                         WHERE a_expr                                                    { $$ = $2; }
7074                         | /*EMPTY*/                                                             { $$ = NULL; }
7075                 ;
7076
7077 /* variant for UPDATE and DELETE */
7078 where_or_current_clause:
7079                         WHERE a_expr                                                    { $$ = $2; }
7080                         | WHERE CURRENT_P OF name
7081                                 {
7082                                         CurrentOfExpr *n = makeNode(CurrentOfExpr);
7083                                         /* cvarno is filled in by parse analysis */
7084                                         n->cursor_name = $4;
7085                                         n->cursor_param = 0;
7086                                         $$ = (Node *) n;
7087                                 }
7088                         | WHERE CURRENT_P OF PARAM
7089                                 {
7090                                         CurrentOfExpr *n = makeNode(CurrentOfExpr);
7091                                         /* cvarno is filled in by parse analysis */
7092                                         n->cursor_name = NULL;
7093                                         n->cursor_param = $4;
7094                                         $$ = (Node *) n;
7095                                 }
7096                         | /*EMPTY*/                                                             { $$ = NULL; }
7097                 ;
7098
7099
7100 TableFuncElementList:
7101                         TableFuncElement
7102                                 {
7103                                         $$ = list_make1($1);
7104                                 }
7105                         | TableFuncElementList ',' TableFuncElement
7106                                 {
7107                                         $$ = lappend($1, $3);
7108                                 }
7109                 ;
7110
7111 TableFuncElement:       ColId Typename
7112                                 {
7113                                         ColumnDef *n = makeNode(ColumnDef);
7114                                         n->colname = $1;
7115                                         n->typename = $2;
7116                                         n->constraints = NIL;
7117                                         n->is_local = true;
7118                                         $$ = (Node *)n;
7119                                 }
7120                 ;
7121
7122 /*****************************************************************************
7123  *
7124  *      Type syntax
7125  *              SQL92 introduces a large amount of type-specific syntax.
7126  *              Define individual clauses to handle these cases, and use
7127  *               the generic case to handle regular type-extensible Postgres syntax.
7128  *              - thomas 1997-10-10
7129  *
7130  *****************************************************************************/
7131
7132 Typename:       SimpleTypename opt_array_bounds
7133                                 {
7134                                         $$ = $1;
7135                                         $$->arrayBounds = $2;
7136                                 }
7137                         | SETOF SimpleTypename opt_array_bounds
7138                                 {
7139                                         $$ = $2;
7140                                         $$->arrayBounds = $3;
7141                                         $$->setof = TRUE;
7142                                 }
7143                         /* SQL standard syntax, currently only one-dimensional */
7144                         | SimpleTypename ARRAY '[' Iconst ']'
7145                                 {
7146                                         $$ = $1;
7147                                         $$->arrayBounds = list_make1(makeInteger($4));
7148                                 }
7149                         | SETOF SimpleTypename ARRAY '[' Iconst ']'
7150                                 {
7151                                         $$ = $2;
7152                                         $$->arrayBounds = list_make1(makeInteger($5));
7153                                         $$->setof = TRUE;
7154                                 }
7155                         | SimpleTypename ARRAY
7156                                 {
7157                                         $$ = $1;
7158                                         $$->arrayBounds = list_make1(makeInteger(-1));
7159                                 }
7160                         | SETOF SimpleTypename ARRAY
7161                                 {
7162                                         $$ = $2;
7163                                         $$->arrayBounds = list_make1(makeInteger(-1));
7164                                         $$->setof = TRUE;
7165                                 }
7166                 ;
7167
7168 opt_array_bounds:
7169                         opt_array_bounds '[' ']'
7170                                         {  $$ = lappend($1, makeInteger(-1)); }
7171                         | opt_array_bounds '[' Iconst ']'
7172                                         {  $$ = lappend($1, makeInteger($3)); }
7173                         | /*EMPTY*/
7174                                         {  $$ = NIL; }
7175                 ;
7176
7177 SimpleTypename:
7178                         GenericType                                                             { $$ = $1; }
7179                         | Numeric                                                               { $$ = $1; }
7180                         | Bit                                                                   { $$ = $1; }
7181                         | Character                                                             { $$ = $1; }
7182                         | ConstDatetime                                                 { $$ = $1; }
7183                         | ConstInterval opt_interval
7184                                 {
7185                                         $$ = $1;
7186                                         $$->typmods = $2;
7187                                 }
7188                         | ConstInterval '(' Iconst ')' opt_interval
7189                                 {
7190                                         $$ = $1;
7191                                         if ($5 != NIL)
7192                                         {
7193                                                 if (list_length($5) != 1)
7194                                                         ereport(ERROR,
7195                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
7196                                                                          errmsg("interval precision specified twice"),
7197                                                                          scanner_errposition(@1)));
7198                                                 $$->typmods = lappend($5, makeIntConst($3, @3));
7199                                         }
7200                                         else
7201                                                 $$->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
7202                                                                                                  makeIntConst($3, @3));
7203                                 }
7204                 ;
7205
7206 /* We have a separate ConstTypename to allow defaulting fixed-length
7207  * types such as CHAR() and BIT() to an unspecified length.
7208  * SQL9x requires that these default to a length of one, but this
7209  * makes no sense for constructs like CHAR 'hi' and BIT '0101',
7210  * where there is an obvious better choice to make.
7211  * Note that ConstInterval is not included here since it must
7212  * be pushed up higher in the rules to accomodate the postfix
7213  * options (e.g. INTERVAL '1' YEAR). Likewise, we have to handle
7214  * the generic-type-name case in AExprConst to avoid premature
7215  * reduce/reduce conflicts against function names.
7216  */
7217 ConstTypename:
7218                         Numeric                                                                 { $$ = $1; }
7219                         | ConstBit                                                              { $$ = $1; }
7220                         | ConstCharacter                                                { $$ = $1; }
7221                         | ConstDatetime                                                 { $$ = $1; }
7222                 ;
7223
7224 /*
7225  * GenericType covers all type names that don't have special syntax mandated
7226  * by the standard, including qualified names.  We also allow type modifiers.
7227  * To avoid parsing conflicts against function invocations, the modifiers
7228  * have to be shown as expr_list here, but parse analysis will only accept
7229  * constants for them.
7230  */
7231 GenericType:
7232                         type_function_name opt_type_modifiers
7233                                 {
7234                                         $$ = makeTypeName($1);
7235                                         $$->typmods = $2;
7236                                         $$->location = @1;
7237                                 }
7238                         | type_function_name attrs opt_type_modifiers
7239                                 {
7240                                         $$ = makeTypeNameFromNameList(lcons(makeString($1), $2));
7241                                         $$->typmods = $3;
7242                                         $$->location = @1;
7243                                 }
7244                 ;
7245
7246 opt_type_modifiers: '(' expr_list ')'                           { $$ = $2; }
7247                                         | /* EMPTY */                                   { $$ = NIL; }
7248                 ;
7249
7250 /*
7251  * SQL92 numeric data types
7252  */
7253 Numeric:        INT_P
7254                                 {
7255                                         $$ = SystemTypeName("int4");
7256                                         $$->location = @1;
7257                                 }
7258                         | INTEGER
7259                                 {
7260                                         $$ = SystemTypeName("int4");
7261                                         $$->location = @1;
7262                                 }
7263                         | SMALLINT
7264                                 {
7265                                         $$ = SystemTypeName("int2");
7266                                         $$->location = @1;
7267                                 }
7268                         | BIGINT
7269                                 {
7270                                         $$ = SystemTypeName("int8");
7271                                         $$->location = @1;
7272                                 }
7273                         | REAL
7274                                 {
7275                                         $$ = SystemTypeName("float4");
7276                                         $$->location = @1;
7277                                 }
7278                         | FLOAT_P opt_float
7279                                 {
7280                                         $$ = $2;
7281                                         $$->location = @1;
7282                                 }
7283                         | DOUBLE_P PRECISION
7284                                 {
7285                                         $$ = SystemTypeName("float8");
7286                                         $$->location = @1;
7287                                 }
7288                         | DECIMAL_P opt_type_modifiers
7289                                 {
7290                                         $$ = SystemTypeName("numeric");
7291                                         $$->typmods = $2;
7292                                         $$->location = @1;
7293                                 }
7294                         | DEC opt_type_modifiers
7295                                 {
7296                                         $$ = SystemTypeName("numeric");
7297                                         $$->typmods = $2;
7298                                         $$->location = @1;
7299                                 }
7300                         | NUMERIC opt_type_modifiers
7301                                 {
7302                                         $$ = SystemTypeName("numeric");
7303                                         $$->typmods = $2;
7304                                         $$->location = @1;
7305                                 }
7306                         | BOOLEAN_P
7307                                 {
7308                                         $$ = SystemTypeName("bool");
7309                                         $$->location = @1;
7310                                 }
7311                 ;
7312
7313 opt_float:      '(' Iconst ')'
7314                                 {
7315                                         /*
7316                                          * Check FLOAT() precision limits assuming IEEE floating
7317                                          * types - thomas 1997-09-18
7318                                          */
7319                                         if ($2 < 1)
7320                                                 ereport(ERROR,
7321                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7322                                                                  errmsg("precision for type float must be at least 1 bit"),
7323                                                                  scanner_errposition(@2)));
7324                                         else if ($2 <= 24)
7325                                                 $$ = SystemTypeName("float4");
7326                                         else if ($2 <= 53)
7327                                                 $$ = SystemTypeName("float8");
7328                                         else
7329                                                 ereport(ERROR,
7330                                                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
7331                                                                  errmsg("precision for type float must be less than 54 bits"),
7332                                                                  scanner_errposition(@2)));
7333                                 }
7334                         | /*EMPTY*/
7335                                 {
7336                                         $$ = SystemTypeName("float8");
7337                                 }
7338                 ;
7339
7340 /*
7341  * SQL92 bit-field data types
7342  * The following implements BIT() and BIT VARYING().
7343  */
7344 Bit:            BitWithLength
7345                                 {
7346                                         $$ = $1;
7347                                 }
7348                         | BitWithoutLength
7349                                 {
7350                                         $$ = $1;
7351                                 }
7352                 ;
7353
7354 /* ConstBit is like Bit except "BIT" defaults to unspecified length */
7355 /* See notes for ConstCharacter, which addresses same issue for "CHAR" */
7356 ConstBit:       BitWithLength
7357                                 {
7358                                         $$ = $1;
7359                                 }
7360                         | BitWithoutLength
7361                                 {
7362                                         $$ = $1;
7363                                         $$->typmods = NIL;
7364                                 }
7365                 ;
7366
7367 BitWithLength:
7368                         BIT opt_varying '(' expr_list ')'
7369                                 {
7370                                         char *typname;
7371
7372                                         typname = $2 ? "varbit" : "bit";
7373                                         $$ = SystemTypeName(typname);
7374                                         $$->typmods = $4;
7375                                         $$->location = @1;
7376                                 }
7377                 ;
7378
7379 BitWithoutLength:
7380                         BIT opt_varying
7381                                 {
7382                                         /* bit defaults to bit(1), varbit to no limit */
7383                                         if ($2)
7384                                         {
7385                                                 $$ = SystemTypeName("varbit");
7386                                         }
7387                                         else
7388                                         {
7389                                                 $$ = SystemTypeName("bit");
7390                                                 $$->typmods = list_make1(makeIntConst(1, -1));
7391                                         }
7392                                         $$->location = @1;
7393                                 }
7394                 ;
7395
7396
7397 /*
7398  * SQL92 character data types
7399  * The following implements CHAR() and VARCHAR().
7400  */
7401 Character:  CharacterWithLength
7402                                 {
7403                                         $$ = $1;
7404                                 }
7405                         | CharacterWithoutLength
7406                                 {
7407                                         $$ = $1;
7408                                 }
7409                 ;
7410
7411 ConstCharacter:  CharacterWithLength
7412                                 {
7413                                         $$ = $1;
7414                                 }
7415                         | CharacterWithoutLength
7416                                 {
7417                                         /* Length was not specified so allow to be unrestricted.
7418                                          * This handles problems with fixed-length (bpchar) strings
7419                                          * which in column definitions must default to a length
7420                                          * of one, but should not be constrained if the length
7421                                          * was not specified.
7422                                          */
7423                                         $$ = $1;
7424                                         $$->typmods = NIL;
7425                                 }
7426                 ;
7427
7428 CharacterWithLength:  character '(' Iconst ')' opt_charset
7429                                 {
7430                                         if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
7431                                         {
7432                                                 char *type;
7433
7434                                                 type = palloc(strlen($1) + 1 + strlen($5) + 1);
7435                                                 strcpy(type, $1);
7436                                                 strcat(type, "_");
7437                                                 strcat(type, $5);
7438                                                 $1 = type;
7439                                         }
7440
7441                                         $$ = SystemTypeName($1);
7442                                         $$->typmods = list_make1(makeIntConst($3, @3));
7443                                         $$->location = @1;
7444                                 }
7445                 ;
7446
7447 CharacterWithoutLength:  character opt_charset
7448                                 {
7449                                         if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
7450                                         {
7451                                                 char *type;
7452
7453                                                 type = palloc(strlen($1) + 1 + strlen($2) + 1);
7454                                                 strcpy(type, $1);
7455                                                 strcat(type, "_");
7456                                                 strcat(type, $2);
7457                                                 $1 = type;
7458                                         }
7459
7460                                         $$ = SystemTypeName($1);
7461
7462                                         /* char defaults to char(1), varchar to no limit */
7463                                         if (strcmp($1, "bpchar") == 0)
7464                                                 $$->typmods = list_make1(makeIntConst(1, -1));
7465
7466                                         $$->location = @1;
7467                                 }
7468                 ;
7469
7470 character:      CHARACTER opt_varying
7471                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
7472                         | CHAR_P opt_varying
7473                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
7474                         | VARCHAR
7475                                                                                 { $$ = "varchar"; }
7476                         | NATIONAL CHARACTER opt_varying
7477                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
7478                         | NATIONAL CHAR_P opt_varying
7479                                                                                 { $$ = $3 ? "varchar": "bpchar"; }
7480                         | NCHAR opt_varying
7481                                                                                 { $$ = $2 ? "varchar": "bpchar"; }
7482                 ;
7483
7484 opt_varying:
7485                         VARYING                                                                 { $$ = TRUE; }
7486                         | /*EMPTY*/                                                             { $$ = FALSE; }
7487                 ;
7488
7489 opt_charset:
7490                         CHARACTER SET ColId                                             { $$ = $3; }
7491                         | /*EMPTY*/                                                             { $$ = NULL; }
7492                 ;
7493
7494 /*
7495  * SQL92 date/time types
7496  */
7497 ConstDatetime:
7498                         TIMESTAMP '(' Iconst ')' opt_timezone
7499                                 {
7500                                         if ($5)
7501                                                 $$ = SystemTypeName("timestamptz");
7502                                         else
7503                                                 $$ = SystemTypeName("timestamp");
7504                                         $$->typmods = list_make1(makeIntConst($3, @3));
7505                                         $$->location = @1;
7506                                 }
7507                         | TIMESTAMP opt_timezone
7508                                 {
7509                                         if ($2)
7510                                                 $$ = SystemTypeName("timestamptz");
7511                                         else
7512                                                 $$ = SystemTypeName("timestamp");
7513                                         $$->location = @1;
7514                                 }
7515                         | TIME '(' Iconst ')' opt_timezone
7516                                 {
7517                                         if ($5)
7518                                                 $$ = SystemTypeName("timetz");
7519                                         else
7520                                                 $$ = SystemTypeName("time");
7521                                         $$->typmods = list_make1(makeIntConst($3, @3));
7522                                         $$->location = @1;
7523                                 }
7524                         | TIME opt_timezone
7525                                 {
7526                                         if ($2)
7527                                                 $$ = SystemTypeName("timetz");
7528                                         else
7529                                                 $$ = SystemTypeName("time");
7530                                         $$->location = @1;
7531                                 }
7532                 ;
7533
7534 ConstInterval:
7535                         INTERVAL
7536                                 {
7537                                         $$ = SystemTypeName("interval");
7538                                         $$->location = @1;
7539                                 }
7540                 ;
7541
7542 opt_timezone:
7543                         WITH_TIME ZONE                                                  { $$ = TRUE; }
7544                         | WITHOUT TIME ZONE                                             { $$ = FALSE; }
7545                         | /*EMPTY*/                                                             { $$ = FALSE; }
7546                 ;
7547
7548 opt_interval:
7549                         YEAR_P
7550                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR), @1)); }
7551                         | MONTH_P
7552                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MONTH), @1)); }
7553                         | DAY_P
7554                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY), @1)); }
7555                         | HOUR_P
7556                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR), @1)); }
7557                         | MINUTE_P
7558                                 { $$ = list_make1(makeIntConst(INTERVAL_MASK(MINUTE), @1)); }
7559                         | interval_second
7560                                 { $$ = $1; }
7561                         | YEAR_P TO MONTH_P
7562                                 {
7563                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(YEAR) |
7564                                                                                                  INTERVAL_MASK(MONTH), @1));
7565                                 }
7566                         | DAY_P TO HOUR_P
7567                                 {
7568                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
7569                                                                                                  INTERVAL_MASK(HOUR), @1));
7570                                 }
7571                         | DAY_P TO MINUTE_P
7572                                 {
7573                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(DAY) |
7574                                                                                                  INTERVAL_MASK(HOUR) |
7575                                                                                                  INTERVAL_MASK(MINUTE), @1));
7576                                 }
7577                         | DAY_P TO interval_second
7578                                 {
7579                                         $$ = $3;
7580                                         linitial($$) = makeIntConst(INTERVAL_MASK(DAY) |
7581                                                                                                 INTERVAL_MASK(HOUR) |
7582                                                                                                 INTERVAL_MASK(MINUTE) |
7583                                                                                                 INTERVAL_MASK(SECOND), @1);
7584                                 }
7585                         | HOUR_P TO MINUTE_P
7586                                 {
7587                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(HOUR) |
7588                                                                                                  INTERVAL_MASK(MINUTE), @1));
7589                                 }
7590                         | HOUR_P TO interval_second
7591                                 {
7592                                         $$ = $3;
7593                                         linitial($$) = makeIntConst(INTERVAL_MASK(HOUR) |
7594                                                                                                 INTERVAL_MASK(MINUTE) |
7595                                                                                                 INTERVAL_MASK(SECOND), @1);
7596                                 }
7597                         | MINUTE_P TO interval_second
7598                                 {
7599                                         $$ = $3;
7600                                         linitial($$) = makeIntConst(INTERVAL_MASK(MINUTE) |
7601                                                                                                 INTERVAL_MASK(SECOND), @1);
7602                                 }
7603                         | /*EMPTY*/
7604                                 { $$ = NIL; }
7605                 ;
7606
7607 interval_second:
7608                         SECOND_P
7609                                 {
7610                                         $$ = list_make1(makeIntConst(INTERVAL_MASK(SECOND), @1));
7611                                 }
7612                         | SECOND_P '(' Iconst ')'
7613                                 {
7614                                         $$ = list_make2(makeIntConst(INTERVAL_MASK(SECOND), @1),
7615                                                                         makeIntConst($3, @3));
7616                                 }
7617                 ;
7618
7619
7620 /*****************************************************************************
7621  *
7622  *      expression grammar
7623  *
7624  *****************************************************************************/
7625
7626 /*
7627  * General expressions
7628  * This is the heart of the expression syntax.
7629  *
7630  * We have two expression types: a_expr is the unrestricted kind, and
7631  * b_expr is a subset that must be used in some places to avoid shift/reduce
7632  * conflicts.  For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
7633  * because that use of AND conflicts with AND as a boolean operator.  So,
7634  * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
7635  *
7636  * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
7637  * always be used by surrounding it with parens.
7638  *
7639  * c_expr is all the productions that are common to a_expr and b_expr;
7640  * it's factored out just to eliminate redundant coding.
7641  */
7642 a_expr:         c_expr                                                                  { $$ = $1; }
7643                         | a_expr TYPECAST Typename
7644                                         { $$ = makeTypeCast($1, $3, @2); }
7645                         | a_expr AT TIME ZONE a_expr
7646                                 {
7647                                         FuncCall *n = makeNode(FuncCall);
7648                                         n->funcname = SystemFuncName("timezone");
7649                                         n->args = list_make2($5, $1);
7650                                         n->agg_star = FALSE;
7651                                         n->agg_distinct = FALSE;
7652                                         n->func_variadic = FALSE;
7653                                         n->location = @2;
7654                                         $$ = (Node *) n;
7655                                 }
7656                 /*
7657                  * These operators must be called out explicitly in order to make use
7658                  * of yacc/bison's automatic operator-precedence handling.  All other
7659                  * operator names are handled by the generic productions using "Op",
7660                  * below; and all those operators will have the same precedence.
7661                  *
7662                  * If you add more explicitly-known operators, be sure to add them
7663                  * also to b_expr and to the MathOp list above.
7664                  */
7665                         | '+' a_expr                                    %prec UMINUS
7666                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
7667                         | '-' a_expr                                    %prec UMINUS
7668                                 { $$ = doNegate($2, @1); }
7669                         | a_expr '+' a_expr
7670                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", $1, $3, @2); }
7671                         | a_expr '-' a_expr
7672                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "-", $1, $3, @2); }
7673                         | a_expr '*' a_expr
7674                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", $1, $3, @2); }
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
7688                         | a_expr qual_Op a_expr                         %prec Op
7689                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
7690                         | qual_Op a_expr                                        %prec Op
7691                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
7692                         | a_expr qual_Op                                        %prec POSTFIXOP
7693                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
7694
7695                         | a_expr AND a_expr
7696                                 { $$ = (Node *) makeA_Expr(AEXPR_AND, NIL, $1, $3, @2); }
7697                         | a_expr OR a_expr
7698                                 { $$ = (Node *) makeA_Expr(AEXPR_OR, NIL, $1, $3, @2); }
7699                         | NOT a_expr
7700                                 { $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL, $2, @1); }
7701
7702                         | a_expr LIKE a_expr
7703                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~", $1, $3, @2); }
7704                         | a_expr LIKE a_expr ESCAPE a_expr
7705                                 {
7706                                         FuncCall *n = makeNode(FuncCall);
7707                                         n->funcname = SystemFuncName("like_escape");
7708                                         n->args = list_make2($3, $5);
7709                                         n->agg_star = FALSE;
7710                                         n->agg_distinct = FALSE;
7711                                         n->func_variadic = FALSE;
7712                                         n->location = @4;
7713                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~", $1, (Node *) n, @2);
7714                                 }
7715                         | a_expr NOT LIKE a_expr
7716                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~", $1, $4, @2); }
7717                         | a_expr NOT LIKE a_expr ESCAPE a_expr
7718                                 {
7719                                         FuncCall *n = makeNode(FuncCall);
7720                                         n->funcname = SystemFuncName("like_escape");
7721                                         n->args = list_make2($4, $6);
7722                                         n->agg_star = FALSE;
7723                                         n->agg_distinct = FALSE;
7724                                         n->func_variadic = FALSE;
7725                                         n->location = @5;
7726                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~", $1, (Node *) n, @2);
7727                                 }
7728                         | a_expr ILIKE a_expr
7729                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~*", $1, $3, @2); }
7730                         | a_expr ILIKE a_expr ESCAPE a_expr
7731                                 {
7732                                         FuncCall *n = makeNode(FuncCall);
7733                                         n->funcname = SystemFuncName("like_escape");
7734                                         n->args = list_make2($3, $5);
7735                                         n->agg_star = FALSE;
7736                                         n->agg_distinct = FALSE;
7737                                         n->func_variadic = FALSE;
7738                                         n->location = @4;
7739                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~~*", $1, (Node *) n, @2);
7740                                 }
7741                         | a_expr NOT ILIKE a_expr
7742                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~*", $1, $4, @2); }
7743                         | a_expr NOT ILIKE a_expr ESCAPE a_expr
7744                                 {
7745                                         FuncCall *n = makeNode(FuncCall);
7746                                         n->funcname = SystemFuncName("like_escape");
7747                                         n->args = list_make2($4, $6);
7748                                         n->agg_star = FALSE;
7749                                         n->agg_distinct = FALSE;
7750                                         n->func_variadic = FALSE;
7751                                         n->location = @5;
7752                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~~*", $1, (Node *) n, @2);
7753                                 }
7754
7755                         | a_expr SIMILAR TO a_expr                              %prec SIMILAR
7756                                 {
7757                                         FuncCall *n = makeNode(FuncCall);
7758                                         n->funcname = SystemFuncName("similar_escape");
7759                                         n->args = list_make2($4, makeNullAConst(-1));
7760                                         n->agg_star = FALSE;
7761                                         n->agg_distinct = FALSE;
7762                                         n->func_variadic = FALSE;
7763                                         n->location = @2;
7764                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~", $1, (Node *) n, @2);
7765                                 }
7766                         | a_expr SIMILAR TO a_expr ESCAPE a_expr
7767                                 {
7768                                         FuncCall *n = makeNode(FuncCall);
7769                                         n->funcname = SystemFuncName("similar_escape");
7770                                         n->args = list_make2($4, $6);
7771                                         n->agg_star = FALSE;
7772                                         n->agg_distinct = FALSE;
7773                                         n->func_variadic = FALSE;
7774                                         n->location = @5;
7775                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "~", $1, (Node *) n, @2);
7776                                 }
7777                         | a_expr NOT SIMILAR TO a_expr                  %prec SIMILAR
7778                                 {
7779                                         FuncCall *n = makeNode(FuncCall);
7780                                         n->funcname = SystemFuncName("similar_escape");
7781                                         n->args = list_make2($5, makeNullAConst(-1));
7782                                         n->agg_star = FALSE;
7783                                         n->agg_distinct = FALSE;
7784                                         n->func_variadic = FALSE;
7785                                         n->location = @5;
7786                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~", $1, (Node *) n, @2);
7787                                 }
7788                         | a_expr NOT SIMILAR TO a_expr ESCAPE a_expr
7789                                 {
7790                                         FuncCall *n = makeNode(FuncCall);
7791                                         n->funcname = SystemFuncName("similar_escape");
7792                                         n->args = list_make2($5, $7);
7793                                         n->agg_star = FALSE;
7794                                         n->agg_distinct = FALSE;
7795                                         n->func_variadic = FALSE;
7796                                         n->location = @6;
7797                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "!~", $1, (Node *) n, @2);
7798                                 }
7799
7800                         /* NullTest clause
7801                          * Define SQL92-style Null test clause.
7802                          * Allow two forms described in the standard:
7803                          *      a IS NULL
7804                          *      a IS NOT NULL
7805                          * Allow two SQL extensions
7806                          *      a ISNULL
7807                          *      a NOTNULL
7808                          */
7809                         | a_expr IS NULL_P
7810                                 {
7811                                         NullTest *n = makeNode(NullTest);
7812                                         n->arg = (Expr *) $1;
7813                                         n->nulltesttype = IS_NULL;
7814                                         $$ = (Node *)n;
7815                                 }
7816                         | a_expr ISNULL
7817                                 {
7818                                         NullTest *n = makeNode(NullTest);
7819                                         n->arg = (Expr *) $1;
7820                                         n->nulltesttype = IS_NULL;
7821                                         $$ = (Node *)n;
7822                                 }
7823                         | a_expr IS NOT NULL_P
7824                                 {
7825                                         NullTest *n = makeNode(NullTest);
7826                                         n->arg = (Expr *) $1;
7827                                         n->nulltesttype = IS_NOT_NULL;
7828                                         $$ = (Node *)n;
7829                                 }
7830                         | a_expr NOTNULL
7831                                 {
7832                                         NullTest *n = makeNode(NullTest);
7833                                         n->arg = (Expr *) $1;
7834                                         n->nulltesttype = IS_NOT_NULL;
7835                                         $$ = (Node *)n;
7836                                 }
7837                         | row OVERLAPS row
7838                                 {
7839                                         $$ = (Node *)makeOverlaps($1, $3, @2);
7840                                 }
7841                         | a_expr IS TRUE_P
7842                                 {
7843                                         BooleanTest *b = makeNode(BooleanTest);
7844                                         b->arg = (Expr *) $1;
7845                                         b->booltesttype = IS_TRUE;
7846                                         $$ = (Node *)b;
7847                                 }
7848                         | a_expr IS NOT TRUE_P
7849                                 {
7850                                         BooleanTest *b = makeNode(BooleanTest);
7851                                         b->arg = (Expr *) $1;
7852                                         b->booltesttype = IS_NOT_TRUE;
7853                                         $$ = (Node *)b;
7854                                 }
7855                         | a_expr IS FALSE_P
7856                                 {
7857                                         BooleanTest *b = makeNode(BooleanTest);
7858                                         b->arg = (Expr *) $1;
7859                                         b->booltesttype = IS_FALSE;
7860                                         $$ = (Node *)b;
7861                                 }
7862                         | a_expr IS NOT FALSE_P
7863                                 {
7864                                         BooleanTest *b = makeNode(BooleanTest);
7865                                         b->arg = (Expr *) $1;
7866                                         b->booltesttype = IS_NOT_FALSE;
7867                                         $$ = (Node *)b;
7868                                 }
7869                         | a_expr IS UNKNOWN
7870                                 {
7871                                         BooleanTest *b = makeNode(BooleanTest);
7872                                         b->arg = (Expr *) $1;
7873                                         b->booltesttype = IS_UNKNOWN;
7874                                         $$ = (Node *)b;
7875                                 }
7876                         | a_expr IS NOT UNKNOWN
7877                                 {
7878                                         BooleanTest *b = makeNode(BooleanTest);
7879                                         b->arg = (Expr *) $1;
7880                                         b->booltesttype = IS_NOT_UNKNOWN;
7881                                         $$ = (Node *)b;
7882                                 }
7883                         | a_expr IS DISTINCT FROM a_expr                        %prec IS
7884                                 {
7885                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
7886                                 }
7887                         | a_expr IS NOT DISTINCT FROM a_expr            %prec IS
7888                                 {
7889                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
7890                                                                         (Node *) makeSimpleA_Expr(AEXPR_DISTINCT,
7891                                                                                                                           "=", $1, $6, @2),
7892                                                                                          @2);
7893
7894                                 }
7895                         | a_expr IS OF '(' type_list ')'                        %prec IS
7896                                 {
7897                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
7898                                 }
7899                         | a_expr IS NOT OF '(' type_list ')'            %prec IS
7900                                 {
7901                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
7902                                 }
7903                         | a_expr BETWEEN opt_asymmetric b_expr AND b_expr               %prec BETWEEN
7904                                 {
7905                                         $$ = (Node *) makeA_Expr(AEXPR_AND, NIL,
7906                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $4, @2),
7907                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $6, @2),
7908                                                                                          @2);
7909                                 }
7910                         | a_expr NOT BETWEEN opt_asymmetric b_expr AND b_expr   %prec BETWEEN
7911                                 {
7912                                         $$ = (Node *) makeA_Expr(AEXPR_OR, NIL,
7913                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $5, @2),
7914                                                 (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $7, @2),
7915                                                                                          @2);
7916                                 }
7917                         | a_expr BETWEEN SYMMETRIC b_expr AND b_expr                    %prec BETWEEN
7918                                 {
7919                                         $$ = (Node *) makeA_Expr(AEXPR_OR, NIL,
7920                                                 (Node *) makeA_Expr(AEXPR_AND, NIL,
7921                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $4, @2),
7922                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $6, @2),
7923                                                                                         @2),
7924                                                 (Node *) makeA_Expr(AEXPR_AND, NIL,
7925                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">=", $1, $6, @2),
7926                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<=", $1, $4, @2),
7927                                                                                         @2),
7928                                                                                          @2);
7929                                 }
7930                         | a_expr NOT BETWEEN SYMMETRIC b_expr AND b_expr                %prec BETWEEN
7931                                 {
7932                                         $$ = (Node *) makeA_Expr(AEXPR_AND, NIL,
7933                                                 (Node *) makeA_Expr(AEXPR_OR, NIL,
7934                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $5, @2),
7935                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $7, @2),
7936                                                                                         @2),
7937                                                 (Node *) makeA_Expr(AEXPR_OR, NIL,
7938                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, "<", $1, $7, @2),
7939                                                     (Node *) makeSimpleA_Expr(AEXPR_OP, ">", $1, $5, @2),
7940                                                                                         @2),
7941                                                                                          @2);
7942                                 }
7943                         | a_expr IN_P in_expr
7944                                 {
7945                                         /* in_expr returns a SubLink or a list of a_exprs */
7946                                         if (IsA($3, SubLink))
7947                                         {
7948                                                 /* generate foo = ANY (subquery) */
7949                                                 SubLink *n = (SubLink *) $3;
7950                                                 n->subLinkType = ANY_SUBLINK;
7951                                                 n->testexpr = $1;
7952                                                 n->operName = list_make1(makeString("="));
7953                                                 n->location = @2;
7954                                                 $$ = (Node *)n;
7955                                         }
7956                                         else
7957                                         {
7958                                                 /* generate scalar IN expression */
7959                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "=", $1, $3, @2);
7960                                         }
7961                                 }
7962                         | a_expr NOT IN_P in_expr
7963                                 {
7964                                         /* in_expr returns a SubLink or a list of a_exprs */
7965                                         if (IsA($4, SubLink))
7966                                         {
7967                                                 /* generate NOT (foo = ANY (subquery)) */
7968                                                 /* Make an = ANY node */
7969                                                 SubLink *n = (SubLink *) $4;
7970                                                 n->subLinkType = ANY_SUBLINK;
7971                                                 n->testexpr = $1;
7972                                                 n->operName = list_make1(makeString("="));
7973                                                 n->location = @3;
7974                                                 /* Stick a NOT on top */
7975                                                 $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL, (Node *) n, @2);
7976                                         }
7977                                         else
7978                                         {
7979                                                 /* generate scalar NOT IN expression */
7980                                                 $$ = (Node *) makeSimpleA_Expr(AEXPR_IN, "<>", $1, $4, @2);
7981                                         }
7982                                 }
7983                         | a_expr subquery_Op sub_type select_with_parens        %prec Op
7984                                 {
7985                                         SubLink *n = makeNode(SubLink);
7986                                         n->subLinkType = $3;
7987                                         n->testexpr = $1;
7988                                         n->operName = $2;
7989                                         n->subselect = $4;
7990                                         n->location = @2;
7991                                         $$ = (Node *)n;
7992                                 }
7993                         | a_expr subquery_Op sub_type '(' a_expr ')'            %prec Op
7994                                 {
7995                                         if ($3 == ANY_SUBLINK)
7996                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ANY, $2, $1, $5, @2);
7997                                         else
7998                                                 $$ = (Node *) makeA_Expr(AEXPR_OP_ALL, $2, $1, $5, @2);
7999                                 }
8000                         | UNIQUE select_with_parens
8001                                 {
8002                                         /* Not sure how to get rid of the parentheses
8003                                          * but there are lots of shift/reduce errors without them.
8004                                          *
8005                                          * Should be able to implement this by plopping the entire
8006                                          * select into a node, then transforming the target expressions
8007                                          * from whatever they are into count(*), and testing the
8008                                          * entire result equal to one.
8009                                          * But, will probably implement a separate node in the executor.
8010                                          */
8011                                         ereport(ERROR,
8012                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
8013                                                          errmsg("UNIQUE predicate is not yet implemented"),
8014                                                          scanner_errposition(@1)));
8015                                 }
8016                         | a_expr IS DOCUMENT_P                                  %prec IS
8017                                 {
8018                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8019                                                                          list_make1($1), @2);
8020                                 }
8021                         | a_expr IS NOT DOCUMENT_P                              %prec IS
8022                                 {
8023                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
8024                                                                                          makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8025                                                                                                                  list_make1($1), @2),
8026                                                                                          @2);
8027                                 }
8028                 ;
8029
8030 /*
8031  * Restricted expressions
8032  *
8033  * b_expr is a subset of the complete expression syntax defined by a_expr.
8034  *
8035  * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
8036  * cause trouble in the places where b_expr is used.  For simplicity, we
8037  * just eliminate all the boolean-keyword-operator productions from b_expr.
8038  */
8039 b_expr:         c_expr
8040                                 { $$ = $1; }
8041                         | b_expr TYPECAST Typename
8042                                 { $$ = makeTypeCast($1, $3, @2); }
8043                         | '+' b_expr                                    %prec UMINUS
8044                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", NULL, $2, @1); }
8045                         | '-' b_expr                                    %prec UMINUS
8046                                 { $$ = doNegate($2, @1); }
8047                         | b_expr '+' b_expr
8048                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "+", $1, $3, @2); }
8049                         | b_expr '-' b_expr
8050                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "-", $1, $3, @2); }
8051                         | b_expr '*' b_expr
8052                                 { $$ = (Node *) makeSimpleA_Expr(AEXPR_OP, "*", $1, $3, @2); }
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 qual_Op b_expr                         %prec Op
8066                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, $3, @2); }
8067                         | qual_Op b_expr                                        %prec Op
8068                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $1, NULL, $2, @1); }
8069                         | b_expr qual_Op                                        %prec POSTFIXOP
8070                                 { $$ = (Node *) makeA_Expr(AEXPR_OP, $2, $1, NULL, @2); }
8071                         | b_expr IS DISTINCT FROM b_expr                %prec IS
8072                                 {
8073                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $5, @2);
8074                                 }
8075                         | b_expr IS NOT DISTINCT FROM b_expr    %prec IS
8076                                 {
8077                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL,
8078                                                 NULL, (Node *) makeSimpleA_Expr(AEXPR_DISTINCT, "=", $1, $6, @2), @2);
8079                                 }
8080                         | b_expr IS OF '(' type_list ')'                %prec IS
8081                                 {
8082                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "=", $1, (Node *) $5, @2);
8083                                 }
8084                         | b_expr IS NOT OF '(' type_list ')'    %prec IS
8085                                 {
8086                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_OF, "<>", $1, (Node *) $6, @2);
8087                                 }
8088                         | b_expr IS DOCUMENT_P                                  %prec IS
8089                                 {
8090                                         $$ = makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8091                                                                          list_make1($1), @2);
8092                                 }
8093                         | b_expr IS NOT DOCUMENT_P                              %prec IS
8094                                 {
8095                                         $$ = (Node *) makeA_Expr(AEXPR_NOT, NIL, NULL,
8096                                                                                          makeXmlExpr(IS_DOCUMENT, NULL, NIL,
8097                                                                                                                  list_make1($1), @2),
8098                                                                                          @2);
8099                                 }
8100                 ;
8101
8102 /*
8103  * Productions that can be used in both a_expr and b_expr.
8104  *
8105  * Note: productions that refer recursively to a_expr or b_expr mostly
8106  * cannot appear here.  However, it's OK to refer to a_exprs that occur
8107  * inside parentheses, such as function arguments; that cannot introduce
8108  * ambiguity to the b_expr syntax.
8109  */
8110 c_expr:         columnref                                                               { $$ = $1; }
8111                         | AexprConst                                                    { $$ = $1; }
8112                         | PARAM opt_indirection
8113                                 {
8114                                         ParamRef *p = makeNode(ParamRef);
8115                                         p->number = $1;
8116                                         p->location = @1;
8117                                         if ($2)
8118                                         {
8119                                                 A_Indirection *n = makeNode(A_Indirection);
8120                                                 n->arg = (Node *) p;
8121                                                 n->indirection = check_indirection($2);
8122                                                 $$ = (Node *) n;
8123                                         }
8124                                         else
8125                                                 $$ = (Node *) p;
8126                                 }
8127                         | '(' a_expr ')' opt_indirection
8128                                 {
8129                                         if ($4)
8130                                         {
8131                                                 A_Indirection *n = makeNode(A_Indirection);
8132                                                 n->arg = $2;
8133                                                 n->indirection = check_indirection($4);
8134                                                 $$ = (Node *)n;
8135                                         }
8136                                         else
8137                                                 $$ = $2;
8138                                 }
8139                         | case_expr
8140                                 { $$ = $1; }
8141                         | func_expr
8142                                 { $$ = $1; }
8143                         | select_with_parens                    %prec UMINUS
8144                                 {
8145                                         SubLink *n = makeNode(SubLink);
8146                                         n->subLinkType = EXPR_SUBLINK;
8147                                         n->testexpr = NULL;
8148                                         n->operName = NIL;
8149                                         n->subselect = $1;
8150                                         n->location = @1;
8151                                         $$ = (Node *)n;
8152                                 }
8153                         | EXISTS select_with_parens
8154                                 {
8155                                         SubLink *n = makeNode(SubLink);
8156                                         n->subLinkType = EXISTS_SUBLINK;
8157                                         n->testexpr = NULL;
8158                                         n->operName = NIL;
8159                                         n->subselect = $2;
8160                                         n->location = @1;
8161                                         $$ = (Node *)n;
8162                                 }
8163                         | ARRAY select_with_parens
8164                                 {
8165                                         SubLink *n = makeNode(SubLink);
8166                                         n->subLinkType = ARRAY_SUBLINK;
8167                                         n->testexpr = NULL;
8168                                         n->operName = NIL;
8169                                         n->subselect = $2;
8170                                         n->location = @1;
8171                                         $$ = (Node *)n;
8172                                 }
8173                         | ARRAY array_expr
8174                                 {
8175                                         A_ArrayExpr *n = (A_ArrayExpr *) $2;
8176                                         Assert(IsA(n, A_ArrayExpr));
8177                                         /* point outermost A_ArrayExpr to the ARRAY keyword */
8178                                         n->location = @1;
8179                                         $$ = (Node *)n;
8180                                 }
8181                         | row
8182                                 {
8183                                         RowExpr *r = makeNode(RowExpr);
8184                                         r->args = $1;
8185                                         r->row_typeid = InvalidOid;     /* not analyzed yet */
8186                                         r->location = @1;
8187                                         $$ = (Node *)r;
8188                                 }
8189                 ;
8190
8191 /*
8192  * func_expr is split out from c_expr just so that we have a classification
8193  * for "everything that is a function call or looks like one".  This isn't
8194  * very important, but it saves us having to document which variants are
8195  * legal in the backwards-compatible functional-index syntax for CREATE INDEX.
8196  * (Note that many of the special SQL functions wouldn't actually make any
8197  * sense as functional index entries, but we ignore that consideration here.)
8198  */
8199 func_expr:      func_name '(' ')'
8200                                 {
8201                                         FuncCall *n = makeNode(FuncCall);
8202                                         n->funcname = $1;
8203                                         n->args = NIL;
8204                                         n->agg_star = FALSE;
8205                                         n->agg_distinct = FALSE;
8206                                         n->func_variadic = FALSE;
8207                                         n->location = @1;
8208                                         $$ = (Node *)n;
8209                                 }
8210                         | func_name '(' expr_list ')'
8211                                 {
8212                                         FuncCall *n = makeNode(FuncCall);
8213                                         n->funcname = $1;
8214                                         n->args = $3;
8215                                         n->agg_star = FALSE;
8216                                         n->agg_distinct = FALSE;
8217                                         n->func_variadic = FALSE;
8218                                         n->location = @1;
8219                                         $$ = (Node *)n;
8220                                 }
8221                         | func_name '(' VARIADIC a_expr ')'
8222                                 {
8223                                         FuncCall *n = makeNode(FuncCall);
8224                                         n->funcname = $1;
8225                                         n->args = list_make1($4);
8226                                         n->agg_star = FALSE;
8227                                         n->agg_distinct = FALSE;
8228                                         n->func_variadic = TRUE;
8229                                         n->location = @1;
8230                                         $$ = (Node *)n;
8231                                 }
8232                         | func_name '(' expr_list ',' VARIADIC a_expr ')'
8233                                 {
8234                                         FuncCall *n = makeNode(FuncCall);
8235                                         n->funcname = $1;
8236                                         n->args = lappend($3, $6);
8237                                         n->agg_star = FALSE;
8238                                         n->agg_distinct = FALSE;
8239                                         n->func_variadic = TRUE;
8240                                         n->location = @1;
8241                                         $$ = (Node *)n;
8242                                 }
8243                         | func_name '(' ALL expr_list ')'
8244                                 {
8245                                         FuncCall *n = makeNode(FuncCall);
8246                                         n->funcname = $1;
8247                                         n->args = $4;
8248                                         n->agg_star = FALSE;
8249                                         n->agg_distinct = FALSE;
8250                                         /* Ideally we'd mark the FuncCall node to indicate
8251                                          * "must be an aggregate", but there's no provision
8252                                          * for that in FuncCall at the moment.
8253                                          */
8254                                         n->func_variadic = FALSE;
8255                                         n->location = @1;
8256                                         $$ = (Node *)n;
8257                                 }
8258                         | func_name '(' DISTINCT expr_list ')'
8259                                 {
8260                                         FuncCall *n = makeNode(FuncCall);
8261                                         n->funcname = $1;
8262                                         n->args = $4;
8263                                         n->agg_star = FALSE;
8264                                         n->agg_distinct = TRUE;
8265                                         n->func_variadic = FALSE;
8266                                         n->location = @1;
8267                                         $$ = (Node *)n;
8268                                 }
8269                         | func_name '(' '*' ')'
8270                                 {
8271                                         /*
8272                                          * We consider AGGREGATE(*) to invoke a parameterless
8273                                          * aggregate.  This does the right thing for COUNT(*),
8274                                          * and there are no other aggregates in SQL92 that accept
8275                                          * '*' as parameter.
8276                                          *
8277                                          * The FuncCall node is also marked agg_star = true,
8278                                          * so that later processing can detect what the argument
8279                                          * really was.
8280                                          */
8281                                         FuncCall *n = makeNode(FuncCall);
8282                                         n->funcname = $1;
8283                                         n->args = NIL;
8284                                         n->agg_star = TRUE;
8285                                         n->agg_distinct = FALSE;
8286                                         n->func_variadic = FALSE;
8287                                         n->location = @1;
8288                                         $$ = (Node *)n;
8289                                 }
8290                         | CURRENT_DATE
8291                                 {
8292                                         /*
8293                                          * Translate as "'now'::text::date".
8294                                          *
8295                                          * We cannot use "'now'::date" because coerce_type() will
8296                                          * immediately reduce that to a constant representing
8297                                          * today's date.  We need to delay the conversion until
8298                                          * runtime, else the wrong things will happen when
8299                                          * CURRENT_DATE is used in a column default value or rule.
8300                                          *
8301                                          * This could be simplified if we had a way to generate
8302                                          * an expression tree representing runtime application
8303                                          * of type-input conversion functions.  (As of PG 7.3
8304                                          * that is actually possible, but not clear that we want
8305                                          * to rely on it.)
8306                                          */
8307                                         Node *n;
8308                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8309                                         $$ = makeTypeCast(n, SystemTypeName("date"), -1);
8310                                 }
8311                         | CURRENT_TIME
8312                                 {
8313                                         /*
8314                                          * Translate as "'now'::text::timetz".
8315                                          * See comments for CURRENT_DATE.
8316                                          */
8317                                         Node *n;
8318                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8319                                         $$ = makeTypeCast(n, SystemTypeName("timetz"), -1);
8320                                 }
8321                         | CURRENT_TIME '(' Iconst ')'
8322                                 {
8323                                         /*
8324                                          * Translate as "'now'::text::timetz(n)".
8325                                          * See comments for CURRENT_DATE.
8326                                          */
8327                                         Node *n;
8328                                         TypeName *d;
8329                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8330                                         d = SystemTypeName("timetz");
8331                                         d->typmods = list_make1(makeIntConst($3, @3));
8332                                         $$ = makeTypeCast(n, d, -1);
8333                                 }
8334                         | CURRENT_TIMESTAMP
8335                                 {
8336                                         /*
8337                                          * Translate as "now()", since we have a function that
8338                                          * does exactly what is needed.
8339                                          */
8340                                         FuncCall *n = makeNode(FuncCall);
8341                                         n->funcname = SystemFuncName("now");
8342                                         n->args = NIL;
8343                                         n->agg_star = FALSE;
8344                                         n->agg_distinct = FALSE;
8345                                         n->func_variadic = FALSE;
8346                                         n->location = @1;
8347                                         $$ = (Node *)n;
8348                                 }
8349                         | CURRENT_TIMESTAMP '(' Iconst ')'
8350                                 {
8351                                         /*
8352                                          * Translate as "'now'::text::timestamptz(n)".
8353                                          * See comments for CURRENT_DATE.
8354                                          */
8355                                         Node *n;
8356                                         TypeName *d;
8357                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8358                                         d = SystemTypeName("timestamptz");
8359                                         d->typmods = list_make1(makeIntConst($3, @3));
8360                                         $$ = makeTypeCast(n, d, -1);
8361                                 }
8362                         | LOCALTIME
8363                                 {
8364                                         /*
8365                                          * Translate as "'now'::text::time".
8366                                          * See comments for CURRENT_DATE.
8367                                          */
8368                                         Node *n;
8369                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8370                                         $$ = makeTypeCast((Node *)n, SystemTypeName("time"), -1);
8371                                 }
8372                         | LOCALTIME '(' Iconst ')'
8373                                 {
8374                                         /*
8375                                          * Translate as "'now'::text::time(n)".
8376                                          * See comments for CURRENT_DATE.
8377                                          */
8378                                         Node *n;
8379                                         TypeName *d;
8380                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8381                                         d = SystemTypeName("time");
8382                                         d->typmods = list_make1(makeIntConst($3, @3));
8383                                         $$ = makeTypeCast((Node *)n, d, -1);
8384                                 }
8385                         | LOCALTIMESTAMP
8386                                 {
8387                                         /*
8388                                          * Translate as "'now'::text::timestamp".
8389                                          * See comments for CURRENT_DATE.
8390                                          */
8391                                         Node *n;
8392                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8393                                         $$ = makeTypeCast(n, SystemTypeName("timestamp"), -1);
8394                                 }
8395                         | LOCALTIMESTAMP '(' Iconst ')'
8396                                 {
8397                                         /*
8398                                          * Translate as "'now'::text::timestamp(n)".
8399                                          * See comments for CURRENT_DATE.
8400                                          */
8401                                         Node *n;
8402                                         TypeName *d;
8403                                         n = makeStringConstCast("now", @1, SystemTypeName("text"));
8404                                         d = SystemTypeName("timestamp");
8405                                         d->typmods = list_make1(makeIntConst($3, @3));
8406                                         $$ = makeTypeCast(n, d, -1);
8407                                 }
8408                         | CURRENT_ROLE
8409                                 {
8410                                         FuncCall *n = makeNode(FuncCall);
8411                                         n->funcname = SystemFuncName("current_user");
8412                                         n->args = NIL;
8413                                         n->agg_star = FALSE;
8414                                         n->agg_distinct = FALSE;
8415                                         n->func_variadic = FALSE;
8416                                         n->location = @1;
8417                                         $$ = (Node *)n;
8418                                 }
8419                         | CURRENT_USER
8420                                 {
8421                                         FuncCall *n = makeNode(FuncCall);
8422                                         n->funcname = SystemFuncName("current_user");
8423                                         n->args = NIL;
8424                                         n->agg_star = FALSE;
8425                                         n->agg_distinct = FALSE;
8426                                         n->func_variadic = FALSE;
8427                                         n->location = @1;
8428                                         $$ = (Node *)n;
8429                                 }
8430                         | SESSION_USER
8431                                 {
8432                                         FuncCall *n = makeNode(FuncCall);
8433                                         n->funcname = SystemFuncName("session_user");
8434                                         n->args = NIL;
8435                                         n->agg_star = FALSE;
8436                                         n->agg_distinct = FALSE;
8437                                         n->func_variadic = FALSE;
8438                                         n->location = @1;
8439                                         $$ = (Node *)n;
8440                                 }
8441                         | USER
8442                                 {
8443                                         FuncCall *n = makeNode(FuncCall);
8444                                         n->funcname = SystemFuncName("current_user");
8445                                         n->args = NIL;
8446                                         n->agg_star = FALSE;
8447                                         n->agg_distinct = FALSE;
8448                                         n->func_variadic = FALSE;
8449                                         n->location = @1;
8450                                         $$ = (Node *)n;
8451                                 }
8452                         | CURRENT_CATALOG
8453                                 {
8454                                         FuncCall *n = makeNode(FuncCall);
8455                                         n->funcname = SystemFuncName("current_database");
8456                                         n->args = NIL;
8457                                         n->agg_star = FALSE;
8458                                         n->agg_distinct = FALSE;
8459                                         n->func_variadic = FALSE;
8460                                         n->location = @1;
8461                                         $$ = (Node *)n;
8462                                 }
8463                         | CURRENT_SCHEMA
8464                                 {
8465                                         FuncCall *n = makeNode(FuncCall);
8466                                         n->funcname = SystemFuncName("current_schema");
8467                                         n->args = NIL;
8468                                         n->agg_star = FALSE;
8469                                         n->agg_distinct = FALSE;
8470                                         n->func_variadic = FALSE;
8471                                         n->location = @1;
8472                                         $$ = (Node *)n;
8473                                 }
8474                         | CAST '(' a_expr AS Typename ')'
8475                                 { $$ = makeTypeCast($3, $5, @1); }
8476                         | EXTRACT '(' extract_list ')'
8477                                 {
8478                                         FuncCall *n = makeNode(FuncCall);
8479                                         n->funcname = SystemFuncName("date_part");
8480                                         n->args = $3;
8481                                         n->agg_star = FALSE;
8482                                         n->agg_distinct = FALSE;
8483                                         n->func_variadic = FALSE;
8484                                         n->location = @1;
8485                                         $$ = (Node *)n;
8486                                 }
8487                         | OVERLAY '(' overlay_list ')'
8488                                 {
8489                                         /* overlay(A PLACING B FROM C FOR D) is converted to
8490                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+D)
8491                                          * overlay(A PLACING B FROM C) is converted to
8492                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+char_length(B))
8493                                          */
8494                                         FuncCall *n = makeNode(FuncCall);
8495                                         n->funcname = SystemFuncName("overlay");
8496                                         n->args = $3;
8497                                         n->agg_star = FALSE;
8498                                         n->agg_distinct = FALSE;
8499                                         n->func_variadic = FALSE;
8500                                         n->location = @1;
8501                                         $$ = (Node *)n;
8502                                 }
8503                         | POSITION '(' position_list ')'
8504                                 {
8505                                         /* position(A in B) is converted to position(B, A) */
8506                                         FuncCall *n = makeNode(FuncCall);
8507                                         n->funcname = SystemFuncName("position");
8508                                         n->args = $3;
8509                                         n->agg_star = FALSE;
8510                                         n->agg_distinct = FALSE;
8511                                         n->func_variadic = FALSE;
8512                                         n->location = @1;
8513                                         $$ = (Node *)n;
8514                                 }
8515                         | SUBSTRING '(' substr_list ')'
8516                                 {
8517                                         /* substring(A from B for C) is converted to
8518                                          * substring(A, B, C) - thomas 2000-11-28
8519                                          */
8520                                         FuncCall *n = makeNode(FuncCall);
8521                                         n->funcname = SystemFuncName("substring");
8522                                         n->args = $3;
8523                                         n->agg_star = FALSE;
8524                                         n->agg_distinct = FALSE;
8525                                         n->func_variadic = FALSE;
8526                                         n->location = @1;
8527                                         $$ = (Node *)n;
8528                                 }
8529                         | TREAT '(' a_expr AS Typename ')'
8530                                 {
8531                                         /* TREAT(expr AS target) converts expr of a particular type to target,
8532                                          * which is defined to be a subtype of the original expression.
8533                                          * In SQL99, this is intended for use with structured UDTs,
8534                                          * but let's make this a generally useful form allowing stronger
8535                                          * coercions than are handled by implicit casting.
8536                                          */
8537                                         FuncCall *n = makeNode(FuncCall);
8538                                         /* Convert SystemTypeName() to SystemFuncName() even though
8539                                          * at the moment they result in the same thing.
8540                                          */
8541                                         n->funcname = SystemFuncName(((Value *)llast($5->names))->val.str);
8542                                         n->args = list_make1($3);
8543                                         n->agg_star = FALSE;
8544                                         n->agg_distinct = FALSE;
8545                                         n->func_variadic = FALSE;
8546                                         n->location = @1;
8547                                         $$ = (Node *)n;
8548                                 }
8549                         | TRIM '(' BOTH trim_list ')'
8550                                 {
8551                                         /* various trim expressions are defined in SQL92
8552                                          * - thomas 1997-07-19
8553                                          */
8554                                         FuncCall *n = makeNode(FuncCall);
8555                                         n->funcname = SystemFuncName("btrim");
8556                                         n->args = $4;
8557                                         n->agg_star = FALSE;
8558                                         n->agg_distinct = FALSE;
8559                                         n->func_variadic = FALSE;
8560                                         n->location = @1;
8561                                         $$ = (Node *)n;
8562                                 }
8563                         | TRIM '(' LEADING trim_list ')'
8564                                 {
8565                                         FuncCall *n = makeNode(FuncCall);
8566                                         n->funcname = SystemFuncName("ltrim");
8567                                         n->args = $4;
8568                                         n->agg_star = FALSE;
8569                                         n->agg_distinct = FALSE;
8570                                         n->func_variadic = FALSE;
8571                                         n->location = @1;
8572                                         $$ = (Node *)n;
8573                                 }
8574                         | TRIM '(' TRAILING trim_list ')'
8575                                 {
8576                                         FuncCall *n = makeNode(FuncCall);
8577                                         n->funcname = SystemFuncName("rtrim");
8578                                         n->args = $4;
8579                                         n->agg_star = FALSE;
8580                                         n->agg_distinct = FALSE;
8581                                         n->func_variadic = FALSE;
8582                                         n->location = @1;
8583                                         $$ = (Node *)n;
8584                                 }
8585                         | TRIM '(' trim_list ')'
8586                                 {
8587                                         FuncCall *n = makeNode(FuncCall);
8588                                         n->funcname = SystemFuncName("btrim");
8589                                         n->args = $3;
8590                                         n->agg_star = FALSE;
8591                                         n->agg_distinct = FALSE;
8592                                         n->func_variadic = FALSE;
8593                                         n->location = @1;
8594                                         $$ = (Node *)n;
8595                                 }
8596                         | NULLIF '(' a_expr ',' a_expr ')'
8597                                 {
8598                                         $$ = (Node *) makeSimpleA_Expr(AEXPR_NULLIF, "=", $3, $5, @1);
8599                                 }
8600                         | COALESCE '(' expr_list ')'
8601                                 {
8602                                         CoalesceExpr *c = makeNode(CoalesceExpr);
8603                                         c->args = $3;
8604                                         c->location = @1;
8605                                         $$ = (Node *)c;
8606                                 }
8607                         | GREATEST '(' expr_list ')'
8608                                 {
8609                                         MinMaxExpr *v = makeNode(MinMaxExpr);
8610                                         v->args = $3;
8611                                         v->op = IS_GREATEST;
8612                                         v->location = @1;
8613                                         $$ = (Node *)v;
8614                                 }
8615                         | LEAST '(' expr_list ')'
8616                                 {
8617                                         MinMaxExpr *v = makeNode(MinMaxExpr);
8618                                         v->args = $3;
8619                                         v->op = IS_LEAST;
8620                                         v->location = @1;
8621                                         $$ = (Node *)v;
8622                                 }
8623                         | XMLCONCAT '(' expr_list ')'
8624                                 {
8625                                         $$ = makeXmlExpr(IS_XMLCONCAT, NULL, NIL, $3, @1);
8626                                 }
8627                         | XMLELEMENT '(' NAME_P ColLabel ')'
8628                                 {
8629                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, NIL, @1);
8630                                 }
8631                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ')'
8632                                 {
8633                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, NIL, @1);
8634                                 }
8635                         | XMLELEMENT '(' NAME_P ColLabel ',' expr_list ')'
8636                                 {
8637                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, NIL, $6, @1);
8638                                 }
8639                         | XMLELEMENT '(' NAME_P ColLabel ',' xml_attributes ',' expr_list ')'
8640                                 {
8641                                         $$ = makeXmlExpr(IS_XMLELEMENT, $4, $6, $8, @1);
8642                                 }
8643                         | XMLFOREST '(' xml_attribute_list ')'
8644                                 {
8645                                         $$ = makeXmlExpr(IS_XMLFOREST, NULL, $3, NIL, @1);
8646                                 }
8647                         | XMLPARSE '(' document_or_content a_expr xml_whitespace_option ')'
8648                                 {
8649                                         XmlExpr *x = (XmlExpr *)
8650                                                 makeXmlExpr(IS_XMLPARSE, NULL, NIL,
8651                                                                         list_make2($4, makeBoolAConst($5, -1)),
8652                                                                         @1);
8653                                         x->xmloption = $3;
8654                                         $$ = (Node *)x;
8655                                 }
8656                         | XMLPI '(' NAME_P ColLabel ')'
8657                                 {
8658                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, NIL, @1);
8659                                 }
8660                         | XMLPI '(' NAME_P ColLabel ',' a_expr ')'
8661                                 {
8662                                         $$ = makeXmlExpr(IS_XMLPI, $4, NULL, list_make1($6), @1);
8663                                 }
8664                         | XMLROOT '(' a_expr ',' xml_root_version opt_xml_root_standalone ')'
8665                                 {
8666                                         $$ = makeXmlExpr(IS_XMLROOT, NULL, NIL,
8667                                                                          list_make3($3, $5, $6), @1);
8668                                 }
8669                         | XMLSERIALIZE '(' document_or_content a_expr AS SimpleTypename ')'
8670                                 {
8671                                         XmlSerialize *n = makeNode(XmlSerialize);
8672                                         n->xmloption = $3;
8673                                         n->expr = $4;
8674                                         n->typename = $6;
8675                                         n->location = @1;
8676                                         $$ = (Node *)n;
8677                                 }
8678                 ;
8679
8680 /*
8681  * SQL/XML support
8682  */
8683 xml_root_version: VERSION_P a_expr
8684                                 { $$ = $2; }
8685                         | VERSION_P NO VALUE_P
8686                                 { $$ = makeNullAConst(-1); }
8687                 ;
8688
8689 opt_xml_root_standalone: ',' STANDALONE_P YES_P
8690                                 { $$ = makeIntConst(XML_STANDALONE_YES, -1); }
8691                         | ',' STANDALONE_P NO
8692                                 { $$ = makeIntConst(XML_STANDALONE_NO, -1); }
8693                         | ',' STANDALONE_P NO VALUE_P
8694                                 { $$ = makeIntConst(XML_STANDALONE_NO_VALUE, -1); }
8695                         | /*EMPTY*/
8696                                 { $$ = makeIntConst(XML_STANDALONE_OMITTED, -1); }
8697                 ;
8698
8699 xml_attributes: XMLATTRIBUTES '(' xml_attribute_list ')'        { $$ = $3; }
8700                 ;
8701
8702 xml_attribute_list:     xml_attribute_el                                        { $$ = list_make1($1); }
8703                         | xml_attribute_list ',' xml_attribute_el       { $$ = lappend($1, $3); }
8704                 ;
8705
8706 xml_attribute_el: a_expr AS ColLabel
8707                                 {
8708                                         $$ = makeNode(ResTarget);
8709                                         $$->name = $3;
8710                                         $$->indirection = NIL;
8711                                         $$->val = (Node *) $1;
8712                                         $$->location = @1;
8713                                 }
8714                         | a_expr
8715                                 {
8716                                         $$ = makeNode(ResTarget);
8717                                         $$->name = NULL;
8718                                         $$->indirection = NIL;
8719                                         $$->val = (Node *) $1;
8720                                         $$->location = @1;
8721                                 }
8722                 ;
8723
8724 document_or_content: DOCUMENT_P                                         { $$ = XMLOPTION_DOCUMENT; }
8725                         | CONTENT_P                                                             { $$ = XMLOPTION_CONTENT; }
8726                 ;
8727
8728 xml_whitespace_option: PRESERVE WHITESPACE_P            { $$ = TRUE; }
8729                         | STRIP_P WHITESPACE_P                                  { $$ = FALSE; }
8730                         | /*EMPTY*/                                                             { $$ = FALSE; }
8731                 ;
8732
8733 /*
8734  * Supporting nonterminals for expressions.
8735  */
8736
8737 /* Explicit row production.
8738  *
8739  * SQL99 allows an optional ROW keyword, so we can now do single-element rows
8740  * without conflicting with the parenthesized a_expr production.  Without the
8741  * ROW keyword, there must be more than one a_expr inside the parens.
8742  */
8743 row:            ROW '(' expr_list ')'                                   { $$ = $3; }
8744                         | ROW '(' ')'                                                   { $$ = NIL; }
8745                         | '(' expr_list ',' a_expr ')'                  { $$ = lappend($2, $4); }
8746                 ;
8747
8748 sub_type:       ANY                                                                             { $$ = ANY_SUBLINK; }
8749                         | SOME                                                                  { $$ = ANY_SUBLINK; }
8750                         | ALL                                                                   { $$ = ALL_SUBLINK; }
8751                 ;
8752
8753 all_Op:         Op                                                                              { $$ = $1; }
8754                         | MathOp                                                                { $$ = $1; }
8755                 ;
8756
8757 MathOp:          '+'                                                                    { $$ = "+"; }
8758                         | '-'                                                                   { $$ = "-"; }
8759                         | '*'                                                                   { $$ = "*"; }
8760                         | '/'                                                                   { $$ = "/"; }
8761                         | '%'                                                                   { $$ = "%"; }
8762                         | '^'                                                                   { $$ = "^"; }
8763                         | '<'                                                                   { $$ = "<"; }
8764                         | '>'                                                                   { $$ = ">"; }
8765                         | '='                                                                   { $$ = "="; }
8766                 ;
8767
8768 qual_Op:        Op
8769                                         { $$ = list_make1(makeString($1)); }
8770                         | OPERATOR '(' any_operator ')'
8771                                         { $$ = $3; }
8772                 ;
8773
8774 qual_all_Op:
8775                         all_Op
8776                                         { $$ = list_make1(makeString($1)); }
8777                         | OPERATOR '(' any_operator ')'
8778                                         { $$ = $3; }
8779                 ;
8780
8781 subquery_Op:
8782                         all_Op
8783                                         { $$ = list_make1(makeString($1)); }
8784                         | OPERATOR '(' any_operator ')'
8785                                         { $$ = $3; }
8786                         | LIKE
8787                                         { $$ = list_make1(makeString("~~")); }
8788                         | NOT LIKE
8789                                         { $$ = list_make1(makeString("!~~")); }
8790                         | ILIKE
8791                                         { $$ = list_make1(makeString("~~*")); }
8792                         | NOT ILIKE
8793                                         { $$ = list_make1(makeString("!~~*")); }
8794 /* cannot put SIMILAR TO here, because SIMILAR TO is a hack.
8795  * the regular expression is preprocessed by a function (similar_escape),
8796  * and the ~ operator for posix regular expressions is used.
8797  *        x SIMILAR TO y     ->    x ~ similar_escape(y)
8798  * this transformation is made on the fly by the parser upwards.
8799  * however the SubLink structure which handles any/some/all stuff
8800  * is not ready for such a thing.
8801  */
8802                         ;
8803
8804 expr_list:      a_expr
8805                                 {
8806                                         $$ = list_make1($1);
8807                                 }
8808                         | expr_list ',' a_expr
8809                                 {
8810                                         $$ = lappend($1, $3);
8811                                 }
8812                 ;
8813
8814 type_list:      Typename                                                                { $$ = list_make1($1); }
8815                         | type_list ',' Typename                                { $$ = lappend($1, $3); }
8816                 ;
8817
8818 array_expr: '[' expr_list ']'
8819                                 {
8820                                         $$ = makeAArrayExpr($2, @1);
8821                                 }
8822                         | '[' array_expr_list ']'
8823                                 {
8824                                         $$ = makeAArrayExpr($2, @1);
8825                                 }
8826                         | '[' ']'
8827                                 {
8828                                         $$ = makeAArrayExpr(NIL, @1);
8829                                 }
8830                 ;
8831
8832 array_expr_list: array_expr                                                     { $$ = list_make1($1); }
8833                         | array_expr_list ',' array_expr                { $$ = lappend($1, $3); }
8834                 ;
8835
8836
8837 extract_list:
8838                         extract_arg FROM a_expr
8839                                 {
8840                                         $$ = list_make2(makeStringConst($1, @1), $3);
8841                                 }
8842                         | /*EMPTY*/                                                             { $$ = NIL; }
8843                 ;
8844
8845 /* Allow delimited string Sconst in extract_arg as an SQL extension.
8846  * - thomas 2001-04-12
8847  */
8848 extract_arg:
8849                         IDENT                                                                   { $$ = $1; }
8850                         | YEAR_P                                                                { $$ = "year"; }
8851                         | MONTH_P                                                               { $$ = "month"; }
8852                         | DAY_P                                                                 { $$ = "day"; }
8853                         | HOUR_P                                                                { $$ = "hour"; }
8854                         | MINUTE_P                                                              { $$ = "minute"; }
8855                         | SECOND_P                                                              { $$ = "second"; }
8856                         | Sconst                                                                { $$ = $1; }
8857                 ;
8858
8859 /* OVERLAY() arguments
8860  * SQL99 defines the OVERLAY() function:
8861  * o overlay(text placing text from int for int)
8862  * o overlay(text placing text from int)
8863  */
8864 overlay_list:
8865                         a_expr overlay_placing substr_from substr_for
8866                                 {
8867                                         $$ = list_make4($1, $2, $3, $4);
8868                                 }
8869                         | a_expr overlay_placing substr_from
8870                                 {
8871                                         $$ = list_make3($1, $2, $3);
8872                                 }
8873                 ;
8874
8875 overlay_placing:
8876                         PLACING a_expr
8877                                 { $$ = $2; }
8878                 ;
8879
8880 /* position_list uses b_expr not a_expr to avoid conflict with general IN */
8881
8882 position_list:
8883                         b_expr IN_P b_expr                                              { $$ = list_make2($3, $1); }
8884                         | /*EMPTY*/                                                             { $$ = NIL; }
8885                 ;
8886
8887 /* SUBSTRING() arguments
8888  * SQL9x defines a specific syntax for arguments to SUBSTRING():
8889  * o substring(text from int for int)
8890  * o substring(text from int) get entire string from starting point "int"
8891  * o substring(text for int) get first "int" characters of string
8892  * o substring(text from pattern) get entire string matching pattern
8893  * o substring(text from pattern for escape) same with specified escape char
8894  * We also want to support generic substring functions which accept
8895  * the usual generic list of arguments. So we will accept both styles
8896  * here, and convert the SQL9x style to the generic list for further
8897  * processing. - thomas 2000-11-28
8898  */
8899 substr_list:
8900                         a_expr substr_from substr_for
8901                                 {
8902                                         $$ = list_make3($1, $2, $3);
8903                                 }
8904                         | a_expr substr_for substr_from
8905                                 {
8906                                         /* not legal per SQL99, but might as well allow it */
8907                                         $$ = list_make3($1, $3, $2);
8908                                 }
8909                         | a_expr substr_from
8910                                 {
8911                                         $$ = list_make2($1, $2);
8912                                 }
8913                         | a_expr substr_for
8914                                 {
8915                                         /*
8916                                          * Since there are no cases where this syntax allows
8917                                          * a textual FOR value, we forcibly cast the argument
8918                                          * to int4.  The possible matches in pg_proc are
8919                                          * substring(text,int4) and substring(text,text),
8920                                          * and we don't want the parser to choose the latter,
8921                                          * which it is likely to do if the second argument
8922                                          * is unknown or doesn't have an implicit cast to int4.
8923                                          */
8924                                         $$ = list_make3($1, makeIntConst(1, -1),
8925                                                                         makeTypeCast($2,
8926                                                                                                  SystemTypeName("int4"), -1));
8927                                 }
8928                         | expr_list
8929                                 {
8930                                         $$ = $1;
8931                                 }
8932                         | /*EMPTY*/
8933                                 { $$ = NIL; }
8934                 ;
8935
8936 substr_from:
8937                         FROM a_expr                                                             { $$ = $2; }
8938                 ;
8939
8940 substr_for: FOR a_expr                                                          { $$ = $2; }
8941                 ;
8942
8943 trim_list:      a_expr FROM expr_list                                   { $$ = lappend($3, $1); }
8944                         | FROM expr_list                                                { $$ = $2; }
8945                         | expr_list                                                             { $$ = $1; }
8946                 ;
8947
8948 in_expr:        select_with_parens
8949                                 {
8950                                         SubLink *n = makeNode(SubLink);
8951                                         n->subselect = $1;
8952                                         /* other fields will be filled later */
8953                                         $$ = (Node *)n;
8954                                 }
8955                         | '(' expr_list ')'                                             { $$ = (Node *)$2; }
8956                 ;
8957
8958 /*
8959  * Define SQL92-style case clause.
8960  * - Full specification
8961  *      CASE WHEN a = b THEN c ... ELSE d END
8962  * - Implicit argument
8963  *      CASE a WHEN b THEN c ... ELSE d END
8964  */
8965 case_expr:      CASE case_arg when_clause_list case_default END_P
8966                                 {
8967                                         CaseExpr *c = makeNode(CaseExpr);
8968                                         c->casetype = InvalidOid; /* not analyzed yet */
8969                                         c->arg = (Expr *) $2;
8970                                         c->args = $3;
8971                                         c->defresult = (Expr *) $4;
8972                                         c->location = @1;
8973                                         $$ = (Node *)c;
8974                                 }
8975                 ;
8976
8977 when_clause_list:
8978                         /* There must be at least one */
8979                         when_clause                                                             { $$ = list_make1($1); }
8980                         | when_clause_list when_clause                  { $$ = lappend($1, $2); }
8981                 ;
8982
8983 when_clause:
8984                         WHEN a_expr THEN a_expr
8985                                 {
8986                                         CaseWhen *w = makeNode(CaseWhen);
8987                                         w->expr = (Expr *) $2;
8988                                         w->result = (Expr *) $4;
8989                                         w->location = @1;
8990                                         $$ = (Node *)w;
8991                                 }
8992                 ;
8993
8994 case_default:
8995                         ELSE a_expr                                                             { $$ = $2; }
8996                         | /*EMPTY*/                                                             { $$ = NULL; }
8997                 ;
8998
8999 case_arg:       a_expr                                                                  { $$ = $1; }
9000                         | /*EMPTY*/                                                             { $$ = NULL; }
9001                 ;
9002
9003 /*
9004  * columnref starts with relation_name not ColId, so that OLD and NEW
9005  * references can be accepted.  Note that when there are more than two
9006  * dotted names, the first name is not actually a relation name...
9007  */
9008 columnref:      relation_name
9009                                 {
9010                                         $$ = makeColumnRef($1, NIL, @1);
9011                                 }
9012                         | relation_name indirection
9013                                 {
9014                                         $$ = makeColumnRef($1, $2, @1);
9015                                 }
9016                 ;
9017
9018 indirection_el:
9019                         '.' attr_name
9020                                 {
9021                                         $$ = (Node *) makeString($2);
9022                                 }
9023                         | '.' '*'
9024                                 {
9025                                         $$ = (Node *) makeNode(A_Star);
9026                                 }
9027                         | '[' a_expr ']'
9028                                 {
9029                                         A_Indices *ai = makeNode(A_Indices);
9030                                         ai->lidx = NULL;
9031                                         ai->uidx = $2;
9032                                         $$ = (Node *) ai;
9033                                 }
9034                         | '[' a_expr ':' a_expr ']'
9035                                 {
9036                                         A_Indices *ai = makeNode(A_Indices);
9037                                         ai->lidx = $2;
9038                                         ai->uidx = $4;
9039                                         $$ = (Node *) ai;
9040                                 }
9041                 ;
9042
9043 indirection:
9044                         indirection_el                                                  { $$ = list_make1($1); }
9045                         | indirection indirection_el                    { $$ = lappend($1, $2); }
9046                 ;
9047
9048 opt_indirection:
9049                         /*EMPTY*/                                                               { $$ = NIL; }
9050                         | opt_indirection indirection_el                { $$ = lappend($1, $2); }
9051                 ;
9052
9053 opt_asymmetric: ASYMMETRIC
9054                         | /*EMPTY*/
9055                 ;
9056
9057 /*
9058  * The SQL spec defines "contextually typed value expressions" and
9059  * "contextually typed row value constructors", which for our purposes
9060  * are the same as "a_expr" and "row" except that DEFAULT can appear at
9061  * the top level.
9062  */
9063
9064 ctext_expr:
9065                         a_expr                                  { $$ = (Node *) $1; }
9066                         | DEFAULT
9067                                 {
9068                                         SetToDefault *n = makeNode(SetToDefault);
9069                                         n->location = @1;
9070                                         $$ = (Node *) n;
9071                                 }
9072                 ;
9073
9074 ctext_expr_list:
9075                         ctext_expr                                                              { $$ = list_make1($1); }
9076                         | ctext_expr_list ',' ctext_expr                { $$ = lappend($1, $3); }
9077                 ;
9078
9079 /*
9080  * We should allow ROW '(' ctext_expr_list ')' too, but that seems to require
9081  * making VALUES a fully reserved word, which will probably break more apps
9082  * than allowing the noise-word is worth.
9083  */
9084 ctext_row: '(' ctext_expr_list ')'                                      { $$ = $2; }
9085                 ;
9086
9087
9088 /*****************************************************************************
9089  *
9090  *      target list for SELECT
9091  *
9092  *****************************************************************************/
9093
9094 target_list:
9095                         target_el                                                               { $$ = list_make1($1); }
9096                         | target_list ',' target_el                             { $$ = lappend($1, $3); }
9097                 ;
9098
9099 target_el:      a_expr AS ColLabel
9100                                 {
9101                                         $$ = makeNode(ResTarget);
9102                                         $$->name = $3;
9103                                         $$->indirection = NIL;
9104                                         $$->val = (Node *)$1;
9105                                         $$->location = @1;
9106                                 }
9107                         /*
9108                          * We support omitting AS only for column labels that aren't
9109                          * any known keyword.  There is an ambiguity against postfix
9110                          * operators: is "a ! b" an infix expression, or a postfix
9111                          * expression and a column label?  We prefer to resolve this
9112                          * as an infix expression, which we accomplish by assigning
9113                          * IDENT a precedence higher than POSTFIXOP.
9114                          */
9115                         | a_expr IDENT
9116                                 {
9117                                         $$ = makeNode(ResTarget);
9118                                         $$->name = $2;
9119                                         $$->indirection = NIL;
9120                                         $$->val = (Node *)$1;
9121                                         $$->location = @1;
9122                                 }
9123                         | a_expr
9124                                 {
9125                                         $$ = makeNode(ResTarget);
9126                                         $$->name = NULL;
9127                                         $$->indirection = NIL;
9128                                         $$->val = (Node *)$1;
9129                                         $$->location = @1;
9130                                 }
9131                         | '*'
9132                                 {
9133                                         ColumnRef *n = makeNode(ColumnRef);
9134                                         n->fields = list_make1(makeNode(A_Star));
9135                                         n->location = @1;
9136
9137                                         $$ = makeNode(ResTarget);
9138                                         $$->name = NULL;
9139                                         $$->indirection = NIL;
9140                                         $$->val = (Node *)n;
9141                                         $$->location = @1;
9142                                 }
9143                 ;
9144
9145
9146 /*****************************************************************************
9147  *
9148  *      Names and constants
9149  *
9150  *****************************************************************************/
9151
9152 relation_name:
9153                         SpecialRuleRelation                                             { $$ = $1; }
9154                         | ColId                                                                 { $$ = $1; }
9155                 ;
9156
9157 qualified_name_list:
9158                         qualified_name                                                  { $$ = list_make1($1); }
9159                         | qualified_name_list ',' qualified_name { $$ = lappend($1, $3); }
9160                 ;
9161
9162 /*
9163  * The production for a qualified relation name has to exactly match the
9164  * production for a qualified func_name, because in a FROM clause we cannot
9165  * tell which we are parsing until we see what comes after it ('(' for a
9166  * func_name, something else for a relation). Therefore we allow 'indirection'
9167  * which may contain subscripts, and reject that case in the C code.
9168  */
9169 qualified_name:
9170                         relation_name
9171                                 {
9172                                         $$ = makeNode(RangeVar);
9173                                         $$->catalogname = NULL;
9174                                         $$->schemaname = NULL;
9175                                         $$->relname = $1;
9176                                         $$->location = @1;
9177                                 }
9178                         | relation_name indirection
9179                                 {
9180                                         check_qualified_name($2);
9181                                         $$ = makeNode(RangeVar);
9182                                         switch (list_length($2))
9183                                         {
9184                                                 case 1:
9185                                                         $$->catalogname = NULL;
9186                                                         $$->schemaname = $1;
9187                                                         $$->relname = strVal(linitial($2));
9188                                                         break;
9189                                                 case 2:
9190                                                         $$->catalogname = $1;
9191                                                         $$->schemaname = strVal(linitial($2));
9192                                                         $$->relname = strVal(lsecond($2));
9193                                                         break;
9194                                                 default:
9195                                                         ereport(ERROR,
9196                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
9197                                                                          errmsg("improper qualified name (too many dotted names): %s",
9198                                                                                         NameListToString(lcons(makeString($1), $2))),
9199                                                                          scanner_errposition(@1)));
9200                                                         break;
9201                                         }
9202                                         $$->location = @1;
9203                                 }
9204                 ;
9205
9206 name_list:      name
9207                                         { $$ = list_make1(makeString($1)); }
9208                         | name_list ',' name
9209                                         { $$ = lappend($1, makeString($3)); }
9210                 ;
9211
9212
9213 name:           ColId                                                                   { $$ = $1; };
9214
9215 database_name:
9216                         ColId                                                                   { $$ = $1; };
9217
9218 access_method:
9219                         ColId                                                                   { $$ = $1; };
9220
9221 attr_name:      ColLabel                                                                { $$ = $1; };
9222
9223 index_name: ColId                                                                       { $$ = $1; };
9224
9225 file_name:      Sconst                                                                  { $$ = $1; };
9226
9227 /*
9228  * The production for a qualified func_name has to exactly match the
9229  * production for a qualified columnref, because we cannot tell which we
9230  * are parsing until we see what comes after it ('(' or Sconst for a func_name,
9231  * anything else for a columnref).  Therefore we allow 'indirection' which
9232  * may contain subscripts, and reject that case in the C code.  (If we
9233  * ever implement SQL99-like methods, such syntax may actually become legal!)
9234  */
9235 func_name:      type_function_name
9236                                         { $$ = list_make1(makeString($1)); }
9237                         | relation_name indirection
9238                                         { $$ = check_func_name(lcons(makeString($1), $2)); }
9239                 ;
9240
9241
9242 /*
9243  * Constants
9244  */
9245 AexprConst: Iconst
9246                                 {
9247                                         $$ = makeIntConst($1, @1);
9248                                 }
9249                         | FCONST
9250                                 {
9251                                         $$ = makeFloatConst($1, @1);
9252                                 }
9253                         | Sconst
9254                                 {
9255                                         $$ = makeStringConst($1, @1);
9256                                 }
9257                         | BCONST
9258                                 {
9259                                         $$ = makeBitStringConst($1, @1);
9260                                 }
9261                         | XCONST
9262                                 {
9263                                         /* This is a bit constant per SQL99:
9264                                          * Without Feature F511, "BIT data type",
9265                                          * a <general literal> shall not be a
9266                                          * <bit string literal> or a <hex string literal>.
9267                                          */
9268                                         $$ = makeBitStringConst($1, @1);
9269                                 }
9270                         | func_name Sconst
9271                                 {
9272                                         /* generic type 'literal' syntax */
9273                                         TypeName *t = makeTypeNameFromNameList($1);
9274                                         t->location = @1;
9275                                         $$ = makeStringConstCast($2, @2, t);
9276                                 }
9277                         | func_name '(' expr_list ')' Sconst
9278                                 {
9279                                         /* generic syntax with a type modifier */
9280                                         TypeName *t = makeTypeNameFromNameList($1);
9281                                         t->typmods = $3;
9282                                         t->location = @1;
9283                                         $$ = makeStringConstCast($5, @5, t);
9284                                 }
9285                         | ConstTypename Sconst
9286                                 {
9287                                         $$ = makeStringConstCast($2, @2, $1);
9288                                 }
9289                         | ConstInterval Sconst opt_interval
9290                                 {
9291                                         TypeName *t = $1;
9292                                         t->typmods = $3;
9293                                         $$ = makeStringConstCast($2, @2, t);
9294                                 }
9295                         | ConstInterval '(' Iconst ')' Sconst opt_interval
9296                                 {
9297                                         TypeName *t = $1;
9298                                         if ($6 != NIL)
9299                                         {
9300                                                 if (list_length($6) != 1)
9301                                                         ereport(ERROR,
9302                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
9303                                                                          errmsg("interval precision specified twice"),
9304                                                                          scanner_errposition(@1)));
9305                                                 t->typmods = lappend($6, makeIntConst($3, @3));
9306                                         }
9307                                         else
9308                                                 t->typmods = list_make2(makeIntConst(INTERVAL_FULL_RANGE, -1),
9309                                                                                                 makeIntConst($3, @3));
9310                                         $$ = makeStringConstCast($5, @5, t);
9311                                 }
9312                         | TRUE_P
9313                                 {
9314                                         $$ = makeBoolAConst(TRUE, @1);
9315                                 }
9316                         | FALSE_P
9317                                 {
9318                                         $$ = makeBoolAConst(FALSE, @1);
9319                                 }
9320                         | NULL_P
9321                                 {
9322                                         $$ = makeNullAConst(@1);
9323                                 }
9324                 ;
9325
9326 Iconst:         ICONST                                                                  { $$ = $1; };
9327 Sconst:         SCONST                                                                  { $$ = $1; };
9328 RoleId:         ColId                                                                   { $$ = $1; };
9329
9330 SignedIconst: Iconst                                                            { $$ = $1; }
9331                         | '+' Iconst                                                    { $$ = + $2; }
9332                         | '-' Iconst                                                    { $$ = - $2; }
9333                 ;
9334
9335 /*
9336  * Name classification hierarchy.
9337  *
9338  * IDENT is the lexeme returned by the lexer for identifiers that match
9339  * no known keyword.  In most cases, we can accept certain keywords as
9340  * names, not only IDENTs.      We prefer to accept as many such keywords
9341  * as possible to minimize the impact of "reserved words" on programmers.
9342  * So, we divide names into several possible classes.  The classification
9343  * is chosen in part to make keywords acceptable as names wherever possible.
9344  */
9345
9346 /* Column identifier --- names that can be column, table, etc names.
9347  */
9348 ColId:          IDENT                                                                   { $$ = $1; }
9349                         | unreserved_keyword                                    { $$ = pstrdup($1); }
9350                         | col_name_keyword                                              { $$ = pstrdup($1); }
9351                 ;
9352
9353 /* Type/function identifier --- names that can be type or function names.
9354  */
9355 type_function_name:     IDENT                                                   { $$ = $1; }
9356                         | unreserved_keyword                                    { $$ = pstrdup($1); }
9357                         | type_func_name_keyword                                { $$ = pstrdup($1); }
9358                 ;
9359
9360 /* Column label --- allowed labels in "AS" clauses.
9361  * This presently includes *all* Postgres keywords.
9362  */
9363 ColLabel:       IDENT                                                                   { $$ = $1; }
9364                         | unreserved_keyword                                    { $$ = pstrdup($1); }
9365                         | col_name_keyword                                              { $$ = pstrdup($1); }
9366                         | type_func_name_keyword                                { $$ = pstrdup($1); }
9367                         | reserved_keyword                                              { $$ = pstrdup($1); }
9368                 ;
9369
9370
9371 /*
9372  * Keyword category lists.  Generally, every keyword present in
9373  * the Postgres grammar should appear in exactly one of these lists.
9374  *
9375  * Put a new keyword into the first list that it can go into without causing
9376  * shift or reduce conflicts.  The earlier lists define "less reserved"
9377  * categories of keywords.
9378  *
9379  * Make sure that each keyword's category in keywords.c matches where
9380  * it is listed here.  (Someday we may be able to generate these lists and
9381  * keywords.c's table from a common master list.)
9382  */
9383
9384 /* "Unreserved" keywords --- available for use as any kind of name.
9385  */
9386 unreserved_keyword:
9387                           ABORT_P
9388                         | ABSOLUTE_P
9389                         | ACCESS
9390                         | ACTION
9391                         | ADD_P
9392                         | ADMIN
9393                         | AFTER
9394                         | AGGREGATE
9395                         | ALSO
9396                         | ALTER
9397                         | ALWAYS
9398                         | ASSERTION
9399                         | ASSIGNMENT
9400                         | AT
9401                         | BACKWARD
9402                         | BEFORE
9403                         | BEGIN_P
9404                         | BY
9405                         | CACHE
9406                         | CALLED
9407                         | CASCADE
9408                         | CASCADED
9409                         | CATALOG_P
9410                         | CHAIN
9411                         | CHARACTERISTICS
9412                         | CHECKPOINT
9413                         | CLASS
9414                         | CLOSE
9415                         | CLUSTER
9416                         | COMMENT
9417                         | COMMIT
9418                         | COMMITTED
9419                         | CONCURRENTLY
9420                         | CONFIGURATION
9421                         | CONNECTION
9422                         | CONSTRAINTS
9423                         | CONTENT_P
9424                         | CONTINUE_P
9425                         | CONVERSION_P
9426                         | COPY
9427                         | COST
9428                         | CREATEDB
9429                         | CREATEROLE
9430                         | CREATEUSER
9431                         | CSV
9432                         | CTYPE
9433                         | CURRENT_P
9434                         | CURSOR
9435                         | CYCLE
9436                         | DATA_P
9437                         | DATABASE
9438                         | DAY_P
9439                         | DEALLOCATE
9440                         | DECLARE
9441                         | DEFAULTS
9442                         | DEFERRED
9443                         | DEFINER
9444                         | DELETE_P
9445                         | DELIMITER
9446                         | DELIMITERS
9447                         | DICTIONARY
9448                         | DISABLE_P
9449                         | DISCARD
9450                         | DOCUMENT_P
9451                         | DOMAIN_P
9452                         | DOUBLE_P
9453                         | DROP
9454                         | EACH
9455                         | ENABLE_P
9456                         | ENCODING
9457                         | ENCRYPTED
9458                         | ENUM_P
9459                         | ESCAPE
9460                         | EXCLUDING
9461                         | EXCLUSIVE
9462                         | EXECUTE
9463                         | EXPLAIN
9464                         | EXTERNAL
9465                         | FAMILY
9466                         | FIRST_P
9467                         | FORCE
9468                         | FORWARD
9469                         | FUNCTION
9470                         | GLOBAL
9471                         | GRANTED
9472                         | HANDLER
9473                         | HEADER_P
9474                         | HOLD
9475                         | HOUR_P
9476                         | IDENTITY_P
9477                         | IF_P
9478                         | IMMEDIATE
9479                         | IMMUTABLE
9480                         | IMPLICIT_P
9481                         | INCLUDING
9482                         | INCREMENT
9483                         | INDEX
9484                         | INDEXES
9485                         | INHERIT
9486                         | INHERITS
9487                         | INPUT_P
9488                         | INSENSITIVE
9489                         | INSERT
9490                         | INSTEAD
9491                         | INVOKER
9492                         | ISOLATION
9493                         | KEY
9494                         | LANCOMPILER
9495                         | LANGUAGE
9496                         | LARGE_P
9497                         | LAST_P
9498                         | LEVEL
9499                         | LISTEN
9500                         | LOAD
9501                         | LOCAL
9502                         | LOCATION
9503                         | LOCK_P
9504                         | LOGIN_P
9505                         | MAPPING
9506                         | MATCH
9507                         | MAXVALUE
9508                         | MINUTE_P
9509                         | MINVALUE
9510                         | MODE
9511                         | MONTH_P
9512                         | MOVE
9513                         | NAME_P
9514                         | NAMES
9515                         | NEXT
9516                         | NO
9517                         | NOCREATEDB
9518                         | NOCREATEROLE
9519                         | NOCREATEUSER
9520                         | NOINHERIT
9521                         | NOLOGIN_P
9522                         | NOSUPERUSER
9523                         | NOTHING
9524                         | NOTIFY
9525                         | NOWAIT
9526                         | NULLS_P
9527                         | OBJECT_P
9528                         | OF
9529                         | OIDS
9530                         | OPERATOR
9531                         | OPTION
9532                         | OWNED
9533                         | OWNER
9534                         | PARSER
9535                         | PARTIAL
9536                         | PASSWORD
9537                         | PLANS
9538                         | PREPARE
9539                         | PREPARED
9540                         | PRESERVE
9541                         | PRIOR
9542                         | PRIVILEGES
9543                         | PROCEDURAL
9544                         | PROCEDURE
9545                         | QUOTE
9546                         | READ
9547                         | REASSIGN
9548                         | RECHECK
9549                         | RECURSIVE
9550                         | REINDEX
9551                         | RELATIVE_P
9552                         | RELEASE
9553                         | RENAME
9554                         | REPEATABLE
9555                         | REPLACE
9556                         | REPLICA
9557                         | RESET
9558                         | RESTART
9559                         | RESTRICT
9560                         | RETURNS
9561                         | REVOKE
9562                         | ROLE
9563                         | ROLLBACK
9564                         | ROWS
9565                         | RULE
9566                         | SAVEPOINT
9567                         | SCHEMA
9568                         | SCROLL
9569                         | SEARCH
9570                         | SECOND_P
9571                         | SECURITY
9572                         | SEQUENCE
9573                         | SERIALIZABLE
9574                         | SESSION
9575                         | SET
9576                         | SHARE
9577                         | SHOW
9578                         | SIMPLE
9579                         | STABLE
9580                         | STANDALONE_P
9581                         | START
9582                         | STATEMENT
9583                         | STATISTICS
9584                         | STDIN
9585                         | STDOUT
9586                         | STORAGE
9587                         | STRICT_P
9588                         | STRIP_P
9589                         | SUPERUSER_P
9590                         | SYSID
9591                         | SYSTEM_P
9592                         | TABLESPACE
9593                         | TEMP
9594                         | TEMPLATE
9595                         | TEMPORARY
9596                         | TEXT_P
9597                         | TRANSACTION
9598                         | TRIGGER
9599                         | TRUNCATE
9600                         | TRUSTED
9601                         | TYPE_P
9602                         | UNCOMMITTED
9603                         | UNENCRYPTED
9604                         | UNKNOWN
9605                         | UNLISTEN
9606                         | UNTIL
9607                         | UPDATE
9608                         | VACUUM
9609                         | VALID
9610                         | VALIDATOR
9611                         | VALUE_P
9612                         | VARYING
9613                         | VERSION_P
9614                         | VIEW
9615                         | VOLATILE
9616                         | WHITESPACE_P
9617                         | WITHOUT
9618                         | WORK
9619                         | WRITE
9620                         | XML_P
9621                         | YEAR_P
9622                         | YES_P
9623                         | ZONE
9624                 ;
9625
9626 /* Column identifier --- keywords that can be column, table, etc names.
9627  *
9628  * Many of these keywords will in fact be recognized as type or function
9629  * names too; but they have special productions for the purpose, and so
9630  * can't be treated as "generic" type or function names.
9631  *
9632  * The type names appearing here are not usable as function names
9633  * because they can be followed by '(' in typename productions, which
9634  * looks too much like a function call for an LR(1) parser.
9635  */
9636 col_name_keyword:
9637                           BIGINT
9638                         | BIT
9639                         | BOOLEAN_P
9640                         | CHAR_P
9641                         | CHARACTER
9642                         | COALESCE
9643                         | DEC
9644                         | DECIMAL_P
9645                         | EXISTS
9646                         | EXTRACT
9647                         | FLOAT_P
9648                         | GREATEST
9649                         | INOUT
9650                         | INT_P
9651                         | INTEGER
9652                         | INTERVAL
9653                         | LEAST
9654                         | NATIONAL
9655                         | NCHAR
9656                         | NONE
9657                         | NULLIF
9658                         | NUMERIC
9659                         | OUT_P
9660                         | OVERLAY
9661                         | POSITION
9662                         | PRECISION
9663                         | REAL
9664                         | ROW
9665                         | SETOF
9666                         | SMALLINT
9667                         | SUBSTRING
9668                         | TIME
9669                         | TIMESTAMP
9670                         | TREAT
9671                         | TRIM
9672                         | VALUES
9673                         | VARCHAR
9674                         | XMLATTRIBUTES
9675                         | XMLCONCAT
9676                         | XMLELEMENT
9677                         | XMLFOREST
9678                         | XMLPARSE
9679                         | XMLPI
9680                         | XMLROOT
9681                         | XMLSERIALIZE
9682                 ;
9683
9684 /* Type/function identifier --- keywords that can be type or function names.
9685  *
9686  * Most of these are keywords that are used as operators in expressions;
9687  * in general such keywords can't be column names because they would be
9688  * ambiguous with variables, but they are unambiguous as function identifiers.
9689  *
9690  * Do not include POSITION, SUBSTRING, etc here since they have explicit
9691  * productions in a_expr to support the goofy SQL9x argument syntax.
9692  * - thomas 2000-11-28
9693  */
9694 type_func_name_keyword:
9695                           AUTHORIZATION
9696                         | BETWEEN
9697                         | BINARY
9698                         | CROSS
9699                         | CURRENT_SCHEMA
9700                         | FREEZE
9701                         | FULL
9702                         | ILIKE
9703                         | INNER_P
9704                         | IS
9705                         | ISNULL
9706                         | JOIN
9707                         | LEFT
9708                         | LIKE
9709                         | NATURAL
9710                         | NOTNULL
9711                         | OUTER_P
9712                         | OVERLAPS
9713                         | RIGHT
9714                         | SIMILAR
9715                         | VERBOSE
9716                 ;
9717
9718 /* Reserved keyword --- these keywords are usable only as a ColLabel.
9719  *
9720  * Keywords appear here if they could not be distinguished from variable,
9721  * type, or function names in some contexts.  Don't put things here unless
9722  * forced to.
9723  */
9724 reserved_keyword:
9725                           ALL
9726                         | ANALYSE
9727                         | ANALYZE
9728                         | AND
9729                         | ANY
9730                         | ARRAY
9731                         | AS
9732                         | ASC
9733                         | ASYMMETRIC
9734                         | BOTH
9735                         | CASE
9736                         | CAST
9737                         | CHECK
9738                         | COLLATE
9739                         | COLUMN
9740                         | CONSTRAINT
9741                         | CREATE
9742                         | CURRENT_CATALOG
9743                         | CURRENT_DATE
9744                         | CURRENT_ROLE
9745                         | CURRENT_TIME
9746                         | CURRENT_TIMESTAMP
9747                         | CURRENT_USER
9748                         | DEFAULT
9749                         | DEFERRABLE
9750                         | DESC
9751                         | DISTINCT
9752                         | DO
9753                         | ELSE
9754                         | END_P
9755                         | EXCEPT
9756                         | FALSE_P
9757                         | FETCH
9758                         | FOR
9759                         | FOREIGN
9760                         | FROM
9761                         | GRANT
9762                         | GROUP_P
9763                         | HAVING
9764                         | IN_P
9765                         | INITIALLY
9766                         | INTERSECT
9767                         | INTO
9768                         | LEADING
9769                         | LIMIT
9770                         | LOCALTIME
9771                         | LOCALTIMESTAMP
9772                         | NEW
9773                         | NOT
9774                         | NULL_P
9775                         | OFF
9776                         | OFFSET
9777                         | OLD
9778                         | ON
9779                         | ONLY
9780                         | OR
9781                         | ORDER
9782                         | PLACING
9783                         | PRIMARY
9784                         | REFERENCES
9785                         | RETURNING
9786                         | SELECT
9787                         | SESSION_USER
9788                         | SOME
9789                         | SYMMETRIC
9790                         | TABLE
9791                         | THEN
9792                         | TO
9793                         | TRAILING
9794                         | TRUE_P
9795                         | UNION
9796                         | UNIQUE
9797                         | USER
9798                         | USING
9799                         | VARIADIC
9800                         | WHEN
9801                         | WHERE
9802                         | WITH
9803                 ;
9804
9805
9806 SpecialRuleRelation:
9807                         OLD
9808                                 {
9809                                         if (QueryIsRule)
9810                                                 $$ = "*OLD*";
9811                                         else
9812                                                 ereport(ERROR,
9813                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
9814                                                                  errmsg("OLD used in query that is not in a rule"),
9815                                                                  scanner_errposition(@1)));
9816                                 }
9817                         | NEW
9818                                 {
9819                                         if (QueryIsRule)
9820                                                 $$ = "*NEW*";
9821                                         else
9822                                                 ereport(ERROR,
9823                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
9824                                                                  errmsg("NEW used in query that is not in a rule"),
9825                                                                  scanner_errposition(@1)));
9826                                 }
9827                 ;
9828
9829 %%
9830
9831 static Node *
9832 makeColumnRef(char *colname, List *indirection, int location)
9833 {
9834         /*
9835          * Generate a ColumnRef node, with an A_Indirection node added if there
9836          * is any subscripting in the specified indirection list.  However,
9837          * any field selection at the start of the indirection list must be
9838          * transposed into the "fields" part of the ColumnRef node.
9839          */
9840         ColumnRef  *c = makeNode(ColumnRef);
9841         int             nfields = 0;
9842         ListCell *l;
9843
9844         c->location = location;
9845         foreach(l, indirection)
9846         {
9847                 if (IsA(lfirst(l), A_Indices))
9848                 {
9849                         A_Indirection *i = makeNode(A_Indirection);
9850
9851                         if (nfields == 0)
9852                         {
9853                                 /* easy case - all indirection goes to A_Indirection */
9854                                 c->fields = list_make1(makeString(colname));
9855                                 i->indirection = check_indirection(indirection);
9856                         }
9857                         else
9858                         {
9859                                 /* got to split the list in two */
9860                                 i->indirection = check_indirection(list_copy_tail(indirection,
9861                                                                                                                                   nfields));
9862                                 indirection = list_truncate(indirection, nfields);
9863                                 c->fields = lcons(makeString(colname), indirection);
9864                         }
9865                         i->arg = (Node *) c;
9866                         return (Node *) i;
9867                 }
9868                 else if (IsA(lfirst(l), A_Star))
9869                 {
9870                         /* We only allow '*' at the end of a ColumnRef */
9871                         if (lnext(l) != NULL)
9872                                 yyerror("improper use of \"*\"");
9873                 }
9874                 nfields++;
9875         }
9876         /* No subscripting, so all indirection gets added to field list */
9877         c->fields = lcons(makeString(colname), indirection);
9878         return (Node *) c;
9879 }
9880
9881 static Node *
9882 makeTypeCast(Node *arg, TypeName *typename, int location)
9883 {
9884         TypeCast *n = makeNode(TypeCast);
9885         n->arg = arg;
9886         n->typename = typename;
9887         n->location = location;
9888         return (Node *) n;
9889 }
9890
9891 static Node *
9892 makeStringConst(char *str, int location)
9893 {
9894         A_Const *n = makeNode(A_Const);
9895
9896         n->val.type = T_String;
9897         n->val.val.str = str;
9898         n->location = location;
9899
9900         return (Node *)n;
9901 }
9902
9903 static Node *
9904 makeStringConstCast(char *str, int location, TypeName *typename)
9905 {
9906         Node *s = makeStringConst(str, location);
9907
9908         return makeTypeCast(s, typename, -1);
9909 }
9910
9911 static Node *
9912 makeIntConst(int val, int location)
9913 {
9914         A_Const *n = makeNode(A_Const);
9915
9916         n->val.type = T_Integer;
9917         n->val.val.ival = val;
9918         n->location = location;
9919
9920         return (Node *)n;
9921 }
9922
9923 static Node *
9924 makeFloatConst(char *str, int location)
9925 {
9926         A_Const *n = makeNode(A_Const);
9927
9928         n->val.type = T_Float;
9929         n->val.val.str = str;
9930         n->location = location;
9931
9932         return (Node *)n;
9933 }
9934
9935 static Node *
9936 makeBitStringConst(char *str, int location)
9937 {
9938         A_Const *n = makeNode(A_Const);
9939
9940         n->val.type = T_BitString;
9941         n->val.val.str = str;
9942         n->location = location;
9943
9944         return (Node *)n;
9945 }
9946
9947 static Node *
9948 makeNullAConst(int location)
9949 {
9950         A_Const *n = makeNode(A_Const);
9951
9952         n->val.type = T_Null;
9953         n->location = location;
9954
9955         return (Node *)n;
9956 }
9957
9958 static Node *
9959 makeAConst(Value *v, int location)
9960 {
9961         Node *n;
9962
9963         switch (v->type)
9964         {
9965                 case T_Float:
9966                         n = makeFloatConst(v->val.str, location);
9967                         break;
9968
9969                 case T_Integer:
9970                         n = makeIntConst(v->val.ival, location);
9971                         break;
9972
9973                 case T_String:
9974                 default:
9975                         n = makeStringConst(v->val.str, location);
9976                         break;
9977         }
9978
9979         return n;
9980 }
9981
9982 /* makeBoolAConst()
9983  * Create an A_Const string node and put it inside a boolean cast.
9984  */
9985 static Node *
9986 makeBoolAConst(bool state, int location)
9987 {
9988         A_Const *n = makeNode(A_Const);
9989
9990         n->val.type = T_String;
9991         n->val.val.str = (state ? "t" : "f");
9992         n->location = location;
9993
9994         return makeTypeCast((Node *)n, SystemTypeName("bool"), -1);
9995 }
9996
9997 /* makeOverlaps()
9998  * Create and populate a FuncCall node to support the OVERLAPS operator.
9999  */
10000 static FuncCall *
10001 makeOverlaps(List *largs, List *rargs, int location)
10002 {
10003         FuncCall *n = makeNode(FuncCall);
10004
10005         n->funcname = SystemFuncName("overlaps");
10006         if (list_length(largs) == 1)
10007                 largs = lappend(largs, largs);
10008         else if (list_length(largs) != 2)
10009                 ereport(ERROR,
10010                                 (errcode(ERRCODE_SYNTAX_ERROR),
10011                                  errmsg("wrong number of parameters on left side of OVERLAPS expression"),
10012                                  scanner_errposition(location)));
10013         if (list_length(rargs) == 1)
10014                 rargs = lappend(rargs, rargs);
10015         else if (list_length(rargs) != 2)
10016                 ereport(ERROR,
10017                                 (errcode(ERRCODE_SYNTAX_ERROR),
10018                                  errmsg("wrong number of parameters on right side of OVERLAPS expression"),
10019                                  scanner_errposition(location)));
10020         n->args = list_concat(largs, rargs);
10021         n->agg_star = FALSE;
10022         n->agg_distinct = FALSE;
10023         n->func_variadic = FALSE;
10024         n->location = location;
10025         return n;
10026 }
10027
10028 /* check_qualified_name --- check the result of qualified_name production
10029  *
10030  * It's easiest to let the grammar production for qualified_name allow
10031  * subscripts and '*', which we then must reject here.
10032  */
10033 static void
10034 check_qualified_name(List *names)
10035 {
10036         ListCell   *i;
10037
10038         foreach(i, names)
10039         {
10040                 if (!IsA(lfirst(i), String))
10041                         yyerror("syntax error");
10042         }
10043 }
10044
10045 /* check_func_name --- check the result of func_name production
10046  *
10047  * It's easiest to let the grammar production for func_name allow subscripts
10048  * and '*', which we then must reject here.
10049  */
10050 static List *
10051 check_func_name(List *names)
10052 {
10053         ListCell   *i;
10054
10055         foreach(i, names)
10056         {
10057                 if (!IsA(lfirst(i), String))
10058                         yyerror("syntax error");
10059         }
10060         return names;
10061 }
10062
10063 /* check_indirection --- check the result of indirection production
10064  *
10065  * We only allow '*' at the end of the list, but it's hard to enforce that
10066  * in the grammar, so do it here.
10067  */
10068 static List *
10069 check_indirection(List *indirection)
10070 {
10071         ListCell *l;
10072
10073         foreach(l, indirection)
10074         {
10075                 if (IsA(lfirst(l), A_Star))
10076                 {
10077                         if (lnext(l) != NULL)
10078                                 yyerror("improper use of \"*\"");
10079                 }
10080         }
10081         return indirection;
10082 }
10083
10084 /* extractArgTypes()
10085  * Given a list of FunctionParameter nodes, extract a list of just the
10086  * argument types (TypeNames) for input parameters only.  This is what
10087  * is needed to look up an existing function, which is what is wanted by
10088  * the productions that use this call.
10089  */
10090 static List *
10091 extractArgTypes(List *parameters)
10092 {
10093         List       *result = NIL;
10094         ListCell   *i;
10095
10096         foreach(i, parameters)
10097         {
10098                 FunctionParameter *p = (FunctionParameter *) lfirst(i);
10099
10100                 if (p->mode != FUNC_PARAM_OUT && p->mode != FUNC_PARAM_TABLE)
10101                         result = lappend(result, p->argType);
10102         }
10103         return result;
10104 }
10105
10106 /* findLeftmostSelect()
10107  * Find the leftmost component SelectStmt in a set-operation parsetree.
10108  */
10109 static SelectStmt *
10110 findLeftmostSelect(SelectStmt *node)
10111 {
10112         while (node && node->op != SETOP_NONE)
10113                 node = node->larg;
10114         Assert(node && IsA(node, SelectStmt) && node->larg == NULL);
10115         return node;
10116 }
10117
10118 /* insertSelectOptions()
10119  * Insert ORDER BY, etc into an already-constructed SelectStmt.
10120  *
10121  * This routine is just to avoid duplicating code in SelectStmt productions.
10122  */
10123 static void
10124 insertSelectOptions(SelectStmt *stmt,
10125                                         List *sortClause, List *lockingClause,
10126                                         Node *limitOffset, Node *limitCount,
10127                                         WithClause *withClause)
10128 {
10129         Assert(IsA(stmt, SelectStmt));
10130
10131         /*
10132          * Tests here are to reject constructs like
10133          *      (SELECT foo ORDER BY bar) ORDER BY baz
10134          */
10135         if (sortClause)
10136         {
10137                 if (stmt->sortClause)
10138                         ereport(ERROR,
10139                                         (errcode(ERRCODE_SYNTAX_ERROR),
10140                                          errmsg("multiple ORDER BY clauses not allowed"),
10141                                          scanner_errposition(exprLocation((Node *) sortClause))));
10142                 stmt->sortClause = sortClause;
10143         }
10144         /* We can handle multiple locking clauses, though */
10145         stmt->lockingClause = list_concat(stmt->lockingClause, lockingClause);
10146         if (limitOffset)
10147         {
10148                 if (stmt->limitOffset)
10149                         ereport(ERROR,
10150                                         (errcode(ERRCODE_SYNTAX_ERROR),
10151                                          errmsg("multiple OFFSET clauses not allowed"),
10152                                          scanner_errposition(exprLocation(limitOffset))));
10153                 stmt->limitOffset = limitOffset;
10154         }
10155         if (limitCount)
10156         {
10157                 if (stmt->limitCount)
10158                         ereport(ERROR,
10159                                         (errcode(ERRCODE_SYNTAX_ERROR),
10160                                          errmsg("multiple LIMIT clauses not allowed"),
10161                                          scanner_errposition(exprLocation(limitCount))));
10162                 stmt->limitCount = limitCount;
10163         }
10164         if (withClause)
10165         {
10166                 if (stmt->withClause)
10167                         ereport(ERROR,
10168                                         (errcode(ERRCODE_SYNTAX_ERROR),
10169                                          errmsg("multiple WITH clauses not allowed"),
10170                                          scanner_errposition(exprLocation((Node *) withClause))));
10171                 stmt->withClause = withClause;
10172         }
10173 }
10174
10175 static Node *
10176 makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
10177 {
10178         SelectStmt *n = makeNode(SelectStmt);
10179
10180         n->op = op;
10181         n->all = all;
10182         n->larg = (SelectStmt *) larg;
10183         n->rarg = (SelectStmt *) rarg;
10184         return (Node *) n;
10185 }
10186
10187 /* SystemFuncName()
10188  * Build a properly-qualified reference to a built-in function.
10189  */
10190 List *
10191 SystemFuncName(char *name)
10192 {
10193         return list_make2(makeString("pg_catalog"), makeString(name));
10194 }
10195
10196 /* SystemTypeName()
10197  * Build a properly-qualified reference to a built-in type.
10198  *
10199  * typmod is defaulted, but may be changed afterwards by caller.
10200  * Likewise for the location.
10201  */
10202 TypeName *
10203 SystemTypeName(char *name)
10204 {
10205         return makeTypeNameFromNameList(list_make2(makeString("pg_catalog"),
10206                                                                                            makeString(name)));
10207 }
10208
10209 /* doNegate()
10210  * Handle negation of a numeric constant.
10211  *
10212  * Formerly, we did this here because the optimizer couldn't cope with
10213  * indexquals that looked like "var = -4" --- it wants "var = const"
10214  * and a unary minus operator applied to a constant didn't qualify.
10215  * As of Postgres 7.0, that problem doesn't exist anymore because there
10216  * is a constant-subexpression simplifier in the optimizer.  However,
10217  * there's still a good reason for doing this here, which is that we can
10218  * postpone committing to a particular internal representation for simple
10219  * negative constants.  It's better to leave "-123.456" in string form
10220  * until we know what the desired type is.
10221  */
10222 static Node *
10223 doNegate(Node *n, int location)
10224 {
10225         if (IsA(n, A_Const))
10226         {
10227                 A_Const *con = (A_Const *)n;
10228
10229                 /* report the constant's location as that of the '-' sign */
10230                 con->location = location;
10231
10232                 if (con->val.type == T_Integer)
10233                 {
10234                         con->val.val.ival = -con->val.val.ival;
10235                         return n;
10236                 }
10237                 if (con->val.type == T_Float)
10238                 {
10239                         doNegateFloat(&con->val);
10240                         return n;
10241                 }
10242         }
10243
10244         return (Node *) makeSimpleA_Expr(AEXPR_OP, "-", NULL, n, location);
10245 }
10246
10247 static void
10248 doNegateFloat(Value *v)
10249 {
10250         char   *oldval = v->val.str;
10251
10252         Assert(IsA(v, Float));
10253         if (*oldval == '+')
10254                 oldval++;
10255         if (*oldval == '-')
10256                 v->val.str = oldval+1;  /* just strip the '-' */
10257         else
10258         {
10259                 char   *newval = (char *) palloc(strlen(oldval) + 2);
10260
10261                 *newval = '-';
10262                 strcpy(newval+1, oldval);
10263                 v->val.str = newval;
10264         }
10265 }
10266
10267 static Node *
10268 makeAArrayExpr(List *elements, int location)
10269 {
10270         A_ArrayExpr *n = makeNode(A_ArrayExpr);
10271
10272         n->elements = elements;
10273         n->location = location;
10274         return (Node *) n;
10275 }
10276
10277 static Node *
10278 makeXmlExpr(XmlExprOp op, char *name, List *named_args, List *args,
10279                         int location)
10280 {
10281         XmlExpr    *x = makeNode(XmlExpr);
10282
10283         x->op = op;
10284         x->name = name;
10285         /*
10286          * named_args is a list of ResTarget; it'll be split apart into separate
10287          * expression and name lists in transformXmlExpr().
10288          */
10289         x->named_args = named_args;
10290         x->arg_names = NIL;
10291         x->args = args;
10292         /* xmloption, if relevant, must be filled in by caller */
10293         /* type and typmod will be filled in during parse analysis */
10294         x->location = location;
10295         return (Node *) x;
10296 }
10297
10298 /* parser_init()
10299  * Initialize to parse one query string
10300  */
10301 void
10302 parser_init(void)
10303 {
10304         QueryIsRule = FALSE;
10305 }
10306
10307 /*
10308  * Merge the input and output parameters of a table function.
10309  */
10310 static List *
10311 mergeTableFuncParameters(List *func_args, List *columns)
10312 {
10313         ListCell   *lc;
10314
10315         /* Explicit OUT and INOUT parameters shouldn't be used in this syntax */
10316         foreach(lc, func_args)
10317         {
10318                 FunctionParameter *p = (FunctionParameter *) lfirst(lc);
10319
10320                 if (p->mode != FUNC_PARAM_IN && p->mode != FUNC_PARAM_VARIADIC)
10321                         ereport(ERROR,
10322                                         (errcode(ERRCODE_SYNTAX_ERROR),
10323                                          errmsg("OUT and INOUT arguments aren't allowed in TABLE functions")));
10324         }
10325
10326         return list_concat(func_args, columns);
10327 }
10328
10329 /*
10330  * Determine return type of a TABLE function.  A single result column
10331  * returns setof that column's type; otherwise return setof record.
10332  */
10333 static TypeName *
10334 TableFuncTypeName(List *columns)
10335 {
10336         TypeName *result;
10337
10338         if (list_length(columns) == 1)
10339         {
10340                 FunctionParameter *p = (FunctionParameter *) linitial(columns);
10341
10342                 result = (TypeName *) copyObject(p->argType);
10343         }
10344         else
10345                 result = SystemTypeName("record");
10346
10347         result->setof = true;
10348
10349         return result;
10350 }
10351
10352 /*
10353  * Must undefine base_yylex before including scan.c, since we want it
10354  * to create the function base_yylex not filtered_base_yylex.
10355  */
10356 #undef base_yylex
10357
10358 #include "scan.c"