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