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