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