gram.y 149 KB
Newer Older
1
%{
2

3
/*#define YYDEBUG 1*/
4
/*-------------------------------------------------------------------------
5
 *
6
 * gram.y
7
 *	  POSTGRES SQL YACC rules/actions
8
 *
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
9 10
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
11 12 13
 *
 *
 * IDENTIFICATION
14
 *	  $Header: /cvsroot/pgsql/src/backend/parser/gram.y,v 2.216 2001/01/17 17:26:45 momjian Exp $
15 16
 *
 * HISTORY
17 18 19
 *	  AUTHOR			DATE			MAJOR EVENT
 *	  Andrew Yu			Sept, 1994		POSTQUEL to SQL conversion
 *	  Andrew Yu			Oct, 1994		lispy code conversion
20 21
 *
 * NOTES
22 23
 *	  CAPITALS are used to represent terminal symbols.
 *	  non-capitals are used to represent non-terminals.
24 25
 *	  SQL92-specific syntax is separated from plain SQL/Postgres syntax
 *	  to help isolate the non-extensible portions of the parser.
26
 *
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
 *	  In general, nothing in this file should initiate database accesses
 *	  nor depend on changeable state (such as SET variables).  If you do
 *	  database accesses, your code will fail when we have aborted the
 *	  current transaction and are just parsing commands to find the next
 *	  ROLLBACK or COMMIT.  If you make use of SET variables, then you
 *	  will do the wrong thing in multi-query strings like this:
 *			SET SQL_inheritance TO off; SELECT * FROM foo;
 *	  because the entire string is parsed by gram.y before the SET gets
 *	  executed.  Anything that depends on the database or changeable state
 *	  should be handled inside parse_analyze() so that it happens at the
 *	  right time not the wrong time.  The handling of SQL_inheritance is
 *	  a good example.
 *
 * WARNINGS
 *	  If you use a list, make sure the datum is a node so that the printing
 *	  routines work.
 *
 *	  Sometimes we assign constants to makeStrings. Make sure we don't free
45
 *	  those.
46 47 48 49
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
50

51 52
#include <ctype.h>

53
#include "access/htup.h"
Bruce Momjian's avatar
Bruce Momjian committed
54 55
#include "catalog/catname.h"
#include "catalog/pg_type.h"
56
#include "nodes/params.h"
57
#include "nodes/parsenodes.h"
Bruce Momjian's avatar
Bruce Momjian committed
58
#include "parser/gramparse.h"
59
#include "storage/lmgr.h"
Bruce Momjian's avatar
Bruce Momjian committed
60
#include "utils/acl.h"
61
#include "utils/numeric.h"
62

Marc G. Fournier's avatar
Marc G. Fournier committed
63
#ifdef MULTIBYTE
64
#include "mb/pg_wchar.h"
65
#else
66 67
#define GetStandardEncoding()	0		/* SQL_ASCII */
#define GetStandardEncodingName()	"SQL_ASCII"
68 69
#endif

70 71
extern List *parsetree;			/* final parse result is delivered here */

72
static bool QueryIsRule = FALSE;
73 74
static Oid	*param_type_info;
static int	pfunc_num_args;
75

76

77
/*
78
 * If you need access to certain yacc-generated variables and find that
79 80 81 82 83
 * they're static by default, uncomment the next line.  (this is not a
 * problem, yet.)
 */
/*#define __YYSCLASS*/

84
static char *xlateSqlFunc(char *);
85
static char *xlateSqlType(char *);
86
static Node *makeA_Expr(int oper, char *opname, Node *lexpr, Node *rexpr);
87
static Node *makeTypeCast(Node *arg, TypeName *typename);
Bruce Momjian's avatar
Bruce Momjian committed
88
static Node *makeRowExpr(char *opr, List *largs, List *rargs);
89
static void mapTargetColumns(List *source, List *target);
90 91 92 93 94
static SelectStmt *findLeftmostSelect(SelectStmt *node);
static void insertSelectOptions(SelectStmt *stmt,
								List *sortClause, List *forUpdate,
								Node *limitOffset, Node *limitCount);
static Node *makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg);
95
static bool exprIsNullConstant(Node *arg);
96
static Node *doNegate(Node *n);
97
static void doNegateFloat(Value *v);
98

99 100 101
%}


102 103 104 105 106 107
%union
{
	int					ival;
	char				chr;
	char				*str;
	bool				boolean;
108
	JoinType			jtype;
109
	InhOption			inhOpt;
110 111 112 113 114
	List				*list;
	Node				*node;
	Value				*value;

	Attr				*attr;
115
	Ident				*ident;
116 117 118 119

	TypeName			*typnam;
	DefElem				*defelt;
	SortGroupBy			*sortgroupby;
120
	JoinExpr			*jexpr;
121 122 123 124 125 126 127 128 129
	IndexElem			*ielem;
	RangeVar			*range;
	A_Indices			*aind;
	ResTarget			*target;
	ParamNo				*paramno;

	VersionStmt			*vstmt;
	DefineStmt			*dstmt;
	RuleStmt			*rstmt;
130
	InsertStmt			*istmt;
131 132
}

133
%type <node>	stmt,
134 135 136 137 138 139 140 141
		AlterGroupStmt, AlterSchemaStmt, AlterTableStmt, AlterUserStmt,
		ClosePortalStmt, ClusterStmt, CommentStmt, ConstraintsSetStmt,
		CopyStmt, CreateAsStmt, CreateGroupStmt, CreatePLangStmt,
		CreateSchemaStmt, CreateSeqStmt, CreateStmt, CreateTrigStmt,
		CreateUserStmt, CreatedbStmt, CursorStmt, DefineStmt, DeleteStmt,
		DropGroupStmt, DropPLangStmt, DropSchemaStmt, DropStmt, DropTrigStmt,
		DropUserStmt, DropdbStmt, ExplainStmt, ExtendStmt, FetchStmt,
		GrantStmt, IndexStmt, InsertStmt, ListenStmt, LoadStmt, LockStmt,
142
		NotifyStmt, OptimizableStmt, ProcedureStmt, ReindexStmt,
143
		RemoveAggrStmt, RemoveFuncStmt, RemoveOperStmt,
144
		RenameStmt, RevokeStmt, RuleActionStmt, RuleActionStmtOrEmpty,
145
		RuleStmt, SelectStmt, TransactionStmt, TruncateStmt,
146
		UnlistenStmt, UpdateStmt, VacuumStmt, VariableResetStmt,
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
147
		VariableSetStmt, VariableShowStmt, ViewStmt, CheckPointStmt
148

149 150
%type <node>	select_no_parens, select_with_parens, select_clause,
				simple_select
151

152 153 154
%type <node>    alter_column_action
%type <ival>    drop_behavior

155
%type <list>	createdb_opt_list, createdb_opt_item
156

157
%type <ival>	opt_lock, lock_type
Hiroshi Inoue's avatar
Hiroshi Inoue committed
158
%type <boolean>	opt_lmode, opt_force
159

160
%type <ival>    user_createdb_clause, user_createuser_clause
161
%type <str>		user_passwd_clause
Bruce Momjian's avatar
Bruce Momjian committed
162
%type <ival>            sysid_clause
163
%type <str>		user_valid_clause
164
%type <list>	user_list, user_group_clause, users_in_new_group_clause
165

166
%type <boolean>	TriggerActionTime, TriggerForSpec, PLangTrusted, opt_procedural
167

168 169
%type <str>		OptConstrFromTable

170 171
%type <str>		TriggerEvents
%type <value>	TriggerFuncArg
172

173
%type <str>		relation_name, copy_file_name, copy_delimiter, copy_null,
174
		database_name, access_method_clause, access_method, attr_name,
175
		class, index_name, name, func_name, file_name
176

177
%type <str>		opt_id,
178
		all_Op, MathOp, opt_name,
179
		OptUseOp, opt_class, SpecialRuleRelation
180

181
%type <str>		opt_level, opt_encoding
182 183
%type <str>		privileges, operation_commalist, grantee
%type <chr>		operation, TriggerOneEvent
184

185
%type <list>	stmtblock, stmtmulti,
186
		into_clause, OptTempTableName, relation_name_list,
187
		OptTableElementList, OptInherit, definition, opt_distinct,
188
		opt_with, func_args, func_args_list, func_as,
189
		oper_argtypes, RuleActionList, RuleActionMulti,
190 191
		opt_column_list, columnList, opt_va_list, va_list,
		sort_clause, sortby_list, index_params, index_list, name_list,
192
		from_clause, from_list, opt_array_bounds,
193
		expr_list, attrs, target_list, update_target_list,
194
		def_list, opt_indirection, group_clause, TriggerFuncArgs,
195
		select_limit, opt_select_limit
196

197
%type <typnam>	func_arg, func_return, aggr_argtype
198

199
%type <boolean>	opt_arg, TriggerForOpt, TriggerForType, OptTemp
200

201
%type <list>	for_update_clause, opt_for_update_clause, update_list
202
%type <boolean>	opt_all
203
%type <boolean>	opt_table
204
%type <boolean>	opt_chain, opt_trans
205

206
%type <node>	join_outer, join_qual
207
%type <jtype>	join_type
208

209
%type <list>	extract_list, position_list
210
%type <list>	substr_list, trim_list
211
%type <list>	opt_interval
212
%type <node>	substr_from, substr_for
213

214 215 216 217
%type <boolean>	opt_binary, opt_using, opt_instead, opt_cursor
%type <boolean>	opt_with_copy, index_opt_unique, opt_verbose, opt_analyze

%type <inhOpt>	opt_inh_star, opt_only
218

219
%type <ival>	copy_dirn, direction, reindex_type, drop_type,
Bruce Momjian's avatar
Bruce Momjian committed
220 221
		opt_column, event, comment_type, comment_cl,
		comment_ag, comment_fn, comment_op, comment_tg
222

Bruce Momjian's avatar
Bruce Momjian committed
223
%type <ival>	fetch_how_many
224

225 226
%type <node>	select_limit_value, select_offset_value

Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
227 228 229
%type <list>	OptSeqList
%type <defelt>	OptSeqElem

230
%type <istmt>	insert_rest
231

232
%type <node>	OptTableElement, ConstraintElem
233
%type <node>	columnDef
234
%type <defelt>	def_elem
235
%type <node>	def_arg, columnElem, where_clause,
236
				a_expr, b_expr, c_expr, AexprConst,
237
				in_expr, having_clause
238
%type <list>	row_descriptor, row_list, in_expr_nodes
239
%type <node>	row_expr
240 241
%type <node>	case_expr, case_arg, when_clause, case_default
%type <list>	when_clause_list
242
%type <ival>	sub_type
243 244
%type <list>	OptCreateAs, CreateAsList
%type <node>	CreateAsElement
245
%type <value>	NumericOnly, FloatOnly, IntegerOnly
246
%type <attr>	event_object, attr, alias_clause
247
%type <sortgroupby>		sortby
248
%type <ielem>	index_elem, func_index
249 250 251
%type <node>	table_ref
%type <jexpr>	joined_table
%type <range>	relation_expr
252
%type <target>	target_el, update_target_el
253
%type <paramno> ParamNo
254

255
%type <typnam>	Typename, SimpleTypename, ConstTypename
256 257
				GenericType, Numeric, Geometric, Character, ConstDatetime, ConstInterval, Bit
%type <str>		character, datetime, bit
258
%type <str>		extract_arg
259
%type <str>		opt_charset, opt_collate
260 261
%type <str>		opt_float
%type <ival>	opt_numeric, opt_decimal
262 263
%type <boolean>	opt_varying, opt_timezone

264
%type <ival>	Iconst
265
%type <str>		Sconst, comment_text
266
%type <str>		UserId, opt_boolean, var_value, zone_value
267
%type <str>		ColId, ColLabel, TokenId
268

269
%type <node>	TableConstraint
270 271
%type <list>	ColQualList
%type <node>	ColConstraint, ColConstraintElem, ConstraintAttr
272
%type <ival>	key_actions, key_delete, key_update, key_reference
Jan Wieck's avatar
Jan Wieck committed
273
%type <str>		key_match
274 275
%type <ival>	ConstraintAttributeSpec, ConstraintDeferrabilitySpec,
				ConstraintTimeSpec
276

277 278 279 280
%type <list>	constraints_set_list
%type <list>	constraints_set_namelist
%type <boolean>	constraints_set_mode

281 282
/*
 * If you make any token changes, remember to:
283 284
 *		- use "yacc -d" and update parse.h
 *		- update the keyword table in parser/keywords.c
285 286
 */

287 288 289 290 291 292 293
/* 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
294 295
 * NOTE: Whenever possible, try to add new keywords to the ColId list,
 * or failing that, at least to the ColLabel list.
296 297 298
 */

/* Keywords (in SQL92 reserved words) */
299
%token	ABSOLUTE, ACTION, ADD, ALL, ALTER, AND, ANY, AS, ASC, AT,
300
		BEGIN_TRANS, BETWEEN, BOTH, BY,
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
301
		CASCADE, CASE, CAST, CHAR, CHARACTER, CHECK, CLOSE, 
302
		COALESCE, COLLATE, COLUMN, COMMIT,
303
		CONSTRAINT, CONSTRAINTS, CREATE, CROSS, CURRENT_DATE,
304
		CURRENT_TIME, CURRENT_TIMESTAMP, CURRENT_USER, CURSOR,
305 306
		DAY_P, DEC, DECIMAL, DECLARE, DEFAULT, DELETE, DESC,
		DISTINCT, DOUBLE, DROP,
307
		ELSE, END_TRANS, ESCAPE, EXCEPT, EXECUTE, EXISTS, EXTRACT,
308
		FALSE_P, FETCH, FLOAT, FOR, FOREIGN, FROM, FULL,
309
		GLOBAL, GRANT, GROUP, HAVING, HOUR_P,
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
310 311
		IN, INNER_P, INSENSITIVE, INSERT, INTERSECT, INTERVAL, INTO, IS,
		ISOLATION, JOIN, KEY, LANGUAGE, LEADING, LEFT, LEVEL, LIKE, LOCAL,
312
		MATCH, MINUTE_P, MONTH_P, NAMES,
313
		NATIONAL, NATURAL, NCHAR, NEXT, NO, NOT, NULLIF, NULL_P, NUMERIC,
314
		OF, OLD, ON, ONLY, OPTION, OR, ORDER, OUTER_P, OVERLAPS,
315 316
		PARTIAL, POSITION, PRECISION, PRIMARY, PRIOR, PRIVILEGES, PROCEDURE, PUBLIC,
		READ, REFERENCES, RELATIVE, REVOKE, RIGHT, ROLLBACK,
317
		SCHEMA, SCROLL, SECOND_P, SELECT, SESSION, SESSION_USER, SET, SOME, SUBSTRING,
318
		TABLE, TEMPORARY, THEN, TIME, TIMESTAMP, TIMEZONE_HOUR,
Bruce Momjian's avatar
Bruce Momjian committed
319
		TIMEZONE_MINUTE, TO, TRAILING, TRANSACTION, TRIM, TRUE_P,
320
		UNION, UNIQUE, UPDATE, USER, USING,
321
		VALUES, VARCHAR, VARYING, VIEW,
322
		WHEN, WHERE, WITH, WORK, YEAR_P, ZONE
323 324

/* Keywords (in SQL3 reserved words) */
325
%token	CHAIN, CHARACTERISTICS,
326 327 328 329
		DEFERRABLE, DEFERRED,
		IMMEDIATE, INITIALLY, INOUT,
		OFF, OUT,
		PATH_P, PENDANT,
330
		RESTRICT,
331 332
        TRIGGER,
		WITHOUT
333 334

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

337 338 339 340 341 342
/* 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?
 */
343
%token	ABORT_TRANS, ACCESS, AFTER, AGGREGATE, ANALYSE, ANALYZE,
344
		BACKWARD, BEFORE, BINARY, BIT,
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
345
		CACHE, CHECKPOINT, CLUSTER, COMMENT, COPY, CREATEDB, CREATEUSER, CYCLE,
346 347
		DATABASE, DELIMITERS, DO,
		EACH, ENCODING, EXCLUSIVE, EXPLAIN, EXTEND,
Hiroshi Inoue's avatar
Hiroshi Inoue committed
348
		FORCE, FORWARD, FUNCTION, HANDLER,
349
		ILIKE, INCREMENT, INDEX, INHERITS, INSTEAD, ISNULL,
350
		LANCOMPILER, LIMIT, LISTEN, LOAD, LOCATION, LOCK_P,
351
		MAXVALUE, MINVALUE, MODE, MOVE,
352
		NEW, NOCREATEDB, NOCREATEUSER, NONE, NOTHING, NOTIFY, NOTNULL,
353
		OFFSET, OIDS, OPERATOR, OWNER, PASSWORD, PROCEDURAL,
Hiroshi Inoue's avatar
Hiroshi Inoue committed
354
		REINDEX, RENAME, RESET, RETURNS, ROW, RULE,
Bruce Momjian's avatar
Bruce Momjian committed
355
		SEQUENCE, SERIAL, SETOF, SHARE, SHOW, START, STATEMENT, STDIN, STDOUT, SYSID,
356
		TEMP, TEMPLATE, TOAST, TRUNCATE, TRUSTED, 
357
		UNLISTEN, UNTIL, VACUUM, VALID, VERBOSE, VERSION
358

359 360 361 362 363 364
/* The grammar thinks these are keywords, but they are not in the keywords.c
 * list and so can never be entered directly.  The filter in parser.c
 * creates these tokens when required.
 */
%token			UNIONJOIN

365
/* Special keywords, not in the query language - see the "lex" file */
366
%token <str>	IDENT, FCONST, SCONST, BITCONST, Op
367 368
%token <ival>	ICONST, PARAM

369
/* these are not real. they are here so that they get generated as #define's*/
370
%token			OP
371

372
/* precedence: lowest to highest */
373 374 375
%left		UNION EXCEPT
%left		INTERSECT
%left		JOIN UNIONJOIN CROSS LEFT FULL RIGHT INNER_P NATURAL
376 377 378 379
%left		OR
%left		AND
%right		NOT
%right		'='
380
%nonassoc	'<' '>'
381
%nonassoc	LIKE ILIKE
382
%nonassoc	ESCAPE
383
%nonassoc	OVERLAPS
384 385
%nonassoc	BETWEEN
%nonassoc	IN
386
%left		Op				/* multi-character ops and user-defined operators */
387 388
%nonassoc	NOTNULL
%nonassoc	ISNULL
389
%nonassoc	NULL_P
390 391
%nonassoc	IS
%left		'+' '-'
392 393
%left		'*' '/' '%'
%left		'^'
394
/* Unary Operators */
395
%left		AT
396 397 398
%right		UMINUS
%left		'.'
%left		'[' ']'
399
%left		'(' ')'
400
%left		TYPECAST
401 402
%%

403 404 405 406 407 408
/*
 *	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
409 410
				{ parsetree = $1; }
		;
411

412
/* the thrashing around here is to discard "empty" statements... */
413
stmtmulti:  stmtmulti ';' stmt
414
				{ if ($3 != (Node *)NULL)
415 416 417 418
					$$ = lappend($1, $3);
				  else
					$$ = $1;
				}
419
		| stmt
420
				{ if ($1 != (Node *)NULL)
421
					$$ = makeList1($1);
422
				  else
423
					$$ = NIL;
424
				}
425
		;
426

427 428
stmt :	AlterSchemaStmt
		| AlterTableStmt
429
		| AlterGroupStmt
430
		| AlterUserStmt
431 432 433
		| ClosePortalStmt
		| CopyStmt
		| CreateStmt
434
		| CreateAsStmt
435
		| CreateSchemaStmt
436
		| CreateGroupStmt
437
		| CreateSeqStmt
438
		| CreatePLangStmt
439
		| CreateTrigStmt
440
		| CreateUserStmt
441 442
		| ClusterStmt
		| DefineStmt
443
		| DropStmt		
444
		| DropSchemaStmt
445
		| TruncateStmt
446
		| CommentStmt
447
		| DropGroupStmt
448
		| DropPLangStmt
449
		| DropTrigStmt
450
		| DropUserStmt
451 452 453 454 455 456
		| ExtendStmt
		| ExplainStmt
		| FetchStmt
		| GrantStmt
		| IndexStmt
		| ListenStmt
457
		| UnlistenStmt
458
		| LockStmt
459
		| NotifyStmt
460
		| ProcedureStmt
Hiroshi Inoue's avatar
Hiroshi Inoue committed
461
		| ReindexStmt
462 463 464 465 466 467 468 469 470 471 472
		| RemoveAggrStmt
		| RemoveOperStmt
		| RemoveFuncStmt
		| RenameStmt
		| RevokeStmt
		| OptimizableStmt
		| RuleStmt
		| TransactionStmt
		| ViewStmt
		| LoadStmt
		| CreatedbStmt
473
		| DropdbStmt
474 475 476 477
		| VacuumStmt
		| VariableSetStmt
		| VariableShowStmt
		| VariableResetStmt
478
		| ConstraintsSetStmt
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
479
		| CheckPointStmt
480 481
		| /*EMPTY*/
			{ $$ = (Node *)NULL; }
482
		;
483

484 485
/*****************************************************************************
 *
486
 * Create a new Postgres DBMS user
487 488 489 490
 *
 *
 *****************************************************************************/

491 492
CreateUserStmt:  CREATE USER UserId
                 user_createdb_clause user_createuser_clause user_group_clause
Bruce Momjian's avatar
Bruce Momjian committed
493
                 user_valid_clause
494 495 496
				{
					CreateUserStmt *n = makeNode(CreateUserStmt);
					n->user = $3;
497
                    n->sysid = -1;
Bruce Momjian's avatar
Bruce Momjian committed
498
					n->password = NULL;
499 500
					n->createdb = $4 == +1 ? TRUE : FALSE;
					n->createuser = $5 == +1 ? TRUE : FALSE;
501 502
					n->groupElts = $6;
					n->validUntil = $7;
503 504
					$$ = (Node *)n;
				}
Bruce Momjian's avatar
Bruce Momjian committed
505
                | CREATE USER UserId WITH sysid_clause user_passwd_clause
506
                user_createdb_clause user_createuser_clause user_group_clause
Bruce Momjian's avatar
Bruce Momjian committed
507 508 509 510
                user_valid_clause
               {
					CreateUserStmt *n = makeNode(CreateUserStmt);
					n->user = $3;
511
                    n->sysid = $5;
Bruce Momjian's avatar
Bruce Momjian committed
512
					n->password = $6;
513 514
					n->createdb = $7 == +1 ? TRUE : FALSE;
					n->createuser = $8 == +1 ? TRUE : FALSE;
515 516
					n->groupElts = $9;
					n->validUntil = $10;
Bruce Momjian's avatar
Bruce Momjian committed
517 518
					$$ = (Node *)n;
               }                   
519
		;
520 521 522

/*****************************************************************************
 *
523
 * Alter a postgresql DBMS user
524 525 526 527
 *
 *
 *****************************************************************************/

528 529
AlterUserStmt:  ALTER USER UserId user_createdb_clause
				user_createuser_clause user_valid_clause
530 531 532
				{
					AlterUserStmt *n = makeNode(AlterUserStmt);
					n->user = $3;
Bruce Momjian's avatar
Bruce Momjian committed
533 534 535
					n->password = NULL;
					n->createdb = $4;
					n->createuser = $5;
536
					n->validUntil = $6;
Bruce Momjian's avatar
Bruce Momjian committed
537 538
					$$ = (Node *)n;
				}
539
			| ALTER USER UserId WITH PASSWORD Sconst
540 541
			  user_createdb_clause
			  user_createuser_clause user_valid_clause
Bruce Momjian's avatar
Bruce Momjian committed
542 543 544 545 546 547
				{
					AlterUserStmt *n = makeNode(AlterUserStmt);
					n->user = $3;
					n->password = $6;
					n->createdb = $7;
					n->createuser = $8;
548
					n->validUntil = $9;
549 550 551
					$$ = (Node *)n;
				}
		;
552 553 554

/*****************************************************************************
 *
555
 * Drop a postgresql DBMS user
556 557 558 559
 *
 *
 *****************************************************************************/

560
DropUserStmt:  DROP USER user_list
561 562
				{
					DropUserStmt *n = makeNode(DropUserStmt);
563
					n->users = $3;
564 565 566 567
					$$ = (Node *)n;
				}
		;

568 569
user_passwd_clause:  PASSWORD Sconst			{ $$ = $2; }
			| /*EMPTY*/							{ $$ = NULL; }
570 571
		;

572
sysid_clause: SYSID Iconst
573 574 575 576 577 578 579
				{
					if ($2 <= 0)
						elog(ERROR, "sysid must be positive");
					$$ = $2;
				}
			| /*EMPTY*/							{ $$ = -1; }
		;
Bruce Momjian's avatar
Bruce Momjian committed
580

581 582 583
user_createdb_clause:  CREATEDB					{ $$ = +1; }
			| NOCREATEDB						{ $$ = -1; }
			| /*EMPTY*/							{ $$ = 0; }
584 585
		;

586 587 588
user_createuser_clause:  CREATEUSER				{ $$ = +1; }
			| NOCREATEUSER						{ $$ = -1; }
			| /*EMPTY*/							{ $$ = 0; }
589 590
		;

591
user_list:  user_list ',' UserId
592
				{
593
					$$ = lappend($1, makeString($3));
594
				}
595
			| UserId
596
				{
597
					$$ = makeList1(makeString($1));
598 599 600
				}
		;

601 602
user_group_clause:  IN GROUP user_list			{ $$ = $3; }
			| /*EMPTY*/							{ $$ = NULL; }
603 604 605 606 607
		;

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

609 610 611

/*****************************************************************************
 *
612
 * Create a postgresql group
613 614 615 616 617
 *
 *
 *****************************************************************************/

CreateGroupStmt:  CREATE GROUP UserId 
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
				{
					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;
				}
		;

users_in_new_group_clause:  USER user_list		{ $$ = $2; }
			| /* EMPTY */						{ $$ = NULL; }
		;                         
638 639 640

/*****************************************************************************
 *
641
 * Alter a postgresql group
642 643 644 645
 *
 *
 *****************************************************************************/

646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
AlterGroupStmt:  ALTER GROUP UserId ADD USER user_list
				{
					AlterGroupStmt *n = makeNode(AlterGroupStmt);
					n->name = $3;
					n->sysid = -1;
					n->action = +1;
					n->listUsers = $6;
					$$ = (Node *)n;
				}
			| ALTER GROUP UserId DROP USER user_list
				{
					AlterGroupStmt *n = makeNode(AlterGroupStmt);
					n->name = $3;
					n->sysid = -1;
					n->action = -1;
					n->listUsers = $6;
					$$ = (Node *)n;
				}
			;
665 666 667

/*****************************************************************************
 *
668
 * Drop a postgresql group
669 670 671 672 673
 *
 *
 *****************************************************************************/

DropGroupStmt: DROP GROUP UserId
674 675 676 677 678 679
				{
					DropGroupStmt *n = makeNode(DropGroupStmt);
					n->name = $3;
					$$ = (Node *)n;
				}
			;
680 681


682 683 684 685 686 687 688 689 690
/*****************************************************************************
 *
 * Manipulate a schema
 *
 *
 *****************************************************************************/

CreateSchemaStmt:  CREATE SCHEMA UserId
				{
691 692 693 694
					/* for now, just make this the same as CREATE DATABASE */
					CreatedbStmt *n = makeNode(CreatedbStmt);
					n->dbname = $3;
					n->dbpath = NULL;
695 696
					n->dbtemplate = NULL;
					n->encoding = -1;
697
					$$ = (Node *)n;
698 699 700 701 702 703 704 705 706
				}
		;

AlterSchemaStmt:  ALTER SCHEMA UserId
				{
					elog(ERROR, "ALTER SCHEMA not yet supported");
				}
		;

707 708 709 710 711 712 713
DropSchemaStmt:  DROP SCHEMA UserId
				{
					DropdbStmt *n = makeNode(DropdbStmt);
					n->dbname = $3;
					$$ = (Node *)n;
				}

714

715
/*****************************************************************************
716
 *
717
 * Set PG internal variable
718
 *	  SET name TO 'var_value'
719 720
 * Include SQL92 syntax (thomas 1997-10-22):
 *    SET TIME ZONE 'var_value'
721
 *
722 723
 *****************************************************************************/

724
VariableSetStmt:  SET ColId TO var_value
725 726 727 728 729 730
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = $2;
					n->value = $4;
					$$ = (Node *) n;
				}
731
		| SET ColId '=' var_value
732 733 734 735 736 737
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = $2;
					n->value = $4;
					$$ = (Node *) n;
				}
738
		| SET TIME ZONE zone_value
739 740 741 742 743 744
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = "timezone";
					n->value = $4;
					$$ = (Node *) n;
				}
745
		| SET TRANSACTION ISOLATION LEVEL opt_level
746 747 748 749 750 751
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = "XactIsoLevel";
					n->value = $5;
					$$ = (Node *) n;
				}
752 753 754 755 756 757 758
        | SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL opt_level
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = "DefaultXactIsoLevel";
					n->value = $8;
					$$ = (Node *) n;
				}
759
		| SET NAMES opt_encoding
760 761 762 763 764 765
				{
					VariableSetStmt *n = makeNode(VariableSetStmt);
					n->name  = "client_encoding";
					n->value = $3;
					$$ = (Node *) n;
				}
766 767
		;

768 769 770 771
opt_level:  READ COMMITTED					{ $$ = "committed"; }
		| SERIALIZABLE						{ $$ = "serializable"; }
		;

772 773 774 775 776 777 778 779 780 781
var_value:  opt_boolean						{ $$ = $1; }
		| SCONST							{ $$ = $1; }
		| ICONST
			{
				char	buf[64];
				sprintf(buf, "%d", $1);
				$$ = pstrdup(buf);
			}
		| '-' ICONST
			{
782 783 784 785
				char	buf[64];
				sprintf(buf, "%d", -($2));
				$$ = pstrdup(buf);
			}
786 787 788
		| FCONST							{ $$ = $1; }
		| '-' FCONST
			{
789 790 791 792 793
				char * s = palloc(strlen($2)+2);
				s[0] = '-';
				strcpy(s + 1, $2);
				$$ = s;
			}
794 795
		| name_list
			{
796 797 798
				List *n;
				int slen = 0;
				char *result;
799

800 801 802
				/* List of words? Then concatenate together */
				if ($1 == NIL)
					elog(ERROR, "SET must have at least one argument");
803

804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
				foreach (n, $1)
				{
					Value *p = (Value *) lfirst(n);
					Assert(IsA(p, String));
					/* keep track of room for string and trailing comma */
					slen += (strlen(p->val.str) + 1);
				}
				result = palloc(slen + 1);
				*result = '\0';
				foreach (n, $1)
				{
					Value *p = (Value *) lfirst(n);
					strcat(result, p->val.str);
					strcat(result, ",");
				}
				/* remove the trailing comma from the last element */
				*(result+strlen(result)-1) = '\0';
				$$ = result;
822
			}
823 824
		| DEFAULT							{ $$ = NULL; }
		;
825

826 827 828 829
opt_boolean:  TRUE_P						{ $$ = "true"; }
		| FALSE_P							{ $$ = "false"; }
		| ON								{ $$ = "on"; }
		| OFF								{ $$ = "off"; }
830 831
		;

832 833 834
zone_value:  Sconst							{ $$ = $1; }
		| DEFAULT							{ $$ = NULL; }
		| LOCAL								{ $$ = NULL; }
835
		;
836

837 838 839
opt_encoding:  Sconst						{ $$ = $1; }
        | DEFAULT							{ $$ = NULL; }
        | /*EMPTY*/							{ $$ = NULL; }
840 841
        ;

842
VariableShowStmt:  SHOW ColId
843 844 845 846 847
				{
					VariableShowStmt *n = makeNode(VariableShowStmt);
					n->name  = $2;
					$$ = (Node *) n;
				}
848 849 850 851 852 853
		| SHOW TIME ZONE
				{
					VariableShowStmt *n = makeNode(VariableShowStmt);
					n->name  = "timezone";
					$$ = (Node *) n;
				}
854 855 856 857 858 859
		| SHOW TRANSACTION ISOLATION LEVEL
				{
					VariableShowStmt *n = makeNode(VariableShowStmt);
					n->name  = "XactIsoLevel";
					$$ = (Node *) n;
				}
860 861
		;

862
VariableResetStmt:	RESET ColId
863 864 865 866 867
				{
					VariableResetStmt *n = makeNode(VariableResetStmt);
					n->name  = $2;
					$$ = (Node *) n;
				}
868 869 870 871 872 873
		| RESET TIME ZONE
				{
					VariableResetStmt *n = makeNode(VariableResetStmt);
					n->name  = "timezone";
					$$ = (Node *) n;
				}
874 875 876 877 878 879
		| RESET TRANSACTION ISOLATION LEVEL
				{
					VariableResetStmt *n = makeNode(VariableResetStmt);
					n->name  = "XactIsoLevel";
					$$ = (Node *) n;
				}
880
		;
881

882

883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
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
				{
906
					$$ = makeList1($1);
907 908 909 910 911 912 913 914 915 916
				}
		| constraints_set_namelist ',' IDENT
				{
					$$ = lappend($1, $3);
				}
		;


constraints_set_mode:	DEFERRED
				{
917
					$$ = TRUE;
918 919 920
				}
		| IMMEDIATE
				{
921
					$$ = FALSE;
922 923 924 925
				}
		;


Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
926 927 928 929 930 931 932 933 934 935
/*
 * Checkpoint statement
 */
CheckPointStmt: CHECKPOINT
				{
					CheckPointStmt *n = makeNode(CheckPointStmt);
					$$ = (Node *)n;
				}
			;

936 937
/*****************************************************************************
 *
938
 *	ALTER TABLE variations
939 940 941
 *
 *****************************************************************************/

942 943
AlterTableStmt:
/* ALTER TABLE <name> ADD [COLUMN] <coldef> */
944 945 946 947 948
		ALTER TABLE relation_name opt_inh_star ADD opt_column columnDef
				{
					AlterTableStmt *n = makeNode(AlterTableStmt);
					n->subtype = 'A';
					n->relname = $3;
949
					n->inhOpt = $4;
950 951 952
					n->def = $7;
					$$ = (Node *)n;
				}
953
/* ALTER TABLE <name> ALTER [COLUMN] <colname> {SET DEFAULT <expr>|DROP DEFAULT} */
954 955 956 957 958
		| ALTER TABLE relation_name opt_inh_star ALTER opt_column ColId alter_column_action
				{
					AlterTableStmt *n = makeNode(AlterTableStmt);
					n->subtype = 'T';
					n->relname = $3;
959
					n->inhOpt = $4;
960 961 962 963
					n->name = $7;
					n->def = $8;
					$$ = (Node *)n;
				}
964
/* ALTER TABLE <name> DROP [COLUMN] <name> {RESTRICT|CASCADE} */
965 966 967 968 969
		| ALTER TABLE relation_name opt_inh_star DROP opt_column ColId drop_behavior
				{
					AlterTableStmt *n = makeNode(AlterTableStmt);
					n->subtype = 'D';
					n->relname = $3;
970
					n->inhOpt = $4;
971 972 973 974
					n->name = $7;
					n->behavior = $8;
					$$ = (Node *)n;
				}
975
/* ALTER TABLE <name> ADD CONSTRAINT ... */
976 977 978 979 980
		| ALTER TABLE relation_name opt_inh_star ADD TableConstraint
				{
					AlterTableStmt *n = makeNode(AlterTableStmt);
					n->subtype = 'C';
					n->relname = $3;
981
					n->inhOpt = $4;
982 983 984
					n->def = $6;
					$$ = (Node *)n;
				}
985
/* ALTER TABLE <name> DROP CONSTRAINT <name> {RESTRICT|CASCADE} */
986 987 988 989 990
		| ALTER TABLE relation_name opt_inh_star DROP CONSTRAINT name drop_behavior
				{
					AlterTableStmt *n = makeNode(AlterTableStmt);
					n->subtype = 'X';
					n->relname = $3;
991
					n->inhOpt = $4;
992 993 994 995
					n->name = $7;
					n->behavior = $8;
					$$ = (Node *)n;
				}
Jan Wieck's avatar
TOAST  
Jan Wieck committed
996 997 998 999 1000 1001 1002 1003
/* ALTER TABLE <name> CREATE TOAST TABLE */
		| ALTER TABLE relation_name CREATE TOAST TABLE
				{
					AlterTableStmt *n = makeNode(AlterTableStmt);
					n->subtype = 'E';
					n->relname = $3;
					$$ = (Node *)n;
				}
1004 1005 1006 1007 1008 1009 1010 1011 1012
/* ALTER TABLE <name> OWNER TO UserId */
		| ALTER TABLE relation_name OWNER TO UserId
				{
					AlterTableStmt *n = makeNode(AlterTableStmt);
					n->subtype = 'U';
					n->relname = $3;
					n->name = $6;
					$$ = (Node *)n;
				}
1013
		;
1014 1015

alter_column_action:
1016 1017 1018 1019 1020 1021 1022 1023
		SET DEFAULT a_expr
			{
				/* Treat SET DEFAULT NULL the same as DROP DEFAULT */
				if (exprIsNullConstant($3))
					$$ = NULL;
				else
					$$ = $3;
			}
1024
		| DROP DEFAULT					{ $$ = NULL; }
1025 1026
        ;

1027 1028
drop_behavior: CASCADE					{ $$ = CASCADE; }
		| RESTRICT						{ $$ = RESTRICT; }
1029
        ;
1030

1031

1032 1033

/*****************************************************************************
1034
 *
1035 1036
 *		QUERY :
 *				close <optname>
1037
 *
1038 1039
 *****************************************************************************/

1040
ClosePortalStmt:  CLOSE opt_id
1041 1042 1043 1044 1045 1046
				{
					ClosePortalStmt *n = makeNode(ClosePortalStmt);
					n->portalname = $2;
					$$ = (Node *)n;
				}
		;
1047

1048 1049 1050 1051
opt_id:  ColId									{ $$ = $1; }
		| /*EMPTY*/								{ $$ = NULL; }
		;

1052 1053 1054

/*****************************************************************************
 *
1055 1056 1057
 *		QUERY :
 *				COPY [BINARY] <relname> FROM/TO
 *				[USING DELIMITERS <delimiter>]
1058 1059 1060
 *
 *****************************************************************************/

1061
CopyStmt:  COPY opt_binary relation_name opt_with_copy copy_dirn copy_file_name copy_delimiter copy_null
1062 1063 1064 1065 1066 1067 1068 1069
				{
					CopyStmt *n = makeNode(CopyStmt);
					n->binary = $2;
					n->relname = $3;
					n->oids = $4;
					n->direction = $5;
					n->filename = $6;
					n->delimiter = $7;
1070
					n->null_print = $8;
1071 1072 1073 1074 1075 1076
					$$ = (Node *)n;
				}
		;

copy_dirn:	TO
				{ $$ = TO; }
1077
		| FROM
1078 1079
				{ $$ = FROM; }
		;
1080

1081
/*
1082 1083
 * 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
1084
 * stdout. We silently correct the "typo".		 - AY 9/94
1085
 */
1086 1087 1088 1089
copy_file_name:  Sconst							{ $$ = $1; }
		| STDIN									{ $$ = NULL; }
		| STDOUT								{ $$ = NULL; }
		;
1090

1091 1092
opt_binary:  BINARY								{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
1093
		;
1094

1095
opt_with_copy:	WITH OIDS						{ $$ = TRUE; }
1096
		| /*EMPTY*/								{ $$ = FALSE; }
1097
		;
1098

1099 1100 1101
/*
 * the default copy delimiter is tab but the user can configure it
 */
Bruce Momjian's avatar
Bruce Momjian committed
1102
copy_delimiter:  opt_using DELIMITERS Sconst	{ $$ = $3; }
1103
		| /*EMPTY*/								{ $$ = "\t"; }
1104
		;
1105

Bruce Momjian's avatar
Bruce Momjian committed
1106 1107 1108 1109
opt_using:	USING								{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = TRUE; }
		;

1110 1111
copy_null:      WITH NULL_P AS Sconst			{ $$ = $4; }
                | /*EMPTY*/						{ $$ = "\\N"; }
1112 1113 1114

/*****************************************************************************
 *
1115 1116
 *		QUERY :
 *				CREATE relname
1117 1118 1119
 *
 *****************************************************************************/

1120
CreateStmt:  CREATE OptTemp TABLE relation_name '(' OptTableElementList ')' OptInherit
1121 1122
				{
					CreateStmt *n = makeNode(CreateStmt);
1123 1124
					n->istemp = $2;
					n->relname = $4;
1125 1126
					n->tableElts = $6;
					n->inhRelnames = $8;
1127
					n->constraints = NIL;
1128 1129 1130 1131
					$$ = (Node *)n;
				}
		;

1132 1133 1134 1135 1136 1137 1138 1139 1140
/*
 * Redundancy here is needed to avoid shift/reduce conflicts,
 * since TEMP is not a reserved word.  See also OptTempTableName.
 */
OptTemp:      TEMPORARY						{ $$ = TRUE; }
			| TEMP							{ $$ = TRUE; }
			| LOCAL TEMPORARY				{ $$ = TRUE; }
			| LOCAL TEMP					{ $$ = TRUE; }
			| GLOBAL TEMPORARY
1141 1142 1143 1144
				{
					elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
					$$ = TRUE;
				}
1145
			| GLOBAL TEMP
1146
				{
1147 1148
					elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
					$$ = TRUE;
1149
				}
1150
			| /*EMPTY*/						{ $$ = FALSE; }
1151 1152
		;

1153
OptTableElementList:  OptTableElementList ',' OptTableElement
1154 1155 1156 1157 1158 1159 1160 1161 1162
				{
					if ($3 != NULL)
						$$ = lappend($1, $3);
					else
						$$ = $1;
				}
			| OptTableElement
				{
					if ($1 != NULL)
1163
						$$ = makeList1($1);
1164
					else
1165
						$$ = NIL;
1166
				}
1167
			| /*EMPTY*/							{ $$ = NIL; }
1168
		;
1169

1170 1171
OptTableElement:  columnDef						{ $$ = $1; }
			| TableConstraint					{ $$ = $1; }
1172
		;
1173

1174
columnDef:  ColId Typename ColQualList opt_collate
1175 1176 1177 1178 1179
				{
					ColumnDef *n = makeNode(ColumnDef);
					n->colname = $1;
					n->typename = $2;
					n->constraints = $3;
1180 1181 1182 1183 1184

					if ($4 != NULL)
						elog(NOTICE,"CREATE TABLE/COLLATE %s not yet implemented"
							 "; clause ignored", $4);

1185 1186
					$$ = (Node *)n;
				}
1187
			| ColId SERIAL ColQualList opt_collate
1188 1189 1190 1191 1192
				{
					ColumnDef *n = makeNode(ColumnDef);
					n->colname = $1;
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("integer");
1193
					n->typename->typmod = -1;
1194
					n->is_sequence = TRUE;
1195 1196 1197 1198 1199
					n->constraints = $3;

					if ($4 != NULL)
						elog(NOTICE,"CREATE TABLE/COLLATE %s not yet implemented"
							 "; clause ignored", $4);
1200

1201 1202 1203 1204
					$$ = (Node *)n;
				}
		;

1205 1206
ColQualList:  ColQualList ColConstraint		{ $$ = lappend($1, $2); }
			| /*EMPTY*/						{ $$ = NIL; }
1207 1208
		;

1209 1210
ColConstraint:
		CONSTRAINT name ColConstraintElem
1211
				{
Jan Wieck's avatar
Jan Wieck committed
1212 1213 1214 1215 1216
					switch (nodeTag($3))
					{
						case T_Constraint:
							{
								Constraint *n = (Constraint *)$3;
1217
								n->name = $2;
Jan Wieck's avatar
Jan Wieck committed
1218 1219 1220 1221 1222
							}
							break;
						case T_FkConstraint:
							{
								FkConstraint *n = (FkConstraint *)$3;
1223
								n->constr_name = $2;
Jan Wieck's avatar
Jan Wieck committed
1224 1225 1226 1227 1228 1229
							}
							break;
						default:
							break;
					}
					$$ = $3;
1230 1231 1232
				}
		| ColConstraintElem
				{ $$ = $1; }
1233
		| ConstraintAttr
1234 1235 1236 1237
				{ $$ = $1; }
		;

/* DEFAULT NULL is already the default for Postgres.
1238
 * But define it here and carry it forward into the system
1239 1240
 * to make it explicit.
 * - thomas 1998-09-13
1241
 *
1242 1243 1244 1245 1246
 * 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
1247 1248 1249 1250
 *
 * 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).
1251
 */
1252 1253
ColConstraintElem:
			  NOT NULL_P
1254
				{
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_NOTNULL;
					n->name = NULL;
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
					n->keys = NULL;
					$$ = (Node *)n;
				}
			| NULL_P
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_NULL;
					n->name = NULL;
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
					n->keys = NULL;
					$$ = (Node *)n;
1272 1273
				}
			| UNIQUE
1274 1275
				{
					Constraint *n = makeNode(Constraint);
1276
					n->contype = CONSTR_UNIQUE;
1277
					n->name = NULL;
1278 1279
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1280 1281 1282
					n->keys = NULL;
					$$ = (Node *)n;
				}
1283
			| PRIMARY KEY
1284
				{
1285 1286 1287 1288 1289 1290 1291
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_PRIMARY;
					n->name = NULL;
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
					n->keys = NULL;
					$$ = (Node *)n;
1292
				}
1293
			| CHECK '(' a_expr ')'
1294 1295
				{
					Constraint *n = makeNode(Constraint);
1296
					n->contype = CONSTR_CHECK;
1297
					n->name = NULL;
1298
					n->raw_expr = $3;
1299
					n->cooked_expr = NULL;
1300 1301 1302
					n->keys = NULL;
					$$ = (Node *)n;
				}
1303 1304 1305 1306 1307
			| DEFAULT b_expr
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_DEFAULT;
					n->name = NULL;
1308 1309 1310 1311 1312 1313 1314 1315 1316
					if (exprIsNullConstant($2))
					{
						/* DEFAULT NULL should be reported as empty expr */
						n->raw_expr = NULL;
					}
					else
					{
						n->raw_expr = $2;
					}
1317 1318 1319 1320 1321
					n->cooked_expr = NULL;
					n->keys = NULL;
					$$ = (Node *)n;
				}
			| REFERENCES ColId opt_column_list key_match key_actions 
1322
				{
Jan Wieck's avatar
Jan Wieck committed
1323 1324 1325 1326 1327 1328 1329
					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;
1330 1331
					n->deferrable		= FALSE;
					n->initdeferred		= FALSE;
Jan Wieck's avatar
Jan Wieck committed
1332
					$$ = (Node *)n;
1333
				}
1334
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1335

1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
/*
 * ConstraintAttr represents constraint attributes, which we parse as if
 * they were independent constraint clauses, in order to avoid shift/reduce
 * conflicts (since NOT might start either an independent NOT NULL clause
 * or an attribute).  analyze.c is responsible for attaching the attribute
 * information to the preceding "real" constraint node, and for complaining
 * if attribute clauses appear in the wrong place or wrong combinations.
 *
 * See also ConstraintAttributeSpec, which can be used in places where
 * there is no parsing conflict.
 */
ConstraintAttr: DEFERRABLE
1348 1349
				{
					Constraint *n = makeNode(Constraint);
1350
					n->contype = CONSTR_ATTR_DEFERRABLE;
1351 1352
					$$ = (Node *)n;
				}
1353
			| NOT DEFERRABLE
1354 1355
				{
					Constraint *n = makeNode(Constraint);
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
					n->contype = CONSTR_ATTR_NOT_DEFERRABLE;
					$$ = (Node *)n;
				}
			| INITIALLY DEFERRED
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_ATTR_DEFERRED;
					$$ = (Node *)n;
				}
			| INITIALLY IMMEDIATE
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_ATTR_IMMEDIATE;
1369 1370
					$$ = (Node *)n;
				}
1371 1372
		;

1373

1374 1375 1376 1377 1378
/* 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
1379
				{
Jan Wieck's avatar
Jan Wieck committed
1380 1381 1382 1383 1384
					switch (nodeTag($3))
					{
						case T_Constraint:
							{
								Constraint *n = (Constraint *)$3;
1385
								n->name = $2;
Jan Wieck's avatar
Jan Wieck committed
1386 1387 1388 1389 1390
							}
							break;
						case T_FkConstraint:
							{
								FkConstraint *n = (FkConstraint *)$3;
1391
								n->constr_name = $2;
Jan Wieck's avatar
Jan Wieck committed
1392 1393 1394 1395 1396 1397
							}
							break;
						default:
							break;
					}
					$$ = $3;
1398
				}
1399 1400
		| ConstraintElem
				{ $$ = $1; }
1401 1402
		;

1403
ConstraintElem:  CHECK '(' a_expr ')'
1404
				{
1405 1406 1407
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_CHECK;
					n->name = NULL;
1408 1409
					n->raw_expr = $3;
					n->cooked_expr = NULL;
1410
					$$ = (Node *)n;
1411
				}
1412
		| UNIQUE '(' columnList ')'
1413 1414 1415 1416
				{
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_UNIQUE;
					n->name = NULL;
1417 1418
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
1419 1420 1421
					n->keys = $3;
					$$ = (Node *)n;
				}
1422
		| PRIMARY KEY '(' columnList ')'
1423
				{
1424 1425 1426 1427 1428 1429
					Constraint *n = makeNode(Constraint);
					n->contype = CONSTR_PRIMARY;
					n->name = NULL;
					n->raw_expr = NULL;
					n->cooked_expr = NULL;
					n->keys = $4;
1430 1431
					$$ = (Node *)n;
				}
1432
		| FOREIGN KEY '(' columnList ')' REFERENCES ColId opt_column_list
1433
				key_match key_actions ConstraintAttributeSpec
Jan Wieck's avatar
Jan Wieck committed
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
				{
					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;
1445
				}
1446
		;
1447

Jan Wieck's avatar
Jan Wieck committed
1448 1449 1450 1451 1452 1453
key_match:  MATCH FULL
			{
				$$ = "FULL";
			}
		| MATCH PARTIAL
			{
1454
				elog(ERROR, "FOREIGN KEY/MATCH PARTIAL not yet implemented");
Jan Wieck's avatar
Jan Wieck committed
1455 1456 1457 1458 1459 1460
				$$ = "PARTIAL";
			}
		| /*EMPTY*/
			{
				$$ = "UNSPECIFIED";
			}
1461 1462
		;

1463 1464 1465 1466
key_actions:  key_delete				{ $$ = $1; }
		| key_update					{ $$ = $1; }
		| key_delete key_update			{ $$ = $1 | $2; }
		| key_update key_delete			{ $$ = $1 | $2; }
Jan Wieck's avatar
Jan Wieck committed
1467
		| /*EMPTY*/						{ $$ = 0; }
1468 1469
		;

1470 1471 1472 1473
key_delete:  ON DELETE key_reference	{ $$ = $3 << FKCONSTR_ON_DELETE_SHIFT; }
		;

key_update:  ON UPDATE key_reference	{ $$ = $3 << FKCONSTR_ON_UPDATE_SHIFT; }
1474 1475
		;

Jan Wieck's avatar
Jan Wieck committed
1476 1477 1478 1479 1480
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; }
1481 1482
		;

1483 1484
opt_only: ONLY              	     	        { $$ = INH_NO; }
        | /*EMPTY*/								{ $$ = INH_DEFAULT; } 
1485 1486
		;

1487
OptInherit:  INHERITS '(' relation_name_list ')'	{ $$ = $3; }
1488
		| /*EMPTY*/									{ $$ = NIL; }
1489 1490
		;

1491 1492 1493 1494 1495
/*
 * Note: CREATE TABLE ... AS SELECT ... is just another spelling for
 * SELECT ... INTO.
 */

1496
CreateAsStmt:  CREATE OptTemp TABLE relation_name OptCreateAs AS SelectStmt
1497
				{
1498 1499 1500 1501 1502 1503 1504
					/*
					 * When the SelectStmt is a set-operation tree, we must
					 * stuff the INTO information into the leftmost component
					 * Select, because that's where analyze.c will expect
					 * to find it.  Similarly, the output column names must
					 * be attached to that Select's target list.
					 */
1505
					SelectStmt *n = findLeftmostSelect((SelectStmt *) $7);
1506 1507
					if (n->into != NULL)
						elog(ERROR,"CREATE TABLE/AS SELECT may not specify INTO");
1508 1509
					n->istemp = $2;
					n->into = $4;
1510 1511 1512
					if ($5 != NIL)
						mapTargetColumns($5, n->targetList);
					$$ = $7;
1513 1514 1515 1516
				}
		;

OptCreateAs:  '(' CreateAsList ')'				{ $$ = $2; }
1517
			| /*EMPTY*/							{ $$ = NIL; }
1518 1519 1520
		;

CreateAsList:  CreateAsList ',' CreateAsElement	{ $$ = lappend($1, $3); }
1521
			| CreateAsElement					{ $$ = makeList1($1); }
1522 1523 1524 1525 1526 1527 1528
		;

CreateAsElement:  ColId
				{
					ColumnDef *n = makeNode(ColumnDef);
					n->colname = $1;
					n->typename = NULL;
1529 1530
					n->raw_default = NULL;
					n->cooked_default = NULL;
1531 1532 1533 1534 1535 1536
					n->is_not_null = FALSE;
					n->constraints = NULL;
					$$ = (Node *)n;
				}
		;

1537

Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1538 1539
/*****************************************************************************
 *
1540 1541
 *		QUERY :
 *				CREATE SEQUENCE seqname
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1542 1543 1544
 *
 *****************************************************************************/

1545
CreateSeqStmt:  CREATE SEQUENCE relation_name OptSeqList
1546 1547 1548 1549 1550 1551 1552
				{
					CreateSeqStmt *n = makeNode(CreateSeqStmt);
					n->seqname = $3;
					n->options = $4;
					$$ = (Node *)n;
				}
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1553

1554
OptSeqList:  OptSeqList OptSeqElem
1555
				{ $$ = lappend($1, $2); }
1556
			|	{ $$ = NIL; }
1557 1558
		;

1559
OptSeqElem:  CACHE IntegerOnly
1560 1561
				{
					$$ = makeNode(DefElem);
1562
					$$->defname = "cache";
1563 1564
					$$->arg = (Node *)$2;
				}
1565
			| CYCLE
1566 1567
				{
					$$ = makeNode(DefElem);
1568
					$$->defname = "cycle";
1569 1570
					$$->arg = (Node *)NULL;
				}
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
			| 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;
				}
		;

1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
NumericOnly:  FloatOnly					{ $$ = $1; }
			| IntegerOnly				{ $$ = $1; }

FloatOnly:  FCONST
				{
					$$ = makeFloat($1);
				}
			| '-' FCONST
				{
					$$ = makeFloat($2);
1607
					doNegateFloat($$);
1608 1609 1610
				}
		;

1611 1612 1613 1614 1615 1616 1617 1618 1619
IntegerOnly:  Iconst
				{
					$$ = makeInteger($1);
				}
			| '-' Iconst
				{
					$$ = makeInteger($2);
					$$->val.ival = - $$->val.ival;
				}
1620
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1621

1622 1623 1624 1625 1626 1627 1628 1629
/*****************************************************************************
 *
 *		QUERIES :
 *				CREATE PROCEDURAL LANGUAGE ...
 *				DROP PROCEDURAL LANGUAGE ...
 *
 *****************************************************************************/

1630
CreatePLangStmt:  CREATE PLangTrusted opt_procedural LANGUAGE Sconst 
1631
			HANDLER func_name LANCOMPILER Sconst
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
			{
				CreatePLangStmt *n = makeNode(CreatePLangStmt);
				n->plname = $5;
				n->plhandler = $7;
				n->plcompiler = $9;
				n->pltrusted = $2;
				$$ = (Node *)n;
			}
		;

1642 1643
PLangTrusted:  TRUSTED			{ $$ = TRUE; }
			| /*EMPTY*/			{ $$ = FALSE; }
1644
		;
1645

1646
DropPLangStmt:  DROP opt_procedural LANGUAGE Sconst
1647 1648 1649 1650 1651 1652
			{
				DropPLangStmt *n = makeNode(DropPLangStmt);
				n->plname = $4;
				$$ = (Node *)n;
			}
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
1653

1654 1655 1656 1657
opt_procedural: PROCEDURAL		{ $$ = TRUE; }
			| /*EMPTY*/			{ $$ = TRUE; }
		;
		
1658 1659
/*****************************************************************************
 *
1660 1661 1662
 *		QUERIES :
 *				CREATE TRIGGER ...
 *				DROP TRIGGER ...
1663 1664 1665
 *
 *****************************************************************************/

1666
CreateTrigStmt:  CREATE TRIGGER name TriggerActionTime TriggerEvents ON
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
				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);
1678 1679 1680 1681 1682
					n->lang = NULL;		/* unused */
					n->text = NULL;		/* unused */
					n->attr = NULL;		/* unused */
					n->when = NULL;		/* unused */

1683 1684 1685
					n->isconstraint  = FALSE;
					n->deferrable    = FALSE;
					n->initdeferred  = FALSE;
1686 1687 1688
					n->constrrelname = NULL;
					$$ = (Node *)n;
				}
1689
		| CREATE CONSTRAINT TRIGGER name AFTER TriggerEvents ON
1690
				relation_name OptConstrFromTable 
1691
				ConstraintAttributeSpec
1692 1693 1694 1695 1696
				FOR EACH ROW EXECUTE PROCEDURE name '(' TriggerFuncArgs ')'
				{
					CreateTrigStmt *n = makeNode(CreateTrigStmt);
					n->trigname = $4;
					n->relname = $8;
Jan Wieck's avatar
Jan Wieck committed
1697 1698
					n->funcname = $16;
					n->args = $18;
1699 1700
					n->before = FALSE;
					n->row = TRUE;
1701
					memcpy (n->actions, $6, 4);
1702 1703 1704 1705 1706
					n->lang = NULL;		/* unused */
					n->text = NULL;		/* unused */
					n->attr = NULL;		/* unused */
					n->when = NULL;		/* unused */

1707
					n->isconstraint  = TRUE;
Jan Wieck's avatar
Jan Wieck committed
1708 1709
					n->deferrable = ($10 & 1) != 0;
					n->initdeferred = ($10 & 2) != 0;
1710 1711

					n->constrrelname = $9;
1712 1713 1714 1715
					$$ = (Node *)n;
				}
		;

1716 1717
TriggerActionTime:  BEFORE						{ $$ = TRUE; }
			| AFTER								{ $$ = FALSE; }
1718 1719 1720
		;

TriggerEvents:	TriggerOneEvent
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
				{
					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;
				}
1736 1737
		;

1738 1739 1740
TriggerOneEvent:  INSERT					{ $$ = 'i'; }
			| DELETE						{ $$ = 'd'; }
			| UPDATE						{ $$ = 'u'; }
1741 1742
		;

1743
TriggerForSpec:  FOR TriggerForOpt TriggerForType
1744
				{
1745
					$$ = $3;
1746 1747
				}
		;
1748

1749 1750 1751 1752 1753 1754 1755 1756
TriggerForOpt:  EACH						{ $$ = TRUE; }
			| /*EMPTY*/						{ $$ = FALSE; }
		;

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

1757
TriggerFuncArgs:  TriggerFuncArg
1758
				{ $$ = makeList1($1); }
1759
			| TriggerFuncArgs ',' TriggerFuncArg
1760
				{ $$ = lappend($1, $3); }
1761
			| /*EMPTY*/
1762
				{ $$ = NIL; }
1763 1764
		;

1765
TriggerFuncArg:  ICONST
1766
				{
1767 1768
					char buf[64];
					sprintf (buf, "%d", $1);
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
					$$ = makeString(pstrdup(buf));
				}
			| FCONST
				{
					$$ = makeString($1);
				}
			| Sconst
				{
					$$ = makeString($1);
				}
1779 1780 1781 1782
			| BITCONST
				{
					$$ = makeString($1);
				}
1783 1784 1785
			| ColId
				{
					$$ = makeString($1);
1786
				}
1787
		;
1788

1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
OptConstrFromTable:			/* Empty */
				{
					$$ = "";
				}
		| FROM relation_name
				{
					$$ = $2;
				}
		;

1799 1800 1801
ConstraintAttributeSpec:  ConstraintDeferrabilitySpec
			{ $$ = $1; }
		| ConstraintDeferrabilitySpec ConstraintTimeSpec
Jan Wieck's avatar
Jan Wieck committed
1802
			{
1803 1804 1805
				if ($1 == 0 && $2 != 0)
					elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
				$$ = $1 | $2;
Jan Wieck's avatar
Jan Wieck committed
1806
			}
1807
		| ConstraintTimeSpec
Jan Wieck's avatar
Jan Wieck committed
1808 1809 1810 1811
			{
				if ($1 != 0)
					$$ = 3;
				else
1812
					$$ = 0;
Jan Wieck's avatar
Jan Wieck committed
1813
			}
1814
		| ConstraintTimeSpec ConstraintDeferrabilitySpec
Jan Wieck's avatar
Jan Wieck committed
1815 1816 1817 1818 1819
			{
				if ($2 == 0 && $1 != 0)
					elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
				$$ = $1 | $2;
			}
1820 1821
		| /* Empty */
			{ $$ = 0; }
1822 1823
		;

1824 1825 1826 1827
ConstraintDeferrabilitySpec: NOT DEFERRABLE
			{ $$ = 0; }
		| DEFERRABLE
			{ $$ = 1; }
Jan Wieck's avatar
Jan Wieck committed
1828 1829
		;

1830 1831 1832 1833
ConstraintTimeSpec: INITIALLY IMMEDIATE
			{ $$ = 0; }
		| INITIALLY DEFERRED
			{ $$ = 2; }
1834
		;
1835

1836

1837
DropTrigStmt:  DROP TRIGGER name ON relation_name
1838 1839 1840 1841 1842 1843 1844
				{
					DropTrigStmt *n = makeNode(DropTrigStmt);
					n->trigname = $3;
					n->relname = $5;
					$$ = (Node *) n;
				}
		;
1845

1846

1847 1848
/*****************************************************************************
 *
1849
 *		QUERY :
1850
 *				define (aggregate,operator,type)
1851 1852 1853
 *
 *****************************************************************************/

1854
DefineStmt:  CREATE AGGREGATE func_name definition
1855
				{
1856
					DefineStmt *n = makeNode(DefineStmt);
1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
					n->defType = AGGREGATE;
					n->defname = $3;
					n->definition = $4;
					$$ = (Node *)n;
				}
		| CREATE OPERATOR all_Op definition
				{
					DefineStmt *n = makeNode(DefineStmt);
					n->defType = OPERATOR;
					n->defname = $3;
					n->definition = $4;
					$$ = (Node *)n;
				}
		| CREATE TYPE_P name definition
				{
					DefineStmt *n = makeNode(DefineStmt);
					n->defType = TYPE_P;
1874 1875 1876
					n->defname = $3;
					n->definition = $4;
					$$ = (Node *)n;
1877 1878
				}
		;
1879

1880
definition:  '(' def_list ')'				{ $$ = $2; }
1881
		;
1882

1883
def_list:  def_elem							{ $$ = makeList1($1); }
1884
		| def_list ',' def_elem				{ $$ = lappend($1, $3); }
1885
		;
1886

1887
def_elem:  ColLabel '=' def_arg
1888 1889 1890 1891 1892
				{
					$$ = makeNode(DefElem);
					$$->defname = $1;
					$$->arg = (Node *)$3;
				}
1893
		| ColLabel
1894 1895 1896 1897 1898 1899 1900
				{
					$$ = makeNode(DefElem);
					$$->defname = $1;
					$$->arg = (Node *)NULL;
				}
		;

1901 1902
def_arg:  func_return  					{  $$ = (Node *)$1; }
		| TokenId						{  $$ = (Node *)makeString($1); }
1903
		| all_Op						{  $$ = (Node *)makeString($1); }
1904
		| NumericOnly					{  $$ = (Node *)$1; }
1905
		| Sconst						{  $$ = (Node *)makeString($1); }
1906
		;
1907 1908 1909 1910


/*****************************************************************************
 *
1911
 *		QUERY:
1912 1913
 *
 *		DROP itemtype itemname [, itemname ...]
1914 1915 1916
 *
 *****************************************************************************/

1917
DropStmt:  DROP drop_type name_list
1918 1919
				{
					DropStmt *n = makeNode(DropStmt);
1920
					n->removeType = $2;
1921
					n->names = $3;
1922 1923 1924
					$$ = (Node *)n;
				}
		;
1925

1926 1927 1928 1929 1930 1931 1932 1933
drop_type: TABLE								{ $$ = DROP_TABLE; }
		| SEQUENCE								{ $$ = DROP_SEQUENCE; }
		| VIEW									{ $$ = DROP_VIEW; }
		| INDEX									{ $$ = DROP_INDEX; }
		| RULE									{ $$ = DROP_RULE; }
		| TYPE_P								{ $$ = DROP_TYPE_P; }
		;

1934 1935 1936 1937 1938 1939 1940
/*****************************************************************************
 *
 *		QUERY:
 *				truncate table relname
 *
 *****************************************************************************/

1941
TruncateStmt:  TRUNCATE opt_table relation_name
1942 1943 1944 1945 1946 1947
				{
					TruncateStmt *n = makeNode(TruncateStmt);
					n->relName = $3;
					$$ = (Node *)n;
				}
			;
1948

1949 1950
/*****************************************************************************
 *
Bruce Momjian's avatar
Bruce Momjian committed
1951 1952 1953 1954 1955 1956 1957 1958
 *  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'
1959 1960 1961
 *
 *****************************************************************************/
 
1962
CommentStmt:	COMMENT ON comment_type name IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1963 1964 1965 1966 1967 1968 1969 1970 1971
			{
				CommentStmt *n = makeNode(CommentStmt);
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = NULL;
				n->objlist = NULL;
				n->comment = $6;
				$$ = (Node *) n;
			}
1972
		| COMMENT ON comment_cl relation_name '.' attr_name IS comment_text
1973 1974
			{
				CommentStmt *n = makeNode(CommentStmt);
Bruce Momjian's avatar
Bruce Momjian committed
1975 1976 1977 1978
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = $6;
				n->objlist = NULL;
1979 1980 1981
				n->comment = $8;
				$$ = (Node *) n;
			}
1982
		| COMMENT ON comment_ag name aggr_argtype IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1983
			{
1984
				CommentStmt *n = makeNode(CommentStmt);
Bruce Momjian's avatar
Bruce Momjian committed
1985 1986
				n->objtype = $3;
				n->objname = $4;
1987 1988
				n->objproperty = NULL;
				n->objlist = makeList1($5);
Bruce Momjian's avatar
Bruce Momjian committed
1989 1990 1991
				n->comment = $7;
				$$ = (Node *) n;
			}
1992
		| COMMENT ON comment_fn func_name func_args IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
1993 1994 1995 1996 1997 1998 1999 2000 2001
			{
				CommentStmt *n = makeNode(CommentStmt);
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = NULL;
				n->objlist = $5;
				n->comment = $7;
				$$ = (Node *) n;
			}
2002
		| COMMENT ON comment_op all_Op '(' oper_argtypes ')' IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
2003 2004 2005 2006 2007 2008 2009
			{
				CommentStmt *n = makeNode(CommentStmt);
				n->objtype = $3;
				n->objname = $4;
				n->objproperty = NULL;
				n->objlist = $6;
				n->comment = $9;
2010 2011
				$$ = (Node *) n;
			}
2012
		| COMMENT ON comment_tg name ON relation_name IS comment_text
Bruce Momjian's avatar
Bruce Momjian committed
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
			{
				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; }
2046
		; 
2047

2048
comment_text:	Sconst { $$ = $1; }
2049
		| NULL_P { $$ = NULL; }
2050 2051
		;
		
2052 2053
/*****************************************************************************
 *
2054
 *		QUERY:
2055 2056 2057
 *			fetch/move [forward | backward] [ # | all ] [ in <portalname> ]
 *			fetch [ forward | backward | absolute | relative ]
 *			      [ # | all | next | prior ] [ [ in | from ] <portalname> ]
2058 2059 2060
 *
 *****************************************************************************/

2061
FetchStmt:  FETCH direction fetch_how_many from_in name
2062 2063
				{
					FetchStmt *n = makeNode(FetchStmt);
2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
					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);
					}
2075 2076
					n->direction = $2;
					n->howMany = $3;
2077
					n->portalname = $5;
2078
					n->ismove = FALSE;
2079 2080
					$$ = (Node *)n;
				}
2081
		| FETCH fetch_how_many from_in name
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
				{
					FetchStmt *n = makeNode(FetchStmt);
					if ($2 < 0)
					{
						n->howMany = -$2;
						n->direction = BACKWARD;
					}
					else
					{
						n->direction = FORWARD;
						n->howMany = $2;
					}
2094
					n->portalname = $4;
2095
					n->ismove = FALSE;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2096 2097
					$$ = (Node *)n;
				}
2098
		| FETCH direction from_in name
2099 2100 2101 2102 2103 2104 2105 2106 2107
				{
					FetchStmt *n = makeNode(FetchStmt);
					if ($2 == RELATIVE)
					{
						$2 = FORWARD;
					}
					n->direction = $2;
					n->howMany = 1;
					n->portalname = $4;
2108
					n->ismove = FALSE;
2109 2110
					$$ = (Node *)n;
				}
2111
		| FETCH from_in name
2112 2113 2114 2115 2116
				{
					FetchStmt *n = makeNode(FetchStmt);
					n->direction = FORWARD;
					n->howMany = 1;
					n->portalname = $3;
2117
					n->ismove = FALSE;
2118 2119
					$$ = (Node *)n;
				}
2120
		| FETCH name
2121 2122 2123 2124 2125
				{
					FetchStmt *n = makeNode(FetchStmt);
					n->direction = FORWARD;
					n->howMany = 1;
					n->portalname = $2;
2126
					n->ismove = FALSE;
2127 2128 2129
					$$ = (Node *)n;
				}

2130
		| MOVE direction fetch_how_many from_in name
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2131 2132
				{
					FetchStmt *n = makeNode(FetchStmt);
2133 2134 2135 2136 2137
					if ($3 < 0)
					{
						$3 = -$3;
						$2 = (($2 == FORWARD)? BACKWARD: FORWARD);
					}
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2138 2139
					n->direction = $2;
					n->howMany = $3;
2140 2141 2142 2143
					n->portalname = $5;
					n->ismove = TRUE;
					$$ = (Node *)n;
				}
2144
		| MOVE fetch_how_many from_in name
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
				{
					FetchStmt *n = makeNode(FetchStmt);
					if ($2 < 0)
					{
						n->howMany = -$2;
						n->direction = BACKWARD;
					}
					else
					{
						n->direction = FORWARD;
						n->howMany = $2;
					}
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2157
					n->portalname = $4;
2158
					n->ismove = TRUE;
2159 2160
					$$ = (Node *)n;
				}
2161
		| MOVE direction from_in name
2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178
				{
					FetchStmt *n = makeNode(FetchStmt);
					n->direction = $2;
					n->howMany = 1;
					n->portalname = $4;
					n->ismove = TRUE;
					$$ = (Node *)n;
				}
		|	MOVE from_in name
				{
					FetchStmt *n = makeNode(FetchStmt);
					n->direction = FORWARD;
					n->howMany = 1;
					n->portalname = $3;
					n->ismove = TRUE;
					$$ = (Node *)n;
				}
2179
		| MOVE name
2180 2181 2182 2183 2184 2185 2186 2187
				{
					FetchStmt *n = makeNode(FetchStmt);
					n->direction = FORWARD;
					n->howMany = 1;
					n->portalname = $2;
					n->ismove = TRUE;
					$$ = (Node *)n;
				}
2188 2189
		;

2190
direction:	FORWARD					{ $$ = FORWARD; }
2191 2192 2193 2194 2195 2196 2197
		| BACKWARD						{ $$ = BACKWARD; }
		| RELATIVE						{ $$ = RELATIVE; }
		| ABSOLUTE
			{
				elog(NOTICE,"FETCH/ABSOLUTE not supported, using RELATIVE");
				$$ = RELATIVE;
			}
2198
		;
2199

2200 2201
fetch_how_many:  Iconst					{ $$ = $1; }
		| '-' Iconst					{ $$ = - $2; }
2202
		| ALL							{ $$ = 0; /* 0 means fetch all tuples*/ }
2203 2204
		| NEXT							{ $$ = 1; }
		| PRIOR							{ $$ = -1; }
2205
		;
2206

2207 2208 2209
from_in:  IN 
	| FROM
	;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
2210

2211

2212 2213
/*****************************************************************************
 *
2214 2215
 *		QUERY:
 *				GRANT [privileges] ON [relation_name_list] TO [GROUP] grantee
2216 2217 2218
 *
 *****************************************************************************/

2219
GrantStmt:  GRANT privileges ON relation_name_list TO grantee opt_with_grant
2220 2221 2222 2223
				{
					$$ = (Node*)makeAclStmt($2,$4,$6,'+');
				}
		;
2224 2225

privileges:  ALL PRIVILEGES
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
				{
				 $$ = aclmakepriv("rwaR",0);
				}
		| ALL
				{
				 $$ = aclmakepriv("rwaR",0);
				}
		| operation_commalist
				{
				 $$ = $1;
				}
		;

2239
operation_commalist:  operation
2240 2241 2242 2243 2244 2245 2246 2247 2248
				{
						$$ = aclmakepriv("",$1);
				}
		| operation_commalist ',' operation
				{
						$$ = aclmakepriv($1,$3);
				}
		;

2249
operation:  SELECT
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
				{
						$$ = ACL_MODE_RD_CHR;
				}
		| INSERT
				{
						$$ = ACL_MODE_AP_CHR;
				}
		| UPDATE
				{
						$$ = ACL_MODE_WR_CHR;
				}
		| DELETE
				{
						$$ = ACL_MODE_WR_CHR;
				}
2265
		| RULE
2266 2267 2268 2269 2270 2271 2272 2273 2274
				{
						$$ = ACL_MODE_RU_CHR;
				}
		;

grantee:  PUBLIC
				{
						$$ = aclmakeuser("A","");
				}
2275
		| GROUP ColId
2276 2277 2278
				{
						$$ = aclmakeuser("G",$2);
				}
2279
		| ColId
2280 2281 2282 2283
				{
						$$ = aclmakeuser("U",$1);
				}
		;
2284

2285
opt_with_grant:  WITH GRANT OPTION
2286
				{
2287
					elog(ERROR,"WITH GRANT OPTION is not supported.  Only relation owners can set privileges");
2288 2289
				 }
		| /*EMPTY*/
2290 2291
		;

2292

2293 2294
/*****************************************************************************
 *
2295 2296
 *		QUERY:
 *				REVOKE [privileges] ON [relation_name] FROM [user]
2297 2298 2299
 *
 *****************************************************************************/

2300
RevokeStmt:  REVOKE privileges ON relation_name_list FROM grantee
2301 2302 2303 2304
				{
					$$ = (Node*)makeAclStmt($2,$4,$6,'-');
				}
		;
2305

2306

2307 2308
/*****************************************************************************
 *
2309
 *		QUERY:
Bruce Momjian's avatar
Bruce Momjian committed
2310
 *				create index <indexname> on <relname>
2311 2312
 *				  using <access> "(" (<col> with <op>)+ ")" [with
 *				  <target_list>]
2313
 *
2314
 *	[where <qual>] is not supported anymore
2315 2316
 *****************************************************************************/

2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
IndexStmt:	CREATE index_opt_unique INDEX index_name ON relation_name
			access_method_clause '(' index_params ')' opt_with
				{
					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;
				}
		;

2332 2333
index_opt_unique:  UNIQUE						{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
2334 2335
		;

2336 2337
access_method_clause:  USING access_method		{ $$ = $2; }
		| /*EMPTY*/								{ $$ = "btree"; }
2338
		;
2339

2340
index_params:  index_list						{ $$ = $1; }
2341
		| func_index							{ $$ = makeList1($1); }
2342 2343 2344
		;

index_list:  index_list ',' index_elem			{ $$ = lappend($1, $3); }
2345
		| index_elem							{ $$ = makeList1($1); }
2346 2347
		;

2348
func_index:  func_name '(' name_list ')' opt_class
2349 2350 2351 2352
				{
					$$ = makeNode(IndexElem);
					$$->name = $1;
					$$->args = $3;
2353
					$$->class = $5;
2354 2355 2356
				}
		  ;

2357
index_elem:  attr_name opt_class
2358 2359 2360 2361
				{
					$$ = makeNode(IndexElem);
					$$->name = $1;
					$$->args = NIL;
2362
					$$->class = $2;
2363 2364 2365
				}
		;

2366 2367 2368
opt_class:  class
				{
					/*
Tom Lane's avatar
Tom Lane committed
2369 2370 2371 2372 2373 2374 2375
					 * Release 7.0 removed network_ops, timespan_ops, and
					 * datetime_ops, so we suppress it from being passed to
					 * the parser so the default *_ops is used.  This can be
					 * removed in some later release.  bjm 2000/02/07
					 *
					 * Release 7.1 removes lztext_ops, so suppress that too
					 * for a while.  tgl 2000/07/30
2376 2377 2378
					 */
					if (strcmp($1, "network_ops") != 0 &&
						strcmp($1, "timespan_ops") != 0 &&
Tom Lane's avatar
Tom Lane committed
2379 2380
						strcmp($1, "datetime_ops") != 0 &&
						strcmp($1, "lztext_ops") != 0)
2381 2382 2383 2384
						$$ = $1;
					else
						$$ = NULL;
				}
2385
		| USING class							{ $$ = $2; }
2386 2387 2388 2389
		| /*EMPTY*/								{ $$ = NULL; }
		;


2390 2391
/*****************************************************************************
 *
2392 2393
 *		QUERY:
 *				extend index <indexname> [where <qual>]
2394 2395 2396 2397
 *
 *****************************************************************************/

ExtendStmt:  EXTEND INDEX index_name where_clause
2398 2399 2400 2401 2402 2403 2404
				{
					ExtendStmt *n = makeNode(ExtendStmt);
					n->idxname = $3;
					n->whereClause = $4;
					$$ = (Node *)n;
				}
		;
2405 2406 2407

/*****************************************************************************
 *
2408 2409
 *		QUERY:
 *				execute recipe <recipeName>
2410 2411 2412
 *
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
2413
/* NOT USED
2414
RecipeStmt:  EXECUTE RECIPE recipe_name
2415
				{
2416
					RecipeStmt *n = makeNode(RecipeStmt);
2417 2418 2419 2420
					n->recipeName = $3;
					$$ = (Node *)n;
				}
		;
Bruce Momjian's avatar
Bruce Momjian committed
2421
*/
2422 2423 2424

/*****************************************************************************
 *
2425 2426
 *		QUERY:
 *				define function <fname>
2427 2428 2429 2430 2431
 *						[(<type-1> { , <type-n>})]
 *						returns <type-r>
 *						as <filename or code in language as appropriate>
 *						language <lang> [with
 *						[  arch_pct = <percentage | pre-defined>]
2432 2433 2434 2435
 *						[, disk_pct = <percentage | pre-defined>]
 *						[, byte_pct = <percentage | pre-defined>]
 *						[, perbyte_cpu = <int | pre-defined>]
 *						[, percall_cpu = <int | pre-defined>]
2436
 *						[, iscachable] ]
2437 2438 2439
 *
 *****************************************************************************/

2440
ProcedureStmt:	CREATE FUNCTION func_name func_args
2441
			 RETURNS func_return AS func_as LANGUAGE Sconst opt_with
2442 2443 2444
				{
					ProcedureStmt *n = makeNode(ProcedureStmt);
					n->funcname = $3;
2445
					n->argTypes = $4;
2446 2447 2448 2449
					n->returnType = (Node *)$6;
					n->withClause = $11;
					n->as = $8;
					n->language = $10;
2450 2451 2452 2453
					$$ = (Node *)n;
				};

opt_with:  WITH definition						{ $$ = $2; }
2454
		| /*EMPTY*/								{ $$ = NIL; }
2455 2456
		;

2457
func_args:  '(' func_args_list ')'				{ $$ = $2; }
2458
		| '(' ')'								{ $$ = NIL; }
2459
		;
2460

2461
func_args_list:  func_arg
2462
				{	$$ = makeList1($1); }
2463
		| func_args_list ',' func_arg
2464
				{	$$ = lappend($1, $3); }
2465 2466
		;

2467
func_arg:  opt_arg Typename
2468
				{
2469 2470 2471 2472
					/* We can catch over-specified arguments here if we want to,
					 * but for now better to silently swallow typmod, etc.
					 * - thomas 2000-03-22
					 */
2473 2474
					$$ = $2;
				}
2475
		| Typename
2476
				{
2477 2478
					$$ = $1;
				}
2479 2480
		;

2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
opt_arg:  IN
				{
					$$ = FALSE;
				}
		| OUT
				{
					elog(ERROR, "CREATE FUNCTION/OUT parameters are not supported");
					$$ = TRUE;
				}
		| INOUT
				{
					elog(ERROR, "CREATE FUNCTION/INOUT parameters are not supported");
					$$ = FALSE;
				}
		;

2497
func_as: Sconst
2498
				{   $$ = makeList1(makeString($1)); }
2499
		| Sconst ',' Sconst
2500
				{ 	$$ = makeList2(makeString($1), makeString($3)); }
2501 2502
		;

2503
func_return:  Typename
2504
				{
2505 2506 2507 2508 2509 2510
					/* We can catch over-specified arguments here if we want to,
					 * but for now better to silently swallow typmod, etc.
					 * - thomas 2000-03-22
					 */
					$$ = $1;
				}
2511 2512
		;

2513 2514 2515

/*****************************************************************************
 *
2516
 *		QUERY:
2517
 *
2518 2519 2520
 *		DROP FUNCTION funcname (arg1, arg2, ...)
 *		DROP AGGREGATE aggname aggtype
 *		DROP OPERATOR opname (leftoperand_typ rightoperand_typ)
2521 2522 2523
 *
 *****************************************************************************/

2524
RemoveFuncStmt:  DROP FUNCTION func_name func_args
2525
				{
2526 2527 2528
					RemoveFuncStmt *n = makeNode(RemoveFuncStmt);
					n->funcname = $3;
					n->args = $4;
2529 2530 2531 2532
					$$ = (Node *)n;
				}
		;

2533
RemoveAggrStmt:  DROP AGGREGATE func_name aggr_argtype
2534 2535 2536
				{
						RemoveAggrStmt *n = makeNode(RemoveAggrStmt);
						n->aggname = $3;
2537
						n->aggtype = (Node *) $4;
2538 2539 2540 2541
						$$ = (Node *)n;
				}
		;

2542
aggr_argtype:  Typename							{ $$ = $1; }
2543
		| '*'									{ $$ = NULL; }
2544
		;
2545

2546
RemoveOperStmt:  DROP OPERATOR all_Op '(' oper_argtypes ')'
2547 2548 2549 2550 2551 2552 2553
				{
					RemoveOperStmt *n = makeNode(RemoveOperStmt);
					n->opname = $3;
					n->args = $5;
					$$ = (Node *)n;
				}
		;
2554

2555
oper_argtypes:	Typename
2556
				{
Bruce Momjian's avatar
Bruce Momjian committed
2557
				   elog(ERROR,"parser: argument type missing (use NONE for unary operators)");
2558
				}
2559 2560 2561 2562 2563 2564
		| Typename ',' Typename
				{ $$ = makeList2($1, $3); }
		| NONE ',' Typename			/* left unary */
				{ $$ = makeList2(NULL, $3); }
		| Typename ',' NONE			/* right unary */
				{ $$ = makeList2($1, NULL); }
2565
		;
2566

2567

Hiroshi Inoue's avatar
Hiroshi Inoue committed
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
/*****************************************************************************
 *
 *		QUERY:
 *
 *		REINDEX type <typename> [FORCE] [ALL]
 *
 *****************************************************************************/

ReindexStmt:  REINDEX reindex_type name opt_force
				{
					ReindexStmt *n = makeNode(ReindexStmt);
					n->reindexType = $2;
					n->name = $3;
					n->force = $4;
					$$ = (Node *)n;
				}
		;

2586 2587 2588
reindex_type:  INDEX								{  $$ = INDEX; }
		| TABLE										{  $$ = TABLE; }
		| DATABASE									{  $$ = DATABASE; }
Hiroshi Inoue's avatar
Hiroshi Inoue committed
2589 2590 2591 2592 2593 2594
		;
opt_force:	FORCE									{  $$ = TRUE; }
		| /* EMPTY */								{  $$ = FALSE; }
		;


2595 2596
/*****************************************************************************
 *
2597 2598 2599
 *		QUERY:
 *				rename <attrname1> in <relname> [*] to <attrname2>
 *				rename <relname1> to <relname2>
2600
 *
2601 2602
 *****************************************************************************/

2603
RenameStmt:  ALTER TABLE relation_name opt_inh_star
2604 2605 2606 2607
				  RENAME opt_column opt_name TO name
				{
					RenameStmt *n = makeNode(RenameStmt);
					n->relname = $3;
2608
					n->inhOpt = $4;
2609 2610 2611 2612 2613 2614 2615
					n->column = $7;
					n->newname = $9;
					$$ = (Node *)n;
				}
		;

opt_name:  name							{ $$ = $1; }
2616
		| /*EMPTY*/						{ $$ = NULL; }
2617 2618 2619 2620 2621
		;

opt_column:  COLUMN						{ $$ = COLUMN; }
		| /*EMPTY*/						{ $$ = 0; }
		;
2622 2623 2624


/*****************************************************************************
2625
 *
2626 2627
 *		QUERY:	Define Rewrite Rule , Define Tuple Rule
 *				Define Rule <old rules >
2628
 *
2629
 *		only rewrite rule is supported -- ay 9/94
2630
 *
2631 2632
 *****************************************************************************/

2633
RuleStmt:  CREATE RULE name AS
2634 2635
		   { QueryIsRule=TRUE; }
		   ON event TO event_object where_clause
2636
		   DO opt_instead RuleActionList
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648
				{
					RuleStmt *n = makeNode(RuleStmt);
					n->rulename = $3;
					n->event = $7;
					n->object = $9;
					n->whereClause = $10;
					n->instead = $12;
					n->actions = $13;
					$$ = (Node *)n;
				}
		;

2649 2650 2651 2652
RuleActionList:  NOTHING				{ $$ = NIL; }
		| RuleActionStmt				{ $$ = makeList1($1); }
		| '[' RuleActionMulti ']'		{ $$ = $2; }
		| '(' RuleActionMulti ')'		{ $$ = $2; } 
2653
		;
2654

2655 2656
/* the thrashing around here is to discard "empty" statements... */
RuleActionMulti:  RuleActionMulti ';' RuleActionStmtOrEmpty
2657
				{ if ($3 != (Node *) NULL)
2658
					$$ = lappend($1, $3);
2659 2660 2661 2662
				  else
					$$ = $1;
				}
		| RuleActionStmtOrEmpty
2663 2664
				{ if ($1 != (Node *) NULL)
					$$ = makeList1($1);
2665 2666 2667
				  else
					$$ = NIL;
				}
2668
		;
2669

2670
RuleActionStmt:	SelectStmt
2671
		| InsertStmt
2672 2673 2674 2675 2676
		| UpdateStmt
		| DeleteStmt
		| NotifyStmt
		;

2677 2678 2679 2680 2681
RuleActionStmtOrEmpty:	RuleActionStmt
		|	/*EMPTY*/
				{ $$ = (Node *)NULL; }
		;

2682
event_object:  relation_name '.' attr_name
2683 2684 2685 2686
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
					$$->paramNo = NULL;
2687
					$$->attrs = makeList1(makeString($3));
2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
					$$->indirection = NIL;
				}
		| relation_name
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
					$$->paramNo = NULL;
					$$->attrs = NIL;
					$$->indirection = NIL;
				}
		;
2699 2700

/* change me to select, update, etc. some day */
2701 2702 2703 2704 2705
event:	SELECT							{ $$ = CMD_SELECT; }
		| UPDATE						{ $$ = CMD_UPDATE; }
		| DELETE						{ $$ = CMD_DELETE; }
		| INSERT						{ $$ = CMD_INSERT; }
		 ;
2706

2707
opt_instead:  INSTEAD					{ $$ = TRUE; }
2708
		| /*EMPTY*/						{ $$ = FALSE; }
2709
		;
2710 2711 2712 2713


/*****************************************************************************
 *
2714 2715 2716
 *		QUERY:
 *				NOTIFY <relation_name>	can appear both in rule bodies and
 *				as a query-level command
2717 2718 2719
 *
 *****************************************************************************/

2720
NotifyStmt:  NOTIFY relation_name
2721 2722 2723 2724 2725 2726
				{
					NotifyStmt *n = makeNode(NotifyStmt);
					n->relname = $2;
					$$ = (Node *)n;
				}
		;
2727

2728
ListenStmt:  LISTEN relation_name
2729 2730 2731 2732 2733
				{
					ListenStmt *n = makeNode(ListenStmt);
					n->relname = $2;
					$$ = (Node *)n;
				}
2734 2735
;

2736 2737 2738 2739 2740 2741
UnlistenStmt:  UNLISTEN relation_name
				{
					UnlistenStmt *n = makeNode(UnlistenStmt);
					n->relname = $2;
					$$ = (Node *)n;
				}
2742 2743 2744 2745 2746 2747
		| UNLISTEN '*'
				{
					UnlistenStmt *n = makeNode(UnlistenStmt);
					n->relname = "*";
					$$ = (Node *)n;
				}
2748 2749
;

2750 2751 2752

/*****************************************************************************
 *
2753
 *		Transactions:
2754
 *
2755 2756
 *      BEGIN / COMMIT / ROLLBACK
 *      (also older versions END / ABORT)
2757
 *
2758 2759
 *****************************************************************************/

2760
TransactionStmt: ABORT_TRANS opt_trans
2761 2762
				{
					TransactionStmt *n = makeNode(TransactionStmt);
2763
					n->command = ROLLBACK;
2764 2765
					$$ = (Node *)n;
				}
2766
		| BEGIN_TRANS opt_trans
2767 2768 2769 2770 2771
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = BEGIN_TRANS;
					$$ = (Node *)n;
				}
2772
		| COMMIT opt_trans
2773 2774
				{
					TransactionStmt *n = makeNode(TransactionStmt);
2775
					n->command = COMMIT;
2776 2777
					$$ = (Node *)n;
				}
2778 2779 2780 2781 2782 2783
		| COMMIT opt_trans opt_chain
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = COMMIT;
					$$ = (Node *)n;
				}
2784
		| END_TRANS opt_trans
2785 2786
				{
					TransactionStmt *n = makeNode(TransactionStmt);
2787
					n->command = COMMIT;
2788 2789
					$$ = (Node *)n;
				}
2790
		| ROLLBACK opt_trans
2791 2792
				{
					TransactionStmt *n = makeNode(TransactionStmt);
2793
					n->command = ROLLBACK;
2794 2795
					$$ = (Node *)n;
				}
2796 2797 2798 2799 2800 2801
		| ROLLBACK opt_trans opt_chain
				{
					TransactionStmt *n = makeNode(TransactionStmt);
					n->command = ROLLBACK;
					$$ = (Node *)n;
				}
2802
		;
2803

2804 2805 2806
opt_trans: WORK									{ $$ = TRUE; }
		| TRANSACTION							{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = TRUE; }
2807
		;
2808

2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821
opt_chain: AND NO CHAIN
				{ $$ = FALSE; }
		| AND CHAIN
				{
					/* SQL99 asks that conforming dbs reject AND CHAIN
					 * if they don't support it. So we can't just ignore it.
					 * - thomas 2000-08-06
					 */
					elog(ERROR, "COMMIT/CHAIN not yet supported");
					$$ = TRUE;
				}
		;

2822 2823 2824

/*****************************************************************************
 *
2825 2826
 *		QUERY:
 *				define view <viewname> '('target-list ')' [where <quals> ]
2827 2828 2829
 *
 *****************************************************************************/

2830
ViewStmt:  CREATE VIEW name opt_column_list AS SelectStmt
2831 2832 2833
				{
					ViewStmt *n = makeNode(ViewStmt);
					n->viewname = $3;
2834
					n->aliases = $4;
2835
					n->query = (Query *) $6;
2836 2837 2838
					$$ = (Node *)n;
				}
		;
2839 2840 2841 2842


/*****************************************************************************
 *
2843 2844
 *		QUERY:
 *				load "filename"
2845 2846 2847
 *
 *****************************************************************************/

2848
LoadStmt:  LOAD file_name
2849 2850 2851 2852 2853 2854
				{
					LoadStmt *n = makeNode(LoadStmt);
					n->filename = $2;
					$$ = (Node *)n;
				}
		;
2855 2856 2857 2858


/*****************************************************************************
 *
2859 2860
 *		CREATE DATABASE
 *
2861 2862 2863
 *
 *****************************************************************************/

2864
CreatedbStmt:  CREATE DATABASE database_name WITH createdb_opt_list
2865
				{
2866
					CreatedbStmt *n = makeNode(CreatedbStmt);
2867
					List   *l;
2868

2869
					n->dbname = $3;
2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
					/* set default options */
					n->dbpath = NULL;
					n->dbtemplate = NULL;
					n->encoding = -1;
					/* process additional options */
					foreach(l, $5)
					{
						List   *optitem = (List *) lfirst(l);

						switch (lfirsti(optitem))
						{
							case 1:
								n->dbpath = (char *) lsecond(optitem);
								break;
							case 2:
								n->dbtemplate = (char *) lsecond(optitem);
								break;
							case 3:
								n->encoding = lfirsti(lnext(optitem));
								break;
						}
					}
2892 2893
					$$ = (Node *)n;
				}
2894 2895 2896 2897 2898
		| CREATE DATABASE database_name
				{
					CreatedbStmt *n = makeNode(CreatedbStmt);
					n->dbname = $3;
					n->dbpath = NULL;
2899 2900
					n->dbtemplate = NULL;
					n->encoding = -1;
2901 2902 2903 2904
					$$ = (Node *)n;
				}
		;

2905 2906 2907 2908
createdb_opt_list:  createdb_opt_item
				{ $$ = makeList1($1); }
		| createdb_opt_list createdb_opt_item
				{ $$ = lappend($1, $2); }
2909 2910
		;

2911 2912 2913 2914 2915
/*
 * createdb_opt_item returns 2-element lists, with the first element
 * being an integer code to indicate which item was specified.
 */
createdb_opt_item:  LOCATION '=' Sconst
2916
				{
2917 2918 2919 2920
					$$ = lconsi(1, makeList1($3));
				}
		| LOCATION '=' DEFAULT
				{
2921
					$$ = lconsi(1, makeList1(NULL));
2922 2923 2924 2925 2926 2927 2928
				}
		| TEMPLATE '=' name
				{
					$$ = lconsi(2, makeList1($3));
				}
		| TEMPLATE '=' DEFAULT
				{
2929
					$$ = lconsi(2, makeList1(NULL));
2930 2931 2932 2933
				}
		| ENCODING '=' Sconst
				{
					int		encoding;
2934
#ifdef MULTIBYTE
2935 2936
					encoding = pg_char_to_encoding($3);
					if (encoding == -1)
2937
						elog(ERROR, "%s is not a valid encoding name", $3);
2938
#else
2939
					if (strcasecmp($3, GetStandardEncodingName()) != 0)
2940
						elog(ERROR, "Multi-byte support is not enabled");
2941
					encoding = GetStandardEncoding();
2942
#endif
2943
					$$ = lconsi(3, makeListi1(encoding));
2944 2945 2946
				}
		| ENCODING '=' Iconst
				{
2947
#ifdef MULTIBYTE
2948 2949
					if (!pg_get_encent_by_encoding($3))
						elog(ERROR, "%d is not a valid encoding code", $3);
2950
#else
2951
					if ($3 != GetStandardEncoding())
2952
						elog(ERROR, "Multi-byte support is not enabled");
2953
#endif
2954
					$$ = lconsi(3, makeListi1($3));
2955 2956 2957
				}
		| ENCODING '=' DEFAULT
				{
2958
					$$ = lconsi(3, makeListi1(-1));
2959 2960
				}
		;
2961

2962

2963 2964
/*****************************************************************************
 *
2965 2966
 *		DROP DATABASE
 *
2967 2968 2969
 *
 *****************************************************************************/

2970
DropdbStmt:	DROP DATABASE database_name
2971
				{
2972
					DropdbStmt *n = makeNode(DropdbStmt);
2973 2974 2975 2976
					n->dbname = $3;
					$$ = (Node *)n;
				}
		;
2977 2978 2979 2980


/*****************************************************************************
 *
2981 2982
 *		QUERY:
 *				cluster <index_name> on <relation_name>
2983 2984 2985
 *
 *****************************************************************************/

2986
ClusterStmt:  CLUSTER index_name ON relation_name
2987 2988 2989 2990 2991 2992 2993
				{
				   ClusterStmt *n = makeNode(ClusterStmt);
				   n->relname = $4;
				   n->indexname = $2;
				   $$ = (Node*)n;
				}
		;
2994 2995 2996

/*****************************************************************************
 *
2997 2998
 *		QUERY:
 *				vacuum
2999 3000 3001
 *
 *****************************************************************************/

Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
3002
VacuumStmt:  VACUUM opt_verbose opt_analyze
3003 3004 3005 3006 3007 3008 3009 3010
				{
					VacuumStmt *n = makeNode(VacuumStmt);
					n->verbose = $2;
					n->analyze = $3;
					n->vacrel = NULL;
					n->va_spec = NIL;
					$$ = (Node *)n;
				}
3011
		| VACUUM opt_verbose opt_analyze relation_name opt_va_list
3012 3013 3014
				{
					VacuumStmt *n = makeNode(VacuumStmt);
					n->verbose = $2;
3015 3016
					n->analyze = $3;
					n->vacrel = $4;
3017 3018
					n->va_spec = $5;
					if ( $5 != NIL && !$4 )
3019 3020
						elog(ERROR,"VACUUM syntax error at or near \"(\""
							"\n\tRelation name must be specified");
3021 3022 3023 3024
					$$ = (Node *)n;
				}
		;

3025
opt_verbose:  VERBOSE							{ $$ = TRUE; }
3026
		| /*EMPTY*/								{ $$ = FALSE; }
3027 3028
		;

3029
opt_analyze:  ANALYZE							{ $$ = TRUE; }
3030
		|	  ANALYSE /* British */				{ $$ = TRUE; }
3031
		| /*EMPTY*/								{ $$ = FALSE; }
3032
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
3033

3034 3035
opt_va_list:  '(' va_list ')'					{ $$ = $2; }
		| /*EMPTY*/								{ $$ = NIL; }
3036
		;
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
3037

3038
va_list:  name
3039
				{ $$ = makeList1($1); }
3040
		| va_list ',' name
3041
				{ $$ = lappend($1, $3); }
3042
		;
3043

3044

3045 3046
/*****************************************************************************
 *
3047 3048
 *		QUERY:
 *				EXPLAIN query
3049 3050 3051
 *
 *****************************************************************************/

3052
ExplainStmt:  EXPLAIN opt_verbose OptimizableStmt
3053 3054 3055 3056 3057 3058 3059
				{
					ExplainStmt *n = makeNode(ExplainStmt);
					n->verbose = $2;
					n->query = (Query*)$3;
					$$ = (Node *)n;
				}
		;
3060

3061

3062
/*****************************************************************************
3063 3064 3065 3066 3067 3068 3069 3070
 *																			 *
 *		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							 *
 *																			 *
3071 3072
 *****************************************************************************/

Bruce Momjian's avatar
Bruce Momjian committed
3073
OptimizableStmt:  SelectStmt
3074
		| CursorStmt
Bruce Momjian's avatar
Bruce Momjian committed
3075 3076
		| UpdateStmt
		| InsertStmt
3077 3078
		| DeleteStmt					/* by default all are $$=$1 */
		;
3079 3080 3081 3082


/*****************************************************************************
 *
3083 3084
 *		QUERY:
 *				INSERT STATEMENTS
3085
 *
3086 3087
 *****************************************************************************/

Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3088
/* This rule used 'opt_column_list' between 'relation_name' and 'insert_rest'
3089 3090 3091 3092 3093 3094
 * 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
3095
				{
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3096
 					$4->relname = $3;
3097
					$$ = (Node *) $4;
3098 3099
				}
		;
3100

3101
insert_rest:  VALUES '(' target_list ')'
3102
				{
Bruce Momjian's avatar
Bruce Momjian committed
3103
					$$ = makeNode(InsertStmt);
3104
					$$->cols = NIL;
3105
					$$->targetList = $3;
3106
					$$->selectStmt = NULL;
3107
				}
3108 3109 3110
		| DEFAULT VALUES
				{
					$$ = makeNode(InsertStmt);
3111
					$$->cols = NIL;
3112
					$$->targetList = NIL;
3113 3114
					$$->selectStmt = NULL;
				}
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3115
		| SelectStmt
3116
				{
Bruce Momjian's avatar
Bruce Momjian committed
3117
					$$ = makeNode(InsertStmt);
3118
					$$->cols = NIL;
3119 3120
					$$->targetList = NIL;
					$$->selectStmt = $1;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3121
				}
3122
		| '(' columnList ')' VALUES '(' target_list ')'
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3123 3124 3125 3126
				{
					$$ = makeNode(InsertStmt);
					$$->cols = $2;
					$$->targetList = $6;
3127
					$$->selectStmt = NULL;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3128 3129 3130 3131 3132
				}
		| '(' columnList ')' SelectStmt
				{
					$$ = makeNode(InsertStmt);
					$$->cols = $2;
3133 3134
					$$->targetList = NIL;
					$$->selectStmt = $4;
3135 3136 3137
				}
		;

3138
opt_column_list:  '(' columnList ')'			{ $$ = $2; }
3139 3140
		| /*EMPTY*/								{ $$ = NIL; }
		;
3141

3142
columnList:  columnList ',' columnElem
3143 3144
				{ $$ = lappend($1, $3); }
		| columnElem
3145
				{ $$ = makeList1($1); }
3146
		;
3147

3148
columnElem:  ColId opt_indirection
3149 3150 3151 3152 3153 3154 3155
				{
					Ident *id = makeNode(Ident);
					id->name = $1;
					id->indirection = $2;
					$$ = (Node *)id;
				}
		;
3156

3157

3158 3159
/*****************************************************************************
 *
3160 3161
 *		QUERY:
 *				DELETE STATEMENTS
3162 3163
 *
 *****************************************************************************/
3164

3165
DeleteStmt:  DELETE FROM opt_only relation_name where_clause
3166 3167
				{
					DeleteStmt *n = makeNode(DeleteStmt);
3168
					n->inhOpt = $3;
3169 3170
					n->relname = $4;
					n->whereClause = $5;
3171 3172 3173
					$$ = (Node *)n;
				}
		;
3174

Bruce Momjian's avatar
Bruce Momjian committed
3175
LockStmt:	LOCK_P opt_table relation_name opt_lock
3176
				{
3177 3178 3179
					LockStmt *n = makeNode(LockStmt);

					n->relname = $3;
Bruce Momjian's avatar
Bruce Momjian committed
3180
					n->mode = $4;
3181 3182
					$$ = (Node *)n;
				}
3183
		;
3184

Bruce Momjian's avatar
Bruce Momjian committed
3185
opt_lock:  IN lock_type MODE		{ $$ = $2; }
3186 3187
		| /*EMPTY*/				{ $$ = AccessExclusiveLock; }
		;
3188

3189 3190 3191 3192
lock_type:  SHARE ROW EXCLUSIVE	{ $$ = ShareRowExclusiveLock; }
		| ROW opt_lmode			{ $$ = ($2? RowShareLock: RowExclusiveLock); }
		| ACCESS opt_lmode		{ $$ = ($2? AccessShareLock: AccessExclusiveLock); }
		| opt_lmode				{ $$ = ($1? ShareLock: ExclusiveLock); }
3193 3194
		;

3195 3196
opt_lmode:	SHARE				{ $$ = TRUE; }
		| EXCLUSIVE				{ $$ = FALSE; }
3197
		;
3198

3199

3200 3201
/*****************************************************************************
 *
3202
 *		QUERY:
Bruce Momjian's avatar
Bruce Momjian committed
3203
 *				UpdateStmt (UPDATE)
3204 3205 3206
 *
 *****************************************************************************/

3207
UpdateStmt:  UPDATE opt_only relation_name
3208
			  SET update_target_list
3209 3210 3211
			  from_clause
			  where_clause
				{
Bruce Momjian's avatar
Bruce Momjian committed
3212
					UpdateStmt *n = makeNode(UpdateStmt);
3213
					n->inhOpt = $2;
3214 3215 3216 3217
					n->relname = $3;
					n->targetList = $5;
					n->fromClause = $6;
					n->whereClause = $7;
3218 3219 3220
					$$ = (Node *)n;
				}
		;
3221

3222 3223 3224

/*****************************************************************************
 *
3225 3226
 *		QUERY:
 *				CURSOR STATEMENTS
3227 3228
 *
 *****************************************************************************/
Jan Wieck's avatar
Jan Wieck committed
3229
CursorStmt:  DECLARE name opt_cursor CURSOR FOR SelectStmt
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3230
  				{
3231
 					SelectStmt *n = (SelectStmt *)$6;
3232 3233
					n->portalname = $2;
					n->binary = $3;
3234
					$$ = $6;
3235 3236
				}
		;
3237

3238 3239 3240 3241 3242 3243 3244
opt_cursor:  BINARY						{ $$ = TRUE; }
		| INSENSITIVE					{ $$ = FALSE; }
		| SCROLL						{ $$ = FALSE; }
		| INSENSITIVE SCROLL			{ $$ = FALSE; }
		| /*EMPTY*/						{ $$ = FALSE; }
		;

3245 3246
/*****************************************************************************
 *
3247 3248
 *		QUERY:
 *				SELECT STATEMENTS
3249 3250
 *
 *****************************************************************************/
3251

3252 3253 3254 3255 3256
/* A complete SELECT statement looks like this.
 *
 * The rule returns either a single SelectStmt node or a tree of them,
 * representing a set-operation tree.
 *
3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287
 * There is an ambiguity when a sub-SELECT is within an a_expr and there
 * are excess parentheses: do the parentheses belong to the sub-SELECT or
 * to the surrounding a_expr?  We don't really care, but yacc wants to know.
 * To resolve the ambiguity, we are careful to define the grammar so that
 * the decision is staved off as long as possible: as long as we can keep
 * absorbing parentheses into the sub-SELECT, we will do so, and only when
 * it's no longer possible to do that will we decide that parens belong to
 * the expression.  For example, in "SELECT (((SELECT 2)) + 3)" the extra
 * parentheses are treated as part of the sub-select.  The necessity of doing
 * it that way is shown by "SELECT (((SELECT 2)) UNION SELECT 2)".  Had we
 * parsed "((SELECT 2))" as an a_expr, it'd be too late to go back to the
 * SELECT viewpoint when we see the UNION.
 *
 * This approach is implemented by defining a nonterminal select_with_parens,
 * which represents a SELECT with at least one outer layer of parentheses,
 * and being careful to use select_with_parens, never '(' SelectStmt ')',
 * in the expression grammar.  We will then have shift-reduce conflicts
 * which we can resolve in favor of always treating '(' <select> ')' as
 * a select_with_parens.  To resolve the conflicts, the productions that
 * conflict with the select_with_parens productions are manually given
 * precedences lower than the precedence of ')', thereby ensuring that we
 * shift ')' (and then reduce to select_with_parens) rather than trying to
 * reduce the inner <select> nonterminal to something else.  We use UMINUS
 * precedence for this, which is a fairly arbitrary choice.
 *
 * To be able to define select_with_parens itself without ambiguity, we need
 * a nonterminal select_no_parens that represents a SELECT structure with no
 * outermost parentheses.  This is a little bit tedious, but it works.
 *
 * In non-expression contexts, we use SelectStmt which can represent a SELECT
 * with or without outer parentheses.
3288 3289
 */

3290 3291 3292 3293 3294
SelectStmt: select_no_parens			%prec UMINUS
		| select_with_parens			%prec UMINUS
		;

select_with_parens: '(' select_no_parens ')'
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3295
			{
3296
				$$ = $2;
3297
			}
3298
		| '(' select_with_parens ')'
3299 3300 3301 3302
			{
				$$ = $2;
			}
		;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3303

3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323
select_no_parens: simple_select
			{
				$$ = $1;
			}
		| select_clause sort_clause opt_for_update_clause opt_select_limit
			{
				insertSelectOptions((SelectStmt *) $1, $2, $3,
									nth(0, $4), nth(1, $4));
				$$ = $1;
			}
		| select_clause for_update_clause opt_select_limit
			{
				insertSelectOptions((SelectStmt *) $1, NIL, $2,
									nth(0, $3), nth(1, $3));
				$$ = $1;
			}
		| select_clause select_limit
			{
				insertSelectOptions((SelectStmt *) $1, NIL, NIL,
									nth(0, $2), nth(1, $2));
3324
				$$ = $1;
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
3325
			}
3326
		;
3327

3328
select_clause: simple_select
3329
		| select_with_parens
3330
		;
3331

3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346
/*
 * 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
 * operations to be ordered per the precedence specs at the head of this file.
 *
 * As with select_no_parens, simple_select cannot have outer parentheses,
 * but can have parenthesized subclauses.
 *
 * Note that sort clauses cannot be included at this level --- SQL92 requires
 *		SELECT foo UNION SELECT bar ORDER BY baz
 * to be parsed as
 *		(SELECT foo UNION SELECT bar) ORDER BY baz
 * not
 *		SELECT foo UNION (SELECT bar ORDER BY baz)
3347 3348 3349 3350
 * Likewise FOR UPDATE and LIMIT.  Therefore, those clauses are described
 * as part of the select_no_parens production, not simple_select.
 * This does not limit functionality, because you can reintroduce sort and
 * limit clauses inside parentheses.
3351 3352 3353 3354 3355 3356
 *
 * NOTE: only the leftmost component SelectStmt should have INTO.
 * However, this is not checked by the grammar; parse analysis must check it.
 */
simple_select: SELECT opt_distinct target_list
			 into_clause from_clause where_clause
3357
			 group_clause having_clause
3358
				{
Bruce Momjian's avatar
Bruce Momjian committed
3359
					SelectStmt *n = makeNode(SelectStmt);
3360
					n->distinctClause = $2;
3361
					n->targetList = $3;
3362 3363
					n->istemp = (bool) ((Value *) lfirst($4))->val.ival;
					n->into = (char *) lnext($4);
3364 3365 3366 3367 3368 3369
					n->fromClause = $5;
					n->whereClause = $6;
					n->groupClause = $7;
					n->havingClause = $8;
					$$ = (Node *)n;
				}
3370
		| select_clause UNION opt_all select_clause
3371
			{	
3372
				$$ = makeSetOp(SETOP_UNION, $3, $1, $4);
3373
			}
3374
		| select_clause INTERSECT opt_all select_clause
3375
			{
3376
				$$ = makeSetOp(SETOP_INTERSECT, $3, $1, $4);
3377
			}
3378
		| select_clause EXCEPT opt_all select_clause
3379
			{
3380
				$$ = makeSetOp(SETOP_EXCEPT, $3, $1, $4);
3381 3382
			}
		; 
3383

3384
		/* easy way to return two values. Can someone improve this?  bjm */
3385
into_clause:  INTO OptTempTableName		{ $$ = $2; }
3386
		| /*EMPTY*/						{ $$ = makeList1(makeInteger(FALSE)); }
3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
		;

/*
 * Redundancy here is needed to avoid shift/reduce conflicts,
 * since TEMP is not a reserved word.  See also OptTemp.
 *
 * The result is a cons cell (not a true list!) containing
 * a boolean and a table name.
 */
OptTempTableName:  TEMPORARY opt_table relation_name
				{ $$ = lcons(makeInteger(TRUE), (List *) $3); }
			| TEMP opt_table relation_name
				{ $$ = lcons(makeInteger(TRUE), (List *) $3); }
			| LOCAL TEMPORARY opt_table relation_name
				{ $$ = lcons(makeInteger(TRUE), (List *) $4); }
			| LOCAL TEMP opt_table relation_name
				{ $$ = lcons(makeInteger(TRUE), (List *) $4); }
			| GLOBAL TEMPORARY opt_table relation_name
				{
					elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
					$$ = lcons(makeInteger(TRUE), (List *) $4);
				}
			| GLOBAL TEMP opt_table relation_name
				{
					elog(ERROR, "GLOBAL TEMPORARY TABLE is not currently supported");
					$$ = lcons(makeInteger(TRUE), (List *) $4);
				}
			| TABLE relation_name
				{ $$ = lcons(makeInteger(FALSE), (List *) $2); }
			| relation_name
				{ $$ = lcons(makeInteger(FALSE), (List *) $1); }
3418 3419 3420 3421
		;

opt_table:  TABLE								{ $$ = TRUE; }
		| /*EMPTY*/								{ $$ = FALSE; }
3422
		;
3423

3424
opt_all:  ALL									{ $$ = TRUE; }
3425 3426 3427
		| /*EMPTY*/								{ $$ = FALSE; }
		;

3428 3429 3430
/* We use (NIL) as a placeholder to indicate that all target expressions
 * should be placed in the DISTINCT list during parsetree analysis.
 */
3431
opt_distinct:  DISTINCT							{ $$ = makeList1(NIL); }
3432 3433 3434
		| DISTINCT ON '(' expr_list ')'			{ $$ = $4; }
		| ALL									{ $$ = NIL; }
		| /*EMPTY*/								{ $$ = NIL; }
3435
		;
3436

3437 3438
sort_clause:  ORDER BY sortby_list				{ $$ = $3; }
		;
3439

3440
sortby_list:  sortby							{ $$ = makeList1($1); }
3441
		| sortby_list ',' sortby				{ $$ = lappend($1, $3); }
3442
		;
3443

3444
sortby: a_expr OptUseOp
3445 3446
				{
					$$ = makeNode(SortGroupBy);
3447
					$$->node = $1;
3448 3449 3450 3451
					$$->useOp = $2;
				}
		;

3452
OptUseOp:  USING all_Op							{ $$ = $2; }
3453 3454 3455
		| ASC									{ $$ = "<"; }
		| DESC									{ $$ = ">"; }
		| /*EMPTY*/								{ $$ = "<"; /*default*/ }
3456
		;
3457

3458

3459
select_limit:	LIMIT select_limit_value ',' select_offset_value
3460
			{ $$ = makeList2($4, $2); }
3461
		| LIMIT select_limit_value OFFSET select_offset_value
3462
			{ $$ = makeList2($4, $2); }
3463
		| LIMIT select_limit_value
3464
			{ $$ = makeList2(NULL, $2); }
3465
		| OFFSET select_offset_value LIMIT select_limit_value
3466
			{ $$ = makeList2($2, $4); }
3467
		| OFFSET select_offset_value
3468
			{ $$ = makeList2($2, NULL); }
3469 3470 3471 3472
		;

opt_select_limit:	select_limit				{ $$ = $1; }
		| /* EMPTY */							{ $$ = makeList2(NULL,NULL); }
3473 3474
		;

3475
select_limit_value:  Iconst
3476 3477 3478
			{
				Const	*n = makeNode(Const);

3479 3480
				if ($1 < 0)
					elog(ERROR, "LIMIT must not be negative");
3481 3482 3483

				n->consttype	= INT4OID;
				n->constlen		= sizeof(int4);
3484
				n->constvalue	= Int32GetDatum($1);
3485 3486 3487 3488 3489 3490 3491 3492
				n->constisnull	= FALSE;
				n->constbyval	= TRUE;
				n->constisset	= FALSE;
				n->constiscast	= FALSE;
				$$ = (Node *)n;
			}
		| ALL
			{
3493
				/* LIMIT ALL is represented as a NULL constant */
3494 3495 3496 3497
				Const	*n = makeNode(Const);

				n->consttype	= INT4OID;
				n->constlen		= sizeof(int4);
3498 3499
				n->constvalue	= (Datum) 0;
				n->constisnull	= TRUE;
3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
				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);

3520 3521 3522
				if ($1 < 0)
					elog(ERROR, "OFFSET must not be negative");

3523 3524
				n->consttype	= INT4OID;
				n->constlen		= sizeof(int4);
3525
				n->constvalue	= Int32GetDatum($1);
3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541
				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;
			}
		;
3542

3543
/*
3544 3545
 *	jimmy bell-style recursive queries aren't supported in the
 *	current system.
3546
 *
3547 3548
 *	...however, recursive addattr and rename supported.  make special
 *	cases for these.
3549
 */
3550 3551
opt_inh_star:  '*'								{ $$ = INH_YES; }
		| /*EMPTY*/								{ $$ = INH_DEFAULT; }
3552
		;
3553

3554
relation_name_list:  name_list;
3555

3556
name_list:  name
3557
				{	$$ = makeList1(makeString($1)); }
3558
		| name_list ',' name
3559
				{	$$ = lappend($1, makeString($3)); }
3560
		;
3561

3562
group_clause:  GROUP BY expr_list				{ $$ = $3; }
3563 3564
		| /*EMPTY*/								{ $$ = NIL; }
		;
3565

Bruce Momjian's avatar
Bruce Momjian committed
3566 3567
having_clause:  HAVING a_expr
				{
3568
					$$ = $2;
Bruce Momjian's avatar
Bruce Momjian committed
3569
				}
3570 3571
		| /*EMPTY*/								{ $$ = NULL; }
		;
3572

3573
for_update_clause:  FOR UPDATE update_list		{ $$ = $3; }
Jan Wieck's avatar
Jan Wieck committed
3574
		| FOR READ ONLY							{ $$ = NULL; }
3575 3576 3577
		;

opt_for_update_clause:	for_update_clause		{ $$ = $1; }
3578 3579 3580 3581
		| /* EMPTY */							{ $$ = NULL; }
		;

update_list:  OF va_list						{ $$ = $2; }
3582
		| /* EMPTY */							{ $$ = makeList1(NULL); }
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
3583
		;
3584

3585
/*****************************************************************************
3586
 *
3587
 *	clauses common to all Optimizable Stmts:
3588 3589
 *		from_clause		- allow list of both JOIN expressions and table names
 *		where_clause	- qualifications for joins or restrictions
3590
 *
3591 3592
 *****************************************************************************/

3593
from_clause:  FROM from_list					{ $$ = $2; }
3594 3595 3596
		| /*EMPTY*/								{ $$ = NIL; }
		;

3597
from_list:  from_list ',' table_ref				{ $$ = lappend($1, $3); }
3598
		| table_ref								{ $$ = makeList1($1); }
3599 3600
		;

3601 3602 3603 3604 3605 3606
/*
 * table_ref is where an alias clause can be attached.  Note we cannot make
 * alias_clause have an empty production because that causes parse conflicts
 * between table_ref := '(' joined_table ')' alias_clause
 * and joined_table := '(' joined_table ')'.  So, we must have the
 * redundant-looking productions here instead.
3607 3608 3609 3610
 *
 * Note that the SQL spec does not permit a subselect (<derived_table>)
 * without an alias clause, so we don't either.  This avoids the problem
 * of needing to invent a refname for an unlabeled subselect.
3611 3612
 */
table_ref:  relation_expr
3613
				{
3614
					$$ = (Node *) $1;
3615
				}
3616
		| relation_expr alias_clause
3617
				{
3618 3619
					$1->name = $2;
					$$ = (Node *) $1;
3620
				}
3621
		| select_with_parens alias_clause
3622
				{
3623
					RangeSubselect *n = makeNode(RangeSubselect);
3624 3625
					n->subquery = $1;
					n->name = $2;
3626
					$$ = (Node *) n;
3627
				}
3628
		| joined_table
3629
				{
3630
					$$ = (Node *) $1;
3631
				}
3632
		| '(' joined_table ')' alias_clause
3633
				{
3634 3635
					$2->alias = $4;
					$$ = (Node *) $2;
3636 3637 3638
				}
		;

3639 3640 3641 3642 3643 3644 3645 3646 3647
/*
 * It may seem silly to separate joined_table from table_ref, but there is
 * method in SQL92's madness: if you don't do it this way you get reduce-
 * reduce conflicts, because it's not clear to the parser generator whether
 * to expect alias_clause after ')' or not.  For the same reason we must
 * treat 'JOIN' and 'join_type JOIN' separately, rather than allowing
 * join_type to expand to empty; if we try it, the parser generator can't
 * figure out when to reduce an empty join_type right after table_ref.
 *
3648
 * Note that a CROSS JOIN is the same as an unqualified
3649 3650
 * INNER JOIN, and an INNER JOIN/ON has the same shape
 * but a qualification expression to limit membership.
3651
 * A NATURAL JOIN implicitly matches column names between
3652 3653
 * tables and the shape is determined by which columns are
 * in common. We'll collect columns during the later transformations.
3654
 */
3655 3656 3657 3658 3659 3660

joined_table:  '(' joined_table ')'
				{
					$$ = $2;
				}
		| table_ref CROSS JOIN table_ref
3661
				{
3662
					/* CROSS JOIN is same as unqualified inner join */
3663
					JoinExpr *n = makeNode(JoinExpr);
3664 3665 3666 3667 3668 3669
					n->jointype = JOIN_INNER;
					n->isNatural = FALSE;
					n->larg = $1;
					n->rarg = $4;
					n->using = NIL;
					n->quals = NULL;
3670
					$$ = n;
3671
				}
3672
		| table_ref UNIONJOIN table_ref
3673
				{
3674 3675 3676
					/* UNION JOIN is made into 1 token to avoid shift/reduce
					 * conflict against regular UNION keyword.
					 */
3677
					JoinExpr *n = makeNode(JoinExpr);
3678 3679 3680 3681 3682 3683
					n->jointype = JOIN_UNION;
					n->isNatural = FALSE;
					n->larg = $1;
					n->rarg = $3;
					n->using = NIL;
					n->quals = NULL;
3684
					$$ = n;
3685
				}
3686
		| table_ref join_type JOIN table_ref join_qual
3687
				{
3688
					JoinExpr *n = makeNode(JoinExpr);
3689
					n->jointype = $2;
3690
					n->isNatural = FALSE;
3691 3692 3693 3694 3695 3696
					n->larg = $1;
					n->rarg = $4;
					if ($5 != NULL && IsA($5, List))
						n->using = (List *) $5;	/* USING clause */
					else
						n->quals = $5; /* ON clause */
3697
					$$ = n;
3698
				}
3699
		| table_ref JOIN table_ref join_qual
3700
				{
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711
					/* letting join_type reduce to empty doesn't work */
					JoinExpr *n = makeNode(JoinExpr);
					n->jointype = JOIN_INNER;
					n->isNatural = FALSE;
					n->larg = $1;
					n->rarg = $3;
					if ($4 != NULL && IsA($4, List))
						n->using = (List *) $4;	/* USING clause */
					else
						n->quals = $4; /* ON clause */
					$$ = n;
3712
				}
3713
		| table_ref NATURAL join_type JOIN table_ref
3714
				{
3715 3716 3717 3718 3719 3720 3721 3722
					JoinExpr *n = makeNode(JoinExpr);
					n->jointype = $3;
					n->isNatural = TRUE;
					n->larg = $1;
					n->rarg = $5;
					n->using = NIL; /* figure out which columns later... */
					n->quals = NULL; /* fill later */
					$$ = n;
3723
				}
3724
		| table_ref NATURAL JOIN table_ref
3725
				{
3726
					/* letting join_type reduce to empty doesn't work */
3727
					JoinExpr *n = makeNode(JoinExpr);
3728 3729 3730 3731 3732 3733
					n->jointype = JOIN_INNER;
					n->isNatural = TRUE;
					n->larg = $1;
					n->rarg = $4;
					n->using = NIL; /* figure out which columns later... */
					n->quals = NULL; /* fill later */
3734
					$$ = n;
3735 3736
				}
		;
3737

3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758
alias_clause:  AS ColId '(' name_list ')'
				{
					$$ = makeNode(Attr);
					$$->relname = $2;
					$$->attrs = $4;
				}
		| AS ColId
				{
					$$ = makeNode(Attr);
					$$->relname = $2;
				}
		| ColId '(' name_list ')'
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
					$$->attrs = $3;
				}
		| ColId
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
3759
				}
3760 3761
		;

3762 3763 3764 3765
join_type:  FULL join_outer						{ $$ = JOIN_FULL; }
		| LEFT join_outer						{ $$ = JOIN_LEFT; }
		| RIGHT join_outer						{ $$ = JOIN_RIGHT; }
		| INNER_P								{ $$ = JOIN_INNER; }
3766 3767
		;

3768
/* OUTER is just noise... */
3769
join_outer:  OUTER_P							{ $$ = NULL; }
3770
		| /*EMPTY*/								{ $$ = NULL; }
3771 3772
		;

3773 3774 3775 3776 3777
/* JOIN qualification clauses
 * Possibilities are:
 *  USING ( column list ) allows only unqualified column names,
 *                        which must match between tables.
 *  ON expr allows more general qualifications.
3778 3779
 *
 * We return USING as a List node, while an ON-expr will not be a List.
3780 3781
 */

3782 3783
join_qual:  USING '(' name_list ')'				{ $$ = (Node *) $3; }
		| ON a_expr								{ $$ = $2; }
3784 3785 3786 3787 3788
		;


relation_expr:	relation_name
				{
3789
					/* default inheritance */
3790
					$$ = makeNode(RangeVar);
3791
					$$->relname = $1;
3792
					$$->inhOpt = INH_DEFAULT;
3793
					$$->name = NULL;
3794
				}
3795
		| relation_name '*'
3796
				{
3797
					/* inheritance query */
3798
					$$ = makeNode(RangeVar);
3799
					$$->relname = $1;
3800
					$$->inhOpt = INH_YES;
3801
					$$->name = NULL;
3802
				}
3803
		| ONLY relation_name
3804
				{
3805
					/* no inheritance */
3806
					$$ = makeNode(RangeVar);
3807
					$$->relname = $2;
3808
					$$->inhOpt = INH_NO;
3809
					$$->name = NULL;
3810
                }
3811
		;
3812

3813 3814
where_clause:  WHERE a_expr						{ $$ = $2; }
		| /*EMPTY*/								{ $$ = NULL;  /* no qualifiers */ }
3815
		;
3816

3817

3818 3819 3820 3821 3822 3823 3824 3825 3826 3827
/*****************************************************************************
 *
 *	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
 *
 *****************************************************************************/

3828
Typename:  SimpleTypename opt_array_bounds
3829 3830 3831
				{
					$$ = $1;
					$$->arrayBounds = $2;
3832
				}
3833
		| SETOF SimpleTypename
3834
				{
3835
					$$ = $2;
3836 3837 3838 3839
					$$->setof = TRUE;
				}
		;

3840 3841 3842 3843
opt_array_bounds:	opt_array_bounds '[' ']'
				{  $$ = lappend($1, makeInteger(-1)); }
		| opt_array_bounds '[' Iconst ']'
				{  $$ = lappend($1, makeInteger($3)); }
3844 3845 3846 3847
		| /*EMPTY*/
				{  $$ = NIL; }
		;

3848 3849 3850 3851
SimpleTypename:  ConstTypename
		| ConstInterval
		;

3852
ConstTypename:  GenericType
3853
		| Numeric
3854
		| Geometric
3855
		| Bit
3856
		| Character
3857
		| ConstDatetime
3858
		;
3859

3860
GenericType:  IDENT
3861
				{
3862 3863
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType($1);
3864
					$$->typmod = -1;
3865 3866 3867 3868 3869
				}
		;

/* SQL92 numeric data types
 * Check FLOAT() precision limits assuming IEEE floating types.
3870
 * Provide real DECIMAL() and NUMERIC() implementations now - Jan 1998-12-30
3871 3872 3873 3874 3875 3876
 * - thomas 1997-09-18
 */
Numeric:  FLOAT opt_float
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType($2);
3877
					$$->typmod = -1;
3878
				}
3879 3880 3881
		| DOUBLE PRECISION
				{
					$$ = makeNode(TypeName);
3882 3883
					$$->name = xlateSqlType("float8");
					$$->typmod = -1;
3884
				}
3885
		| DECIMAL opt_decimal
3886 3887
				{
					$$ = makeNode(TypeName);
3888
					$$->name = xlateSqlType("decimal");
3889 3890 3891
					$$->typmod = $2;
				}
		| DEC opt_decimal
3892
				{
3893
					$$ = makeNode(TypeName);
3894
					$$->name = xlateSqlType("decimal");
3895
					$$->typmod = $2;
3896 3897 3898 3899
				}
		| NUMERIC opt_numeric
				{
					$$ = makeNode(TypeName);
3900 3901
					$$->name = xlateSqlType("numeric");
					$$->typmod = $2;
3902 3903
				}
		;
3904

3905 3906 3907 3908 3909 3910 3911 3912
Geometric:  PATH_P
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType("path");
					$$->typmod = -1;
				}
		;

3913 3914 3915
opt_float:  '(' Iconst ')'
				{
					if ($2 < 1)
Bruce Momjian's avatar
Bruce Momjian committed
3916
						elog(ERROR,"precision for FLOAT must be at least 1");
3917 3918 3919 3920 3921
					else if ($2 < 7)
						$$ = xlateSqlType("float4");
					else if ($2 < 16)
						$$ = xlateSqlType("float8");
					else
Bruce Momjian's avatar
Bruce Momjian committed
3922
						elog(ERROR,"precision for FLOAT must be less than 16");
3923 3924 3925 3926 3927 3928 3929 3930 3931
				}
		| /*EMPTY*/
				{
					$$ = xlateSqlType("float8");
				}
		;

opt_numeric:  '(' Iconst ',' Iconst ')'
				{
3932
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
3933
						elog(ERROR,"NUMERIC precision %d must be beween 1 and %d",
3934 3935 3936 3937 3938 3939
									$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;
3940 3941 3942
				}
		| '(' Iconst ')'
				{
3943
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
3944
						elog(ERROR,"NUMERIC precision %d must be beween 1 and %d",
3945 3946 3947
									$2, NUMERIC_MAX_PRECISION);

					$$ = ($2 << 16) + VARHDRSZ;
3948 3949 3950
				}
		| /*EMPTY*/
				{
3951 3952
					/* Insert "-1" meaning "default"; may be replaced later */
					$$ = -1;
3953 3954 3955 3956 3957
				}
		;

opt_decimal:  '(' Iconst ',' Iconst ')'
				{
3958
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
3959
						elog(ERROR,"DECIMAL precision %d must be beween 1 and %d",
3960 3961 3962 3963 3964 3965
									$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;
3966 3967 3968
				}
		| '(' Iconst ')'
				{
3969
					if ($2 < 1 || $2 > NUMERIC_MAX_PRECISION)
3970
						elog(ERROR,"DECIMAL precision %d must be beween 1 and %d",
3971 3972 3973
									$2, NUMERIC_MAX_PRECISION);

					$$ = ($2 << 16) + VARHDRSZ;
3974 3975 3976
				}
		| /*EMPTY*/
				{
3977 3978
					/* Insert "-1" meaning "default"; may be replaced later */
					$$ = -1;
3979 3980 3981
				}
		;

3982

3983 3984 3985 3986 3987 3988 3989 3990 3991
/*
 * SQL92 bit-field data types
 * The following implements BIT() and BIT VARYING().
 */
Bit:  bit '(' Iconst ')'
				{
					$$ = makeNode(TypeName);
					$$->name = $1;
					if ($3 < 1)
3992 3993
						elog(ERROR,"length for type '%s' must be at least 1",
							 $1);
3994
					else if ($3 > (MaxAttrSize * BITS_PER_BYTE))
3995
						elog(ERROR,"length for type '%s' cannot exceed %d",
3996
							 $1, (MaxAttrSize * BITS_PER_BYTE));
3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017
					$$->typmod = $3;
				}
		| bit
				{
					$$ = makeNode(TypeName);
					$$->name = $1;
					/* default length, if needed, will be inserted later */
					$$->typmod = -1;
				}
		;

bit:  BIT opt_varying
				{
					char *type;

					if ($2) type = xlateSqlType("varbit");
					else type = xlateSqlType("bit");
					$$ = type;
				}


4018 4019
/*
 * SQL92 character data types
4020 4021 4022 4023 4024
 * The following implements CHAR() and VARCHAR().
 */
Character:  character '(' Iconst ')'
				{
					$$ = makeNode(TypeName);
4025
					$$->name = $1;
4026
					if ($3 < 1)
4027 4028
						elog(ERROR,"length for type '%s' must be at least 1",
							 $1);
4029
					else if ($3 > MaxAttrSize)
4030 4031
						elog(ERROR,"length for type '%s' cannot exceed %d",
							 $1, MaxAttrSize);
4032

4033
					/* we actually implement these like a varlen, so
4034
					 * the first 4 bytes is the length. (the difference
4035 4036
					 * between these and "text" is that we blank-pad and
					 * truncate where necessary)
4037
					 */
4038
					$$->typmod = VARHDRSZ + $3;
4039
				}
4040
		| character
4041 4042
				{
					$$ = makeNode(TypeName);
4043
					$$->name = $1;
4044 4045
					/* default length, if needed, will be inserted later */
					$$->typmod = -1;
4046 4047
				}
		;
4048

4049
character:  CHARACTER opt_varying opt_charset
4050 4051
				{
					char *type, *c;
4052
					if (($3 == NULL) || (strcmp($3, "sql_text") == 0)) {
4053
						if ($2) type = xlateSqlType("varchar");
4054
						else type = xlateSqlType("bpchar");
4055
					} else {
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066
						if ($2) {
							c = palloc(strlen("var") + strlen($3) + 1);
							strcpy(c, "var");
							strcat(c, $3);
							type = xlateSqlType(c);
						} else {
							type = xlateSqlType($3);
						}
					};
					$$ = type;
				}
4067
		| CHAR opt_varying						{ $$ = xlateSqlType($2 ? "varchar": "bpchar"); }
4068
		| VARCHAR								{ $$ = xlateSqlType("varchar"); }
4069 4070 4071
		| NATIONAL CHARACTER opt_varying		{ $$ = xlateSqlType($3 ? "varchar": "bpchar"); }
		| NATIONAL CHAR opt_varying				{ $$ = xlateSqlType($3 ? "varchar": "bpchar"); }
		| NCHAR opt_varying						{ $$ = xlateSqlType($2 ? "varchar": "bpchar"); }
4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085
		;

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

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

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

4086
ConstDatetime:  datetime
4087 4088 4089
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType($1);
4090
					$$->typmod = -1;
4091 4092 4093 4094 4095 4096
				}
		| TIMESTAMP opt_timezone
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType("timestamp");
					$$->timezone = $2;
4097
					$$->typmod = -1;
4098
				}
4099
		| TIME opt_timezone
4100 4101
				{
					$$ = makeNode(TypeName);
4102 4103 4104 4105
					if ($2)
						$$->name = xlateSqlType("timetz");
					else
						$$->name = xlateSqlType("time");
4106
					$$->typmod = -1;
4107
				}
4108 4109 4110
		;

ConstInterval:  INTERVAL opt_interval
4111 4112 4113
				{
					$$ = makeNode(TypeName);
					$$->name = xlateSqlType("interval");
4114
					$$->typmod = -1;
4115
				}
4116
		;
4117

4118 4119 4120 4121 4122 4123 4124 4125 4126
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; }
4127
		| WITHOUT TIME ZONE						{ $$ = FALSE; }
4128 4129 4130
		| /*EMPTY*/								{ $$ = FALSE; }
		;

4131
opt_interval:  datetime							{ $$ = makeList1($1); }
4132 4133 4134 4135 4136 4137
		| 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; }
4138
		| MINUTE_P TO SECOND_P					{ $$ = NIL; }
4139
		| /*EMPTY*/								{ $$ = NIL; }
4140 4141
		;

4142 4143 4144

/*****************************************************************************
 *
4145
 *	expression grammar
4146 4147 4148
 *
 *****************************************************************************/

4149 4150 4151 4152
/* Expressions using row descriptors
 * Define row_descriptor to allow yacc to break the reduce/reduce conflict
 *  with singleton expressions.
 */
4153
row_expr: '(' row_descriptor ')' IN select_with_parens
4154
				{
4155 4156
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
4157
					n->oper = (List *) makeA_Expr(OP, "=", NULL, NULL);
4158
					n->useor = FALSE;
4159
					n->subLinkType = ANY_SUBLINK;
4160
					n->subselect = $5;
4161
					$$ = (Node *)n;
4162
				}
4163
		| '(' row_descriptor ')' NOT IN select_with_parens
4164
				{
4165 4166
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
4167
					n->oper = (List *) makeA_Expr(OP, "<>", NULL, NULL);
4168
					n->useor = TRUE;
4169
					n->subLinkType = ALL_SUBLINK;
4170
					n->subselect = $6;
4171 4172
					$$ = (Node *)n;
				}
4173
		| '(' row_descriptor ')' all_Op sub_type select_with_parens
4174 4175 4176
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
4177 4178
					n->oper = (List *) makeA_Expr(OP, $4, NULL, NULL);
					if (strcmp($4, "<>") == 0)
4179
						n->useor = TRUE;
4180
					else
4181
						n->useor = FALSE;
4182
					n->subLinkType = $5;
4183
					n->subselect = $6;
Bruce Momjian's avatar
Bruce Momjian committed
4184 4185
					$$ = (Node *)n;
				}
4186
		| '(' row_descriptor ')' all_Op select_with_parens
Bruce Momjian's avatar
Bruce Momjian committed
4187 4188 4189
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = $2;
4190 4191
					n->oper = (List *) makeA_Expr(OP, $4, NULL, NULL);
					if (strcmp($4, "<>") == 0)
4192
						n->useor = TRUE;
4193
					else
4194
						n->useor = FALSE;
4195
					n->subLinkType = MULTIEXPR_SUBLINK;
4196
					n->subselect = $5;
Bruce Momjian's avatar
Bruce Momjian committed
4197 4198
					$$ = (Node *)n;
				}
4199
		| '(' row_descriptor ')' all_Op '(' row_descriptor ')'
4200
				{
Bruce Momjian's avatar
Bruce Momjian committed
4201
					$$ = makeRowExpr($4, $2, $6);
4202
				}
4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219
		| '(' row_descriptor ')' OVERLAPS '(' row_descriptor ')'
				{
					FuncCall *n = makeNode(FuncCall);
					List *largs = $2;
					List *rargs = $6;
					n->funcname = xlateSqlFunc("overlaps");
					if (length(largs) == 1)
						largs = lappend(largs, $2);
					else if (length(largs) != 2)
						elog(ERROR, "Wrong number of parameters"
							 " on left side of OVERLAPS expression");
					if (length(rargs) == 1)
						rargs = lappend(rargs, $6);
					else if (length(rargs) != 2)
						elog(ERROR, "Wrong number of parameters"
							 " on right side of OVERLAPS expression");
					n->args = nconc(largs, rargs);
4220 4221
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4222 4223
					$$ = (Node *)n;
				}
4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237
		;

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

row_list:  row_list ',' a_expr
				{
					$$ = lappend($1, $3);
				}
		| a_expr
				{
4238
					$$ = makeList1($1);
4239 4240
				}
		;
4241

4242
sub_type:  ANY								{ $$ = ANY_SUBLINK; }
4243
		| SOME								{ $$ = ANY_SUBLINK; }
4244 4245 4246
		| ALL								{ $$ = ALL_SUBLINK; }
		;

4247 4248
all_Op:  Op | MathOp;

4249
MathOp:  '+'			{ $$ = "+"; }
4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261
		| '-'			{ $$ = "-"; }
		| '*'			{ $$ = "*"; }
		| '/'			{ $$ = "/"; }
		| '%'			{ $$ = "%"; }
		| '^'			{ $$ = "^"; }
		| '<'			{ $$ = "<"; }
		| '>'			{ $$ = ">"; }
		| '='			{ $$ = "="; }
		;

/*
 * General expressions
4262
 * This is the heart of the expression syntax.
4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
 *
 * 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.
 *
4273
 * c_expr is all the productions that are common to a_expr and b_expr;
4274
 * it's factored out just to eliminate redundant coding.
4275
 */
4276
a_expr:  c_expr
4277
				{	$$ = $1;  }
4278
		| a_expr TYPECAST Typename
4279
				{	$$ = makeTypeCast($1, $3); }
4280 4281 4282 4283 4284 4285 4286 4287 4288
		| a_expr AT TIME ZONE c_expr
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "timezone";
					n->args = makeList2($5, $1);
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
					$$ = (Node *) n;
				}
4289 4290 4291 4292 4293 4294 4295 4296 4297
		/*
		 * 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.
		 */
4298
		| '+' a_expr					%prec UMINUS
4299
				{	$$ = makeA_Expr(OP, "+", NULL, $2); }
4300
		| '-' a_expr					%prec UMINUS
4301
				{	$$ = doNegate($2); }
Bruce Momjian's avatar
Bruce Momjian committed
4302
		| '%' a_expr
Bruce Momjian's avatar
Bruce Momjian committed
4303
				{	$$ = makeA_Expr(OP, "%", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
4304 4305
		| '^' a_expr
				{	$$ = makeA_Expr(OP, "^", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
4306
		| a_expr '%'
Bruce Momjian's avatar
Bruce Momjian committed
4307
				{	$$ = makeA_Expr(OP, "%", $1, NULL); }
Bruce Momjian's avatar
Bruce Momjian committed
4308 4309
		| a_expr '^'
				{	$$ = makeA_Expr(OP, "^", $1, NULL); }
4310 4311 4312 4313
		| a_expr '+' a_expr
				{	$$ = makeA_Expr(OP, "+", $1, $3); }
		| a_expr '-' a_expr
				{	$$ = makeA_Expr(OP, "-", $1, $3); }
4314 4315
		| a_expr '*' a_expr
				{	$$ = makeA_Expr(OP, "*", $1, $3); }
4316 4317
		| a_expr '/' a_expr
				{	$$ = makeA_Expr(OP, "/", $1, $3); }
4318 4319
		| a_expr '%' a_expr
				{	$$ = makeA_Expr(OP, "%", $1, $3); }
Bruce Momjian's avatar
Bruce Momjian committed
4320 4321
		| a_expr '^' a_expr
				{	$$ = makeA_Expr(OP, "^", $1, $3); }
4322 4323 4324 4325 4326
		| a_expr '<' a_expr
				{	$$ = makeA_Expr(OP, "<", $1, $3); }
		| a_expr '>' a_expr
				{	$$ = makeA_Expr(OP, ">", $1, $3); }
		| a_expr '=' a_expr
4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339
				{
					/*
					 * Special-case "foo = NULL" and "NULL = foo" for
					 * compatibility with standards-broken products
					 * (like Microsoft's).  Turn these into IS NULL exprs.
					 */
					if (exprIsNullConstant($3))
						$$ = makeA_Expr(ISNULL, NULL, $1, NULL);
					else if (exprIsNullConstant($1))
						$$ = makeA_Expr(ISNULL, NULL, $3, NULL);
					else
						$$ = makeA_Expr(OP, "=", $1, $3);
				}
4340

4341
		| a_expr Op a_expr
4342
				{	$$ = makeA_Expr(OP, $2, $1, $3); }
4343 4344 4345 4346
		| Op a_expr
				{	$$ = makeA_Expr(OP, $1, NULL, $2); }
		| a_expr Op
				{	$$ = makeA_Expr(OP, $2, $1, NULL); }
4347

4348 4349 4350 4351 4352 4353
		| 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); }
4354

4355
		| a_expr LIKE a_expr
4356
				{	$$ = makeA_Expr(OP, "~~", $1, $3); }
4357 4358 4359
		| a_expr LIKE a_expr ESCAPE a_expr
				{
					FuncCall *n = makeNode(FuncCall);
4360
					n->funcname = "like_escape";
4361
					n->args = makeList2($3, $5);
4362 4363
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4364
					$$ = makeA_Expr(OP, "~~", $1, (Node *) n);
4365
				}
4366
		| a_expr NOT LIKE a_expr
4367
				{	$$ = makeA_Expr(OP, "!~~", $1, $4); }
4368 4369 4370
		| a_expr NOT LIKE a_expr ESCAPE a_expr
				{
					FuncCall *n = makeNode(FuncCall);
4371
					n->funcname = "like_escape";
4372
					n->args = makeList2($4, $6);
4373 4374
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4375
					$$ = makeA_Expr(OP, "!~~", $1, (Node *) n);
4376 4377
				}
		| a_expr ILIKE a_expr
4378
				{	$$ = makeA_Expr(OP, "~~*", $1, $3); }
4379 4380 4381
		| a_expr ILIKE a_expr ESCAPE a_expr
				{
					FuncCall *n = makeNode(FuncCall);
4382
					n->funcname = "like_escape";
4383
					n->args = makeList2($3, $5);
4384 4385
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4386
					$$ = makeA_Expr(OP, "~~*", $1, (Node *) n);
4387 4388
				}
		| a_expr NOT ILIKE a_expr
4389
				{	$$ = makeA_Expr(OP, "!~~*", $1, $4); }
4390 4391 4392
		| a_expr NOT ILIKE a_expr ESCAPE a_expr
				{
					FuncCall *n = makeNode(FuncCall);
4393
					n->funcname = "like_escape";
4394
					n->args = makeList2($4, $6);
4395 4396
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4397
					$$ = makeA_Expr(OP, "!~~*", $1, (Node *) n);
4398
				}
4399

4400 4401
		| a_expr ISNULL
				{	$$ = makeA_Expr(ISNULL, NULL, $1, NULL); }
4402
		| a_expr IS NULL_P
4403 4404 4405
				{	$$ = makeA_Expr(ISNULL, NULL, $1, NULL); }
		| a_expr NOTNULL
				{	$$ = makeA_Expr(NOTNULL, NULL, $1, NULL); }
4406
		| a_expr IS NOT NULL_P
4407
				{	$$ = makeA_Expr(NOTNULL, NULL, $1, NULL); }
4408 4409 4410 4411 4412
		/* 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
		 */
4413 4414
		| a_expr IS TRUE_P
				{
4415 4416 4417 4418 4419
					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");
4420
					n->typename->typmod = -1;
4421
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4422
				}
4423
		| a_expr IS NOT FALSE_P
4424
				{
4425 4426 4427 4428 4429
					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");
4430
					n->typename->typmod = -1;
4431
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4432
				}
4433
		| a_expr IS FALSE_P
4434
				{
4435 4436 4437 4438 4439
					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");
4440
					n->typename->typmod = -1;
4441
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4442
				}
4443
		| a_expr IS NOT TRUE_P
4444
				{
4445 4446 4447 4448 4449
					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");
4450
					n->typename->typmod = -1;
4451
					$$ = makeA_Expr(OP, "=", $1,(Node *)n);
4452
				}
4453
		| a_expr BETWEEN b_expr AND b_expr
4454 4455 4456 4457 4458
				{
					$$ = makeA_Expr(AND, NULL,
						makeA_Expr(OP, ">=", $1, $3),
						makeA_Expr(OP, "<=", $1, $5));
				}
4459
		| a_expr NOT BETWEEN b_expr AND b_expr
4460 4461 4462 4463 4464
				{
					$$ = makeA_Expr(OR, NULL,
						makeA_Expr(OP, "<", $1, $4),
						makeA_Expr(OP, ">", $1, $6));
				}
4465
		| a_expr IN in_expr
4466
				{
4467
					/* in_expr returns a SubLink or a list of a_exprs */
4468
					if (IsA($3, SubLink))
4469
					{
4470
							SubLink *n = (SubLink *)$3;
4471
							n->lefthand = makeList1($1);
4472
							n->oper = (List *) makeA_Expr(OP, "=", NULL, NULL);
4473
							n->useor = FALSE;
4474 4475
							n->subLinkType = ANY_SUBLINK;
							$$ = (Node *)n;
4476
					}
4477 4478 4479 4480
					else
					{
						Node *n = NULL;
						List *l;
4481
						foreach(l, (List *) $3)
4482 4483 4484 4485 4486 4487 4488 4489 4490
						{
							Node *cmp = makeA_Expr(OP, "=", $1, lfirst(l));
							if (n == NULL)
								n = cmp;
							else
								n = makeA_Expr(OR, NULL, n, cmp);
						}
						$$ = n;
					}
4491
				}
4492
		| a_expr NOT IN in_expr
4493
				{
4494
					/* in_expr returns a SubLink or a list of a_exprs */
4495
					if (IsA($4, SubLink))
4496
					{
4497
						SubLink *n = (SubLink *)$4;
4498
						n->lefthand = makeList1($1);
4499
						n->oper = (List *) makeA_Expr(OP, "<>", NULL, NULL);
4500
						n->useor = FALSE;
4501 4502 4503 4504 4505 4506 4507
						n->subLinkType = ALL_SUBLINK;
						$$ = (Node *)n;
					}
					else
					{
						Node *n = NULL;
						List *l;
4508
						foreach(l, (List *) $4)
4509 4510 4511 4512 4513 4514 4515 4516
						{
							Node *cmp = makeA_Expr(OP, "<>", $1, lfirst(l));
							if (n == NULL)
								n = cmp;
							else
								n = makeA_Expr(AND, NULL, n, cmp);
						}
						$$ = n;
4517 4518
					}
				}
4519
		| a_expr all_Op sub_type select_with_parens
Bruce Momjian's avatar
Bruce Momjian committed
4520 4521
				{
					SubLink *n = makeNode(SubLink);
4522
					n->lefthand = makeList1($1);
4523
					n->oper = (List *) makeA_Expr(OP, $2, NULL, NULL);
4524
					n->useor = FALSE; /* doesn't matter since only one col */
4525
					n->subLinkType = $3;
4526
					n->subselect = $4;
Bruce Momjian's avatar
Bruce Momjian committed
4527 4528
					$$ = (Node *)n;
				}
4529 4530
		| row_expr
				{	$$ = $1;  }
4531
		;
4532

4533 4534 4535 4536 4537
/*
 * Restricted expressions
 *
 * b_expr is a subset of the complete expression syntax defined by a_expr.
 *
4538
 * Presently, AND, NOT, IS, and IN are the a_expr keywords that would
4539 4540
 * cause trouble in the places where b_expr is used.  For simplicity, we
 * just eliminate all the boolean-keyword-operator productions from b_expr.
4541
 */
4542
b_expr:  c_expr
4543
				{	$$ = $1;  }
4544
		| b_expr TYPECAST Typename
4545
				{	$$ = makeTypeCast($1, $3); }
4546
		| '+' b_expr					%prec UMINUS
4547
				{	$$ = makeA_Expr(OP, "+", NULL, $2); }
4548
		| '-' b_expr					%prec UMINUS
4549
				{	$$ = doNegate($2); }
Bruce Momjian's avatar
Bruce Momjian committed
4550 4551
		| '%' b_expr
				{	$$ = makeA_Expr(OP, "%", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
4552 4553
		| '^' b_expr
				{	$$ = makeA_Expr(OP, "^", NULL, $2); }
Bruce Momjian's avatar
Bruce Momjian committed
4554 4555
		| b_expr '%'
				{	$$ = makeA_Expr(OP, "%", $1, NULL); }
Bruce Momjian's avatar
Bruce Momjian committed
4556 4557
		| b_expr '^'
				{	$$ = makeA_Expr(OP, "^", $1, NULL); }
4558 4559 4560 4561
		| b_expr '+' b_expr
				{	$$ = makeA_Expr(OP, "+", $1, $3); }
		| b_expr '-' b_expr
				{	$$ = makeA_Expr(OP, "-", $1, $3); }
4562 4563
		| b_expr '*' b_expr
				{	$$ = makeA_Expr(OP, "*", $1, $3); }
4564 4565
		| b_expr '/' b_expr
				{	$$ = makeA_Expr(OP, "/", $1, $3); }
4566 4567
		| b_expr '%' b_expr
				{	$$ = makeA_Expr(OP, "%", $1, $3); }
4568 4569
		| b_expr '^' b_expr
				{	$$ = makeA_Expr(OP, "^", $1, $3); }
4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592
		| 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.
 */
4593
c_expr:  attr
4594 4595
				{	$$ = (Node *) $1;  }
		| ColId opt_indirection
4596
				{
4597 4598 4599 4600 4601
					/* could be a column name or a relation_name */
					Ident *n = makeNode(Ident);
					n->name = $1;
					n->indirection = $2;
					$$ = (Node *)n;
4602
				}
4603 4604
		| AexprConst
				{	$$ = $1;  }
4605
		| '(' a_expr ')'
4606
				{	$$ = $2; }
4607
		| CAST '(' a_expr AS Typename ')'
4608
				{	$$ = makeTypeCast($3, $5); }
4609 4610
		| case_expr
				{	$$ = $1; }
4611
		| func_name '(' ')'
4612 4613 4614 4615
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = $1;
					n->args = NIL;
4616 4617
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4618 4619
					$$ = (Node *)n;
				}
4620
		| func_name '(' expr_list ')'
4621 4622 4623 4624
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = $1;
					n->args = $3;
4625 4626
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4627 4628
					$$ = (Node *)n;
				}
4629 4630 4631 4632 4633
		| func_name '(' ALL expr_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = $1;
					n->args = $4;
4634 4635
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4636 4637 4638 4639 4640 4641
					/* Ideally we'd mark the FuncCall node to indicate
					 * "must be an aggregate", but there's no provision
					 * for that in FuncCall at the moment.
					 */
					$$ = (Node *)n;
				}
4642 4643 4644 4645 4646
		| func_name '(' DISTINCT expr_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = $1;
					n->args = $4;
4647 4648
					n->agg_star = FALSE;
					n->agg_distinct = TRUE;
4649 4650
					$$ = (Node *)n;
				}
4651 4652 4653 4654 4655 4656 4657 4658 4659 4660
		| 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.
					 *
4661 4662 4663
					 * The FuncCall node is also marked agg_star = true,
					 * so that later processing can detect what the argument
					 * really was.
4664 4665 4666 4667 4668 4669 4670
					 */
					FuncCall *n = makeNode(FuncCall);
					A_Const *star = makeNode(A_Const);

					star->val.type = T_Integer;
					star->val.val.ival = 1;
					n->funcname = $1;
4671
					n->args = makeList1(star);
4672 4673
					n->agg_star = TRUE;
					n->agg_distinct = FALSE;
4674 4675
					$$ = (Node *)n;
				}
4676 4677
		| CURRENT_DATE
				{
4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691
					/*
					 * 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);
4692
					TypeName *t = makeNode(TypeName);
4693
					FuncCall *n = makeNode(FuncCall);
4694

4695 4696 4697
					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;
4698

4699
					t->name = xlateSqlType("text");
4700
					t->setof = FALSE;
4701
					t->typmod = -1;
4702

4703
					n->funcname = xlateSqlType("date");
4704
					n->args = makeList1(s);
4705 4706
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4707

4708 4709 4710 4711
					$$ = (Node *)n;
				}
		| CURRENT_TIME
				{
4712 4713 4714 4715 4716
					/*
					 * Translate as "time('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
					A_Const *s = makeNode(A_Const);
4717
					TypeName *t = makeNode(TypeName);
4718
					FuncCall *n = makeNode(FuncCall);
4719

4720 4721 4722
					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;
4723

4724
					t->name = xlateSqlType("text");
4725
					t->setof = FALSE;
4726
					t->typmod = -1;
4727

4728
					n->funcname = xlateSqlType("time");
4729
					n->args = makeList1(s);
4730 4731
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4732

4733 4734 4735 4736
					$$ = (Node *)n;
				}
		| CURRENT_TIME '(' Iconst ')'
				{
4737 4738 4739 4740
					/*
					 * Translate as "time('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
4741 4742
					A_Const *s = makeNode(A_Const);
					TypeName *t = makeNode(TypeName);
4743
					FuncCall *n = makeNode(FuncCall);
4744 4745 4746 4747 4748

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

4749
					t->name = xlateSqlType("text");
4750
					t->setof = FALSE;
4751
					t->typmod = -1;
4752

4753
					n->funcname = xlateSqlType("time");
4754
					n->args = makeList1(s);
4755 4756
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4757

4758
					if ($3 != 0)
4759 4760
						elog(NOTICE,"CURRENT_TIME(%d) precision not implemented"
							 "; zero used instead",$3);
4761 4762 4763 4764 4765

					$$ = (Node *)n;
				}
		| CURRENT_TIMESTAMP
				{
4766 4767 4768 4769 4770
					/*
					 * Translate as "timestamp('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
					A_Const *s = makeNode(A_Const);
4771
					TypeName *t = makeNode(TypeName);
4772
					FuncCall *n = makeNode(FuncCall);
4773

4774 4775 4776
					s->val.type = T_String;
					s->val.val.str = "now";
					s->typename = t;
4777

4778
					t->name = xlateSqlType("text");
4779
					t->setof = FALSE;
4780
					t->typmod = -1;
4781

4782
					n->funcname = xlateSqlType("timestamp");
4783
					n->args = makeList1(s);
4784 4785
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4786

4787 4788 4789 4790
					$$ = (Node *)n;
				}
		| CURRENT_TIMESTAMP '(' Iconst ')'
				{
4791 4792 4793 4794
					/*
					 * Translate as "timestamp('now'::text)".
					 * See comments for CURRENT_DATE.
					 */
4795 4796
					A_Const *s = makeNode(A_Const);
					TypeName *t = makeNode(TypeName);
4797
					FuncCall *n = makeNode(FuncCall);
4798 4799 4800 4801 4802

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

4803
					t->name = xlateSqlType("text");
4804
					t->setof = FALSE;
4805
					t->typmod = -1;
4806

4807
					n->funcname = xlateSqlType("timestamp");
4808
					n->args = makeList1(s);
4809 4810
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4811

4812
					if ($3 != 0)
4813 4814
						elog(NOTICE,"CURRENT_TIMESTAMP(%d) precision not implemented"
							 "; zero used instead",$3);
4815 4816 4817 4818 4819 4820

					$$ = (Node *)n;
				}
		| CURRENT_USER
				{
					FuncCall *n = makeNode(FuncCall);
4821
					n->funcname = "current_user";
4822
					n->args = NIL;
4823 4824
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4825 4826
					$$ = (Node *)n;
				}
4827 4828 4829
		| SESSION_USER
				{
					FuncCall *n = makeNode(FuncCall);
4830
					n->funcname = "session_user";
4831
					n->args = NIL;
4832 4833
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4834 4835
					$$ = (Node *)n;
				}
4836 4837 4838
		| USER
				{
					FuncCall *n = makeNode(FuncCall);
4839
					n->funcname = "current_user";
4840
					n->args = NIL;
4841 4842
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4843 4844
					$$ = (Node *)n;
				}
4845 4846 4847 4848 4849
		| EXTRACT '(' extract_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "date_part";
					n->args = $3;
4850 4851
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4852 4853
					$$ = (Node *)n;
				}
4854 4855
		| POSITION '(' position_list ')'
				{
4856
					/* position(A in B) is converted to position(B, A) */
4857
					FuncCall *n = makeNode(FuncCall);
4858
					n->funcname = "position";
4859
					n->args = $3;
4860 4861
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4862 4863 4864 4865
					$$ = (Node *)n;
				}
		| SUBSTRING '(' substr_list ')'
				{
4866
					/* substring(A from B for C) is converted to
4867 4868
					 * substring(A, B, C) - thomas 2000-11-28
					 */
4869
					FuncCall *n = makeNode(FuncCall);
4870
					n->funcname = "substring";
4871
					n->args = $3;
4872 4873
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4874 4875 4876 4877
					$$ = (Node *)n;
				}
		| TRIM '(' BOTH trim_list ')'
				{
4878 4879 4880
					/* various trim expressions are defined in SQL92
					 * - thomas 1997-07-19
					 */
4881 4882 4883
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "btrim";
					n->args = $4;
4884 4885
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4886 4887 4888 4889 4890 4891 4892
					$$ = (Node *)n;
				}
		| TRIM '(' LEADING trim_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "ltrim";
					n->args = $4;
4893 4894
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4895 4896 4897 4898 4899 4900 4901
					$$ = (Node *)n;
				}
		| TRIM '(' TRAILING trim_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "rtrim";
					n->args = $4;
4902 4903
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4904 4905 4906 4907 4908 4909 4910
					$$ = (Node *)n;
				}
		| TRIM '(' trim_list ')'
				{
					FuncCall *n = makeNode(FuncCall);
					n->funcname = "btrim";
					n->args = $3;
4911 4912
					n->agg_star = FALSE;
					n->agg_distinct = FALSE;
4913 4914
					$$ = (Node *)n;
				}
4915
		| select_with_parens			%prec UMINUS
4916 4917 4918 4919
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = NIL;
					n->oper = NIL;
4920
					n->useor = FALSE;
4921
					n->subLinkType = EXPR_SUBLINK;
4922
					n->subselect = $1;
4923 4924
					$$ = (Node *)n;
				}
4925
		| EXISTS select_with_parens
4926 4927 4928 4929
				{
					SubLink *n = makeNode(SubLink);
					n->lefthand = NIL;
					n->oper = NIL;
4930
					n->useor = FALSE;
4931
					n->subLinkType = EXISTS_SUBLINK;
4932
					n->subselect = $2;
4933 4934
					$$ = (Node *)n;
				}
4935 4936
		;

4937 4938 4939 4940
/*
 * Supporting nonterminals for expressions.
 */

4941
opt_indirection:	opt_indirection '[' a_expr ']'
4942 4943 4944
				{
					A_Indices *ai = makeNode(A_Indices);
					ai->lidx = NULL;
4945 4946
					ai->uidx = $3;
					$$ = lappend($1, ai);
4947
				}
4948
		| opt_indirection '[' a_expr ':' a_expr ']'
4949 4950
				{
					A_Indices *ai = makeNode(A_Indices);
4951 4952 4953
					ai->lidx = $3;
					ai->uidx = $5;
					$$ = lappend($1, ai);
4954
				}
4955
		| /*EMPTY*/
4956 4957
				{	$$ = NIL; }
		;
4958

4959
expr_list:  a_expr
4960
				{ $$ = makeList1($1); }
4961
		| expr_list ',' a_expr
4962
				{ $$ = lappend($1, $3); }
4963
		| expr_list USING a_expr
4964 4965
				{ $$ = lappend($1, $3); }
		;
4966

4967
extract_list:  extract_arg FROM a_expr
4968 4969 4970 4971
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = $1;
4972
					$$ = makeList2((Node *) n, $3);
4973
				}
4974
		| /*EMPTY*/
4975 4976
				{	$$ = NIL; }
		;
4977

4978 4979 4980
extract_arg:  datetime						{ $$ = $1; }
		| TIMEZONE_HOUR						{ $$ = "tz_hour"; }
		| TIMEZONE_MINUTE					{ $$ = "tz_minute"; }
4981 4982
		;

4983 4984 4985
/* position_list uses b_expr not a_expr to avoid conflict with general IN */

position_list:  b_expr IN b_expr
4986
				{	$$ = makeList2($3, $1); }
4987
		| /*EMPTY*/
4988 4989
				{	$$ = NIL; }
		;
4990

4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
/* SUBSTRING() arguments
 * SQL9x defines a specific syntax for arguments to SUBSTRING():
 * o substring(text from int for int)
 * o substring(text from int) get entire string from starting point "int"
 * o substring(text for int) get first "int" characters of string
 * We also want to implement generic substring functions which accept
 * the usual generic list of arguments. So we will accept both styles
 * here, and convert the SQL9x style to the generic list for further
 * processing. - thomas 2000-11-28
 */
substr_list:  a_expr substr_from substr_for
5002
				{
5003
					$$ = makeList3($1, $2, $3);
5004
				}
5005 5006 5007 5008 5009 5010 5011 5012 5013
		| a_expr substr_for substr_from
				{
					$$ = makeList3($1, $3, $2);
				}
		| a_expr substr_from
				{
					$$ = makeList2($1, $2);
				}
		| a_expr substr_for
5014 5015 5016 5017
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Integer;
					n->val.val.ival = 1;
5018 5019 5020 5021 5022
					$$ = makeList3($1, (Node *)n, $2);
				}
		| expr_list
				{
					$$ = $1;
5023
				}
5024 5025
		| /*EMPTY*/
				{	$$ = NIL; }
5026
		;
5027

5028 5029 5030 5031 5032
substr_from:  FROM a_expr
				{	$$ = $2; }
		;

substr_for:  FOR a_expr
5033 5034
				{	$$ = $2; }
		;
5035

5036
trim_list:  a_expr FROM expr_list
5037
				{ $$ = lappend($3, $1); }
5038
		| FROM expr_list
5039
				{ $$ = $2; }
5040
		| expr_list
5041 5042
				{ $$ = $1; }
		;
5043

5044
in_expr:  select_with_parens
5045
				{
5046 5047 5048
					SubLink *n = makeNode(SubLink);
					n->subselect = $1;
					$$ = (Node *)n;
5049
				}
5050 5051
		| '(' in_expr_nodes ')'
				{	$$ = (Node *)$2; }
5052
		;
5053

5054
in_expr_nodes:  a_expr
5055
				{	$$ = makeList1($1); }
5056 5057
		| in_expr_nodes ',' a_expr
				{	$$ = lappend($1, $3); }
5058
		;
5059

5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086
/* 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);
5087 5088 5089 5090 5091 5092
/*
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Null;
					w->result = (Node *)n;
*/
					w->expr = makeA_Expr(OP, "=", $3, $5);
5093
					c->args = makeList1(w);
5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115
					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
5116
				{ $$ = makeList1($1); }
5117 5118
		;

5119
when_clause:  WHEN a_expr THEN a_expr
5120 5121 5122 5123 5124 5125 5126 5127
				{
					CaseWhen *w = makeNode(CaseWhen);
					w->expr = $2;
					w->result = $4;
					$$ = (Node *)w;
				}
		;

5128
case_default:  ELSE a_expr						{ $$ = $2; }
5129 5130 5131
		| /*EMPTY*/								{ $$ = NULL; }
		;

5132 5133
case_arg:  a_expr
				{	$$ = $1; }
5134 5135 5136 5137
		| /*EMPTY*/
				{	$$ = NULL; }
		;

5138
attr:  relation_name '.' attrs opt_indirection
5139 5140 5141 5142 5143
				{
					$$ = makeNode(Attr);
					$$->relname = $1;
					$$->paramNo = NULL;
					$$->attrs = $3;
5144
					$$->indirection = $4;
5145
				}
5146
		| ParamNo '.' attrs opt_indirection
5147 5148 5149 5150 5151
				{
					$$ = makeNode(Attr);
					$$->relname = NULL;
					$$->paramNo = $1;
					$$->attrs = $3;
5152
					$$->indirection = $4;
5153 5154 5155 5156
				}
		;

attrs:	  attr_name
5157
				{ $$ = makeList1(makeString($1)); }
5158 5159 5160 5161 5162 5163
		| attrs '.' attr_name
				{ $$ = lappend($1, makeString($3)); }
		| attrs '.' '*'
				{ $$ = lappend($1, makeString("*")); }
		;

5164 5165 5166

/*****************************************************************************
 *
5167
 *	target lists
5168 5169 5170
 *
 *****************************************************************************/

5171
/* Target lists as found in SELECT ... and INSERT VALUES ( ... ) */
5172

5173
target_list:  target_list ',' target_el
5174
				{	$$ = lappend($1, $3);  }
5175
		| target_el
5176
				{	$$ = makeList1($1);  }
5177
		;
5178 5179

/* AS is not optional because shift/red conflict with unary ops */
5180
target_el:  a_expr AS ColLabel
5181 5182 5183 5184 5185 5186
				{
					$$ = makeNode(ResTarget);
					$$->name = $3;
					$$->indirection = NULL;
					$$->val = (Node *)$1;
				}
5187
		| a_expr
5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198
				{
					$$ = makeNode(ResTarget);
					$$->name = NULL;
					$$->indirection = NULL;
					$$->val = (Node *)$1;
				}
		| relation_name '.' '*'
				{
					Attr *att = makeNode(Attr);
					att->relname = $1;
					att->paramNo = NULL;
5199
					att->attrs = makeList1(makeString("*"));
5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219
					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;
				}
		;

5220 5221 5222 5223 5224
/* Target list as found in UPDATE table SET ... */

update_target_list:  update_target_list ',' update_target_el
				{	$$ = lappend($1,$3);  }
		| update_target_el
5225
				{	$$ = makeList1($1);  }
5226 5227
		;

5228
update_target_el:  ColId opt_indirection '=' a_expr
5229 5230 5231 5232 5233 5234
				{
					$$ = makeNode(ResTarget);
					$$->name = $1;
					$$->indirection = $2;
					$$->val = (Node *)$4;
				}
5235 5236
		;

5237 5238 5239 5240 5241 5242
/*****************************************************************************
 *
 *	Names and constants
 *
 *****************************************************************************/

5243 5244 5245 5246 5247 5248
relation_name:	SpecialRuleRelation
				{
					$$ = $1;
				}
		| ColId
				{
5249
					/* disallow refs to variable system tables */
5250
					if (strcmp(LogRelationName, $1) == 0
5251
						|| strcmp(VariableRelationName, $1) == 0)
5252
						elog(ERROR,"%s cannot be accessed by users",$1);
5253 5254 5255 5256 5257
					else
						$$ = $1;
				}
		;

5258
name:					ColId			{ $$ = $1; };
5259
database_name:			ColId			{ $$ = $1; };
5260
access_method:			ColId			{ $$ = $1; };
5261
attr_name:				ColId			{ $$ = $1; };
5262
class:					ColId			{ $$ = $1; };
5263
index_name:				ColId			{ $$ = $1; };
5264

5265 5266 5267
/* Functions
 * Include date/time keywords as SQL92 extension.
 * Include TYPE as a SQL92 unreserved keyword. - thomas 1997-10-05
5268 5269 5270 5271 5272 5273 5274 5275 5276 5277
 * Any tokens which show up as operators will screw up the parsing if
 * allowed as identifiers, but are acceptable as ColLabels:
 *  BETWEEN, IN, IS, ISNULL, NOTNULL, OVERLAPS
 * Thanks to Tom Lane for pointing this out. - thomas 2000-03-29
 * We need OVERLAPS allowed as a function name to enable the implementation
 *  of argument type variations on the underlying implementation. These
 *  variations are done as SQL-language entries in the pg_proc catalog.
 * Do not include SUBSTRING here since it has explicit productions
 *  in a_expr to support the goofy SQL9x argument syntax.
 *  - thomas 2000-11-28
5278
 */
5279 5280 5281 5282 5283 5284 5285 5286 5287 5288
func_name:  ColId						{ $$ = xlateSqlFunc($1); }
		| BETWEEN						{ $$ = xlateSqlFunc("between"); }
		| ILIKE							{ $$ = xlateSqlFunc("ilike"); }
		| IN							{ $$ = xlateSqlFunc("in"); }
		| IS							{ $$ = xlateSqlFunc("is"); }
		| ISNULL						{ $$ = xlateSqlFunc("isnull"); }
		| LIKE							{ $$ = xlateSqlFunc("like"); }
		| NOTNULL						{ $$ = xlateSqlFunc("notnull"); }
		| OVERLAPS						{ $$ = xlateSqlFunc("overlaps"); }
		;
5289 5290

file_name:				Sconst			{ $$ = $1; };
5291

5292 5293 5294
/* Constants
 * Include TRUE/FALSE for SQL3 support. - thomas 1997-10-24
 */
5295
AexprConst:  Iconst
5296 5297 5298 5299 5300 5301 5302 5303 5304 5305
				{
					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;
5306
					n->val.val.str = $1;
5307 5308 5309 5310 5311 5312 5313 5314 5315
					$$ = (Node *)n;
				}
		| Sconst
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = $1;
					$$ = (Node *)n;
				}
5316 5317 5318 5319 5320 5321 5322
		| BITCONST
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_BitString;
					n->val.val.str = $1;
					$$ = (Node *)n;
				}
5323
		/* This rule formerly used Typename,
5324 5325 5326 5327
		 * but that causes reduce conflicts with subscripted column names.
		 * Now, separate into ConstTypename and ConstInterval,
		 * to allow implementing the SQL92 syntax for INTERVAL literals.
		 * - thomas 2000-06-24
5328
		 */
5329 5330 5331 5332 5333 5334 5335 5336 5337
		| ConstTypename Sconst
				{
					A_Const *n = makeNode(A_Const);
					n->typename = $1;
					n->val.type = T_String;
					n->val.val.str = $2;
					$$ = (Node *)n;
				}
		| ConstInterval Sconst opt_interval
5338 5339 5340 5341 5342 5343 5344
				{
					A_Const *n = makeNode(A_Const);
					n->typename = $1;
					n->val.type = T_String;
					n->val.val.str = $2;
					$$ = (Node *)n;
				}
5345 5346
		| ParamNo
				{	$$ = (Node *)$1;  }
5347 5348 5349 5350 5351
		| TRUE_P
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "t";
5352 5353
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
5354
					n->typename->typmod = -1;
5355 5356 5357 5358 5359 5360 5361
					$$ = (Node *)n;
				}
		| FALSE_P
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_String;
					n->val.val.str = "f";
5362 5363
					n->typename = makeNode(TypeName);
					n->typename->name = xlateSqlType("bool");
5364
					n->typename->typmod = -1;
5365 5366
					$$ = (Node *)n;
				}
5367 5368 5369 5370 5371 5372
		| NULL_P
				{
					A_Const *n = makeNode(A_Const);
					n->val.type = T_Null;
					$$ = (Node *)n;
				}
5373
		;
5374

5375
ParamNo:  PARAM opt_indirection
5376 5377 5378
				{
					$$ = makeNode(ParamNo);
					$$->number = $1;
5379
					$$->indirection = $2;
5380 5381
				}
		;
5382

5383 5384
Iconst:  ICONST							{ $$ = $1; };
Sconst:  SCONST							{ $$ = $1; };
5385
UserId:  ColId							{ $$ = $1; };
5386

5387 5388 5389
/* Column identifier
 * Include date/time keywords as SQL92 extension.
 * Include TYPE as a SQL92 unreserved keyword. - thomas 1997-10-05
5390 5391 5392 5393
 * 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
5394
 */
5395
ColId:  IDENT							{ $$ = $1; }
5396
		| datetime						{ $$ = $1; }
5397
		| TokenId						{ $$ = $1; }
5398
		| INTERVAL						{ $$ = "interval"; }
5399
		| NATIONAL						{ $$ = "national"; }
5400
		| NONE							{ $$ = "none"; }
5401 5402
		| PATH_P						{ $$ = "path"; }
		| SERIAL						{ $$ = "serial"; }
5403 5404 5405 5406 5407 5408 5409 5410 5411
		| TIME							{ $$ = "time"; }
		| TIMESTAMP						{ $$ = "timestamp"; }
		;

/* Parser tokens to be used as identifiers.
 * Tokens involving data types should appear in ColId only,
 * since they will conflict with real TypeName productions.
 */
TokenId:  ABSOLUTE						{ $$ = "absolute"; }
5412
		| ACCESS						{ $$ = "access"; }
5413
		| ACTION						{ $$ = "action"; }
5414
		| ADD							{ $$ = "add"; }
5415 5416
		| AFTER							{ $$ = "after"; }
		| AGGREGATE						{ $$ = "aggregate"; }
5417
		| ALTER							{ $$ = "alter"; }
5418
		| AT							{ $$ = "at"; }
5419 5420
		| BACKWARD						{ $$ = "backward"; }
		| BEFORE						{ $$ = "before"; }
5421 5422
		| BEGIN_TRANS					{ $$ = "begin"; }
		| BY							{ $$ = "by"; }
5423
		| CACHE							{ $$ = "cache"; }
5424
		| CASCADE						{ $$ = "cascade"; }
5425
		| CHAIN							{ $$ = "chain"; }
5426
		| CHARACTERISTICS				{ $$ = "characteristics"; }
Vadim B. Mikheev's avatar
Vadim B. Mikheev committed
5427
		| CHECKPOINT					{ $$ = "checkpoint"; }
5428
		| CLOSE							{ $$ = "close"; }
5429
		| COMMENT						{ $$ = "comment"; }
5430
		| COMMIT						{ $$ = "commit"; }
5431
		| COMMITTED						{ $$ = "committed"; }
5432
		| CONSTRAINTS					{ $$ = "constraints"; }
5433
		| CREATE						{ $$ = "create"; }
5434 5435
		| CREATEDB						{ $$ = "createdb"; }
		| CREATEUSER					{ $$ = "createuser"; }
5436
		| CURSOR						{ $$ = "cursor"; }
5437
		| CYCLE							{ $$ = "cycle"; }
5438
		| DATABASE						{ $$ = "database"; }
5439
		| DECLARE						{ $$ = "declare"; }
5440
		| DEFERRED						{ $$ = "deferred"; }
5441
		| DELETE						{ $$ = "delete"; }
5442
		| DELIMITERS					{ $$ = "delimiters"; }
5443
		| DOUBLE						{ $$ = "double"; }
5444
		| DROP							{ $$ = "drop"; }
5445
		| EACH							{ $$ = "each"; }
5446
		| ENCODING						{ $$ = "encoding"; }
5447
		| ESCAPE						{ $$ = "escape"; }
5448
		| EXCLUSIVE						{ $$ = "exclusive"; }
5449 5450
		| EXECUTE						{ $$ = "execute"; }
		| FETCH							{ $$ = "fetch"; }
Hiroshi Inoue's avatar
Hiroshi Inoue committed
5451
		| FORCE							{ $$ = "force"; }
5452
		| FORWARD						{ $$ = "forward"; }
5453
		| FUNCTION						{ $$ = "function"; }
5454
		| GRANT							{ $$ = "grant"; }
5455
		| HANDLER						{ $$ = "handler"; }
5456
		| IMMEDIATE						{ $$ = "immediate"; }
5457
		| INCREMENT						{ $$ = "increment"; }
5458
		| INDEX							{ $$ = "index"; }
5459
		| INHERITS						{ $$ = "inherits"; }
5460
		| INSENSITIVE					{ $$ = "insensitive"; }
5461
		| INSERT						{ $$ = "insert"; }
5462
		| INSTEAD						{ $$ = "instead"; }
5463
		| ISOLATION						{ $$ = "isolation"; }
5464 5465
		| KEY							{ $$ = "key"; }
		| LANGUAGE						{ $$ = "language"; }
5466
		| LANCOMPILER					{ $$ = "lancompiler"; }
5467
		| LEVEL							{ $$ = "level"; }
5468 5469
		| LOCATION						{ $$ = "location"; }
		| MATCH							{ $$ = "match"; }
5470 5471
		| MAXVALUE						{ $$ = "maxvalue"; }
		| MINVALUE						{ $$ = "minvalue"; }
5472
		| MODE							{ $$ = "mode"; }
5473
		| NAMES							{ $$ = "names"; }
5474
		| NEXT							{ $$ = "next"; }
5475
		| NO							{ $$ = "no"; }
5476 5477 5478
		| NOCREATEDB					{ $$ = "nocreatedb"; }
		| NOCREATEUSER					{ $$ = "nocreateuser"; }
		| NOTHING						{ $$ = "nothing"; }
5479
		| NOTIFY						{ $$ = "notify"; }
5480
		| OF							{ $$ = "of"; }
5481
		| OIDS							{ $$ = "oids"; }
5482 5483
		| OPERATOR						{ $$ = "operator"; }
		| OPTION						{ $$ = "option"; }
5484
		| OWNER							{ $$ = "owner"; }
5485
		| PARTIAL						{ $$ = "partial"; }
5486
		| PASSWORD						{ $$ = "password"; }
5487
		| PENDANT						{ $$ = "pendant"; }
5488
		| PRIOR							{ $$ = "prior"; }
5489
		| PRIVILEGES					{ $$ = "privileges"; }
5490
		| PROCEDURAL					{ $$ = "procedural"; }
5491
		| PROCEDURE						{ $$ = "procedure"; }
5492
		| READ							{ $$ = "read"; }
5493
		| REINDEX						{ $$ = "reindex"; }
5494
		| RELATIVE						{ $$ = "relative"; }
5495
		| RENAME						{ $$ = "rename"; }
5496
		| RESTRICT						{ $$ = "restrict"; }
5497
		| RETURNS						{ $$ = "returns"; }
5498 5499
		| REVOKE						{ $$ = "revoke"; }
		| ROLLBACK						{ $$ = "rollback"; }
5500
		| ROW							{ $$ = "row"; }
5501
		| RULE							{ $$ = "rule"; }
5502
		| SCHEMA						{ $$ = "schema"; }
5503
		| SCROLL						{ $$ = "scroll"; }
5504
		| SESSION						{ $$ = "session"; }
5505
		| SEQUENCE						{ $$ = "sequence"; }
5506
		| SERIALIZABLE					{ $$ = "serializable"; }
5507
		| SET							{ $$ = "set"; }
5508
		| SHARE							{ $$ = "share"; }
5509
		| START							{ $$ = "start"; }
5510
		| STATEMENT						{ $$ = "statement"; }
5511 5512
		| STDIN							{ $$ = "stdin"; }
		| STDOUT						{ $$ = "stdout"; }
5513
		| SYSID							{ $$ = "sysid"; }
5514
		| TEMP							{ $$ = "temp"; }
5515
		| TEMPLATE						{ $$ = "template"; }
5516
		| TEMPORARY						{ $$ = "temporary"; }
5517 5518
		| TIMEZONE_HOUR					{ $$ = "timezone_hour"; }
		| TIMEZONE_MINUTE				{ $$ = "timezone_minute"; }
Jan Wieck's avatar
TOAST  
Jan Wieck committed
5519
		| TOAST							{ $$ = "toast"; }
5520
		| TRIGGER						{ $$ = "trigger"; }
5521
		| TRUNCATE						{ $$ = "truncate"; }
5522
		| TRUSTED						{ $$ = "trusted"; }
5523
		| TYPE_P						{ $$ = "type"; }
5524 5525 5526
		| UNLISTEN						{ $$ = "unlisten"; }
		| UNTIL							{ $$ = "until"; }
		| UPDATE						{ $$ = "update"; }
5527
		| VALID							{ $$ = "valid"; }
5528 5529
		| VALUES						{ $$ = "values"; }
		| VARYING						{ $$ = "varying"; }
5530
		| VERSION						{ $$ = "version"; }
5531 5532
		| VIEW							{ $$ = "view"; }
		| WITH							{ $$ = "with"; }
5533
		| WITHOUT						{ $$ = "without"; }
5534
		| WORK							{ $$ = "work"; }
5535
		| ZONE							{ $$ = "zone"; }
5536 5537 5538 5539 5540 5541 5542 5543
		;

/* 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
5544 5545 5546
 * 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
5547 5548
 */
ColLabel:  ColId						{ $$ = $1; }
5549
		| ABORT_TRANS					{ $$ = "abort"; }
5550
		| ALL							{ $$ = "all"; }
5551
		| ANALYSE						{ $$ = "analyse"; } /* British */
5552
		| ANALYZE						{ $$ = "analyze"; }
5553
		| AND							{ $$ = "and"; }
5554
		| ANY							{ $$ = "any"; }
5555
		| ASC							{ $$ = "asc"; }
5556
		| BETWEEN						{ $$ = "between"; }
5557
		| BINARY						{ $$ = "binary"; }
5558
		| BIT							{ $$ = "bit"; }
5559
		| BOTH							{ $$ = "both"; }
5560
		| CASE							{ $$ = "case"; }
5561 5562
		| CAST							{ $$ = "cast"; }
		| CHAR							{ $$ = "char"; }
5563
		| CHARACTER						{ $$ = "character"; }
5564
		| CHECK							{ $$ = "check"; }
5565
		| CLUSTER						{ $$ = "cluster"; }
5566
		| COALESCE						{ $$ = "coalesce"; }
5567 5568
		| COLLATE						{ $$ = "collate"; }
		| COLUMN						{ $$ = "column"; }
5569
		| CONSTRAINT					{ $$ = "constraint"; }
5570
		| COPY							{ $$ = "copy"; }
5571 5572 5573 5574
		| CROSS							{ $$ = "cross"; }
		| CURRENT_DATE					{ $$ = "current_date"; }
		| CURRENT_TIME					{ $$ = "current_time"; }
		| CURRENT_TIMESTAMP				{ $$ = "current_timestamp"; }
5575 5576
		| CURRENT_USER					{ $$ = "current_user"; }
		| DEC							{ $$ = "dec"; }
5577
		| DECIMAL						{ $$ = "decimal"; }
5578
		| DEFAULT						{ $$ = "default"; }
5579
		| DEFERRABLE					{ $$ = "deferrable"; }
5580 5581
		| DESC							{ $$ = "desc"; }
		| DISTINCT						{ $$ = "distinct"; }
5582
		| DO							{ $$ = "do"; }
5583 5584
		| ELSE							{ $$ = "else"; }
		| END_TRANS						{ $$ = "end"; }
5585
		| EXCEPT						{ $$ = "except"; }
5586
		| EXISTS						{ $$ = "exists"; }
5587 5588
		| EXPLAIN						{ $$ = "explain"; }
		| EXTEND						{ $$ = "extend"; }
5589
		| EXTRACT						{ $$ = "extract"; }
5590
		| FALSE_P						{ $$ = "false"; }
5591
		| FLOAT							{ $$ = "float"; }
5592
		| FOR							{ $$ = "for"; }
5593
		| FOREIGN						{ $$ = "foreign"; }
5594 5595
		| FROM							{ $$ = "from"; }
		| FULL							{ $$ = "full"; }
5596
		| GLOBAL						{ $$ = "global"; }
5597
		| GROUP							{ $$ = "group"; }
5598
		| HAVING						{ $$ = "having"; }
5599
		| ILIKE							{ $$ = "ilike"; }
5600
		| INITIALLY						{ $$ = "initially"; }
5601
		| IN							{ $$ = "in"; }
5602
		| INNER_P						{ $$ = "inner"; }
5603
		| INTERSECT						{ $$ = "intersect"; }
5604
		| INTO							{ $$ = "into"; }
5605
		| INOUT							{ $$ = "inout"; }
5606 5607
		| IS							{ $$ = "is"; }
		| ISNULL						{ $$ = "isnull"; }
5608 5609 5610
		| JOIN							{ $$ = "join"; }
		| LEADING						{ $$ = "leading"; }
		| LEFT							{ $$ = "left"; }
5611 5612
		| LIKE							{ $$ = "like"; }
		| LIMIT							{ $$ = "limit"; }
5613
		| LISTEN						{ $$ = "listen"; }
5614
		| LOAD							{ $$ = "load"; }
5615
		| LOCAL							{ $$ = "local"; }
5616 5617
		| LOCK_P						{ $$ = "lock"; }
		| MOVE							{ $$ = "move"; }
5618 5619
		| NATURAL						{ $$ = "natural"; }
		| NCHAR							{ $$ = "nchar"; }
5620
		| NEW							{ $$ = "new"; }
5621 5622 5623 5624
		| NOT							{ $$ = "not"; }
		| NOTNULL						{ $$ = "notnull"; }
		| NULLIF						{ $$ = "nullif"; }
		| NULL_P						{ $$ = "null"; }
5625
		| NUMERIC						{ $$ = "numeric"; }
5626
		| OFF							{ $$ = "off"; }
5627
		| OFFSET						{ $$ = "offset"; }
5628
		| OLD							{ $$ = "old"; }
5629
		| ON							{ $$ = "on"; }
5630
		| ONLY							{ $$ = "only"; }
5631
		| OR							{ $$ = "or"; }
5632
		| ORDER							{ $$ = "order"; }
5633
		| OUT							{ $$ = "out"; }
5634
		| OUTER_P						{ $$ = "outer"; }
5635
		| OVERLAPS						{ $$ = "overlaps"; }
5636 5637
		| POSITION						{ $$ = "position"; }
		| PRECISION						{ $$ = "precision"; }
5638 5639 5640
		| PRIMARY						{ $$ = "primary"; }
		| PUBLIC						{ $$ = "public"; }
		| REFERENCES					{ $$ = "references"; }
5641
		| RESET							{ $$ = "reset"; }
5642 5643
		| RIGHT							{ $$ = "right"; }
		| SELECT						{ $$ = "select"; }
5644
		| SESSION_USER					{ $$ = "session_user"; }
5645 5646
		| SETOF							{ $$ = "setof"; }
		| SHOW							{ $$ = "show"; }
5647
		| SOME							{ $$ = "some"; }
5648
		| SUBSTRING						{ $$ = "substring"; }
5649
		| TABLE							{ $$ = "table"; }
5650
		| THEN							{ $$ = "then"; }
5651
		| TO							{ $$ = "to"; }
5652
		| TRAILING						{ $$ = "trailing"; }
5653
		| TRANSACTION					{ $$ = "transaction"; }
5654
		| TRIM							{ $$ = "trim"; }
5655
		| TRUE_P						{ $$ = "true"; }
5656
		| UNION							{ $$ = "union"; }
5657
		| UNIQUE						{ $$ = "unique"; }
5658
		| USER							{ $$ = "user"; }
5659
		| USING							{ $$ = "using"; }
5660
		| VACUUM						{ $$ = "vacuum"; }
5661
		| VARCHAR						{ $$ = "varchar"; }
5662
		| VERBOSE						{ $$ = "verbose"; }
5663
		| WHEN							{ $$ = "when"; }
5664
		| WHERE							{ $$ = "where"; }
5665
		;
5666

5667
SpecialRuleRelation:  OLD
5668 5669
				{
					if (QueryIsRule)
5670
						$$ = "*OLD*";
5671
					else
5672
						elog(ERROR,"OLD used in non-rule query");
5673 5674 5675 5676 5677 5678
				}
		| NEW
				{
					if (QueryIsRule)
						$$ = "*NEW*";
					else
Bruce Momjian's avatar
Bruce Momjian committed
5679
						elog(ERROR,"NEW used in non-rule query");
5680 5681
				}
		;
5682 5683 5684

%%

5685 5686
static Node *
makeA_Expr(int oper, char *opname, Node *lexpr, Node *rexpr)
5687
{
5688 5689 5690 5691 5692 5693
	A_Expr *a = makeNode(A_Expr);
	a->oper = oper;
	a->opname = opname;
	a->lexpr = lexpr;
	a->rexpr = rexpr;
	return (Node *)a;
5694 5695
}

5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725
static Node *
makeTypeCast(Node *arg, TypeName *typename)
{
	/*
	 * If arg is an A_Const or ParamNo, just stick the typename into the
	 * field reserved for it --- unless there's something there already!
	 * (We don't want to collapse x::type1::type2 into just x::type2.)
	 * Otherwise, generate a TypeCast node.
	 */
	if (IsA(arg, A_Const) &&
		((A_Const *) arg)->typename == NULL)
	{
		((A_Const *) arg)->typename = typename;
		return arg;
	}
	else if (IsA(arg, ParamNo) &&
			 ((ParamNo *) arg)->typename == NULL)
	{
		((ParamNo *) arg)->typename = typename;
		return arg;
	}
	else
	{
		TypeCast *n = makeNode(TypeCast);
		n->arg = arg;
		n->typename = typename;
		return (Node *) n;
	}
}

Bruce Momjian's avatar
Bruce Momjian committed
5726 5727
/* makeRowExpr()
 * Generate separate operator nodes for a single row descriptor expression.
5728 5729
 * Perhaps this should go deeper in the parser someday...
 * - thomas 1997-12-22
Bruce Momjian's avatar
Bruce Momjian committed
5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771
 */
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;
}

5772
static void
5773 5774 5775 5776 5777 5778
mapTargetColumns(List *src, List *dst)
{
	ColumnDef *s;
	ResTarget *d;

	if (length(src) != length(dst))
Bruce Momjian's avatar
Bruce Momjian committed
5779
		elog(ERROR,"CREATE TABLE/AS SELECT has mismatched column count");
5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791

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

		d->name = s->colname;

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

5793

5794
/* findLeftmostSelect()
5795
 *		Find the leftmost component SelectStmt in a set-operation parsetree.
5796 5797
 */
static SelectStmt *
5798
findLeftmostSelect(SelectStmt *node)
5799
{
5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855
	while (node && node->op != SETOP_NONE)
		node = node->larg;
	Assert(node && IsA(node, SelectStmt) && node->larg == NULL);
	return node;
}

/* insertSelectOptions()
 *		Insert ORDER BY, etc into an already-constructed SelectStmt.
 *
 * This routine is just to avoid duplicating code in SelectStmt productions.
 */
static void
insertSelectOptions(SelectStmt *stmt,
					List *sortClause, List *forUpdate,
					Node *limitOffset, Node *limitCount)
{
	/*
	 * Tests here are to reject constructs like
	 *	(SELECT foo ORDER BY bar) ORDER BY baz
	 */
	if (sortClause)
	{
		if (stmt->sortClause)
			elog(ERROR, "Multiple ORDER BY clauses not allowed");
		stmt->sortClause = sortClause;
	}
	if (forUpdate)
	{
		if (stmt->forUpdate)
			elog(ERROR, "Multiple FOR UPDATE clauses not allowed");
		stmt->forUpdate = forUpdate;
	}
	if (limitOffset)
	{
		if (stmt->limitOffset)
			elog(ERROR, "Multiple OFFSET clauses not allowed");
		stmt->limitOffset = limitOffset;
	}
	if (limitCount)
	{
		if (stmt->limitCount)
			elog(ERROR, "Multiple LIMIT clauses not allowed");
		stmt->limitCount = limitCount;
	}
}

static Node *
makeSetOp(SetOperation op, bool all, Node *larg, Node *rarg)
{
	SelectStmt *n = makeNode(SelectStmt);

	n->op = op;
	n->all = all;
	n->larg = (SelectStmt *) larg;
	n->rarg = (SelectStmt *) rarg;
	return (Node *) n;
5856 5857 5858
}


5859
/* xlateSqlFunc()
5860 5861
 * Convert alternate function names to internal Postgres functions.
 *
5862 5863
 * Do not convert "float", since that is handled elsewhere
 *  for FLOAT(p) syntax.
5864
 *
5865 5866
 * Converting "datetime" to "timestamp" and "timespan" to "interval"
 * is a temporary expedient for pre-7.0 to 7.0 compatibility;
5867
 * these should go away for v7.1.
5868
 */
5869
static char *
5870 5871
xlateSqlFunc(char *name)
{
5872
	if (strcmp(name,"character_length") == 0)
5873
		return "char_length";
5874
	else if (strcmp(name,"datetime") == 0)
5875
		return "timestamp";
5876
	else if (strcmp(name,"timespan") == 0)
5877
		return "interval";
5878 5879 5880 5881 5882 5883
	else
		return name;
} /* xlateSqlFunc() */

/* xlateSqlType()
 * Convert alternate type names to internal Postgres types.
5884 5885 5886 5887
 *
 * NB: do NOT put "char" -> "bpchar" here, because that renders it impossible
 * to refer to our single-byte char type, even with quotes.  (Without quotes,
 * CHAR is a keyword, and the code above produces "bpchar" for it.)
5888 5889 5890
 *
 * Convert "datetime" and "timespan" to allow a transition to SQL92 type names.
 * Remove this translation for v7.1 - thomas 2000-03-25
Tom Lane's avatar
Tom Lane committed
5891 5892 5893 5894
 *
 * Convert "lztext" to "text" to allow forward compatibility for anyone using
 * the undocumented "lztext" type in 7.0.  This can go away in 7.2 or later
 * - tgl 2000-07-30
5895 5896
 */
static char *
5897 5898
xlateSqlType(char *name)
{
5899 5900
	if ((strcmp(name,"int") == 0)
		|| (strcmp(name,"integer") == 0))
5901
		return "int4";
5902
	else if (strcmp(name, "smallint") == 0)
5903
		return "int2";
5904 5905
	else if (strcmp(name, "bigint") == 0)
		return "int8";
5906 5907 5908
	else if (strcmp(name, "real") == 0)
		return "float4";
	else if (strcmp(name, "float") == 0)
5909
		return "float8";
5910
	else if (strcmp(name, "decimal") == 0)
5911
		return "numeric";
5912
	else if (strcmp(name, "datetime") == 0)
5913
		return "timestamp";
5914
	else if (strcmp(name, "timespan") == 0)
5915
		return "interval";
Tom Lane's avatar
Tom Lane committed
5916 5917
	else if (strcmp(name, "lztext") == 0)
		return "text";
5918
	else if (strcmp(name, "boolean") == 0)
5919
		return "bool";
5920 5921
	else
		return name;
5922
} /* xlateSqlType() */
5923

5924

5925 5926
void parser_init(Oid *typev, int nargs)
{
5927
	QueryIsRule = FALSE;
5928 5929 5930 5931
	/*
	 * Keep enough information around to fill out the type of param nodes
	 * used in postquel functions
	 */
5932
	param_type_info = typev;
5933
	pfunc_num_args = nargs;
5934 5935 5936 5937
}

Oid param_type(int t)
{
5938
	if ((t > pfunc_num_args) || (t <= 0))
5939 5940 5941
		return InvalidOid;
	return param_type_info[t - 1];
}
5942

5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954
/*
 * Test whether an a_expr is a plain NULL constant or not.
 */
static bool
exprIsNullConstant(Node *arg)
{
	if (arg && IsA(arg, A_Const))
	{
		A_Const *con = (A_Const *) arg;

		if (con->val.type == T_Null &&
			con->typename == NULL)
5955
			return TRUE;
5956
	}
5957
	return FALSE;
5958 5959
}

5960
/*
5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971
 * doNegate --- handle negation of a numeric constant.
 *
 * Formerly, we did this here because the optimizer couldn't cope with
 * indexquals that looked like "var = -4" --- it wants "var = const"
 * and a unary minus operator applied to a constant didn't qualify.
 * As of Postgres 7.0, that problem doesn't exist anymore because there
 * is a constant-subexpression simplifier in the optimizer.  However,
 * there's still a good reason for doing this here, which is that we can
 * postpone committing to a particular internal representation for simple
 * negative constants.  It's better to leave "-123.456" in string form
 * until we know what the desired type is.
5972
 */
5973 5974
static Node *
doNegate(Node *n)
5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986
{
	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)
		{
5987
			doNegateFloat(&con->val);
5988 5989 5990 5991 5992 5993
			return n;
		}
	}

	return makeA_Expr(OP, "-", NULL, n);
}
5994 5995 5996 5997 5998 5999 6000 6001 6002 6003

static void
doNegateFloat(Value *v)
{
	char   *oldval = v->val.str;

	Assert(IsA(v, Float));
	if (*oldval == '+')
		oldval++;
	if (*oldval == '-')
6004
		v->val.str = oldval+1;	/* just strip the '-' */
6005 6006 6007 6008 6009 6010 6011 6012 6013
	else
	{
		char   *newval = (char *) palloc(strlen(oldval) + 2);

		*newval = '-';
		strcpy(newval+1, oldval);
		v->val.str = newval;
	}
}