gram.y 131 KB
Newer Older
1 2
%{ /* -*-text-*- */

3
/*#define YYDEBUG 1*/
4
/*-------------------------------------------------------------------------
5
 *
6
 * gram.y
7
 *	  POSTGRES SQL YACC rules/actions
8
 *
9 10 11 12
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
13
 *	  $Header: /cvsroot/pgsql/src/backend/parser/gram.y,v 2.127 2000/01/16 20:04:55 petere Exp $
14 15
 *
 * HISTORY
16 17 18
 *	  AUTHOR			DATE			MAJOR EVENT
 *	  Andrew Yu			Sept, 1994		POSTQUEL to SQL conversion
 *	  Andrew Yu			Oct, 1994		lispy code conversion
19 20
 *
 * NOTES
21 22
 *	  CAPITALS are used to represent terminal symbols.
 *	  non-capitals are used to represent non-terminals.
23 24
 *	  SQL92-specific syntax is separated from plain SQL/Postgres syntax
 *	  to help isolate the non-extensible portions of the parser.
25
 *
26 27
 *	  if you use list, make sure the datum is a node so that the printing
 *	  routines work
28 29
 *
 * WARNING
30 31
 *	  sometimes we assign constants to makeStrings. Make sure we don't free
 *	  those.
32 33 34 35
 *
 *-------------------------------------------------------------------------
 */
#include <ctype.h>
Bruce Momjian's avatar
Bruce Momjian committed
36

37
#include "postgres.h"
38
#include "access/htup.h"
Bruce Momjian's avatar
Bruce Momjian committed
39 40 41
#include "access/xact.h"
#include "catalog/catname.h"
#include "catalog/pg_type.h"
42
#include "nodes/parsenodes.h"
43
#include "nodes/print.h"
Bruce Momjian's avatar
Bruce Momjian committed
44
#include "parser/analyze.h"
Bruce Momjian's avatar
Bruce Momjian committed
45
#include "parser/gramparse.h"
46
#include "parser/parse_type.h"
Bruce Momjian's avatar
Bruce Momjian committed
47
#include "storage/bufpage.h"
48
#include "storage/lmgr.h"
Bruce Momjian's avatar
Bruce Momjian committed
49
#include "utils/acl.h"
50
#include "utils/numeric.h"
51

Marc G. Fournier's avatar
Marc G. Fournier committed
52
#ifdef MULTIBYTE
53 54 55
#include "mb/pg_wchar.h"
#endif

56 57
extern List *parsetree;			/* final parse result is delivered here */

58
static char saved_relname[NAMEDATALEN];  /* need this for complex attributes */
59
static bool QueryIsRule = FALSE;
60 61
static Oid	*param_type_info;
static int	pfunc_num_args;
62

63

64
/*
65
 * If you need access to certain yacc-generated variables and find that
66 67 68 69 70
 * they're static by default, uncomment the next line.  (this is not a
 * problem, yet.)
 */
/*#define __YYSCLASS*/

71
static char *xlateSqlFunc(char *);
72
static char *xlateSqlType(char *);
73
static Node *makeA_Expr(int oper, char *opname, Node *lexpr, Node *rexpr);
Bruce Momjian's avatar
Bruce Momjian committed
74
static Node *makeRowExpr(char *opr, List *largs, List *rargs);
75
static void mapTargetColumns(List *source, List *target);
76
static void param_type_init(Oid *typev, int nargs);
77
static Node *doNegate(Node *n);
78

79 80 81 82 83 84 85
/* old versions of flex define this as a macro */
#if defined(yywrap)
#undef yywrap
#endif /* yywrap */
%}


86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
%union
{
	double				dval;
	int					ival;
	char				chr;
	char				*str;
	bool				boolean;
	List				*list;
	Node				*node;
	Value				*value;

	Attr				*attr;

	TypeName			*typnam;
	DefElem				*defelt;
	SortGroupBy			*sortgroupby;
102
	JoinExpr			*joinexpr;
103 104 105 106 107 108 109 110 111 112
	IndexElem			*ielem;
	RangeVar			*range;
	RelExpr				*relexp;
	A_Indices			*aind;
	ResTarget			*target;
	ParamNo				*paramno;

	VersionStmt			*vstmt;
	DefineStmt			*dstmt;
	RuleStmt			*rstmt;
Bruce Momjian's avatar
Bruce Momjian committed
113
	InsertStmt			*astmt;
114 115
}

116
%type <node>	stmt,
117
		AlterTableStmt, ClosePortalStmt,
118
		CopyStmt, CreateStmt, CreateAsStmt, CreateSeqStmt, DefineStmt, DropStmt,
119
		TruncateStmt, CommentStmt,
120
		ExtendStmt, FetchStmt,	GrantStmt, CreateTrigStmt, DropTrigStmt,
121
		CreatePLangStmt, DropPLangStmt,
122
		IndexStmt, ListenStmt, UnlistenStmt, LockStmt, OptimizableStmt,
Bruce Momjian's avatar
Bruce Momjian committed
123
		ProcedureStmt, RemoveAggrStmt, RemoveOperStmt,
Bruce Momjian's avatar
Bruce Momjian committed
124
		RemoveFuncStmt, RemoveStmt,
125
		RenameStmt, RevokeStmt, RuleStmt, TransactionStmt, ViewStmt, LoadStmt,
126
		CreatedbStmt, DropdbStmt, VacuumStmt, CursorStmt, SubSelect,
127
		UpdateStmt, InsertStmt, select_clause, SelectStmt, NotifyStmt, DeleteStmt, 
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
128
		ClusterStmt, ExplainStmt, VariableSetStmt, VariableShowStmt, VariableResetStmt,
129
		CreateUserStmt, AlterUserStmt, DropUserStmt, RuleActionStmt,
130
		RuleActionStmtOrEmpty, ConstraintsSetStmt,
131
                CreateGroupStmt, AlterGroupStmt, DropGroupStmt
132

133 134 135
%type <node>    alter_column_action
%type <ival>    drop_behavior

136 137
%type <str>		createdb_opt_location
%type <ival>    createdb_opt_encoding
138

139 140
%type <ival>	opt_lock, lock_type
%type <boolean>	opt_lmode
141

142
%type <ival>    user_createdb_clause, user_createuser_clause
143
%type <str>		user_passwd_clause
Bruce Momjian's avatar
Bruce Momjian committed
144
%type <ival>            sysid_clause
145
%type <str>		user_valid_clause
146
%type <list>	user_list, user_group_clause, users_in_new_group_clause
147

148
%type <boolean>	TriggerActionTime, TriggerForSpec, PLangTrusted
149

150 151
%type <str>		OptConstrFromTable

152
%type <str>		TriggerEvents, TriggerFuncArg
153

154
%type <str>		relation_name, copy_file_name, copy_delimiter, copy_null, def_name,
155
		database_name, access_method_clause, access_method, attr_name,
Bruce Momjian's avatar
Bruce Momjian committed
156
		class, index_name, name, func_name, file_name, aggr_argtype
157

158
%type <str>		opt_id, opt_portal_name,
Bruce Momjian's avatar
Bruce Momjian committed
159
		all_Op, MathOp, opt_name, opt_unique,
160
		OptUseOp, opt_class, SpecialRuleRelation
161

162
%type <str>		opt_level, opt_encoding
163 164
%type <str>		privileges, operation_commalist, grantee
%type <chr>		operation, TriggerOneEvent
165

166
%type <list>	stmtblock, stmtmulti,
167
		result, relation_name_list, OptTableElementList,
168
		OptInherit, definition,
169
		opt_with, func_args, func_args_list, func_as,
170
		oper_argtypes, RuleActionList, RuleActionMulti,
171 172
		opt_column_list, columnList, opt_va_list, va_list,
		sort_clause, sortby_list, index_params, index_list, name_list,
173 174
		from_clause, from_expr, table_list, opt_array_bounds,
		expr_list, attrs, target_list, update_target_list,
175 176
		def_list, opt_indirection, group_clause, TriggerFuncArgs,
		opt_select_limit
177

178 179 180
%type <node>	func_return
%type <boolean>	set_opt

181
%type <boolean>	TriggerForOpt, TriggerForType, OptTemp, OptTempType, OptTempScope
182

183
%type <list>	for_update_clause, update_list
184
%type <boolean>	opt_all
185
%type <boolean>	opt_table
186
%type <boolean>	opt_trans
187

188 189 190 191 192
%type <list>	join_clause_with_union, join_clause, join_list, join_qual, using_list
%type <node>	join_expr, using_expr
%type <str>		join_outer
%type <ival>	join_type

193 194
%type <list>	extract_list, position_list
%type <list>	substr_list, substr_from, substr_for, trim_list
195
%type <list>	opt_interval
196

Bruce Momjian's avatar
Bruce Momjian committed
197 198
%type <boolean> opt_inh_star, opt_binary, opt_using, opt_instead,
				opt_with_copy, index_opt_unique, opt_verbose, opt_analyze
Jan Wieck's avatar
Jan Wieck committed
199
%type <boolean> opt_cursor
200

Bruce Momjian's avatar
Bruce Momjian committed
201
%type <ival>	copy_dirn, def_type, opt_direction, remove_type,
Bruce Momjian's avatar
Bruce Momjian committed
202 203
		opt_column, event, comment_type, comment_cl,
		comment_ag, comment_fn, comment_op, comment_tg
204

Bruce Momjian's avatar
Bruce Momjian committed
205
%type <ival>	fetch_how_many
206

207 208
%type <node>	select_limit_value, select_offset_value

Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
209 210 211
%type <list>	OptSeqList
%type <defelt>	OptSeqElem

212 213 214
%type <dstmt>	def_rest
%type <astmt>	insert_rest

215
%type <node>	OptTableElement, ConstraintElem
216
%type <node>	columnDef
217
%type <defelt>	def_elem
218
%type <node>	def_arg, columnElem, where_clause,
219
				a_expr, a_expr_or_null, b_expr, com_expr, AexprConst,
220
				in_expr, having_clause
221
%type <list>	row_descriptor, row_list, in_expr_nodes
222
%type <node>	row_expr
223 224
%type <node>	case_expr, case_arg, when_clause, case_default
%type <list>	when_clause_list
225
%type <ival>	sub_type
226 227
%type <list>	OptCreateAs, CreateAsList
%type <node>	CreateAsElement
228
%type <value>	NumericOnly, FloatOnly, IntegerOnly
229
%type <attr>	event_object, attr
230
%type <sortgroupby>		sortby
231
%type <ielem>	index_elem, func_index
232
%type <range>	table_expr
233
%type <relexp>	relation_expr
234
%type <target>	target_el, update_target_el
235
%type <paramno> ParamNo
236

237 238
%type <typnam>	Typename, opt_type, SimpleTypename,
				Generic, Numeric, Character, Datetime
239
%type <str>		generic, numeric, character, datetime
240
%type <str>		extract_arg
241
%type <str>		opt_charset, opt_collate
242 243
%type <str>		opt_float
%type <ival>	opt_numeric, opt_decimal
244 245
%type <boolean>	opt_varying, opt_timezone

246
%type <ival>	Iconst
247
%type <str>		Sconst, comment_text
248
%type <str>		UserId, var_value, zone_value
249
%type <str>		ColId, ColLabel
250
%type <str>		TypeId
251

252
%type <node>	TableConstraint
253
%type <list>	ColPrimaryKey, ColConstraintList
254
%type <node>	ColConstraint, ColConstraintElem
Jan Wieck's avatar
Jan Wieck committed
255 256 257 258
%type <ival>	key_actions, key_action, key_reference
%type <str>		key_match
%type <ival>	ConstraintAttributeSpec, ConstraintDeferrabilitySpec,
				ConstraintTimeSpec
259

260 261 262 263
%type <list>	constraints_set_list
%type <list>	constraints_set_namelist
%type <boolean>	constraints_set_mode

264 265
/*
 * If you make any token changes, remember to:
266 267
 *		- use "yacc -d" and update parse.h
 *		- update the keyword table in parser/keywords.c
268 269
 */

270 271 272 273 274 275 276 277 278 279
/* Reserved word tokens
 * SQL92 syntax has many type-specific constructs.
 * So, go ahead and make these types reserved words,
 *  and call-out the syntax explicitly.
 * This gets annoying when trying to also retain Postgres' nice
 *  type-extensible features, but we don't really have a choice.
 * - thomas 1997-10-11
 */

/* Keywords (in SQL92 reserved words) */
280
%token	ABSOLUTE, ACTION, ADD, ALL, ALTER, AND, ANY, AS, ASC,
281
		BEGIN_TRANS, BETWEEN, BOTH, BY,
282
		CASCADE, CASE, CAST, CHAR, CHARACTER, CHECK, CLOSE,
283
		COALESCE, COLLATE, COLUMN, COMMIT,
284 285
		CONSTRAINT, CONSTRAINTS, CREATE, CROSS, CURRENT, CURRENT_DATE,
		CURRENT_TIME, CURRENT_TIMESTAMP, CURRENT_USER, CURSOR,
286
		DAY_P, DECIMAL, DECLARE, DEFAULT, DELETE, DESC, DISTINCT, DOUBLE, DROP,
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
287
		ELSE, END_TRANS, EXCEPT, EXECUTE, EXISTS, EXTRACT,
288
		FALSE_P, FETCH, FLOAT, FOR, FOREIGN, FROM, FULL,
289
		GLOBAL, GRANT, GROUP, HAVING, HOUR_P,
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
290 291
		IN, INNER_P, INSENSITIVE, INSERT, INTERSECT, INTERVAL, INTO, IS,
		ISOLATION, JOIN, KEY, LANGUAGE, LEADING, LEFT, LEVEL, LIKE, LOCAL,
292
		MATCH, MINUTE_P, MONTH_P, NAMES,
293
		NATIONAL, NATURAL, NCHAR, NEXT, NO, NOT, NULLIF, NULL_P, NUMERIC,
294 295 296 297
		OF, ON, ONLY, OPTION, OR, ORDER, OUTER_P,
		PARTIAL, POSITION, PRECISION, PRIMARY, PRIOR, PRIVILEGES, PROCEDURE, PUBLIC,
		READ, REFERENCES, RELATIVE, REVOKE, RIGHT, ROLLBACK,
		SCROLL, SECOND_P, SELECT, SET, SUBSTRING,
Bruce Momjian's avatar
Bruce Momjian committed
298 299
		TABLE, TEMP, TEMPORARY, THEN, TIME, TIMESTAMP, TIMEZONE_HOUR,
		TIMEZONE_MINUTE, TO, TRAILING, TRANSACTION, TRIM, TRUE_P,
300
		UNION, UNIQUE, UPDATE, USER, USING,
301
		VALUES, VARCHAR, VARYING, VIEW,
302
		WHEN, WHERE, WITH, WORK, YEAR_P, ZONE
303

Bruce Momjian's avatar
Bruce Momjian committed
304

305
/* Keywords (in SQL3 reserved words) */
306 307 308 309 310
%token	DEFERRABLE, DEFERRED,
		IMMEDIATE, INITIALLY,
		PENDANT,
		RESTRICT,
		TRIGGER
311 312

/* Keywords (in SQL92 non-reserved words) */
313
%token	COMMITTED, SERIALIZABLE, TYPE_P
314

315 316 317 318 319 320
/* Keywords for Postgres support (not in SQL92 reserved words)
 *
 * The CREATEDB and CREATEUSER tokens should go away
 * when some sort of pg_privileges relation is introduced.
 * - Todd A. Brandys 1998-01-01?
 */
321 322
%token	ABORT_TRANS, ACCESS, AFTER, AGGREGATE, ANALYZE,
		BACKWARD, BEFORE, BINARY, 
323
		CACHE, CLUSTER, COMMENT, COPY, CREATEDB, CREATEUSER, CYCLE,
324 325
		DATABASE, DELIMITERS, DO,
		EACH, ENCODING, EXCLUSIVE, EXPLAIN, EXTEND,
Bruce Momjian's avatar
Bruce Momjian committed
326
		FORWARD, FUNCTION, HANDLER,
327
		INCREMENT, INDEX, INHERITS, INSTEAD, ISNULL,
328
		LANCOMPILER, LIMIT, LISTEN, LOAD, LOCATION, LOCK_P,
329
		MAXVALUE, MINVALUE, MODE, MOVE,
330
		NEW, NOCREATEDB, NOCREATEUSER, NONE, NOTHING, NOTIFY, NOTNULL,
331
		OFFSET, OIDS, OPERATOR, PASSWORD, PROCEDURAL,
Bruce Momjian's avatar
Bruce Momjian committed
332
		RENAME, RESET, RETURNS, ROW, RULE,
Bruce Momjian's avatar
Bruce Momjian committed
333
		SEQUENCE, SERIAL, SETOF, SHARE, SHOW, START, STATEMENT, STDIN, STDOUT, SYSID,
334
		TRUNCATE, TRUSTED, 
335
		UNLISTEN, UNTIL, VACUUM, VALID, VERBOSE, VERSION
336

337
/* Special keywords, not in the query language - see the "lex" file */
338
%token <str>	IDENT, SCONST, Op
339 340 341
%token <ival>	ICONST, PARAM
%token <dval>	FCONST

342
/* these are not real. they are here so that they get generated as #define's*/
343
%token			OP
344 345

/* precedence */
346 347 348 349
%left		OR
%left		AND
%right		NOT
%right		'='
350
%nonassoc	'<' '>'
351 352 353
%nonassoc	LIKE
%nonassoc	BETWEEN
%nonassoc	IN
354
%left		Op				/* multi-character ops and user-defined operators */
355 356
%nonassoc	NOTNULL
%nonassoc	ISNULL
357
%nonassoc	NULL_P
358 359
%nonassoc	IS
%left		'+' '-'
360 361
%left		'*' '/' '%'
%left		'^'
362 363 364 365 366 367 368
%left		'|'				/* this is the relation union op, not logical or */
/* Unary Operators */
%right		':'
%left		';'				/* end of statement or natural log */
%right		UMINUS
%left		'.'
%left		'[' ']'
369
%left		TYPECAST
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
370
%left		UNION INTERSECT EXCEPT
371 372
%%

373 374 375 376 377 378
/*
 *	Handle comment-only lines, and ;; SELECT * FROM pg_class ;;;
 *	psql already handles such cases, but other interfaces don't.
 *	bjm 1999/10/05
 */
stmtblock:  stmtmulti
379 380
				{ parsetree = $1; }
		;
381

382
/* the thrashing around here is to discard "empty" statements... */
383
stmtmulti:  stmtmulti ';' stmt
384
				{ if ($3 != (Node *)NULL)
385 386 387 388
					$$ = lappend($1, $3);
				  else
					$$ = $1;
				}
389
		| stmt
390
				{ if ($1 != (Node *)NULL)
391 392
					$$ = lcons($1,NIL);
				  else
393
					$$ = NIL;
394
				}
395
		;
396

397
stmt :          AlterTableStmt
398
                | AlterGroupStmt
399
		| AlterUserStmt
400 401 402
		| ClosePortalStmt
		| CopyStmt
		| CreateStmt
403
		| CreateAsStmt
404
                | CreateGroupStmt
405
		| CreateSeqStmt
406
		| CreatePLangStmt
407
		| CreateTrigStmt
408
		| CreateUserStmt
409 410
		| ClusterStmt
		| DefineStmt
411
		| DropStmt		
412
		| TruncateStmt
413
		| CommentStmt
414
                | DropGroupStmt
415
		| DropPLangStmt
416
		| DropTrigStmt
417
		| DropUserStmt
418 419 420 421 422 423
		| ExtendStmt
		| ExplainStmt
		| FetchStmt
		| GrantStmt
		| IndexStmt
		| ListenStmt
424
		| UnlistenStmt
425
		| LockStmt
426 427 428 429 430 431 432 433 434 435 436 437 438
		| ProcedureStmt
		| RemoveAggrStmt
		| RemoveOperStmt
		| RemoveFuncStmt
		| RemoveStmt
		| RenameStmt
		| RevokeStmt
		| OptimizableStmt
		| RuleStmt
		| TransactionStmt
		| ViewStmt
		| LoadStmt
		| CreatedbStmt
439
		| DropdbStmt
440 441 442 443
		| VacuumStmt
		| VariableSetStmt
		| VariableShowStmt
		| VariableResetStmt
444
		| ConstraintsSetStmt
445
		|	/*EMPTY*/
446
				{ $$ = (Node *)NULL; }
447
		;
448

449 450
/*****************************************************************************
 *
451
 * Create a new Postgres DBMS user
452 453 454 455
 *
 *
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
456 457 458
CreateUserStmt:  CREATE USER UserId
                 user_createdb_clause user_createuser_clause user_group_clause
                 user_valid_clause
459 460 461
				{
					CreateUserStmt *n = makeNode(CreateUserStmt);
					n->user = $3;
Bruce Momjian's avatar
Bruce Momjian committed
462 463
                    n->sysid = -1;
					n->password = NULL;
464 465
					n->createdb = $4 == +1 ? true : false;
					n->createuser = $5 == +1 ? true : false;
Bruce Momjian's avatar
Bruce Momjian committed
466 467
					n->groupElts = $6;
					n->validUntil = $7;
468 469
					$$ = (Node *)n;
				}
Bruce Momjian's avatar
Bruce Momjian committed
470 471 472 473 474 475 476 477
                | CREATE USER UserId WITH sysid_clause user_passwd_clause
                user_createdb_clause user_createuser_clause user_group_clause
                user_valid_clause
               {
					CreateUserStmt *n = makeNode(CreateUserStmt);
					n->user = $3;
                    n->sysid = $5;
					n->password = $6;
478 479
					n->createdb = $7 == +1 ? true : false;
					n->createuser = $8 == +1 ? true : false;
Bruce Momjian's avatar
Bruce Momjian committed
480 481 482 483
					n->groupElts = $9;
					n->validUntil = $10;
					$$ = (Node *)n;
               }                   
484
		;
485 486 487 488 489 490 491 492

/*****************************************************************************
 *
 * Alter a postresql DBMS user
 *
 *
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
493
AlterUserStmt:  ALTER USER UserId user_createdb_clause
494
                user_createuser_clause user_valid_clause
495 496 497
				{
					AlterUserStmt *n = makeNode(AlterUserStmt);
					n->user = $3;
Bruce Momjian's avatar
Bruce Momjian committed
498 499 500
					n->password = NULL;
					n->createdb = $4;
					n->createuser = $5;
501
					n->validUntil = $6;
Bruce Momjian's avatar
Bruce Momjian committed
502 503
					$$ = (Node *)n;
				}
504
              | ALTER USER UserId WITH PASSWORD Sconst
Bruce Momjian's avatar
Bruce Momjian committed
505
                user_createdb_clause
506
                user_createuser_clause user_valid_clause
Bruce Momjian's avatar
Bruce Momjian committed
507 508 509 510 511 512
				{
					AlterUserStmt *n = makeNode(AlterUserStmt);
					n->user = $3;
					n->password = $6;
					n->createdb = $7;
					n->createuser = $8;
513
                    n->validUntil = $9;
514 515 516
					$$ = (Node *)n;
				}
		;
517 518 519 520 521 522 523 524

/*****************************************************************************
 *
 * Drop a postresql DBMS user
 *
 *
 *****************************************************************************/

525
DropUserStmt:  DROP USER user_list
526 527
				{
					DropUserStmt *n = makeNode(DropUserStmt);
528
					n->users = $3;
529 530 531 532
					$$ = (Node *)n;
				}
		;

533
user_passwd_clause:  PASSWORD Sconst		        { $$ = $2; }
Bruce Momjian's avatar
Bruce Momjian committed
534
                        | /*EMPTY*/					{ $$ = NULL; }
535 536
		;

537 538 539 540 541 542
sysid_clause: SYSID Iconst
              {
                  if ($2 <= 0)
                      elog(ERROR, "sysid must be positive");
                  $$ = $2;
              }
Bruce Momjian's avatar
Bruce Momjian committed
543 544 545
                        | /*EMPTY*/                     { $$ = -1; }
        ;

546 547 548
user_createdb_clause:  CREATEDB                         { $$ = +1; }
            | NOCREATEDB                    { $$ = -1; }
			| /*EMPTY*/			{ $$ = 0; }
549 550
		;

551 552 553
user_createuser_clause:  CREATEUSER                     { $$ = +1; }
			| NOCREATEUSER                  { $$ = -1; }
			| /*EMPTY*/			{ $$ = 0; }
554 555
		;

556
user_list:  user_list ',' UserId
557 558 559
				{
					$$ = lcons((void*)makeString($3), $1);
				}
560
			| UserId
561 562 563 564 565
				{
					$$ = lcons((void*)makeString($1), NIL);
				}
		;

566
user_group_clause:  IN GROUP user_list    { $$ = $3; }
567
			| /*EMPTY*/             { $$ = NULL; }
568 569 570 571 572
		;

user_valid_clause:  VALID UNTIL SCONST			{ $$ = $3; }
			| /*EMPTY*/							{ $$ = NULL; }
		;
573

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600

/*****************************************************************************
 *
 * Create a postresql group
 *
 *
 *****************************************************************************/

CreateGroupStmt:  CREATE GROUP UserId 
                  {
                        CreateGroupStmt *n = makeNode(CreateGroupStmt);
			n->name = $3;
                        n->sysid = -1;
                        n->initUsers = NULL;
                        $$ = (Node *)n;
                  }
                  |
                  CREATE GROUP UserId WITH sysid_clause users_in_new_group_clause
                  {
                        CreateGroupStmt *n = makeNode(CreateGroupStmt);
			n->name = $3;
                        n->sysid = $5;
                        n->initUsers = $6;
                        $$ = (Node *)n;
                  }
                ;

601
users_in_new_group_clause:  USER user_list   { $$ = $2; }
602 603 604 605 606 607 608 609 610 611
                            | /* EMPTY */          { $$ = NULL; }
                ;                         

/*****************************************************************************
 *
 * Alter a postresql group
 *
 *
 *****************************************************************************/

612
AlterGroupStmt: ALTER GROUP UserId ADD USER user_list
613 614 615 616 617 618 619 620 621
                {
                        AlterGroupStmt *n = makeNode(AlterGroupStmt);
			n->name = $3;
                        n->sysid = -1;
                        n->action = +1;
                        n->listUsers = $6;
                        $$ = (Node *)n;
                }
                |
622
                ALTER GROUP UserId DROP USER user_list
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
                {
                        AlterGroupStmt *n = makeNode(AlterGroupStmt);
			n->name = $3;
                        n->sysid = -1;
                        n->action = -1;
                        n->listUsers = $6;
                        $$ = (Node *)n;
                }
                ;

/*****************************************************************************
 *
 * Drop a postresql group
 *
 *
 *****************************************************************************/

DropGroupStmt: DROP GROUP UserId
               {
                        DropGroupStmt *n = makeNode(DropGroupStmt);
			n->name = $3;
                        $$ = (Node *)n;
               }
                ;


649
/*****************************************************************************
650
 *
651
 * Set PG internal variable
652
 *	  SET name TO 'var_value'
653 654
 * Include SQL92 syntax (thomas 1997-10-22):
 *    SET TIME ZONE 'var_value'
655
 *
656 657
 *****************************************************************************/

658
VariableSetStmt:  SET ColId TO var_value
659 660 661 662 663 664
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = $2;
					n->value = $4;
					$$ = (Node *) n;
				}
665
		| SET ColId '=' var_value
666 667 668 669 670 671
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = $2;
					n->value = $4;
					$$ = (Node *) n;
				}
672
		| SET TIME ZONE zone_value
673 674 675 676 677 678
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = "timezone";
					n->value = $4;
					$$ = (Node *) n;
				}
679
		| SET TRANSACTION ISOLATION LEVEL opt_level
680 681 682 683 684 685
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = "XactIsoLevel";
					n->value = $5;
					$$ = (Node *) n;
				}
686
		| SET NAMES opt_encoding
687
				{
688
#ifdef MULTIBYTE
689 690 691 692 693
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = "client_encoding";
					n->value = $3;
					$$ = (Node *) n;
#else
694
					elog(ERROR, "SET NAMES is not supported.");
695 696
#endif
				}
697 698
		;

699 700 701 702
opt_level:  READ COMMITTED					{ $$ = "committed"; }
		| SERIALIZABLE						{ $$ = "serializable"; }
		;

703
var_value:  Sconst			{ $$ = $1; }
704
		| DEFAULT			{ $$ = NULL; }
705 706
		;

707
zone_value:  Sconst			{ $$ = $1; }
708
		| DEFAULT			{ $$ = NULL; }
709
		| LOCAL				{ $$ = NULL; }
710
		;
711

712 713 714 715 716
opt_encoding:  Sconst       { $$ = $1; }
        | DEFAULT           { $$ = NULL; }
        | /*EMPTY*/         { $$ = NULL; }
        ;

717
VariableShowStmt:  SHOW ColId
718 719 720 721 722
				{
					VariableShowStmt *n = makeNode(VariableShowStmt);
					n->name  = $2;
					$$ = (Node *) n;
				}
723 724 725 726 727 728
		| SHOW TIME ZONE
				{
					VariableShowStmt *n = makeNode(VariableShowStmt);
					n->name  = "timezone";
					$$ = (Node *) n;
				}
729 730 731 732 733 734
		| SHOW TRANSACTION ISOLATION LEVEL
				{
					VariableShowStmt *n = makeNode(VariableShowStmt);
					n->name  = "XactIsoLevel";
					$$ = (Node *) n;
				}
735 736
		;

737
VariableResetStmt:	RESET ColId
738 739 740 741 742
				{
					VariableResetStmt *n = makeNode(VariableResetStmt);
					n->name  = $2;
					$$ = (Node *) n;
				}
743 744 745 746 747 748
		| RESET TIME ZONE
				{
					VariableResetStmt *n = makeNode(VariableResetStmt);
					n->name  = "timezone";
					$$ = (Node *) n;
				}
749 750 751 752 753 754
		| RESET TRANSACTION ISOLATION LEVEL
				{
					VariableResetStmt *n = makeNode(VariableResetStmt);
					n->name  = "XactIsoLevel";
					$$ = (Node *) n;
				}
755
		;
756

757

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
ConstraintsSetStmt:	SET CONSTRAINTS constraints_set_list constraints_set_mode
				{
					ConstraintsSetStmt *n = makeNode(ConstraintsSetStmt);
					n->constraints = $3;
					n->deferred    = $4;
					$$ = (Node *) n;
				}
		;


constraints_set_list:	ALL
				{
					$$ = NIL;
				}
		| constraints_set_namelist
				{
					$$ = $1;
				}
		;


constraints_set_namelist:	IDENT
				{
					$$ = lappend(NIL, $1);
				}
		| constraints_set_namelist ',' IDENT
				{
					$$ = lappend($1, $3);
				}
		;


constraints_set_mode:	DEFERRED
				{
					$$ = true;
				}
		| IMMEDIATE
				{
					$$ = false;
				}
		;


801 802
/*****************************************************************************
 *
803
 *	ALTER TABLE variations
804 805 806
 *
 *****************************************************************************/

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
AlterTableStmt:
/* ALTER TABLE <name> ADD [COLUMN] <coldef> */
        ALTER TABLE relation_name opt_inh_star ADD opt_column columnDef
	{
		AlterTableStmt *n = makeNode(AlterTableStmt);
                n->subtype = 'A';
		n->relname = $3;
		n->inh = $4;
		n->def = $7;
		$$ = (Node *)n;
	}
/* ALTER TABLE <name> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
      | ALTER TABLE relation_name opt_inh_star ALTER opt_column ColId alter_column_action
        {
                AlterTableStmt *n = makeNode(AlterTableStmt);
                n->subtype = 'T';
                n->relname = $3;
                n->inh = $4;
                n->name = $7;
                n->def = $8;
                $$ = (Node *)n;
        }
/* ALTER TABLE <name> DROP [COLUMN] <name> {RESTRICT|CASCADE} */
      | ALTER TABLE relation_name opt_inh_star DROP opt_column ColId drop_behavior
        {
                AlterTableStmt *n = makeNode(AlterTableStmt);
                n->subtype = 'D';
                n->relname = $3;
                n->inh = $4;
                n->name = $7;
                n->behavior = $8;
                $$ = (Node *)n;
        }
/* ALTER TABLE <name> ADD CONSTRAINT ... */
      | ALTER TABLE relation_name opt_inh_star ADD TableConstraint
        {
                AlterTableStmt *n = makeNode(AlterTableStmt);
                n->subtype = 'A';
                n->relname = $3;
                n->inh = $4;
                n->def = $6;
                $$ = (Node *)n;
        }
/* ALTER TABLE <name> DROP CONSTRAINT <name> {RESTRICT|CASCADE} */
      | ALTER TABLE relation_name opt_inh_star DROP CONSTRAINT name drop_behavior
        {
                AlterTableStmt *n = makeNode(AlterTableStmt);
                n->relname = $3;
                n->inh = $4;
                n->name = $7;
                n->behavior = $8;
                $$ = (Node *)n;
        }
        ;

alter_column_action:
        SET DEFAULT a_expr_or_null { $$ = $3; }
        | DROP DEFAULT          { $$ = NULL; }
        ;

drop_behavior: CASCADE { $$ = CASCADE; }
               | RESTRICT { $$ = RESTRICT; }
        ;
870

871

872 873

/*****************************************************************************
874
 *
875 876
 *		QUERY :
 *				close <optname>
877
 *
878 879
 *****************************************************************************/

880
ClosePortalStmt:  CLOSE opt_id
881 882 883 884 885 886
				{
					ClosePortalStmt *n = makeNode(ClosePortalStmt);
					n->portalname = $2;
					$$ = (Node *)n;
				}
		;
887

888 889 890 891
opt_id:  ColId									{ $$ = $1; }
		| /*EMPTY*/								{ $$ = NULL; }
		;

892 893 894

/*****************************************************************************
 *
895 896 897
 *		QUERY :
 *				COPY [BINARY] <relname> FROM/TO
 *				[USING DELIMITERS <delimiter>]
898 899 900
 *
 *****************************************************************************/

901
CopyStmt:  COPY opt_binary relation_name opt_with_copy copy_dirn copy_file_name copy_delimiter copy_null
902 903 904 905 906 907 908 909
				{
					CopyStmt *n = makeNode(CopyStmt);
					n->binary = $2;
					n->relname = $3;
					n->oids = $4;
					n->direction = $5;
					n->filename = $6;
					n->delimiter = $7;
910
                                        n->null_print = $8;
911 912 913 914 915 916
					$$ = (Node *)n;
				}
		;

copy_dirn:	TO
				{ $$ = TO; }
917
		| FROM
918 919
				{ $$ = FROM; }
		;
920

921
/*
922 923
 * copy_file_name NULL indicates stdio is used. Whether stdin or stdout is
 * used depends on the direction. (It really doesn't make sense to copy from
924
 * stdout. We silently correct the "typo".		 - AY 9/94
925
 */
926 927 928 929
copy_file_name:  Sconst							{ $$ = $1; }
		| STDIN									{ $$ = NULL; }
		| STDOUT								{ $$ = NULL; }
		;
930

931 932
opt_binary:  BINARY								{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
933
		;
934

935
opt_with_copy:	WITH OIDS						{ $$ = TRUE; }
936
		| /*EMPTY*/								{ $$ = FALSE; }
937
		;
938

939 940 941
/*
 * the default copy delimiter is tab but the user can configure it
 */
Bruce Momjian's avatar
Bruce Momjian committed
942
copy_delimiter:  opt_using DELIMITERS Sconst	{ $$ = $3; }
943
		| /*EMPTY*/								{ $$ = "\t"; }
944
		;
945

Bruce Momjian's avatar
Bruce Momjian committed
946 947 948 949
opt_using:	USING								{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = TRUE; }
		;

950 951
copy_null:      WITH NULL_P AS Sconst { $$ = $4; }
                | /*EMPTY*/         { $$ = "\\N"; }
952 953 954

/*****************************************************************************
 *
955 956
 *		QUERY :
 *				CREATE relname
957 958 959
 *
 *****************************************************************************/

960
CreateStmt:  CREATE OptTemp TABLE relation_name '(' OptTableElementList ')'
961
				OptInherit
962 963
				{
					CreateStmt *n = makeNode(CreateStmt);
964 965 966 967
					n->istemp = $2;
					n->relname = $4;
					n->tableElts = $6;
					n->inhRelnames = $8;
968
					n->constraints = NIL;
969 970 971 972
					$$ = (Node *)n;
				}
		;

973 974 975 976 977
OptTemp:  OptTempType						{ $$ = $1; }
			| OptTempScope OptTempType		{ $$ = $2; }
		;

OptTempType:  TEMP							{ $$ = TRUE; }
Bruce Momjian's avatar
Bruce Momjian committed
978
			| TEMPORARY						{ $$ = TRUE; }
979 980 981
			| /*EMPTY*/						{ $$ = FALSE; }
		;

982 983 984 985 986 987 988 989 990 991 992
OptTempScope:  GLOBAL
				{
					elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
					$$ = TRUE;
				}
			| LOCAL
				{
					 $$ = FALSE;
				}
		;

993
OptTableElementList:  OptTableElementList ',' OptTableElement
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
				{
					if ($3 != NULL)
						$$ = lappend($1, $3);
					else
						$$ = $1;
				}
			| OptTableElement
				{
					if ($1 != NULL)
						$$ = lcons($1, NIL);
					else
						$$ = NULL;
				}
1007
			| /*EMPTY*/							{ $$ = NULL; }
1008
		;
1009

1010 1011
OptTableElement:  columnDef						{ $$ = $1; }
			| TableConstraint					{ $$ = $1; }
1012
		;
1013

1014
columnDef:  ColId Typename ColConstraintList
1015 1016 1017 1018
				{
					ColumnDef *n = makeNode(ColumnDef);
					n->colname = $1;
					n->typename = $2;
1019 1020
					n->raw_default = NULL;
					n->cooked_default = NULL;
1021 1022
					n->is_not_null = FALSE;
					n->constraints = $3;
1023 1024
					$$ = (Node *)n;
				}
1025
			| ColId SERIAL ColPrimaryKey
1026 1027 1028 1029 1030
				{
					ColumnDef *n = makeNode(ColumnDef);
					n->colname = $1;
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("integer");
1031 1032
					n->raw_default = NULL;
					n->cooked_default = NULL;
1033 1034
					n->is_not_null = TRUE;
					n->is_sequence = TRUE;
1035
					n->constraints = $3;
1036

1037 1038 1039 1040
					$$ = (Node *)n;
				}
		;

1041
ColConstraintList:  ColConstraintList ColConstraint
1042 1043 1044 1045 1046 1047
				{
					if ($2 != NULL)
						$$ = lappend($1, $2);
					else
						$$ = $1;
				}
1048 1049
			| /*EMPTY*/
				{ $$ = NIL; }
1050 1051
		;

1052 1053 1054 1055 1056
ColPrimaryKey:  PRIMARY KEY
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_PRIMARY;
					n->name = NULL;
1057 1058
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1059 1060 1061 1062 1063 1064
					n->keys = NULL;
					$$ = lcons((Node *)n, NIL);
				}
			| /*EMPTY*/							{ $$ = NULL; }
		;

1065 1066 1067
ColConstraint:
		CONSTRAINT name ColConstraintElem
				{
Jan Wieck's avatar
Jan Wieck committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
					switch (nodeTag($3))
					{
						case T_Constraint:
							{
								Constraint *n = (Constraint *)$3;
								if (n != NULL) n->name = $2;
							}
							break;
						case T_FkConstraint:
							{
								FkConstraint *n = (FkConstraint *)$3;
								if (n != NULL) n->constr_name = $2;
							}
							break;
						default:
							break;
					}
					$$ = $3;
1086 1087 1088
				}
		| ColConstraintElem
				{ $$ = $1; }
1089
		;
1090

1091 1092
/*
 * DEFAULT NULL is already the default for Postgres.
1093
 * But define it here and carry it forward into the system
1094 1095
 * to make it explicit.
 * - thomas 1998-09-13
1096
 *
1097 1098 1099 1100 1101
 * WITH NULL and NULL are not SQL92-standard syntax elements,
 * so leave them out. Use DEFAULT NULL to explicitly indicate
 * that a column may have that value. WITH NULL leads to
 * shift/reduce conflicts with WITH TIME ZONE anyway.
 * - thomas 1999-01-08
1102
 *
1103 1104 1105
 * DEFAULT expression must be b_expr not a_expr to prevent shift/reduce
 * conflict on NOT (since NOT might start a subsequent NOT NULL constraint,
 * or be part of a_expr NOT LIKE or similar constructs).
1106
 */
1107
ColConstraintElem:  CHECK '(' a_expr ')'
1108 1109 1110 1111
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_CHECK;
					n->name = NULL;
1112 1113
					n->raw_expr = $3;
					n->cooked_expr = NULL;
1114 1115 1116
					n->keys = NULL;
					$$ = (Node *)n;
				}
1117 1118 1119 1120 1121
			| DEFAULT NULL_P
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_DEFAULT;
					n->name = NULL;
1122 1123
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1124 1125 1126
					n->keys = NULL;
					$$ = (Node *)n;
				}
1127
			| DEFAULT b_expr
1128 1129 1130 1131
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_DEFAULT;
					n->name = NULL;
1132 1133
					n->raw_expr = $2;
					n->cooked_expr = NULL;
1134 1135 1136 1137 1138 1139 1140 1141
					n->keys = NULL;
					$$ = (Node *)n;
				}
			| NOT NULL_P
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_NOTNULL;
					n->name = NULL;
1142 1143
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1144 1145 1146 1147 1148 1149 1150 1151
					n->keys = NULL;
					$$ = (Node *)n;
				}
			| UNIQUE
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_UNIQUE;
					n->name = NULL;
1152 1153
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1154 1155 1156 1157 1158 1159 1160 1161
					n->keys = NULL;
					$$ = (Node *)n;
				}
			| PRIMARY KEY
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_PRIMARY;
					n->name = NULL;
1162 1163
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1164 1165 1166
					n->keys = NULL;
					$$ = (Node *)n;
				}
Jan Wieck's avatar
Jan Wieck committed
1167
			| REFERENCES ColId opt_column_list key_match key_actions 
1168
				{
Jan Wieck's avatar
Jan Wieck committed
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
					/* XXX
					 *	Need ConstraintAttributeSpec as $6 -- Jan
					 */
					FkConstraint *n = makeNode(FkConstraint);
					n->constr_name		= NULL;
					n->pktable_name		= $2;
					n->fk_attrs			= NIL;
					n->pk_attrs			= $3;
					n->match_type		= $4;
					n->actions			= $5;
					n->deferrable		= true;
					n->initdeferred		= false;
					/*
					n->deferrable		= ($6 & 1) != 0;
					n->initdeferred		= ($6 & 2) != 0;
					*/
					$$ = (Node *)n;
1186
				}
1187
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1188

1189 1190 1191 1192 1193
/* ConstraintElem specifies constraint syntax which is not embedded into
 *  a column definition. ColConstraintElem specifies the embedded form.
 * - thomas 1997-12-03
 */
TableConstraint:  CONSTRAINT name ConstraintElem
1194
				{
Jan Wieck's avatar
Jan Wieck committed
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
					switch (nodeTag($3))
					{
						case T_Constraint:
							{
								Constraint *n = (Constraint *)$3;
								if (n != NULL) n->name = $2;
							}
							break;
						case T_FkConstraint:
							{
								FkConstraint *n = (FkConstraint *)$3;
								if (n != NULL) n->constr_name = $2;
							}
							break;
						default:
							break;
					}
					$$ = $3;
1213
				}
1214 1215
		| ConstraintElem
				{ $$ = $1; }
1216 1217
		;

1218
ConstraintElem:  CHECK '(' a_expr ')'
1219
				{
1220 1221 1222
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_CHECK;
					n->name = NULL;
1223 1224
					n->raw_expr = $3;
					n->cooked_expr = NULL;
1225
					$$ = (Node *)n;
1226
				}
1227
		| UNIQUE '(' columnList ')'
1228 1229 1230 1231
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_UNIQUE;
					n->name = NULL;
1232 1233
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1234 1235 1236
					n->keys = $3;
					$$ = (Node *)n;
				}
1237
		| PRIMARY KEY '(' columnList ')'
1238 1239 1240 1241
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_PRIMARY;
					n->name = NULL;
1242 1243
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1244 1245 1246
					n->keys = $4;
					$$ = (Node *)n;
				}
Jan Wieck's avatar
Jan Wieck committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
		| FOREIGN KEY '(' columnList ')' REFERENCES ColId opt_column_list key_match key_actions ConstraintAttributeSpec
				{
					FkConstraint *n = makeNode(FkConstraint);
					n->constr_name		= NULL;
					n->pktable_name		= $7;
					n->fk_attrs			= $4;
					n->pk_attrs			= $8;
					n->match_type		= $9;
					n->actions			= $10;
					n->deferrable		= ($11 & 1) != 0;
					n->initdeferred		= ($11 & 2) != 0;
					$$ = (Node *)n;
1259
				}
1260
		;
1261

Jan Wieck's avatar
Jan Wieck committed
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
key_match:  MATCH FULL
			{
				$$ = "FULL";
			}
		| MATCH PARTIAL
			{
				elog(ERROR, "FOREIGN KEY match type PARTIAL not implemented yet");
				$$ = "PARTIAL";
			}
		| /*EMPTY*/
			{
				elog(ERROR, "FOREIGN KEY match type UNSPECIFIED not implemented yet");
				$$ = "UNSPECIFIED";
			}
1276 1277
		;

Jan Wieck's avatar
Jan Wieck committed
1278 1279 1280
key_actions:  key_action key_action		{ $$ = $1 | $2; }
		| key_action					{ $$ = $1; }
		| /*EMPTY*/						{ $$ = 0; }
1281 1282
		;

Jan Wieck's avatar
Jan Wieck committed
1283 1284
key_action:  ON DELETE key_reference	{ $$ = $3 << FKCONSTR_ON_DELETE_SHIFT; }
		| ON UPDATE key_reference		{ $$ = $3 << FKCONSTR_ON_UPDATE_SHIFT; }
1285 1286
		;

Jan Wieck's avatar
Jan Wieck committed
1287 1288 1289 1290 1291
key_reference:  NO ACTION				{ $$ = FKCONSTR_ON_KEY_NOACTION; }
		| RESTRICT						{ $$ = FKCONSTR_ON_KEY_RESTRICT; }
		| CASCADE						{ $$ = FKCONSTR_ON_KEY_CASCADE; }
		| SET NULL_P					{ $$ = FKCONSTR_ON_KEY_SETNULL; }
		| SET DEFAULT					{ $$ = FKCONSTR_ON_KEY_SETDEFAULT; }
1292 1293
		;

1294 1295 1296 1297
OptInherit:  INHERITS '(' relation_name_list ')'		{ $$ = $3; }
		| /*EMPTY*/										{ $$ = NIL; }
		;

1298 1299 1300 1301 1302 1303
/*
 * Note: CREATE TABLE ... AS SELECT ... is just another spelling for
 * SELECT ... INTO.
 */

CreateAsStmt:  CREATE OptTemp TABLE relation_name OptCreateAs AS SelectStmt
1304
				{
1305 1306 1307
					SelectStmt *n = (SelectStmt *)$7;
					if ($5 != NIL)
						mapTargetColumns($5, n->targetList);
1308 1309
					if (n->into != NULL)
						elog(ERROR,"CREATE TABLE/AS SELECT may not specify INTO");
1310 1311
					n->istemp = $2;
					n->into = $4;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
					$$ = (Node *)n;
				}
		;

OptCreateAs:  '(' CreateAsList ')'				{ $$ = $2; }
			| /*EMPTY*/							{ $$ = NULL; }
		;

CreateAsList:  CreateAsList ',' CreateAsElement	{ $$ = lappend($1, $3); }
			| CreateAsElement					{ $$ = lcons($1, NIL); }
		;

CreateAsElement:  ColId
				{
					ColumnDef *n = makeNode(ColumnDef);
					n->colname = $1;
					n->typename = NULL;
1329 1330
					n->raw_default = NULL;
					n->cooked_default = NULL;
1331 1332 1333 1334 1335 1336
					n->is_not_null = FALSE;
					n->constraints = NULL;
					$$ = (Node *)n;
				}
		;

1337

Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1338 1339
/*****************************************************************************
 *
1340 1341
 *		QUERY :
 *				CREATE SEQUENCE seqname
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1342 1343 1344
 *
 *****************************************************************************/

1345
CreateSeqStmt:  CREATE SEQUENCE relation_name OptSeqList
1346 1347 1348 1349 1350 1351 1352
				{
					CreateSeqStmt *n = makeNode(CreateSeqStmt);
					n->seqname = $3;
					n->options = $4;
					$$ = (Node *)n;
				}
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1353

1354
OptSeqList:  OptSeqList OptSeqElem
1355
				{ $$ = lappend($1, $2); }
1356
			|	{ $$ = NIL; }
1357 1358
		;

1359
OptSeqElem:  CACHE IntegerOnly
1360 1361
				{
					$$ = makeNode(DefElem);
1362
					$$->defname = "cache";
1363 1364
					$$->arg = (Node *)$2;
				}
1365
			| CYCLE
1366 1367
				{
					$$ = makeNode(DefElem);
1368
					$$->defname = "cycle";
1369 1370
					$$->arg = (Node *)NULL;
				}
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
			| INCREMENT IntegerOnly
				{
					$$ = makeNode(DefElem);
					$$->defname = "increment";
					$$->arg = (Node *)$2;
				}
			| MAXVALUE IntegerOnly
				{
					$$ = makeNode(DefElem);
					$$->defname = "maxvalue";
					$$->arg = (Node *)$2;
				}
			| MINVALUE IntegerOnly
				{
					$$ = makeNode(DefElem);
					$$->defname = "minvalue";
					$$->arg = (Node *)$2;
				}
			| START IntegerOnly
				{
					$$ = makeNode(DefElem);
					$$->defname = "start";
					$$->arg = (Node *)$2;
				}
		;

1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
NumericOnly:  FloatOnly					{ $$ = $1; }
			| IntegerOnly				{ $$ = $1; }

FloatOnly:  FCONST
				{
					$$ = makeFloat($1);
				}
			| '-' FCONST
				{
					$$ = makeFloat($2);
					$$->val.dval = - $$->val.dval;
				}
		;

1411 1412 1413 1414 1415 1416 1417 1418 1419
IntegerOnly:  Iconst
				{
					$$ = makeInteger($1);
				}
			| '-' Iconst
				{
					$$ = makeInteger($2);
					$$->val.ival = - $$->val.ival;
				}
1420
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1421

1422 1423 1424 1425 1426 1427 1428 1429
/*****************************************************************************
 *
 *		QUERIES :
 *				CREATE PROCEDURAL LANGUAGE ...
 *				DROP PROCEDURAL LANGUAGE ...
 *
 *****************************************************************************/

1430
CreatePLangStmt:  CREATE PLangTrusted PROCEDURAL LANGUAGE Sconst 
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
			HANDLER def_name LANCOMPILER Sconst
			{
				CreatePLangStmt *n = makeNode(CreatePLangStmt);
				n->plname = $5;
				n->plhandler = $7;
				n->plcompiler = $9;
				n->pltrusted = $2;
				$$ = (Node *)n;
			}
		;

PLangTrusted:		TRUSTED { $$ = TRUE; }
			|	{ $$ = FALSE; }

1445
DropPLangStmt:  DROP PROCEDURAL LANGUAGE Sconst
1446 1447 1448 1449 1450 1451
			{
				DropPLangStmt *n = makeNode(DropPLangStmt);
				n->plname = $4;
				$$ = (Node *)n;
			}
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1452

1453 1454
/*****************************************************************************
 *
1455 1456 1457
 *		QUERIES :
 *				CREATE TRIGGER ...
 *				DROP TRIGGER ...
1458 1459 1460
 *
 *****************************************************************************/

1461
CreateTrigStmt:  CREATE TRIGGER name TriggerActionTime TriggerEvents ON
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
				relation_name TriggerForSpec EXECUTE PROCEDURE
				name '(' TriggerFuncArgs ')'
				{
					CreateTrigStmt *n = makeNode(CreateTrigStmt);
					n->trigname = $3;
					n->relname = $7;
					n->funcname = $11;
					n->args = $13;
					n->before = $4;
					n->row = $8;
					memcpy (n->actions, $5, 4);
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
					n->lang = NULL;		/* unused */
					n->text = NULL;		/* unused */
					n->attr = NULL;		/* unused */
					n->when = NULL;		/* unused */

					n->isconstraint  = false;
					n->deferrable    = false;
					n->initdeferred  = false;
					n->constrrelname = NULL;
					$$ = (Node *)n;
				}
		| CREATE CONSTRAINT TRIGGER name AFTER TriggerOneEvent ON
				relation_name OptConstrFromTable 
Jan Wieck's avatar
Jan Wieck committed
1486
				ConstraintAttributeSpec
1487 1488 1489 1490 1491
				FOR EACH ROW EXECUTE PROCEDURE name '(' TriggerFuncArgs ')'
				{
					CreateTrigStmt *n = makeNode(CreateTrigStmt);
					n->trigname = $4;
					n->relname = $8;
Jan Wieck's avatar
Jan Wieck committed
1492 1493
					n->funcname = $16;
					n->args = $18;
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
					n->before = false;
					n->row = true;
					n->actions[0] = $6;
					n->actions[1] = '\0';
					n->lang = NULL;		/* unused */
					n->text = NULL;		/* unused */
					n->attr = NULL;		/* unused */
					n->when = NULL;		/* unused */

					n->isconstraint  = true;
Jan Wieck's avatar
Jan Wieck committed
1504 1505
					n->deferrable = ($10 & 1) != 0;
					n->initdeferred = ($10 & 2) != 0;
1506 1507

					n->constrrelname = $9;
1508 1509 1510 1511
					$$ = (Node *)n;
				}
		;

1512 1513
TriggerActionTime:  BEFORE						{ $$ = TRUE; }
			| AFTER								{ $$ = FALSE; }
1514 1515 1516
		;

TriggerEvents:	TriggerOneEvent
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
				{
					char *e = palloc (4);
					e[0] = $1; e[1] = 0; $$ = e;
				}
			| TriggerOneEvent OR TriggerOneEvent
				{
					char *e = palloc (4);
					e[0] = $1; e[1] = $3; e[2] = 0; $$ = e;
				}
			| TriggerOneEvent OR TriggerOneEvent OR TriggerOneEvent
				{
					char *e = palloc (4);
					e[0] = $1; e[1] = $3; e[2] = $5; e[3] = 0;
					$$ = e;
				}
1532 1533
		;

1534 1535 1536
TriggerOneEvent:  INSERT					{ $$ = 'i'; }
			| DELETE						{ $$ = 'd'; }
			| UPDATE						{ $$ = 'u'; }
1537 1538
		;

1539
TriggerForSpec:  FOR TriggerForOpt TriggerForType
1540
				{
1541
					$$ = $3;
1542 1543
				}
		;
1544

1545 1546 1547 1548 1549 1550 1551 1552
TriggerForOpt:  EACH						{ $$ = TRUE; }
			| /*EMPTY*/						{ $$ = FALSE; }
		;

TriggerForType:  ROW						{ $$ = TRUE; }
			| STATEMENT						{ $$ = FALSE; }
		;

1553
TriggerFuncArgs:  TriggerFuncArg
1554
				{ $$ = lcons($1, NIL); }
1555
			| TriggerFuncArgs ',' TriggerFuncArg
1556
				{ $$ = lappend($1, $3); }
1557
			| /*EMPTY*/
1558
				{ $$ = NIL; }
1559 1560
		;

1561
TriggerFuncArg:  ICONST
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
				{
					char *s = (char *) palloc (256);
					sprintf (s, "%d", $1);
					$$ = s;
				}
			| FCONST
				{
					char *s = (char *) palloc (256);
					sprintf (s, "%g", $1);
					$$ = s;
				}
			| Sconst						{  $$ = $1; }
			| IDENT							{  $$ = $1; }
1575
		;
1576

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
OptConstrFromTable:			/* Empty */
				{
					$$ = "";
				}
		| FROM relation_name
				{
					$$ = $2;
				}
		;

Jan Wieck's avatar
Jan Wieck committed
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
ConstraintAttributeSpec: /* Empty */
			{ $$ = 0; }
		| ConstraintDeferrabilitySpec
			{ $$ = $1; }
		| ConstraintDeferrabilitySpec ConstraintTimeSpec
			{
				if ($1 == 0 && $2 != 0)
					elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
				$$ = $1 | $2;
			}
		| ConstraintTimeSpec
			{
				if ($1 != 0)
					$$ = 3;
				else
1602
					$$ = 0;
Jan Wieck's avatar
Jan Wieck committed
1603 1604 1605 1606 1607 1608 1609
			}
		| ConstraintTimeSpec ConstraintDeferrabilitySpec
			{
				if ($2 == 0 && $1 != 0)
					elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
				$$ = $1 | $2;
			}
1610 1611
		;

Jan Wieck's avatar
Jan Wieck committed
1612 1613 1614 1615 1616 1617 1618 1619
ConstraintDeferrabilitySpec: NOT DEFERRABLE
			{ $$ = 0; }
		| DEFERRABLE
			{ $$ = 1; }
		;

ConstraintTimeSpec: INITIALLY IMMEDIATE
			{ $$ = 0; }
1620
		| INITIALLY DEFERRED
Jan Wieck's avatar
Jan Wieck committed
1621
			{ $$ = 2; }
1622
		;
1623

1624

1625
DropTrigStmt:  DROP TRIGGER name ON relation_name
1626 1627 1628 1629 1630 1631 1632
				{
					DropTrigStmt *n = makeNode(DropTrigStmt);
					n->trigname = $3;
					n->relname = $5;
					$$ = (Node *) n;
				}
		;
1633

1634

1635 1636
/*****************************************************************************
 *
1637 1638
 *		QUERY :
 *				define (type,operator,aggregate)
1639 1640 1641 1642
 *
 *****************************************************************************/

DefineStmt:  CREATE def_type def_rest
1643 1644 1645 1646 1647
				{
					$3->defType = $2;
					$$ = (Node *)$3;
				}
		;
1648

1649
def_rest:  def_name definition
1650 1651 1652 1653 1654 1655 1656
				{
					$$ = makeNode(DefineStmt);
					$$->defname = $1;
					$$->definition = $2;
				}
		;

1657
def_type:  OPERATOR							{ $$ = OPERATOR; }
1658
		| TYPE_P							{ $$ = TYPE_P; }
1659
		| AGGREGATE							{ $$ = AGGREGATE; }
1660
		;
1661

1662
def_name:  PROCEDURE						{ $$ = "procedure"; }
1663 1664
		| JOIN								{ $$ = "join"; }
		| ColId								{ $$ = $1; }
1665
		| all_Op							{ $$ = $1; }
1666
		;
1667

1668
definition:  '(' def_list ')'				{ $$ = $2; }
1669
		;
1670

1671
def_list:  def_elem							{ $$ = lcons($1, NIL); }
1672
		| def_list ',' def_elem				{ $$ = lappend($1, $3); }
1673
		;
1674 1675

def_elem:  def_name '=' def_arg
1676 1677 1678 1679 1680
				{
					$$ = makeNode(DefElem);
					$$->defname = $1;
					$$->arg = (Node *)$3;
				}
1681
		| def_name
1682 1683 1684 1685 1686
				{
					$$ = makeNode(DefElem);
					$$->defname = $1;
					$$->arg = (Node *)NULL;
				}
1687
		| DEFAULT '=' def_arg
1688 1689
				{
					$$ = makeNode(DefElem);
1690
					$$->defname = "default";
1691 1692 1693 1694
					$$->arg = (Node *)$3;
				}
		;

1695 1696
def_arg:  ColId							{  $$ = (Node *)makeString($1); }
		| all_Op						{  $$ = (Node *)makeString($1); }
1697
		| NumericOnly					{  $$ = (Node *)$1; }
1698 1699
		| Sconst						{  $$ = (Node *)makeString($1); }
		| SETOF ColId
1700 1701 1702 1703 1704
				{
					TypeName *n = makeNode(TypeName);
					n->name = $2;
					n->setof = TRUE;
					n->arrayBounds = NULL;
1705
					n->typmod = -1;
1706 1707
					$$ = (Node *)n;
				}
1708
		;
1709 1710 1711 1712


/*****************************************************************************
 *
1713
 *		QUERY:
1714
 *				drop <relname1> [, <relname2> .. <relnameN> ]
1715 1716 1717
 *
 *****************************************************************************/

1718
DropStmt:  DROP TABLE relation_name_list
1719
				{
1720
					DropStmt *n = makeNode(DropStmt);
1721
					n->relNames = $3;
1722
					n->sequence = FALSE;
1723 1724
					$$ = (Node *)n;
				}
1725
		| DROP SEQUENCE relation_name_list
1726
				{
1727
					DropStmt *n = makeNode(DropStmt);
1728
					n->relNames = $3;
1729
					n->sequence = TRUE;
1730 1731 1732
					$$ = (Node *)n;
				}
		;
1733

1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
/*****************************************************************************
 *
 *		QUERY:
 *				truncate table relname
 *
 *****************************************************************************/

TruncateStmt:  TRUNCATE TABLE relation_name
				{
					TruncateStmt *n = makeNode(TruncateStmt);
					n->relName = $3;
					$$ = (Node *)n;
				}
			;
1748

1749 1750
/*****************************************************************************
 *
Bruce Momjian's avatar
Bruce Momjian committed
1751 1752 1753 1754 1755 1756 1757 1758
 *  The COMMENT ON statement can take different forms based upon the type of
 *  the object associated with the comment. The form of the statement is:
 *
 *  COMMENT ON [ [ DATABASE | INDEX | RULE | SEQUENCE | TABLE | TYPE | VIEW ] 
 *               <objname> | AGGREGATE <aggname> <aggtype> | FUNCTION 
 *		 <funcname> (arg1, arg2, ...) | OPERATOR <op> 
 *		 (leftoperand_typ rightoperand_typ) | TRIGGER <triggername> ON
 *		 <relname> ] IS 'text'
1759 1760 1761
 *
 *****************************************************************************/
 
1762
CommentStmt:	COMMENT ON comment_type name IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1763 1764 1765 1766 1767 1768 1769 1770 1771
			{
				CommentStmt *n = makeNode(CommentStmt);
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = NULL;
				n->objlist = NULL;
				n->comment = $6;
				$$ = (Node *) n;
			}
1772
		| COMMENT ON comment_cl relation_name '.' attr_name IS comment_text
1773 1774
			{
				CommentStmt *n = makeNode(CommentStmt);
Bruce Momjian's avatar
Bruce Momjian committed
1775 1776 1777 1778
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = $6;
				n->objlist = NULL;
1779 1780 1781
				n->comment = $8;
				$$ = (Node *) n;
			}
1782
		| COMMENT ON comment_ag name aggr_argtype IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1783
			{
1784
				CommentStmt *n = makeNode(CommentStmt);
Bruce Momjian's avatar
Bruce Momjian committed
1785 1786 1787 1788 1789 1790 1791
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = $5;
				n->objlist = NULL;
				n->comment = $7;
				$$ = (Node *) n;
			}
1792
		| COMMENT ON comment_fn func_name func_args IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1793 1794 1795 1796 1797 1798 1799 1800 1801
			{
				CommentStmt *n = makeNode(CommentStmt);
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = NULL;
				n->objlist = $5;
				n->comment = $7;
				$$ = (Node *) n;
			}
1802
		| COMMENT ON comment_op all_Op '(' oper_argtypes ')' IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1803 1804 1805 1806 1807 1808 1809
			{
				CommentStmt *n = makeNode(CommentStmt);
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = NULL;
				n->objlist = $6;
				n->comment = $9;
1810 1811
				$$ = (Node *) n;
			}
1812
		| COMMENT ON comment_tg name ON relation_name IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
			{
				CommentStmt *n = makeNode(CommentStmt);
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = $6;
				n->objlist = NULL;
				n->comment = $8;
				$$ = (Node *) n;
			}
		;

comment_type:	DATABASE { $$ = DATABASE; }
		| INDEX { $$ = INDEX; }
		| RULE { $$ = RULE; }
		| SEQUENCE { $$ = SEQUENCE; }
		| TABLE { $$ = TABLE; }
		| TYPE_P { $$ = TYPE_P; }
		| VIEW { $$ = VIEW; }
		;		

comment_cl:	COLUMN { $$ = COLUMN; }
		;

comment_ag:	AGGREGATE { $$ = AGGREGATE; }
		;

comment_fn:	FUNCTION { $$ = FUNCTION; }
		;

comment_op:	OPERATOR { $$ = OPERATOR; }
		;

comment_tg:	TRIGGER { $$ = TRIGGER; }
1846
		; 
1847

1848
comment_text:	Sconst { $$ = $1; }
1849
		| NULL_P { $$ = NULL; }
1850 1851
		;
		
1852 1853
/*****************************************************************************
 *
1854
 *		QUERY:
1855 1856 1857
 *			fetch/move [forward | backward] [ # | all ] [ in <portalname> ]
 *			fetch [ forward | backward | absolute | relative ]
 *			      [ # | all | next | prior ] [ [ in | from ] <portalname> ]
1858 1859 1860
 *
 *****************************************************************************/

1861 1862 1863
FetchStmt:	FETCH opt_direction fetch_how_many opt_portal_name
				{
					FetchStmt *n = makeNode(FetchStmt);
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
					if ($2 == RELATIVE)
					{
						if ($3 == 0)
							elog(ERROR,"FETCH/RELATIVE at current position is not supported");
						$2 = FORWARD;
					}
					if ($3 < 0)
					{
						$3 = -$3;
						$2 = (($2 == FORWARD)? BACKWARD: FORWARD);
					}
1875 1876 1877
					n->direction = $2;
					n->howMany = $3;
					n->portalname = $4;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1878 1879 1880 1881 1882 1883
					n->ismove = false;
					$$ = (Node *)n;
				}
		|	MOVE opt_direction fetch_how_many opt_portal_name
				{
					FetchStmt *n = makeNode(FetchStmt);
1884 1885 1886 1887 1888
					if ($3 < 0)
					{
						$3 = -$3;
						$2 = (($2 == FORWARD)? BACKWARD: FORWARD);
					}
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1889 1890 1891
					n->direction = $2;
					n->howMany = $3;
					n->portalname = $4;
1892
					n->ismove = TRUE;
1893 1894 1895 1896
					$$ = (Node *)n;
				}
		;

1897 1898 1899 1900 1901 1902 1903 1904 1905
opt_direction:	FORWARD					{ $$ = FORWARD; }
		| BACKWARD						{ $$ = BACKWARD; }
		| RELATIVE						{ $$ = RELATIVE; }
		| ABSOLUTE
			{
				elog(NOTICE,"FETCH/ABSOLUTE not supported, using RELATIVE");
				$$ = RELATIVE;
			}
		| /*EMPTY*/						{ $$ = FORWARD; /* default */ }
1906
		;
1907

1908 1909
fetch_how_many:  Iconst					{ $$ = $1; }
		| '-' Iconst					{ $$ = - $2; }
1910
		| ALL							{ $$ = 0; /* 0 means fetch all tuples*/ }
1911 1912
		| NEXT							{ $$ = 1; }
		| PRIOR							{ $$ = -1; }
1913
		| /*EMPTY*/						{ $$ = 1; /*default*/ }
1914
		;
1915

1916
opt_portal_name:  IN name				{ $$ = $2; }
1917
		| FROM name						{ $$ = $2; }
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1918 1919 1920
		| /*EMPTY*/						{ $$ = NULL; }
		;

1921

1922 1923
/*****************************************************************************
 *
1924 1925
 *		QUERY:
 *				GRANT [privileges] ON [relation_name_list] TO [GROUP] grantee
1926 1927 1928
 *
 *****************************************************************************/

1929
GrantStmt:  GRANT privileges ON relation_name_list TO grantee opt_with_grant
1930 1931 1932 1933
				{
					$$ = (Node*)makeAclStmt($2,$4,$6,'+');
				}
		;
1934 1935

privileges:  ALL PRIVILEGES
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
				{
				 $$ = aclmakepriv("rwaR",0);
				}
		| ALL
				{
				 $$ = aclmakepriv("rwaR",0);
				}
		| operation_commalist
				{
				 $$ = $1;
				}
		;

1949
operation_commalist:  operation
1950 1951 1952 1953 1954 1955 1956 1957 1958
				{
						$$ = aclmakepriv("",$1);
				}
		| operation_commalist ',' operation
				{
						$$ = aclmakepriv($1,$3);
				}
		;

1959
operation:  SELECT
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
				{
						$$ = ACL_MODE_RD_CHR;
				}
		| INSERT
				{
						$$ = ACL_MODE_AP_CHR;
				}
		| UPDATE
				{
						$$ = ACL_MODE_WR_CHR;
				}
		| DELETE
				{
						$$ = ACL_MODE_WR_CHR;
				}
1975
		| RULE
1976 1977 1978 1979 1980 1981 1982 1983 1984
				{
						$$ = ACL_MODE_RU_CHR;
				}
		;

grantee:  PUBLIC
				{
						$$ = aclmakeuser("A","");
				}
1985
		| GROUP ColId
1986 1987 1988
				{
						$$ = aclmakeuser("G",$2);
				}
1989
		| ColId
1990 1991 1992 1993
				{
						$$ = aclmakeuser("U",$1);
				}
		;
1994

1995
opt_with_grant:  WITH GRANT OPTION
1996 1997
				{
					yyerror("WITH GRANT OPTION is not supported.  Only relation owners can set privileges");
1998 1999
				 }
		| /*EMPTY*/
2000 2001
		;

2002

2003 2004
/*****************************************************************************
 *
2005 2006
 *		QUERY:
 *				REVOKE [privileges] ON [relation_name] FROM [user]
2007 2008 2009
 *
 *****************************************************************************/

2010
RevokeStmt:  REVOKE privileges ON relation_name_list FROM grantee
2011 2012 2013 2014
				{
					$$ = (Node*)makeAclStmt($2,$4,$6,'-');
				}
		;
2015

2016

2017 2018
/*****************************************************************************
 *
2019
 *		QUERY:
Bruce Momjian's avatar
Bruce Momjian committed
2020
 *				create index <indexname> on <relname>
2021 2022
 *				  using <access> "(" (<col> with <op>)+ ")" [with
 *				  <target_list>]
2023
 *
2024
 *	[where <qual>] is not supported anymore
2025 2026
 *****************************************************************************/

2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
IndexStmt:	CREATE index_opt_unique INDEX index_name ON relation_name
			access_method_clause '(' index_params ')' opt_with
				{
					/* should check that access_method is valid,
					   etc ... but doesn't */
					IndexStmt *n = makeNode(IndexStmt);
					n->unique = $2;
					n->idxname = $4;
					n->relname = $6;
					n->accessMethod = $7;
					n->indexParams = $9;
					n->withClause = $11;
					n->whereClause = NULL;
					$$ = (Node *)n;
				}
		;

2044 2045
index_opt_unique:  UNIQUE						{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
2046 2047
		;

2048 2049
access_method_clause:  USING access_method		{ $$ = $2; }
		| /*EMPTY*/								{ $$ = "btree"; }
2050
		;
2051

2052 2053 2054 2055 2056 2057 2058 2059
index_params:  index_list						{ $$ = $1; }
		| func_index							{ $$ = lcons($1,NIL); }
		;

index_list:  index_list ',' index_elem			{ $$ = lappend($1, $3); }
		| index_elem							{ $$ = lcons($1, NIL); }
		;

2060
func_index:  func_name '(' name_list ')' opt_type opt_class
2061 2062 2063 2064 2065
				{
					$$ = makeNode(IndexElem);
					$$->name = $1;
					$$->args = $3;
					$$->class = $6;
2066
					$$->typename = $5;
2067 2068 2069 2070 2071 2072 2073 2074 2075
				}
		  ;

index_elem:  attr_name opt_type opt_class
				{
					$$ = makeNode(IndexElem);
					$$->name = $1;
					$$->args = NIL;
					$$->class = $3;
2076
					$$->typename = $2;
2077 2078 2079
				}
		;

2080 2081 2082
opt_type:  ':' Typename							{ $$ = $2; }
		| FOR Typename							{ $$ = $2; }
		| /*EMPTY*/								{ $$ = NULL; }
2083 2084 2085 2086 2087 2088
		;

/* opt_class "WITH class" conflicts with preceeding opt_type
 *  for Typename of "TIMESTAMP WITH TIME ZONE"
 * So, remove "WITH class" from the syntax. OK??
 * - thomas 1997-10-12
2089
 *		| WITH class							{ $$ = $2; }
2090 2091
 */
opt_class:  class								{ $$ = $1; }
2092
		| USING class							{ $$ = $2; }
2093 2094 2095 2096
		| /*EMPTY*/								{ $$ = NULL; }
		;


2097 2098
/*****************************************************************************
 *
2099 2100
 *		QUERY:
 *				extend index <indexname> [where <qual>]
2101 2102 2103 2104
 *
 *****************************************************************************/

ExtendStmt:  EXTEND INDEX index_name where_clause
2105 2106 2107 2108 2109 2110 2111
				{
					ExtendStmt *n = makeNode(ExtendStmt);
					n->idxname = $3;
					n->whereClause = $4;
					$$ = (Node *)n;
				}
		;
2112 2113 2114

/*****************************************************************************
 *
2115 2116
 *		QUERY:
 *				execute recipe <recipeName>
2117 2118 2119
 *
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
2120
/* NOT USED
2121
RecipeStmt:  EXECUTE RECIPE recipe_name
2122 2123 2124
				{
					RecipeStmt *n;
					if (!IsTransactionBlock())
Bruce Momjian's avatar
Bruce Momjian committed
2125
						elog(ERROR,"EXECUTE RECIPE may only be used in begin/end transaction blocks");
2126 2127 2128 2129 2130 2131

					n = makeNode(RecipeStmt);
					n->recipeName = $3;
					$$ = (Node *)n;
				}
		;
Bruce Momjian's avatar
Bruce Momjian committed
2132
*/
2133 2134 2135

/*****************************************************************************
 *
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
 *		QUERY:
 *				define function <fname>
 *					   (language = <lang>, returntype = <typename>
 *						[, arch_pct = <percentage | pre-defined>]
 *						[, disk_pct = <percentage | pre-defined>]
 *						[, byte_pct = <percentage | pre-defined>]
 *						[, perbyte_cpu = <int | pre-defined>]
 *						[, percall_cpu = <int | pre-defined>]
 *						[, iscachable])
 *						[arg is (<type-1> { , <type-n>})]
 *						as <filename or code in language as appropriate>
2147 2148 2149
 *
 *****************************************************************************/

2150
ProcedureStmt:	CREATE FUNCTION func_name func_args
2151
			 RETURNS func_return opt_with AS func_as LANGUAGE Sconst
2152 2153 2154 2155
				{
					ProcedureStmt *n = makeNode(ProcedureStmt);
					n->funcname = $3;
					n->defArgs = $4;
2156
					n->returnType = $6;
2157 2158 2159 2160 2161 2162 2163
					n->withClause = $7;
					n->as = $9;
					n->language = $11;
					$$ = (Node *)n;
				};

opt_with:  WITH definition						{ $$ = $2; }
2164
		| /*EMPTY*/								{ $$ = NIL; }
2165 2166
		;

2167
func_args:  '(' func_args_list ')'				{ $$ = $2; }
2168
		| '(' ')'								{ $$ = NIL; }
2169
		;
2170

2171 2172 2173 2174 2175 2176
func_args_list:  TypeId
				{	$$ = lcons(makeString($1),NIL); }
		| func_args_list ',' TypeId
				{	$$ = lappend($1,makeString($3)); }
		;

2177 2178 2179 2180 2181 2182
func_as: Sconst	
				{   $$ = lcons(makeString($1),NIL); }
		| Sconst ',' Sconst
				{ 	$$ = lappend(lcons(makeString($1),NIL), makeString($3)); }
		;

2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
func_return:  set_opt TypeId
				{
					TypeName *n = makeNode(TypeName);
					n->name = $2;
					n->setof = $1;
					n->arrayBounds = NULL;
					$$ = (Node *)n;
				}
		;

set_opt:  SETOF									{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
		;
2196 2197 2198

/*****************************************************************************
 *
2199
 *		QUERY:
2200
 *
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
 *		remove function <funcname>
 *				(REMOVE FUNCTION "funcname" (arg1, arg2, ...))
 *		remove aggregate <aggname>
 *				(REMOVE AGGREGATE "aggname" "aggtype")
 *		remove operator <opname>
 *				(REMOVE OPERATOR "opname" (leftoperand_typ rightoperand_typ))
 *		remove type <typename>
 *				(REMOVE TYPE "typename")
 *		remove rule <rulename>
 *				(REMOVE RULE "rulename")
2211 2212 2213 2214
 *
 *****************************************************************************/

RemoveStmt:  DROP remove_type name
2215 2216 2217 2218 2219 2220 2221 2222
				{
					RemoveStmt *n = makeNode(RemoveStmt);
					n->removeType = $2;
					n->name = $3;
					$$ = (Node *)n;
				}
		;

2223
remove_type:  TYPE_P							{  $$ = TYPE_P; }
2224 2225 2226
		| INDEX									{  $$ = INDEX; }
		| RULE									{  $$ = RULE; }
		| VIEW									{  $$ = VIEW; }
2227
		;
2228

2229

2230
RemoveAggrStmt:  DROP AGGREGATE name aggr_argtype
2231 2232 2233 2234 2235 2236 2237 2238 2239
				{
						RemoveAggrStmt *n = makeNode(RemoveAggrStmt);
						n->aggname = $3;
						n->aggtype = $4;
						$$ = (Node *)n;
				}
		;

aggr_argtype:  name								{ $$ = $1; }
2240
		| '*'									{ $$ = NULL; }
2241
		;
2242

2243 2244

RemoveFuncStmt:  DROP FUNCTION func_name func_args
2245 2246 2247
				{
					RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
					n->funcname = $3;
2248
					n->args = $4;
2249 2250 2251 2252
					$$ = (Node *)n;
				}
		;

2253 2254

RemoveOperStmt:  DROP OPERATOR all_Op '(' oper_argtypes ')'
2255 2256 2257 2258 2259 2260 2261
				{
					RemoveOperStmt *n = makeNode(RemoveOperStmt);
					n->opname = $3;
					n->args = $5;
					$$ = (Node *)n;
				}
		;
2262

2263 2264
oper_argtypes:	name
				{
Bruce Momjian's avatar
Bruce Momjian committed
2265
				   elog(ERROR,"parser: argument type missing (use NONE for unary operators)");
2266 2267 2268 2269 2270 2271 2272 2273
				}
		| name ',' name
				{ $$ = makeList(makeString($1), makeString($3), -1); }
		| NONE ',' name			/* left unary */
				{ $$ = makeList(NULL, makeString($3), -1); }
		| name ',' NONE			/* right unary */
				{ $$ = makeList(makeString($1), NULL, -1); }
		;
2274

2275

2276 2277
/*****************************************************************************
 *
2278 2279 2280
 *		QUERY:
 *				rename <attrname1> in <relname> [*] to <attrname2>
 *				rename <relname1> to <relname2>
2281
 *
2282 2283
 *****************************************************************************/

2284
RenameStmt:  ALTER TABLE relation_name opt_inh_star
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
				  RENAME opt_column opt_name TO name
				{
					RenameStmt *n = makeNode(RenameStmt);
					n->relname = $3;
					n->inh = $4;
					n->column = $7;
					n->newname = $9;
					$$ = (Node *)n;
				}
		;

opt_name:  name							{ $$ = $1; }
2297
		| /*EMPTY*/						{ $$ = NULL; }
2298 2299 2300 2301 2302
		;

opt_column:  COLUMN						{ $$ = COLUMN; }
		| /*EMPTY*/						{ $$ = 0; }
		;
2303 2304 2305


/*****************************************************************************
2306
 *
2307 2308
 *		QUERY:	Define Rewrite Rule , Define Tuple Rule
 *				Define Rule <old rules >
2309
 *
2310
 *		only rewrite rule is supported -- ay 9/94
2311
 *
2312 2313
 *****************************************************************************/

2314
RuleStmt:  CREATE RULE name AS
2315 2316
		   { QueryIsRule=TRUE; }
		   ON event TO event_object where_clause
2317
		   DO opt_instead RuleActionList
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329
				{
					RuleStmt *n = makeNode(RuleStmt);
					n->rulename = $3;
					n->event = $7;
					n->object = $9;
					n->whereClause = $10;
					n->instead = $12;
					n->actions = $13;
					$$ = (Node *)n;
				}
		;

2330 2331 2332
RuleActionList:  NOTHING				{ $$ = NIL; }
		| SelectStmt					{ $$ = lcons($1, NIL); }
		| RuleActionStmt				{ $$ = lcons($1, NIL); }
2333 2334
		| '[' RuleActionMulti ']'		{ $$ = $2; }
		| '(' RuleActionMulti ')'		{ $$ = $2; } 
2335
		;
2336

2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
/* the thrashing around here is to discard "empty" statements... */
RuleActionMulti:  RuleActionMulti ';' RuleActionStmtOrEmpty
				{ if ($3 != (Node *)NULL)
					$$ = lappend($1, $3);
				  else
					$$ = $1;
				}
		| RuleActionStmtOrEmpty
				{ if ($1 != (Node *)NULL)
					$$ = lcons($1,NIL);
				  else
					$$ = NIL;
				}
2350
		;
2351

2352 2353 2354 2355 2356 2357
RuleActionStmt:	InsertStmt
		| UpdateStmt
		| DeleteStmt
		| NotifyStmt
		;

2358 2359 2360 2361 2362
RuleActionStmtOrEmpty:	RuleActionStmt
		|	/*EMPTY*/
				{ $$ = (Node *)NULL; }
		;

2363
event_object:  relation_name '.' attr_name
2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
					$$->paramNo = NULL;
					$$->attrs = lcons(makeString($3), NIL);
					$$->indirection = NIL;
				}
		| relation_name
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
					$$->paramNo = NULL;
					$$->attrs = NIL;
					$$->indirection = NIL;
				}
		;
2380 2381

/* change me to select, update, etc. some day */
2382 2383 2384 2385 2386
event:	SELECT							{ $$ = CMD_SELECT; }
		| UPDATE						{ $$ = CMD_UPDATE; }
		| DELETE						{ $$ = CMD_DELETE; }
		| INSERT						{ $$ = CMD_INSERT; }
		 ;
2387

2388
opt_instead:  INSTEAD					{ $$ = TRUE; }
2389
		| /*EMPTY*/						{ $$ = FALSE; }
2390
		;
2391 2392 2393 2394


/*****************************************************************************
 *
2395 2396 2397
 *		QUERY:
 *				NOTIFY <relation_name>	can appear both in rule bodies and
 *				as a query-level command
2398 2399 2400
 *
 *****************************************************************************/

2401
NotifyStmt:  NOTIFY relation_name
2402 2403 2404 2405 2406 2407
				{
					NotifyStmt *n = makeNode(NotifyStmt);
					n->relname = $2;
					$$ = (Node *)n;
				}
		;
2408

2409
ListenStmt:  LISTEN relation_name
2410 2411 2412 2413 2414
				{
					ListenStmt *n = makeNode(ListenStmt);
					n->relname = $2;
					$$ = (Node *)n;
				}
2415 2416
;

2417 2418 2419 2420 2421 2422
UnlistenStmt:  UNLISTEN relation_name
				{
					UnlistenStmt *n = makeNode(UnlistenStmt);
					n->relname = $2;
					$$ = (Node *)n;
				}
2423 2424 2425 2426 2427 2428
		| UNLISTEN '*'
				{
					UnlistenStmt *n = makeNode(UnlistenStmt);
					n->relname = "*";
					$$ = (Node *)n;
				}
2429 2430
;

2431 2432 2433

/*****************************************************************************
 *
2434
 *		Transactions:
2435
 *
2436 2437 2438 2439 2440 2441
 *		abort transaction
 *				(ABORT)
 *		begin transaction
 *				(BEGIN)
 *		end transaction
 *				(END)
2442
 *
2443 2444
 *****************************************************************************/

2445
TransactionStmt: ABORT_TRANS opt_trans
2446 2447 2448 2449 2450
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = ABORT_TRANS;
					$$ = (Node *)n;
				}
2451
		| BEGIN_TRANS opt_trans
2452 2453 2454 2455 2456
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = BEGIN_TRANS;
					$$ = (Node *)n;
				}
2457
		| COMMIT opt_trans
2458 2459 2460 2461 2462
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = END_TRANS;
					$$ = (Node *)n;
				}
2463
		| END_TRANS opt_trans
2464 2465 2466 2467 2468
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = END_TRANS;
					$$ = (Node *)n;
				}
2469
		| ROLLBACK opt_trans
2470 2471 2472 2473 2474
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = ABORT_TRANS;
					$$ = (Node *)n;
				}
2475
		;
2476

2477 2478 2479
opt_trans: WORK									{ $$ = TRUE; }
		| TRANSACTION							{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = TRUE; }
2480
		;
2481 2482 2483 2484


/*****************************************************************************
 *
2485 2486
 *		QUERY:
 *				define view <viewname> '('target-list ')' [where <quals> ]
2487 2488 2489
 *
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
2490
ViewStmt:  CREATE VIEW name AS SelectStmt
2491 2492 2493 2494
				{
					ViewStmt *n = makeNode(ViewStmt);
					n->viewname = $3;
					n->query = (Query *)$5;
Bruce Momjian's avatar
Bruce Momjian committed
2495 2496
					if (((SelectStmt *)n->query)->sortClause != NULL)
						elog(ERROR,"Order by and Distinct on views is not implemented.");
Bruce Momjian's avatar
Bruce Momjian committed
2497
					if (((SelectStmt *)n->query)->unionClause != NULL)
Bruce Momjian's avatar
Bruce Momjian committed
2498
						elog(ERROR,"Views on unions not implemented.");
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2499 2500
					if (((SelectStmt *)n->query)->forUpdate != NULL)
						elog(ERROR, "SELECT FOR UPDATE is not allowed in CREATE VIEW");
2501 2502 2503
					$$ = (Node *)n;
				}
		;
2504 2505 2506 2507


/*****************************************************************************
 *
2508 2509
 *		QUERY:
 *				load "filename"
2510 2511 2512
 *
 *****************************************************************************/

2513
LoadStmt:  LOAD file_name
2514 2515 2516 2517 2518 2519
				{
					LoadStmt *n = makeNode(LoadStmt);
					n->filename = $2;
					$$ = (Node *)n;
				}
		;
2520 2521 2522 2523


/*****************************************************************************
 *
2524 2525
 *		CREATE DATABASE
 *
2526 2527 2528
 *
 *****************************************************************************/

2529 2530 2531 2532 2533 2534 2535 2536
CreatedbStmt:  CREATE DATABASE database_name WITH createdb_opt_location createdb_opt_encoding
               {
                   CreatedbStmt *n;

                   if ($5 == NULL && $6 == -1)
                       elog(ERROR, "CREATE DATABASE WITH requires at least one option.");

                    n = makeNode(CreatedbStmt);
2537
					n->dbname = $3;
2538
					n->dbpath = $5;
Marc G. Fournier's avatar
Marc G. Fournier committed
2539
#ifdef MULTIBYTE
2540
                    n->encoding = $6;
2541
#else
2542
					n->encoding = 0;
2543
#endif
2544 2545
					$$ = (Node *)n;
				}
2546 2547 2548 2549 2550
		| CREATE DATABASE database_name
				{
					CreatedbStmt *n = makeNode(CreatedbStmt);
					n->dbname = $3;
					n->dbpath = NULL;
Marc G. Fournier's avatar
Marc G. Fournier committed
2551
#ifdef MULTIBYTE
2552
					n->encoding = GetTemplateEncoding();
2553 2554
#else
					n->encoding = 0;
2555 2556 2557 2558 2559
#endif
					$$ = (Node *)n;
				}
		;

2560 2561
createdb_opt_location:  LOCATION '=' Sconst		{ $$ = $3; }
        | LOCATION '=' DEFAULT                  { $$ = NULL; }
2562 2563 2564
		| /*EMPTY*/								{ $$ = NULL; }
		;

2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
createdb_opt_encoding:
        ENCODING '=' Sconst
        {
#ifdef MULTIBYTE
            int i;
            i = pg_char_to_encoding($3);
            if (i == -1)
                elog(ERROR, "%s is not a valid encoding name.", $3);
            $$ = i;
#else
            elog(ERROR, "WITH ENCODING is not supported.");
#endif
        }
        | ENCODING '=' Iconst
        {
#ifdef MULTIBYTE
            if (!pg_get_encent_by_encoding($3))
                elog(ERROR, "%d is not a valid encoding code.", $3);
            $$ = $3;
#else
            elog(ERROR, "WITH ENCODING is not supported.");
#endif
        }
        | ENCODING '=' DEFAULT
        {
#ifdef MULTIBYTE
            $$ = GetTemplateEncoding();
#else
            $$ = -1;
#endif
        }
        | /*EMPTY*/
        {
#ifdef MULTIBYTE
            $$ = GetTemplateEncoding();
#else
            $$= -1;
#endif
        }
        ;
2605

2606

2607 2608
/*****************************************************************************
 *
2609 2610
 *		DROP DATABASE
 *
2611 2612 2613
 *
 *****************************************************************************/

2614
DropdbStmt:	DROP DATABASE database_name
2615
				{
2616
					DropdbStmt *n = makeNode(DropdbStmt);
2617 2618 2619 2620
					n->dbname = $3;
					$$ = (Node *)n;
				}
		;
2621 2622 2623 2624


/*****************************************************************************
 *
2625 2626
 *		QUERY:
 *				cluster <index_name> on <relation_name>
2627 2628 2629
 *
 *****************************************************************************/

2630
ClusterStmt:  CLUSTER index_name ON relation_name
2631 2632 2633 2634 2635 2636 2637
				{
				   ClusterStmt *n = makeNode(ClusterStmt);
				   n->relname = $4;
				   n->indexname = $2;
				   $$ = (Node*)n;
				}
		;
2638 2639 2640

/*****************************************************************************
 *
2641 2642
 *		QUERY:
 *				vacuum
2643 2644 2645
 *
 *****************************************************************************/

Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2646
VacuumStmt:  VACUUM opt_verbose opt_analyze
2647 2648 2649 2650 2651 2652 2653 2654
				{
					VacuumStmt *n = makeNode(VacuumStmt);
					n->verbose = $2;
					n->analyze = $3;
					n->vacrel = NULL;
					n->va_spec = NIL;
					$$ = (Node *)n;
				}
2655
		| VACUUM opt_verbose opt_analyze relation_name opt_va_list
2656 2657 2658
				{
					VacuumStmt *n = makeNode(VacuumStmt);
					n->verbose = $2;
2659 2660
					n->analyze = $3;
					n->vacrel = $4;
2661 2662
					n->va_spec = $5;
					if ( $5 != NIL && !$4 )
Bruce Momjian's avatar
Bruce Momjian committed
2663
						elog(ERROR,"parser: syntax error at or near \"(\"");
2664 2665 2666 2667
					$$ = (Node *)n;
				}
		;

2668
opt_verbose:  VERBOSE							{ $$ = TRUE; }
2669
		| /*EMPTY*/								{ $$ = FALSE; }
2670 2671
		;

2672
opt_analyze:  ANALYZE							{ $$ = TRUE; }
2673
		| /*EMPTY*/								{ $$ = FALSE; }
2674
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2675

2676 2677
opt_va_list:  '(' va_list ')'					{ $$ = $2; }
		| /*EMPTY*/								{ $$ = NIL; }
2678
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2679

2680
va_list:  name
2681 2682 2683 2684
				{ $$=lcons($1,NIL); }
		| va_list ',' name
				{ $$=lappend($1,$3); }
		;
2685

2686

2687 2688
/*****************************************************************************
 *
2689 2690
 *		QUERY:
 *				EXPLAIN query
2691 2692 2693
 *
 *****************************************************************************/

2694
ExplainStmt:  EXPLAIN opt_verbose OptimizableStmt
2695 2696 2697 2698 2699 2700 2701
				{
					ExplainStmt *n = makeNode(ExplainStmt);
					n->verbose = $2;
					n->query = (Query*)$3;
					$$ = (Node *)n;
				}
		;
2702

2703

2704
/*****************************************************************************
2705 2706 2707 2708 2709 2710 2711 2712
 *																			 *
 *		Optimizable Stmts:													 *
 *																			 *
 *		one of the five queries processed by the planner					 *
 *																			 *
 *		[ultimately] produces query-trees as specified						 *
 *		in the query-spec document in ~postgres/ref							 *
 *																			 *
2713 2714
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
2715
OptimizableStmt:  SelectStmt
2716
		| CursorStmt
Bruce Momjian's avatar
Bruce Momjian committed
2717 2718
		| UpdateStmt
		| InsertStmt
2719 2720 2721
		| NotifyStmt
		| DeleteStmt					/* by default all are $$=$1 */
		;
2722 2723 2724 2725


/*****************************************************************************
 *
2726 2727
 *		QUERY:
 *				INSERT STATEMENTS
2728
 *
2729 2730
 *****************************************************************************/

Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2731
/* This rule used 'opt_column_list' between 'relation_name' and 'insert_rest'
2732 2733 2734 2735 2736 2737
 * originally. When the second rule of 'insert_rest' was changed to use the
 * new 'SelectStmt' rule (for INTERSECT and EXCEPT) it produced a shift/reduce
 * conflict. So I just changed the rules 'InsertStmt' and 'insert_rest' to
 * accept the same statements without any shift/reduce conflicts
 */
InsertStmt:  INSERT INTO relation_name insert_rest
2738
				{
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2739
 					$4->relname = $3;
2740
					$$ = (Node *) $4;
2741 2742
				}
		;
2743

2744
insert_rest:  VALUES '(' target_list ')'
2745
				{
Bruce Momjian's avatar
Bruce Momjian committed
2746
					$$ = makeNode(InsertStmt);
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2747
					$$->cols = NULL;
2748
					$$->unique = NULL;
2749 2750
					$$->targetList = $3;
					$$->fromClause = NIL;
2751
					$$->whereClause = NULL;
2752
					$$->groupClause = NIL;
2753
					$$->havingClause = NULL;
2754
					$$->unionClause = NIL;
2755
				}
2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
		| DEFAULT VALUES
				{
					$$ = makeNode(InsertStmt);
					$$->unique = NULL;
					$$->targetList = NIL;
					$$->fromClause = NIL;
					$$->whereClause = NULL;
					$$->groupClause = NIL;
					$$->havingClause = NULL;
					$$->unionClause = NIL;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2766
				 	$$->intersectClause = NIL;
2767
				}
2768 2769 2770
/* We want the full power of SelectStatements including INTERSECT and EXCEPT
 * for insertion.  However, we can't support sort or limit clauses.
 */
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2771
		| SelectStmt
2772
				{
2773 2774 2775
					SelectStmt *n = (SelectStmt *) $1;
					if (n->sortClause)
						elog(ERROR, "INSERT ... SELECT can't have ORDER BY");
Bruce Momjian's avatar
Bruce Momjian committed
2776
					$$ = makeNode(InsertStmt);
2777
					$$->cols = NIL;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2778 2779 2780 2781 2782 2783 2784 2785
					$$->unique = n->unique;
					$$->targetList = n->targetList;
					$$->fromClause = n->fromClause;
					$$->whereClause = n->whereClause;
					$$->groupClause = n->groupClause;
					$$->havingClause = n->havingClause;
					$$->unionClause = n->unionClause;
					$$->intersectClause = n->intersectClause;
2786
					$$->unionall = n->unionall;
2787
					$$->forUpdate = n->forUpdate;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2788
				}
2789
		| '(' columnList ')' VALUES '(' target_list ')'
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
				{
					$$ = makeNode(InsertStmt);
					$$->cols = $2;
					$$->unique = NULL;
					$$->targetList = $6;
					$$->fromClause = NIL;
					$$->whereClause = NULL;
					$$->groupClause = NIL;
					$$->havingClause = NULL;
					$$->unionClause = NIL; 
				 	$$->intersectClause = NIL;
				}
		| '(' columnList ')' SelectStmt
				{
2804 2805 2806
					SelectStmt *n = (SelectStmt *) $4;
					if (n->sortClause)
						elog(ERROR, "INSERT ... SELECT can't have ORDER BY");
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
					$$ = makeNode(InsertStmt);
					$$->cols = $2;
					$$->unique = n->unique;
					$$->targetList = n->targetList;
					$$->fromClause = n->fromClause;
					$$->whereClause = n->whereClause;
					$$->groupClause = n->groupClause;
					$$->havingClause = n->havingClause;
					$$->unionClause = n->unionClause;
					$$->intersectClause = n->intersectClause;
2817 2818
					$$->unionall = n->unionall;
					$$->forUpdate = n->forUpdate;
2819 2820 2821
				}
		;

2822
opt_column_list:  '(' columnList ')'			{ $$ = $2; }
2823 2824
		| /*EMPTY*/								{ $$ = NIL; }
		;
2825

2826
columnList:
2827 2828 2829 2830 2831
		  columnList ',' columnElem
				{ $$ = lappend($1, $3); }
		| columnElem
				{ $$ = lcons($1, NIL); }
		;
2832

2833
columnElem:  ColId opt_indirection
2834 2835 2836 2837 2838 2839 2840
				{
					Ident *id = makeNode(Ident);
					id->name = $1;
					id->indirection = $2;
					$$ = (Node *)id;
				}
		;
2841

2842

2843 2844
/*****************************************************************************
 *
2845 2846
 *		QUERY:
 *				DELETE STATEMENTS
2847 2848
 *
 *****************************************************************************/
2849

2850
DeleteStmt:  DELETE FROM relation_name
2851 2852 2853 2854 2855 2856 2857 2858
			 where_clause
				{
					DeleteStmt *n = makeNode(DeleteStmt);
					n->relname = $3;
					n->whereClause = $4;
					$$ = (Node *)n;
				}
		;
2859

Bruce Momjian's avatar
Bruce Momjian committed
2860
LockStmt:	LOCK_P opt_table relation_name opt_lock
2861
				{
2862 2863 2864
					LockStmt *n = makeNode(LockStmt);

					n->relname = $3;
Bruce Momjian's avatar
Bruce Momjian committed
2865
					n->mode = $4;
2866 2867
					$$ = (Node *)n;
				}
2868
		;
2869

Bruce Momjian's avatar
Bruce Momjian committed
2870
opt_lock:  IN lock_type MODE		{ $$ = $2; }
2871 2872
		| /*EMPTY*/				{ $$ = AccessExclusiveLock; }
		;
2873

2874 2875 2876 2877
lock_type:  SHARE ROW EXCLUSIVE	{ $$ = ShareRowExclusiveLock; }
		| ROW opt_lmode			{ $$ = ($2? RowShareLock: RowExclusiveLock); }
		| ACCESS opt_lmode		{ $$ = ($2? AccessShareLock: AccessExclusiveLock); }
		| opt_lmode				{ $$ = ($1? ShareLock: ExclusiveLock); }
2878 2879
		;

2880 2881
opt_lmode:	SHARE				{ $$ = TRUE; }
		| EXCLUSIVE				{ $$ = FALSE; }
2882
		;
2883

2884

2885 2886
/*****************************************************************************
 *
2887
 *		QUERY:
Bruce Momjian's avatar
Bruce Momjian committed
2888
 *				UpdateStmt (UPDATE)
2889 2890 2891
 *
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
2892
UpdateStmt:  UPDATE relation_name
2893
			  SET update_target_list
2894 2895 2896
			  from_clause
			  where_clause
				{
Bruce Momjian's avatar
Bruce Momjian committed
2897
					UpdateStmt *n = makeNode(UpdateStmt);
2898 2899 2900 2901 2902 2903 2904
					n->relname = $2;
					n->targetList = $4;
					n->fromClause = $5;
					n->whereClause = $6;
					$$ = (Node *)n;
				}
		;
2905

2906 2907 2908

/*****************************************************************************
 *
2909 2910
 *		QUERY:
 *				CURSOR STATEMENTS
2911 2912
 *
 *****************************************************************************/
Jan Wieck's avatar
Jan Wieck committed
2913
CursorStmt:  DECLARE name opt_cursor CURSOR FOR SelectStmt
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2914 2915 2916 2917 2918 2919 2920
  				{
 					SelectStmt *n;
  
 					n= (SelectStmt *)$6;
  					/* from PORTAL name */
  					/*
  					 *	15 august 1991 -- since 3.0 postgres does locking
2921 2922 2923 2924 2925 2926
					 *	right, we discovered that portals were violating
					 *	locking protocol.  portal locks cannot span xacts.
					 *	as a short-term fix, we installed the check here.
					 *							-- mao
					 */
					if (!IsTransactionBlock())
Bruce Momjian's avatar
Bruce Momjian committed
2927
						elog(ERROR,"Named portals may only be used in begin/end transaction blocks");
2928 2929 2930

					n->portalname = $2;
					n->binary = $3;
Jan Wieck's avatar
Jan Wieck committed
2931 2932 2933
					if (n->forUpdate != NULL)
							elog(ERROR,"DECLARE/UPDATE not supported;"
								 		" Cursors must be READ ONLY.");
2934 2935 2936
					$$ = (Node *)n;
				}
		;
2937

2938 2939 2940 2941 2942 2943 2944
opt_cursor:  BINARY						{ $$ = TRUE; }
		| INSENSITIVE					{ $$ = FALSE; }
		| SCROLL						{ $$ = FALSE; }
		| INSENSITIVE SCROLL			{ $$ = FALSE; }
		| /*EMPTY*/						{ $$ = FALSE; }
		;

2945 2946
/*****************************************************************************
 *
2947 2948
 *		QUERY:
 *				SELECT STATEMENTS
2949 2950
 *
 *****************************************************************************/
2951 2952 2953

/* A complete SELECT statement looks like this.  Note sort, for_update,
 * and limit clauses can only appear once, not in each subselect.
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2954 2955
 * 
 * The rule returns a SelectStmt Node having the set operations attached to 
2956 2957 2958 2959
 * unionClause and intersectClause (NIL if no set operations were present)
 */

SelectStmt:	  select_clause sort_clause for_update_clause opt_select_limit
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2960 2961 2962
			{
				if IsA($1, SelectStmt)
				{
2963 2964 2965 2966 2967 2968 2969 2970 2971
					/* There were no set operations, so just attach the
					 * one-time clauses.
					 */
					SelectStmt *n = (SelectStmt *) $1;
					n->sortClause = $2;
					n->forUpdate = $3;
					n->limitOffset = nth(0, $4);
					n->limitCount = nth(1, $4);
					$$ = (Node *) n;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2972 2973 2974
                }
				else
				{
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
					/* There were set operations.  The root of the operator
					 * tree is delivered by $1, but we must hand back a
					 * SelectStmt node not an A_Expr Node.
					 * So we find the leftmost 'SelectStmt' in the operator
					 * tree $1 (which is the first Select Statement in the
					 * query), which will be the returned node.
					 * Then we attach the whole operator tree to that node's
					 * 'intersectClause', and a list of all 'SelectStmt' Nodes
					 * in the tree to its 'unionClause'. (NOTE that this means
					 * the top node has indirect recursive pointers to itself!
					 * This would cause trouble if we tried copyObject!!)
					 * The intersectClause and unionClause subtrees will be
					 * left untouched by the main parser, and will only be
					 * processed when control gets to the function
					 * Except_Intersect_Rewrite() (in rewriteHandler.c).
					 */
					Node *op = (Node *) $1;
					List *select_list = NIL;
					SelectStmt *first_select;
					bool	intersect_present = false,
							unionall_present = false;

					/* Take the operator tree as an argument and create a
					 * list of all SelectStmt Nodes found in the tree.
					 *
					 * If one of the SelectStmt Nodes has the 'unionall' flag
					 * set to true the 'unionall_present' flag is also set to
					 * true.
					 */
					create_select_list(op, &select_list, &unionall_present);

					/* Replace all the A_Expr Nodes in the operator tree by
					 * Expr Nodes.
					 *
					 * If an INTERSECT or an EXCEPT is present, the 
					 * 'intersect_present' flag is set to true
					 */
					op = A_Expr_to_Expr(op, &intersect_present);
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3013

3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
					/* If both flags are set to true we have a UNION ALL
					 * statement mixed up with INTERSECT or EXCEPT 
					 * which can not be handled at the moment.
					 */
					if (intersect_present && unionall_present)
						elog(ERROR, "UNION ALL not allowed in mixed set operations");

					/* Get the leftmost SeletStmt Node (which automatically
					 * represents the first Select Statement of the query!)
					 */
					first_select = (SelectStmt *) lfirst(select_list);
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3025

3026 3027
					/* Attach the list of all SeletStmt Nodes to unionClause */
					first_select->unionClause = select_list;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3028

3029 3030
					/* Attach the whole operator tree to intersectClause */
					first_select->intersectClause = (List *) op;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3031

3032 3033 3034 3035 3036 3037
					/* finally attach the sort clause &etc */
					first_select->sortClause = $2;
					first_select->forUpdate = $3;
					first_select->limitOffset = nth(0, $4);
					first_select->limitCount = nth(1, $4);
					$$ = (Node *) first_select;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3038
				}		
3039 3040
				if (((SelectStmt *)$$)->forUpdate != NULL && QueryIsRule)
					elog(ERROR, "SELECT FOR UPDATE is not allowed in RULES");
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3041 3042 3043
			}
		;

3044 3045 3046
/* This rule parses Select statements that can appear within set operations,
 * including UNION, INTERSECT and EXCEPT.  '(' and ')' can be used to specify
 * the ordering of the set operations.  Without '(' and ')' we want the
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3047 3048
 * operations to be left associative.
 *
3049 3050 3051
 * Note that sort clauses cannot be included at this level --- a sort clause
 * can only appear at the end of the complete Select, and it will be handled
 * by the topmost SelectStmt rule.  Likewise FOR UPDATE and LIMIT.
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3052 3053
 * 
 * The rule builds up an operator tree using A_Expr Nodes. AND Nodes represent
3054
 * INTERSECTs, OR Nodes represent UNIONs, and AND NOT nodes represent EXCEPTs. 
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3055 3056
 * The SelectStatements to be connected are the left and right arguments to
 * the A_Expr Nodes.
3057 3058 3059
 * If no set operations appear in the query, the tree consists only of one
 * SelectStmt Node.
 */
3060
select_clause: '(' select_clause ')'
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3061 3062 3063 3064 3065 3066 3067
			{
				$$ = $2; 
			}
		| SubSelect
			{
				$$ = $1; 
			}
3068
		| select_clause EXCEPT select_clause
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3069 3070 3071 3072
			{
				$$ = (Node *)makeA_Expr(AND,NULL,$1,
							makeA_Expr(NOT,NULL,NULL,$3));
			}
3073
		| select_clause UNION opt_all select_clause
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3074 3075 3076 3077 3078
			{	
				if (IsA($4, SelectStmt))
				  {
				     SelectStmt *n = (SelectStmt *)$4;
				     n->unionall = $3;
3079 3080 3081 3082 3083 3084
					 /* NOTE: if UNION ALL appears with a parenthesized set
					  * operation to its right, the ALL is silently discarded.
					  * Should we generate an error instead?  I think it may
					  * be OK since ALL with UNION to its right is ignored
					  * anyway...
					  */
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3085 3086 3087
				  }
				$$ = (Node *)makeA_Expr(OR,NULL,$1,$4);
			}
3088
		| select_clause INTERSECT select_clause
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3089 3090 3091 3092
			{
				$$ = (Node *)makeA_Expr(AND,NULL,$1,$3);
			}
		; 
3093

3094
SubSelect:	SELECT opt_unique target_list
3095 3096
			 result from_clause where_clause
			 group_clause having_clause
3097
				{
Bruce Momjian's avatar
Bruce Momjian committed
3098
					SelectStmt *n = makeNode(SelectStmt);
3099
					n->unique = $2;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3100
					n->unionall = FALSE;
3101
					n->targetList = $3;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3102 3103 3104 3105 3106 3107 3108
					/* This is new: Subselects support the INTO clause
					 * which allows queries that are not part of the
					 * SQL92 standard and should not be formulated!
					 * We need it for INTERSECT and EXCEPT and I did not
					 * want to create a new rule 'SubSelect1' including the
					 * feature. If it makes troubles we will have to add 
					 * a new rule and change this to prevent INTOs in 
3109 3110
					 * Subselects again.
					 */
3111 3112
					n->istemp = (bool) ((Value *) lfirst($4))->val.ival;
					n->into = (char *) lnext($4);
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3113

3114 3115 3116 3117 3118 3119 3120
					n->fromClause = $5;
					n->whereClause = $6;
					n->groupClause = $7;
					n->havingClause = $8;
					$$ = (Node *)n;
				}
		;
3121

3122 3123 3124
		/* easy way to return two values. Can someone improve this?  bjm */
result:  INTO OptTemp opt_table relation_name	{ $$ = lcons(makeInteger($2), (List *)$4); }
		| /*EMPTY*/								{ $$ = lcons(makeInteger(false), NIL); }
3125 3126 3127 3128
		;

opt_table:  TABLE								{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
3129
		;
3130

3131
opt_all:  ALL									{ $$ = TRUE; }
3132 3133 3134
		| /*EMPTY*/								{ $$ = FALSE; }
		;

3135 3136
opt_unique:  DISTINCT							{ $$ = "*"; }
		| DISTINCT ON ColId						{ $$ = $3; }
3137 3138
		| ALL									{ $$ = NULL; }
		| /*EMPTY*/								{ $$ = NULL; }
3139
		;
3140

3141
sort_clause:  ORDER BY sortby_list				{ $$ = $3; }
3142
		| /*EMPTY*/								{ $$ = NIL; }
3143
		;
3144

3145 3146
sortby_list:  sortby							{ $$ = lcons($1, NIL); }
		| sortby_list ',' sortby				{ $$ = lappend($1, $3); }
3147
		;
3148

3149
sortby: a_expr OptUseOp
3150 3151
				{
					$$ = makeNode(SortGroupBy);
3152
					$$->node = $1;
3153 3154 3155 3156
					$$->useOp = $2;
				}
		;

3157
OptUseOp:  USING all_Op							{ $$ = $2; }
3158 3159 3160
		| ASC									{ $$ = "<"; }
		| DESC									{ $$ = ">"; }
		| /*EMPTY*/								{ $$ = "<"; /*default*/ }
3161
		;
3162

3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240

opt_select_limit:	LIMIT select_limit_value ',' select_offset_value
			{ $$ = lappend(lappend(NIL, $4), $2); }
		| LIMIT select_limit_value OFFSET select_offset_value
			{ $$ = lappend(lappend(NIL, $4), $2); }
		| LIMIT select_limit_value
			{ $$ = lappend(lappend(NIL, NULL), $2); }
		| OFFSET select_offset_value LIMIT select_limit_value
			{ $$ = lappend(lappend(NIL, $2), $4); }
		| OFFSET select_offset_value
			{ $$ = lappend(lappend(NIL, $2), NULL); }
		| /* EMPTY */
			{ $$ = lappend(lappend(NIL, NULL), NULL); }
		;

select_limit_value:		Iconst
			{
				Const	*n = makeNode(Const);

				if ($1 < 1)
					elog(ERROR, "selection limit must be ALL or a positive integer value > 0");

				n->consttype	= INT4OID;
				n->constlen		= sizeof(int4);
				n->constvalue	= (Datum)$1;
				n->constisnull	= FALSE;
				n->constbyval	= TRUE;
				n->constisset	= FALSE;
				n->constiscast	= FALSE;
				$$ = (Node *)n;
			}
		| ALL
			{
				Const	*n = makeNode(Const);

				n->consttype	= INT4OID;
				n->constlen		= sizeof(int4);
				n->constvalue	= (Datum)0;
				n->constisnull	= FALSE;
				n->constbyval	= TRUE;
				n->constisset	= FALSE;
				n->constiscast	= FALSE;
				$$ = (Node *)n;
			}
		| PARAM
			{
				Param	*n = makeNode(Param);

				n->paramkind	= PARAM_NUM;
				n->paramid		= $1;
				n->paramtype	= INT4OID;
				$$ = (Node *)n;
			}
		;

select_offset_value:	Iconst
			{
				Const	*n = makeNode(Const);

				n->consttype	= INT4OID;
				n->constlen		= sizeof(int4);
				n->constvalue	= (Datum)$1;
				n->constisnull	= FALSE;
				n->constbyval	= TRUE;
				n->constisset	= FALSE;
				n->constiscast	= FALSE;
				$$ = (Node *)n;
			}
		| PARAM
			{
				Param	*n = makeNode(Param);

				n->paramkind	= PARAM_NUM;
				n->paramid		= $1;
				n->paramtype	= INT4OID;
				$$ = (Node *)n;
			}
		;
3241
/*
3242 3243
 *	jimmy bell-style recursive queries aren't supported in the
 *	current system.
3244
 *
3245 3246
 *	...however, recursive addattr and rename supported.  make special
 *	cases for these.
3247
 */
3248 3249
opt_inh_star:  '*'								{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
3250
		;
3251

3252
relation_name_list:  name_list;
3253

3254
name_list:  name
3255
				{	$$ = lcons(makeString($1),NIL); }
3256
		| name_list ',' name
3257
				{	$$ = lappend($1,makeString($3)); }
3258
		;
3259

3260
group_clause:  GROUP BY expr_list				{ $$ = $3; }
3261 3262
		| /*EMPTY*/								{ $$ = NIL; }
		;
3263

Bruce Momjian's avatar
Bruce Momjian committed
3264 3265
having_clause:  HAVING a_expr
				{
3266
					$$ = $2;
Bruce Momjian's avatar
Bruce Momjian committed
3267
				}
3268 3269
		| /*EMPTY*/								{ $$ = NULL; }
		;
3270

3271
for_update_clause:  FOR UPDATE update_list		{ $$ = $3; }
Jan Wieck's avatar
Jan Wieck committed
3272
		| FOR READ ONLY							{ $$ = NULL; }
3273 3274 3275 3276 3277
		| /* EMPTY */							{ $$ = NULL; }
		;

update_list:  OF va_list						{ $$ = $2; }
		| /* EMPTY */							{ $$ = lcons(NULL, NULL); }
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
3278
		;
3279

3280
/*****************************************************************************
3281
 *
3282 3283 3284
 *	clauses common to all Optimizable Stmts:
 *		from_clause		-
 *		where_clause	-
3285
 *
3286 3287
 *****************************************************************************/

3288
from_clause:  FROM from_expr					{ $$ = $2; }
3289 3290 3291
		| /*EMPTY*/								{ $$ = NIL; }
		;

3292 3293 3294 3295 3296 3297 3298 3299 3300
from_expr:  '(' join_clause_with_union ')'
				{ $$ = $2; }
		| join_clause
				{ $$ = $1; }
		| table_list
				{ $$ = $1; }
		;

table_list:  table_list ',' table_expr
3301
				{ $$ = lappend($1, $3); }
3302
		| table_expr
3303 3304
				{ $$ = lcons($1, NIL); }
		;
3305

3306
table_expr:  relation_expr AS ColLabel
3307 3308 3309 3310 3311
				{
					$$ = makeNode(RangeVar);
					$$->relExpr = $1;
					$$->name = $3;
				}
3312
		| relation_expr ColId
3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
				{
					$$ = makeNode(RangeVar);
					$$->relExpr = $1;
					$$->name = $2;
				}
		| relation_expr
				{
					$$ = makeNode(RangeVar);
					$$->relExpr = $1;
					$$->name = NULL;
				}
		;
3325

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
/* A UNION JOIN is the same as a FULL OUTER JOIN which *omits*
 * all result rows which would have matched on an INNER JOIN.
 * Let's reject this for now. - thomas 1999-01-08
 */
join_clause_with_union:  join_clause
				{	$$ = $1; }
		| table_expr UNION JOIN table_expr
				{	elog(ERROR,"UNION JOIN not yet implemented"); }
		;

join_clause:  table_expr join_list
				{
					Node *n = lfirst($2);

					/* JoinExpr came back? then it is a join of some sort...
					 */
					if (IsA(n, JoinExpr))
					{
						JoinExpr *j = (JoinExpr *)n;
						j->larg = $1;
						$$ = $2;
					}
					/* otherwise, it was a cross join,
					 * which we just represent as an inner join...
					 */
					else
						$$ = lcons($1, $2);
				}
		;

join_list:  join_list join_expr
				{
					$$ = lappend($1, $2);
				}
		| join_expr
				{
					$$ = lcons($1, NIL);
				}
		;

/* This is everything but the left side of a join.
 * Note that a CROSS JOIN is the same as an unqualified
 * inner join, so just pass back the right-side table.
 * A NATURAL JOIN implicitly matches column names between
 * tables, so we'll collect those during the later transformation.
 */
join_expr:  join_type JOIN table_expr join_qual
				{
					JoinExpr *n = makeNode(JoinExpr);
					n->jointype = $1;
					n->rarg = (Node *)$3;
					n->quals = $4;
					$$ = (Node *)n;
				}
		| NATURAL join_type JOIN table_expr
				{
					JoinExpr *n = makeNode(JoinExpr);
					n->jointype = $2;
					n->rarg = (Node *)$4;
					n->quals = NULL; /* figure out which columns later... */
					$$ = (Node *)n;
				}
		| CROSS JOIN table_expr
				{ $$ = (Node *)$3; }
		;

/* OUTER is just noise... */
join_type:  FULL join_outer
				{
					$$ = FULL;
					elog(NOTICE,"FULL OUTER JOIN not yet implemented");
				}
3398
		| LEFT join_outer
3399 3400 3401 3402
				{
					$$ = LEFT;
					elog(NOTICE,"LEFT OUTER JOIN not yet implemented");
				}
3403
		| RIGHT join_outer
3404 3405 3406 3407
				{
					$$ = RIGHT;
					elog(NOTICE,"RIGHT OUTER JOIN not yet implemented");
				}
3408
		| OUTER_P
3409 3410 3411 3412
				{
					$$ = LEFT;
					elog(NOTICE,"OUTER JOIN not yet implemented");
				}
3413
		| INNER_P
3414 3415 3416
				{
					$$ = INNER_P;
				}
3417
		| /*EMPTY*/
3418 3419 3420
				{
					$$ = INNER_P;
				}
3421 3422
		;

3423 3424
join_outer:  OUTER_P							{ $$ = NULL; }
		| /*EMPTY*/								{ $$ = NULL;  /* no qualifiers */ }
3425 3426
		;

3427 3428 3429 3430 3431 3432 3433 3434 3435 3436
/* JOIN qualification clauses
 * Possibilities are:
 *  USING ( column list ) allows only unqualified column names,
 *                        which must match between tables.
 *  ON expr allows more general qualifications.
 * - thomas 1999-01-07
 */

join_qual:  USING '(' using_list ')'			{ $$ = $3; }
		| ON a_expr								{ $$ = lcons($2, NIL); }
3437 3438
		;

3439 3440
using_list:  using_list ',' using_expr			{ $$ = lappend($1, $3); }
		| using_expr							{ $$ = lcons($1, NIL); }
3441
		;
3442

3443
using_expr:  ColId
3444
				{
3445 3446 3447 3448 3449
					/* could be a column name or a relation_name */
					Ident *n = makeNode(Ident);
					n->name = $1;
					n->indirection = NULL;
					$$ = (Node *)n;
3450 3451 3452
				}
		;

3453 3454
where_clause:  WHERE a_expr						{ $$ = $2; }
		| /*EMPTY*/								{ $$ = NULL;  /* no qualifiers */ }
3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
		;

relation_expr:	relation_name
				{
					/* normal relations */
					$$ = makeNode(RelExpr);
					$$->relname = $1;
					$$->inh = FALSE;
				}
		| relation_name '*'				  %prec '='
				{
3466
					/* inheritance query */
3467 3468 3469 3470
					$$ = makeNode(RelExpr);
					$$->relname = $1;
					$$->inh = TRUE;
				}
3471

3472
opt_array_bounds:	'[' ']' opt_array_bounds
3473
				{  $$ = lcons(makeInteger(-1), $3); }
3474
		| '[' Iconst ']' opt_array_bounds
3475 3476 3477 3478
				{  $$ = lcons(makeInteger($2), $4); }
		| /*EMPTY*/
				{  $$ = NIL; }
		;
3479

3480

3481 3482 3483 3484 3485 3486 3487 3488 3489 3490
/*****************************************************************************
 *
 *	Type syntax
 *		SQL92 introduces a large amount of type-specific syntax.
 *		Define individual clauses to handle these cases, and use
 *		 the generic case to handle regular type-extensible Postgres syntax.
 *		- thomas 1997-10-10
 *
 *****************************************************************************/

3491
Typename:  SimpleTypename opt_array_bounds
3492 3493 3494
				{
					$$ = $1;
					$$->arrayBounds = $2;
3495 3496 3497 3498

					/* Is this the name of a complex type? If so, implement
					 * it as a set.
					 */
3499
					if (!strcmp(saved_relname, $$->name))
3500 3501 3502 3503 3504
						/* This attr is the same type as the relation
						 * being defined. The classic example: create
						 * emp(name=text,mgr=emp)
						 */
						$$->setof = TRUE;
3505
					else if (typeTypeRelid(typenameType($$->name)) != InvalidOid)
3506 3507 3508 3509 3510 3511 3512
						 /* (Eventually add in here that the set can only
						  * contain one element.)
						  */
						$$->setof = TRUE;
					else
						$$->setof = FALSE;
				}
3513
		| SETOF SimpleTypename
3514
				{
3515
					$$ = $2;
3516 3517 3518 3519
					$$->setof = TRUE;
				}
		;

3520
SimpleTypename:  Generic
3521
		| Numeric
3522
		| Character
3523
		| Datetime
3524
		;
3525

3526
Generic:  generic
3527
				{
3528 3529
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType($1);
3530
					$$->typmod = -1;
3531 3532 3533
				}
		;

3534
generic:  IDENT									{ $$ = $1; }
3535
		| TYPE_P								{ $$ = "type"; }
3536 3537 3538 3539
		;

/* SQL92 numeric data types
 * Check FLOAT() precision limits assuming IEEE floating types.
3540
 * Provide real DECIMAL() and NUMERIC() implementations now - Jan 1998-12-30
3541 3542 3543 3544 3545 3546
 * - thomas 1997-09-18
 */
Numeric:  FLOAT opt_float
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType($2);
3547
					$$->typmod = -1;
3548
				}
3549 3550 3551 3552 3553
		| DOUBLE PRECISION
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType("float");
				}
3554
		| DECIMAL opt_decimal
3555
				{
3556
					$$ = makeNode(TypeName);
3557
					$$->name = xlateSqlType("numeric");
3558
					$$->typmod = $2;
3559 3560 3561 3562
				}
		| NUMERIC opt_numeric
				{
					$$ = makeNode(TypeName);
3563 3564
					$$->name = xlateSqlType("numeric");
					$$->typmod = $2;
3565 3566
				}
		;
3567

3568 3569 3570 3571 3572
numeric:  FLOAT
				{	$$ = xlateSqlType("float8"); }
		| DOUBLE PRECISION
				{	$$ = xlateSqlType("float8"); }
		| DECIMAL
3573
				{	$$ = xlateSqlType("numeric"); }
3574 3575 3576 3577
		| NUMERIC
				{	$$ = xlateSqlType("numeric"); }
		;

3578 3579 3580
opt_float:  '(' Iconst ')'
				{
					if ($2 < 1)
Bruce Momjian's avatar
Bruce Momjian committed
3581
						elog(ERROR,"precision for FLOAT must be at least 1");
3582 3583 3584 3585 3586
					else if ($2 < 7)
						$$ = xlateSqlType("float4");
					else if ($2 < 16)
						$$ = xlateSqlType("float8");
					else
Bruce Momjian's avatar
Bruce Momjian committed
3587
						elog(ERROR,"precision for FLOAT must be less than 16");
3588 3589 3590 3591 3592 3593 3594 3595 3596
				}
		| /*EMPTY*/
				{
					$$ = xlateSqlType("float8");
				}
		;

opt_numeric:  '(' Iconst ',' Iconst ')'
				{
3597
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
Bruce Momjian's avatar
Bruce Momjian committed
3598
						elog(ERROR,"NUMERIC precision %d must be between 1 and %d",
3599 3600 3601 3602 3603 3604
									$2, NUMERIC_MAX_PRECISION);
					if ($4 < 0 || $4 > $2)
						elog(ERROR,"NUMERIC scale %d must be between 0 and precision %d",
									$4,$2);

					$$ = (($2 << 16) | $4) + VARHDRSZ;
3605 3606 3607
				}
		| '(' Iconst ')'
				{
3608
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
Bruce Momjian's avatar
Bruce Momjian committed
3609
						elog(ERROR,"NUMERIC precision %d must be between 1 and %d",
3610 3611 3612
									$2, NUMERIC_MAX_PRECISION);

					$$ = ($2 << 16) + VARHDRSZ;
3613 3614 3615
				}
		| /*EMPTY*/
				{
3616
					$$ = ((NUMERIC_DEFAULT_PRECISION << 16) | NUMERIC_DEFAULT_SCALE) + VARHDRSZ;
3617 3618 3619 3620 3621
				}
		;

opt_decimal:  '(' Iconst ',' Iconst ')'
				{
3622
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
Bruce Momjian's avatar
Bruce Momjian committed
3623
						elog(ERROR,"DECIMAL precision %d must be between 1 and %d",
3624 3625 3626 3627 3628 3629
									$2, NUMERIC_MAX_PRECISION);
					if ($4 < 0 || $4 > $2)
						elog(ERROR,"DECIMAL scale %d must be between 0 and precision %d",
									$4,$2);

					$$ = (($2 << 16) | $4) + VARHDRSZ;
3630 3631 3632
				}
		| '(' Iconst ')'
				{
3633
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
Bruce Momjian's avatar
Bruce Momjian committed
3634
						elog(ERROR,"DECIMAL precision %d must be between 1 and %d",
3635 3636 3637
									$2, NUMERIC_MAX_PRECISION);

					$$ = ($2 << 16) + VARHDRSZ;
3638 3639 3640
				}
		| /*EMPTY*/
				{
3641
					$$ = ((NUMERIC_DEFAULT_PRECISION << 16) | NUMERIC_DEFAULT_SCALE) + VARHDRSZ;
3642 3643 3644
				}
		;

3645

3646 3647 3648 3649 3650 3651
/* SQL92 character data types
 * The following implements CHAR() and VARCHAR().
 */
Character:  character '(' Iconst ')'
				{
					$$ = makeNode(TypeName);
3652
					if (strcasecmp($1, "char") == 0)
3653
						$$->name = xlateSqlType("bpchar");
3654
					else if (strcasecmp($1, "varchar") == 0)
3655 3656
						$$->name = xlateSqlType("varchar");
					else
3657 3658
						yyerror("internal parsing error; unrecognized character type");

3659
					if ($3 < 1)
3660
						elog(ERROR,"length for '%s' type must be at least 1",$1);
3661
					else if ($3 > MaxAttrSize)
3662
						elog(ERROR,"length for type '%s' cannot exceed %ld",$1,
3663
							MaxAttrSize);
3664 3665 3666 3667 3668 3669

					/* we actually implement this sort of like a varlen, so
					 * the first 4 bytes is the length. (the difference
					 * between this and "text" is that we blank-pad and
					 * truncate where necessary
					 */
3670
					$$->typmod = VARHDRSZ + $3;
3671
				}
3672
		| character
3673 3674
				{
					$$ = makeNode(TypeName);
3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687
					/* Let's try to make all single-character types into bpchar(1)
					 * - thomas 1998-05-07
					 */
					if (strcasecmp($1, "char") == 0)
					{
						$$->name = xlateSqlType("bpchar");
						$$->typmod = VARHDRSZ + 1;
					}
					else
					{
						$$->name = xlateSqlType($1);
						$$->typmod = -1;
					}
3688 3689
				}
		;
3690

3691 3692 3693 3694 3695 3696
character:  CHARACTER opt_varying opt_charset opt_collate
				{
					char *type, *c;
					if (($3 == NULL) || (strcasecmp($3, "sql_text") == 0)) {
						if ($2) type = xlateSqlType("varchar");
						else type = xlateSqlType("char");
3697
					} else {
3698 3699 3700 3701 3702 3703 3704 3705 3706 3707
						if ($2) {
							c = palloc(strlen("var") + strlen($3) + 1);
							strcpy(c, "var");
							strcat(c, $3);
							type = xlateSqlType(c);
						} else {
							type = xlateSqlType($3);
						}
					};
					if ($4 != NULL)
3708
						elog(NOTICE,"COLLATE %s not yet implemented; clause ignored",$4);
3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732
					$$ = type;
				}
		| CHAR opt_varying						{ $$ = xlateSqlType($2? "varchar": "char"); }
		| VARCHAR								{ $$ = xlateSqlType("varchar"); }
		| NATIONAL CHARACTER opt_varying		{ $$ = xlateSqlType($3? "varchar": "char"); }
		| NCHAR opt_varying						{ $$ = xlateSqlType($2? "varchar": "char"); }
		;

opt_varying:  VARYING							{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
		;

opt_charset:  CHARACTER SET ColId				{ $$ = $3; }
		| /*EMPTY*/								{ $$ = NULL; }
		;

opt_collate:  COLLATE ColId						{ $$ = $2; }
		| /*EMPTY*/								{ $$ = NULL; }
		;

Datetime:  datetime
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType($1);
3733
					$$->typmod = -1;
3734 3735 3736 3737 3738 3739
				}
		| TIMESTAMP opt_timezone
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType("timestamp");
					$$->timezone = $2;
3740
					$$->typmod = -1;
3741 3742 3743 3744 3745
				}
		| TIME
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType("time");
3746
					$$->typmod = -1;
3747 3748 3749 3750 3751
				}
		| INTERVAL opt_interval
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType("interval");
3752
					$$->typmod = -1;
3753
				}
3754
		;
3755

3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
datetime:  YEAR_P								{ $$ = "year"; }
		| MONTH_P								{ $$ = "month"; }
		| DAY_P									{ $$ = "day"; }
		| HOUR_P								{ $$ = "hour"; }
		| MINUTE_P								{ $$ = "minute"; }
		| SECOND_P								{ $$ = "second"; }
		;

opt_timezone:  WITH TIME ZONE					{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
		;

opt_interval:  datetime							{ $$ = lcons($1, NIL); }
		| YEAR_P TO MONTH_P						{ $$ = NIL; }
		| DAY_P TO HOUR_P						{ $$ = NIL; }
		| DAY_P TO MINUTE_P						{ $$ = NIL; }
		| DAY_P TO SECOND_P						{ $$ = NIL; }
		| HOUR_P TO MINUTE_P					{ $$ = NIL; }
		| HOUR_P TO SECOND_P					{ $$ = NIL; }
3775
		| MINUTE_P TO SECOND_P					{ $$ = NIL; }
3776
		| /*EMPTY*/								{ $$ = NIL; }
3777 3778
		;

3779 3780 3781

/*****************************************************************************
 *
3782
 *	expression grammar
3783 3784 3785
 *
 *****************************************************************************/

3786
a_expr_or_null:  a_expr
3787
				{ $$ = $1; }
3788
		| NULL_P
3789 3790 3791 3792 3793
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Null;
					$$ = (Node *)n;
				}
3794 3795 3796 3797 3798 3799 3800 3801
		;

/* Expressions using row descriptors
 * Define row_descriptor to allow yacc to break the reduce/reduce conflict
 *  with singleton expressions.
 */
row_expr: '(' row_descriptor ')' IN '(' SubSelect ')'
				{
3802 3803
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
3804
					n->oper = lcons("=", NIL);
3805 3806
					n->useor = false;
					n->subLinkType = ANY_SUBLINK;
3807 3808
					n->subselect = $6;
					$$ = (Node *)n;
3809 3810 3811
				}
		| '(' row_descriptor ')' NOT IN '(' SubSelect ')'
				{
3812 3813
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
3814
					n->oper = lcons("<>", NIL);
3815 3816 3817 3818 3819
					n->useor = true;
					n->subLinkType = ALL_SUBLINK;
					n->subselect = $7;
					$$ = (Node *)n;
				}
3820
		| '(' row_descriptor ')' all_Op sub_type '(' SubSelect ')'
3821 3822 3823 3824 3825 3826 3827 3828
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
					n->oper = lcons($4, NIL);
					if (strcmp($4,"<>") == 0)
						n->useor = true;
					else
						n->useor = false;
3829
					n->subLinkType = $5;
Bruce Momjian's avatar
Bruce Momjian committed
3830 3831 3832
					n->subselect = $7;
					$$ = (Node *)n;
				}
3833
		| '(' row_descriptor ')' all_Op '(' SubSelect ')'
Bruce Momjian's avatar
Bruce Momjian committed
3834 3835 3836
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
3837
					n->oper = lcons($4, NIL);
3838 3839 3840 3841
					if (strcmp($4,"<>") == 0)
						n->useor = true;
					else
						n->useor = false;
3842
					n->subLinkType = MULTIEXPR_SUBLINK;
3843
					n->subselect = $6;
Bruce Momjian's avatar
Bruce Momjian committed
3844 3845
					$$ = (Node *)n;
				}
3846
		| '(' row_descriptor ')' all_Op '(' row_descriptor ')'
3847
				{
Bruce Momjian's avatar
Bruce Momjian committed
3848
					$$ = makeRowExpr($4, $2, $6);
3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866
				}
		;

row_descriptor:  row_list ',' a_expr
				{
					$$ = lappend($1, $3);
				}
		;

row_list:  row_list ',' a_expr
				{
					$$ = lappend($1, $3);
				}
		| a_expr
				{
					$$ = lcons($1, NIL);
				}
		;
3867

3868 3869 3870 3871
sub_type:  ANY								{ $$ = ANY_SUBLINK; }
		| ALL								{ $$ = ALL_SUBLINK; }
		;

3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
all_Op:  Op | MathOp;

MathOp:	'+'				{ $$ = "+"; }
		| '-'			{ $$ = "-"; }
		| '*'			{ $$ = "*"; }
		| '/'			{ $$ = "/"; }
		| '%'			{ $$ = "%"; }
		| '^'			{ $$ = "^"; }
		| '|'			{ $$ = "|"; }
		| '<'			{ $$ = "<"; }
		| '>'			{ $$ = ">"; }
		| '='			{ $$ = "="; }
		;

/*
 * General expressions
3888
 * This is the heart of the expression syntax.
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900
 *
 * We have two expression types: a_expr is the unrestricted kind, and
 * b_expr is a subset that must be used in some places to avoid shift/reduce
 * conflicts.  For example, we can't do BETWEEN as "BETWEEN a_expr AND a_expr"
 * because that use of AND conflicts with AND as a boolean operator.  So,
 * b_expr is used in BETWEEN and we remove boolean keywords from b_expr.
 *
 * Note that '(' a_expr ')' is a b_expr, so an unrestricted expression can
 * always be used by surrounding it with parens.
 *
 * com_expr is all the productions that are common to a_expr and b_expr;
 * it's factored out just to eliminate redundant coding.
3901
 */
3902
a_expr:  com_expr
3903
				{	$$ = $1;  }
3904
		| a_expr TYPECAST Typename
3905
				{
3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916
					$$ = (Node *)$1;
					/* AexprConst can be either A_Const or ParamNo */
					if (nodeTag($1) == T_A_Const) {
						((A_Const *)$1)->typename = $3;
					} else if (nodeTag($1) == T_ParamNo) {
						((ParamNo *)$1)->typename = $3;
					/* otherwise, try to transform to a function call */
					} else {
						FuncCall *n = makeNode(FuncCall);
						n->funcname = $3->name;
						n->args = lcons($1,NIL);
3917 3918
						n->agg_star = false;
						n->agg_distinct = false;
3919 3920
						$$ = (Node *)n;
					}
3921
				}
3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932
		/*
		 * Can't collapse this into prior rule by using a_expr_or_null;
		 * that creates reduce/reduce conflicts.  Grumble.
		 */
		| NULL_P TYPECAST Typename
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Null;
					n->typename = $3;
					$$ = (Node *)n;
				}
3933 3934 3935 3936 3937 3938 3939 3940 3941
		/*
		 * These operators must be called out explicitly in order to make use
		 * of yacc/bison's automatic operator-precedence handling.  All other
		 * operator names are handled by the generic productions using "Op",
		 * below; and all those operators will have the same precedence.
		 *
		 * If you add more explicitly-known operators, be sure to add them
		 * also to b_expr and to the MathOp list above.
		 */
3942
		| '-' a_expr %prec UMINUS
3943
				{	$$ = doNegate($2); }
Bruce Momjian's avatar
Bruce Momjian committed
3944
		| '%' a_expr
Bruce Momjian's avatar
Bruce Momjian committed
3945
				{	$$ = makeA_Expr(OP, "%", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
3946 3947
		| '^' a_expr
				{	$$ = makeA_Expr(OP, "^", NULL, $2); }
3948 3949
		| '|' a_expr
				{	$$ = makeA_Expr(OP, "|", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
3950 3951 3952 3953
		| ':' a_expr
				{	$$ = makeA_Expr(OP, ":", NULL, $2); }
		| ';' a_expr
				{	$$ = makeA_Expr(OP, ";", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
3954
		| a_expr '%'
Bruce Momjian's avatar
Bruce Momjian committed
3955
				{	$$ = makeA_Expr(OP, "%", $1, NULL); }
Bruce Momjian's avatar
Bruce Momjian committed
3956 3957
		| a_expr '^'
				{	$$ = makeA_Expr(OP, "^", $1, NULL); }
3958 3959
		| a_expr '|'
				{	$$ = makeA_Expr(OP, "|", $1, NULL); }
3960 3961 3962 3963
		| a_expr '+' a_expr
				{	$$ = makeA_Expr(OP, "+", $1, $3); }
		| a_expr '-' a_expr
				{	$$ = makeA_Expr(OP, "-", $1, $3); }
3964 3965
		| a_expr '*' a_expr
				{	$$ = makeA_Expr(OP, "*", $1, $3); }
3966 3967
		| a_expr '/' a_expr
				{	$$ = makeA_Expr(OP, "/", $1, $3); }
3968 3969
		| a_expr '%' a_expr
				{	$$ = makeA_Expr(OP, "%", $1, $3); }
Bruce Momjian's avatar
Bruce Momjian committed
3970 3971
		| a_expr '^' a_expr
				{	$$ = makeA_Expr(OP, "^", $1, $3); }
3972 3973
		| a_expr '|' a_expr
				{	$$ = makeA_Expr(OP, "|", $1, $3); }
3974 3975 3976 3977
		| a_expr '<' a_expr
				{	$$ = makeA_Expr(OP, "<", $1, $3); }
		| a_expr '>' a_expr
				{	$$ = makeA_Expr(OP, ">", $1, $3); }
3978

3979 3980
  		| a_expr '=' NULL_P
  				{	$$ = makeA_Expr(ISNULL, NULL, $1, NULL); }
Bruce Momjian's avatar
Bruce Momjian committed
3981 3982
		/* We allow this for standards-broken SQL products, like MS stuff */
  		| NULL_P '=' a_expr
3983 3984
  				{	$$ = makeA_Expr(ISNULL, NULL, $3, NULL); }

3985 3986
		| a_expr '=' a_expr
				{	$$ = makeA_Expr(OP, "=", $1, $3); }
3987

3988
		| a_expr Op a_expr
3989
				{	$$ = makeA_Expr(OP, $2, $1, $3); }
3990 3991 3992 3993
		| Op a_expr
				{	$$ = makeA_Expr(OP, $1, NULL, $2); }
		| a_expr Op
				{	$$ = makeA_Expr(OP, $2, $1, NULL); }
3994

3995 3996 3997 3998 3999 4000
		| a_expr AND a_expr
				{	$$ = makeA_Expr(AND, NULL, $1, $3); }
		| a_expr OR a_expr
				{	$$ = makeA_Expr(OR, NULL, $1, $3); }
		| NOT a_expr
				{	$$ = makeA_Expr(NOT, NULL, NULL, $2); }
4001

4002 4003 4004 4005
		| a_expr LIKE a_expr
				{	$$ = makeA_Expr(OP, "~~", $1, $3); }
		| a_expr NOT LIKE a_expr
				{	$$ = makeA_Expr(OP, "!~~", $1, $4); }
4006

4007 4008
		| a_expr ISNULL
				{	$$ = makeA_Expr(ISNULL, NULL, $1, NULL); }
4009
		| a_expr IS NULL_P
4010 4011 4012
				{	$$ = makeA_Expr(ISNULL, NULL, $1, NULL); }
		| a_expr NOTNULL
				{	$$ = makeA_Expr(NOTNULL, NULL, $1, NULL); }
4013
		| a_expr IS NOT NULL_P
4014
				{	$$ = makeA_Expr(NOTNULL, NULL, $1, NULL); }
4015 4016 4017 4018 4019
		/* IS TRUE, IS FALSE, etc used to be function calls
		 *  but let's make them expressions to allow the optimizer
		 *  a chance to eliminate them if a_expr is a constant string.
		 * - thomas 1997-12-22
		 */
4020 4021
		| a_expr IS TRUE_P
				{
4022 4023 4024 4025 4026
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "t";
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
4027
					n->typename->typmod = -1;
4028
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4029
				}
4030
		| a_expr IS NOT FALSE_P
4031
				{
4032 4033 4034 4035 4036
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "t";
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
4037
					n->typename->typmod = -1;
4038
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4039
				}
4040
		| a_expr IS FALSE_P
4041
				{
4042 4043 4044 4045 4046
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "f";
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
4047
					n->typename->typmod = -1;
4048
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4049
				}
4050
		| a_expr IS NOT TRUE_P
4051
				{
4052 4053 4054 4055 4056
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "f";
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
4057
					n->typename->typmod = -1;
4058
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4059
				}
4060
		| a_expr BETWEEN b_expr AND b_expr
4061 4062 4063 4064 4065
				{
					$$ = makeA_Expr(AND, NULL,
						makeA_Expr(OP, ">=", $1, $3),
						makeA_Expr(OP, "<=", $1, $5));
				}
4066
		| a_expr NOT BETWEEN b_expr AND b_expr
4067 4068 4069 4070 4071
				{
					$$ = makeA_Expr(OR, NULL,
						makeA_Expr(OP, "<", $1, $4),
						makeA_Expr(OP, ">", $1, $6));
				}
4072
		| a_expr IN '(' in_expr ')'
4073
				{
4074 4075
					/* in_expr returns a SubLink or a list of a_exprs */
					if (IsA($4, SubLink))
4076
					{
4077
							SubLink *n = (SubLink *)$4;
4078
							n->lefthand = lcons($1, NIL);
4079
							n->oper = lcons("=", NIL);
4080 4081 4082
							n->useor = false;
							n->subLinkType = ANY_SUBLINK;
							$$ = (Node *)n;
4083
					}
4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
					else
					{
						Node *n = NULL;
						List *l;
						foreach(l, (List *) $4)
						{
							Node *cmp = makeA_Expr(OP, "=", $1, lfirst(l));
							if (n == NULL)
								n = cmp;
							else
								n = makeA_Expr(OR, NULL, n, cmp);
						}
						$$ = n;
					}
4098
				}
4099
		| a_expr NOT IN '(' in_expr ')'
4100
				{
4101 4102
					/* in_expr returns a SubLink or a list of a_exprs */
					if (IsA($5, SubLink))
4103
					{
4104 4105
						SubLink *n = (SubLink *)$5;
						n->lefthand = lcons($1, NIL);
4106
						n->oper = lcons("<>", NIL);
4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
						n->useor = false;
						n->subLinkType = ALL_SUBLINK;
						$$ = (Node *)n;
					}
					else
					{
						Node *n = NULL;
						List *l;
						foreach(l, (List *) $5)
						{
							Node *cmp = makeA_Expr(OP, "<>", $1, lfirst(l));
							if (n == NULL)
								n = cmp;
							else
								n = makeA_Expr(AND, NULL, n, cmp);
						}
						$$ = n;
4124 4125
					}
				}
4126
		| a_expr all_Op sub_type '(' SubSelect ')'
Bruce Momjian's avatar
Bruce Momjian committed
4127 4128
				{
					SubLink *n = makeNode(SubLink);
4129 4130 4131 4132
					n->lefthand = lcons($1, NIL);
					n->oper = lcons($2, NIL);
					n->useor = false; /* doesn't matter since only one col */
					n->subLinkType = $3;
4133
					n->subselect = $5;
Bruce Momjian's avatar
Bruce Momjian committed
4134 4135
					$$ = (Node *)n;
				}
4136 4137
		| row_expr
				{	$$ = $1;  }
4138
		;
4139

4140 4141 4142 4143 4144 4145 4146 4147
/*
 * Restricted expressions
 *
 * b_expr is a subset of the complete expression syntax defined by a_expr.
 *
 * Presently, AND, NOT, IS, IN, and NULL are the a_expr keywords that would
 * cause trouble in the places where b_expr is used.  For simplicity, we
 * just eliminate all the boolean-keyword-operator productions from b_expr.
4148
 */
4149
b_expr:  com_expr
4150
				{	$$ = $1;  }
4151
		| b_expr TYPECAST Typename
4152
				{
4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163
					$$ = (Node *)$1;
					/* AexprConst can be either A_Const or ParamNo */
					if (nodeTag($1) == T_A_Const) {
						((A_Const *)$1)->typename = $3;
					} else if (nodeTag($1) == T_ParamNo) {
						((ParamNo *)$1)->typename = $3;
					/* otherwise, try to transform to a function call */
					} else {
						FuncCall *n = makeNode(FuncCall);
						n->funcname = $3->name;
						n->args = lcons($1,NIL);
4164 4165
						n->agg_star = false;
						n->agg_distinct = false;
4166 4167
						$$ = (Node *)n;
					}
4168
				}
4169 4170 4171 4172 4173 4174 4175
		| NULL_P TYPECAST Typename
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Null;
					n->typename = $3;
					$$ = (Node *)n;
				}
4176
		| '-' b_expr %prec UMINUS
4177
				{	$$ = doNegate($2); }
Bruce Momjian's avatar
Bruce Momjian committed
4178 4179
		| '%' b_expr
				{	$$ = makeA_Expr(OP, "%", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
4180 4181
		| '^' b_expr
				{	$$ = makeA_Expr(OP, "^", NULL, $2); }
4182 4183
		| '|' b_expr
				{	$$ = makeA_Expr(OP, "|", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
4184 4185 4186 4187
		| ':' b_expr
				{	$$ = makeA_Expr(OP, ":", NULL, $2); }
		| ';' b_expr
				{	$$ = makeA_Expr(OP, ";", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
4188 4189
		| b_expr '%'
				{	$$ = makeA_Expr(OP, "%", $1, NULL); }
Bruce Momjian's avatar
Bruce Momjian committed
4190 4191
		| b_expr '^'
				{	$$ = makeA_Expr(OP, "^", $1, NULL); }
4192 4193
		| b_expr '|'
				{	$$ = makeA_Expr(OP, "|", $1, NULL); }
4194 4195 4196 4197
		| b_expr '+' b_expr
				{	$$ = makeA_Expr(OP, "+", $1, $3); }
		| b_expr '-' b_expr
				{	$$ = makeA_Expr(OP, "-", $1, $3); }
4198 4199
		| b_expr '*' b_expr
				{	$$ = makeA_Expr(OP, "*", $1, $3); }
4200 4201
		| b_expr '/' b_expr
				{	$$ = makeA_Expr(OP, "/", $1, $3); }
4202 4203
		| b_expr '%' b_expr
				{	$$ = makeA_Expr(OP, "%", $1, $3); }
4204 4205
		| b_expr '^' b_expr
				{	$$ = makeA_Expr(OP, "^", $1, $3); }
4206 4207
		| b_expr '|' b_expr
				{	$$ = makeA_Expr(OP, "|", $1, $3); }
4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233
		| b_expr '<' b_expr
				{	$$ = makeA_Expr(OP, "<", $1, $3); }
		| b_expr '>' b_expr
				{	$$ = makeA_Expr(OP, ">", $1, $3); }
		| b_expr '=' b_expr
				{	$$ = makeA_Expr(OP, "=", $1, $3); }

		| b_expr Op b_expr
				{	$$ = makeA_Expr(OP, $2, $1, $3); }
		| Op b_expr
				{	$$ = makeA_Expr(OP, $1, NULL, $2); }
		| b_expr Op
				{	$$ = makeA_Expr(OP, $2, $1, NULL); }
		;

/*
 * Productions that can be used in both a_expr and b_expr.
 *
 * Note: productions that refer recursively to a_expr or b_expr mostly
 * cannot appear here.  However, it's OK to refer to a_exprs that occur
 * inside parentheses, such as function arguments; that cannot introduce
 * ambiguity to the b_expr syntax.
 */
com_expr:  attr
				{	$$ = (Node *) $1;  }
		| ColId opt_indirection
4234
				{
4235 4236 4237 4238 4239
					/* could be a column name or a relation_name */
					Ident *n = makeNode(Ident);
					n->name = $1;
					n->indirection = $2;
					$$ = (Node *)n;
4240
				}
4241 4242 4243 4244
		| AexprConst
				{	$$ = $1;  }
		| '(' a_expr_or_null ')'
				{	$$ = $2; }
4245
		| CAST '(' a_expr_or_null AS Typename ')'
4246
				{
4247
					$$ = (Node *)$3;
4248
					/* AexprConst can be either A_Const or ParamNo */
4249 4250
					if (nodeTag($3) == T_A_Const) {
						((A_Const *)$3)->typename = $5;
4251
					} else if (nodeTag($3) == T_ParamNo) {
4252
						((ParamNo *)$3)->typename = $5;
4253 4254 4255
					/* otherwise, try to transform to a function call */
					} else {
						FuncCall *n = makeNode(FuncCall);
4256 4257
						n->funcname = $5->name;
						n->args = lcons($3,NIL);
4258 4259
						n->agg_star = false;
						n->agg_distinct = false;
4260 4261 4262
						$$ = (Node *)n;
					}
				}
4263 4264
		| case_expr
				{	$$ = $1; }
4265
		| func_name '(' ')'
4266 4267 4268 4269
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = $1;
					n->args = NIL;
4270 4271
					n->agg_star = false;
					n->agg_distinct = false;
4272 4273
					$$ = (Node *)n;
				}
4274
		| func_name '(' expr_list ')'
4275 4276 4277 4278
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = $1;
					n->args = $3;
4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
					n->agg_star = false;
					n->agg_distinct = false;
					$$ = (Node *)n;
				}
		| func_name '(' DISTINCT expr_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = $1;
					n->args = $4;
					n->agg_star = false;
					n->agg_distinct = true;
4290 4291
					$$ = (Node *)n;
				}
4292 4293 4294 4295 4296 4297 4298 4299 4300 4301
		| func_name '(' '*' ')'
				{
					/*
					 * For now, we transform AGGREGATE(*) into AGGREGATE(1).
					 *
					 * This does the right thing for COUNT(*) (in fact,
					 * any certainly-non-null expression would do for COUNT),
					 * and there are no other aggregates in SQL92 that accept
					 * '*' as parameter.
					 *
4302 4303 4304
					 * The FuncCall node is also marked agg_star = true,
					 * so that later processing can detect what the argument
					 * really was.
4305 4306 4307 4308 4309 4310 4311 4312
					 */
					FuncCall *n = makeNode(FuncCall);
					A_Const *star = makeNode(A_Const);

					star->val.type = T_Integer;
					star->val.val.ival = 1;
					n->funcname = $1;
					n->args = lcons(star, NIL);
4313 4314
					n->agg_star = true;
					n->agg_distinct = false;
4315 4316
					$$ = (Node *)n;
				}
4317 4318
		| CURRENT_DATE
				{
4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332
					/*
					 * Translate as "date('now'::text)".
					 *
					 * We cannot use "'now'::date" because coerce_type() will
					 * immediately reduce that to a constant representing
					 * today's date.  We need to delay the conversion until
					 * runtime, else the wrong things will happen when
					 * CURRENT_DATE is used in a column default value or rule.
					 *
					 * This could be simplified if we had a way to generate
					 * an expression tree representing runtime application
					 * of type-input conversion functions...
					 */
					A_Const *s = makeNode(A_Const);
4333
					TypeName *t = makeNode(TypeName);
4334
					FuncCall *n = makeNode(FuncCall);
4335

4336 4337 4338
					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;
4339

4340
					t->name = xlateSqlType("text");
4341
					t->setof = FALSE;
4342
					t->typmod = -1;
4343

4344 4345
					n->funcname = xlateSqlType("date");
					n->args = lcons(s, NIL);
4346 4347
					n->agg_star = false;
					n->agg_distinct = false;
4348

4349 4350 4351 4352
					$$ = (Node *)n;
				}
		| CURRENT_TIME
				{
4353 4354 4355 4356 4357
					/*
					 * Translate as "time('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
					A_Const *s = makeNode(A_Const);
4358
					TypeName *t = makeNode(TypeName);
4359
					FuncCall *n = makeNode(FuncCall);
4360

4361 4362 4363
					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;
4364

4365
					t->name = xlateSqlType("text");
4366
					t->setof = FALSE;
4367
					t->typmod = -1;
4368

4369 4370
					n->funcname = xlateSqlType("time");
					n->args = lcons(s, NIL);
4371 4372
					n->agg_star = false;
					n->agg_distinct = false;
4373

4374 4375 4376 4377
					$$ = (Node *)n;
				}
		| CURRENT_TIME '(' Iconst ')'
				{
4378 4379 4380 4381
					/*
					 * Translate as "time('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
4382 4383
					A_Const *s = makeNode(A_Const);
					TypeName *t = makeNode(TypeName);
4384
					FuncCall *n = makeNode(FuncCall);
4385 4386 4387 4388 4389

					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;

4390
					t->name = xlateSqlType("text");
4391
					t->setof = FALSE;
4392
					t->typmod = -1;
4393

4394 4395
					n->funcname = xlateSqlType("time");
					n->args = lcons(s, NIL);
4396 4397
					n->agg_star = false;
					n->agg_distinct = false;
4398

4399 4400 4401 4402 4403 4404 4405
					if ($3 != 0)
						elog(NOTICE,"CURRENT_TIME(%d) precision not implemented; zero used instead",$3);

					$$ = (Node *)n;
				}
		| CURRENT_TIMESTAMP
				{
4406 4407 4408 4409 4410
					/*
					 * Translate as "timestamp('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
					A_Const *s = makeNode(A_Const);
4411
					TypeName *t = makeNode(TypeName);
4412
					FuncCall *n = makeNode(FuncCall);
4413

4414 4415 4416
					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;
4417

4418
					t->name = xlateSqlType("text");
4419
					t->setof = FALSE;
4420
					t->typmod = -1;
4421

4422 4423
					n->funcname = xlateSqlType("timestamp");
					n->args = lcons(s, NIL);
4424 4425
					n->agg_star = false;
					n->agg_distinct = false;
4426

4427 4428 4429 4430
					$$ = (Node *)n;
				}
		| CURRENT_TIMESTAMP '(' Iconst ')'
				{
4431 4432 4433 4434
					/*
					 * Translate as "timestamp('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
4435 4436
					A_Const *s = makeNode(A_Const);
					TypeName *t = makeNode(TypeName);
4437
					FuncCall *n = makeNode(FuncCall);
4438 4439 4440 4441 4442

					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;

4443
					t->name = xlateSqlType("text");
4444
					t->setof = FALSE;
4445
					t->typmod = -1;
4446

4447 4448
					n->funcname = xlateSqlType("timestamp");
					n->args = lcons(s, NIL);
4449 4450
					n->agg_star = false;
					n->agg_distinct = false;
4451

4452 4453 4454 4455 4456 4457 4458 4459 4460 4461
					if ($3 != 0)
						elog(NOTICE,"CURRENT_TIMESTAMP(%d) precision not implemented; zero used instead",$3);

					$$ = (Node *)n;
				}
		| CURRENT_USER
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "getpgusername";
					n->args = NIL;
4462 4463
					n->agg_star = false;
					n->agg_distinct = false;
4464 4465
					$$ = (Node *)n;
				}
4466 4467 4468 4469 4470
		| USER
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "getpgusername";
					n->args = NIL;
4471 4472
					n->agg_star = false;
					n->agg_distinct = false;
4473 4474
					$$ = (Node *)n;
				}
4475 4476 4477 4478 4479
		| EXTRACT '(' extract_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "date_part";
					n->args = $3;
4480 4481
					n->agg_star = false;
					n->agg_distinct = false;
4482 4483
					$$ = (Node *)n;
				}
4484 4485 4486 4487 4488
		| POSITION '(' position_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "strpos";
					n->args = $3;
4489 4490
					n->agg_star = false;
					n->agg_distinct = false;
4491 4492 4493 4494 4495 4496 4497
					$$ = (Node *)n;
				}
		| SUBSTRING '(' substr_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "substr";
					n->args = $3;
4498 4499
					n->agg_star = false;
					n->agg_distinct = false;
4500 4501 4502 4503 4504 4505 4506 4507
					$$ = (Node *)n;
				}
		/* various trim expressions are defined in SQL92 - thomas 1997-07-19 */
		| TRIM '(' BOTH trim_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "btrim";
					n->args = $4;
4508 4509
					n->agg_star = false;
					n->agg_distinct = false;
4510 4511 4512 4513 4514 4515 4516
					$$ = (Node *)n;
				}
		| TRIM '(' LEADING trim_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "ltrim";
					n->args = $4;
4517 4518
					n->agg_star = false;
					n->agg_distinct = false;
4519 4520 4521 4522 4523 4524 4525
					$$ = (Node *)n;
				}
		| TRIM '(' TRAILING trim_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "rtrim";
					n->args = $4;
4526 4527
					n->agg_star = false;
					n->agg_distinct = false;
4528 4529 4530 4531 4532 4533 4534
					$$ = (Node *)n;
				}
		| TRIM '(' trim_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "btrim";
					n->args = $3;
4535 4536
					n->agg_star = false;
					n->agg_distinct = false;
4537 4538
					$$ = (Node *)n;
				}
4539 4540 4541 4542 4543 4544 4545 4546 4547 4548
		| '(' SubSelect ')'
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = NIL;
					n->oper = NIL;
					n->useor = false;
					n->subLinkType = EXPR_SUBLINK;
					n->subselect = $2;
					$$ = (Node *)n;
				}
4549 4550 4551 4552 4553 4554 4555 4556 4557 4558
		| EXISTS '(' SubSelect ')'
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = NIL;
					n->oper = NIL;
					n->useor = false;
					n->subLinkType = EXISTS_SUBLINK;
					n->subselect = $3;
					$$ = (Node *)n;
				}
4559 4560
		;

4561 4562 4563 4564
/*
 * Supporting nonterminals for expressions.
 */

4565
opt_indirection:  '[' a_expr ']' opt_indirection
4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578
				{
					A_Indices *ai = makeNode(A_Indices);
					ai->lidx = NULL;
					ai->uidx = $2;
					$$ = lcons(ai, $4);
				}
		| '[' a_expr ':' a_expr ']' opt_indirection
				{
					A_Indices *ai = makeNode(A_Indices);
					ai->lidx = $2;
					ai->uidx = $4;
					$$ = lcons(ai, $6);
				}
4579
		| /*EMPTY*/
4580 4581
				{	$$ = NIL; }
		;
4582

4583
expr_list:  a_expr_or_null
4584
				{ $$ = lcons($1, NIL); }
4585
		| expr_list ',' a_expr_or_null
4586
				{ $$ = lappend($1, $3); }
4587
		| expr_list USING a_expr
4588 4589
				{ $$ = lappend($1, $3); }
		;
4590

4591
extract_list:  extract_arg FROM a_expr
4592 4593 4594 4595 4596 4597
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = $1;
					$$ = lappend(lcons((Node *)n,NIL), $3);
				}
4598
		| /*EMPTY*/
4599 4600
				{	$$ = NIL; }
		;
4601

4602 4603 4604
extract_arg:  datetime						{ $$ = $1; }
		| TIMEZONE_HOUR						{ $$ = "tz_hour"; }
		| TIMEZONE_MINUTE					{ $$ = "tz_minute"; }
4605 4606
		;

4607 4608 4609
/* position_list uses b_expr not a_expr to avoid conflict with general IN */

position_list:  b_expr IN b_expr
4610
				{	$$ = makeList($3, $1, -1); }
4611
		| /*EMPTY*/
4612 4613
				{	$$ = NIL; }
		;
4614

4615
substr_list:  expr_list substr_from substr_for
4616
				{
4617
					$$ = nconc(nconc($1,$2),$3);
4618
				}
4619
		| /*EMPTY*/
4620 4621
				{	$$ = NIL; }
		;
4622

4623
substr_from:  FROM expr_list
4624
				{	$$ = $2; }
4625
		| /*EMPTY*/
4626 4627 4628 4629 4630 4631
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Integer;
					n->val.val.ival = 1;
					$$ = lcons((Node *)n,NIL);
				}
4632
		;
4633

4634
substr_for:  FOR expr_list
4635
				{	$$ = $2; }
4636
		| /*EMPTY*/
4637 4638
				{	$$ = NIL; }
		;
4639

4640
trim_list:  a_expr FROM expr_list
4641
				{ $$ = lappend($3, $1); }
4642
		| FROM expr_list
4643
				{ $$ = $2; }
4644
		| expr_list
4645 4646
				{ $$ = $1; }
		;
4647

4648 4649
in_expr:  SubSelect
				{
4650 4651 4652
					SubLink *n = makeNode(SubLink);
					n->subselect = $1;
					$$ = (Node *)n;
4653 4654
				}
		| in_expr_nodes
4655
				{	$$ = (Node *)$1; }
4656
		;
4657

4658 4659 4660 4661
in_expr_nodes:  a_expr
				{	$$ = lcons($1, NIL); }
		| in_expr_nodes ',' a_expr
				{	$$ = lappend($1, $3); }
4662
		;
4663

4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690
/* Case clause
 * Define SQL92-style case clause.
 * Allow all four forms described in the standard:
 * - Full specification
 *  CASE WHEN a = b THEN c ... ELSE d END
 * - Implicit argument
 *  CASE a WHEN b THEN c ... ELSE d END
 * - Conditional NULL
 *  NULLIF(x,y)
 *  same as CASE WHEN x = y THEN NULL ELSE x END
 * - Conditional substitution from list, use first non-null argument
 *  COALESCE(a,b,...)
 * same as CASE WHEN a IS NOT NULL THEN a WHEN b IS NOT NULL THEN b ... END
 * - thomas 1998-11-09
 */
case_expr:  CASE case_arg when_clause_list case_default END_TRANS
				{
					CaseExpr *c = makeNode(CaseExpr);
					c->arg = $2;
					c->args = $3;
					c->defresult = $4;
					$$ = (Node *)c;
				}
		| NULLIF '(' a_expr ',' a_expr ')'
				{
					CaseExpr *c = makeNode(CaseExpr);
					CaseWhen *w = makeNode(CaseWhen);
4691 4692 4693 4694 4695 4696
/*
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Null;
					w->result = (Node *)n;
*/
					w->expr = makeA_Expr(OP, "=", $3, $5);
4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735
					c->args = lcons(w, NIL);
					c->defresult = $3;
					$$ = (Node *)c;
				}
		| COALESCE '(' expr_list ')'
				{
					CaseExpr *c = makeNode(CaseExpr);
					CaseWhen *w;
					List *l;
					foreach (l,$3)
					{
						w = makeNode(CaseWhen);
						w->expr = makeA_Expr(NOTNULL, NULL, lfirst(l), NULL);
						w->result = lfirst(l);
						c->args = lappend(c->args, w);
					}
					$$ = (Node *)c;
				}
		;

when_clause_list:  when_clause_list when_clause
				{ $$ = lappend($1, $2); }
		| when_clause
				{ $$ = lcons($1, NIL); }
		;

when_clause:  WHEN a_expr THEN a_expr_or_null
				{
					CaseWhen *w = makeNode(CaseWhen);
					w->expr = $2;
					w->result = $4;
					$$ = (Node *)w;
				}
		;

case_default:  ELSE a_expr_or_null				{ $$ = $2; }
		| /*EMPTY*/								{ $$ = NULL; }
		;

4736 4737
case_arg:  a_expr
				{	$$ = $1; }
4738 4739 4740 4741
		| /*EMPTY*/
				{	$$ = NULL; }
		;

4742
attr:  relation_name '.' attrs opt_indirection
4743 4744 4745 4746 4747
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
					$$->paramNo = NULL;
					$$->attrs = $3;
4748
					$$->indirection = $4;
4749
				}
4750
		| ParamNo '.' attrs opt_indirection
4751 4752 4753 4754 4755
				{
					$$ = makeNode(Attr);
					$$->relname = NULL;
					$$->paramNo = $1;
					$$->attrs = $3;
4756
					$$->indirection = $4;
4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767
				}
		;

attrs:	  attr_name
				{ $$ = lcons(makeString($1), NIL); }
		| attrs '.' attr_name
				{ $$ = lappend($1, makeString($3)); }
		| attrs '.' '*'
				{ $$ = lappend($1, makeString("*")); }
		;

4768 4769 4770

/*****************************************************************************
 *
4771
 *	target lists
4772 4773 4774
 *
 *****************************************************************************/

4775
/* Target lists as found in SELECT ... and INSERT VALUES ( ... ) */
4776

4777
target_list:  target_list ',' target_el
4778
				{	$$ = lappend($1, $3);  }
4779
		| target_el
4780 4781
				{	$$ = lcons($1, NIL);  }
		;
4782 4783

/* AS is not optional because shift/red conflict with unary ops */
4784
target_el:  a_expr_or_null AS ColLabel
4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823
				{
					$$ = makeNode(ResTarget);
					$$->name = $3;
					$$->indirection = NULL;
					$$->val = (Node *)$1;
				}
		| a_expr_or_null
				{
					$$ = makeNode(ResTarget);
					$$->name = NULL;
					$$->indirection = NULL;
					$$->val = (Node *)$1;
				}
		| relation_name '.' '*'
				{
					Attr *att = makeNode(Attr);
					att->relname = $1;
					att->paramNo = NULL;
					att->attrs = lcons(makeString("*"), NIL);
					att->indirection = NIL;
					$$ = makeNode(ResTarget);
					$$->name = NULL;
					$$->indirection = NULL;
					$$->val = (Node *)att;
				}
		| '*'
				{
					Attr *att = makeNode(Attr);
					att->relname = "*";
					att->paramNo = NULL;
					att->attrs = NULL;
					att->indirection = NIL;
					$$ = makeNode(ResTarget);
					$$->name = NULL;
					$$->indirection = NULL;
					$$->val = (Node *)att;
				}
		;

4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838
/* Target list as found in UPDATE table SET ... */

update_target_list:  update_target_list ',' update_target_el
				{	$$ = lappend($1,$3);  }
		| update_target_el
				{	$$ = lcons($1, NIL);  }
		;

update_target_el:  ColId opt_indirection '=' a_expr_or_null
				{
					$$ = makeNode(ResTarget);
					$$->name = $1;
					$$->indirection = $2;
					$$->val = (Node *)$4;
				}
4839 4840
		;

4841 4842 4843 4844 4845 4846
/*****************************************************************************
 *
 *	Names and constants
 *
 *****************************************************************************/

4847 4848 4849
relation_name:	SpecialRuleRelation
				{
					$$ = $1;
4850
					StrNCpy(saved_relname, $1, NAMEDATALEN);
4851 4852 4853
				}
		| ColId
				{
4854
					/* disallow refs to variable system tables */
4855
					if (strcmp(LogRelationName, $1) == 0
4856
					   || strcmp(VariableRelationName, $1) == 0)
4857
						elog(ERROR,"%s cannot be accessed by users",$1);
4858 4859
					else
						$$ = $1;
4860
					StrNCpy(saved_relname, $1, NAMEDATALEN);
4861 4862 4863
				}
		;

4864
database_name:			ColId			{ $$ = $1; };
4865
access_method:			IDENT			{ $$ = $1; };
4866
attr_name:				ColId			{ $$ = $1; };
4867
class:					IDENT			{ $$ = $1; };
4868
index_name:				ColId			{ $$ = $1; };
4869

4870 4871 4872 4873 4874
/* Functions
 * Include date/time keywords as SQL92 extension.
 * Include TYPE as a SQL92 unreserved keyword. - thomas 1997-10-05
 */
name:					ColId			{ $$ = $1; };
4875
func_name:				ColId			{ $$ = xlateSqlFunc($1); };
4876 4877

file_name:				Sconst			{ $$ = $1; };
Bruce Momjian's avatar
Bruce Momjian committed
4878
/* NOT USED recipe_name:			IDENT			{ $$ = $1; };*/
4879

4880 4881 4882
/* Constants
 * Include TRUE/FALSE for SQL3 support. - thomas 1997-10-24
 */
4883
AexprConst:  Iconst
4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Integer;
					n->val.val.ival = $1;
					$$ = (Node *)n;
				}
		| FCONST
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Float;
					n->val.val.dval = $1;
					$$ = (Node *)n;
				}
		| Sconst
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = $1;
					$$ = (Node *)n;
				}
4904 4905 4906 4907
		/* this rule formerly used Typename, but that causes reduce conflicts
		 * with subscripted column names ...
		 */
		| SimpleTypename Sconst
4908 4909 4910 4911 4912 4913 4914
				{
					A_Const *n = makeNode(A_Const);
					n->typename = $1;
					n->val.type = T_String;
					n->val.val.str = $2;
					$$ = (Node *)n;
				}
4915 4916
		| ParamNo
				{	$$ = (Node *)$1;  }
4917 4918 4919 4920 4921
		| TRUE_P
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "t";
4922 4923
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
4924
					n->typename->typmod = -1;
4925 4926 4927 4928 4929 4930 4931
					$$ = (Node *)n;
				}
		| FALSE_P
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "f";
4932 4933
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
4934
					n->typename->typmod = -1;
4935 4936
					$$ = (Node *)n;
				}
4937
		;
4938

4939
ParamNo:  PARAM opt_indirection
4940 4941 4942
				{
					$$ = makeNode(ParamNo);
					$$->number = $1;
4943
					$$->indirection = $2;
4944 4945
				}
		;
4946

4947 4948
Iconst:  ICONST							{ $$ = $1; };
Sconst:  SCONST							{ $$ = $1; };
4949
UserId:  IDENT							{ $$ = $1; };
4950

4951 4952 4953 4954 4955
/* Column and type identifier
 * Does not include explicit datetime types
 *  since these must be decoupled in Typename syntax.
 * Use ColId for most identifiers. - thomas 1997-10-21
 */
4956 4957 4958 4959 4960 4961 4962
TypeId:  ColId
			{	$$ = xlateSqlType($1); }
		| numeric
			{	$$ = xlateSqlType($1); }
		| character
			{	$$ = xlateSqlType($1); }
		;
4963 4964 4965
/* Column identifier
 * Include date/time keywords as SQL92 extension.
 * Include TYPE as a SQL92 unreserved keyword. - thomas 1997-10-05
4966 4967 4968 4969
 * Add other keywords. Note that as the syntax expands,
 *  some of these keywords will have to be removed from this
 *  list due to shift/reduce conflicts in yacc. If so, move
 *  down to the ColLabel entity. - thomas 1997-11-06
4970
 */
4971
ColId:  IDENT							{ $$ = $1; }
4972
		| datetime						{ $$ = $1; }
4973
		| ABSOLUTE						{ $$ = "absolute"; }
4974
		| ACCESS						{ $$ = "access"; }
4975
		| ACTION						{ $$ = "action"; }
4976 4977 4978 4979
		| AFTER							{ $$ = "after"; }
		| AGGREGATE						{ $$ = "aggregate"; }
		| BACKWARD						{ $$ = "backward"; }
		| BEFORE						{ $$ = "before"; }
4980
		| CACHE							{ $$ = "cache"; }
4981
		| COMMENT						{ $$ = "comment"; }
4982
		| COMMITTED						{ $$ = "committed"; }
4983
		| CONSTRAINTS					{ $$ = "constraints"; }
4984 4985
		| CREATEDB						{ $$ = "createdb"; }
		| CREATEUSER					{ $$ = "createuser"; }
4986
		| CYCLE							{ $$ = "cycle"; }
4987
		| DATABASE						{ $$ = "database"; }
4988 4989
		| DEFERRABLE					{ $$ = "deferrable"; }
		| DEFERRED						{ $$ = "deferred"; }
4990
		| DELIMITERS					{ $$ = "delimiters"; }
4991 4992
		| DOUBLE						{ $$ = "double"; }
		| EACH							{ $$ = "each"; }
4993
		| ENCODING						{ $$ = "encoding"; }
4994
		| EXCLUSIVE						{ $$ = "exclusive"; }
4995
		| FORWARD						{ $$ = "forward"; }
4996
		| FUNCTION						{ $$ = "function"; }
4997
		| HANDLER						{ $$ = "handler"; }
4998
		| IMMEDIATE						{ $$ = "immediate"; }
4999
		| INCREMENT						{ $$ = "increment"; }
5000
		| INDEX							{ $$ = "index"; }
5001
		| INHERITS						{ $$ = "inherits"; }
5002
		| INITIALLY						{ $$ = "initially"; }
5003
		| INSENSITIVE					{ $$ = "insensitive"; }
5004 5005
		| INSTEAD						{ $$ = "instead"; }
		| ISNULL						{ $$ = "isnull"; }
5006
		| ISOLATION						{ $$ = "isolation"; }
5007 5008
		| KEY							{ $$ = "key"; }
		| LANGUAGE						{ $$ = "language"; }
5009
		| LANCOMPILER					{ $$ = "lancompiler"; }
5010
		| LEVEL							{ $$ = "level"; }
5011 5012
		| LOCATION						{ $$ = "location"; }
		| MATCH							{ $$ = "match"; }
5013 5014
		| MAXVALUE						{ $$ = "maxvalue"; }
		| MINVALUE						{ $$ = "minvalue"; }
5015
		| MODE							{ $$ = "mode"; }
5016
		| NEXT							{ $$ = "next"; }
5017 5018 5019 5020
		| NOCREATEDB					{ $$ = "nocreatedb"; }
		| NOCREATEUSER					{ $$ = "nocreateuser"; }
		| NOTHING						{ $$ = "nothing"; }
		| NOTNULL						{ $$ = "notnull"; }
5021
		| OF							{ $$ = "of"; }
5022
		| OIDS							{ $$ = "oids"; }
5023
		| ONLY							{ $$ = "only"; }
5024 5025
		| OPERATOR						{ $$ = "operator"; }
		| OPTION						{ $$ = "option"; }
5026
		| PASSWORD						{ $$ = "password"; }
5027
		| PENDANT						{ $$ = "pendant"; }
5028
		| PRIOR							{ $$ = "prior"; }
5029
		| PRIVILEGES					{ $$ = "privileges"; }
5030
		| PROCEDURAL					{ $$ = "procedural"; }
5031 5032
		| READ							{ $$ = "read"; }
		| RELATIVE						{ $$ = "relative"; }
5033
		| RENAME						{ $$ = "rename"; }
5034
		| RESTRICT						{ $$ = "restrict"; }
5035
		| RETURNS						{ $$ = "returns"; }
5036
		| ROW							{ $$ = "row"; }
5037
		| RULE							{ $$ = "rule"; }
5038
		| SCROLL						{ $$ = "scroll"; }
5039
		| SEQUENCE						{ $$ = "sequence"; }
5040
		| SERIAL						{ $$ = "serial"; }
5041 5042
		| SERIALIZABLE					{ $$ = "serializable"; }
		| SHARE							{ $$ = "share"; }
5043
		| START							{ $$ = "start"; }
5044
		| STATEMENT						{ $$ = "statement"; }
5045 5046
		| STDIN							{ $$ = "stdin"; }
		| STDOUT						{ $$ = "stdout"; }
5047
		| SYSID							{ $$ = "sysid"; }
5048
		| TIME							{ $$ = "time"; }
5049
		| TIMESTAMP						{ $$ = "timestamp"; }
5050 5051
		| TIMEZONE_HOUR					{ $$ = "timezone_hour"; }
		| TIMEZONE_MINUTE				{ $$ = "timezone_minute"; }
5052
		| TRIGGER						{ $$ = "trigger"; }
5053
		| TRUNCATE						{ $$ = "truncate"; }
5054
		| TRUSTED						{ $$ = "trusted"; }
5055
		| TYPE_P						{ $$ = "type"; }
5056
		| VALID							{ $$ = "valid"; }
5057 5058
		| VERSION						{ $$ = "version"; }
		| ZONE							{ $$ = "zone"; }
5059 5060 5061 5062 5063 5064 5065 5066
		;

/* Column label
 * Allowed labels in "AS" clauses.
 * Include TRUE/FALSE SQL3 reserved words for Postgres backward
 *  compatibility. Cannot allow this for column names since the
 *  syntax would not distinguish between the constant value and
 *  a column name. - thomas 1997-10-24
5067 5068 5069
 * Add other keywords to this list. Note that they appear here
 *  rather than in ColId if there was a shift/reduce conflict
 *  when used as a full identifier. - thomas 1997-11-06
5070 5071
 */
ColLabel:  ColId						{ $$ = $1; }
5072 5073 5074
		| ABORT_TRANS					{ $$ = "abort"; }
		| ANALYZE						{ $$ = "analyze"; }
		| BINARY						{ $$ = "binary"; }
5075
		| CASE							{ $$ = "case"; }
5076
		| CLUSTER						{ $$ = "cluster"; }
5077
		| COALESCE						{ $$ = "coalesce"; }
5078
		| CONSTRAINT					{ $$ = "constraint"; }
5079 5080 5081
		| COPY							{ $$ = "copy"; }
		| CURRENT						{ $$ = "current"; }
		| DO							{ $$ = "do"; }
5082 5083
		| ELSE							{ $$ = "else"; }
		| END_TRANS						{ $$ = "end"; }
5084 5085 5086
		| EXPLAIN						{ $$ = "explain"; }
		| EXTEND						{ $$ = "extend"; }
		| FALSE_P						{ $$ = "false"; }
5087
		| FOREIGN						{ $$ = "foreign"; }
5088
		| GLOBAL						{ $$ = "global"; }
5089
		| GROUP							{ $$ = "group"; }
5090
		| LISTEN						{ $$ = "listen"; }
5091
		| LOAD							{ $$ = "load"; }
5092
		| LOCAL							{ $$ = "local"; }
5093 5094 5095 5096
		| LOCK_P						{ $$ = "lock"; }
		| MOVE							{ $$ = "move"; }
		| NEW							{ $$ = "new"; }
		| NONE							{ $$ = "none"; }
5097
		| NULLIF						{ $$ = "nullif"; }
5098 5099 5100
		| ORDER							{ $$ = "order"; }
		| POSITION						{ $$ = "position"; }
		| PRECISION						{ $$ = "precision"; }
5101 5102 5103
		| RESET							{ $$ = "reset"; }
		| SETOF							{ $$ = "setof"; }
		| SHOW							{ $$ = "show"; }
5104
		| TABLE							{ $$ = "table"; }
5105
		| THEN							{ $$ = "then"; }
5106
		| TRANSACTION					{ $$ = "transaction"; }
5107
		| TRUE_P						{ $$ = "true"; }
5108 5109
		| VACUUM						{ $$ = "vacuum"; }
		| VERBOSE						{ $$ = "verbose"; }
5110
		| WHEN							{ $$ = "when"; }
5111
		;
5112 5113

SpecialRuleRelation:  CURRENT
5114 5115 5116 5117
				{
					if (QueryIsRule)
						$$ = "*CURRENT*";
					else
Bruce Momjian's avatar
Bruce Momjian committed
5118
						elog(ERROR,"CURRENT used in non-rule query");
5119 5120 5121 5122 5123 5124
				}
		| NEW
				{
					if (QueryIsRule)
						$$ = "*NEW*";
					else
Bruce Momjian's avatar
Bruce Momjian committed
5125
						elog(ERROR,"NEW used in non-rule query");
5126 5127
				}
		;
5128 5129 5130

%%

5131 5132
static Node *
makeA_Expr(int oper, char *opname, Node *lexpr, Node *rexpr)
5133
{
5134 5135 5136 5137 5138 5139
	A_Expr *a = makeNode(A_Expr);
	a->oper = oper;
	a->opname = opname;
	a->lexpr = lexpr;
	a->rexpr = rexpr;
	return (Node *)a;
5140 5141
}

Bruce Momjian's avatar
Bruce Momjian committed
5142 5143
/* makeRowExpr()
 * Generate separate operator nodes for a single row descriptor expression.
5144 5145
 * Perhaps this should go deeper in the parser someday...
 * - thomas 1997-12-22
Bruce Momjian's avatar
Bruce Momjian committed
5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
 */
static Node *
makeRowExpr(char *opr, List *largs, List *rargs)
{
	Node *expr = NULL;
	Node *larg, *rarg;

	if (length(largs) != length(rargs))
		elog(ERROR,"Unequal number of entries in row expression");

	if (lnext(largs) != NIL)
		expr = makeRowExpr(opr,lnext(largs),lnext(rargs));

	larg = lfirst(largs);
	rarg = lfirst(rargs);

	if ((strcmp(opr, "=") == 0)
	 || (strcmp(opr, "<") == 0)
	 || (strcmp(opr, "<=") == 0)
	 || (strcmp(opr, ">") == 0)
	 || (strcmp(opr, ">=") == 0))
	{
		if (expr == NULL)
			expr = makeA_Expr(OP, opr, larg, rarg);
		else
			expr = makeA_Expr(AND, NULL, expr, makeA_Expr(OP, opr, larg, rarg));
	}
	else if (strcmp(opr, "<>") == 0)
	{
		if (expr == NULL)
			expr = makeA_Expr(OP, opr, larg, rarg);
		else
			expr = makeA_Expr(OR, NULL, expr, makeA_Expr(OP, opr, larg, rarg));
	}
	else
	{
		elog(ERROR,"Operator '%s' not implemented for row expressions",opr);
	}

	return expr;
}

5188
static void
5189 5190 5191 5192 5193 5194
mapTargetColumns(List *src, List *dst)
{
	ColumnDef *s;
	ResTarget *d;

	if (length(src) != length(dst))
Bruce Momjian's avatar
Bruce Momjian committed
5195
		elog(ERROR,"CREATE TABLE/AS SELECT has mismatched column count");
5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207

	while ((src != NIL) && (dst != NIL))
	{
		s = (ColumnDef *)lfirst(src);
		d = (ResTarget *)lfirst(dst);

		d->name = s->colname;

		src = lnext(src);
		dst = lnext(dst);
	}
} /* mapTargetColumns() */
5208

5209

5210
/* xlateSqlFunc()
5211
 * Convert alternate type names to internal Postgres types.
5212 5213
 * Do not convert "float", since that is handled elsewhere
 *  for FLOAT(p) syntax.
5214
 */
5215
static char *
5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228
xlateSqlFunc(char *name)
{
	if (!strcasecmp(name,"character_length")
	 || !strcasecmp(name,"char_length"))
		return "length";
	else
		return name;
} /* xlateSqlFunc() */

/* xlateSqlType()
 * Convert alternate type names to internal Postgres types.
 */
static char *
5229 5230
xlateSqlType(char *name)
{
5231 5232
	if (!strcasecmp(name,"int")
	 || !strcasecmp(name,"integer"))
5233
		return "int4";
5234 5235
	else if (!strcasecmp(name, "smallint"))
		return "int2";
5236 5237
	else if (!strcasecmp(name, "real")
	 || !strcasecmp(name, "float"))
5238 5239 5240
		return "float8";
	else if (!strcasecmp(name, "interval"))
		return "timespan";
5241 5242
	else if (!strcasecmp(name, "boolean"))
		return "bool";
5243 5244
	else
		return name;
5245
} /* xlateSqlType() */
5246

5247

5248 5249
void parser_init(Oid *typev, int nargs)
{
5250
	QueryIsRule = FALSE;
5251
	saved_relname[0]= '\0';
5252

5253
	param_type_init(typev, nargs);
5254
}
5255

5256

5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275
/*
 * param_type_init()
 *
 * keep enough information around fill out the type of param nodes
 * used in postquel functions
 */
static void
param_type_init(Oid *typev, int nargs)
{
	pfunc_num_args = nargs;
	param_type_info = typev;
}

Oid param_type(int t)
{
	if ((t > pfunc_num_args) || (t == 0))
		return InvalidOid;
	return param_type_info[t - 1];
}
5276 5277

/*
Bruce Momjian's avatar
Bruce Momjian committed
5278 5279 5280
 *	The optimizer doesn't like '-' 4 for index use.  It only checks for
 *	Var '=' Const.  It wants an integer of -4, so we try to merge the
 *	minus into the constant.
5281 5282 5283 5284 5285
 *
 *	This code is no longer essential as of 10/1999, since the optimizer
 *	now has a constant-subexpression simplifier.  However, we can save
 *	a few cycles throughout the parse and rewrite stages if we collapse
 *	the minus into the constant sooner rather than later...
5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306
 */
static Node *doNegate(Node *n)
{
	if (IsA(n, A_Const))
	{
		A_Const *con = (A_Const *)n;

		if (con->val.type == T_Integer)
		{
			con->val.val.ival = -con->val.val.ival;
			return n;
		}
		if (con->val.type == T_Float)
		{
			con->val.val.dval = -con->val.val.dval;
			return n;
		}
	}

	return makeA_Expr(OP, "-", NULL, n);
}