]> granicus.if.org Git - postgresql/blob - src/backend/parser/gram.y
Add LOCALTIME and LOCALTIMESTAMP functions per SQL99 standard.
[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-2001, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $Header: /cvsroot/pgsql/src/backend/parser/gram.y,v 2.323 2002/06/15 03:00:03 thomas 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 inside parse_analyze() 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
53 #include "access/htup.h"
54 #include "catalog/index.h"
55 #include "catalog/namespace.h"
56 #include "catalog/pg_type.h"
57 #include "nodes/makefuncs.h"
58 #include "nodes/params.h"
59 #include "nodes/parsenodes.h"
60 #include "parser/gramparse.h"
61 #include "storage/lmgr.h"
62 #include "utils/numeric.h"
63 #include "utils/datetime.h"
64 #include "utils/date.h"
65
66 #ifdef MULTIBYTE
67 #include "mb/pg_wchar.h"
68 #else
69 #define GetStandardEncoding()   0               /* PG_SQL_ASCII */
70 #define GetStandardEncodingName()       "SQL_ASCII"
71 #endif
72
73 extern List *parsetree;                 /* final parse result is delivered here */
74
75 static bool QueryIsRule = FALSE;
76 static Oid      *param_type_info;
77 static int      pfunc_num_args;
78
79
80 /*
81  * If you need access to certain yacc-generated variables and find that
82  * they're static by default, uncomment the next line.  (this is not a
83  * problem, yet.)
84  */
85 /*#define __YYSCLASS*/
86
87 static Node *makeTypeCast(Node *arg, TypeName *typename);
88 static Node *makeStringConst(char *str, TypeName *typename);
89 static Node *makeIntConst(int val);
90 static Node *makeFloatConst(char *str);
91 static Node *makeAConst(Value *v);
92 static Node *makeRowExpr(List *opr, List *largs, List *rargs);
93 static SelectStmt *findLeftmostSelect(SelectStmt *node);
94 static void insertSelectOptions(SelectStmt *stmt,
95                                                                 List *sortClause, List *forUpdate,
96                                                                 Node *limitOffset, Node *limitCount);
97 static Node *makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg);
98 static Node *doNegate(Node *n);
99 static void doNegateFloat(Value *v);
100
101 #define MASK(b) (1 << (b))
102
103 %}
104
105
106 %union
107 {
108         int                                     ival;
109         char                            chr;
110         char                            *str;
111         const char                      *keyword;
112         bool                            boolean;
113         JoinType                        jtype;
114         List                            *list;
115         Node                            *node;
116         Value                           *value;
117         ColumnRef                       *columnref;
118
119         TypeName                        *typnam;
120         DefElem                         *defelt;
121         SortGroupBy                     *sortgroupby;
122         JoinExpr                        *jexpr;
123         IndexElem                       *ielem;
124         Alias                           *alias;
125         RangeVar                        *range;
126         A_Indices                       *aind;
127         ResTarget                       *target;
128         PrivTarget                      *privtarget;
129
130         InsertStmt                      *istmt;
131         VariableSetStmt         *vsetstmt;
132 }
133
134 %type <node>    stmt, schema_stmt,
135                 AlterDatabaseSetStmt, AlterGroupStmt, AlterSchemaStmt, AlterTableStmt,
136                 AlterUserStmt, AlterUserSetStmt, AnalyzeStmt,
137                 ClosePortalStmt, ClusterStmt, CommentStmt, ConstraintsSetStmt,
138                 CopyStmt, CreateAsStmt, CreateDomainStmt, CreateGroupStmt, CreatePLangStmt,
139                 CreateSchemaStmt, CreateSeqStmt, CreateStmt, CreateAssertStmt, CreateTrigStmt,
140                 CreateUserStmt, CreatedbStmt, CursorStmt, DefineStmt, DeleteStmt,
141                 DropGroupStmt, DropPLangStmt, DropSchemaStmt, DropStmt, DropAssertStmt, DropTrigStmt,
142                 DropRuleStmt, DropUserStmt, DropdbStmt, ExplainStmt, FetchStmt,
143                 GrantStmt, IndexStmt, InsertStmt, ListenStmt, LoadStmt, LockStmt,
144                 NotifyStmt, OptimizableStmt, CreateFunctionStmt, ReindexStmt,
145                 RemoveAggrStmt, RemoveFuncStmt, RemoveOperStmt,
146                 RenameStmt, RevokeStmt, RuleActionStmt, RuleActionStmtOrEmpty,
147                 RuleStmt, SelectStmt, TransactionStmt, TruncateStmt,
148                 UnlistenStmt, UpdateStmt, VacuumStmt, VariableResetStmt,
149                 VariableSetStmt, VariableShowStmt, ViewStmt, CheckPointStmt
150
151 %type <node>    select_no_parens, select_with_parens, select_clause,
152                                 simple_select
153
154 %type <node>    alter_column_default
155 %type <ival>    drop_behavior, opt_drop_behavior
156
157 %type <list>    createdb_opt_list, createdb_opt_item
158 %type <boolean> opt_equal
159
160 %type <ival>    opt_lock, lock_type
161 %type <boolean> opt_force, opt_or_replace
162
163 %type <list>    user_list
164
165 %type <list>    OptGroupList
166 %type <defelt>  OptGroupElem
167
168 %type <list>    OptUserList
169 %type <defelt>  OptUserElem
170
171 %type <str>             OptSchemaName
172 %type <list>    OptSchemaEltList
173
174 %type <boolean> TriggerActionTime, TriggerForSpec, opt_trusted, opt_procedural
175 %type <str>             opt_lancompiler
176
177 %type <str>             TriggerEvents
178 %type <value>   TriggerFuncArg
179
180 %type <str>             relation_name, copy_file_name, copy_delimiter, copy_null,
181                 database_name, access_method_clause, access_method, attr_name,
182                 index_name, name, function_name, file_name
183
184 %type <list>    func_name, handler_name, qual_Op, qual_all_Op, OptUseOp,
185                 opt_class, opt_validator
186
187 %type <range>   qualified_name, OptConstrFromTable
188
189 %type <str>             opt_id,
190                 all_Op, MathOp, opt_name, SpecialRuleRelation
191
192 %type <str>             opt_level, opt_encoding
193 %type <node>    grantee
194 %type <list>    grantee_list
195 %type <ival>    privilege
196 %type <list>    privileges, privilege_list
197 %type <privtarget> privilege_target
198 %type <node>    function_with_argtypes
199 %type <list>    function_with_argtypes_list
200 %type <chr>     TriggerOneEvent
201
202 %type <list>    stmtblock, stmtmulti,
203                 OptTableElementList, OptInherit, definition, opt_distinct,
204                 opt_with, func_args, func_args_list, func_as, createfunc_opt_list
205                 oper_argtypes, RuleActionList, RuleActionMulti,
206                 opt_column_list, columnList, opt_name_list,
207                 sort_clause, sortby_list, index_params, index_list, name_list,
208                 from_clause, from_list, opt_array_bounds, qualified_name_list,
209                 any_name, any_name_list, any_operator, expr_list, dotted_name, attrs,
210                 target_list, update_target_list, insert_column_list,
211                 insert_target_list,
212                 def_list, opt_indirection, group_clause, TriggerFuncArgs,
213                 select_limit, opt_select_limit
214
215 %type <range>   into_clause, OptTempTableName
216
217 %type <defelt>  createfunc_opt_item
218 %type <typnam>  func_arg, func_return, func_type, aggr_argtype
219
220 %type <boolean> opt_arg, TriggerForOpt, TriggerForType, OptTemp, OptWithOids
221
222 %type <list>    for_update_clause, opt_for_update_clause, update_list
223 %type <boolean> opt_all
224 %type <boolean> opt_table
225 %type <boolean> opt_chain, opt_trans
226
227 %type <node>    join_outer, join_qual
228 %type <jtype>   join_type
229
230 %type <list>    extract_list, overlay_list, position_list
231 %type <list>    substr_list, trim_list
232 %type <ival>    opt_interval
233 %type <node>    overlay_placing, substr_from, substr_for
234
235 %type <boolean> opt_binary, opt_using, opt_instead, opt_cursor
236 %type <boolean> opt_with_copy, index_opt_unique, opt_verbose, opt_full
237 %type <boolean> opt_freeze, analyze_keyword
238
239 %type <ival>    copy_dirn, direction, reindex_type, drop_type,
240                                 opt_column, event, comment_type
241
242 %type <ival>    fetch_how_many
243
244 %type <node>    select_limit_value, select_offset_value
245
246 %type <list>    OptSeqList
247 %type <defelt>  OptSeqElem
248
249 %type <istmt>   insert_rest
250
251 %type <vsetstmt>        set_rest
252
253 %type <node>    OptTableElement, ConstraintElem
254 %type <node>    columnDef
255 %type <defelt>  def_elem
256 %type <node>    def_arg, columnElem, where_clause, insert_column_item,
257                                 a_expr, b_expr, c_expr, AexprConst,
258                                 in_expr, having_clause, func_table
259 %type <list>    row_descriptor, row_list, in_expr_nodes
260 %type <node>    row_expr
261 %type <node>    case_expr, case_arg, when_clause, case_default
262 %type <list>    when_clause_list
263 %type <ival>    sub_type
264 %type <list>    OptCreateAs, CreateAsList
265 %type <node>    CreateAsElement
266 %type <value>   NumericOnly, FloatOnly, IntegerOnly
267 %type <columnref>       columnref
268 %type <alias>   alias_clause
269 %type <sortgroupby>             sortby
270 %type <ielem>   index_elem, func_index
271 %type <node>    table_ref
272 %type <jexpr>   joined_table
273 %type <range>   relation_expr
274 %type <target>  target_el, insert_target_el, update_target_el
275
276 %type <typnam>  Typename, SimpleTypename, ConstTypename,
277                                 GenericType, Numeric, opt_float, Character,
278                                 ConstDatetime, ConstInterval, Bit
279 %type <str>             character
280 %type <str>             extract_arg
281 %type <str>             opt_charset, opt_collate
282 %type <ival>    opt_numeric, opt_decimal
283 %type <boolean> opt_varying, opt_timezone
284
285 %type <ival>    Iconst
286 %type <str>             Sconst, comment_text
287 %type <str>             UserId, opt_boolean, ColId_or_Sconst
288 %type <list>    var_list, var_list_or_default
289 %type <str>             ColId, ColLabel, type_name
290 %type <node>    var_value, zone_value
291
292 %type <keyword> unreserved_keyword, func_name_keyword
293 %type <keyword> col_name_keyword, reserved_keyword
294
295 %type <node>    TableConstraint
296 %type <list>    ColQualList
297 %type <node>    ColConstraint, ColConstraintElem, ConstraintAttr
298 %type <ival>    key_actions, key_delete, key_update, key_reference
299 %type <str>             key_match
300 %type <ival>    ConstraintAttributeSpec, ConstraintDeferrabilitySpec,
301                                 ConstraintTimeSpec
302
303 %type <list>    constraints_set_list
304 %type <boolean> constraints_set_mode
305
306 %type <boolean> opt_as
307
308
309 /*
310  * If you make any token changes, update the keyword table in
311  * parser/keywords.c and add new keywords to the appropriate one of
312  * the reserved-or-not-so-reserved keyword lists, below.
313  */
314
315 /* ordinary key words in alphabetical order */
316 %token <keyword> ABORT_TRANS, ABSOLUTE, ACCESS, ACTION, ADD, AFTER,
317         AGGREGATE, ALL, ALTER, ANALYSE, ANALYZE, AND, ANY, AS, ASC, ASSERTION,
318         AT, AUTHORIZATION,
319
320         BACKWARD, BEFORE, BEGIN_TRANS, BETWEEN, BIGINT, BINARY, BIT, BOTH,
321         BOOLEAN, BY,
322
323         CACHE, CALLED, CASCADE, CASE, CAST, CHAIN, CHAR_P, CHARACTER,
324         CHARACTERISTICS, CHECK, CHECKPOINT, CLOSE, CLUSTER, COALESCE, COLLATE,
325         COLUMN, COMMENT, COMMIT, COMMITTED, CONSTRAINT, CONSTRAINTS, COPY,
326         CREATE, CREATEDB, CREATEUSER, CROSS, CURRENT_DATE, CURRENT_TIME,
327         CURRENT_TIMESTAMP, CURRENT_USER, CURSOR, CYCLE,
328
329         DATABASE, DAY_P, DEC, DECIMAL, DECLARE, DEFAULT, DEFERRABLE, DEFERRED,
330         DEFINER, DELETE_P, DELIMITERS, DESC, DISTINCT, DO, DOMAIN_P, DOUBLE, DROP,
331
332         EACH, ELSE, ENCODING, ENCRYPTED, END_TRANS, ESCAPE, EXCEPT, EXCLUSIVE,
333         EXECUTE, EXISTS, EXPLAIN, EXTERNAL, EXTRACT,
334
335         FALSE_P, FETCH, FLOAT_P, FOR, FORCE, FOREIGN, FORWARD, FREEZE, FROM,
336         FULL, FUNCTION,
337
338         GET, GLOBAL, GRANT, GROUP_P,
339         HANDLER, HAVING, HOUR_P,
340
341         ILIKE, IMMEDIATE, IMMUTABLE, IMPLICIT, IN_P, INCREMENT, INDEX, INHERITS,
342         INITIALLY, INNER_P, INOUT, INPUT, INSENSITIVE, INSERT, INSTEAD, INT,
343         INTEGER, INTERSECT, INTERVAL, INTO, INVOKER, IS, ISNULL, ISOLATION,
344
345         JOIN,
346         KEY,
347
348         LANCOMPILER, LANGUAGE, LEADING, LEFT, LEVEL, LIKE, LIMIT, LISTEN,
349         LOAD, LOCAL, LOCALTIME, LOCALTIMESTAMP, LOCATION, LOCK_P,
350
351         MATCH, MAXVALUE, MINUTE_P, MINVALUE, MODE, MONTH_P, MOVE,
352
353         NAMES, NATIONAL, NATURAL, NCHAR, NEW, NEXT, NO, NOCREATEDB,
354         NOCREATEUSER, NONE, NOT, NOTHING, NOTIFY, NOTNULL, NULL_P, NULLIF,
355         NUMERIC,
356
357         OF, OFF, OFFSET, OIDS, OLD, ON, ONLY, OPERATOR, OPTION, OR, ORDER,
358         OUT_P, OUTER_P, OVERLAPS, OVERLAY, OWNER,
359
360         PARTIAL, PASSWORD, PATH_P, PENDANT, PLACING, POSITION, PRECISION, PRIMARY,
361         PRIOR, PRIVILEGES, PROCEDURE, PROCEDURAL,
362
363         READ, REAL, REFERENCES, REINDEX, RELATIVE, RENAME, REPLACE, RESET,
364         RESTRICT, RETURNS, REVOKE, RIGHT, ROLLBACK, ROW, RULE,
365
366         SCHEMA, SCROLL, SECOND_P, SECURITY, SELECT, SEQUENCE, SERIALIZABLE,
367         SESSION, SESSION_USER, SET, SETOF, SHARE, SHOW, SIMILAR, SMALLINT, SOME,
368         STABLE, START, STATEMENT, STATISTICS, STDIN, STDOUT, STORAGE, STRICT,
369         SUBSTRING, SYSID,
370
371         TABLE, TEMP, TEMPLATE, TEMPORARY, THEN, TIME, TIMESTAMP, TO, TOAST,
372         TRAILING, TRANSACTION, TRIGGER, TRIM, TRUE_P, TRUNCATE, TRUSTED, TYPE_P,
373
374         UNENCRYPTED, UNION, UNIQUE, UNKNOWN, UNLISTEN, UNTIL, UPDATE, USAGE,
375         USER, USING,
376
377         VACUUM, VALID, VALIDATOR, VALUES, VARCHAR, VARYING, VERBOSE, VERSION, VIEW, VOLATILE,
378         WHEN, WHERE, WITH, WITHOUT, WORK,
379         YEAR_P,
380         ZONE
381
382 /* The grammar thinks these are keywords, but they are not in the keywords.c
383  * list and so can never be entered directly.  The filter in parser.c
384  * creates these tokens when required.
385  */
386 %token                  UNIONJOIN
387
388 /* Special keywords, not in the query language - see the "lex" file */
389 %token <str>    IDENT, FCONST, SCONST, BITCONST, Op
390 %token <ival>   ICONST, PARAM
391
392 /* these are not real. they are here so that they get generated as #define's*/
393 %token                  OP
394
395 /* precedence: lowest to highest */
396 %left           UNION EXCEPT
397 %left           INTERSECT
398 %left           JOIN UNIONJOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
399 %left           OR
400 %left           AND
401 %right          NOT
402 %right          '='
403 %nonassoc       '<' '>'
404 %nonassoc       LIKE ILIKE SIMILAR
405 %nonassoc       ESCAPE
406 %nonassoc       OVERLAPS
407 %nonassoc       BETWEEN
408 %nonassoc       IN_P
409 %left           POSTFIXOP               /* dummy for postfix Op rules */
410 %left           Op OPERATOR             /* multi-character ops and user-defined operators */
411 %nonassoc       NOTNULL
412 %nonassoc       ISNULL
413 %nonassoc       IS NULL_P TRUE_P FALSE_P UNKNOWN        /* sets precedence for IS NULL, etc */
414 %left           '+' '-'
415 %left           '*' '/' '%'
416 %left           '^'
417 /* Unary Operators */
418 %left           AT ZONE                 /* sets precedence for AT TIME ZONE */
419 %right          UMINUS
420 %left           '[' ']'
421 %left           '(' ')'
422 %left           COLLATE
423 %left           TYPECAST
424 %left           '.'
425 %%
426
427 /*
428  *      Handle comment-only lines, and ;; SELECT * FROM pg_class ;;;
429  *      psql already handles such cases, but other interfaces don't.
430  *      bjm 1999/10/05
431  */
432 stmtblock:  stmtmulti
433                                 { parsetree = $1; }
434                 ;
435
436 /* the thrashing around here is to discard "empty" statements... */
437 stmtmulti:  stmtmulti ';' stmt
438                                 { if ($3 != (Node *)NULL)
439                                         $$ = lappend($1, $3);
440                                   else
441                                         $$ = $1;
442                                 }
443                 | stmt
444                                 { if ($1 != (Node *)NULL)
445                                         $$ = makeList1($1);
446                                   else
447                                         $$ = NIL;
448                                 }
449                 ;
450
451 stmt : AlterDatabaseSetStmt
452                 | AlterGroupStmt
453                 | AlterSchemaStmt
454                 | AlterTableStmt
455                 | AlterUserStmt
456                 | AlterUserSetStmt
457                 | ClosePortalStmt
458                 | CopyStmt
459                 | CreateStmt
460                 | CreateAsStmt
461                 | CreateDomainStmt
462                 | CreateFunctionStmt
463                 | CreateSchemaStmt
464                 | CreateGroupStmt
465                 | CreateSeqStmt
466                 | CreatePLangStmt
467                 | CreateAssertStmt
468                 | CreateTrigStmt
469                 | CreateUserStmt
470                 | ClusterStmt
471                 | DefineStmt
472                 | DropStmt              
473                 | DropSchemaStmt
474                 | TruncateStmt
475                 | CommentStmt
476                 | DropGroupStmt
477                 | DropPLangStmt
478                 | DropAssertStmt
479                 | DropTrigStmt
480                 | DropRuleStmt
481                 | DropUserStmt
482                 | ExplainStmt
483                 | FetchStmt
484                 | GrantStmt
485                 | IndexStmt
486                 | ListenStmt
487                 | UnlistenStmt
488                 | LockStmt
489                 | NotifyStmt
490                 | ReindexStmt
491                 | RemoveAggrStmt
492                 | RemoveOperStmt
493                 | RemoveFuncStmt
494                 | RenameStmt
495                 | RevokeStmt
496                 | OptimizableStmt
497                 | RuleStmt
498                 | TransactionStmt
499                 | ViewStmt
500                 | LoadStmt
501                 | CreatedbStmt
502                 | DropdbStmt
503                 | VacuumStmt
504                 | AnalyzeStmt
505                 | VariableSetStmt
506                 | VariableShowStmt
507                 | VariableResetStmt
508                 | ConstraintsSetStmt
509                 | CheckPointStmt
510                 | /*EMPTY*/
511                         { $$ = (Node *)NULL; }
512                 ;
513
514 /*****************************************************************************
515  *
516  * Create a new Postgres DBMS user
517  *
518  *
519  *****************************************************************************/
520
521 CreateUserStmt:  CREATE USER UserId OptUserList 
522                                 {
523                                         CreateUserStmt *n = makeNode(CreateUserStmt);
524                                         n->user = $3;
525                                         n->options = $4;
526                                         $$ = (Node *)n;
527                                 }
528                         | CREATE USER UserId WITH OptUserList
529                                 {
530                                         CreateUserStmt *n = makeNode(CreateUserStmt);
531                                         n->user = $3;
532                                         n->options = $5;
533                                         $$ = (Node *)n;
534                                 }                   
535                 ;
536
537 /*****************************************************************************
538  *
539  * Alter a postgresql DBMS user
540  *
541  *
542  *****************************************************************************/
543
544 AlterUserStmt:  ALTER USER UserId OptUserList
545                                  {
546                                         AlterUserStmt *n = makeNode(AlterUserStmt);
547                                         n->user = $3;
548                                         n->options = $4;
549                                         $$ = (Node *)n;
550                                  }
551                             | ALTER USER UserId WITH OptUserList
552                                  {
553                                         AlterUserStmt *n = makeNode(AlterUserStmt);
554                                         n->user = $3;
555                                         n->options = $5;
556                                         $$ = (Node *)n;
557                                  }
558                 ;
559
560
561 AlterUserSetStmt: ALTER USER UserId SET set_rest
562                                 {
563                                         AlterUserSetStmt *n = makeNode(AlterUserSetStmt);
564                                         n->user = $3;
565                                         n->variable = $5->name;
566                                         n->value = $5->args;
567                                         $$ = (Node *)n;
568                                 }
569                                 | ALTER USER UserId VariableResetStmt
570                                 {
571                                         AlterUserSetStmt *n = makeNode(AlterUserSetStmt);
572                                         n->user = $3;
573                                         n->variable = ((VariableResetStmt *)$4)->name;
574                                         n->value = NIL;
575                                         $$ = (Node *)n;
576                                 }
577                 ;
578
579
580 /*****************************************************************************
581  *
582  * Drop a postgresql DBMS user
583  *
584  *
585  *****************************************************************************/
586
587 DropUserStmt:  DROP USER user_list
588                                 {
589                                         DropUserStmt *n = makeNode(DropUserStmt);
590                                         n->users = $3;
591                                         $$ = (Node *)n;
592                                 }
593                 ;
594
595 /*
596  * Options for CREATE USER and ALTER USER
597  */
598 OptUserList: OptUserList OptUserElem            { $$ = lappend($1, $2); }
599                         | /* EMPTY */                                   { $$ = NIL; }
600                 ;
601
602 OptUserElem:  PASSWORD Sconst
603                                 { 
604                                         $$ = makeNode(DefElem);
605                                         $$->defname = "password";
606                                         $$->arg = (Node *)makeString($2);
607                                 }
608                         | ENCRYPTED PASSWORD Sconst
609                                 { 
610                                         $$ = makeNode(DefElem);
611                                         $$->defname = "encryptedPassword";
612                                         $$->arg = (Node *)makeString($3);
613                                 }
614                         | UNENCRYPTED PASSWORD Sconst
615                                 { 
616                                         $$ = makeNode(DefElem);
617                                         $$->defname = "unencryptedPassword";
618                                         $$->arg = (Node *)makeString($3);
619                                 }
620                         | SYSID Iconst
621                                 {
622                                         $$ = makeNode(DefElem);
623                                         $$->defname = "sysid";
624                                         $$->arg = (Node *)makeInteger($2);
625                                 }
626                         | CREATEDB
627                                 { 
628                                         $$ = makeNode(DefElem);
629                                         $$->defname = "createdb";
630                                         $$->arg = (Node *)makeInteger(TRUE);
631                                 }
632                         | NOCREATEDB
633                                 { 
634                                         $$ = makeNode(DefElem);
635                                         $$->defname = "createdb";
636                                         $$->arg = (Node *)makeInteger(FALSE);
637                                 }
638                         | CREATEUSER
639                                 { 
640                                         $$ = makeNode(DefElem);
641                                         $$->defname = "createuser";
642                                         $$->arg = (Node *)makeInteger(TRUE);
643                                 }
644                         | NOCREATEUSER
645                                 { 
646                                         $$ = makeNode(DefElem);
647                                         $$->defname = "createuser";
648                                         $$->arg = (Node *)makeInteger(FALSE);
649                                 }
650                         | IN_P GROUP_P user_list
651                                 { 
652                                         $$ = makeNode(DefElem);
653                                         $$->defname = "groupElts";
654                                         $$->arg = (Node *)$3;
655                                 }
656                         | VALID UNTIL Sconst
657                                 { 
658                                         $$ = makeNode(DefElem);
659                                         $$->defname = "validUntil";
660                                         $$->arg = (Node *)makeString($3);
661                                 }
662                 ;
663
664 user_list:  user_list ',' UserId
665                                 {
666                                         $$ = lappend($1, makeString($3));
667                                 }
668                         | UserId
669                                 {
670                                         $$ = makeList1(makeString($1));
671                                 }
672                 ;
673
674
675
676 /*****************************************************************************
677  *
678  * Create a postgresql group
679  *
680  *
681  *****************************************************************************/
682
683 CreateGroupStmt:  CREATE GROUP_P UserId OptGroupList
684                                 {
685                                         CreateGroupStmt *n = makeNode(CreateGroupStmt);
686                                         n->name = $3;
687                                         n->options = $4;
688                                         $$ = (Node *)n;
689                                 }
690                         | CREATE GROUP_P UserId WITH OptGroupList
691                                 {
692                                         CreateGroupStmt *n = makeNode(CreateGroupStmt);
693                                         n->name = $3;
694                                         n->options = $5;
695                                         $$ = (Node *)n;
696                                 }
697                 ;
698
699 /*
700  * Options for CREATE GROUP
701  */
702 OptGroupList: OptGroupList OptGroupElem         { $$ = lappend($1, $2); }
703                         | /* EMPTY */                                   { $$ = NIL; }
704                 ;
705
706 OptGroupElem:  USER user_list
707                                 { 
708                                         $$ = makeNode(DefElem);
709                                         $$->defname = "userElts";
710                                         $$->arg = (Node *)$2;
711                                 }
712                         | SYSID Iconst
713                                 {
714                                         $$ = makeNode(DefElem);
715                                         $$->defname = "sysid";
716                                         $$->arg = (Node *)makeInteger($2);
717                                 }
718                 ;
719
720
721 /*****************************************************************************
722  *
723  * Alter a postgresql group
724  *
725  *
726  *****************************************************************************/
727
728 AlterGroupStmt:  ALTER GROUP_P UserId ADD USER user_list
729                                 {
730                                         AlterGroupStmt *n = makeNode(AlterGroupStmt);
731                                         n->name = $3;
732                                         n->action = +1;
733                                         n->listUsers = $6;
734                                         $$ = (Node *)n;
735                                 }
736                         | ALTER GROUP_P UserId DROP USER user_list
737                                 {
738                                         AlterGroupStmt *n = makeNode(AlterGroupStmt);
739                                         n->name = $3;
740                                         n->action = -1;
741                                         n->listUsers = $6;
742                                         $$ = (Node *)n;
743                                 }
744                         ;
745
746
747 /*****************************************************************************
748  *
749  * Drop a postgresql group
750  *
751  *
752  *****************************************************************************/
753
754 DropGroupStmt: DROP GROUP_P UserId
755                                 {
756                                         DropGroupStmt *n = makeNode(DropGroupStmt);
757                                         n->name = $3;
758                                         $$ = (Node *)n;
759                                 }
760                         ;
761
762
763 /*****************************************************************************
764  *
765  * Manipulate a schema
766  *
767  *
768  *****************************************************************************/
769
770 CreateSchemaStmt:  CREATE SCHEMA OptSchemaName AUTHORIZATION UserId OptSchemaEltList
771                                 {
772                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
773                                         /* One can omit the schema name or the authorization id... */
774                                         if ($3 != NULL)
775                                                 n->schemaname = $3;
776                                         else
777                                                 n->schemaname = $5;
778                                         n->authid = $5;
779                                         n->schemaElts = $6;
780                                         $$ = (Node *)n;
781                                 }
782                 | CREATE SCHEMA ColId OptSchemaEltList
783                                 {
784                                         CreateSchemaStmt *n = makeNode(CreateSchemaStmt);
785                                         /* ...but not both */
786                                         n->schemaname = $3;
787                                         n->authid = NULL;
788                                         n->schemaElts = $4;
789                                         $$ = (Node *)n;
790                                 }
791                 ;
792
793 AlterSchemaStmt:  ALTER SCHEMA ColId
794                                 {
795                                         elog(ERROR, "ALTER SCHEMA not yet supported");
796                                 }
797                 ;
798
799 DropSchemaStmt:  DROP SCHEMA ColId
800                                 {
801                                         elog(ERROR, "DROP SCHEMA not yet supported");
802                                 }
803                 ;
804
805 OptSchemaName: ColId                                                            { $$ = $1; }
806                 | /* EMPTY */                                                           { $$ = NULL; }
807                 ;
808
809 OptSchemaEltList: OptSchemaEltList schema_stmt          { $$ = lappend($1, $2); }
810                 | /* EMPTY */                                                           { $$ = NIL; }
811                 ;
812
813 /*
814  *      schema_stmt are the ones that can show up inside a CREATE SCHEMA
815  *      statement (in addition to by themselves).
816  */
817 schema_stmt: CreateStmt
818                 | GrantStmt
819                 | ViewStmt
820                 ;
821
822
823 /*****************************************************************************
824  *
825  * Set PG internal variable
826  *        SET name TO 'var_value'
827  * Include SQL92 syntax (thomas 1997-10-22):
828  *    SET TIME ZONE 'var_value'
829  *
830  *****************************************************************************/
831
832 VariableSetStmt:  SET set_rest
833                                 {
834                                         VariableSetStmt *n = $2;
835                                         n->is_local = false;
836                                         $$ = (Node *) n;
837                                 }
838                 | SET LOCAL set_rest
839                                 {
840                                         VariableSetStmt *n = $3;
841                                         n->is_local = true;
842                                         $$ = (Node *) n;
843                                 }
844                 | SET SESSION set_rest
845                                 {
846                                         VariableSetStmt *n = $3;
847                                         n->is_local = false;
848                                         $$ = (Node *) n;
849                                 }
850                 ;
851
852 set_rest:  ColId TO var_list_or_default
853                                 {
854                                         VariableSetStmt *n = makeNode(VariableSetStmt);
855                                         n->name = $1;
856                                         n->args = $3;
857                                         $$ = n;
858                                 }
859                 | ColId '=' var_list_or_default
860                                 {
861                                         VariableSetStmt *n = makeNode(VariableSetStmt);
862                                         n->name = $1;
863                                         n->args = $3;
864                                         $$ = n;
865                                 }
866                 | TIME ZONE zone_value
867                                 {
868                                         VariableSetStmt *n = makeNode(VariableSetStmt);
869                                         n->name = "timezone";
870                                         if ($3 != NULL)
871                                                 n->args = makeList1($3);
872                                         $$ = n;
873                                 }
874                 | TRANSACTION ISOLATION LEVEL opt_level
875                                 {
876                                         VariableSetStmt *n = makeNode(VariableSetStmt);
877                                         n->name = "TRANSACTION ISOLATION LEVEL";
878                                         n->args = makeList1(makeStringConst($4, NULL));
879                                         $$ = n;
880                                 }
881         | SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL opt_level
882                                 {
883                                         VariableSetStmt *n = makeNode(VariableSetStmt);
884                                         n->name = "default_transaction_isolation";
885                                         n->args = makeList1(makeStringConst($7, NULL));
886                                         $$ = n;
887                                 }
888                 | NAMES opt_encoding
889                                 {
890                                         VariableSetStmt *n = makeNode(VariableSetStmt);
891                                         n->name = "client_encoding";
892                                         if ($2 != NULL)
893                                                 n->args = makeList1(makeStringConst($2, NULL));
894                                         $$ = n;
895                                 }
896                 | SESSION AUTHORIZATION ColId_or_Sconst
897                                 {
898                                         VariableSetStmt *n = makeNode(VariableSetStmt);
899                                         n->name = "session_authorization";
900                                         n->args = makeList1(makeStringConst($3, NULL));
901                                         $$ = n;
902                                 }
903                 | SESSION AUTHORIZATION DEFAULT
904                                 {
905                                         VariableSetStmt *n = makeNode(VariableSetStmt);
906                                         n->name = "session_authorization";
907                                         n->args = NIL;
908                                         $$ = n;
909                                 }
910                 ;
911
912 var_list_or_default:  var_list
913                                 { $$ = $1; }
914                 | DEFAULT
915                                 { $$ = NIL; }
916                 ;
917
918 var_list:  var_value
919                                 {       $$ = makeList1($1); }
920                 | var_list ',' var_value
921                                 {       $$ = lappend($1, $3); }
922                 ;
923
924 var_value:  opt_boolean
925                                 { $$ = makeStringConst($1, NULL); }
926                 | ColId_or_Sconst
927                                 { $$ = makeStringConst($1, NULL); }
928                 | NumericOnly
929                                 { $$ = makeAConst($1); }
930                 ;
931
932 opt_level:  READ COMMITTED                                      { $$ = "read committed"; }
933                 | SERIALIZABLE                                          { $$ = "serializable"; }
934                 ;
935
936 opt_boolean:  TRUE_P                                            { $$ = "true"; }
937                 | FALSE_P                                                       { $$ = "false"; }
938                 | ON                                                            { $$ = "on"; }
939                 | OFF                                                           { $$ = "off"; }
940                 ;
941
942 /* Timezone values can be:
943  * - a string such as 'pst8pdt'
944  * - an identifier such as "pst8pdt"
945  * - an integer or floating point number
946  * - a time interval per SQL99
947  * ColId gives reduce/reduce errors against ConstInterval and LOCAL,
948  * so use IDENT and reject anything which is a reserved word.
949  */
950 zone_value:  Sconst
951                         {
952                                 $$ = makeStringConst($1, NULL);
953                         }
954                 | IDENT
955                         {
956                                 $$ = makeStringConst($1, NULL);
957                         }
958                 | ConstInterval Sconst opt_interval
959                         {
960                                 A_Const *n = (A_Const *) makeStringConst($2, $1);
961                                 if ($3 != -1)
962                                 {
963                                         if (($3 & ~(MASK(HOUR) | MASK(MINUTE))) != 0)
964                                                 elog(ERROR, "Time zone interval must be HOUR or HOUR TO MINUTE");
965                                         n->typename->typmod = ((($3 & 0x7FFF) << 16) | 0xFFFF);
966                                 }
967                                 $$ = (Node *)n;
968                         }
969                 | ConstInterval '(' Iconst ')' Sconst opt_interval
970                         {
971                                 A_Const *n = (A_Const *) makeStringConst($5, $1);
972                                 if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
973                                         elog(ERROR, "INTERVAL(%d) precision must be between %d and %d",
974                                                  $3, 0, MAX_INTERVAL_PRECISION);
975                                 if ($6 != -1)
976                                 {
977                                         if (($6 & ~(MASK(HOUR) | MASK(MINUTE))) != 0)
978                                                 elog(ERROR, "Time zone interval must be HOUR or HOUR TO MINUTE");
979                                         n->typename->typmod = ((($6 & 0x7FFF) << 16) | $3);
980                                 }
981                                 else
982                                 {
983                                         n->typename->typmod = ((0x7FFF << 16) | $3);
984                                 }
985
986                                 $$ = (Node *)n;
987                         }
988                 | NumericOnly                                           { $$ = makeAConst($1); }
989                 | DEFAULT                                                       { $$ = NULL; }
990                 | LOCAL                                                         { $$ = NULL; }
991                 ;
992
993 opt_encoding:  Sconst                                           { $$ = $1; }
994         | DEFAULT                                                       { $$ = NULL; }
995         | /*EMPTY*/                                                     { $$ = NULL; }
996         ;
997
998 ColId_or_Sconst: ColId                                          { $$ = $1; }
999                 | SCONST                                                        { $$ = $1; }
1000                 ;
1001
1002
1003 VariableShowStmt:  SHOW ColId
1004                                 {
1005                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1006                                         n->name = $2;
1007                                         $$ = (Node *) n;
1008                                 }
1009                 | SHOW TIME ZONE
1010                                 {
1011                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1012                                         n->name = "timezone";
1013                                         $$ = (Node *) n;
1014                                 }
1015                 | SHOW TRANSACTION ISOLATION LEVEL
1016                                 {
1017                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1018                                         n->name = "TRANSACTION ISOLATION LEVEL";
1019                                         $$ = (Node *) n;
1020                                 }
1021                 | SHOW SESSION AUTHORIZATION
1022                                 {
1023                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1024                                         n->name = "session_authorization";
1025                                         $$ = (Node *) n;
1026                                 }
1027                 | SHOW ALL
1028                                 {
1029                                         VariableShowStmt *n = makeNode(VariableShowStmt);
1030                                         n->name = "all";
1031                                         $$ = (Node *) n;
1032                                 }
1033                 ;
1034
1035 VariableResetStmt:      RESET ColId
1036                                 {
1037                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1038                                         n->name = $2;
1039                                         $$ = (Node *) n;
1040                                 }
1041                 | RESET TIME ZONE
1042                                 {
1043                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1044                                         n->name = "timezone";
1045                                         $$ = (Node *) n;
1046                                 }
1047                 | RESET TRANSACTION ISOLATION LEVEL
1048                                 {
1049                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1050                                         n->name = "TRANSACTION ISOLATION LEVEL";
1051                                         $$ = (Node *) n;
1052                                 }
1053                 | RESET SESSION AUTHORIZATION
1054                                 {
1055                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1056                                         n->name = "session_authorization";
1057                                         $$ = (Node *) n;
1058                                 }
1059                 | RESET ALL
1060                                 {
1061                                         VariableResetStmt *n = makeNode(VariableResetStmt);
1062                                         n->name = "all";
1063                                         $$ = (Node *) n;
1064                                 }
1065                 ;
1066
1067
1068 ConstraintsSetStmt:     SET CONSTRAINTS constraints_set_list constraints_set_mode
1069                                 {
1070                                         ConstraintsSetStmt *n = makeNode(ConstraintsSetStmt);
1071                                         n->constraints = $3;
1072                                         n->deferred    = $4;
1073                                         $$ = (Node *) n;
1074                                 }
1075                 ;
1076
1077 constraints_set_list:   ALL                                     { $$ = NIL; }
1078                 | name_list                                                     { $$ = $1; }
1079                 ;
1080
1081 constraints_set_mode:   DEFERRED                        { $$ = TRUE; }
1082                 | IMMEDIATE                                                     { $$ = FALSE; }
1083                 ;
1084
1085
1086 /*
1087  * Checkpoint statement
1088  */
1089 CheckPointStmt: CHECKPOINT
1090                                 {
1091                                         CheckPointStmt *n = makeNode(CheckPointStmt);
1092                                         $$ = (Node *)n;
1093                                 }
1094                         ;
1095
1096 /*****************************************************************************
1097  *
1098  *      ALTER TABLE variations
1099  *
1100  *****************************************************************************/
1101
1102 AlterTableStmt:
1103 /* ALTER TABLE <relation> ADD [COLUMN] <coldef> */
1104                 ALTER TABLE relation_expr ADD opt_column columnDef
1105                                 {
1106                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1107                                         n->subtype = 'A';
1108                                         n->relation = $3;
1109                                         n->def = $6;
1110                                         $$ = (Node *)n;
1111                                 }
1112 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
1113                 | ALTER TABLE relation_expr ALTER opt_column ColId alter_column_default
1114                                 {
1115                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1116                                         n->subtype = 'T';
1117                                         n->relation = $3;
1118                                         n->name = $6;
1119                                         n->def = $7;
1120                                         $$ = (Node *)n;
1121                                 }
1122 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> DROP NOT NULL */
1123                 | ALTER TABLE relation_expr ALTER opt_column ColId DROP NOT NULL_P
1124                                 {
1125                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1126                                         n->subtype = 'N';
1127                                         n->relation = $3;
1128                                         n->name = $6;
1129                                         $$ = (Node *)n;
1130                                 }
1131 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET NOT NULL */
1132                 | ALTER TABLE relation_expr ALTER opt_column ColId SET NOT NULL_P
1133                                 {
1134                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1135                                         n->subtype = 'O';
1136                                         n->relation = $3;
1137                                         n->name = $6;
1138                                         $$ = (Node *)n;
1139                                 }
1140 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STATISTICS <Iconst> */
1141                 | ALTER TABLE relation_expr ALTER opt_column ColId SET STATISTICS Iconst
1142                                 {
1143                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1144                                         n->subtype = 'S';
1145                                         n->relation = $3;
1146                                         n->name = $6;
1147                                         n->def = (Node *) makeInteger($9);
1148                                         $$ = (Node *)n;
1149                                 }
1150 /* ALTER TABLE <relation> ALTER [COLUMN] <colname> SET STORAGE <storagemode> */
1151         | ALTER TABLE relation_expr ALTER opt_column ColId SET STORAGE ColId
1152                 {
1153                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1154                                         n->subtype = 'M';
1155                                         n->relation = $3;
1156                                         n->name = $6;
1157                                         n->def = (Node *) makeString($9);
1158                                         $$ = (Node *)n;
1159                                 }
1160 /* ALTER TABLE <relation> DROP [COLUMN] <colname> {RESTRICT|CASCADE} */
1161                 | ALTER TABLE relation_expr DROP opt_column ColId drop_behavior
1162                                 {
1163                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1164                                         n->subtype = 'D';
1165                                         n->relation = $3;
1166                                         n->name = $6;
1167                                         n->behavior = $7;
1168                                         $$ = (Node *)n;
1169                                 }
1170 /* ALTER TABLE <relation> ADD CONSTRAINT ... */
1171                 | ALTER TABLE relation_expr ADD TableConstraint
1172                                 {
1173                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1174                                         n->subtype = 'C';
1175                                         n->relation = $3;
1176                                         n->def = $5;
1177                                         $$ = (Node *)n;
1178                                 }
1179 /* ALTER TABLE <relation> DROP CONSTRAINT <name> {RESTRICT|CASCADE} */
1180                 | ALTER TABLE relation_expr DROP CONSTRAINT name drop_behavior
1181                                 {
1182                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1183                                         n->subtype = 'X';
1184                                         n->relation = $3;
1185                                         n->name = $6;
1186                                         n->behavior = $7;
1187                                         $$ = (Node *)n;
1188                                 }
1189 /* ALTER TABLE <name> CREATE TOAST TABLE */
1190                 | ALTER TABLE qualified_name CREATE TOAST TABLE
1191                                 {
1192                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1193                                         n->subtype = 'E';
1194                                         $3->inhOpt = INH_NO;
1195                                         n->relation = $3;
1196                                         $$ = (Node *)n;
1197                                 }
1198 /* ALTER TABLE <name> OWNER TO UserId */
1199                 | ALTER TABLE qualified_name OWNER TO UserId
1200                                 {
1201                                         AlterTableStmt *n = makeNode(AlterTableStmt);
1202                                         n->subtype = 'U';
1203                                         $3->inhOpt = INH_NO;
1204                                         n->relation = $3;
1205                                         n->name = $6;
1206                                         $$ = (Node *)n;
1207                                 }
1208                 ;
1209
1210 alter_column_default:
1211                 SET DEFAULT a_expr
1212                         {
1213                                 /* Treat SET DEFAULT NULL the same as DROP DEFAULT */
1214                                 if (exprIsNullConstant($3))
1215                                         $$ = NULL;
1216                                 else
1217                                         $$ = $3;
1218                         }
1219                 | DROP DEFAULT                                  { $$ = NULL; }
1220         ;
1221
1222 drop_behavior: CASCADE                                  { $$ = CASCADE; }
1223                 | RESTRICT                                              { $$ = RESTRICT; }
1224         ;
1225
1226 opt_drop_behavior: CASCADE                              { $$ = CASCADE; }
1227                 | RESTRICT                                              { $$ = RESTRICT; }
1228                 | /* EMPTY */                                   { $$ = RESTRICT; /* default */ }
1229                 ;
1230
1231
1232
1233 /*****************************************************************************
1234  *
1235  *              QUERY :
1236  *                              close <optname>
1237  *
1238  *****************************************************************************/
1239
1240 ClosePortalStmt:  CLOSE opt_id
1241                                 {
1242                                         ClosePortalStmt *n = makeNode(ClosePortalStmt);
1243                                         n->portalname = $2;
1244                                         $$ = (Node *)n;
1245                                 }
1246                 ;
1247
1248 opt_id:  ColId                                                                  { $$ = $1; }
1249                 | /*EMPTY*/                                                             { $$ = NULL; }
1250                 ;
1251
1252
1253 /*****************************************************************************
1254  *
1255  *              QUERY :
1256  *                              COPY [BINARY] <relname> FROM/TO
1257  *                              [USING DELIMITERS <delimiter>]
1258  *
1259  *****************************************************************************/
1260
1261 CopyStmt:  COPY opt_binary qualified_name opt_with_copy copy_dirn copy_file_name copy_delimiter copy_null
1262                                 {
1263                                         CopyStmt *n = makeNode(CopyStmt);
1264                                         n->binary = $2;
1265                                         n->relation = $3;
1266                                         n->oids = $4;
1267                                         n->direction = $5;
1268                                         n->filename = $6;
1269                                         n->delimiter = $7;
1270                                         n->null_print = $8;
1271                                         $$ = (Node *)n;
1272                                 }
1273                 ;
1274
1275 copy_dirn:      TO
1276                                 { $$ = TO; }
1277                 | FROM
1278                                 { $$ = FROM; }
1279                 ;
1280
1281 /*
1282  * copy_file_name NULL indicates stdio is used. Whether stdin or stdout is
1283  * used depends on the direction. (It really doesn't make sense to copy from
1284  * stdout. We silently correct the "typo".               - AY 9/94
1285  */
1286 copy_file_name:  Sconst                                                 { $$ = $1; }
1287                 | STDIN                                                                 { $$ = NULL; }
1288                 | STDOUT                                                                { $$ = NULL; }
1289                 ;
1290
1291 opt_binary:  BINARY                                                             { $$ = TRUE; }
1292                 | /*EMPTY*/                                                             { $$ = FALSE; }
1293                 ;
1294
1295 opt_with_copy:  WITH OIDS                                               { $$ = TRUE; }
1296                 | /*EMPTY*/                                                             { $$ = FALSE; }
1297                 ;
1298
1299 /*
1300  * the default copy delimiter is tab but the user can configure it
1301  */
1302 copy_delimiter:  opt_using DELIMITERS Sconst    { $$ = $3; }
1303                 | /*EMPTY*/                                                             { $$ = "\t"; }
1304                 ;
1305
1306 opt_using:      USING                                                           { $$ = TRUE; }
1307                 | /*EMPTY*/                                                             { $$ = TRUE; }
1308                 ;
1309
1310 copy_null:  WITH NULL_P AS Sconst                               { $$ = $4; }
1311                 | /*EMPTY*/                                                             { $$ = "\\N"; }
1312                 ;
1313
1314 /*****************************************************************************
1315  *
1316  *              QUERY :
1317  *                              CREATE relname
1318  *
1319  *****************************************************************************/
1320
1321 CreateStmt:  CREATE OptTemp TABLE qualified_name '(' OptTableElementList ')' OptInherit OptWithOids
1322                                 {
1323                                         CreateStmt *n = makeNode(CreateStmt);
1324                                         $4->istemp = $2;
1325                                         n->relation = $4;
1326                                         n->tableElts = $6;
1327                                         n->inhRelations = $8;
1328                                         n->constraints = NIL;
1329                                         n->hasoids = $9;
1330                                         $$ = (Node *)n;
1331                                 }
1332                 ;
1333
1334 /*
1335  * Redundancy here is needed to avoid shift/reduce conflicts,
1336  * since TEMP is not a reserved word.  See also OptTempTableName.
1337  */
1338 OptTemp:      TEMPORARY                                         { $$ = TRUE; }
1339                         | TEMP                                                  { $$ = TRUE; }
1340                         | LOCAL TEMPORARY                               { $$ = TRUE; }
1341                         | LOCAL TEMP                                    { $$ = TRUE; }
1342                         | GLOBAL TEMPORARY
1343                                 {
1344                                         elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
1345                                         $$ = TRUE;
1346                                 }
1347                         | GLOBAL TEMP
1348                                 {
1349                                         elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
1350                                         $$ = TRUE;
1351                                 }
1352                         | /*EMPTY*/                                             { $$ = FALSE; }
1353                 ;
1354
1355 OptTableElementList:  OptTableElementList ',' OptTableElement
1356                                 {
1357                                         if ($3 != NULL)
1358                                                 $$ = lappend($1, $3);
1359                                         else
1360                                                 $$ = $1;
1361                                 }
1362                         | OptTableElement
1363                                 {
1364                                         if ($1 != NULL)
1365                                                 $$ = makeList1($1);
1366                                         else
1367                                                 $$ = NIL;
1368                                 }
1369                         | /*EMPTY*/                                                     { $$ = NIL; }
1370                 ;
1371
1372 OptTableElement:  columnDef                                             { $$ = $1; }
1373                         | TableConstraint                                       { $$ = $1; }
1374                 ;
1375
1376 columnDef:  ColId Typename ColQualList opt_collate
1377                                 {
1378                                         ColumnDef *n = makeNode(ColumnDef);
1379                                         n->colname = $1;
1380                                         n->typename = $2;
1381                                         n->constraints = $3;
1382
1383                                         if ($4 != NULL)
1384                                                 elog(NOTICE, "CREATE TABLE / COLLATE %s not yet implemented"
1385                                                          "; clause ignored", $4);
1386
1387                                         $$ = (Node *)n;
1388                                 }
1389                 ;
1390
1391 ColQualList:  ColQualList ColConstraint         { $$ = lappend($1, $2); }
1392                         | /*EMPTY*/                                             { $$ = NIL; }
1393                 ;
1394
1395 ColConstraint:
1396                 CONSTRAINT name ColConstraintElem
1397                                 {
1398                                         switch (nodeTag($3))
1399                                         {
1400                                                 case T_Constraint:
1401                                                         {
1402                                                                 Constraint *n = (Constraint *)$3;
1403                                                                 n->name = $2;
1404                                                         }
1405                                                         break;
1406                                                 case T_FkConstraint:
1407                                                         {
1408                                                                 FkConstraint *n = (FkConstraint *)$3;
1409                                                                 n->constr_name = $2;
1410                                                         }
1411                                                         break;
1412                                                 default:
1413                                                         break;
1414                                         }
1415                                         $$ = $3;
1416                                 }
1417                 | ColConstraintElem
1418                                 { $$ = $1; }
1419                 | ConstraintAttr
1420                                 { $$ = $1; }
1421                 ;
1422
1423 /* DEFAULT NULL is already the default for Postgres.
1424  * But define it here and carry it forward into the system
1425  * to make it explicit.
1426  * - thomas 1998-09-13
1427  *
1428  * WITH NULL and NULL are not SQL92-standard syntax elements,
1429  * so leave them out. Use DEFAULT NULL to explicitly indicate
1430  * that a column may have that value. WITH NULL leads to
1431  * shift/reduce conflicts with WITH TIME ZONE anyway.
1432  * - thomas 1999-01-08
1433  *
1434  * DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
1435  * conflict on NOT (since NOT might start a subsequent NOT NULL constraint,
1436  * or be part of a_expr NOT LIKE or similar constructs).
1437  */
1438 ColConstraintElem:
1439                           NOT NULL_P
1440                                 {
1441                                         Constraint *n = makeNode(Constraint);
1442                                         n->contype = CONSTR_NOTNULL;
1443                                         n->name = NULL;
1444                                         n->raw_expr = NULL;
1445                                         n->cooked_expr = NULL;
1446                                         n->keys = NULL;
1447                                         $$ = (Node *)n;
1448                                 }
1449                         | NULL_P
1450                                 {
1451                                         Constraint *n = makeNode(Constraint);
1452                                         n->contype = CONSTR_NULL;
1453                                         n->name = NULL;
1454                                         n->raw_expr = NULL;
1455                                         n->cooked_expr = NULL;
1456                                         n->keys = NULL;
1457                                         $$ = (Node *)n;
1458                                 }
1459                         | UNIQUE
1460                                 {
1461                                         Constraint *n = makeNode(Constraint);
1462                                         n->contype = CONSTR_UNIQUE;
1463                                         n->name = NULL;
1464                                         n->raw_expr = NULL;
1465                                         n->cooked_expr = NULL;
1466                                         n->keys = NULL;
1467                                         $$ = (Node *)n;
1468                                 }
1469                         | PRIMARY KEY
1470                                 {
1471                                         Constraint *n = makeNode(Constraint);
1472                                         n->contype = CONSTR_PRIMARY;
1473                                         n->name = NULL;
1474                                         n->raw_expr = NULL;
1475                                         n->cooked_expr = NULL;
1476                                         n->keys = NULL;
1477                                         $$ = (Node *)n;
1478                                 }
1479                         | CHECK '(' a_expr ')'
1480                                 {
1481                                         Constraint *n = makeNode(Constraint);
1482                                         n->contype = CONSTR_CHECK;
1483                                         n->name = NULL;
1484                                         n->raw_expr = $3;
1485                                         n->cooked_expr = NULL;
1486                                         n->keys = NULL;
1487                                         $$ = (Node *)n;
1488                                 }
1489                         | DEFAULT b_expr
1490                                 {
1491                                         Constraint *n = makeNode(Constraint);
1492                                         n->contype = CONSTR_DEFAULT;
1493                                         n->name = NULL;
1494                                         if (exprIsNullConstant($2))
1495                                         {
1496                                                 /* DEFAULT NULL should be reported as empty expr */
1497                                                 n->raw_expr = NULL;
1498                                         }
1499                                         else
1500                                         {
1501                                                 n->raw_expr = $2;
1502                                         }
1503                                         n->cooked_expr = NULL;
1504                                         n->keys = NULL;
1505                                         $$ = (Node *)n;
1506                                 }
1507                         | REFERENCES qualified_name opt_column_list key_match key_actions 
1508                                 {
1509                                         FkConstraint *n = makeNode(FkConstraint);
1510                                         n->constr_name          = NULL;
1511                                         n->pktable                      = $2;
1512                                         n->fk_attrs                     = NIL;
1513                                         n->pk_attrs                     = $3;
1514                                         n->match_type           = $4;
1515                                         n->actions                      = $5;
1516                                         n->deferrable           = FALSE;
1517                                         n->initdeferred         = FALSE;
1518                                         $$ = (Node *)n;
1519                                 }
1520                 ;
1521
1522 /*
1523  * ConstraintAttr represents constraint attributes, which we parse as if
1524  * they were independent constraint clauses, in order to avoid shift/reduce
1525  * conflicts (since NOT might start either an independent NOT NULL clause
1526  * or an attribute).  analyze.c is responsible for attaching the attribute
1527  * information to the preceding "real" constraint node, and for complaining
1528  * if attribute clauses appear in the wrong place or wrong combinations.
1529  *
1530  * See also ConstraintAttributeSpec, which can be used in places where
1531  * there is no parsing conflict.
1532  */
1533 ConstraintAttr: DEFERRABLE
1534                                 {
1535                                         Constraint *n = makeNode(Constraint);
1536                                         n->contype = CONSTR_ATTR_DEFERRABLE;
1537                                         $$ = (Node *)n;
1538                                 }
1539                         | NOT DEFERRABLE
1540                                 {
1541                                         Constraint *n = makeNode(Constraint);
1542                                         n->contype = CONSTR_ATTR_NOT_DEFERRABLE;
1543                                         $$ = (Node *)n;
1544                                 }
1545                         | INITIALLY DEFERRED
1546                                 {
1547                                         Constraint *n = makeNode(Constraint);
1548                                         n->contype = CONSTR_ATTR_DEFERRED;
1549                                         $$ = (Node *)n;
1550                                 }
1551                         | INITIALLY IMMEDIATE
1552                                 {
1553                                         Constraint *n = makeNode(Constraint);
1554                                         n->contype = CONSTR_ATTR_IMMEDIATE;
1555                                         $$ = (Node *)n;
1556                                 }
1557                 ;
1558
1559
1560 /* ConstraintElem specifies constraint syntax which is not embedded into
1561  *  a column definition. ColConstraintElem specifies the embedded form.
1562  * - thomas 1997-12-03
1563  */
1564 TableConstraint:  CONSTRAINT name ConstraintElem
1565                                 {
1566                                         switch (nodeTag($3))
1567                                         {
1568                                                 case T_Constraint:
1569                                                         {
1570                                                                 Constraint *n = (Constraint *)$3;
1571                                                                 n->name = $2;
1572                                                         }
1573                                                         break;
1574                                                 case T_FkConstraint:
1575                                                         {
1576                                                                 FkConstraint *n = (FkConstraint *)$3;
1577                                                                 n->constr_name = $2;
1578                                                         }
1579                                                         break;
1580                                                 default:
1581                                                         break;
1582                                         }
1583                                         $$ = $3;
1584                                 }
1585                 | ConstraintElem
1586                                 { $$ = $1; }
1587                 ;
1588
1589 ConstraintElem:  CHECK '(' a_expr ')'
1590                                 {
1591                                         Constraint *n = makeNode(Constraint);
1592                                         n->contype = CONSTR_CHECK;
1593                                         n->name = NULL;
1594                                         n->raw_expr = $3;
1595                                         n->cooked_expr = NULL;
1596                                         $$ = (Node *)n;
1597                                 }
1598                 | UNIQUE '(' columnList ')'
1599                                 {
1600                                         Constraint *n = makeNode(Constraint);
1601                                         n->contype = CONSTR_UNIQUE;
1602                                         n->name = NULL;
1603                                         n->raw_expr = NULL;
1604                                         n->cooked_expr = NULL;
1605                                         n->keys = $3;
1606                                         $$ = (Node *)n;
1607                                 }
1608                 | PRIMARY KEY '(' columnList ')'
1609                                 {
1610                                         Constraint *n = makeNode(Constraint);
1611                                         n->contype = CONSTR_PRIMARY;
1612                                         n->name = NULL;
1613                                         n->raw_expr = NULL;
1614                                         n->cooked_expr = NULL;
1615                                         n->keys = $4;
1616                                         $$ = (Node *)n;
1617                                 }
1618                 | FOREIGN KEY '(' columnList ')' REFERENCES qualified_name opt_column_list
1619                                 key_match key_actions ConstraintAttributeSpec
1620                                 {
1621                                         FkConstraint *n = makeNode(FkConstraint);
1622                                         n->constr_name          = NULL;
1623                                         n->pktable                      = $7;
1624                                         n->fk_attrs                     = $4;
1625                                         n->pk_attrs                     = $8;
1626                                         n->match_type           = $9;
1627                                         n->actions                      = $10;
1628                                         n->deferrable           = ($11 & 1) != 0;
1629                                         n->initdeferred         = ($11 & 2) != 0;
1630                                         $$ = (Node *)n;
1631                                 }
1632                 ;
1633
1634 opt_column_list:  '(' columnList ')'                    { $$ = $2; }
1635                 | /*EMPTY*/                                                             { $$ = NIL; }
1636                 ;
1637
1638 columnList:  columnList ',' columnElem
1639                                 { $$ = lappend($1, $3); }
1640                 | columnElem
1641                                 { $$ = makeList1($1); }
1642                 ;
1643
1644 columnElem:  ColId
1645                                 {
1646                                         Ident *id = makeNode(Ident);
1647                                         id->name = $1;
1648                                         $$ = (Node *)id;
1649                                 }
1650                 ;
1651
1652 key_match:  MATCH FULL
1653                         {
1654                                 $$ = "FULL";
1655                         }
1656                 | MATCH PARTIAL
1657                         {
1658                                 elog(ERROR, "FOREIGN KEY/MATCH PARTIAL not yet implemented");
1659                                 $$ = "PARTIAL";
1660                         }
1661                 | /*EMPTY*/
1662                         {
1663                                 $$ = "UNSPECIFIED";
1664                         }
1665                 ;
1666
1667 key_actions:  key_delete                                { $$ = $1; }
1668                 | key_update                                    { $$ = $1; }
1669                 | key_delete key_update                 { $$ = $1 | $2; }
1670                 | key_update key_delete                 { $$ = $1 | $2; }
1671                 | /*EMPTY*/                                             { $$ = 0; }
1672                 ;
1673
1674 key_delete:  ON DELETE_P key_reference  { $$ = $3 << FKCONSTR_ON_DELETE_SHIFT; }
1675                 ;
1676
1677 key_update:  ON UPDATE key_reference    { $$ = $3 << FKCONSTR_ON_UPDATE_SHIFT; }
1678                 ;
1679
1680 key_reference:  NO ACTION                               { $$ = FKCONSTR_ON_KEY_NOACTION; }
1681                 | RESTRICT                                              { $$ = FKCONSTR_ON_KEY_RESTRICT; }
1682                 | CASCADE                                               { $$ = FKCONSTR_ON_KEY_CASCADE; }
1683                 | SET NULL_P                                    { $$ = FKCONSTR_ON_KEY_SETNULL; }
1684                 | SET DEFAULT                                   { $$ = FKCONSTR_ON_KEY_SETDEFAULT; }
1685                 ;
1686
1687 OptInherit:  INHERITS '(' qualified_name_list ')'       { $$ = $3; }
1688                 | /*EMPTY*/                                                                     { $$ = NIL; }
1689                 ;
1690
1691 OptWithOids:  WITH OIDS                                         { $$ = TRUE; }
1692                         | WITHOUT OIDS                                  { $$ = FALSE; }
1693                         | /*EMPTY*/                                             { $$ = TRUE; }
1694                 ;
1695
1696
1697 /*
1698  * Note: CREATE TABLE ... AS SELECT ... is just another spelling for
1699  * SELECT ... INTO.
1700  */
1701
1702 CreateAsStmt:  CREATE OptTemp TABLE qualified_name OptCreateAs AS SelectStmt
1703                                 {
1704                                         /*
1705                                          * When the SelectStmt is a set-operation tree, we must
1706                                          * stuff the INTO information into the leftmost component
1707                                          * Select, because that's where analyze.c will expect
1708                                          * to find it.  Similarly, the output column names must
1709                                          * be attached to that Select's target list.
1710                                          */
1711                                         SelectStmt *n = findLeftmostSelect((SelectStmt *) $7);
1712                                         if (n->into != NULL)
1713                                                 elog(ERROR, "CREATE TABLE AS may not specify INTO");
1714                                         $4->istemp = $2;
1715                                         n->into = $4;
1716                                         n->intoColNames = $5;
1717                                         $$ = $7;
1718                                 }
1719                 ;
1720
1721 OptCreateAs:  '(' CreateAsList ')'                              { $$ = $2; }
1722                         | /*EMPTY*/                                                     { $$ = NIL; }
1723                 ;
1724
1725 CreateAsList:  CreateAsList ',' CreateAsElement { $$ = lappend($1, $3); }
1726                         | CreateAsElement                                       { $$ = makeList1($1); }
1727                 ;
1728
1729 CreateAsElement:  ColId
1730                                 {
1731                                         ColumnDef *n = makeNode(ColumnDef);
1732                                         n->colname = $1;
1733                                         n->typename = NULL;
1734                                         n->raw_default = NULL;
1735                                         n->cooked_default = NULL;
1736                                         n->is_not_null = FALSE;
1737                                         n->constraints = NULL;
1738                                         $$ = (Node *)n;
1739                                 }
1740                 ;
1741
1742
1743 /*****************************************************************************
1744  *
1745  *              QUERY :
1746  *                              CREATE SEQUENCE seqname
1747  *
1748  *****************************************************************************/
1749
1750 CreateSeqStmt:  CREATE OptTemp SEQUENCE qualified_name OptSeqList
1751                                 {
1752                                         CreateSeqStmt *n = makeNode(CreateSeqStmt);
1753                                         $4->istemp = $2;
1754                                         n->sequence = $4;
1755                                         n->options = $5;
1756                                         $$ = (Node *)n;
1757                                 }
1758                 ;
1759
1760 OptSeqList:  OptSeqList OptSeqElem
1761                                 { $$ = lappend($1, $2); }
1762                         |       { $$ = NIL; }
1763                 ;
1764
1765 OptSeqElem:  CACHE NumericOnly
1766                                 {
1767                                         $$ = makeNode(DefElem);
1768                                         $$->defname = "cache";
1769                                         $$->arg = (Node *)$2;
1770                                 }
1771                         | CYCLE
1772                                 {
1773                                         $$ = makeNode(DefElem);
1774                                         $$->defname = "cycle";
1775                                         $$->arg = (Node *)NULL;
1776                                 }
1777                         | INCREMENT NumericOnly
1778                                 {
1779                                         $$ = makeNode(DefElem);
1780                                         $$->defname = "increment";
1781                                         $$->arg = (Node *)$2;
1782                                 }
1783                         | MAXVALUE NumericOnly
1784                                 {
1785                                         $$ = makeNode(DefElem);
1786                                         $$->defname = "maxvalue";
1787                                         $$->arg = (Node *)$2;
1788                                 }
1789                         | MINVALUE NumericOnly
1790                                 {
1791                                         $$ = makeNode(DefElem);
1792                                         $$->defname = "minvalue";
1793                                         $$->arg = (Node *)$2;
1794                                 }
1795                         | START NumericOnly
1796                                 {
1797                                         $$ = makeNode(DefElem);
1798                                         $$->defname = "start";
1799                                         $$->arg = (Node *)$2;
1800                                 }
1801                 ;
1802
1803 NumericOnly:  FloatOnly                                 { $$ = $1; }
1804                         | IntegerOnly                           { $$ = $1; }
1805                 ;
1806
1807 FloatOnly:  FCONST
1808                                 {
1809                                         $$ = makeFloat($1);
1810                                 }
1811                         | '-' FCONST
1812                                 {
1813                                         $$ = makeFloat($2);
1814                                         doNegateFloat($$);
1815                                 }
1816                 ;
1817
1818 IntegerOnly:  Iconst
1819                                 {
1820                                         $$ = makeInteger($1);
1821                                 }
1822                         | '-' Iconst
1823                                 {
1824                                         $$ = makeInteger($2);
1825                                         $$->val.ival = - $$->val.ival;
1826                                 }
1827                 ;
1828
1829 /*****************************************************************************
1830  *
1831  *              QUERIES :
1832  *                              CREATE PROCEDURAL LANGUAGE ...
1833  *                              DROP PROCEDURAL LANGUAGE ...
1834  *
1835  *****************************************************************************/
1836
1837 CreatePLangStmt:  CREATE opt_trusted opt_procedural LANGUAGE ColId_or_Sconst
1838                         HANDLER handler_name opt_validator opt_lancompiler
1839                         {
1840                                 CreatePLangStmt *n = makeNode(CreatePLangStmt);
1841                                 n->plname = $5;
1842                                 n->plhandler = $7;
1843                                 n->plvalidator = $8;
1844                                 n->plcompiler = $9;
1845                                 n->pltrusted = $2;
1846                                 $$ = (Node *)n;
1847                         }
1848                 ;
1849
1850 opt_trusted:  TRUSTED                   { $$ = TRUE; }
1851                         | /*EMPTY*/                     { $$ = FALSE; }
1852                 ;
1853
1854 /* This ought to be just func_name, but that causes reduce/reduce conflicts
1855  * (CREATE LANGUAGE is the only place where func_name isn't followed by '(').
1856  * Work around by using name and dotted_name separately.
1857  */
1858 handler_name: name
1859                                 { $$ = makeList1(makeString($1)); }
1860                         | dotted_name
1861                                 { $$ = $1; }
1862                 ;
1863
1864 opt_lancompiler: LANCOMPILER Sconst { $$ = $2; }
1865                         | /*EMPTY*/                     { $$ = ""; }
1866                 ;
1867
1868 opt_validator: VALIDATOR handler_name { $$ = $2; }
1869                         | /*EMPTY*/ { $$ = NULL; }
1870                 ;
1871
1872 DropPLangStmt:  DROP opt_procedural LANGUAGE ColId_or_Sconst
1873                         {
1874                                 DropPLangStmt *n = makeNode(DropPLangStmt);
1875                                 n->plname = $4;
1876                                 $$ = (Node *)n;
1877                         }
1878                 ;
1879
1880 opt_procedural: PROCEDURAL              { $$ = TRUE; }
1881                         | /*EMPTY*/                     { $$ = TRUE; }
1882                 ;
1883                 
1884 /*****************************************************************************
1885  *
1886  *              QUERIES :
1887  *                              CREATE TRIGGER ...
1888  *                              DROP TRIGGER ...
1889  *
1890  *****************************************************************************/
1891
1892 CreateTrigStmt:  CREATE TRIGGER name TriggerActionTime TriggerEvents ON
1893                                 qualified_name TriggerForSpec EXECUTE PROCEDURE
1894                                 func_name '(' TriggerFuncArgs ')'
1895                                 {
1896                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
1897                                         n->trigname = $3;
1898                                         n->relation = $7;
1899                                         n->funcname = $11;
1900                                         n->args = $13;
1901                                         n->before = $4;
1902                                         n->row = $8;
1903                                         memcpy (n->actions, $5, 4);
1904                                         n->lang = NULL;         /* unused */
1905                                         n->text = NULL;         /* unused */
1906                                         n->attr = NULL;         /* unused */
1907                                         n->when = NULL;         /* unused */
1908
1909                                         n->isconstraint  = FALSE;
1910                                         n->deferrable    = FALSE;
1911                                         n->initdeferred  = FALSE;
1912                                         n->constrrel = NULL;
1913                                         $$ = (Node *)n;
1914                                 }
1915                 | CREATE CONSTRAINT TRIGGER name AFTER TriggerEvents ON
1916                                 qualified_name OptConstrFromTable 
1917                                 ConstraintAttributeSpec
1918                                 FOR EACH ROW EXECUTE PROCEDURE
1919                                 func_name '(' TriggerFuncArgs ')'
1920                                 {
1921                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
1922                                         n->trigname = $4;
1923                                         n->relation = $8;
1924                                         n->funcname = $16;
1925                                         n->args = $18;
1926                                         n->before = FALSE;
1927                                         n->row = TRUE;
1928                                         memcpy (n->actions, $6, 4);
1929                                         n->lang = NULL;         /* unused */
1930                                         n->text = NULL;         /* unused */
1931                                         n->attr = NULL;         /* unused */
1932                                         n->when = NULL;         /* unused */
1933
1934                                         n->isconstraint  = TRUE;
1935                                         n->deferrable = ($10 & 1) != 0;
1936                                         n->initdeferred = ($10 & 2) != 0;
1937
1938                                         n->constrrel = $9;
1939                                         $$ = (Node *)n;
1940                                 }
1941                 ;
1942
1943 TriggerActionTime:  BEFORE                                              { $$ = TRUE; }
1944                         | AFTER                                                         { $$ = FALSE; }
1945                 ;
1946
1947 TriggerEvents:  TriggerOneEvent
1948                                 {
1949                                         char *e = palloc (4);
1950                                         e[0] = $1; e[1] = 0; $$ = e;
1951                                 }
1952                         | TriggerOneEvent OR TriggerOneEvent
1953                                 {
1954                                         char *e = palloc (4);
1955                                         e[0] = $1; e[1] = $3; e[2] = 0; $$ = e;
1956                                 }
1957                         | TriggerOneEvent OR TriggerOneEvent OR TriggerOneEvent
1958                                 {
1959                                         char *e = palloc (4);
1960                                         e[0] = $1; e[1] = $3; e[2] = $5; e[3] = 0;
1961                                         $$ = e;
1962                                 }
1963                 ;
1964
1965 TriggerOneEvent:  INSERT                                        { $$ = 'i'; }
1966                         | DELETE_P                                              { $$ = 'd'; }
1967                         | UPDATE                                                { $$ = 'u'; }
1968                 ;
1969
1970 TriggerForSpec:  FOR TriggerForOpt TriggerForType
1971                                 {
1972                                         $$ = $3;
1973                                 }
1974                 ;
1975
1976 TriggerForOpt:  EACH                                            { $$ = TRUE; }
1977                         | /*EMPTY*/                                             { $$ = FALSE; }
1978                 ;
1979
1980 TriggerForType:  ROW                                            { $$ = TRUE; }
1981                         | STATEMENT                                             { $$ = FALSE; }
1982                 ;
1983
1984 TriggerFuncArgs:  TriggerFuncArg
1985                                 { $$ = makeList1($1); }
1986                         | TriggerFuncArgs ',' TriggerFuncArg
1987                                 { $$ = lappend($1, $3); }
1988                         | /*EMPTY*/
1989                                 { $$ = NIL; }
1990                 ;
1991
1992 TriggerFuncArg:  ICONST
1993                                 {
1994                                         char buf[64];
1995                                         sprintf (buf, "%d", $1);
1996                                         $$ = makeString(pstrdup(buf));
1997                                 }
1998                         | FCONST
1999                                 {
2000                                         $$ = makeString($1);
2001                                 }
2002                         | Sconst
2003                                 {
2004                                         $$ = makeString($1);
2005                                 }
2006                         | BITCONST
2007                                 {
2008                                         $$ = makeString($1);
2009                                 }
2010                         | ColId
2011                                 {
2012                                         $$ = makeString($1);
2013                                 }
2014                 ;
2015
2016 OptConstrFromTable:                     /* Empty */
2017                                 {
2018                                         $$ = NULL;
2019                                 }
2020                 | FROM qualified_name
2021                                 {
2022                                         $$ = $2;
2023                                 }
2024                 ;
2025
2026 ConstraintAttributeSpec:  ConstraintDeferrabilitySpec
2027                         { $$ = $1; }
2028                 | ConstraintDeferrabilitySpec ConstraintTimeSpec
2029                         {
2030                                 if ($1 == 0 && $2 != 0)
2031                                         elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2032                                 $$ = $1 | $2;
2033                         }
2034                 | ConstraintTimeSpec
2035                         {
2036                                 if ($1 != 0)
2037                                         $$ = 3;
2038                                 else
2039                                         $$ = 0;
2040                         }
2041                 | ConstraintTimeSpec ConstraintDeferrabilitySpec
2042                         {
2043                                 if ($2 == 0 && $1 != 0)
2044                                         elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2045                                 $$ = $1 | $2;
2046                         }
2047                 | /* Empty */
2048                         { $$ = 0; }
2049                 ;
2050
2051 ConstraintDeferrabilitySpec: NOT DEFERRABLE
2052                         { $$ = 0; }
2053                 | DEFERRABLE
2054                         { $$ = 1; }
2055                 ;
2056
2057 ConstraintTimeSpec: INITIALLY IMMEDIATE
2058                         { $$ = 0; }
2059                 | INITIALLY DEFERRED
2060                         { $$ = 2; }
2061                 ;
2062
2063
2064 DropTrigStmt:  DROP TRIGGER name ON qualified_name
2065                                 {
2066                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
2067                                         n->relation = $5;
2068                                         n->property = $3;
2069                                         n->removeType = DROP_TRIGGER;
2070                                         $$ = (Node *) n;
2071                                 }
2072                 ;
2073
2074
2075 /*****************************************************************************
2076  *
2077  *              QUERIES :
2078  *                              CREATE ASSERTION ...
2079  *                              DROP ASSERTION ...
2080  *
2081  *****************************************************************************/
2082
2083 CreateAssertStmt:  CREATE ASSERTION name
2084                         CHECK '(' a_expr ')' ConstraintAttributeSpec
2085                                 {
2086                                         CreateTrigStmt *n = makeNode(CreateTrigStmt);
2087                                         n->trigname = $3;
2088                                         n->args = makeList1($6);
2089                                         n->isconstraint  = TRUE;
2090                                         n->deferrable = ($8 & 1) != 0;
2091                                         n->initdeferred = ($8 & 2) != 0;
2092
2093                                         elog(ERROR, "CREATE ASSERTION is not yet supported");
2094
2095                                         $$ = (Node *)n;
2096                                 }
2097                 ;
2098
2099 DropAssertStmt:  DROP ASSERTION name
2100                                 {
2101                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
2102                                         n->relation = NULL;
2103                                         n->property = $3;
2104                                         n->removeType = DROP_TRIGGER;
2105                                         elog(ERROR, "DROP ASSERTION is not yet supported");
2106                                         $$ = (Node *) n;
2107                                 }
2108                 ;
2109
2110
2111 /*****************************************************************************
2112  *
2113  *              QUERY :
2114  *                              define (aggregate,operator,type)
2115  *
2116  *****************************************************************************/
2117
2118 DefineStmt:  CREATE AGGREGATE func_name definition
2119                                 {
2120                                         DefineStmt *n = makeNode(DefineStmt);
2121                                         n->defType = AGGREGATE;
2122                                         n->defnames = $3;
2123                                         n->definition = $4;
2124                                         $$ = (Node *)n;
2125                                 }
2126                 | CREATE OPERATOR any_operator definition
2127                                 {
2128                                         DefineStmt *n = makeNode(DefineStmt);
2129                                         n->defType = OPERATOR;
2130                                         n->defnames = $3;
2131                                         n->definition = $4;
2132                                         $$ = (Node *)n;
2133                                 }
2134                 | CREATE TYPE_P any_name definition
2135                                 {
2136                                         DefineStmt *n = makeNode(DefineStmt);
2137                                         n->defType = TYPE_P;
2138                                         n->defnames = $3;
2139                                         n->definition = $4;
2140                                         $$ = (Node *)n;
2141                                 }
2142                 | CREATE CHARACTER SET opt_as any_name GET definition opt_collate
2143                                 {
2144                                         DefineStmt *n = makeNode(DefineStmt);
2145                                         n->defType = CHARACTER;
2146                                         n->defnames = $5;
2147                                         n->definition = $7;
2148                                         $$ = (Node *)n;
2149                                 }
2150                 ;
2151
2152 definition:  '(' def_list ')'                           { $$ = $2; }
2153                 ;
2154
2155 def_list:  def_elem                                                     { $$ = makeList1($1); }
2156                 | def_list ',' def_elem                         { $$ = lappend($1, $3); }
2157                 ;
2158
2159 def_elem:  ColLabel '=' def_arg
2160                                 {
2161                                         $$ = makeNode(DefElem);
2162                                         $$->defname = $1;
2163                                         $$->arg = (Node *)$3;
2164                                 }
2165                 | ColLabel
2166                                 {
2167                                         $$ = makeNode(DefElem);
2168                                         $$->defname = $1;
2169                                         $$->arg = (Node *)NULL;
2170                                 }
2171                 ;
2172
2173 /* Note: any simple identifier will be returned as a type name! */
2174 def_arg:  func_return                                   {  $$ = (Node *)$1; }
2175                 | all_Op                                                {  $$ = (Node *)makeString($1); }
2176                 | NumericOnly                                   {  $$ = (Node *)$1; }
2177                 | Sconst                                                {  $$ = (Node *)makeString($1); }
2178                 ;
2179
2180
2181 /*****************************************************************************
2182  *
2183  *              QUERY:
2184  *
2185  *              DROP itemtype itemname [, itemname ...]
2186  *
2187  *****************************************************************************/
2188
2189 DropStmt:  DROP drop_type any_name_list opt_drop_behavior
2190                                 {
2191                                         DropStmt *n = makeNode(DropStmt);
2192                                         n->removeType = $2;
2193                                         n->objects = $3;
2194                                         n->behavior = $4;
2195                                         $$ = (Node *)n;
2196                                 }
2197                 ;
2198
2199 drop_type: TABLE                                                                { $$ = DROP_TABLE; }
2200                 | SEQUENCE                                                              { $$ = DROP_SEQUENCE; }
2201                 | VIEW                                                                  { $$ = DROP_VIEW; }
2202                 | INDEX                                                                 { $$ = DROP_INDEX; }
2203                 | TYPE_P                                                                { $$ = DROP_TYPE; }
2204                 | DOMAIN_P                                                              { $$ = DROP_DOMAIN; }
2205                 ;
2206
2207 any_name_list:  any_name
2208                         { $$ = makeList1($1); }
2209                 | any_name_list ',' any_name
2210                         { $$ = lappend($1, $3); }
2211                 ;
2212
2213 any_name: ColId
2214                         { $$ = makeList1(makeString($1)); }
2215                 | dotted_name
2216                         { $$ = $1; }
2217                 ;
2218
2219 /*****************************************************************************
2220  *
2221  *              QUERY:
2222  *                              truncate table relname
2223  *
2224  *****************************************************************************/
2225
2226 TruncateStmt:  TRUNCATE opt_table qualified_name
2227                                 {
2228                                         TruncateStmt *n = makeNode(TruncateStmt);
2229                                         n->relation = $3;
2230                                         $$ = (Node *)n;
2231                                 }
2232                         ;
2233
2234 /*****************************************************************************
2235  *
2236  *  The COMMENT ON statement can take different forms based upon the type of
2237  *  the object associated with the comment. The form of the statement is:
2238  *
2239  *  COMMENT ON [ [ DATABASE | DOMAIN | INDEX | SEQUENCE | TABLE | TYPE | VIEW ]
2240  *               <objname> | AGGREGATE <aggname> (<aggtype>) | FUNCTION 
2241  *               <funcname> (arg1, arg2, ...) | OPERATOR <op> 
2242  *               (leftoperand_typ rightoperand_typ) | TRIGGER <triggername> ON
2243  *               <relname> | RULE <rulename> ON <relname> ] IS 'text'
2244  *
2245  *****************************************************************************/
2246  
2247 CommentStmt:    COMMENT ON comment_type any_name IS comment_text
2248                         {
2249                                 CommentStmt *n = makeNode(CommentStmt);
2250                                 n->objtype = $3;
2251                                 n->objname = $4;
2252                                 n->objargs = NIL;
2253                                 n->comment = $6;
2254                                 $$ = (Node *) n;
2255                         }
2256                 | COMMENT ON AGGREGATE func_name '(' aggr_argtype ')' IS comment_text
2257                         {
2258                                 CommentStmt *n = makeNode(CommentStmt);
2259                                 n->objtype = AGGREGATE;
2260                                 n->objname = $4;
2261                                 n->objargs = makeList1($6);
2262                                 n->comment = $9;
2263                                 $$ = (Node *) n;
2264                         }
2265                 | COMMENT ON FUNCTION func_name func_args IS comment_text
2266                         {
2267                                 CommentStmt *n = makeNode(CommentStmt);
2268                                 n->objtype = FUNCTION;
2269                                 n->objname = $4;
2270                                 n->objargs = $5;
2271                                 n->comment = $7;
2272                                 $$ = (Node *) n;
2273                         }
2274                 | COMMENT ON OPERATOR any_operator '(' oper_argtypes ')' IS comment_text
2275                         {
2276                                 CommentStmt *n = makeNode(CommentStmt);
2277                                 n->objtype = OPERATOR;
2278                                 n->objname = $4;
2279                                 n->objargs = $6;
2280                                 n->comment = $9;
2281                                 $$ = (Node *) n;
2282                         }
2283                 | COMMENT ON TRIGGER name ON any_name IS comment_text
2284                         {
2285                                 CommentStmt *n = makeNode(CommentStmt);
2286                                 n->objtype = TRIGGER;
2287                                 n->objname = lappend($6, makeString($4));
2288                                 n->objargs = NIL;
2289                                 n->comment = $8;
2290                                 $$ = (Node *) n;
2291                         }
2292                 | COMMENT ON RULE name ON any_name IS comment_text
2293                         {
2294                                 CommentStmt *n = makeNode(CommentStmt);
2295                                 n->objtype = RULE;
2296                                 n->objname = lappend($6, makeString($4));
2297                                 n->objargs = NIL;
2298                                 n->comment = $8;
2299                                 $$ = (Node *) n;
2300                         }
2301                 | COMMENT ON RULE name IS comment_text
2302                         {
2303                                 /* Obsolete syntax supported for awhile for compatibility */
2304                                 CommentStmt *n = makeNode(CommentStmt);
2305                                 n->objtype = RULE;
2306                                 n->objname = makeList1(makeString($4));
2307                                 n->objargs = NIL;
2308                                 n->comment = $6;
2309                                 $$ = (Node *) n;
2310                         }
2311                 ;
2312
2313 comment_type:   COLUMN { $$ = COLUMN; }
2314                 | DATABASE { $$ = DATABASE; }
2315                 | SCHEMA { $$ = SCHEMA; }
2316                 | INDEX { $$ = INDEX; }
2317                 | SEQUENCE { $$ = SEQUENCE; }
2318                 | TABLE { $$ = TABLE; }
2319                 | DOMAIN_P { $$ = TYPE_P; }
2320                 | TYPE_P { $$ = TYPE_P; }
2321                 | VIEW { $$ = VIEW; }
2322                 ;               
2323
2324 comment_text:   Sconst { $$ = $1; }
2325                 | NULL_P { $$ = NULL; }
2326                 ;
2327                 
2328 /*****************************************************************************
2329  *
2330  *              QUERY:
2331  *                      fetch/move [forward | backward] [ # | all ] [ in <portalname> ]
2332  *                      fetch [ forward | backward | absolute | relative ]
2333  *                            [ # | all | next | prior ] [ [ in | from ] <portalname> ]
2334  *
2335  *****************************************************************************/
2336
2337 FetchStmt:  FETCH direction fetch_how_many from_in name
2338                                 {
2339                                         FetchStmt *n = makeNode(FetchStmt);
2340                                         if ($2 == RELATIVE)
2341                                         {
2342                                                 if ($3 == 0)
2343                                                         elog(ERROR,"FETCH / RELATIVE at current position is not supported");
2344                                                 $2 = FORWARD;
2345                                         }
2346                                         if ($3 < 0)
2347                                         {
2348                                                 $3 = -$3;
2349                                                 $2 = (($2 == FORWARD)? BACKWARD: FORWARD);
2350                                         }
2351                                         n->direction = $2;
2352                                         n->howMany = $3;
2353                                         n->portalname = $5;
2354                                         n->ismove = FALSE;
2355                                         $$ = (Node *)n;
2356                                 }
2357                 | FETCH fetch_how_many from_in name
2358                                 {
2359                                         FetchStmt *n = makeNode(FetchStmt);
2360                                         if ($2 < 0)
2361                                         {
2362                                                 n->howMany = -$2;
2363                                                 n->direction = BACKWARD;
2364                                         }
2365                                         else
2366                                         {
2367                                                 n->direction = FORWARD;
2368                                                 n->howMany = $2;
2369                                         }
2370                                         n->portalname = $4;
2371                                         n->ismove = FALSE;
2372                                         $$ = (Node *)n;
2373                                 }
2374                 | FETCH direction from_in name
2375                                 {
2376                                         FetchStmt *n = makeNode(FetchStmt);
2377                                         if ($2 == RELATIVE)
2378                                         {
2379                                                 $2 = FORWARD;
2380                                         }
2381                                         n->direction = $2;
2382                                         n->howMany = 1;
2383                                         n->portalname = $4;
2384                                         n->ismove = FALSE;
2385                                         $$ = (Node *)n;
2386                                 }
2387                 | FETCH from_in name
2388                                 {
2389                                         FetchStmt *n = makeNode(FetchStmt);
2390                                         n->direction = FORWARD;
2391                                         n->howMany = 1;
2392                                         n->portalname = $3;
2393                                         n->ismove = FALSE;
2394                                         $$ = (Node *)n;
2395                                 }
2396                 | FETCH name
2397                                 {
2398                                         FetchStmt *n = makeNode(FetchStmt);
2399                                         n->direction = FORWARD;
2400                                         n->howMany = 1;
2401                                         n->portalname = $2;
2402                                         n->ismove = FALSE;
2403                                         $$ = (Node *)n;
2404                                 }
2405
2406                 | MOVE direction fetch_how_many from_in name
2407                                 {
2408                                         FetchStmt *n = makeNode(FetchStmt);
2409                                         if ($3 < 0)
2410                                         {
2411                                                 $3 = -$3;
2412                                                 $2 = (($2 == FORWARD)? BACKWARD: FORWARD);
2413                                         }
2414                                         n->direction = $2;
2415                                         n->howMany = $3;
2416                                         n->portalname = $5;
2417                                         n->ismove = TRUE;
2418                                         $$ = (Node *)n;
2419                                 }
2420                 | MOVE fetch_how_many from_in name
2421                                 {
2422                                         FetchStmt *n = makeNode(FetchStmt);
2423                                         if ($2 < 0)
2424                                         {
2425                                                 n->howMany = -$2;
2426                                                 n->direction = BACKWARD;
2427                                         }
2428                                         else
2429                                         {
2430                                                 n->direction = FORWARD;
2431                                                 n->howMany = $2;
2432                                         }
2433                                         n->portalname = $4;
2434                                         n->ismove = TRUE;
2435                                         $$ = (Node *)n;
2436                                 }
2437                 | MOVE direction from_in name
2438                                 {
2439                                         FetchStmt *n = makeNode(FetchStmt);
2440                                         n->direction = $2;
2441                                         n->howMany = 1;
2442                                         n->portalname = $4;
2443                                         n->ismove = TRUE;
2444                                         $$ = (Node *)n;
2445                                 }
2446                 |       MOVE from_in name
2447                                 {
2448                                         FetchStmt *n = makeNode(FetchStmt);
2449                                         n->direction = FORWARD;
2450                                         n->howMany = 1;
2451                                         n->portalname = $3;
2452                                         n->ismove = TRUE;
2453                                         $$ = (Node *)n;
2454                                 }
2455                 | MOVE name
2456                                 {
2457                                         FetchStmt *n = makeNode(FetchStmt);
2458                                         n->direction = FORWARD;
2459                                         n->howMany = 1;
2460                                         n->portalname = $2;
2461                                         n->ismove = TRUE;
2462                                         $$ = (Node *)n;
2463                                 }
2464                 ;
2465
2466 direction:      FORWARD                                 { $$ = FORWARD; }
2467                 | BACKWARD                                              { $$ = BACKWARD; }
2468                 | RELATIVE                                              { $$ = RELATIVE; }
2469                 | ABSOLUTE
2470                         {
2471                                 elog(NOTICE,"FETCH / ABSOLUTE not supported, using RELATIVE");
2472                                 $$ = RELATIVE;
2473                         }
2474                 ;
2475
2476 fetch_how_many:  Iconst                                 { $$ = $1; }
2477                 | '-' Iconst                                    { $$ = - $2; }
2478                 | ALL                                                   { $$ = 0; /* 0 means fetch all tuples*/ }
2479                 | NEXT                                                  { $$ = 1; }
2480                 | PRIOR                                                 { $$ = -1; }
2481                 ;
2482
2483 from_in:  IN_P                                                  { }
2484         | FROM                                                          { }
2485         ;
2486
2487
2488 /*****************************************************************************
2489  *
2490  * GRANT and REVOKE statements
2491  *
2492  *****************************************************************************/
2493
2494 GrantStmt:  GRANT privileges ON privilege_target TO grantee_list opt_grant_grant_option
2495                                 {
2496                                         GrantStmt *n = makeNode(GrantStmt);
2497                                         n->is_grant = true;
2498                                         n->privileges = $2;
2499                                         n->objtype = ($4)->objtype;
2500                                         n->objects = ($4)->objs;
2501                                         n->grantees = $6;
2502                                         $$ = (Node*)n;
2503                                 }
2504                 ;
2505
2506 RevokeStmt:  REVOKE opt_revoke_grant_option privileges ON privilege_target FROM grantee_list
2507                                 {
2508                                         GrantStmt *n = makeNode(GrantStmt);
2509                                         n->is_grant = false;
2510                                         n->privileges = $3;
2511                                         n->objtype = ($5)->objtype;
2512                                         n->objects = ($5)->objs;
2513                                         n->grantees = $7;
2514                                         $$ = (Node *)n;
2515                                 }
2516                 ;
2517
2518
2519 /* either ALL [PRIVILEGES] or a list of individual privileges */
2520 privileges: privilege_list { $$ = $1; }
2521                 | ALL { $$ = makeListi1(ACL_ALL_RIGHTS); }
2522                 | ALL PRIVILEGES { $$ = makeListi1(ACL_ALL_RIGHTS); }
2523                 ;
2524
2525 privilege_list: privilege { $$ = makeListi1($1); }
2526                 | privilege_list ',' privilege { $$ = lappendi($1, $3); }
2527                 ;
2528
2529 /* Not all of these privilege types apply to all objects, but that
2530  * gets sorted out later.
2531  */
2532 privilege: SELECT    { $$ = ACL_SELECT; }
2533                 | INSERT     { $$ = ACL_INSERT; }
2534                 | UPDATE     { $$ = ACL_UPDATE; }
2535                 | DELETE_P   { $$ = ACL_DELETE; }
2536                 | RULE       { $$ = ACL_RULE; }
2537                 | REFERENCES { $$ = ACL_REFERENCES; }
2538                 | TRIGGER    { $$ = ACL_TRIGGER; }
2539                 | EXECUTE    { $$ = ACL_EXECUTE; }
2540                 | USAGE      { $$ = ACL_USAGE; }
2541                 | CREATE     { $$ = ACL_CREATE; }
2542                 | TEMPORARY  { $$ = ACL_CREATE_TEMP; }
2543                 | TEMP       { $$ = ACL_CREATE_TEMP; }
2544                 ;
2545
2546
2547 /* Don't bother trying to fold the first two rules into one using
2548    opt_table.  You're going to get conflicts. */
2549 privilege_target: qualified_name_list
2550                                 {
2551                                         PrivTarget *n = makeNode(PrivTarget);
2552                                         n->objtype = ACL_OBJECT_RELATION;
2553                                         n->objs = $1;
2554                                         $$ = n;
2555                                 }
2556                         | TABLE qualified_name_list
2557                                 {
2558                                         PrivTarget *n = makeNode(PrivTarget);
2559                                         n->objtype = ACL_OBJECT_RELATION;
2560                                         n->objs = $2;
2561                                         $$ = n;
2562                                 }
2563                         | FUNCTION function_with_argtypes_list
2564                                 {
2565                                         PrivTarget *n = makeNode(PrivTarget);
2566                                         n->objtype = ACL_OBJECT_FUNCTION;
2567                                         n->objs = $2;
2568                                         $$ = n;
2569                                 }
2570                         | DATABASE name_list
2571                                 {
2572                                         PrivTarget *n = makeNode(PrivTarget);
2573                                         n->objtype = ACL_OBJECT_DATABASE;
2574                                         n->objs = $2;
2575                                         $$ = n;
2576                                 }
2577                         | LANGUAGE name_list
2578                                 {
2579                                         PrivTarget *n = makeNode(PrivTarget);
2580                                         n->objtype = ACL_OBJECT_LANGUAGE;
2581                                         n->objs = $2;
2582                                         $$ = n;
2583                                 }
2584                         | SCHEMA name_list
2585                                 {
2586                                         PrivTarget *n = makeNode(PrivTarget);
2587                                         n->objtype = ACL_OBJECT_NAMESPACE;
2588                                         n->objs = $2;
2589                                         $$ = n;
2590                                 }
2591                 ;
2592
2593
2594 grantee_list: grantee                                   { $$ = makeList1($1); }
2595                 | grantee_list ',' grantee              { $$ = lappend($1, $3); }
2596                 ;
2597
2598 grantee:  ColId
2599                                 {
2600                                         PrivGrantee *n = makeNode(PrivGrantee);
2601                                         /* This hack lets us avoid reserving PUBLIC as a keyword */
2602                                         if (strcmp($1, "public") == 0)
2603                                                 n->username = NULL;
2604                                         else
2605                                                 n->username = $1;
2606                                         n->groupname = NULL;
2607                                         $$ = (Node *)n;
2608                                 }
2609                 | GROUP_P ColId
2610                                 {
2611                                         PrivGrantee *n = makeNode(PrivGrantee);
2612                                         /* Treat GROUP PUBLIC as a synonym for PUBLIC */
2613                                         if (strcmp($2, "public") == 0)
2614                                                 n->groupname = NULL;
2615                                         else
2616                                                 n->groupname = $2;
2617                                         n->username = NULL;
2618                                         $$ = (Node *)n;
2619                                 }
2620                 ;
2621
2622
2623 opt_grant_grant_option: WITH GRANT OPTION
2624                                 {
2625                                         elog(ERROR, "grant options are not implemented");
2626                                 }
2627                 | /*EMPTY*/
2628                 ;
2629
2630 opt_revoke_grant_option: GRANT OPTION FOR
2631                                 {
2632                                         elog(ERROR, "grant options are not implemented");
2633                                 }
2634                 | /*EMPTY*/
2635                 ;
2636
2637
2638 function_with_argtypes_list: function_with_argtypes
2639                                 { $$ = makeList1($1); }
2640                 | function_with_argtypes_list ',' function_with_argtypes
2641                                 { $$ = lappend($1, $3); }
2642                 ;
2643
2644 function_with_argtypes: func_name func_args
2645                                 {
2646                                         FuncWithArgs *n = makeNode(FuncWithArgs);
2647                                         n->funcname = $1;
2648                                         n->funcargs = $2;
2649                                         $$ = (Node *)n;
2650                                 }
2651                 ;
2652
2653
2654 /*****************************************************************************
2655  *
2656  *              QUERY:
2657  *                              create index <indexname> on <relname>
2658  *                                [ using <access> ] "(" (<col> with <op>)+ ")"
2659  *                                [ where <predicate> ]
2660  *
2661  *****************************************************************************/
2662
2663 IndexStmt:      CREATE index_opt_unique INDEX index_name ON qualified_name
2664                         access_method_clause '(' index_params ')' where_clause
2665                                 {
2666                                         IndexStmt *n = makeNode(IndexStmt);
2667                                         n->unique = $2;
2668                                         n->idxname = $4;
2669                                         n->relation = $6;
2670                                         n->accessMethod = $7;
2671                                         n->indexParams = $9;
2672                                         n->whereClause = $11;
2673                                         $$ = (Node *)n;
2674                                 }
2675                 ;
2676
2677 index_opt_unique:  UNIQUE                                               { $$ = TRUE; }
2678                 | /*EMPTY*/                                                             { $$ = FALSE; }
2679                 ;
2680
2681 access_method_clause:  USING access_method              { $$ = $2; }
2682                 /* If btree changes as our default, update pg_get_indexdef() */
2683                 | /*EMPTY*/                                                             { $$ = DEFAULT_INDEX_TYPE; }
2684                 ;
2685
2686 index_params:  index_list                                               { $$ = $1; }
2687                 | func_index                                                    { $$ = makeList1($1); }
2688                 ;
2689
2690 index_list:  index_list ',' index_elem                  { $$ = lappend($1, $3); }
2691                 | index_elem                                                    { $$ = makeList1($1); }
2692                 ;
2693
2694 func_index:  func_name '(' name_list ')' opt_class
2695                                 {
2696                                         $$ = makeNode(IndexElem);
2697                                         $$->name = NULL;
2698                                         $$->funcname = $1;
2699                                         $$->args = $3;
2700                                         $$->opclass = $5;
2701                                 }
2702                   ;
2703
2704 index_elem:  attr_name opt_class
2705                                 {
2706                                         $$ = makeNode(IndexElem);
2707                                         $$->name = $1;
2708                                         $$->funcname = NIL;
2709                                         $$->args = NIL;
2710                                         $$->opclass = $2;
2711                                 }
2712                 ;
2713
2714 opt_class:  any_name
2715                                 {
2716                                         /*
2717                                          * Release 7.0 removed network_ops, timespan_ops, and
2718                                          * datetime_ops, so we suppress it from being passed to
2719                                          * the parser so the default *_ops is used.  This can be
2720                                          * removed in some later release.  bjm 2000/02/07
2721                                          *
2722                                          * Release 7.1 removes lztext_ops, so suppress that too
2723                                          * for a while.  tgl 2000/07/30
2724                                          *
2725                                          * Release 7.2 renames timestamp_ops to timestamptz_ops,
2726                                          * so suppress that too for awhile.  I'm starting to
2727                                          * think we need a better approach.  tgl 2000/10/01
2728                                          */
2729                                         if (length($1) == 1)
2730                                         {
2731                                                 char   *claname = strVal(lfirst($1));
2732
2733                                                 if (strcmp(claname, "network_ops") != 0 &&
2734                                                         strcmp(claname, "timespan_ops") != 0 &&
2735                                                         strcmp(claname, "datetime_ops") != 0 &&
2736                                                         strcmp(claname, "lztext_ops") != 0 &&
2737                                                         strcmp(claname, "timestamp_ops") != 0)
2738                                                         $$ = $1;
2739                                                 else
2740                                                         $$ = NIL;
2741                                         }
2742                                         else
2743                                                 $$ = $1;
2744                                 }
2745                 | USING any_name                                                { $$ = $2; }
2746                 | /*EMPTY*/                                                             { $$ = NIL; }
2747                 ;
2748
2749 /*****************************************************************************
2750  *
2751  *              QUERY:
2752  *                              execute recipe <recipeName>
2753  *
2754  *****************************************************************************/
2755
2756 /* NOT USED
2757 RecipeStmt:  EXECUTE RECIPE recipe_name
2758                                 {
2759                                         RecipeStmt *n = makeNode(RecipeStmt);
2760                                         n->recipeName = $3;
2761                                         $$ = (Node *)n;
2762                                 }
2763                 ;
2764 */
2765
2766 /*****************************************************************************
2767  *
2768  *              QUERY:
2769  *                              create [or replace] function <fname>
2770  *                                              [(<type-1> { , <type-n>})]
2771  *                                              returns <type-r>
2772  *                                              as <filename or code in language as appropriate>
2773  *                                              language <lang> [with parameters]
2774  *
2775  *****************************************************************************/
2776
2777 CreateFunctionStmt:     CREATE opt_or_replace FUNCTION func_name func_args
2778                          RETURNS func_return createfunc_opt_list opt_with
2779                                 {
2780                                         CreateFunctionStmt *n = makeNode(CreateFunctionStmt);
2781                                         n->replace = $2;
2782                                         n->funcname = $4;
2783                                         n->argTypes = $5;
2784                                         n->returnType = $7;
2785                                         n->options = $8;
2786                                         n->withClause = $9;
2787                                         $$ = (Node *)n;
2788                                 };
2789
2790 opt_or_replace:  OR REPLACE                                             { $$ = TRUE; }
2791                 | /*EMPTY*/                                                             { $$ = FALSE; }
2792                 ;
2793
2794 func_args:  '(' func_args_list ')'                              { $$ = $2; }
2795                 | '(' ')'                                                               { $$ = NIL; }
2796                 ;
2797
2798 func_args_list:  func_arg
2799                                 {       $$ = makeList1($1); }
2800                 | func_args_list ',' func_arg
2801                                 {       $$ = lappend($1, $3); }
2802                 ;
2803
2804 func_arg:  opt_arg func_type
2805                                 {
2806                                         /* We can catch over-specified arguments here if we want to,
2807                                          * but for now better to silently swallow typmod, etc.
2808                                          * - thomas 2000-03-22
2809                                          */
2810                                         $$ = $2;
2811                                 }
2812                 | func_type
2813                                 {
2814                                         $$ = $1;
2815                                 }
2816                 ;
2817
2818 opt_arg:  IN_P
2819                                 {
2820                                         $$ = FALSE;
2821                                 }
2822                 | OUT_P
2823                                 {
2824                                         elog(ERROR, "CREATE FUNCTION / OUT parameters are not supported");
2825                                         $$ = TRUE;
2826                                 }
2827                 | INOUT
2828                                 {
2829                                         elog(ERROR, "CREATE FUNCTION / INOUT parameters are not supported");
2830                                         $$ = FALSE;
2831                                 }
2832                 ;
2833
2834 func_return:  func_type
2835                                 {
2836                                         /* We can catch over-specified arguments here if we want to,
2837                                          * but for now better to silently swallow typmod, etc.
2838                                          * - thomas 2000-03-22
2839                                          */
2840                                         $$ = $1;
2841                                 }
2842                 ;
2843
2844 /*
2845  * We would like to make the second production here be ColId attrs etc,
2846  * but that causes reduce/reduce conflicts.  type_name is next best choice.
2847  */
2848 func_type:      Typename
2849                                 {
2850                                         $$ = $1;
2851                                 }
2852                 | type_name attrs '%' TYPE_P
2853                                 {
2854                                         $$ = makeNode(TypeName);
2855                                         $$->names = lcons(makeString($1), $2);
2856                                         $$->pct_type = true;
2857                                         $$->typmod = -1;
2858                                 }
2859                 ;
2860
2861
2862 createfunc_opt_list: createfunc_opt_item
2863                 { $$ = makeList1($1); }
2864         | createfunc_opt_list createfunc_opt_item
2865                 { $$ = lappend($1, $2); }
2866         ;
2867
2868 createfunc_opt_item: AS func_as
2869                                 {
2870                                         $$ = makeNode(DefElem);
2871                                         $$->defname = "as";
2872                                         $$->arg = (Node *)$2;
2873                                 }
2874                 | LANGUAGE ColId_or_Sconst
2875                                 {
2876                                         $$ = makeNode(DefElem);
2877                                         $$->defname = "language";
2878                                         $$->arg = (Node *)makeString($2);
2879                                 }
2880                 | IMMUTABLE
2881                                 {
2882                                         $$ = makeNode(DefElem);
2883                                         $$->defname = "volatility";
2884                                         $$->arg = (Node *)makeString("immutable");
2885                                 }
2886                 | STABLE
2887                                 {
2888                                         $$ = makeNode(DefElem);
2889                                         $$->defname = "volatility";
2890                                         $$->arg = (Node *)makeString("stable");
2891                                 }
2892                 | VOLATILE
2893                                 {
2894                                         $$ = makeNode(DefElem);
2895                                         $$->defname = "volatility";
2896                                         $$->arg = (Node *)makeString("volatile");
2897                                 }
2898                 | CALLED ON NULL_P INPUT
2899                                 {
2900                                         $$ = makeNode(DefElem);
2901                                         $$->defname = "strict";
2902                                         $$->arg = (Node *)makeInteger(FALSE);
2903                                 }
2904                 | RETURNS NULL_P ON NULL_P INPUT
2905                                 {
2906                                         $$ = makeNode(DefElem);
2907                                         $$->defname = "strict";
2908                                         $$->arg = (Node *)makeInteger(TRUE);
2909                                 }
2910                 | STRICT
2911                                 {
2912                                         $$ = makeNode(DefElem);
2913                                         $$->defname = "strict";
2914                                         $$->arg = (Node *)makeInteger(TRUE);
2915                                 }
2916                 | EXTERNAL SECURITY DEFINER
2917                                 {
2918                                         $$ = makeNode(DefElem);
2919                                         $$->defname = "security";
2920                                         $$->arg = (Node *)makeInteger(TRUE);
2921                                 }
2922                 | EXTERNAL SECURITY INVOKER
2923                                 {
2924                                         $$ = makeNode(DefElem);
2925                                         $$->defname = "security";
2926                                         $$->arg = (Node *)makeInteger(FALSE);
2927                                 }
2928                 | SECURITY DEFINER
2929                                 {
2930                                         $$ = makeNode(DefElem);
2931                                         $$->defname = "security";
2932                                         $$->arg = (Node *)makeInteger(TRUE);
2933                                 }
2934                 | SECURITY INVOKER
2935                                 {
2936                                         $$ = makeNode(DefElem);
2937                                         $$->defname = "security";
2938                                         $$->arg = (Node *)makeInteger(FALSE);
2939                                 }
2940                 | IMPLICIT CAST
2941                                 {
2942                                         $$ = makeNode(DefElem);
2943                                         $$->defname = "implicit";
2944                                         $$->arg = (Node *)makeInteger(TRUE);
2945                                 }
2946                 ;
2947
2948 func_as: Sconst
2949                                 {   $$ = makeList1(makeString($1)); }
2950                 | Sconst ',' Sconst
2951                                 {       $$ = makeList2(makeString($1), makeString($3)); }
2952                 ;
2953
2954 opt_with:  WITH definition                                              { $$ = $2; }
2955                 | /*EMPTY*/                                                             { $$ = NIL; }
2956                 ;
2957
2958
2959 /*****************************************************************************
2960  *
2961  *              QUERY:
2962  *
2963  *              DROP FUNCTION funcname (arg1, arg2, ...)
2964  *              DROP AGGREGATE aggname (aggtype)
2965  *              DROP OPERATOR opname (leftoperand_typ rightoperand_typ)
2966  *
2967  *****************************************************************************/
2968
2969 RemoveFuncStmt:  DROP FUNCTION func_name func_args
2970                                 {
2971                                         RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
2972                                         n->funcname = $3;
2973                                         n->args = $4;
2974                                         $$ = (Node *)n;
2975                                 }
2976                 ;
2977
2978 RemoveAggrStmt:  DROP AGGREGATE func_name '(' aggr_argtype ')'
2979                                 {
2980                                                 RemoveAggrStmt *n = makeNode(RemoveAggrStmt);
2981                                                 n->aggname = $3;
2982                                                 n->aggtype = $5;
2983                                                 $$ = (Node *)n;
2984                                 }
2985                 ;
2986
2987 aggr_argtype:  Typename                                                 { $$ = $1; }
2988                 | '*'                                                                   { $$ = NULL; }
2989                 ;
2990
2991 RemoveOperStmt:  DROP OPERATOR any_operator '(' oper_argtypes ')'
2992                                 {
2993                                         RemoveOperStmt *n = makeNode(RemoveOperStmt);
2994                                         n->opname = $3;
2995                                         n->args = $5;
2996                                         $$ = (Node *)n;
2997                                 }
2998                 ;
2999
3000 oper_argtypes:  Typename
3001                                 {
3002                                    elog(ERROR,"parser: argument type missing (use NONE for unary operators)");
3003                                 }
3004                 | Typename ',' Typename
3005                                 { $$ = makeList2($1, $3); }
3006                 | NONE ',' Typename                     /* left unary */
3007                                 { $$ = makeList2(NULL, $3); }
3008                 | Typename ',' NONE                     /* right unary */
3009                                 { $$ = makeList2($1, NULL); }
3010                 ;
3011
3012 any_operator: all_Op
3013                         { $$ = makeList1(makeString($1)); }
3014                 | ColId '.' any_operator
3015                         { $$ = lcons(makeString($1), $3); }
3016                 ;
3017
3018
3019 /*****************************************************************************
3020  *
3021  *              QUERY:
3022  *
3023  *              REINDEX type <typename> [FORCE] [ALL]
3024  *
3025  *****************************************************************************/
3026
3027 ReindexStmt:  REINDEX reindex_type qualified_name opt_force
3028                                 {
3029                                         ReindexStmt *n = makeNode(ReindexStmt);
3030                                         n->reindexType = $2;
3031                                         n->relation = $3;
3032                                         n->name = NULL;
3033                                         n->force = $4;
3034                                         $$ = (Node *)n;
3035                                 }
3036                 | REINDEX DATABASE name opt_force
3037                                 {
3038                                         ReindexStmt *n = makeNode(ReindexStmt);
3039                                         n->reindexType = DATABASE;
3040                                         n->name = $3;
3041                                         n->relation = NULL;
3042                                         n->force = $4;
3043                                         $$ = (Node *)n;
3044                                 }
3045                 ;
3046
3047 reindex_type:  INDEX                                                            {  $$ = INDEX; }
3048                 | TABLE                                                                         {  $$ = TABLE; }
3049                 ;
3050
3051 opt_force:      FORCE                                                                   {  $$ = TRUE; }
3052                 | /* EMPTY */                                                           {  $$ = FALSE; }
3053                 ;
3054
3055
3056 /*****************************************************************************
3057  *
3058  *              QUERY:
3059  *                              rename <attrname1> in <relname> [*] to <attrname2>
3060  *                              rename <relname1> to <relname2>
3061  *
3062  *****************************************************************************/
3063
3064 RenameStmt:  ALTER TABLE relation_expr RENAME opt_column opt_name TO name
3065                                 {
3066                                         RenameStmt *n = makeNode(RenameStmt);
3067                                         n->relation = $3;
3068                                         n->oldname = $6;
3069                                         n->newname = $8;
3070                                         if ($6 == NULL)
3071                                                 n->renameType = RENAME_TABLE;
3072                                         else
3073                                                 n->renameType = RENAME_COLUMN;
3074                                         $$ = (Node *)n;
3075                                 }
3076                 | ALTER TRIGGER name ON relation_expr RENAME TO name
3077                                 {
3078                                         RenameStmt *n = makeNode(RenameStmt);
3079                                         n->relation = $5;
3080                                         n->oldname = $3;
3081                                         n->newname = $8;
3082                                         n->renameType = RENAME_TRIGGER;
3083                                         $$ = (Node *)n;
3084                                 }
3085                 ;
3086
3087 opt_name:  name                                                 { $$ = $1; }
3088                 | /*EMPTY*/                                             { $$ = NULL; }
3089                 ;
3090
3091 opt_column:  COLUMN                                             { $$ = COLUMN; }
3092                 | /*EMPTY*/                                             { $$ = 0; }
3093                 ;
3094
3095
3096 /*****************************************************************************
3097  *
3098  *              QUERY:  Define Rewrite Rule
3099  *
3100  *****************************************************************************/
3101
3102 RuleStmt:  CREATE RULE name AS
3103                         { QueryIsRule=TRUE; }
3104                         ON event TO qualified_name where_clause
3105                         DO opt_instead RuleActionList
3106                                 {
3107                                         RuleStmt *n = makeNode(RuleStmt);
3108                                         n->relation = $9;
3109                                         n->rulename = $3;
3110                                         n->whereClause = $10;
3111                                         n->event = $7;
3112                                         n->instead = $12;
3113                                         n->actions = $13;
3114                                         $$ = (Node *)n;
3115                                         QueryIsRule=FALSE;
3116                                 }
3117                 ;
3118
3119 RuleActionList:  NOTHING                                { $$ = NIL; }
3120                 | RuleActionStmt                                { $$ = makeList1($1); }
3121                 | '(' RuleActionMulti ')'               { $$ = $2; } 
3122                 ;
3123
3124 /* the thrashing around here is to discard "empty" statements... */
3125 RuleActionMulti:  RuleActionMulti ';' RuleActionStmtOrEmpty
3126                                 { if ($3 != (Node *) NULL)
3127                                         $$ = lappend($1, $3);
3128                                   else
3129                                         $$ = $1;
3130                                 }
3131                 | RuleActionStmtOrEmpty
3132                                 { if ($1 != (Node *) NULL)
3133                                         $$ = makeList1($1);
3134                                   else
3135                                         $$ = NIL;
3136                                 }
3137                 ;
3138
3139 RuleActionStmt: SelectStmt
3140                 | InsertStmt
3141                 | UpdateStmt
3142                 | DeleteStmt
3143                 | NotifyStmt
3144                 ;
3145
3146 RuleActionStmtOrEmpty:  RuleActionStmt
3147                 |       /*EMPTY*/
3148                                 { $$ = (Node *)NULL; }
3149                 ;
3150
3151 /* change me to select, update, etc. some day */
3152 event:  SELECT                                                  { $$ = CMD_SELECT; }
3153                 | UPDATE                                                { $$ = CMD_UPDATE; }
3154                 | DELETE_P                                              { $$ = CMD_DELETE; }
3155                 | INSERT                                                { $$ = CMD_INSERT; }
3156                  ;
3157
3158 opt_instead:  INSTEAD                                   { $$ = TRUE; }
3159                 | /*EMPTY*/                                             { $$ = FALSE; }
3160                 ;
3161
3162
3163 DropRuleStmt:  DROP RULE name ON qualified_name
3164                                 {
3165                                         DropPropertyStmt *n = makeNode(DropPropertyStmt);
3166                                         n->relation = $5;
3167                                         n->property = $3;
3168                                         n->removeType = DROP_RULE;
3169                                         $$ = (Node *) n;
3170                                 }
3171                 ;
3172
3173
3174 /*****************************************************************************
3175  *
3176  *              QUERY:
3177  *                              NOTIFY <qualified_name> can appear both in rule bodies and
3178  *                              as a query-level command
3179  *
3180  *****************************************************************************/
3181
3182 NotifyStmt:  NOTIFY qualified_name
3183                                 {
3184                                         NotifyStmt *n = makeNode(NotifyStmt);
3185                                         n->relation = $2;
3186                                         $$ = (Node *)n;
3187                                 }
3188                 ;
3189
3190 ListenStmt:  LISTEN qualified_name
3191                                 {
3192                                         ListenStmt *n = makeNode(ListenStmt);
3193                                         n->relation = $2;
3194                                         $$ = (Node *)n;
3195                                 }
3196                 ;
3197
3198 UnlistenStmt:  UNLISTEN qualified_name
3199                                 {
3200                                         UnlistenStmt *n = makeNode(UnlistenStmt);
3201                                         n->relation = $2;
3202                                         $$ = (Node *)n;
3203                                 }
3204                 | UNLISTEN '*'
3205                                 {
3206                                         UnlistenStmt *n = makeNode(UnlistenStmt);
3207                                         n->relation = makeNode(RangeVar);
3208                                         n->relation->relname = "*";
3209                                         n->relation->schemaname = NULL;
3210                                         $$ = (Node *)n;
3211                                 }
3212                 ;
3213
3214
3215 /*****************************************************************************
3216  *
3217  *              Transactions:
3218  *
3219  *      BEGIN / COMMIT / ROLLBACK
3220  *      (also older versions END / ABORT)
3221  *
3222  *****************************************************************************/
3223
3224 TransactionStmt: ABORT_TRANS opt_trans
3225                                 {
3226                                         TransactionStmt *n = makeNode(TransactionStmt);
3227                                         n->command = ROLLBACK;
3228                                         $$ = (Node *)n;
3229                                 }
3230                 | BEGIN_TRANS opt_trans
3231                                 {
3232                                         TransactionStmt *n = makeNode(TransactionStmt);
3233                                         n->command = BEGIN_TRANS;
3234                                         $$ = (Node *)n;
3235                                 }
3236                 | COMMIT opt_trans
3237                                 {
3238                                         TransactionStmt *n = makeNode(TransactionStmt);
3239                                         n->command = COMMIT;
3240                                         $$ = (Node *)n;
3241                                 }
3242                 | COMMIT opt_trans opt_chain
3243                                 {
3244                                         TransactionStmt *n = makeNode(TransactionStmt);
3245                                         n->command = COMMIT;
3246                                         $$ = (Node *)n;
3247                                 }
3248                 | END_TRANS opt_trans
3249                                 {
3250                                         TransactionStmt *n = makeNode(TransactionStmt);
3251                                         n->command = COMMIT;
3252                                         $$ = (Node *)n;
3253                                 }
3254                 | ROLLBACK opt_trans
3255                                 {
3256                                         TransactionStmt *n = makeNode(TransactionStmt);
3257                                         n->command = ROLLBACK;
3258                                         $$ = (Node *)n;
3259                                 }
3260                 | ROLLBACK opt_trans opt_chain
3261                                 {
3262                                         TransactionStmt *n = makeNode(TransactionStmt);
3263                                         n->command = ROLLBACK;
3264                                         $$ = (Node *)n;
3265                                 }
3266                 ;
3267
3268 opt_trans: WORK                                                                 { $$ = TRUE; }
3269                 | TRANSACTION                                                   { $$ = TRUE; }
3270                 | /*EMPTY*/                                                             { $$ = TRUE; }
3271                 ;
3272
3273 opt_chain: AND NO CHAIN
3274                                 { $$ = FALSE; }
3275                 | AND CHAIN
3276                                 {
3277                                         /* SQL99 asks that conforming dbs reject AND CHAIN
3278                                          * if they don't support it. So we can't just ignore it.
3279                                          * - thomas 2000-08-06
3280                                          */
3281                                         elog(ERROR, "COMMIT / CHAIN not yet supported");
3282                                         $$ = TRUE;
3283                                 }
3284                 ;
3285
3286
3287 /*****************************************************************************
3288  *
3289  *              QUERY:
3290  *                              define view <viewname> '('target-list ')' [where <quals> ]
3291  *
3292  *****************************************************************************/
3293
3294 ViewStmt:  CREATE VIEW qualified_name opt_column_list AS SelectStmt
3295                                 {
3296                                         ViewStmt *n = makeNode(ViewStmt);
3297                                         n->view = $3;
3298                                         n->aliases = $4;
3299                                         n->query = (Query *) $6;
3300                                         $$ = (Node *)n;
3301                                 }
3302                 ;
3303
3304
3305 /*****************************************************************************
3306  *
3307  *              QUERY:
3308  *                              load "filename"
3309  *
3310  *****************************************************************************/
3311
3312 LoadStmt:  LOAD file_name
3313                                 {
3314                                         LoadStmt *n = makeNode(LoadStmt);
3315                                         n->filename = $2;
3316                                         $$ = (Node *)n;
3317                                 }
3318                 ;
3319
3320
3321 /*****************************************************************************
3322  *
3323  *              CREATE DATABASE
3324  *
3325  *****************************************************************************/
3326
3327 CreatedbStmt:  CREATE DATABASE database_name WITH createdb_opt_list
3328                                 {
3329                                         CreatedbStmt *n = makeNode(CreatedbStmt);
3330                                         List   *l;
3331
3332                                         n->dbname = $3;
3333                                         /* set default options */
3334                                         n->dbowner = NULL;
3335                                         n->dbpath = NULL;
3336                                         n->dbtemplate = NULL;
3337                                         n->encoding = -1;
3338                                         /* process additional options */
3339                                         foreach(l, $5)
3340                                         {
3341                                                 List   *optitem = (List *) lfirst(l);
3342
3343                                                 switch (lfirsti(optitem))
3344                                                 {
3345                                                         case 1:
3346                                                                 n->dbpath = (char *) lsecond(optitem);
3347                                                                 break;
3348                                                         case 2:
3349                                                                 n->dbtemplate = (char *) lsecond(optitem);
3350                                                                 break;
3351                                                         case 3:
3352                                                                 n->encoding = lfirsti(lnext(optitem));
3353                                                                 break;
3354                                                         case 4:
3355                                                                 n->dbowner = (char *) lsecond(optitem);
3356                                                                 break;
3357                                                 }
3358                                         }
3359                                         $$ = (Node *)n;
3360                                 }
3361                 | CREATE DATABASE database_name
3362                                 {
3363                                         CreatedbStmt *n = makeNode(CreatedbStmt);
3364                                         n->dbname = $3;
3365                                         n->dbowner = NULL;
3366                                         n->dbpath = NULL;
3367                                         n->dbtemplate = NULL;
3368                                         n->encoding = -1;
3369                                         $$ = (Node *)n;
3370                                 }
3371                 ;
3372
3373 createdb_opt_list:  createdb_opt_item
3374                                 { $$ = makeList1($1); }
3375                 | createdb_opt_list createdb_opt_item
3376                                 { $$ = lappend($1, $2); }
3377                 ;
3378
3379 /*
3380  * createdb_opt_item returns 2-element lists, with the first element
3381  * being an integer code to indicate which item was specified.
3382  */
3383 createdb_opt_item:  LOCATION opt_equal Sconst
3384                                 {
3385                                         $$ = lconsi(1, makeList1($3));
3386                                 }
3387                 | LOCATION opt_equal DEFAULT
3388                                 {
3389                                         $$ = lconsi(1, makeList1(NULL));
3390                                 }
3391                 | TEMPLATE opt_equal name
3392                                 {
3393                                         $$ = lconsi(2, makeList1($3));
3394                                 }
3395                 | TEMPLATE opt_equal DEFAULT
3396                                 {
3397                                         $$ = lconsi(2, makeList1(NULL));
3398                                 }
3399                 | ENCODING opt_equal Sconst
3400                                 {
3401                                         int             encoding;
3402 #ifdef MULTIBYTE
3403                                         encoding = pg_char_to_encoding($3);
3404                                         if (encoding == -1)
3405                                                 elog(ERROR, "%s is not a valid encoding name", $3);
3406 #else
3407                                         if (strcasecmp($3, GetStandardEncodingName()) != 0)
3408                                                 elog(ERROR, "Multi-byte support is not enabled");
3409                                         encoding = GetStandardEncoding();
3410 #endif
3411                                         $$ = lconsi(3, makeListi1(encoding));
3412                                 }
3413                 | ENCODING opt_equal Iconst
3414                                 {
3415 #ifdef MULTIBYTE
3416                                         if (!pg_get_enconv_by_encoding($3))
3417                                                 elog(ERROR, "%d is not a valid encoding code", $3);
3418 #else
3419                                         if ($3 != GetStandardEncoding())
3420                                                 elog(ERROR, "Multi-byte support is not enabled");
3421 #endif
3422                                         $$ = lconsi(3, makeListi1($3));
3423                                 }
3424                 | ENCODING opt_equal DEFAULT
3425                                 {
3426                                         $$ = lconsi(3, makeListi1(-1));
3427                                 }
3428                 | OWNER opt_equal name 
3429                                 {
3430                                         $$ = lconsi(4, makeList1($3));
3431                                 }
3432                 | OWNER opt_equal DEFAULT
3433                                 {
3434                                         $$ = lconsi(4, makeList1(NULL));
3435                                 }
3436                 ;
3437
3438 /*
3439  *      Though the equals sign doesn't match other WITH options, pg_dump uses
3440  *  equals for backward compability, and it doesn't seem worth remove it.
3441  */
3442 opt_equal: '='                                                          { $$ = TRUE; }
3443                 | /*EMPTY*/                                                     { $$ = FALSE; }
3444                 ;
3445
3446
3447 /*****************************************************************************
3448  *
3449  *              ALTER DATABASE
3450  *
3451  *****************************************************************************/
3452
3453 AlterDatabaseSetStmt: ALTER DATABASE database_name SET set_rest
3454                                 {
3455                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
3456                                         n->dbname = $3;
3457                                         n->variable = $5->name;
3458                                         n->value = $5->args;
3459                                         $$ = (Node *)n;
3460                                 }
3461                                 | ALTER DATABASE database_name VariableResetStmt
3462                                 {
3463                                         AlterDatabaseSetStmt *n = makeNode(AlterDatabaseSetStmt);
3464                                         n->dbname = $3;
3465                                         n->variable = ((VariableResetStmt *)$4)->name;
3466                                         n->value = NIL;
3467                                         $$ = (Node *)n;
3468                                 }
3469                 ;
3470
3471
3472 /*****************************************************************************
3473  *
3474  *              DROP DATABASE
3475  *
3476  *****************************************************************************/
3477
3478 DropdbStmt:     DROP DATABASE database_name
3479                                 {
3480                                         DropdbStmt *n = makeNode(DropdbStmt);
3481                                         n->dbname = $3;
3482                                         $$ = (Node *)n;
3483                                 }
3484                 ;
3485
3486
3487 /*****************************************************************************
3488  *
3489  * Manipulate a domain
3490  *
3491  *****************************************************************************/
3492
3493 CreateDomainStmt:  CREATE DOMAIN_P any_name opt_as Typename ColQualList opt_collate
3494                                 {
3495                                         CreateDomainStmt *n = makeNode(CreateDomainStmt);
3496                                         n->domainname = $3;
3497                                         n->typename = $5;
3498                                         n->constraints = $6;
3499                                         
3500                                         if ($7 != NULL)
3501                                                 elog(NOTICE,"CREATE DOMAIN / COLLATE %s not yet "
3502                                                         "implemented; clause ignored", $7);
3503                                         $$ = (Node *)n;
3504                                 }
3505                 ;
3506
3507 opt_as: AS      {$$ = TRUE; }
3508         | /* EMPTY */   {$$ = FALSE; }
3509         ;
3510
3511
3512 /*****************************************************************************
3513  *
3514  *              QUERY:
3515  *                              cluster <index_name> on <qualified_name>
3516  *
3517  *****************************************************************************/
3518
3519 ClusterStmt:  CLUSTER index_name ON qualified_name
3520                                 {
3521                                    ClusterStmt *n = makeNode(ClusterStmt);
3522                                    n->relation = $4;
3523                                    n->indexname = $2;
3524                                    $$ = (Node*)n;
3525                                 }
3526                 ;
3527
3528 /*****************************************************************************
3529  *
3530  *              QUERY:
3531  *                              vacuum
3532  *                              analyze
3533  *
3534  *****************************************************************************/
3535
3536 VacuumStmt:  VACUUM opt_full opt_freeze opt_verbose
3537                                 {
3538                                         VacuumStmt *n = makeNode(VacuumStmt);
3539                                         n->vacuum = true;
3540                                         n->analyze = false;
3541                                         n->full = $2;
3542                                         n->freeze = $3;
3543                                         n->verbose = $4;
3544                                         n->relation = NULL;
3545                                         n->va_cols = NIL;
3546                                         $$ = (Node *)n;
3547                                 }
3548                 | VACUUM opt_full opt_freeze opt_verbose qualified_name
3549                                 {
3550                                         VacuumStmt *n = makeNode(VacuumStmt);
3551                                         n->vacuum = true;
3552                                         n->analyze = false;
3553                                         n->full = $2;
3554                                         n->freeze = $3;
3555                                         n->verbose = $4;
3556                                         n->relation = $5;
3557                                         n->va_cols = NIL;
3558                                         $$ = (Node *)n;
3559                                 }
3560                 | VACUUM opt_full opt_freeze opt_verbose AnalyzeStmt
3561                                 {
3562                                         VacuumStmt *n = (VacuumStmt *) $5;
3563                                         n->vacuum = true;
3564                                         n->full = $2;
3565                                         n->freeze = $3;
3566                                         n->verbose |= $4;
3567                                         $$ = (Node *)n;
3568                                 }
3569                 ;
3570
3571 AnalyzeStmt:  analyze_keyword opt_verbose
3572                                 {
3573                                         VacuumStmt *n = makeNode(VacuumStmt);
3574                                         n->vacuum = false;
3575                                         n->analyze = true;
3576                                         n->full = false;
3577                                         n->freeze = false;
3578                                         n->verbose = $2;
3579                                         n->relation = NULL;
3580                                         n->va_cols = NIL;
3581                                         $$ = (Node *)n;
3582                                 }
3583                 | analyze_keyword opt_verbose qualified_name opt_name_list
3584                                 {
3585                                         VacuumStmt *n = makeNode(VacuumStmt);
3586                                         n->vacuum = false;
3587                                         n->analyze = true;
3588                                         n->full = false;
3589                                         n->freeze = false;
3590                                         n->verbose = $2;
3591                                         n->relation = $3;
3592                                         n->va_cols = $4;
3593                                         $$ = (Node *)n;
3594                                 }
3595                 ;
3596
3597 analyze_keyword:  ANALYZE                                               { $$ = TRUE; }
3598                 |         ANALYSE /* British */                         { $$ = TRUE; }
3599                 ;
3600
3601 opt_verbose:  VERBOSE                                                   { $$ = TRUE; }
3602                 | /*EMPTY*/                                                             { $$ = FALSE; }
3603                 ;
3604
3605 opt_full:  FULL                                                                 { $$ = TRUE; }
3606                 | /*EMPTY*/                                                             { $$ = FALSE; }
3607                 ;
3608
3609 opt_freeze:  FREEZE                                                             { $$ = TRUE; }
3610                 | /*EMPTY*/                                                             { $$ = FALSE; }
3611                 ;
3612
3613 opt_name_list:  '(' name_list ')'                               { $$ = $2; }
3614                 | /*EMPTY*/                                                             { $$ = NIL; }
3615                 ;
3616
3617
3618 /*****************************************************************************
3619  *
3620  *              QUERY:
3621  *                              EXPLAIN query
3622  *                              EXPLAIN ANALYZE query
3623  *
3624  *****************************************************************************/
3625
3626 ExplainStmt:  EXPLAIN opt_verbose OptimizableStmt
3627                                 {
3628                                         ExplainStmt *n = makeNode(ExplainStmt);
3629                                         n->verbose = $2;
3630                                         n->analyze = FALSE;
3631                                         n->query = (Query*)$3;
3632                                         $$ = (Node *)n;
3633                                 }
3634                         | EXPLAIN analyze_keyword opt_verbose OptimizableStmt
3635                                 {
3636                                         ExplainStmt *n = makeNode(ExplainStmt);
3637                                         n->verbose = $3;
3638                                         n->analyze = TRUE;
3639                                         n->query = (Query*)$4;
3640                                         $$ = (Node *)n;
3641                                 }
3642                 ;
3643
3644
3645 /*****************************************************************************
3646  *                                                                                                                                                       *
3647  *              Optimizable Stmts:                                                                                                       *
3648  *                                                                                                                                                       *
3649  *              one of the five queries processed by the planner                                         *
3650  *                                                                                                                                                       *
3651  *              [ultimately] produces query-trees as specified                                           *
3652  *              in the query-spec document in ~postgres/ref                                                      *
3653  *                                                                                                                                                       *
3654  *****************************************************************************/
3655
3656 OptimizableStmt:  SelectStmt
3657                 | CursorStmt
3658                 | UpdateStmt
3659                 | InsertStmt
3660                 | DeleteStmt                                    /* by default all are $$=$1 */
3661                 ;
3662
3663
3664 /*****************************************************************************
3665  *
3666  *              QUERY:
3667  *                              INSERT STATEMENTS
3668  *
3669  *****************************************************************************/
3670
3671 InsertStmt:  INSERT INTO qualified_name insert_rest
3672                                 {
3673                                         $4->relation = $3;
3674                                         $$ = (Node *) $4;
3675                                 }
3676                 ;
3677
3678 insert_rest:  VALUES '(' insert_target_list ')'
3679                                 {
3680                                         $$ = makeNode(InsertStmt);
3681                                         $$->cols = NIL;
3682                                         $$->targetList = $3;
3683                                         $$->selectStmt = NULL;
3684                                 }
3685                 | DEFAULT VALUES
3686                                 {
3687                                         $$ = makeNode(InsertStmt);
3688                                         $$->cols = NIL;
3689                                         $$->targetList = NIL;
3690                                         $$->selectStmt = NULL;
3691                                 }
3692                 | SelectStmt
3693                                 {
3694                                         $$ = makeNode(InsertStmt);
3695                                         $$->cols = NIL;
3696                                         $$->targetList = NIL;
3697                                         $$->selectStmt = $1;
3698                                 }
3699                 | '(' insert_column_list ')' VALUES '(' insert_target_list ')'
3700                                 {
3701                                         $$ = makeNode(InsertStmt);
3702                                         $$->cols = $2;
3703                                         $$->targetList = $6;
3704                                         $$->selectStmt = NULL;
3705                                 }
3706                 | '(' insert_column_list ')' SelectStmt
3707                                 {
3708                                         $$ = makeNode(InsertStmt);
3709                                         $$->cols = $2;
3710                                         $$->targetList = NIL;
3711                                         $$->selectStmt = $4;
3712                                 }
3713                 ;
3714
3715 insert_column_list:  insert_column_list ',' insert_column_item
3716                                 { $$ = lappend($1, $3); }
3717                 | insert_column_item
3718                                 { $$ = makeList1($1); }
3719                 ;
3720
3721 insert_column_item:  ColId opt_indirection
3722                                 {
3723                                         ResTarget *n = makeNode(ResTarget);
3724                                         n->name = $1;
3725                                         n->indirection = $2;
3726                                         n->val = NULL;
3727                                         $$ = (Node *)n;
3728                                 }
3729                 ;
3730
3731
3732 /*****************************************************************************
3733  *
3734  *              QUERY:
3735  *                              DELETE STATEMENTS
3736  *
3737  *****************************************************************************/
3738
3739 DeleteStmt:  DELETE_P FROM relation_expr where_clause
3740                                 {
3741                                         DeleteStmt *n = makeNode(DeleteStmt);
3742                                         n->relation = $3;
3743                                         n->whereClause = $4;
3744                                         $$ = (Node *)n;
3745                                 }
3746                 ;
3747
3748 LockStmt:       LOCK_P opt_table qualified_name_list opt_lock
3749                                 {
3750                                         LockStmt *n = makeNode(LockStmt);
3751
3752                                         n->relations = $3;
3753                                         n->mode = $4;
3754                                         $$ = (Node *)n;
3755                                 }
3756                 ;
3757
3758 opt_lock:  IN_P lock_type MODE  { $$ = $2; }
3759                 | /*EMPTY*/                             { $$ = AccessExclusiveLock; }
3760                 ;
3761
3762 lock_type:  ACCESS SHARE                { $$ = AccessShareLock; }
3763                 | ROW SHARE                             { $$ = RowShareLock; }
3764                 | ROW EXCLUSIVE                 { $$ = RowExclusiveLock; }
3765                 | SHARE UPDATE EXCLUSIVE { $$ = ShareUpdateExclusiveLock; }
3766                 | SHARE                                 { $$ = ShareLock; }
3767                 | SHARE ROW EXCLUSIVE   { $$ = ShareRowExclusiveLock; }
3768                 | EXCLUSIVE                             { $$ = ExclusiveLock; }
3769                 | ACCESS EXCLUSIVE              { $$ = AccessExclusiveLock; }
3770                 ;
3771
3772
3773 /*****************************************************************************
3774  *
3775  *              QUERY:
3776  *                              UpdateStmt (UPDATE)
3777  *
3778  *****************************************************************************/
3779
3780 UpdateStmt:  UPDATE relation_expr
3781                           SET update_target_list
3782                           from_clause
3783                           where_clause
3784                                 {
3785                                         UpdateStmt *n = makeNode(UpdateStmt);
3786                                         n->relation = $2;
3787                                         n->targetList = $4;
3788                                         n->fromClause = $5;
3789                                         n->whereClause = $6;
3790                                         $$ = (Node *)n;
3791                                 }
3792                 ;
3793
3794
3795 /*****************************************************************************
3796  *
3797  *              QUERY:
3798  *                              CURSOR STATEMENTS
3799  *
3800  *****************************************************************************/
3801 CursorStmt:  DECLARE name opt_cursor CURSOR FOR SelectStmt
3802                                 {
3803                                         SelectStmt *n = (SelectStmt *)$6;
3804                                         n->portalname = $2;
3805                                         n->binary = $3;
3806                                         $$ = $6;
3807                                 }
3808                 ;
3809
3810 opt_cursor:  BINARY                                             { $$ = TRUE; }
3811                 | INSENSITIVE                                   { $$ = FALSE; }
3812                 | SCROLL                                                { $$ = FALSE; }
3813                 | INSENSITIVE SCROLL                    { $$ = FALSE; }
3814                 | /*EMPTY*/                                             { $$ = FALSE; }
3815                 ;
3816
3817 /*****************************************************************************
3818  *
3819  *              QUERY:
3820  *                              SELECT STATEMENTS
3821  *
3822  *****************************************************************************/
3823
3824 /* A complete SELECT statement looks like this.
3825  *
3826  * The rule returns either a single SelectStmt node or a tree of them,
3827  * representing a set-operation tree.
3828  *
3829  * There is an ambiguity when a sub-SELECT is within an a_expr and there
3830  * are excess parentheses: do the parentheses belong to the sub-SELECT or
3831  * to the surrounding a_expr?  We don't really care, but yacc wants to know.
3832  * To resolve the ambiguity, we are careful to define the grammar so that
3833  * the decision is staved off as long as possible: as long as we can keep
3834  * absorbing parentheses into the sub-SELECT, we will do so, and only when
3835  * it's no longer possible to do that will we decide that parens belong to
3836  * the expression.  For example, in "SELECT (((SELECT 2)) + 3)" the extra
3837  * parentheses are treated as part of the sub-select.  The necessity of doing
3838  * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)".  Had we
3839  * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
3840  * SELECT viewpoint when we see the UNION.
3841  *
3842  * This approach is implemented by defining a nonterminal select_with_parens,
3843  * which represents a SELECT with at least one outer layer of parentheses,
3844  * and being careful to use select_with_parens, never '(' SelectStmt ')',
3845  * in the expression grammar.  We will then have shift-reduce conflicts
3846  * which we can resolve in favor of always treating '(' <select> ')' as
3847  * a select_with_parens.  To resolve the conflicts, the productions that
3848  * conflict with the select_with_parens productions are manually given
3849  * precedences lower than the precedence of ')', thereby ensuring that we
3850  * shift ')' (and then reduce to select_with_parens) rather than trying to
3851  * reduce the inner <select> nonterminal to something else.  We use UMINUS
3852  * precedence for this, which is a fairly arbitrary choice.
3853  *
3854  * To be able to define select_with_parens itself without ambiguity, we need
3855  * a nonterminal select_no_parens that represents a SELECT structure with no
3856  * outermost parentheses.  This is a little bit tedious, but it works.
3857  *
3858  * In non-expression contexts, we use SelectStmt which can represent a SELECT
3859  * with or without outer parentheses.
3860  */
3861
3862 SelectStmt: select_no_parens                    %prec UMINUS
3863                 | select_with_parens                    %prec UMINUS
3864                 ;
3865
3866 select_with_parens: '(' select_no_parens ')'
3867                         {
3868                                 $$ = $2;
3869                         }
3870                 | '(' select_with_parens ')'
3871                         {
3872                                 $$ = $2;
3873                         }
3874                 ;
3875
3876 select_no_parens: simple_select
3877                         {
3878                                 $$ = $1;
3879                         }
3880                 | select_clause sort_clause opt_for_update_clause opt_select_limit
3881                         {
3882                                 insertSelectOptions((SelectStmt *) $1, $2, $3,
3883                                                                         nth(0, $4), nth(1, $4));
3884                                 $$ = $1;
3885                         }
3886                 | select_clause for_update_clause opt_select_limit
3887                         {
3888                                 insertSelectOptions((SelectStmt *) $1, NIL, $2,
3889                                                                         nth(0, $3), nth(1, $3));
3890                                 $$ = $1;
3891                         }
3892                 | select_clause select_limit
3893                         {
3894                                 insertSelectOptions((SelectStmt *) $1, NIL, NIL,
3895                                                                         nth(0, $2), nth(1, $2));
3896                                 $$ = $1;
3897                         }
3898                 ;
3899
3900 select_clause: simple_select
3901                 | select_with_parens
3902                 ;
3903
3904 /*
3905  * This rule parses SELECT statements that can appear within set operations,
3906  * including UNION, INTERSECT and EXCEPT.  '(' and ')' can be used to specify
3907  * the ordering of the set operations.  Without '(' and ')' we want the
3908  * operations to be ordered per the precedence specs at the head of this file.
3909  *
3910  * As with select_no_parens, simple_select cannot have outer parentheses,
3911  * but can have parenthesized subclauses.
3912  *
3913  * Note that sort clauses cannot be included at this level --- SQL92 requires
3914  *              SELECT foo UNION SELECT bar ORDER BY baz
3915  * to be parsed as
3916  *              (SELECT foo UNION SELECT bar) ORDER BY baz
3917  * not
3918  *              SELECT foo UNION (SELECT bar ORDER BY baz)
3919  * Likewise FOR UPDATE and LIMIT.  Therefore, those clauses are described
3920  * as part of the select_no_parens production, not simple_select.
3921  * This does not limit functionality, because you can reintroduce sort and
3922  * limit clauses inside parentheses.
3923  *
3924  * NOTE: only the leftmost component SelectStmt should have INTO.
3925  * However, this is not checked by the grammar; parse analysis must check it.
3926  */
3927 simple_select: SELECT opt_distinct target_list
3928                          into_clause from_clause where_clause
3929                          group_clause having_clause
3930                                 {
3931                                         SelectStmt *n = makeNode(SelectStmt);
3932                                         n->distinctClause = $2;
3933                                         n->targetList = $3;
3934                                         n->into = $4;
3935                                         n->intoColNames = NIL;
3936                                         n->fromClause = $5;
3937                                         n->whereClause = $6;
3938                                         n->groupClause = $7;
3939                                         n->havingClause = $8;
3940                                         $$ = (Node *)n;
3941                                 }
3942                 | select_clause UNION opt_all select_clause
3943                         {       
3944                                 $$ = makeSetOp(SETOP_UNION, $3, $1, $4);
3945                         }
3946                 | select_clause INTERSECT opt_all select_clause
3947                         {
3948                                 $$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
3949                         }
3950                 | select_clause EXCEPT opt_all select_clause
3951                         {
3952                                 $$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
3953                         }
3954                 ; 
3955
3956 into_clause:  INTO OptTempTableName             { $$ = $2; }
3957                 | /*EMPTY*/             { $$ = NULL; }
3958                 ;
3959
3960 /*
3961  * Redundancy here is needed to avoid shift/reduce conflicts,
3962  * since TEMP is not a reserved word.  See also OptTemp.
3963  */
3964 OptTempTableName:  TEMPORARY opt_table qualified_name
3965                                 { 
3966                                         $$ = $3;
3967                                         $$->istemp = true;
3968                                 }
3969                         | TEMP opt_table qualified_name
3970                                 { 
3971                                         $$ = $3;
3972                                         $$->istemp = true;
3973                                 }
3974                         | LOCAL TEMPORARY opt_table qualified_name
3975                                 { 
3976                                         $$ = $4;
3977                                         $$->istemp = true;
3978                                 }
3979                         | LOCAL TEMP opt_table qualified_name
3980                                 { 
3981                                         $$ = $4;
3982                                         $$->istemp = true;
3983                                 }
3984                         | GLOBAL TEMPORARY opt_table qualified_name
3985                                 {
3986                                         elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
3987                                         $$ = $4;
3988                                         $$->istemp = true;
3989                                 }
3990                         | GLOBAL TEMP opt_table qualified_name
3991                                 {
3992                                         elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
3993                                         $$ = $4;
3994                                         $$->istemp = true;
3995                                 }
3996                         | TABLE qualified_name
3997                                 { 
3998                                         $$ = $2;
3999                                         $$->istemp = false;
4000                                 }
4001                         | qualified_name
4002                                 { 
4003                                         $$ = $1;
4004                                         $$->istemp = false;
4005                                 }
4006                 ;
4007
4008 opt_table:  TABLE                                                               { $$ = TRUE; }
4009                 | /*EMPTY*/                                                             { $$ = FALSE; }
4010                 ;
4011
4012 opt_all:  ALL                                                                   { $$ = TRUE; }
4013                 | /*EMPTY*/                                                             { $$ = FALSE; }
4014                 ;
4015
4016 /* We use (NIL) as a placeholder to indicate that all target expressions
4017  * should be placed in the DISTINCT list during parsetree analysis.
4018  */
4019 opt_distinct:  DISTINCT                                                 { $$ = makeList1(NIL); }
4020                 | DISTINCT ON '(' expr_list ')'                 { $$ = $4; }
4021                 | ALL                                                                   { $$ = NIL; }
4022                 | /*EMPTY*/                                                             { $$ = NIL; }
4023                 ;
4024
4025 sort_clause:  ORDER BY sortby_list                              { $$ = $3; }
4026                 ;
4027
4028 sortby_list:  sortby                                                    { $$ = makeList1($1); }
4029                 | sortby_list ',' sortby                                { $$ = lappend($1, $3); }
4030                 ;
4031
4032 sortby: a_expr OptUseOp
4033                                 {
4034                                         $$ = makeNode(SortGroupBy);
4035                                         $$->node = $1;
4036                                         $$->useOp = $2;
4037                                 }
4038                 ;
4039
4040 OptUseOp:  USING qual_all_Op
4041                                 { $$ = $2; }
4042                 | ASC
4043                                 { $$ = makeList1(makeString("<")); }
4044                 | DESC
4045                                 { $$ = makeList1(makeString(">")); }
4046                 | /*EMPTY*/
4047                                 { $$ = makeList1(makeString("<"));      /*default*/ }
4048                 ;
4049
4050
4051 select_limit:   LIMIT select_limit_value OFFSET select_offset_value
4052                         { $$ = makeList2($4, $2); }
4053                 | OFFSET select_offset_value LIMIT select_limit_value
4054                         { $$ = makeList2($2, $4); }
4055                 | LIMIT select_limit_value
4056                         { $$ = makeList2(NULL, $2); }
4057                 | OFFSET select_offset_value
4058                         { $$ = makeList2($2, NULL); }
4059                 | LIMIT select_limit_value ',' select_offset_value
4060                         /* Disabled because it was too confusing, bjm 2002-02-18 */
4061                         { elog(ERROR, "LIMIT #,# syntax not supported.\n\tUse separate LIMIT and OFFSET clauses."); }
4062                 ;
4063
4064
4065 opt_select_limit:       select_limit                            { $$ = $1; }
4066                 | /* EMPTY */                                                   { $$ = makeList2(NULL,NULL); }
4067                 ;
4068
4069 select_limit_value:  Iconst
4070                         {
4071                                 Const   *n = makeNode(Const);
4072
4073                                 if ($1 < 0)
4074                                         elog(ERROR, "LIMIT must not be negative");
4075
4076                                 n->consttype    = INT4OID;
4077                                 n->constlen             = sizeof(int4);
4078                                 n->constvalue   = Int32GetDatum($1);
4079                                 n->constisnull  = FALSE;
4080                                 n->constbyval   = TRUE;
4081                                 n->constisset   = FALSE;
4082                                 n->constiscast  = FALSE;
4083                                 $$ = (Node *)n;
4084                         }
4085                 | ALL
4086                         {
4087                                 /* LIMIT ALL is represented as a NULL constant */
4088                                 Const   *n = makeNode(Const);
4089
4090                                 n->consttype    = INT4OID;
4091                                 n->constlen             = sizeof(int4);
4092                                 n->constvalue   = (Datum) 0;
4093                                 n->constisnull  = TRUE;
4094                                 n->constbyval   = TRUE;
4095                                 n->constisset   = FALSE;
4096                                 n->constiscast  = FALSE;
4097                                 $$ = (Node *)n;
4098                         }
4099                 | PARAM
4100                         {
4101                                 Param   *n = makeNode(Param);
4102
4103                                 n->paramkind    = PARAM_NUM;
4104                                 n->paramid              = $1;
4105                                 n->paramtype    = INT4OID;
4106                                 $$ = (Node *)n;
4107                         }
4108                 ;
4109
4110 select_offset_value:    Iconst
4111                         {
4112                                 Const   *n = makeNode(Const);
4113
4114                                 if ($1 < 0)
4115                                         elog(ERROR, "OFFSET must not be negative");
4116
4117                                 n->consttype    = INT4OID;
4118                                 n->constlen             = sizeof(int4);
4119                                 n->constvalue   = Int32GetDatum($1);
4120                                 n->constisnull  = FALSE;
4121                                 n->constbyval   = TRUE;
4122                                 n->constisset   = FALSE;
4123                                 n->constiscast  = FALSE;
4124                                 $$ = (Node *)n;
4125                         }
4126                 | PARAM
4127                         {
4128                                 Param   *n = makeNode(Param);
4129
4130                                 n->paramkind    = PARAM_NUM;
4131                                 n->paramid              = $1;
4132                                 n->paramtype    = INT4OID;
4133                                 $$ = (Node *)n;
4134                         }
4135                 ;
4136
4137 /*
4138  *      jimmy bell-style recursive queries aren't supported in the
4139  *      current system.
4140  *
4141  *      ...however, recursive addattr and rename supported.  make special
4142  *      cases for these.
4143  */
4144
4145 group_clause:  GROUP_P BY expr_list                             { $$ = $3; }
4146                 | /*EMPTY*/                                                             { $$ = NIL; }
4147                 ;
4148
4149 having_clause:  HAVING a_expr
4150                                 {
4151                                         $$ = $2;
4152                                 }
4153                 | /*EMPTY*/                                                             { $$ = NULL; }
4154                 ;
4155
4156 for_update_clause:  FOR UPDATE update_list              { $$ = $3; }
4157                 | FOR READ ONLY                                                 { $$ = NULL; }
4158                 ;
4159
4160 opt_for_update_clause:  for_update_clause               { $$ = $1; }
4161                 | /* EMPTY */                                                   { $$ = NULL; }
4162                 ;
4163
4164 update_list:  OF name_list                                              { $$ = $2; }
4165                 | /* EMPTY */                                                   { $$ = makeList1(NULL); }
4166                 ;
4167
4168 /*****************************************************************************
4169  *
4170  *      clauses common to all Optimizable Stmts:
4171  *              from_clause             - allow list of both JOIN expressions and table names
4172  *              where_clause    - qualifications for joins or restrictions
4173  *
4174  *****************************************************************************/
4175
4176 from_clause:  FROM from_list                                    { $$ = $2; }
4177                 | /*EMPTY*/                                                             { $$ = NIL; }
4178                 ;
4179
4180 from_list:  from_list ',' table_ref                             { $$ = lappend($1, $3); }
4181                 | table_ref                                                             { $$ = makeList1($1); }
4182                 ;
4183
4184 /*
4185  * table_ref is where an alias clause can be attached.  Note we cannot make
4186  * alias_clause have an empty production because that causes parse conflicts
4187  * between table_ref := '(' joined_table ')' alias_clause
4188  * and joined_table := '(' joined_table ')'.  So, we must have the
4189  * redundant-looking productions here instead.
4190  */
4191 table_ref:  relation_expr
4192                                 {
4193                                         $$ = (Node *) $1;
4194                                 }
4195                 | relation_expr alias_clause
4196                                 {
4197                                         $1->alias = $2;
4198                                         $$ = (Node *) $1;
4199                                 }
4200                 | func_table
4201                                 {
4202                                         RangeFunction *n = makeNode(RangeFunction);
4203                                         n->funccallnode = $1;
4204                                         $$ = (Node *) n;
4205                                 }
4206                 | func_table alias_clause
4207                                 {
4208                                         RangeFunction *n = makeNode(RangeFunction);
4209                                         n->funccallnode = $1;
4210                                         n->alias = $2;
4211                                         $$ = (Node *) n;
4212                                 }
4213                 | select_with_parens
4214                                 {
4215                                         /*
4216                                          * The SQL spec does not permit a subselect
4217                                          * (<derived_table>) without an alias clause,
4218                                          * so we don't either.  This avoids the problem
4219                                          * of needing to invent a unique refname for it.
4220                                          * That could be surmounted if there's sufficient
4221                                          * popular demand, but for now let's just implement
4222                                          * the spec and see if anyone complains.
4223                                          * However, it does seem like a good idea to emit
4224                                          * an error message that's better than "parse error".
4225                                          */
4226                                         elog(ERROR, "sub-SELECT in FROM must have an alias"
4227                                                  "\n\tFor example, FROM (SELECT ...) [AS] foo");
4228                                         $$ = NULL;
4229                                 }
4230                 | select_with_parens alias_clause
4231                                 {
4232                                         RangeSubselect *n = makeNode(RangeSubselect);
4233                                         n->subquery = $1;
4234                                         n->alias = $2;
4235                                         $$ = (Node *) n;
4236                                 }
4237                 | joined_table
4238                                 {
4239                                         $$ = (Node *) $1;
4240                                 }
4241                 | '(' joined_table ')' alias_clause
4242                                 {
4243                                         $2->alias = $4;
4244                                         $$ = (Node *) $2;
4245                                 }
4246                 ;
4247
4248
4249 /*
4250  * It may seem silly to separate joined_table from table_ref, but there is
4251  * method in SQL92's madness: if you don't do it this way you get reduce-
4252  * reduce conflicts, because it's not clear to the parser generator whether
4253  * to expect alias_clause after ')' or not.  For the same reason we must
4254  * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
4255  * join_type to expand to empty; if we try it, the parser generator can't
4256  * figure out when to reduce an empty join_type right after table_ref.
4257  *
4258  * Note that a CROSS JOIN is the same as an unqualified
4259  * INNER JOIN, and an INNER JOIN/ON has the same shape
4260  * but a qualification expression to limit membership.
4261  * A NATURAL JOIN implicitly matches column names between
4262  * tables and the shape is determined by which columns are
4263  * in common. We'll collect columns during the later transformations.
4264  */
4265
4266 joined_table:  '(' joined_table ')'
4267                                 {
4268                                         $$ = $2;
4269                                 }
4270                 | table_ref CROSS JOIN table_ref
4271                                 {
4272                                         /* CROSS JOIN is same as unqualified inner join */
4273                                         JoinExpr *n = makeNode(JoinExpr);
4274                                         n->jointype = JOIN_INNER;
4275                                         n->isNatural = FALSE;
4276                                         n->larg = $1;
4277                                         n->rarg = $4;
4278                                         n->using = NIL;
4279                                         n->quals = NULL;
4280                                         $$ = n;
4281                                 }
4282                 | table_ref UNIONJOIN table_ref
4283                                 {
4284                                         /* UNION JOIN is made into 1 token to avoid shift/reduce
4285                                          * conflict against regular UNION keyword.
4286                                          */
4287                                         JoinExpr *n = makeNode(JoinExpr);
4288                                         n->jointype = JOIN_UNION;
4289                                         n->isNatural = FALSE;
4290                                         n->larg = $1;
4291                                         n->rarg = $3;
4292                                         n->using = NIL;
4293                                         n->quals = NULL;
4294                                         $$ = n;
4295                                 }
4296                 | table_ref join_type JOIN table_ref join_qual
4297                                 {
4298                                         JoinExpr *n = makeNode(JoinExpr);
4299                                         n->jointype = $2;
4300                                         n->isNatural = FALSE;
4301                                         n->larg = $1;
4302                                         n->rarg = $4;
4303                                         if ($5 != NULL && IsA($5, List))
4304                                                 n->using = (List *) $5; /* USING clause */
4305                                         else
4306                                                 n->quals = $5; /* ON clause */
4307                                         $$ = n;
4308                                 }
4309                 | table_ref JOIN table_ref join_qual
4310                                 {
4311                                         /* letting join_type reduce to empty doesn't work */
4312                                         JoinExpr *n = makeNode(JoinExpr);
4313                                         n->jointype = JOIN_INNER;
4314                                         n->isNatural = FALSE;
4315                                         n->larg = $1;
4316                                         n->rarg = $3;
4317                                         if ($4 != NULL && IsA($4, List))
4318                                                 n->using = (List *) $4; /* USING clause */
4319                                         else
4320                                                 n->quals = $4; /* ON clause */
4321                                         $$ = n;
4322                                 }
4323                 | table_ref NATURAL join_type JOIN table_ref
4324                                 {
4325                                         JoinExpr *n = makeNode(JoinExpr);
4326                                         n->jointype = $3;
4327                                         n->isNatural = TRUE;
4328                                         n->larg = $1;
4329                                         n->rarg = $5;
4330                                         n->using = NIL; /* figure out which columns later... */
4331                                         n->quals = NULL; /* fill later */
4332                                         $$ = n;
4333                                 }
4334                 | table_ref NATURAL JOIN table_ref
4335                                 {
4336                                         /* letting join_type reduce to empty doesn't work */
4337                                         JoinExpr *n = makeNode(JoinExpr);
4338                                         n->jointype = JOIN_INNER;
4339                                         n->isNatural = TRUE;
4340                                         n->larg = $1;
4341                                         n->rarg = $4;
4342                                         n->using = NIL; /* figure out which columns later... */
4343                                         n->quals = NULL; /* fill later */
4344                                         $$ = n;
4345                                 }
4346                 ;
4347
4348 alias_clause:  AS ColId '(' name_list ')'
4349                                 {
4350                                         $$ = makeNode(Alias);
4351                                         $$->aliasname = $2;
4352                                         $$->colnames = $4;
4353                                 }
4354                 | AS ColId
4355                                 {
4356                                         $$ = makeNode(Alias);
4357                                         $$->aliasname = $2;
4358                                 }
4359                 | ColId '(' name_list ')'
4360                                 {
4361                                         $$ = makeNode(Alias);
4362                                         $$->aliasname = $1;
4363                                         $$->colnames = $3;
4364                                 }
4365                 | ColId
4366                                 {
4367                                         $$ = makeNode(Alias);
4368                                         $$->aliasname = $1;
4369                                 }
4370                 ;
4371
4372 join_type:  FULL join_outer                                             { $$ = JOIN_FULL; }
4373                 | LEFT join_outer                                               { $$ = JOIN_LEFT; }
4374                 | RIGHT join_outer                                              { $$ = JOIN_RIGHT; }
4375                 | INNER_P                                                               { $$ = JOIN_INNER; }
4376                 ;
4377
4378 /* OUTER is just noise... */
4379 join_outer:  OUTER_P                                                    { $$ = NULL; }
4380                 | /*EMPTY*/                                                             { $$ = NULL; }
4381                 ;
4382
4383 /* JOIN qualification clauses
4384  * Possibilities are:
4385  *  USING ( column list ) allows only unqualified column names,
4386  *                        which must match between tables.
4387  *  ON expr allows more general qualifications.
4388  *
4389  * We return USING as a List node, while an ON-expr will not be a List.
4390  */
4391
4392 join_qual:  USING '(' name_list ')'                             { $$ = (Node *) $3; }
4393                 | ON a_expr                                                             { $$ = $2; }
4394                 ;
4395
4396
4397 relation_expr:  qualified_name
4398                                 {
4399                                         /* default inheritance */
4400                                         $$ = $1;
4401                                         $$->inhOpt = INH_DEFAULT;
4402                                         $$->alias = NULL;
4403                                 }
4404                 | qualified_name '*'
4405                                 {
4406                                         /* inheritance query */
4407                                         $$ = $1;
4408                                         $$->inhOpt = INH_YES;
4409                                         $$->alias = NULL;
4410                                 }
4411                 | ONLY qualified_name
4412                                 {
4413                                         /* no inheritance */
4414                                         $$ = $2;
4415                                         $$->inhOpt = INH_NO;
4416                                         $$->alias = NULL;
4417                 }
4418                 ;
4419
4420
4421 func_table:  func_name '(' ')'
4422                                 {
4423                                         FuncCall *n = makeNode(FuncCall);
4424                                         n->funcname = $1;
4425                                         n->args = NIL;
4426                                         n->agg_star = FALSE;
4427                                         n->agg_distinct = FALSE;
4428                                         $$ = (Node *)n;
4429                                 }
4430                 | func_name '(' expr_list ')'
4431                                 {
4432                                         FuncCall *n = makeNode(FuncCall);
4433                                         n->funcname = $1;
4434                                         n->args = $3;
4435                                         n->agg_star = FALSE;
4436                                         n->agg_distinct = FALSE;
4437                                         $$ = (Node *)n;
4438                                 }
4439                 ;
4440
4441
4442 where_clause:  WHERE a_expr                                             { $$ = $2; }
4443                 | /*EMPTY*/                                                             { $$ = NULL;  /* no qualifiers */ }
4444                 ;
4445
4446
4447 /*****************************************************************************
4448  *
4449  *      Type syntax
4450  *              SQL92 introduces a large amount of type-specific syntax.
4451  *              Define individual clauses to handle these cases, and use
4452  *               the generic case to handle regular type-extensible Postgres syntax.
4453  *              - thomas 1997-10-10
4454  *
4455  *****************************************************************************/
4456
4457 Typename:  SimpleTypename opt_array_bounds
4458                                 {
4459                                         $$ = $1;
4460                                         $$->arrayBounds = $2;
4461                                 }
4462                 | SETOF SimpleTypename
4463                                 {
4464                                         $$ = $2;
4465                                         $$->setof = TRUE;
4466                                 }
4467                 ;
4468
4469 opt_array_bounds:       opt_array_bounds '[' ']'
4470                                 {  $$ = lappend($1, makeInteger(-1)); }
4471                 | opt_array_bounds '[' Iconst ']'
4472                                 {  $$ = lappend($1, makeInteger($3)); }
4473                 | /*EMPTY*/
4474                                 {  $$ = NIL; }
4475                 ;
4476
4477 /*
4478  * XXX ideally, the production for a qualified typename should be ColId attrs
4479  * (there's no obvious reason why the first name should need to be restricted)
4480  * and should be an alternative of GenericType (so that it can be used to
4481  * specify a type for a literal in AExprConst).  However doing either causes
4482  * reduce/reduce conflicts that I haven't been able to find a workaround
4483  * for.  FIXME later.
4484  */
4485 SimpleTypename:  ConstTypename
4486                 | ConstInterval opt_interval
4487                                 {
4488                                         $$ = $1;
4489                                         if ($2 != -1)
4490                                                 $$->typmod = ((($2 & 0x7FFF) << 16) | 0xFFFF);
4491                                 }
4492                 | ConstInterval '(' Iconst ')' opt_interval
4493                                 {
4494                                         $$ = $1;
4495                                         if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
4496                                                 elog(ERROR, "INTERVAL(%d) precision must be between %d and %d",
4497                                                          $3, 0, MAX_INTERVAL_PRECISION);
4498                                         $$->typmod = ((($5 & 0x7FFF) << 16) | $3);
4499                                 }
4500                 | type_name attrs
4501                                 {
4502                                         $$ = makeNode(TypeName);
4503                                         $$->names = lcons(makeString($1), $2);
4504                                         $$->typmod = -1;
4505                                 }
4506                 ;
4507
4508 ConstTypename:  GenericType
4509                 | Numeric
4510                 | Bit
4511                 | Character
4512                 | ConstDatetime
4513                 ;
4514
4515 GenericType:  type_name
4516                                 {
4517                                         $$ = makeTypeName($1);
4518                                 }
4519                 ;
4520
4521 /* SQL92 numeric data types
4522  * Check FLOAT() precision limits assuming IEEE floating types.
4523  * Provide real DECIMAL() and NUMERIC() implementations now - Jan 1998-12-30
4524  * - thomas 1997-09-18
4525  */
4526 Numeric:  INT
4527                                 {
4528                                         $$ = SystemTypeName("int4");
4529                                 }
4530                 | INTEGER
4531                                 {
4532                                         $$ = SystemTypeName("int4");
4533                                 }
4534                 | SMALLINT
4535                                 {
4536                                         $$ = SystemTypeName("int2");
4537                                 }
4538                 | BIGINT
4539                                 {
4540                                         $$ = SystemTypeName("int8");
4541                                 }
4542                 | REAL
4543                                 {
4544                                         $$ = SystemTypeName("float4");
4545                                 }
4546                 | FLOAT_P opt_float
4547                                 {
4548                                         $$ = $2;
4549                                 }
4550                 | DOUBLE PRECISION
4551                                 {
4552                                         $$ = SystemTypeName("float8");
4553                                 }
4554                 | DECIMAL opt_decimal
4555                                 {
4556                                         $$ = SystemTypeName("numeric");
4557                                         $$->typmod = $2;
4558                                 }
4559                 | DEC opt_decimal
4560                                 {
4561                                         $$ = SystemTypeName("numeric");
4562                                         $$->typmod = $2;
4563                                 }
4564                 | NUMERIC opt_numeric
4565                                 {
4566                                         $$ = SystemTypeName("numeric");
4567                                         $$->typmod = $2;
4568                                 }
4569                 | BOOLEAN
4570                                 {
4571                                         $$ = SystemTypeName("bool");
4572                                 }
4573                 ;
4574
4575 opt_float:  '(' Iconst ')'
4576                                 {
4577                                         if ($2 < 1)
4578                                                 elog(ERROR, "precision for FLOAT must be at least 1");
4579                                         else if ($2 < 7)
4580                                                 $$ = SystemTypeName("float4");
4581                                         else if ($2 < 16)
4582                                                 $$ = SystemTypeName("float8");
4583                                         else
4584                                                 elog(ERROR, "precision for FLOAT must be less than 16");
4585                                 }
4586                 | /*EMPTY*/
4587                                 {
4588                                         $$ = SystemTypeName("float8");
4589                                 }
4590                 ;
4591
4592 opt_numeric:  '(' Iconst ',' Iconst ')'
4593                                 {
4594                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4595                                                 elog(ERROR, "NUMERIC precision %d must be between 1 and %d",
4596                                                          $2, NUMERIC_MAX_PRECISION);
4597                                         if ($4 < 0 || $4 > $2)
4598                                                 elog(ERROR, "NUMERIC scale %d must be between 0 and precision %d",
4599                                                          $4,$2);
4600
4601                                         $$ = (($2 << 16) | $4) + VARHDRSZ;
4602                                 }
4603                 | '(' Iconst ')'
4604                                 {
4605                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4606                                                 elog(ERROR, "NUMERIC precision %d must be between 1 and %d",
4607                                                          $2, NUMERIC_MAX_PRECISION);
4608
4609                                         $$ = ($2 << 16) + VARHDRSZ;
4610                                 }
4611                 | /*EMPTY*/
4612                                 {
4613                                         /* Insert "-1" meaning "no limit" */
4614                                         $$ = -1;
4615                                 }
4616                 ;
4617
4618 opt_decimal:  '(' Iconst ',' Iconst ')'
4619                                 {
4620                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4621                                                 elog(ERROR, "DECIMAL precision %d must be between 1 and %d",
4622                                                                         $2, NUMERIC_MAX_PRECISION);
4623                                         if ($4 < 0 || $4 > $2)
4624                                                 elog(ERROR, "DECIMAL scale %d must be between 0 and precision %d",
4625                                                                         $4,$2);
4626
4627                                         $$ = (($2 << 16) | $4) + VARHDRSZ;
4628                                 }
4629                 | '(' Iconst ')'
4630                                 {
4631                                         if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
4632                                                 elog(ERROR, "DECIMAL precision %d must be between 1 and %d",
4633                                                                         $2, NUMERIC_MAX_PRECISION);
4634
4635                                         $$ = ($2 << 16) + VARHDRSZ;
4636                                 }
4637                 | /*EMPTY*/
4638                                 {
4639                                         /* Insert "-1" meaning "no limit" */
4640                                         $$ = -1;
4641                                 }
4642                 ;
4643
4644
4645 /*
4646  * SQL92 bit-field data types
4647  * The following implements BIT() and BIT VARYING().
4648  */
4649 Bit:  BIT opt_varying '(' Iconst ')'
4650                                 {
4651                                         char *typname;
4652
4653                                         typname = $2 ? "varbit" : "bit";
4654                                         $$ = SystemTypeName(typname);
4655                                         if ($4 < 1)
4656                                                 elog(ERROR, "length for type '%s' must be at least 1",
4657                                                          typname);
4658                                         else if ($4 > (MaxAttrSize * BITS_PER_BYTE))
4659                                                 elog(ERROR, "length for type '%s' cannot exceed %d",
4660                                                          typname, (MaxAttrSize * BITS_PER_BYTE));
4661                                         $$->typmod = $4;
4662                                 }
4663                 | BIT opt_varying
4664                                 {
4665                                         /* bit defaults to bit(1), varbit to no limit */
4666                                         if ($2)
4667                                         {
4668                                                 $$ = SystemTypeName("varbit");
4669                                                 $$->typmod = -1;
4670                                         }
4671                                         else
4672                                         {
4673                                                 $$ = SystemTypeName("bit");
4674                                                 $$->typmod = 1;
4675                                         }
4676                                 }
4677                 ;
4678
4679
4680 /*
4681  * SQL92 character data types
4682  * The following implements CHAR() and VARCHAR().
4683  */
4684 Character:  character '(' Iconst ')' opt_charset
4685                                 {
4686                                         if (($5 != NULL) && (strcmp($5, "sql_text") != 0))
4687                                         {
4688                                                 char *type;
4689
4690                                                 type = palloc(strlen($1) + 1 + strlen($5) + 1);
4691                                                 strcpy(type, $1);
4692                                                 strcat(type, "_");
4693                                                 strcat(type, $5);
4694                                                 $1 = type;
4695                                         }
4696
4697                                         $$ = SystemTypeName($1);
4698
4699                                         if ($3 < 1)
4700                                                 elog(ERROR, "length for type '%s' must be at least 1",
4701                                                          $1);
4702                                         else if ($3 > MaxAttrSize)
4703                                                 elog(ERROR, "length for type '%s' cannot exceed %d",
4704                                                          $1, MaxAttrSize);
4705
4706                                         /* we actually implement these like a varlen, so
4707                                          * the first 4 bytes is the length. (the difference
4708                                          * between these and "text" is that we blank-pad and
4709                                          * truncate where necessary)
4710                                          */
4711                                         $$->typmod = VARHDRSZ + $3;
4712                                 }
4713                 | character opt_charset
4714                                 {
4715                                         if (($2 != NULL) && (strcmp($2, "sql_text") != 0))
4716                                         {
4717                                                 char *type;
4718
4719                                                 type = palloc(strlen($1) + 1 + strlen($2) + 1);
4720                                                 strcpy(type, $1);
4721                                                 strcat(type, "_");
4722                                                 strcat(type, $2);
4723                                                 $1 = type;
4724                                         }
4725
4726                                         $$ = SystemTypeName($1);
4727
4728                                         /* char defaults to char(1), varchar to no limit */
4729                                         if (strcmp($1, "bpchar") == 0)
4730                                                 $$->typmod = VARHDRSZ + 1;
4731                                         else
4732                                                 $$->typmod = -1;
4733                                 }
4734                 ;
4735
4736 character:  CHARACTER opt_varying                               { $$ = $2 ? "varchar": "bpchar"; }
4737                 | CHAR_P opt_varying                                            { $$ = $2 ? "varchar": "bpchar"; }
4738                 | VARCHAR                                                               { $$ = "varchar"; }
4739                 | NATIONAL CHARACTER opt_varying                { $$ = $3 ? "varchar": "bpchar"; }
4740                 | NATIONAL CHAR_P opt_varying                           { $$ = $3 ? "varchar": "bpchar"; }
4741                 | NCHAR opt_varying                                             { $$ = $2 ? "varchar": "bpchar"; }
4742                 ;
4743
4744 opt_varying:  VARYING                                                   { $$ = TRUE; }
4745                 | /*EMPTY*/                                                             { $$ = FALSE; }
4746                 ;
4747
4748 opt_charset:  CHARACTER SET ColId                               { $$ = $3; }
4749                 | /*EMPTY*/                                                             { $$ = NULL; }
4750                 ;
4751
4752 opt_collate:  COLLATE ColId                                             { $$ = $2; }
4753                 | /*EMPTY*/                                                             { $$ = NULL; }
4754                 ;
4755
4756 ConstDatetime:  TIMESTAMP '(' Iconst ')' opt_timezone
4757                                 {
4758                                         if ($5)
4759                                                 $$ = SystemTypeName("timestamptz");
4760                                         else
4761                                                 $$ = SystemTypeName("timestamp");
4762                                         /* XXX the timezone field seems to be unused
4763                                          * - thomas 2001-09-06
4764                                          */
4765                                         $$->timezone = $5;
4766                                         if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
4767                                                 elog(ERROR, "TIMESTAMP(%d)%s precision must be between %d and %d",
4768                                                          $3, ($5 ? " WITH TIME ZONE": ""), 0, MAX_TIMESTAMP_PRECISION);
4769                                         $$->typmod = $3;
4770                                 }
4771                 | TIMESTAMP opt_timezone
4772                                 {
4773                                         if ($2)
4774                                                 $$ = SystemTypeName("timestamptz");
4775                                         else
4776                                                 $$ = SystemTypeName("timestamp");
4777                                         /* XXX the timezone field seems to be unused
4778                                          * - thomas 2001-09-06
4779                                          */
4780                                         $$->timezone = $2;
4781                                         /* SQL99 specified a default precision of six
4782                                          * for schema definitions. But for timestamp
4783                                          * literals we don't want to throw away precision
4784                                          * so leave this as unspecified for now.
4785                                          * Later, we may want a different production
4786                                          * for schemas. - thomas 2001-12-07
4787                                          */
4788                                         $$->typmod = -1;
4789                                 }
4790                 | TIME '(' Iconst ')' opt_timezone
4791                                 {
4792                                         if ($5)
4793                                                 $$ = SystemTypeName("timetz");
4794                                         else
4795                                                 $$ = SystemTypeName("time");
4796                                         if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
4797                                                 elog(ERROR, "TIME(%d)%s precision must be between %d and %d",
4798                                                          $3, ($5 ? " WITH TIME ZONE": ""), 0, MAX_TIME_PRECISION);
4799                                         $$->typmod = $3;
4800                                 }
4801                 | TIME opt_timezone
4802                                 {
4803                                         if ($2)
4804                                                 $$ = SystemTypeName("timetz");
4805                                         else
4806                                                 $$ = SystemTypeName("time");
4807                                         /* SQL99 specified a default precision of zero.
4808                                          * See comments for timestamp above on why we will
4809                                          * leave this unspecified for now. - thomas 2001-12-07
4810                                          */
4811                                         $$->typmod = -1;
4812                                 }
4813                 ;
4814
4815 ConstInterval:  INTERVAL
4816                                 {
4817                                         $$ = SystemTypeName("interval");
4818                                 }
4819                 ;
4820
4821 opt_timezone:  WITH TIME ZONE                                   { $$ = TRUE; }
4822                 | WITHOUT TIME ZONE                                             { $$ = FALSE; }
4823                 | /*EMPTY*/                                                             { $$ = FALSE; }
4824                 ;
4825
4826 opt_interval:  YEAR_P                                                   { $$ = MASK(YEAR); }
4827                 | MONTH_P                                                               { $$ = MASK(MONTH); }
4828                 | DAY_P                                                                 { $$ = MASK(DAY); }
4829                 | HOUR_P                                                                { $$ = MASK(HOUR); }
4830                 | MINUTE_P                                                              { $$ = MASK(MINUTE); }
4831                 | SECOND_P                                                              { $$ = MASK(SECOND); }
4832                 | YEAR_P TO MONTH_P                                             { $$ = MASK(YEAR) | MASK(MONTH); }
4833                 | DAY_P TO HOUR_P                                               { $$ = MASK(DAY) | MASK(HOUR); }
4834                 | DAY_P TO MINUTE_P                                             { $$ = MASK(DAY) | MASK(HOUR) | MASK(MINUTE); }
4835                 | DAY_P TO SECOND_P                                             { $$ = MASK(DAY) | MASK(HOUR) | MASK(MINUTE) | MASK(SECOND); }
4836                 | HOUR_P TO MINUTE_P                                    { $$ = MASK(HOUR) | MASK(MINUTE); }
4837                 | HOUR_P TO SECOND_P                                    { $$ = MASK(HOUR) | MASK(MINUTE) | MASK(SECOND); }
4838                 | MINUTE_P TO SECOND_P                                  { $$ = MASK(MINUTE) | MASK(SECOND); }
4839                 | /*EMPTY*/                                                             { $$ = -1; }
4840                 ;
4841
4842
4843 /*****************************************************************************
4844  *
4845  *      expression grammar
4846  *
4847  *****************************************************************************/
4848
4849 /* Expressions using row descriptors
4850  * Define row_descriptor to allow yacc to break the reduce/reduce conflict
4851  *  with singleton expressions.
4852  */
4853 row_expr: '(' row_descriptor ')' IN_P select_with_parens
4854                                 {
4855                                         SubLink *n = makeNode(SubLink);
4856                                         n->lefthand = $2;
4857                                         n->oper = (List *) makeSimpleA_Expr(OP, "=", NULL, NULL);
4858                                         n->useor = FALSE;
4859                                         n->subLinkType = ANY_SUBLINK;
4860                                         n->subselect = $5;
4861                                         $$ = (Node *)n;
4862                                 }
4863                 | '(' row_descriptor ')' NOT IN_P select_with_parens
4864                                 {
4865                                         SubLink *n = makeNode(SubLink);
4866                                         n->lefthand = $2;
4867                                         n->oper = (List *) makeSimpleA_Expr(OP, "<>", NULL, NULL);
4868                                         n->useor = TRUE;
4869                                         n->subLinkType = ALL_SUBLINK;
4870                                         n->subselect = $6;
4871                                         $$ = (Node *)n;
4872                                 }
4873                 | '(' row_descriptor ')' qual_all_Op sub_type select_with_parens        %prec Op
4874                                 {
4875                                         SubLink *n = makeNode(SubLink);
4876                                         n->lefthand = $2;
4877                                         n->oper = (List *) makeA_Expr(OP, $4, NULL, NULL);
4878                                         if (strcmp(strVal(llast($4)), "<>") == 0)
4879                                                 n->useor = TRUE;
4880                                         else
4881                                                 n->useor = FALSE;
4882                                         n->subLinkType = $5;
4883                                         n->subselect = $6;
4884                                         $$ = (Node *)n;
4885                                 }
4886                 | '(' row_descriptor ')' qual_all_Op select_with_parens         %prec Op
4887                                 {
4888                                         SubLink *n = makeNode(SubLink);
4889                                         n->lefthand = $2;
4890                                         n->oper = (List *) makeA_Expr(OP, $4, NULL, NULL);
4891                                         if (strcmp(strVal(llast($4)), "<>") == 0)
4892                                                 n->useor = TRUE;
4893                                         else
4894                                                 n->useor = FALSE;
4895                                         n->subLinkType = MULTIEXPR_SUBLINK;
4896                                         n->subselect = $5;
4897                                         $$ = (Node *)n;
4898                                 }
4899                 | '(' row_descriptor ')' qual_all_Op '(' row_descriptor ')'             %prec Op
4900                                 {
4901                                         $$ = makeRowExpr($4, $2, $6);
4902                                 }
4903                 | '(' row_descriptor ')' OVERLAPS '(' row_descriptor ')'
4904                                 {
4905                                         FuncCall *n = makeNode(FuncCall);
4906                                         List *largs = $2;
4907                                         List *rargs = $6;
4908                                         n->funcname = SystemFuncName("overlaps");
4909                                         if (length(largs) == 1)
4910                                                 largs = lappend(largs, $2);
4911                                         else if (length(largs) != 2)
4912                                                 elog(ERROR, "Wrong number of parameters"
4913                                                          " on left side of OVERLAPS expression");
4914                                         if (length(rargs) == 1)
4915                                                 rargs = lappend(rargs, $6);
4916                                         else if (length(rargs) != 2)
4917                                                 elog(ERROR, "Wrong number of parameters"
4918                                                          " on right side of OVERLAPS expression");
4919                                         n->args = nconc(largs, rargs);
4920                                         n->agg_star = FALSE;
4921                                         n->agg_distinct = FALSE;
4922                                         $$ = (Node *)n;
4923                                 }
4924                 ;
4925
4926 row_descriptor:  row_list ',' a_expr
4927                                 {
4928                                         $$ = lappend($1, $3);
4929                                 }
4930                 ;
4931
4932 row_list:  row_list ',' a_expr
4933                                 {
4934                                         $$ = lappend($1, $3);
4935                                 }
4936                 | a_expr
4937                                 {
4938                                         $$ = makeList1($1);
4939                                 }
4940                 ;
4941
4942 sub_type:  ANY                                                          { $$ = ANY_SUBLINK; }
4943                 | SOME                                                          { $$ = ANY_SUBLINK; }
4944                 | ALL                                                           { $$ = ALL_SUBLINK; }
4945                 ;
4946
4947 all_Op:  Op | MathOp;
4948
4949 MathOp:  '+'                    { $$ = "+"; }
4950                 | '-'                   { $$ = "-"; }
4951                 | '*'                   { $$ = "*"; }
4952                 | '/'                   { $$ = "/"; }
4953                 | '%'                   { $$ = "%"; }
4954                 | '^'                   { $$ = "^"; }
4955                 | '<'                   { $$ = "<"; }
4956                 | '>'                   { $$ = ">"; }
4957                 | '='                   { $$ = "="; }
4958                 ;
4959
4960 qual_Op:  Op
4961                         { $$ = makeList1(makeString($1)); }
4962                 |  OPERATOR '(' any_operator ')'
4963                         { $$ = $3; }
4964                 ;
4965
4966 qual_all_Op:  all_Op
4967                         { $$ = makeList1(makeString($1)); }
4968                 |  OPERATOR '(' any_operator ')'
4969                         { $$ = $3; }
4970                 ;
4971
4972 /*
4973  * General expressions
4974  * This is the heart of the expression syntax.
4975  *
4976  * We have two expression types: a_expr is the unrestricted kind, and
4977  * b_expr is a subset that must be used in some places to avoid shift/reduce
4978  * conflicts.  For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
4979  * because that use of AND conflicts with AND as a boolean operator.  So,
4980  * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
4981  *
4982  * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
4983  * always be used by surrounding it with parens.
4984  *
4985  * c_expr is all the productions that are common to a_expr and b_expr;
4986  * it's factored out just to eliminate redundant coding.
4987  */
4988 a_expr:  c_expr
4989                                 {       $$ = $1; }
4990                 | a_expr TYPECAST Typename
4991                                 {       $$ = makeTypeCast($1, $3); }
4992                 | a_expr COLLATE ColId
4993                                 {
4994                                         FuncCall *n = makeNode(FuncCall);
4995                                         n->funcname = SystemFuncName($3);
4996                                         n->args = makeList1($1);
4997                                         n->agg_star = FALSE;
4998                                         n->agg_distinct = FALSE;
4999                                         $$ = (Node *) n;
5000                                 }
5001                 | a_expr AT TIME ZONE c_expr
5002                                 {
5003                                         FuncCall *n = makeNode(FuncCall);
5004                                         n->funcname = SystemFuncName("timezone");
5005                                         n->args = makeList2($5, $1);
5006                                         n->agg_star = FALSE;
5007                                         n->agg_distinct = FALSE;
5008                                         $$ = (Node *) n;
5009                                 }
5010                 /*
5011                  * These operators must be called out explicitly in order to make use
5012                  * of yacc/bison's automatic operator-precedence handling.  All other
5013                  * operator names are handled by the generic productions using "Op",
5014                  * below; and all those operators will have the same precedence.
5015                  *
5016                  * If you add more explicitly-known operators, be sure to add them
5017                  * also to b_expr and to the MathOp list above.
5018                  */
5019                 | '+' a_expr                                    %prec UMINUS
5020                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "+", NULL, $2); }
5021                 | '-' a_expr                                    %prec UMINUS
5022                                 {       $$ = doNegate($2); }
5023                 | '%' a_expr
5024                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "%", NULL, $2); }
5025                 | '^' a_expr
5026                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "^", NULL, $2); }
5027                 | a_expr '%'
5028                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, NULL); }
5029                 | a_expr '^'
5030                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, NULL); }
5031                 | a_expr '+' a_expr
5032                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "+", $1, $3); }
5033                 | a_expr '-' a_expr
5034                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "-", $1, $3); }
5035                 | a_expr '*' a_expr
5036                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "*", $1, $3); }
5037                 | a_expr '/' a_expr
5038                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "/", $1, $3); }
5039                 | a_expr '%' a_expr
5040                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, $3); }
5041                 | a_expr '^' a_expr
5042                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, $3); }
5043                 | a_expr '<' a_expr
5044                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "<", $1, $3); }
5045                 | a_expr '>' a_expr
5046                                 {       $$ = (Node *) makeSimpleA_Expr(OP, ">", $1, $3); }
5047                 | a_expr '=' a_expr
5048                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "=", $1, $3); }
5049
5050                 | a_expr qual_Op a_expr                         %prec Op
5051                                 {       $$ = (Node *) makeA_Expr(OP, $2, $1, $3); }
5052                 | qual_Op a_expr                                        %prec Op
5053                                 {       $$ = (Node *) makeA_Expr(OP, $1, NULL, $2); }
5054                 | a_expr qual_Op                                        %prec POSTFIXOP
5055                                 {       $$ = (Node *) makeA_Expr(OP, $2, $1, NULL); }
5056
5057                 | a_expr AND a_expr
5058                                 {       $$ = (Node *) makeA_Expr(AND, NIL, $1, $3); }
5059                 | a_expr OR a_expr
5060                                 {       $$ = (Node *) makeA_Expr(OR, NIL, $1, $3); }
5061                 | NOT a_expr
5062                                 {       $$ = (Node *) makeA_Expr(NOT, NIL, NULL, $2); }
5063
5064                 | a_expr LIKE a_expr
5065                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "~~", $1, $3); }
5066                 | a_expr LIKE a_expr ESCAPE a_expr
5067                                 {
5068                                         FuncCall *n = makeNode(FuncCall);
5069                                         n->funcname = SystemFuncName("like_escape");
5070                                         n->args = makeList2($3, $5);
5071                                         n->agg_star = FALSE;
5072                                         n->agg_distinct = FALSE;
5073                                         $$ = (Node *) makeSimpleA_Expr(OP, "~~", $1, (Node *) n);
5074                                 }
5075                 | a_expr NOT LIKE a_expr
5076                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "!~~", $1, $4); }
5077                 | a_expr NOT LIKE a_expr ESCAPE a_expr
5078                                 {
5079                                         FuncCall *n = makeNode(FuncCall);
5080                                         n->funcname = SystemFuncName("like_escape");
5081                                         n->args = makeList2($4, $6);
5082                                         n->agg_star = FALSE;
5083                                         n->agg_distinct = FALSE;
5084                                         $$ = (Node *) makeSimpleA_Expr(OP, "!~~", $1, (Node *) n);
5085                                 }
5086                 | a_expr ILIKE a_expr
5087                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "~~*", $1, $3); }
5088                 | a_expr ILIKE a_expr ESCAPE a_expr
5089                                 {
5090                                         FuncCall *n = makeNode(FuncCall);
5091                                         n->funcname = SystemFuncName("like_escape");
5092                                         n->args = makeList2($3, $5);
5093                                         n->agg_star = FALSE;
5094                                         n->agg_distinct = FALSE;
5095                                         $$ = (Node *) makeSimpleA_Expr(OP, "~~*", $1, (Node *) n);
5096                                 }
5097                 | a_expr NOT ILIKE a_expr
5098                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "!~~*", $1, $4); }
5099                 | a_expr NOT ILIKE a_expr ESCAPE a_expr
5100                                 {
5101                                         FuncCall *n = makeNode(FuncCall);
5102                                         n->funcname = SystemFuncName("like_escape");
5103                                         n->args = makeList2($4, $6);
5104                                         n->agg_star = FALSE;
5105                                         n->agg_distinct = FALSE;
5106                                         $$ = (Node *) makeSimpleA_Expr(OP, "!~~*", $1, (Node *) n);
5107                                 }
5108
5109                 | a_expr SIMILAR TO a_expr                              %prec SIMILAR
5110                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "~", $1, $4); }
5111                 | a_expr SIMILAR TO a_expr ESCAPE a_expr
5112                                 {
5113                                         FuncCall *n = makeNode(FuncCall);
5114                                         n->funcname = SystemFuncName("like_escape");
5115                                         n->args = makeList2($4, $6);
5116                                         n->agg_star = FALSE;
5117                                         n->agg_distinct = FALSE;
5118                                         $$ = (Node *) makeSimpleA_Expr(OP, "~", $1, (Node *) n);
5119                                 }
5120                 | a_expr NOT SIMILAR TO a_expr                  %prec SIMILAR
5121                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "!~", $1, $5); }
5122                 | a_expr NOT SIMILAR TO a_expr ESCAPE a_expr
5123                                 {
5124                                         FuncCall *n = makeNode(FuncCall);
5125                                         n->funcname = SystemFuncName("like_escape");
5126                                         n->args = makeList2($5, $7);
5127                                         n->agg_star = FALSE;
5128                                         n->agg_distinct = FALSE;
5129                                         $$ = (Node *) makeSimpleA_Expr(OP, "!~", $1, (Node *) n);
5130                                 }
5131
5132                 /* NullTest clause
5133                  * Define SQL92-style Null test clause.
5134                  * Allow two forms described in the standard:
5135                  *  a IS NULL
5136                  *  a IS NOT NULL
5137                  * Allow two SQL extensions
5138                  *  a ISNULL
5139                  *  a NOTNULL
5140                  * NOTE: this is not yet fully SQL-compatible, since SQL92
5141                  * allows a row constructor as argument, not just a scalar.
5142                  */
5143                 | a_expr ISNULL
5144                                 {
5145                                         NullTest *n = makeNode(NullTest);
5146                                         n->arg = $1;
5147                                         n->nulltesttype = IS_NULL;
5148                                         $$ = (Node *)n;
5149                                 }
5150                 | a_expr IS NULL_P
5151                                 {
5152                                         NullTest *n = makeNode(NullTest);
5153                                         n->arg = $1;
5154                                         n->nulltesttype = IS_NULL;
5155                                         $$ = (Node *)n;
5156                                 }
5157                 | a_expr NOTNULL
5158                                 {
5159                                         NullTest *n = makeNode(NullTest);
5160                                         n->arg = $1;
5161                                         n->nulltesttype = IS_NOT_NULL;
5162                                         $$ = (Node *)n;
5163                                 }
5164                 | a_expr IS NOT NULL_P
5165                                 {
5166                                         NullTest *n = makeNode(NullTest);
5167                                         n->arg = $1;
5168                                         n->nulltesttype = IS_NOT_NULL;
5169                                         $$ = (Node *)n;
5170                                 }
5171                 /* IS TRUE, IS FALSE, etc used to be function calls
5172                  *  but let's make them expressions to allow the optimizer
5173                  *  a chance to eliminate them if a_expr is a constant string.
5174                  * - thomas 1997-12-22
5175                  *
5176                  *  Created BooleanTest Node type, and changed handling
5177                  *  for NULL inputs
5178                  * - jec 2001-06-18
5179                  */
5180                 | a_expr IS TRUE_P
5181                                 {
5182                                         BooleanTest *b = makeNode(BooleanTest);
5183                                         b->arg = $1;
5184                                         b->booltesttype = IS_TRUE;
5185                                         $$ = (Node *)b;
5186                                 }
5187                 | a_expr IS NOT TRUE_P
5188                                 {
5189                                         BooleanTest *b = makeNode(BooleanTest);
5190                                         b->arg = $1;
5191                                         b->booltesttype = IS_NOT_TRUE;
5192                                         $$ = (Node *)b;
5193                                 }
5194                 | a_expr IS FALSE_P
5195                                 {
5196                                         BooleanTest *b = makeNode(BooleanTest);
5197                                         b->arg = $1;
5198                                         b->booltesttype = IS_FALSE;
5199                                         $$ = (Node *)b;
5200                                 }
5201                 | a_expr IS NOT FALSE_P
5202                                 {
5203                                         BooleanTest *b = makeNode(BooleanTest);
5204                                         b->arg = $1;
5205                                         b->booltesttype = IS_NOT_FALSE;
5206                                         $$ = (Node *)b;
5207                                 }
5208                 | a_expr IS UNKNOWN
5209                                 {
5210                                         BooleanTest *b = makeNode(BooleanTest);
5211                                         b->arg = $1;
5212                                         b->booltesttype = IS_UNKNOWN;
5213                                         $$ = (Node *)b;
5214                                 }
5215                 | a_expr IS NOT UNKNOWN
5216                                 {
5217                                         BooleanTest *b = makeNode(BooleanTest);
5218                                         b->arg = $1;
5219                                         b->booltesttype = IS_NOT_UNKNOWN;
5220                                         $$ = (Node *)b;
5221                                 }
5222                 | a_expr BETWEEN b_expr AND b_expr                      %prec BETWEEN
5223                                 {
5224                                         $$ = (Node *) makeA_Expr(AND, NIL,
5225                                                 (Node *) makeSimpleA_Expr(OP, ">=", $1, $3),
5226                                                 (Node *) makeSimpleA_Expr(OP, "<=", $1, $5));
5227                                 }
5228                 | a_expr NOT BETWEEN b_expr AND b_expr          %prec BETWEEN
5229                                 {
5230                                         $$ = (Node *) makeA_Expr(OR, NIL,
5231                                                 (Node *) makeSimpleA_Expr(OP, "<", $1, $4),
5232                                                 (Node *) makeSimpleA_Expr(OP, ">", $1, $6));
5233                                 }
5234                 | a_expr IN_P in_expr
5235                                 {
5236                                         /* in_expr returns a SubLink or a list of a_exprs */
5237                                         if (IsA($3, SubLink))
5238                                         {
5239                                                         SubLink *n = (SubLink *)$3;
5240                                                         n->lefthand = makeList1($1);
5241                                                         n->oper = (List *) makeSimpleA_Expr(OP, "=",
5242                                                                                                                                 NULL, NULL);
5243                                                         n->useor = FALSE;
5244                                                         n->subLinkType = ANY_SUBLINK;
5245                                                         $$ = (Node *)n;
5246                                         }
5247                                         else
5248                                         {
5249                                                 Node *n = NULL;
5250                                                 List *l;
5251                                                 foreach(l, (List *) $3)
5252                                                 {
5253                                                         Node *cmp;
5254                                                         cmp = (Node *) makeSimpleA_Expr(OP, "=",
5255                                                                                                                         $1, lfirst(l));
5256                                                         if (n == NULL)
5257                                                                 n = cmp;
5258                                                         else
5259                                                                 n = (Node *) makeA_Expr(OR, NIL, n, cmp);
5260                                                 }
5261                                                 $$ = n;
5262                                         }
5263                                 }
5264                 | a_expr NOT IN_P in_expr
5265                                 {
5266                                         /* in_expr returns a SubLink or a list of a_exprs */
5267                                         if (IsA($4, SubLink))
5268                                         {
5269                                                 SubLink *n = (SubLink *)$4;
5270                                                 n->lefthand = makeList1($1);
5271                                                 n->oper = (List *) makeSimpleA_Expr(OP, "<>",
5272                                                                                                                         NULL, NULL);
5273                                                 n->useor = FALSE;
5274                                                 n->subLinkType = ALL_SUBLINK;
5275                                                 $$ = (Node *)n;
5276                                         }
5277                                         else
5278                                         {
5279                                                 Node *n = NULL;
5280                                                 List *l;
5281                                                 foreach(l, (List *) $4)
5282                                                 {
5283                                                         Node *cmp;
5284                                                         cmp = (Node *) makeSimpleA_Expr(OP, "<>",
5285                                                                                                                         $1, lfirst(l));
5286                                                         if (n == NULL)
5287                                                                 n = cmp;
5288                                                         else
5289                                                                 n = (Node *) makeA_Expr(AND, NIL, n, cmp);
5290                                                 }
5291                                                 $$ = n;
5292                                         }
5293                                 }
5294                 | a_expr qual_all_Op sub_type select_with_parens                %prec Op
5295                                 {
5296                                         SubLink *n = makeNode(SubLink);
5297                                         n->lefthand = makeList1($1);
5298                                         n->oper = (List *) makeA_Expr(OP, $2, NULL, NULL);
5299                                         n->useor = FALSE; /* doesn't matter since only one col */
5300                                         n->subLinkType = $3;
5301                                         n->subselect = $4;
5302                                         $$ = (Node *)n;
5303                                 }
5304                 | row_expr
5305                                 {       $$ = $1;  }
5306                 ;
5307
5308 /*
5309  * Restricted expressions
5310  *
5311  * b_expr is a subset of the complete expression syntax defined by a_expr.
5312  *
5313  * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
5314  * cause trouble in the places where b_expr is used.  For simplicity, we
5315  * just eliminate all the boolean-keyword-operator productions from b_expr.
5316  */
5317 b_expr:  c_expr
5318                                 {       $$ = $1;  }
5319                 | b_expr TYPECAST Typename
5320                                 {       $$ = makeTypeCast($1, $3); }
5321                 | '+' b_expr                                    %prec UMINUS
5322                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "+", NULL, $2); }
5323                 | '-' b_expr                                    %prec UMINUS
5324                                 {       $$ = doNegate($2); }
5325                 | '%' b_expr
5326                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "%", NULL, $2); }
5327                 | '^' b_expr
5328                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "^", NULL, $2); }
5329                 | b_expr '%'
5330                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, NULL); }
5331                 | b_expr '^'
5332                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, NULL); }
5333                 | b_expr '+' b_expr
5334                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "+", $1, $3); }
5335                 | b_expr '-' b_expr
5336                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "-", $1, $3); }
5337                 | b_expr '*' b_expr
5338                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "*", $1, $3); }
5339                 | b_expr '/' b_expr
5340                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "/", $1, $3); }
5341                 | b_expr '%' b_expr
5342                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "%", $1, $3); }
5343                 | b_expr '^' b_expr
5344                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "^", $1, $3); }
5345                 | b_expr '<' b_expr
5346                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "<", $1, $3); }
5347                 | b_expr '>' b_expr
5348                                 {       $$ = (Node *) makeSimpleA_Expr(OP, ">", $1, $3); }
5349                 | b_expr '=' b_expr
5350                                 {       $$ = (Node *) makeSimpleA_Expr(OP, "=", $1, $3); }
5351
5352                 | b_expr qual_Op b_expr                         %prec Op
5353                                 {       $$ = (Node *) makeA_Expr(OP, $2, $1, $3); }
5354                 | qual_Op b_expr                                        %prec Op
5355                                 {       $$ = (Node *) makeA_Expr(OP, $1, NULL, $2); }
5356                 | b_expr qual_Op                                        %prec POSTFIXOP
5357                                 {       $$ = (Node *) makeA_Expr(OP, $2, $1, NULL); }
5358                 ;
5359
5360 /*
5361  * Productions that can be used in both a_expr and b_expr.
5362  *
5363  * Note: productions that refer recursively to a_expr or b_expr mostly
5364  * cannot appear here.  However, it's OK to refer to a_exprs that occur
5365  * inside parentheses, such as function arguments; that cannot introduce
5366  * ambiguity to the b_expr syntax.
5367  */
5368 c_expr:  columnref
5369                                 {       $$ = (Node *) $1;  }
5370                 | AexprConst
5371                                 {       $$ = $1;  }
5372                 | PARAM attrs opt_indirection
5373                                 {
5374                                         /*
5375                                          * PARAM without field names is considered a constant,
5376                                          * but with 'em, it is not.  Not very consistent ...
5377                                          */
5378                                         ParamRef *n = makeNode(ParamRef);
5379                                         n->number = $1;
5380                                         n->fields = $2;
5381                                         n->indirection = $3;
5382                                         $$ = (Node *)n;
5383                                 }
5384                 | '(' a_expr ')'
5385                                 {       $$ = $2; }
5386                 | '(' a_expr ')' attrs opt_indirection
5387                                 {
5388                                         ExprFieldSelect *n = makeNode(ExprFieldSelect);
5389                                         n->arg = $2;
5390                                         n->fields = $4;
5391                                         n->indirection = $5;
5392                                         $$ = (Node *)n;
5393                                 }
5394                 | CAST '(' a_expr AS Typename ')'
5395                                 {       $$ = makeTypeCast($3, $5); }
5396                 | case_expr
5397                                 {       $$ = $1; }
5398                 | func_name '(' ')'
5399                                 {
5400                                         FuncCall *n = makeNode(FuncCall);
5401                                         n->funcname = $1;
5402                                         n->args = NIL;
5403                                         n->agg_star = FALSE;
5404                                         n->agg_distinct = FALSE;
5405                                         $$ = (Node *)n;
5406                                 }
5407                 | func_name '(' expr_list ')'
5408                                 {
5409                                         FuncCall *n = makeNode(FuncCall);
5410                                         n->funcname = $1;
5411                                         n->args = $3;
5412                                         n->agg_star = FALSE;
5413                                         n->agg_distinct = FALSE;
5414                                         $$ = (Node *)n;
5415                                 }
5416                 | func_name '(' ALL expr_list ')'
5417                                 {
5418                                         FuncCall *n = makeNode(FuncCall);
5419                                         n->funcname = $1;
5420                                         n->args = $4;
5421                                         n->agg_star = FALSE;
5422                                         n->agg_distinct = FALSE;
5423                                         /* Ideally we'd mark the FuncCall node to indicate
5424                                          * "must be an aggregate", but there's no provision
5425                                          * for that in FuncCall at the moment.
5426                                          */
5427                                         $$ = (Node *)n;
5428                                 }
5429                 | func_name '(' DISTINCT expr_list ')'
5430                                 {
5431                                         FuncCall *n = makeNode(FuncCall);
5432                                         n->funcname = $1;
5433                                         n->args = $4;
5434                                         n->agg_star = FALSE;
5435                                         n->agg_distinct = TRUE;
5436                                         $$ = (Node *)n;
5437                                 }
5438                 | func_name '(' '*' ')'
5439                                 {
5440                                         /*
5441                                          * For now, we transform AGGREGATE(*) into AGGREGATE(1).
5442                                          *
5443                                          * This does the right thing for COUNT(*) (in fact,
5444                                          * any certainly-non-null expression would do for COUNT),
5445                                          * and there are no other aggregates in SQL92 that accept
5446                                          * '*' as parameter.
5447                                          *
5448                                          * The FuncCall node is also marked agg_star = true,
5449                                          * so that later processing can detect what the argument
5450                                          * really was.
5451                                          */
5452                                         FuncCall *n = makeNode(FuncCall);
5453                                         A_Const *star = makeNode(A_Const);
5454
5455                                         star->val.type = T_Integer;
5456                                         star->val.val.ival = 1;
5457                                         n->funcname = $1;
5458                                         n->args = makeList1(star);
5459                                         n->agg_star = TRUE;
5460                                         n->agg_distinct = FALSE;
5461                                         $$ = (Node *)n;
5462                                 }
5463                 | CURRENT_DATE
5464                                 {
5465                                         /*
5466                                          * Translate as "'now'::text::date".
5467                                          *
5468                                          * We cannot use "'now'::date" because coerce_type() will
5469                                          * immediately reduce that to a constant representing
5470                                          * today's date.  We need to delay the conversion until
5471                                          * runtime, else the wrong things will happen when
5472                                          * CURRENT_DATE is used in a column default value or rule.
5473                                          *
5474                                          * This could be simplified if we had a way to generate
5475                                          * an expression tree representing runtime application
5476                                          * of type-input conversion functions...
5477                                          */
5478                                         A_Const *s = makeNode(A_Const);
5479                                         TypeName *d;
5480
5481                                         s->val.type = T_String;
5482                                         s->val.val.str = "now";
5483                                         s->typename = SystemTypeName("text");
5484
5485                                         d = SystemTypeName("date");
5486
5487                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5488                                 }
5489                 | CURRENT_TIME
5490                                 {
5491                                         /*
5492                                          * Translate as "'now'::text::timetz".
5493                                          * See comments for CURRENT_DATE.
5494                                          */
5495                                         A_Const *s = makeNode(A_Const);
5496                                         TypeName *d;
5497
5498                                         s->val.type = T_String;
5499                                         s->val.val.str = "now";
5500                                         s->typename = SystemTypeName("text");
5501
5502                                         d = SystemTypeName("timetz");
5503                                         /* SQL99 mandates a default precision of zero for TIME
5504                                          * fields in schemas. However, for CURRENT_TIME
5505                                          * let's preserve the microsecond precision we
5506                                          * might see from the system clock. - thomas 2001-12-07
5507                                          */
5508                                         d->typmod = 6;
5509
5510                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5511                                 }
5512                 | CURRENT_TIME '(' Iconst ')'
5513                                 {
5514                                         /*
5515                                          * Translate as "'now'::text::timetz(n)".
5516                                          * See comments for CURRENT_DATE.
5517                                          */
5518                                         A_Const *s = makeNode(A_Const);
5519                                         TypeName *d;
5520
5521                                         s->val.type = T_String;
5522                                         s->val.val.str = "now";
5523                                         s->typename = SystemTypeName("text");
5524                                         d = SystemTypeName("timetz");
5525                                         if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
5526                                                 elog(ERROR, "CURRENT_TIME(%d) precision must be between %d and %d",
5527                                                          $3, 0, MAX_TIME_PRECISION);
5528                                         d->typmod = $3;
5529
5530                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5531                                 }
5532                 | CURRENT_TIMESTAMP
5533                                 {
5534                                         /*
5535                                          * Translate as "'now'::text::timestamptz".
5536                                          * See comments for CURRENT_DATE.
5537                                          */
5538                                         A_Const *s = makeNode(A_Const);
5539                                         TypeName *d;
5540
5541                                         s->val.type = T_String;
5542                                         s->val.val.str = "now";
5543                                         s->typename = SystemTypeName("text");
5544
5545                                         d = SystemTypeName("timestamptz");
5546                                         /* SQL99 mandates a default precision of 6 for timestamp.
5547                                          * Also, that is about as precise as we will get since
5548                                          * we are using a microsecond time interface.
5549                                          * - thomas 2001-12-07
5550                                          */
5551                                         d->typmod = 6;
5552
5553                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5554                                 }
5555                 | CURRENT_TIMESTAMP '(' Iconst ')'
5556                                 {
5557                                         /*
5558                                          * Translate as "'now'::text::timestamptz(n)".
5559                                          * See comments for CURRENT_DATE.
5560                                          */
5561                                         A_Const *s = makeNode(A_Const);
5562                                         TypeName *d;
5563
5564                                         s->val.type = T_String;
5565                                         s->val.val.str = "now";
5566                                         s->typename = SystemTypeName("text");
5567
5568                                         d = SystemTypeName("timestamptz");
5569                                         if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
5570                                                 elog(ERROR, "CURRENT_TIMESTAMP(%d) precision must be between %d and %d",
5571                                                          $3, 0, MAX_TIMESTAMP_PRECISION);
5572                                         d->typmod = $3;
5573
5574                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5575                                 }
5576                 | LOCALTIME
5577                                 {
5578                                         /*
5579                                          * Translate as "'now'::text::time".
5580                                          * See comments for CURRENT_DATE.
5581                                          */
5582                                         A_Const *s = makeNode(A_Const);
5583                                         TypeName *d;
5584
5585                                         s->val.type = T_String;
5586                                         s->val.val.str = "now";
5587                                         s->typename = SystemTypeName("text");
5588
5589                                         d = SystemTypeName("time");
5590                                         /* SQL99 mandates a default precision of zero for TIME
5591                                          * fields in schemas. However, for LOCALTIME
5592                                          * let's preserve the microsecond precision we
5593                                          * might see from the system clock. - thomas 2001-12-07
5594                                          */
5595                                         d->typmod = 6;
5596
5597                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5598                                 }
5599                 | LOCALTIME '(' Iconst ')'
5600                                 {
5601                                         /*
5602                                          * Translate as "'now'::text::time(n)".
5603                                          * See comments for CURRENT_DATE.
5604                                          */
5605                                         A_Const *s = makeNode(A_Const);
5606                                         TypeName *d;
5607
5608                                         s->val.type = T_String;
5609                                         s->val.val.str = "now";
5610                                         s->typename = SystemTypeName("text");
5611                                         d = SystemTypeName("time");
5612                                         if (($3 < 0) || ($3 > MAX_TIME_PRECISION))
5613                                                 elog(ERROR, "LOCALTIME(%d) precision must be between %d and %d",
5614                                                          $3, 0, MAX_TIME_PRECISION);
5615                                         d->typmod = $3;
5616
5617                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5618                                 }
5619                 | LOCALTIMESTAMP
5620                                 {
5621                                         /*
5622                                          * Translate as "'now'::text::timestamp".
5623                                          * See comments for CURRENT_DATE.
5624                                          */
5625                                         A_Const *s = makeNode(A_Const);
5626                                         TypeName *d;
5627
5628                                         s->val.type = T_String;
5629                                         s->val.val.str = "now";
5630                                         s->typename = SystemTypeName("text");
5631
5632                                         d = SystemTypeName("timestamp");
5633                                         /* SQL99 mandates a default precision of 6 for timestamp.
5634                                          * Also, that is about as precise as we will get since
5635                                          * we are using a microsecond time interface.
5636                                          * - thomas 2001-12-07
5637                                          */
5638                                         d->typmod = 6;
5639
5640                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5641                                 }
5642                 | LOCALTIMESTAMP '(' Iconst ')'
5643                                 {
5644                                         /*
5645                                          * Translate as "'now'::text::timestamp(n)".
5646                                          * See comments for CURRENT_DATE.
5647                                          */
5648                                         A_Const *s = makeNode(A_Const);
5649                                         TypeName *d;
5650
5651                                         s->val.type = T_String;
5652                                         s->val.val.str = "now";
5653                                         s->typename = SystemTypeName("text");
5654
5655                                         d = SystemTypeName("timestamp");
5656                                         if (($3 < 0) || ($3 > MAX_TIMESTAMP_PRECISION))
5657                                                 elog(ERROR, "LOCALTIMESTAMP(%d) precision must be between %d and %d",
5658                                                          $3, 0, MAX_TIMESTAMP_PRECISION);
5659                                         d->typmod = $3;
5660
5661                                         $$ = (Node *)makeTypeCast((Node *)s, d);
5662                                 }
5663                 | CURRENT_USER
5664                                 {
5665                                         FuncCall *n = makeNode(FuncCall);
5666                                         n->funcname = SystemFuncName("current_user");
5667                                         n->args = NIL;
5668                                         n->agg_star = FALSE;
5669                                         n->agg_distinct = FALSE;
5670                                         $$ = (Node *)n;
5671                                 }
5672                 | SESSION_USER
5673                                 {
5674                                         FuncCall *n = makeNode(FuncCall);
5675                                         n->funcname = SystemFuncName("session_user");
5676                                         n->args = NIL;
5677                                         n->agg_star = FALSE;
5678                                         n->agg_distinct = FALSE;
5679                                         $$ = (Node *)n;
5680                                 }
5681                 | USER
5682                                 {
5683                                         FuncCall *n = makeNode(FuncCall);
5684                                         n->funcname = SystemFuncName("current_user");
5685                                         n->args = NIL;
5686                                         n->agg_star = FALSE;
5687                                         n->agg_distinct = FALSE;
5688                                         $$ = (Node *)n;
5689                                 }
5690                 | EXTRACT '(' extract_list ')'
5691                                 {
5692                                         FuncCall *n = makeNode(FuncCall);
5693                                         n->funcname = SystemFuncName("date_part");
5694                                         n->args = $3;
5695                                         n->agg_star = FALSE;
5696                                         n->agg_distinct = FALSE;
5697                                         $$ = (Node *)n;
5698                                 }
5699                 | OVERLAY '(' overlay_list ')'
5700                                 {
5701                                         /* overlay(A PLACING B FROM C FOR D) is converted to
5702                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+D)
5703                                          * overlay(A PLACING B FROM C) is converted to
5704                                          * substring(A, 1, C-1) || B || substring(A, C+1, C+char_length(B))
5705                                          */
5706                                         FuncCall *n = makeNode(FuncCall);
5707                                         n->funcname = SystemFuncName("overlay");
5708                                         n->args = $3;
5709                                         n->agg_star = FALSE;
5710                                         n->agg_distinct = FALSE;
5711                                         $$ = (Node *)n;
5712                                 }
5713                 | POSITION '(' position_list ')'
5714                                 {
5715                                         /* position(A in B) is converted to position(B, A) */
5716                                         FuncCall *n = makeNode(FuncCall);
5717                                         n->funcname = SystemFuncName("position");
5718                                         n->args = $3;
5719                                         n->agg_star = FALSE;
5720                                         n->agg_distinct = FALSE;
5721                                         $$ = (Node *)n;
5722                                 }
5723                 | SUBSTRING '(' substr_list ')'
5724                                 {
5725                                         /* substring(A from B for C) is converted to
5726                                          * substring(A, B, C) - thomas 2000-11-28
5727                                          */
5728                                         FuncCall *n = makeNode(FuncCall);
5729                                         n->funcname = SystemFuncName("substring");
5730                                         n->args = $3;
5731                                         n->agg_star = FALSE;
5732                                         n->agg_distinct = FALSE;
5733                                         $$ = (Node *)n;
5734                                 }
5735                 | TRIM '(' BOTH trim_list ')'
5736                                 {
5737                                         /* various trim expressions are defined in SQL92
5738                                          * - thomas 1997-07-19
5739                                          */
5740                                         FuncCall *n = makeNode(FuncCall);
5741                                         n->funcname = SystemFuncName("btrim");
5742                                         n->args = $4;
5743                                         n->agg_star = FALSE;
5744                                         n->agg_distinct = FALSE;
5745                                         $$ = (Node *)n;
5746                                 }
5747                 | TRIM '(' LEADING trim_list ')'
5748                                 {
5749                                         FuncCall *n = makeNode(FuncCall);
5750                                         n->funcname = SystemFuncName("ltrim");
5751                                         n->args = $4;
5752                                         n->agg_star = FALSE;
5753                                         n->agg_distinct = FALSE;
5754                                         $$ = (Node *)n;
5755                                 }
5756                 | TRIM '(' TRAILING trim_list ')'
5757                                 {
5758                                         FuncCall *n = makeNode(FuncCall);
5759                                         n->funcname = SystemFuncName("rtrim");
5760                                         n->args = $4;
5761                                         n->agg_star = FALSE;
5762                                         n->agg_distinct = FALSE;
5763                                         $$ = (Node *)n;
5764                                 }
5765                 | TRIM '(' trim_list ')'
5766                                 {
5767                                         FuncCall *n = makeNode(FuncCall);
5768                                         n->funcname = SystemFuncName("btrim");
5769                                         n->args = $3;
5770                                         n->agg_star = FALSE;
5771                                         n->agg_distinct = FALSE;
5772                                         $$ = (Node *)n;
5773                                 }
5774                 | select_with_parens                    %prec UMINUS
5775                                 {
5776                                         SubLink *n = makeNode(SubLink);
5777                                         n->lefthand = NIL;
5778                                         n->oper = NIL;
5779                                         n->useor = FALSE;
5780                                         n->subLinkType = EXPR_SUBLINK;
5781                                         n->subselect = $1;
5782                                         $$ = (Node *)n;
5783                                 }
5784                 | EXISTS select_with_parens
5785                                 {
5786                                         SubLink *n = makeNode(SubLink);
5787                                         n->lefthand = NIL;
5788                                         n->oper = NIL;
5789                                         n->useor = FALSE;
5790                                         n->subLinkType = EXISTS_SUBLINK;
5791                                         n->subselect = $2;
5792                                         $$ = (Node *)n;
5793                                 }
5794                 ;
5795
5796 /*
5797  * Supporting nonterminals for expressions.
5798  */
5799
5800 opt_indirection:        opt_indirection '[' a_expr ']'
5801                                 {
5802                                         A_Indices *ai = makeNode(A_Indices);
5803                                         ai->lidx = NULL;
5804                                         ai->uidx = $3;
5805                                         $$ = lappend($1, ai);
5806                                 }
5807                 | opt_indirection '[' a_expr ':' a_expr ']'
5808                                 {
5809                                         A_Indices *ai = makeNode(A_Indices);
5810                                         ai->lidx = $3;
5811                                         ai->uidx = $5;
5812                                         $$ = lappend($1, ai);
5813                                 }
5814                 | /*EMPTY*/
5815                                 {       $$ = NIL; }
5816                 ;
5817
5818 expr_list:  a_expr
5819                                 { $$ = makeList1($1); }
5820                 | expr_list ',' a_expr
5821                                 { $$ = lappend($1, $3); }
5822                 | expr_list USING a_expr
5823                                 { $$ = lappend($1, $3); }
5824                 ;
5825
5826 extract_list:  extract_arg FROM a_expr
5827                                 {
5828                                         A_Const *n = makeNode(A_Const);
5829                                         n->val.type = T_String;
5830                                         n->val.val.str = $1;
5831                                         $$ = makeList2((Node *) n, $3);
5832                                 }
5833                 | /*EMPTY*/
5834                                 {       $$ = NIL; }
5835                 ;
5836
5837 /* Allow delimited string SCONST in extract_arg as an SQL extension.
5838  * - thomas 2001-04-12
5839  */
5840
5841 extract_arg:  IDENT                                             { $$ = $1; }
5842                 | YEAR_P                                                { $$ = "year"; }
5843                 | MONTH_P                                               { $$ = "month"; }
5844                 | DAY_P                                                 { $$ = "day"; }
5845                 | HOUR_P                                                { $$ = "hour"; }
5846                 | MINUTE_P                                              { $$ = "minute"; }
5847                 | SECOND_P                                              { $$ = "second"; }
5848                 | SCONST                                                { $$ = $1; }
5849                 ;
5850
5851 /* OVERLAY() arguments
5852  * SQL99 defines the OVERLAY() function:
5853  * o overlay(text placing text from int for int)
5854  * o overlay(text placing text from int)
5855  */
5856 overlay_list:  a_expr overlay_placing substr_from substr_for
5857                                 {
5858                                         $$ = makeList4($1, $2, $3, $4);
5859                                 }
5860                 | a_expr overlay_placing substr_from
5861                                 {
5862                                         $$ = makeList3($1, $2, $3);
5863                                 }
5864                 ;
5865
5866 overlay_placing:  PLACING a_expr
5867                                 {       $$ = $2; }
5868                 ;
5869
5870 /* position_list uses b_expr not a_expr to avoid conflict with general IN */
5871
5872 position_list:  b_expr IN_P b_expr
5873                                 {       $$ = makeList2($3, $1); }
5874                 | /*EMPTY*/
5875                                 {       $$ = NIL; }
5876                 ;
5877
5878 /* SUBSTRING() arguments
5879  * SQL9x defines a specific syntax for arguments to SUBSTRING():
5880  * o substring(text from int for int)
5881  * o substring(text from int) get entire string from starting point "int"
5882  * o substring(text for int) get first "int" characters of string
5883  * We also want to implement generic substring functions which accept
5884  * the usual generic list of arguments. So we will accept both styles
5885  * here, and convert the SQL9x style to the generic list for further
5886  * processing. - thomas 2000-11-28
5887  */
5888 substr_list:  a_expr substr_from substr_for
5889                                 {
5890                                         $$ = makeList3($1, $2, $3);
5891                                 }
5892                 | a_expr substr_for substr_from
5893                                 {
5894                                         $$ = makeList3($1, $3, $2);
5895                                 }
5896                 | a_expr substr_from
5897                                 {
5898                                         $$ = makeList2($1, $2);
5899                                 }
5900                 | a_expr substr_for
5901                                 {
5902                                         A_Const *n = makeNode(A_Const);
5903                                         n->val.type = T_Integer;
5904                                         n->val.val.ival = 1;
5905                                         $$ = makeList3($1, (Node *)n, $2);
5906                                 }
5907                 | expr_list
5908                                 {
5909                                         $$ = $1;
5910                                 }
5911                 | /*EMPTY*/
5912                                 {       $$ = NIL; }
5913                 ;
5914
5915 substr_from:  FROM a_expr
5916                                 {       $$ = $2; }
5917                 ;
5918
5919 substr_for:  FOR a_expr
5920                                 {       $$ = $2; }
5921                 ;
5922
5923 trim_list:  a_expr FROM expr_list
5924                                 { $$ = lappend($3, $1); }
5925                 | FROM expr_list
5926                                 { $$ = $2; }
5927                 | expr_list
5928                                 { $$ = $1; }
5929                 ;
5930
5931 in_expr:  select_with_parens
5932                                 {
5933                                         SubLink *n = makeNode(SubLink);
5934                                         n->subselect = $1;
5935                                         $$ = (Node *)n;
5936                                 }
5937                 | '(' in_expr_nodes ')'
5938                                 {       $$ = (Node *)$2; }
5939                 ;
5940
5941 in_expr_nodes:  a_expr
5942                                 {       $$ = makeList1($1); }
5943                 | in_expr_nodes ',' a_expr
5944                                 {       $$ = lappend($1, $3); }
5945                 ;
5946
5947 /* Case clause
5948  * Define SQL92-style case clause.
5949  * Allow all four forms described in the standard:
5950  * - Full specification
5951  *  CASE WHEN a = b THEN c ... ELSE d END
5952  * - Implicit argument
5953  *  CASE a WHEN b THEN c ... ELSE d END
5954  * - Conditional NULL
5955  *  NULLIF(x,y)
5956  *  same as CASE WHEN x = y THEN NULL ELSE x END
5957  * - Conditional substitution from list, use first non-null argument
5958  *  COALESCE(a,b,...)
5959  * same as CASE WHEN a IS NOT NULL THEN a WHEN b IS NOT NULL THEN b ... END
5960  * - thomas 1998-11-09
5961  */
5962 case_expr:  CASE case_arg when_clause_list case_default END_TRANS
5963                                 {
5964                                         CaseExpr *c = makeNode(CaseExpr);
5965                                         c->arg = $2;
5966                                         c->args = $3;
5967                                         c->defresult = $4;
5968                                         $$ = (Node *)c;
5969                                 }
5970                 | NULLIF '(' a_expr ',' a_expr ')'
5971                                 {
5972                                         CaseExpr *c = makeNode(CaseExpr);
5973                                         CaseWhen *w = makeNode(CaseWhen);
5974
5975                                         w->expr = (Node *) makeSimpleA_Expr(OP, "=", $3, $5);
5976                                         /* w->result is left NULL */
5977                                         c->args = makeList1(w);
5978                                         c->defresult = $3;
5979                                         $$ = (Node *)c;
5980                                 }
5981                 | COALESCE '(' expr_list ')'
5982                                 {
5983                                         CaseExpr *c = makeNode(CaseExpr);
5984                                         List *l;
5985                                         foreach (l,$3)
5986                                         {
5987                                                 CaseWhen *w = makeNode(CaseWhen);
5988                                                 NullTest *n = makeNode(NullTest);
5989                                                 n->arg = lfirst(l);
5990                                                 n->nulltesttype = IS_NOT_NULL;
5991                                                 w->expr = (Node *) n;
5992                                                 w->result = lfirst(l);
5993                                                 c->args = lappend(c->args, w);
5994                                         }
5995                                         $$ = (Node *)c;
5996                                 }
5997                 ;
5998
5999 when_clause_list:  when_clause_list when_clause
6000                                 { $$ = lappend($1, $2); }
6001                 | when_clause
6002                                 { $$ = makeList1($1); }
6003                 ;
6004
6005 when_clause:  WHEN a_expr THEN a_expr
6006                                 {
6007                                         CaseWhen *w = makeNode(CaseWhen);
6008                                         w->expr = $2;
6009                                         w->result = $4;
6010                                         $$ = (Node *)w;
6011                                 }
6012                 ;
6013
6014 case_default:  ELSE a_expr                                              { $$ = $2; }
6015                 | /*EMPTY*/                                                             { $$ = NULL; }
6016                 ;
6017
6018 case_arg:  a_expr
6019                                 {       $$ = $1; }
6020                 | /*EMPTY*/
6021                                 {       $$ = NULL; }
6022                 ;
6023
6024 /*
6025  * columnref starts with relation_name not ColId, so that OLD and NEW
6026  * references can be accepted.  Note that when there are more than two
6027  * dotted names, the first name is not actually a relation name...
6028  */
6029 columnref: relation_name opt_indirection
6030                                 {
6031                                         $$ = makeNode(ColumnRef);
6032                                         $$->fields = makeList1(makeString($1));
6033                                         $$->indirection = $2;
6034                                 }
6035                 | dotted_name opt_indirection
6036                                 {
6037                                         $$ = makeNode(ColumnRef);
6038                                         $$->fields = $1;
6039                                         $$->indirection = $2;
6040                                 }
6041                 ;
6042
6043 dotted_name: relation_name attrs
6044                                 { $$ = lcons(makeString($1), $2); }
6045                 ;
6046
6047 attrs:  '.' attr_name
6048                                 { $$ = makeList1(makeString($2)); }
6049                 | '.' '*'
6050                                 { $$ = makeList1(makeString("*")); }
6051                 | '.' attr_name attrs
6052                                 { $$ = lcons(makeString($2), $3); }
6053                 ;
6054
6055
6056 /*****************************************************************************
6057  *
6058  *      target lists
6059  *
6060  *****************************************************************************/
6061
6062 /* Target lists as found in SELECT ... and INSERT VALUES ( ... ) */
6063
6064 target_list:  target_list ',' target_el
6065                                 {       $$ = lappend($1, $3);  }
6066                 | target_el
6067                                 {       $$ = makeList1($1);  }
6068                 ;
6069
6070 /* AS is not optional because shift/red conflict with unary ops */
6071 target_el:  a_expr AS ColLabel
6072                                 {
6073                                         $$ = makeNode(ResTarget);
6074                                         $$->name = $3;
6075                                         $$->indirection = NIL;
6076                                         $$->val = (Node *)$1;
6077                                 }
6078                 | a_expr
6079                                 {
6080                                         $$ = makeNode(ResTarget);
6081                                         $$->name = NULL;
6082                                         $$->indirection = NIL;
6083                                         $$->val = (Node *)$1;
6084                                 }
6085                 | '*'
6086                                 {
6087                                         ColumnRef *n = makeNode(ColumnRef);
6088                                         n->fields = makeList1(makeString("*"));
6089                                         n->indirection = NIL;
6090                                         $$ = makeNode(ResTarget);
6091                                         $$->name = NULL;
6092                                         $$->indirection = NIL;
6093                                         $$->val = (Node *)n;
6094                                 }
6095                 ;
6096
6097 /* Target list as found in UPDATE table SET ...
6098 | '(' row_ ')' = '(' row_ ')'
6099 {
6100         $$ = NULL;
6101 }
6102  */
6103 update_target_list:  update_target_list ',' update_target_el
6104                                 {       $$ = lappend($1,$3);  }
6105                 | update_target_el
6106                                 {       $$ = makeList1($1);  }
6107                 ;
6108
6109 update_target_el:  ColId opt_indirection '=' a_expr
6110                                 {
6111                                         $$ = makeNode(ResTarget);
6112                                         $$->name = $1;
6113                                         $$->indirection = $2;
6114                                         $$->val = (Node *)$4;
6115                                 }
6116                 ;
6117
6118 insert_target_list:  insert_target_list ',' insert_target_el
6119                                 {       $$ = lappend($1, $3);  }
6120                 | insert_target_el
6121                                 {       $$ = makeList1($1);  }
6122                 ;
6123
6124 insert_target_el:  target_el    {       $$ = $1;  }
6125                                 | DEFAULT               {       
6126                                                                         InsertDefault *def = makeNode(InsertDefault);
6127                                                                         $$ = makeNode(ResTarget);
6128                                                                         $$->name = NULL;
6129                                                                         $$->indirection = NULL;
6130                                                                         $$->val = (Node *)def;
6131                                                                 }
6132                                 ;
6133
6134
6135 /*****************************************************************************
6136  *
6137  *      Names and constants
6138  *
6139  *****************************************************************************/
6140
6141 relation_name:  SpecialRuleRelation
6142                                 {
6143                                         $$ = $1;
6144                                 }
6145                 | ColId
6146                                 {
6147                                         $$ = $1;
6148                                 }
6149                 ;
6150
6151 qualified_name_list:  qualified_name
6152                                 { $$ = makeList1($1); }
6153                 | qualified_name_list ',' qualified_name
6154                                 { $$ = lappend($1, $3); }
6155                 ;
6156
6157 qualified_name: relation_name
6158                                 {
6159                                         $$ = makeNode(RangeVar);
6160                                         $$->catalogname = NULL;
6161                                         $$->schemaname = NULL;
6162                                         $$->relname = $1;
6163                                 }
6164                 | dotted_name
6165                                 {
6166                                         $$ = makeNode(RangeVar);
6167                                         switch (length($1))
6168                                         {
6169                                                 case 2:
6170                                                         $$->catalogname = NULL;
6171                                                         $$->schemaname = strVal(lfirst($1));
6172                                                         $$->relname = strVal(lsecond($1));
6173                                                         break;
6174                                                 case 3:
6175                                                         $$->catalogname = strVal(lfirst($1));
6176                                                         $$->schemaname = strVal(lsecond($1));
6177                                                         $$->relname = strVal(lfirst(lnext(lnext($1))));
6178                                                         break;
6179                                                 default:
6180                                                         elog(ERROR, "Improper qualified name (too many dotted names): %s",
6181                                                                  NameListToString($1));
6182                                                         break;
6183                                         }
6184                                 }
6185                 ;
6186
6187 name_list:  name
6188                                 {       $$ = makeList1(makeString($1)); }
6189                 | name_list ',' name
6190                                 {       $$ = lappend($1, makeString($3)); }
6191                 ;
6192
6193
6194 name:                                   ColId                   { $$ = $1; };
6195 database_name:                  ColId                   { $$ = $1; };
6196 access_method:                  ColId                   { $$ = $1; };
6197 attr_name:                              ColId                   { $$ = $1; };
6198 index_name:                             ColId                   { $$ = $1; };
6199 file_name:                              Sconst                  { $$ = $1; };
6200
6201 func_name: function_name
6202                         { $$ = makeList1(makeString($1)); }
6203                 | dotted_name
6204                         { $$ = $1; }
6205                 ;
6206
6207
6208 /* Constants
6209  * Include TRUE/FALSE for SQL3 support. - thomas 1997-10-24
6210  */
6211 AexprConst:  Iconst
6212                                 {
6213                                         A_Const *n = makeNode(A_Const);
6214                                         n->val.type = T_Integer;
6215                                         n->val.val.ival = $1;
6216                                         $$ = (Node *)n;
6217                                 }
6218                 | FCONST
6219                                 {
6220                                         A_Const *n = makeNode(A_Const);
6221                                         n->val.type = T_Float;
6222                                         n->val.val.str = $1;
6223                                         $$ = (Node *)n;
6224                                 }
6225                 | Sconst
6226                                 {
6227                                         A_Const *n = makeNode(A_Const);
6228                                         n->val.type = T_String;
6229                                         n->val.val.str = $1;
6230                                         $$ = (Node *)n;
6231                                 }
6232                 | BITCONST
6233                                 {
6234                                         A_Const *n = makeNode(A_Const);
6235                                         n->val.type = T_BitString;
6236                                         n->val.val.str = $1;
6237                                         $$ = (Node *)n;
6238                                 }
6239                 /* This rule formerly used Typename,
6240                  * but that causes reduce conflicts with subscripted column names.
6241                  * Now, separate into ConstTypename and ConstInterval,
6242                  * to allow implementing the SQL92 syntax for INTERVAL literals.
6243                  * - thomas 2000-06-24
6244                  */
6245                 | ConstTypename Sconst
6246                                 {
6247                                         A_Const *n = makeNode(A_Const);
6248                                         n->typename = $1;
6249                                         n->val.type = T_String;
6250                                         n->val.val.str = $2;
6251                                         $$ = (Node *)n;
6252                                 }
6253                 | ConstInterval Sconst opt_interval
6254                                 {
6255                                         A_Const *n = makeNode(A_Const);
6256                                         n->typename = $1;
6257                                         n->val.type = T_String;
6258                                         n->val.val.str = $2;
6259                                         /* precision is not specified, but fields may be... */
6260                                         if ($3 != -1)
6261                                                 n->typename->typmod = ((($3 & 0x7FFF) << 16) | 0xFFFF);
6262                                         $$ = (Node *)n;
6263                                 }
6264                 | ConstInterval '(' Iconst ')' Sconst opt_interval
6265                                 {
6266                                         A_Const *n = makeNode(A_Const);
6267                                         n->typename = $1;
6268                                         n->val.type = T_String;
6269                                         n->val.val.str = $5;
6270                                         /* precision specified, and fields may be... */
6271                                         if (($3 < 0) || ($3 > MAX_INTERVAL_PRECISION))
6272                                                 elog(ERROR, "INTERVAL(%d) precision must be between %d and %d",
6273                                                          $3, 0, MAX_INTERVAL_PRECISION);
6274                                         n->typename->typmod = ((($6 & 0x7FFF) << 16) | $3);
6275                                         $$ = (Node *)n;
6276                                 }
6277                 | PARAM opt_indirection
6278                                 {
6279                                         ParamRef *n = makeNode(ParamRef);
6280                                         n->number = $1;
6281                                         n->fields = NIL;
6282                                         n->indirection = $2;
6283                                         $$ = (Node *)n;
6284                                 }
6285                 | TRUE_P
6286                                 {
6287                                         A_Const *n = makeNode(A_Const);
6288                                         n->val.type = T_String;
6289                                         n->val.val.str = "t";
6290                                         n->typename = SystemTypeName("bool");
6291                                         $$ = (Node *)n;
6292                                 }
6293                 | FALSE_P
6294                                 {
6295                                         A_Const *n = makeNode(A_Const);
6296                                         n->val.type = T_String;
6297                                         n->val.val.str = "f";
6298                                         n->typename = SystemTypeName("bool");
6299                                         $$ = (Node *)n;
6300                                 }
6301                 | NULL_P
6302                                 {
6303                                         A_Const *n = makeNode(A_Const);
6304                                         n->val.type = T_Null;
6305                                         $$ = (Node *)n;
6306                                 }
6307                 ;
6308
6309 Iconst:  ICONST                                                 { $$ = $1; };
6310 Sconst:  SCONST                                                 { $$ = $1; };
6311 UserId:  ColId                                                  { $$ = $1; };
6312
6313 /*
6314  * Name classification hierarchy.
6315  *
6316  * IDENT is the lexeme returned by the lexer for identifiers that match
6317  * no known keyword.  In most cases, we can accept certain keywords as
6318  * names, not only IDENTs.  We prefer to accept as many such keywords
6319  * as possible to minimize the impact of "reserved words" on programmers.
6320  * So, we divide names into several possible classes.  The classification
6321  * is chosen in part to make keywords acceptable as names wherever possible.
6322  */
6323
6324 /* Column identifier --- names that can be column, table, etc names.
6325  */
6326 ColId:  IDENT                                                   { $$ = $1; }
6327                 | unreserved_keyword                    { $$ = pstrdup($1); }
6328                 | col_name_keyword                              { $$ = pstrdup($1); }
6329                 ;
6330
6331 /* Type identifier --- names that can be type names.
6332  */
6333 type_name:  IDENT                                               { $$ = $1; }
6334                 | unreserved_keyword                    { $$ = pstrdup($1); }
6335                 ;
6336
6337 /* Function identifier --- names that can be function names.
6338  */
6339 function_name:  IDENT                                   { $$ = $1; }
6340                 | unreserved_keyword                    { $$ = pstrdup($1); }
6341                 | func_name_keyword                             { $$ = pstrdup($1); }
6342                 ;
6343
6344 /* Column label --- allowed labels in "AS" clauses.
6345  * This presently includes *all* Postgres keywords.
6346  */
6347 ColLabel:  IDENT                                                { $$ = $1; }
6348                 | unreserved_keyword                    { $$ = pstrdup($1); }
6349                 | col_name_keyword                              { $$ = pstrdup($1); }
6350                 | func_name_keyword                             { $$ = pstrdup($1); }
6351                 | reserved_keyword                              { $$ = pstrdup($1); }
6352                 ;
6353
6354
6355 /*
6356  * Keyword classification lists.  Generally, every keyword present in
6357  * the Postgres grammar should appear in exactly one of these lists.
6358  *
6359  * Put a new keyword into the first list that it can go into without causing
6360  * shift or reduce conflicts.  The earlier lists define "less reserved"
6361  * categories of keywords.
6362  */
6363
6364 /* "Unreserved" keywords --- available for use as any kind of name.
6365  */
6366 unreserved_keyword:
6367                   ABORT_TRANS
6368                 | ABSOLUTE
6369                 | ACCESS
6370                 | ACTION
6371                 | ADD
6372                 | AFTER
6373                 | AGGREGATE
6374                 | ALTER
6375                 | ASSERTION
6376                 | AT
6377                 | BACKWARD
6378                 | BEFORE
6379                 | BEGIN_TRANS
6380                 | BY
6381                 | CACHE
6382                 | CALLED
6383                 | CASCADE
6384                 | CHAIN
6385                 | CHARACTERISTICS
6386                 | CHECKPOINT
6387                 | CLOSE
6388                 | CLUSTER
6389                 | COMMENT
6390                 | COMMIT
6391                 | COMMITTED
6392                 | CONSTRAINTS
6393                 | COPY
6394                 | CREATEDB
6395                 | CREATEUSER
6396                 | CURSOR
6397                 | CYCLE
6398                 | DATABASE
6399                 | DAY_P
6400                 | DECLARE
6401                 | DEFERRED
6402                 | DEFINER
6403                 | DELETE_P
6404                 | DELIMITERS
6405                 | DOMAIN_P
6406                 | DOUBLE
6407                 | DROP
6408                 | EACH
6409                 | ENCODING
6410                 | ENCRYPTED
6411                 | ESCAPE
6412                 | EXCLUSIVE
6413                 | EXECUTE
6414                 | EXPLAIN
6415                 | EXTERNAL
6416                 | FETCH
6417                 | FORCE
6418                 | FORWARD
6419                 | FUNCTION
6420                 | GET
6421                 | GLOBAL
6422                 | HANDLER
6423                 | HOUR_P
6424                 | IMMEDIATE
6425                 | IMMUTABLE
6426                 | IMPLICIT
6427                 | INCREMENT
6428                 | INDEX
6429                 | INHERITS
6430                 | INOUT
6431                 | INPUT
6432                 | INSENSITIVE
6433                 | INSERT
6434                 | INSTEAD
6435                 | INVOKER
6436                 | ISOLATION
6437                 | KEY
6438                 | LANGUAGE
6439                 | LANCOMPILER
6440                 | LEVEL
6441                 | LISTEN
6442                 | LOAD
6443                 | LOCAL
6444                 | LOCATION
6445                 | LOCK_P
6446                 | MATCH
6447                 | MAXVALUE
6448                 | MINUTE_P
6449                 | MINVALUE
6450                 | MODE
6451                 | MONTH_P
6452                 | MOVE
6453                 | NAMES
6454                 | NATIONAL
6455                 | NEXT
6456                 | NO
6457                 | NOCREATEDB
6458                 | NOCREATEUSER
6459                 | NOTHING
6460                 | NOTIFY
6461                 | OF
6462                 | OIDS
6463                 | OPERATOR
6464                 | OPTION
6465                 | OUT_P
6466                 | OWNER
6467                 | PARTIAL
6468                 | PASSWORD
6469                 | PATH_P
6470                 | PENDANT
6471                 | PRECISION
6472                 | PRIOR
6473                 | PRIVILEGES
6474                 | PROCEDURAL
6475                 | PROCEDURE
6476                 | READ
6477                 | REINDEX
6478                 | RELATIVE
6479                 | RENAME
6480                 | REPLACE
6481                 | RESET
6482                 | RESTRICT
6483                 | RETURNS
6484                 | REVOKE
6485                 | ROLLBACK
6486                 | ROW
6487                 | RULE
6488                 | SCHEMA
6489                 | SCROLL
6490                 | SECOND_P
6491                 | SECURITY
6492                 | SESSION
6493                 | SEQUENCE
6494                 | SERIALIZABLE
6495                 | SET
6496                 | SHARE
6497                 | SHOW
6498                 | STABLE
6499                 | START
6500                 | STATEMENT
6501                 | STATISTICS
6502                 | STDIN
6503                 | STDOUT
6504                 | STORAGE
6505                 | STRICT
6506                 | SYSID
6507                 | TEMP
6508                 | TEMPLATE
6509                 | TEMPORARY
6510                 | TOAST
6511                 | TRANSACTION
6512                 | TRIGGER
6513                 | TRUNCATE
6514                 | TRUSTED
6515                 | TYPE_P
6516                 | UNENCRYPTED
6517                 | UNKNOWN
6518                 | UNLISTEN
6519                 | UNTIL
6520                 | UPDATE
6521                 | USAGE
6522                 | VACUUM
6523                 | VALID
6524                 | VALIDATOR
6525                 | VALUES
6526                 | VARYING
6527                 | VERSION
6528                 | VIEW
6529                 | VOLATILE
6530                 | WITH
6531                 | WITHOUT
6532                 | WORK
6533                 | YEAR_P
6534                 | ZONE
6535                 ;
6536
6537 /* Column identifier --- keywords that can be column, table, etc names.
6538  *
6539  * Many of these keywords will in fact be recognized as type or function
6540  * names too; but they have special productions for the purpose, and so
6541  * can't be treated as "generic" type or function names.
6542  *
6543  * The type names appearing here are not usable as function names
6544  * because they can be followed by '(' in typename productions, which
6545  * looks too much like a function call for an LR(1) parser.
6546  */
6547 col_name_keyword:
6548                   BIGINT
6549                 | BIT
6550                 | BOOLEAN
6551                 | CHAR_P
6552                 | CHARACTER
6553                 | COALESCE
6554                 | DEC
6555                 | DECIMAL
6556                 | EXISTS
6557                 | EXTRACT
6558                 | FLOAT_P
6559                 | INT
6560                 | INTEGER
6561                 | INTERVAL
6562                 | NCHAR
6563                 | NONE
6564                 | NULLIF
6565                 | NUMERIC
6566                 | OVERLAY
6567                 | POSITION
6568                 | REAL
6569                 | SETOF
6570                 | SMALLINT
6571                 | SUBSTRING
6572                 | TIME
6573                 | TIMESTAMP
6574                 | TRIM
6575                 | VARCHAR
6576                 ;
6577
6578 /* Function identifier --- keywords that can be function names.
6579  *
6580  * Most of these are keywords that are used as operators in expressions;
6581  * in general such keywords can't be column names because they would be
6582  * ambiguous with variables, but they are unambiguous as function identifiers.
6583  *
6584  * Do not include POSITION, SUBSTRING, etc here since they have explicit
6585  * productions in a_expr to support the goofy SQL9x argument syntax.
6586  * - thomas 2000-11-28
6587  */
6588 func_name_keyword:
6589                   AUTHORIZATION
6590                 | BETWEEN
6591                 | BINARY
6592                 | CROSS
6593                 | FREEZE
6594                 | FULL
6595                 | ILIKE
6596                 | IN_P
6597                 | INNER_P
6598                 | IS
6599                 | ISNULL
6600                 | JOIN
6601                 | LEFT
6602                 | LIKE
6603                 | NATURAL
6604                 | NOTNULL
6605                 | OUTER_P
6606                 | OVERLAPS
6607                 | RIGHT
6608                 | SIMILAR
6609                 | VERBOSE
6610                 ;
6611
6612 /* Reserved keyword --- these keywords are usable only as a ColLabel.
6613  *
6614  * Keywords appear here if they could not be distinguished from variable,
6615  * type, or function names in some contexts.  Don't put things here unless
6616  * forced to.
6617  */
6618 reserved_keyword:
6619                   ALL
6620                 | ANALYSE
6621                 | ANALYZE
6622                 | AND
6623                 | ANY
6624                 | AS
6625                 | ASC
6626                 | BOTH
6627                 | CASE
6628                 | CAST
6629                 | CHECK
6630                 | COLLATE
6631                 | COLUMN
6632                 | CONSTRAINT
6633                 | CREATE
6634                 | CURRENT_DATE
6635                 | CURRENT_TIME
6636                 | CURRENT_TIMESTAMP
6637                 | CURRENT_USER
6638                 | DEFAULT
6639                 | DEFERRABLE
6640                 | DESC
6641                 | DISTINCT
6642                 | DO
6643                 | ELSE
6644                 | END_TRANS
6645                 | EXCEPT
6646                 | FALSE_P
6647                 | FOR
6648                 | FOREIGN
6649                 | FROM
6650                 | GRANT
6651                 | GROUP_P
6652                 | HAVING
6653                 | INITIALLY
6654                 | INTERSECT
6655                 | INTO
6656                 | LEADING
6657                 | LIMIT
6658                 | LOCALTIME
6659                 | LOCALTIMESTAMP
6660                 | NEW
6661                 | NOT
6662                 | NULL_P
6663                 | OFF
6664                 | OFFSET
6665                 | OLD
6666                 | ON
6667                 | ONLY
6668                 | OR
6669                 | ORDER
6670                 | PLACING
6671                 | PRIMARY
6672                 | REFERENCES
6673                 | SELECT
6674                 | SESSION_USER
6675                 | SOME
6676                 | TABLE
6677                 | THEN
6678                 | TO
6679                 | TRAILING
6680                 | TRUE_P
6681                 | UNION
6682                 | UNIQUE
6683                 | USER
6684                 | USING
6685                 | WHEN
6686                 | WHERE
6687                 ;
6688
6689
6690 SpecialRuleRelation:  OLD
6691                                 {
6692                                         if (QueryIsRule)
6693                                                 $$ = "*OLD*";
6694                                         else
6695                                                 elog(ERROR, "OLD used in non-rule query");
6696                                 }
6697                 | NEW
6698                                 {
6699                                         if (QueryIsRule)
6700                                                 $$ = "*NEW*";
6701                                         else
6702                                                 elog(ERROR, "NEW used in non-rule query");
6703                                 }
6704                 ;
6705
6706 %%
6707
6708 static Node *
6709 makeTypeCast(Node *arg, TypeName *typename)
6710 {
6711         /*
6712          * If arg is an A_Const, just stick the typename into the
6713          * field reserved for it --- unless there's something there already!
6714          * (We don't want to collapse x::type1::type2 into just x::type2.)
6715          * Otherwise, generate a TypeCast node.
6716          */
6717         if (IsA(arg, A_Const) &&
6718                 ((A_Const *) arg)->typename == NULL)
6719         {
6720                 ((A_Const *) arg)->typename = typename;
6721                 return arg;
6722         }
6723         else
6724         {
6725                 TypeCast *n = makeNode(TypeCast);
6726                 n->arg = arg;
6727                 n->typename = typename;
6728                 return (Node *) n;
6729         }
6730 }
6731
6732 static Node *
6733 makeStringConst(char *str, TypeName *typename)
6734 {
6735         A_Const *n = makeNode(A_Const);
6736
6737         n->val.type = T_String;
6738         n->val.val.str = str;
6739         n->typename = typename;
6740
6741         return (Node *)n;
6742 }
6743
6744 static Node *
6745 makeIntConst(int val)
6746 {
6747         A_Const *n = makeNode(A_Const);
6748         n->val.type = T_Integer;
6749         n->val.val.ival = val;
6750         n->typename = SystemTypeName("int4");
6751
6752         return (Node *)n;
6753 }
6754
6755 static Node *
6756 makeFloatConst(char *str)
6757 {
6758         A_Const *n = makeNode(A_Const);
6759
6760         n->val.type = T_Float;
6761         n->val.val.str = str;
6762         n->typename = SystemTypeName("float8");
6763
6764         return (Node *)n;
6765 }
6766
6767 static Node *
6768 makeAConst(Value *v)
6769 {
6770         Node *n;
6771
6772         switch (v->type)
6773         {
6774                 case T_Float:
6775                         n = makeFloatConst(v->val.str);
6776                         break;
6777
6778                 case T_Integer:
6779                         n = makeIntConst(v->val.ival);
6780                         break;
6781
6782                 case T_String:
6783                 default:
6784                         n = makeStringConst(v->val.str, NULL);
6785                         break;
6786         }
6787
6788         return n;
6789 }
6790
6791 /* makeRowExpr()
6792  * Generate separate operator nodes for a single row descriptor expression.
6793  * Perhaps this should go deeper in the parser someday...
6794  * - thomas 1997-12-22
6795  */
6796 static Node *
6797 makeRowExpr(List *opr, List *largs, List *rargs)
6798 {
6799         Node *expr = NULL;
6800         Node *larg, *rarg;
6801         char *oprname;
6802
6803         if (length(largs) != length(rargs))
6804                 elog(ERROR, "Unequal number of entries in row expression");
6805
6806         if (lnext(largs) != NIL)
6807                 expr = makeRowExpr(opr, lnext(largs), lnext(rargs));
6808
6809         larg = lfirst(largs);
6810         rarg = lfirst(rargs);
6811
6812         oprname = strVal(llast(opr));
6813
6814         if ((strcmp(oprname, "=") == 0) ||
6815                 (strcmp(oprname, "<") == 0) ||
6816                 (strcmp(oprname, "<=") == 0) ||
6817                 (strcmp(oprname, ">") == 0) ||
6818                 (strcmp(oprname, ">=") == 0))
6819         {
6820                 if (expr == NULL)
6821                         expr = (Node *) makeA_Expr(OP, opr, larg, rarg);
6822                 else
6823                         expr = (Node *) makeA_Expr(AND, NIL, expr,
6824                                                                            (Node *) makeA_Expr(OP, opr,
6825                                                                                                                    larg, rarg));
6826         }
6827         else if (strcmp(oprname, "<>") == 0)
6828         {
6829                 if (expr == NULL)
6830                         expr = (Node *) makeA_Expr(OP, opr, larg, rarg);
6831                 else
6832                         expr = (Node *) makeA_Expr(OR, NIL, expr,
6833                                                                            (Node *) makeA_Expr(OP, opr,
6834                                                                                                                    larg, rarg));
6835         }
6836         else
6837         {
6838                 elog(ERROR, "Operator '%s' not implemented for row expressions",
6839                          oprname);
6840         }
6841
6842         return expr;
6843 }
6844
6845 /* findLeftmostSelect()
6846  *              Find the leftmost component SelectStmt in a set-operation parsetree.
6847  */
6848 static SelectStmt *
6849 findLeftmostSelect(SelectStmt *node)
6850 {
6851         while (node && node->op != SETOP_NONE)
6852                 node = node->larg;
6853         Assert(node && IsA(node, SelectStmt) && node->larg == NULL);
6854         return node;
6855 }
6856
6857 /* insertSelectOptions()
6858  *              Insert ORDER BY, etc into an already-constructed SelectStmt.
6859  *
6860  * This routine is just to avoid duplicating code in SelectStmt productions.
6861  */
6862 static void
6863 insertSelectOptions(SelectStmt *stmt,
6864                                         List *sortClause, List *forUpdate,
6865                                         Node *limitOffset, Node *limitCount)
6866 {
6867         /*
6868          * Tests here are to reject constructs like
6869          *      (SELECT foo ORDER BY bar) ORDER BY baz
6870          */
6871         if (sortClause)
6872         {
6873                 if (stmt->sortClause)
6874                         elog(ERROR, "Multiple ORDER BY clauses not allowed");
6875                 stmt->sortClause = sortClause;
6876         }
6877         if (forUpdate)
6878         {
6879                 if (stmt->forUpdate)
6880                         elog(ERROR, "Multiple FOR UPDATE clauses not allowed");
6881                 stmt->forUpdate = forUpdate;
6882         }
6883         if (limitOffset)
6884         {
6885                 if (stmt->limitOffset)
6886                         elog(ERROR, "Multiple OFFSET clauses not allowed");
6887                 stmt->limitOffset = limitOffset;
6888         }
6889         if (limitCount)
6890         {
6891                 if (stmt->limitCount)
6892                         elog(ERROR, "Multiple LIMIT clauses not allowed");
6893                 stmt->limitCount = limitCount;
6894         }
6895 }
6896
6897 static Node *
6898 makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
6899 {
6900         SelectStmt *n = makeNode(SelectStmt);
6901
6902         n->op = op;
6903         n->all = all;
6904         n->larg = (SelectStmt *) larg;
6905         n->rarg = (SelectStmt *) rarg;
6906         return (Node *) n;
6907 }
6908
6909 /* SystemFuncName()
6910  *      Build a properly-qualified reference to a built-in function.
6911  */
6912 List *
6913 SystemFuncName(char *name)
6914 {
6915         return makeList2(makeString("pg_catalog"), makeString(name));
6916 }
6917
6918 /* SystemTypeName()
6919  *      Build a properly-qualified reference to a built-in type.
6920  *
6921  * typmod is defaulted, but may be changed afterwards by caller.
6922  */
6923 TypeName *
6924 SystemTypeName(char *name)
6925 {
6926         TypeName   *n = makeNode(TypeName);
6927
6928         n->names = makeList2(makeString("pg_catalog"), makeString(name));
6929         n->typmod = -1;
6930         return n;
6931 }
6932
6933 /*
6934  * Initialize to parse one query string
6935  */
6936 void
6937 parser_init(Oid *typev, int nargs)
6938 {
6939         QueryIsRule = FALSE;
6940         /*
6941          * Keep enough information around to fill out the type of param nodes
6942          * used in postquel functions
6943          */
6944         param_type_info = typev;
6945         pfunc_num_args = nargs;
6946 }
6947
6948 /*
6949  * Fetch a parameter type previously passed to parser_init
6950  */
6951 Oid
6952 param_type(int t)
6953 {
6954         if ((t > pfunc_num_args) || (t <= 0))
6955                 return InvalidOid;
6956         return param_type_info[t - 1];
6957 }
6958
6959 /*
6960  * Test whether an a_expr is a plain NULL constant or not.
6961  */
6962 bool
6963 exprIsNullConstant(Node *arg)
6964 {
6965         if (arg && IsA(arg, A_Const))
6966         {
6967                 A_Const *con = (A_Const *) arg;
6968
6969                 if (con->val.type == T_Null &&
6970                         con->typename == NULL)
6971                         return TRUE;
6972         }
6973         return FALSE;
6974 }
6975
6976 /*
6977  * doNegate --- handle negation of a numeric constant.
6978  *
6979  * Formerly, we did this here because the optimizer couldn't cope with
6980  * indexquals that looked like "var = -4" --- it wants "var = const"
6981  * and a unary minus operator applied to a constant didn't qualify.
6982  * As of Postgres 7.0, that problem doesn't exist anymore because there
6983  * is a constant-subexpression simplifier in the optimizer.  However,
6984  * there's still a good reason for doing this here, which is that we can
6985  * postpone committing to a particular internal representation for simple
6986  * negative constants.  It's better to leave "-123.456" in string form
6987  * until we know what the desired type is.
6988  */
6989 static Node *
6990 doNegate(Node *n)
6991 {
6992         if (IsA(n, A_Const))
6993         {
6994                 A_Const *con = (A_Const *)n;
6995
6996                 if (con->val.type == T_Integer)
6997                 {
6998                         con->val.val.ival = -con->val.val.ival;
6999                         return n;
7000                 }
7001                 if (con->val.type == T_Float)
7002                 {
7003                         doNegateFloat(&con->val);
7004                         return n;
7005                 }
7006         }
7007
7008         return (Node *) makeSimpleA_Expr(OP, "-", NULL, n);
7009 }
7010
7011 static void
7012 doNegateFloat(Value *v)
7013 {
7014         char   *oldval = v->val.str;
7015
7016         Assert(IsA(v, Float));
7017         if (*oldval == '+')
7018                 oldval++;
7019         if (*oldval == '-')
7020                 v->val.str = oldval+1;  /* just strip the '-' */
7021         else
7022         {
7023                 char   *newval = (char *) palloc(strlen(oldval) + 2);
7024
7025                 *newval = '-';
7026                 strcpy(newval+1, oldval);
7027                 v->val.str = newval;
7028         }
7029 }