analyze.c 88.3 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * analyze.c
4
 *	  transform the parse tree into a query tree
5
 *
6
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
Bruce Momjian's avatar
Add:  
Bruce Momjian committed
7
 * Portions Copyright (c) 1994, Regents of the University of California
8
 *
9
 *	$PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.316 2005/03/10 23:21:23 tgl Exp $
10 11 12
 *
 *-------------------------------------------------------------------------
 */
13

Bruce Momjian's avatar
Bruce Momjian committed
14
#include "postgres.h"
Bruce Momjian's avatar
Bruce Momjian committed
15

16
#include "access/heapam.h"
Jan Wieck's avatar
Jan Wieck committed
17
#include "catalog/catname.h"
18
#include "catalog/heap.h"
19
#include "catalog/index.h"
20
#include "catalog/namespace.h"
Jan Wieck's avatar
Jan Wieck committed
21
#include "catalog/pg_index.h"
Bruce Momjian's avatar
Bruce Momjian committed
22
#include "catalog/pg_type.h"
23
#include "commands/defrem.h"
24
#include "commands/prepare.h"
Bruce Momjian's avatar
Bruce Momjian committed
25
#include "miscadmin.h"
26
#include "nodes/makefuncs.h"
27
#include "optimizer/clauses.h"
28
#include "optimizer/var.h"
29
#include "parser/analyze.h"
30
#include "parser/gramparse.h"
31
#include "parser/parsetree.h"
32
#include "parser/parse_agg.h"
Bruce Momjian's avatar
Bruce Momjian committed
33
#include "parser/parse_clause.h"
34
#include "parser/parse_coerce.h"
35 36
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
37 38
#include "parser/parse_relation.h"
#include "parser/parse_target.h"
39
#include "parser/parse_type.h"
40
#include "parser/parse_expr.h"
41
#include "rewrite/rewriteManip.h"
Bruce Momjian's avatar
Bruce Momjian committed
42
#include "utils/acl.h"
43
#include "utils/builtins.h"
44
#include "utils/fmgroids.h"
45
#include "utils/guc.h"
46
#include "utils/lsyscache.h"
47 48
#include "utils/relcache.h"
#include "utils/syscache.h"
49

50

51 52 53
/* State shared by transformCreateSchemaStmt and its subroutines */
typedef struct
{
54
	const char *stmtType;		/* "CREATE SCHEMA" or "ALTER SCHEMA" */
55 56
	char	   *schemaname;		/* name of schema */
	char	   *authid;			/* owner of schema */
57
	List	   *sequences;		/* CREATE SEQUENCE items */
58 59
	List	   *tables;			/* CREATE TABLE items */
	List	   *views;			/* CREATE VIEW items */
60 61
	List	   *indexes;		/* CREATE INDEX items */
	List	   *triggers;		/* CREATE TRIGGER items */
62
	List	   *grants;			/* GRANT items */
Bruce Momjian's avatar
Bruce Momjian committed
63 64
	List	   *fwconstraints;	/* Forward referencing FOREIGN KEY
								 * constraints */
65 66 67 68 69 70 71 72
	List	   *alters;			/* Generated ALTER items (from the above) */
	List	   *ixconstraints;	/* index-creating constraints */
	List	   *blist;			/* "before list" of things to do before
								 * creating the schema */
	List	   *alist;			/* "after list" of things to do after
								 * creating the schema */
} CreateSchemaStmtContext;

73 74 75 76
/* State shared by transformCreateStmt and its subroutines */
typedef struct
{
	const char *stmtType;		/* "CREATE TABLE" or "ALTER TABLE" */
77 78
	RangeVar   *relation;		/* relation to create */
	List	   *inhRelations;	/* relations to inherit from */
79
	bool		hasoids;		/* does relation have an OID column? */
80
	bool		isalter;		/* true if altering existing table */
81 82 83 84 85 86 87 88 89 90 91
	List	   *columns;		/* ColumnDef items */
	List	   *ckconstraints;	/* CHECK constraints */
	List	   *fkconstraints;	/* FOREIGN KEY constraints */
	List	   *ixconstraints;	/* index-creating constraints */
	List	   *blist;			/* "before list" of things to do before
								 * creating the table */
	List	   *alist;			/* "after list" of things to do after
								 * creating the table */
	IndexStmt  *pkey;			/* PRIMARY KEY index, if any */
} CreateStmtContext;

92 93 94 95
typedef struct
{
	Oid		   *paramTypes;
	int			numParams;
96
} check_parameter_resolution_context;
97

98

99
static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
100
static Query *transformStmt(ParseState *pstate, Node *stmt,
Bruce Momjian's avatar
Bruce Momjian committed
101
			  List **extras_before, List **extras_after);
102
static Query *transformViewStmt(ParseState *pstate, ViewStmt *stmt,
Bruce Momjian's avatar
Bruce Momjian committed
103
				  List **extras_before, List **extras_after);
104
static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
105
static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
Bruce Momjian's avatar
Bruce Momjian committed
106
					List **extras_before, List **extras_after);
107
static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
108
static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
Bruce Momjian's avatar
Bruce Momjian committed
109
				  List **extras_before, List **extras_after);
Bruce Momjian's avatar
Bruce Momjian committed
110
static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
111 112
static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
Bruce Momjian's avatar
Bruce Momjian committed
113
static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
114
static Query *transformDeclareCursorStmt(ParseState *pstate,
115
						   DeclareCursorStmt *stmt);
116 117
static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
118
static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
Bruce Momjian's avatar
Bruce Momjian committed
119
					List **extras_before, List **extras_after);
120 121
static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
						List **extras_before, List **extras_after);
122
static void transformColumnDefinition(ParseState *pstate,
Bruce Momjian's avatar
Bruce Momjian committed
123 124
						  CreateStmtContext *cxt,
						  ColumnDef *column);
125
static void transformTableConstraint(ParseState *pstate,
Bruce Momjian's avatar
Bruce Momjian committed
126 127
						 CreateStmtContext *cxt,
						 Constraint *constraint);
Bruce Momjian's avatar
Bruce Momjian committed
128
static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
129
					 InhRelation *inhrelation);
130
static void transformIndexConstraints(ParseState *pstate,
Bruce Momjian's avatar
Bruce Momjian committed
131
						  CreateStmtContext *cxt);
132
static void transformFKConstraints(ParseState *pstate,
Bruce Momjian's avatar
Bruce Momjian committed
133
					   CreateStmtContext *cxt,
134
					   bool skipValidation,
Bruce Momjian's avatar
Bruce Momjian committed
135
					   bool isAddConstraint);
136
static void applyColumnNames(List *dst, List *src);
137
static List *getSetColTypes(ParseState *pstate, Node *node);
Bruce Momjian's avatar
Bruce Momjian committed
138
static void transformForUpdate(Query *qry, List *forUpdate);
139
static void transformConstraintAttrs(List *constraintList);
140
static void transformColumnType(ParseState *pstate, ColumnDef *column);
141
static void release_pstate_resources(ParseState *pstate);
142
static FromExpr *makeFromExpr(List *fromlist, Node *quals);
143
static bool check_parameter_resolution_walker(Node *node,
144
							check_parameter_resolution_context *context);
145

146

147
/*
148 149 150 151 152
 * parse_analyze
 *		Analyze a raw parse tree and transform it to Query form.
 *
 * Optionally, information about $n parameter types can be supplied.
 * References to $n indexes not defined by paramTypes[] are disallowed.
153
 *
154 155 156 157
 * The result is a List of Query nodes (we need a list since some commands
 * produce multiple Queries).  Optimizable statements require considerable
 * transformation, while many utility-type statements are simply hung off
 * a dummy CMD_UTILITY Query node.
158
 */
159
List *
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
parse_analyze(Node *parseTree, Oid *paramTypes, int numParams)
{
	ParseState *pstate = make_parsestate(NULL);
	List	   *result;

	pstate->p_paramtypes = paramTypes;
	pstate->p_numparams = numParams;
	pstate->p_variableparams = false;

	result = do_parse_analyze(parseTree, pstate);

	pfree(pstate);

	return result;
}

/*
 * parse_analyze_varparams
 *
 * This variant is used when it's okay to deduce information about $n
 * symbol datatypes from context.  The passed-in paramTypes[] array can
 * be modified or enlarged (via repalloc).
 */
List *
parse_analyze_varparams(Node *parseTree, Oid **paramTypes, int *numParams)
{
	ParseState *pstate = make_parsestate(NULL);
	List	   *result;

	pstate->p_paramtypes = *paramTypes;
	pstate->p_numparams = *numParams;
	pstate->p_variableparams = true;

	result = do_parse_analyze(parseTree, pstate);

	*paramTypes = pstate->p_paramtypes;
	*numParams = pstate->p_numparams;

	pfree(pstate);

200 201 202 203 204 205 206 207 208 209
	/* make sure all is well with parameter types */
	if (*numParams > 0)
	{
		check_parameter_resolution_context context;

		context.paramTypes = *paramTypes;
		context.numParams = *numParams;
		check_parameter_resolution_walker((Node *) result, &context);
	}

210 211 212 213 214 215 216 217 218
	return result;
}

/*
 * parse_sub_analyze
 *		Entry point for recursively analyzing a sub-statement.
 */
List *
parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
219
{
220
	ParseState *pstate = make_parsestate(parentParseState);
221 222 223
	List	   *result;

	result = do_parse_analyze(parseTree, pstate);
Bruce Momjian's avatar
Bruce Momjian committed
224

225 226 227 228 229 230 231 232 233 234 235 236 237
	pfree(pstate);

	return result;
}

/*
 * do_parse_analyze
 *		Workhorse code shared by the above variants of parse_analyze.
 */
static List *
do_parse_analyze(Node *parseTree, ParseState *pstate)
{
	List	   *result = NIL;
Bruce Momjian's avatar
Bruce Momjian committed
238

239
	/* Lists to return extra commands from transformation */
240 241 242
	List	   *extras_before = NIL;
	List	   *extras_after = NIL;
	Query	   *query;
243
	ListCell   *l;
244

245
	query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
246 247

	/* don't need to access result relation any more */
248
	release_pstate_resources(pstate);
249

250
	foreach(l, extras_before)
251
		result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
Bruce Momjian's avatar
Bruce Momjian committed
252

253
	result = lappend(result, query);
Bruce Momjian's avatar
Bruce Momjian committed
254

255
	foreach(l, extras_after)
256
		result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
257

258
	/*
Bruce Momjian's avatar
Bruce Momjian committed
259
	 * Make sure that only the original query is marked original. We have
Bruce Momjian's avatar
Bruce Momjian committed
260 261 262 263
	 * to do this explicitly since recursive calls of do_parse_analyze
	 * will have marked some of the added-on queries as "original".  Also
	 * mark only the original query as allowed to set the command-result
	 * tag.
264
	 */
265
	foreach(l, result)
266
	{
267
		Query	   *q = lfirst(l);
268

269 270 271 272 273 274 275 276 277 278
		if (q == query)
		{
			q->querySource = QSRC_ORIGINAL;
			q->canSetTag = true;
		}
		else
		{
			q->querySource = QSRC_PARSER;
			q->canSetTag = false;
		}
279 280
	}

281
	return result;
282 283
}

284 285 286 287
static void
release_pstate_resources(ParseState *pstate)
{
	if (pstate->p_target_relation != NULL)
288
		heap_close(pstate->p_target_relation, NoLock);
289 290 291 292
	pstate->p_target_relation = NULL;
	pstate->p_target_rangetblentry = NULL;
}

293 294
/*
 * transformStmt -
295
 *	  transform a Parse tree into a Query tree.
296
 */
297
static Query *
298
transformStmt(ParseState *pstate, Node *parseTree,
Bruce Momjian's avatar
Bruce Momjian committed
299
			  List **extras_before, List **extras_after)
300
{
301
	Query	   *result = NULL;
302 303 304

	switch (nodeTag(parseTree))
	{
305 306
			/*
			 * Non-optimizable statements
307
			 */
308
		case T_CreateStmt:
309
			result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
Bruce Momjian's avatar
Bruce Momjian committed
310
										 extras_before, extras_after);
311 312
			break;

313 314 315
		case T_IndexStmt:
			result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
			break;
316

317
		case T_RuleStmt:
318
			result = transformRuleStmt(pstate, (RuleStmt *) parseTree,
Bruce Momjian's avatar
Bruce Momjian committed
319
									   extras_before, extras_after);
320
			break;
321

322
		case T_ViewStmt:
323 324
			result = transformViewStmt(pstate, (ViewStmt *) parseTree,
									   extras_before, extras_after);
325
			break;
326

327 328 329
		case T_ExplainStmt:
			{
				ExplainStmt *n = (ExplainStmt *) parseTree;
330

331 332
				result = makeNode(Query);
				result->commandType = CMD_UTILITY;
333
				n->query = transformStmt(pstate, (Node *) n->query,
Bruce Momjian's avatar
Bruce Momjian committed
334
										 extras_before, extras_after);
335 336 337
				result->utilityStmt = (Node *) parseTree;
			}
			break;
338

339
		case T_AlterTableStmt:
340 341
			result = transformAlterTableStmt(pstate,
											 (AlterTableStmt *) parseTree,
Bruce Momjian's avatar
Bruce Momjian committed
342
											 extras_before, extras_after);
343 344
			break;

345 346 347 348 349 350 351 352
		case T_PrepareStmt:
			result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
			break;

		case T_ExecuteStmt:
			result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
			break;

353 354
			/*
			 * Optimizable statements
355
			 */
Bruce Momjian's avatar
Bruce Momjian committed
356
		case T_InsertStmt:
357
			result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
Bruce Momjian's avatar
Bruce Momjian committed
358
										 extras_before, extras_after);
359
			break;
360

361 362 363
		case T_DeleteStmt:
			result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
			break;
364

Bruce Momjian's avatar
Bruce Momjian committed
365 366
		case T_UpdateStmt:
			result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
367
			break;
368

Bruce Momjian's avatar
Bruce Momjian committed
369
		case T_SelectStmt:
370 371 372 373 374
			if (((SelectStmt *) parseTree)->op == SETOP_NONE)
				result = transformSelectStmt(pstate,
											 (SelectStmt *) parseTree);
			else
				result = transformSetOperationStmt(pstate,
375
											   (SelectStmt *) parseTree);
376
			break;
377

378 379
		case T_DeclareCursorStmt:
			result = transformDeclareCursorStmt(pstate,
Bruce Momjian's avatar
Bruce Momjian committed
380
										(DeclareCursorStmt *) parseTree);
381 382
			break;

383
		default:
384

385
			/*
386
			 * other statements don't require any transformation-- just
Bruce Momjian's avatar
Bruce Momjian committed
387
			 * return the original parsetree, yea!
388 389 390 391 392
			 */
			result = makeNode(Query);
			result->commandType = CMD_UTILITY;
			result->utilityStmt = (Node *) parseTree;
			break;
393
	}
394 395 396 397 398

	/* Mark as original query until we learn differently */
	result->querySource = QSRC_ORIGINAL;
	result->canSetTag = true;

399 400 401 402 403 404 405 406 407 408 409 410
	/*
	 * Check that we did not produce too many resnos; at the very
	 * least we cannot allow more than 2^16, since that would exceed
	 * the range of a AttrNumber. It seems safest to use
	 * MaxTupleAttributeNumber.
	 */
	if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
		ereport(ERROR,
				(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
				 errmsg("target lists can have at most %d entries",
						MaxTupleAttributeNumber)));

411
	return result;
412 413
}

414 415 416 417
static Query *
transformViewStmt(ParseState *pstate, ViewStmt *stmt,
				  List **extras_before, List **extras_after)
{
Bruce Momjian's avatar
Bruce Momjian committed
418
	Query	   *result = makeNode(Query);
419 420 421 422 423 424 425 426

	result->commandType = CMD_UTILITY;
	result->utilityStmt = (Node *) stmt;

	stmt->query = transformStmt(pstate, (Node *) stmt->query,
								extras_before, extras_after);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
427 428
	 * If a list of column names was given, run through and insert these
	 * into the actual query tree. - thomas 2000-03-08
429 430 431 432 433 434
	 *
	 * Outer loop is over targetlist to make it easier to skip junk
	 * targetlist entries.
	 */
	if (stmt->aliases != NIL)
	{
Bruce Momjian's avatar
Bruce Momjian committed
435 436
		ListCell   *alist_item = list_head(stmt->aliases);
		ListCell   *targetList;
437 438 439 440 441 442 443 444 445 446 447 448

		foreach(targetList, stmt->query->targetList)
		{
			TargetEntry *te = (TargetEntry *) lfirst(targetList);
			Resdom	   *rd;

			Assert(IsA(te, TargetEntry));
			rd = te->resdom;
			Assert(IsA(rd, Resdom));
			/* junk columns don't get aliases */
			if (rd->resjunk)
				continue;
449 450 451
			rd->resname = pstrdup(strVal(lfirst(alist_item)));
			alist_item = lnext(alist_item);
			if (alist_item == NULL)
Bruce Momjian's avatar
Bruce Momjian committed
452
				break;			/* done assigning aliases */
453 454
		}

455
		if (alist_item != NULL)
456 457 458 459 460 461 462 463 464
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("CREATE VIEW specifies more column "
							"names than columns")));
	}

	return result;
}

465 466
/*
 * transformDeleteStmt -
467
 *	  transforms a Delete Statement
468
 */
469
static Query *
470
transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
471
{
472
	Query	   *qry = makeNode(Query);
473
	Node	   *qual;
474

475
	qry->commandType = CMD_DELETE;
476

477
	/* set up range table with just the result rel */
478
	qry->resultRelation = setTargetTable(pstate, stmt->relation,
Bruce Momjian's avatar
Bruce Momjian committed
479
							  interpretInhOption(stmt->relation->inhOpt),
480 481
										 true,
										 ACL_DELETE);
482

483
	qry->distinctClause = NIL;
484

485
	/* fix where clause */
486
	qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
487

488
	/* done building the range table and jointree */
489
	qry->rtable = pstate->p_rtable;
490
	qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
491

492
	qry->hasSubLinks = pstate->p_hasSubLinks;
Bruce Momjian's avatar
Bruce Momjian committed
493
	qry->hasAggs = pstate->p_hasAggs;
494
	if (pstate->p_hasAggs)
495
		parseCheckAggregates(pstate, qry);
496

497
	return qry;
498 499 500 501
}

/*
 * transformInsertStmt -
502
 *	  transform an Insert Statement
503
 */
504
static Query *
505 506
transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
					List **extras_before, List **extras_after)
507
{
508
	Query	   *qry = makeNode(Query);
509 510
	Query	   *selectQuery = NULL;
	bool		copy_up_hack = false;
511 512
	List	   *sub_rtable;
	List	   *sub_namespace;
513
	List	   *icolumns;
514
	List	   *attrnos;
515 516 517
	ListCell   *icols;
	ListCell   *attnos;
	ListCell   *tl;
518

519 520
	qry->commandType = CMD_INSERT;
	pstate->p_is_insert = true;
521

522
	/*
523 524
	 * If a non-nil rangetable/namespace was passed in, and we are doing
	 * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
525 526
	 * SELECT.	This can only happen if we are inside a CREATE RULE, and
	 * in that case we want the rule's OLD and NEW rtable entries to
527
	 * appear as part of the SELECT's rtable, not as outer references for
528 529
	 * it.	(Kluge!)  The SELECT's joinlist is not affected however. We
	 * must do this before adding the target table to the INSERT's rtable.
530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
	 */
	if (stmt->selectStmt)
	{
		sub_rtable = pstate->p_rtable;
		pstate->p_rtable = NIL;
		sub_namespace = pstate->p_namespace;
		pstate->p_namespace = NIL;
	}
	else
	{
		sub_rtable = NIL;		/* not used, but keep compiler quiet */
		sub_namespace = NIL;
	}

	/*
	 * Must get write lock on INSERT target table before scanning SELECT,
546
	 * else we will grab the wrong kind of initial lock if the target
547
	 * table is also mentioned in the SELECT part.	Note that the target
548
	 * table is not added to the joinlist or namespace.
549
	 */
550
	qry->resultRelation = setTargetTable(pstate, stmt->relation,
551
										 false, false, ACL_INSERT);
552

553
	/*
554
	 * Is it INSERT ... SELECT or INSERT ... VALUES?
Bruce Momjian's avatar
Bruce Momjian committed
555
	 */
556 557
	if (stmt->selectStmt)
	{
558 559 560 561 562 563 564 565
		/*
		 * We make the sub-pstate a child of the outer pstate so that it
		 * can see any Param definitions supplied from above.  Since the
		 * outer pstate's rtable and namespace are presently empty, there
		 * are no side-effects of exposing names the sub-SELECT shouldn't
		 * be able to see.
		 */
		ParseState *sub_pstate = make_parsestate(pstate);
566 567
		RangeTblEntry *rte;
		RangeTblRef *rtr;
Bruce Momjian's avatar
Bruce Momjian committed
568

569 570 571
		/*
		 * Process the source SELECT.
		 *
572 573 574 575
		 * It is important that this be handled just like a standalone
		 * SELECT; otherwise the behavior of SELECT within INSERT might be
		 * different from a stand-alone SELECT. (Indeed, Postgres up
		 * through 6.5 had bugs of just that nature...)
576
		 */
577 578 579
		sub_pstate->p_rtable = sub_rtable;
		sub_pstate->p_namespace = sub_namespace;

580 581
		/*
		 * Note: we are not expecting that extras_before and extras_after
Bruce Momjian's avatar
Bruce Momjian committed
582 583
		 * are going to be used by the transformation of the SELECT
		 * statement.
Bruce Momjian's avatar
Bruce Momjian committed
584
		 */
585
		selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
Bruce Momjian's avatar
Bruce Momjian committed
586
									extras_before, extras_after);
587

588 589
		release_pstate_resources(sub_pstate);
		pfree(sub_pstate);
590 591 592

		Assert(IsA(selectQuery, Query));
		Assert(selectQuery->commandType == CMD_SELECT);
593
		if (selectQuery->into)
594 595 596
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("INSERT ... SELECT may not specify INTO")));
597

598
		/*
599 600
		 * Make the source be a subquery in the INSERT's rangetable, and
		 * add it to the INSERT's joinlist.
601 602 603
		 */
		rte = addRangeTableEntryForSubquery(pstate,
											selectQuery,
604
											makeAlias("*SELECT*", NIL),
605 606 607
											true);
		rtr = makeNode(RangeTblRef);
		/* assume new rte is at end */
608
		rtr->rtindex = list_length(pstate->p_rtable);
609 610
		Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
		pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
611

612
		/*----------
613 614 615 616
		 * Generate a targetlist for the INSERT that selects all the
		 * non-resjunk columns from the subquery.  (We need this to be
		 * separate from the subquery's tlist because we may add columns,
		 * insert datatype coercions, etc.)
617
		 *
618 619
		 * HACK: unknown-type constants and params in the INSERT's targetlist
		 * are copied up as-is rather than being referenced as subquery
Bruce Momjian's avatar
Bruce Momjian committed
620 621
		 * outputs.  This is to ensure that when we try to coerce them to
		 * the target column's datatype, the right things happen (see
622 623 624
		 * special cases in coerce_type).  Otherwise, this fails:
		 *		INSERT INTO foo SELECT 'bar', ... FROM baz
		 *----------
625 626 627 628 629 630
		 */
		qry->targetList = NIL;
		foreach(tl, selectQuery->targetList)
		{
			TargetEntry *tle = (TargetEntry *) lfirst(tl);
			Resdom	   *resnode = tle->resdom;
631
			Expr	   *expr;
632 633 634

			if (resnode->resjunk)
				continue;
635
			if (tle->expr &&
636
				(IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
637
				exprType((Node *) tle->expr) == UNKNOWNOID)
638
			{
639
				expr = tle->expr;
640 641
				copy_up_hack = true;
			}
642
			else
643
				expr = (Expr *) makeVar(rtr->rtindex,
644 645 646 647 648
										resnode->resno,
										resnode->restype,
										resnode->restypmod,
										0);
			resnode = copyObject(resnode);
649
			resnode->resno = (AttrNumber) pstate->p_next_resno++;
650 651 652 653 654 655 656
			qry->targetList = lappend(qry->targetList,
									  makeTargetEntry(resnode, expr));
		}
	}
	else
	{
		/*
657 658
		 * For INSERT ... VALUES, transform the given list of values to
		 * form a targetlist for the INSERT.
659 660 661
		 */
		qry->targetList = transformTargetList(pstate, stmt->targetList);
	}
662

663
	/*
664 665 666 667 668
	 * Now we are done with SELECT-like processing, and can get on with
	 * transforming the target list to match the INSERT target columns.
	 */

	/* Prepare to assign non-conflicting resnos to resjunk attributes */
669 670
	if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
		pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
671 672

	/* Validate stmt->cols list, or build default list if no list given */
673
	icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
674

675 676 677
	/*
	 * Prepare columns for assignment to target table.
	 */
678 679
	icols = list_head(icolumns);
	attnos = list_head(attrnos);
680
	foreach(tl, qry->targetList)
681 682
	{
		TargetEntry *tle = (TargetEntry *) lfirst(tl);
Bruce Momjian's avatar
Bruce Momjian committed
683
		ResTarget  *col;
684

685
		if (icols == NULL || attnos == NULL)
686 687
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
688
			 errmsg("INSERT has more expressions than target columns")));
689

690
		col = (ResTarget *) lfirst(icols);
691
		Assert(IsA(col, ResTarget));
Bruce Momjian's avatar
Bruce Momjian committed
692

693
		Assert(!tle->resdom->resjunk);
694
		updateTargetListEntry(pstate, tle, col->name, lfirst_int(attnos),
695
							  col->indirection);
Bruce Momjian's avatar
Bruce Momjian committed
696

697
		icols = lnext(icols);
698
		attnos = lnext(attnos);
699 700
	}

701
	/*
Bruce Momjian's avatar
Bruce Momjian committed
702 703
	 * Ensure that the targetlist has the same number of entries that were
	 * present in the columns list.  Don't do the check unless an explicit
704
	 * columns list was given, though.
705
	 */
706
	if (stmt->cols != NIL && (icols != NULL || attnos != NULL))
707 708
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
709
			 errmsg("INSERT has more target columns than expressions")));
710

711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
	/*
	 * If we copied up any unknown Params (see HACK above) then their
	 * resolved types need to be propagated into the Resdom nodes of
	 * the sub-INSERT's tlist.  One hack begets another :-(
	 */
	if (copy_up_hack)
	{
		foreach(tl, selectQuery->targetList)
		{
			TargetEntry *tle = (TargetEntry *) lfirst(tl);
			Resdom	   *resnode = tle->resdom;

			if (resnode->resjunk)
				continue;
			if (resnode->restype == UNKNOWNOID)
			{
				resnode->restype = exprType((Node *) tle->expr);
				resnode->restypmod = exprTypmod((Node *) tle->expr);
			}
		}
	}

733 734 735
	/* done building the range table and jointree */
	qry->rtable = pstate->p_rtable;
	qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
736

737
	qry->hasSubLinks = pstate->p_hasSubLinks;
738 739
	qry->hasAggs = pstate->p_hasAggs;
	if (pstate->p_hasAggs)
740
		parseCheckAggregates(pstate, qry);
741

742
	return qry;
743 744
}

745 746 747 748 749 750 751 752 753 754
/*
 * transformCreateStmt -
 *	  transforms the "create table" statement
 *	  SQL92 allows constraints to be scattered all over, so thumb through
 *	   the columns and collect all constraints into one place.
 *	  If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
 *	   then expand those into multiple IndexStmt blocks.
 *	  - thomas 1997-12-02
 */
static Query *
755 756
transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
					List **extras_before, List **extras_after)
757
{
758
	CreateStmtContext cxt;
759
	Query	   *q;
760
	ListCell   *elements;
761

762
	cxt.stmtType = "CREATE TABLE";
763 764
	cxt.relation = stmt->relation;
	cxt.inhRelations = stmt->inhRelations;
765
	cxt.isalter = false;
766 767 768 769 770 771 772
	cxt.columns = NIL;
	cxt.ckconstraints = NIL;
	cxt.fkconstraints = NIL;
	cxt.ixconstraints = NIL;
	cxt.blist = NIL;
	cxt.alist = NIL;
	cxt.pkey = NULL;
773
	cxt.hasoids = interpretOidsOption(stmt->hasoids);
774

775
	/*
776 777
	 * Run through each primary element in the table creation clause.
	 * Separate column defs from constraints, and do preliminary analysis.
778
	 */
779
	foreach(elements, stmt->tableElts)
780
	{
781 782
		Node	   *element = lfirst(elements);

783 784 785
		switch (nodeTag(element))
		{
			case T_ColumnDef:
786 787 788
				transformColumnDefinition(pstate, &cxt,
										  (ColumnDef *) element);
				break;
789

790 791 792 793
			case T_Constraint:
				transformTableConstraint(pstate, &cxt,
										 (Constraint *) element);
				break;
794

795 796 797 798
			case T_FkConstraint:
				/* No pre-transformation needed */
				cxt.fkconstraints = lappend(cxt.fkconstraints, element);
				break;
799

Bruce Momjian's avatar
Bruce Momjian committed
800 801 802 803 804
			case T_InhRelation:
				transformInhRelation(pstate, &cxt,
									 (InhRelation *) element);
				break;

805
			default:
806 807 808
				elog(ERROR, "unrecognized node type: %d",
					 (int) nodeTag(element));
				break;
809 810
		}
	}
811

812
	Assert(stmt->constraints == NIL);
813

814 815 816 817
	/*
	 * Postprocess constraints that give rise to index definitions.
	 */
	transformIndexConstraints(pstate, &cxt);
818

819 820 821
	/*
	 * Postprocess foreign-key constraints.
	 */
822
	transformFKConstraints(pstate, &cxt, true, false);
823 824 825 826 827 828 829 830 831

	/*
	 * Output results.
	 */
	q = makeNode(Query);
	q->commandType = CMD_UTILITY;
	q->utilityStmt = (Node *) stmt;
	stmt->tableElts = cxt.columns;
	stmt->constraints = cxt.ckconstraints;
832 833
	*extras_before = list_concat(*extras_before, cxt.blist);
	*extras_after = list_concat(cxt.alist, *extras_after);
834

835 836
	return q;
}
837

838 839 840 841 842 843 844
static void
transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
						  ColumnDef *column)
{
	bool		is_serial;
	bool		saw_nullable;
	Constraint *constraint;
845
	ListCell   *clist;
846

847
	cxt->columns = lappend(cxt->columns, column);
848

849 850
	/* Check for SERIAL pseudo-types */
	is_serial = false;
851
	if (list_length(column->typename->names) == 1)
852
	{
853
		char	   *typname = strVal(linitial(column->typename->names));
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868

		if (strcmp(typname, "serial") == 0 ||
			strcmp(typname, "serial4") == 0)
		{
			is_serial = true;
			column->typename->names = NIL;
			column->typename->typeid = INT4OID;
		}
		else if (strcmp(typname, "bigserial") == 0 ||
				 strcmp(typname, "serial8") == 0)
		{
			is_serial = true;
			column->typename->names = NIL;
			column->typename->typeid = INT8OID;
		}
869
	}
870

871 872
	/* Do necessary work on the column type declaration */
	transformColumnType(pstate, column);
Jan Wieck's avatar
Jan Wieck committed
873

874 875 876
	/* Special actions for SERIAL pseudo-types */
	if (is_serial)
	{
877
		Oid			snamespaceid;
878
		char	   *snamespace;
879
		char	   *sname;
880 881 882
		char	   *qstring;
		A_Const    *snamenode;
		FuncCall   *funccallnode;
883 884 885
		CreateSeqStmt *seqstmt;

		/*
886 887
		 * Determine namespace and name to use for the sequence.
		 *
Bruce Momjian's avatar
Bruce Momjian committed
888 889 890
		 * Although we use ChooseRelationName, it's not guaranteed that the
		 * selected sequence name won't conflict; given sufficiently long
		 * field names, two different serial columns in the same table
891 892
		 * could be assigned the same sequence name, and we'd not notice
		 * since we aren't creating the sequence quite yet.  In practice
Bruce Momjian's avatar
Bruce Momjian committed
893 894
		 * this seems quite unlikely to be a problem, especially since few
		 * people would need two serial columns in one table.
895
		 */
896 897 898 899 900 901
		snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
		snamespace = get_namespace_name(snamespaceid);
		sname = ChooseRelationName(cxt->relation->relname,
								   column->colname,
								   "seq",
								   snamespaceid);
902

903
		ereport(NOTICE,
904
				(errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
905 906
						cxt->stmtType, sname,
						cxt->relation->relname, column->colname)));
907 908 909 910 911 912 913 914 915 916 917

		/*
		 * Build a CREATE SEQUENCE command to create the sequence object,
		 * and add it to the list of things to be done before this
		 * CREATE/ALTER TABLE.
		 */
		seqstmt = makeNode(CreateSeqStmt);
		seqstmt->sequence = makeRangeVar(snamespace, sname);
		seqstmt->options = NIL;

		cxt->blist = lappend(cxt->blist, seqstmt);
918

919 920 921 922 923 924
		/*
		 * Mark the ColumnDef so that during execution, an appropriate
		 * dependency will be added from the sequence to the column.
		 */
		column->support = makeRangeVar(snamespace, sname);

925
		/*
926 927 928 929
		 * Create appropriate constraints for SERIAL.  We do this in full,
		 * rather than shortcutting, so that we will detect any
		 * conflicting constraints the user wrote (like a different
		 * DEFAULT).
930
		 *
931 932
		 * Create an expression tree representing the function call
		 * nextval('"sequencename"')
933
		 */
934
		qstring = quote_qualified_identifier(snamespace, sname);
935 936 937 938
		snamenode = makeNode(A_Const);
		snamenode->val.type = T_String;
		snamenode->val.val.str = qstring;
		funccallnode = makeNode(FuncCall);
939
		funccallnode->funcname = SystemFuncName("nextval");
940
		funccallnode->args = list_make1(snamenode);
941 942 943 944 945 946 947 948 949 950 951 952 953 954
		funccallnode->agg_star = false;
		funccallnode->agg_distinct = false;

		constraint = makeNode(Constraint);
		constraint->contype = CONSTR_DEFAULT;
		constraint->raw_expr = (Node *) funccallnode;
		constraint->cooked_expr = NULL;
		constraint->keys = NIL;
		column->constraints = lappend(column->constraints, constraint);

		constraint = makeNode(Constraint);
		constraint->contype = CONSTR_NOTNULL;
		column->constraints = lappend(column->constraints, constraint);
	}
955

956 957
	/* Process column constraints, if any... */
	transformConstraintAttrs(column->constraints);
958

959
	saw_nullable = false;
960

961 962 963
	foreach(clist, column->constraints)
	{
		constraint = lfirst(clist);
964

965
		/*
966
		 * If this column constraint is a FOREIGN KEY constraint, then we
967
		 * fill in the current attribute's name and throw it into the list
968
		 * of FK constraints to be processed later.
969 970 971 972
		 */
		if (IsA(constraint, FkConstraint))
		{
			FkConstraint *fkconstraint = (FkConstraint *) constraint;
973

974
			fkconstraint->fk_attrs = list_make1(makeString(column->colname));
975 976 977
			cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
			continue;
		}
978

979
		Assert(IsA(constraint, Constraint));
980

981 982 983 984
		switch (constraint->contype)
		{
			case CONSTR_NULL:
				if (saw_nullable && column->is_not_null)
985 986
					ereport(ERROR,
							(errcode(ERRCODE_SYNTAX_ERROR),
987
							 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
Bruce Momjian's avatar
Bruce Momjian committed
988
							  column->colname, cxt->relation->relname)));
989 990 991
				column->is_not_null = FALSE;
				saw_nullable = true;
				break;
992

993 994
			case CONSTR_NOTNULL:
				if (saw_nullable && !column->is_not_null)
995 996
					ereport(ERROR,
							(errcode(ERRCODE_SYNTAX_ERROR),
997
							 errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
Bruce Momjian's avatar
Bruce Momjian committed
998
							  column->colname, cxt->relation->relname)));
999 1000 1001
				column->is_not_null = TRUE;
				saw_nullable = true;
				break;
1002

1003 1004
			case CONSTR_DEFAULT:
				if (column->raw_default != NULL)
1005 1006
					ereport(ERROR,
							(errcode(ERRCODE_SYNTAX_ERROR),
1007
							 errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
Bruce Momjian's avatar
Bruce Momjian committed
1008
							  column->colname, cxt->relation->relname)));
1009 1010 1011 1012 1013 1014 1015
				column->raw_default = constraint->raw_expr;
				Assert(constraint->cooked_expr == NULL);
				break;

			case CONSTR_PRIMARY:
			case CONSTR_UNIQUE:
				if (constraint->keys == NIL)
1016
					constraint->keys = list_make1(makeString(column->colname));
1017 1018
				cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
				break;
1019

1020 1021 1022 1023 1024 1025 1026 1027 1028
			case CONSTR_CHECK:
				cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
				break;

			case CONSTR_ATTR_DEFERRABLE:
			case CONSTR_ATTR_NOT_DEFERRABLE:
			case CONSTR_ATTR_DEFERRED:
			case CONSTR_ATTR_IMMEDIATE:
				/* transformConstraintAttrs took care of these */
Jan Wieck's avatar
Jan Wieck committed
1029 1030
				break;

1031
			default:
1032 1033
				elog(ERROR, "unrecognized constraint type: %d",
					 constraint->contype);
1034
				break;
1035 1036
		}
	}
1037
}
1038

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
static void
transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
						 Constraint *constraint)
{
	switch (constraint->contype)
	{
		case CONSTR_PRIMARY:
		case CONSTR_UNIQUE:
			cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
			break;

		case CONSTR_CHECK:
			cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
			break;

		case CONSTR_NULL:
		case CONSTR_NOTNULL:
		case CONSTR_DEFAULT:
		case CONSTR_ATTR_DEFERRABLE:
		case CONSTR_ATTR_NOT_DEFERRABLE:
		case CONSTR_ATTR_DEFERRED:
		case CONSTR_ATTR_IMMEDIATE:
1061
			elog(ERROR, "invalid context for constraint type %d",
1062
				 constraint->contype);
1063 1064 1065
			break;

		default:
1066 1067
			elog(ERROR, "unrecognized constraint type: %d",
				 constraint->contype);
1068 1069 1070 1071
			break;
	}
}

Bruce Momjian's avatar
Bruce Momjian committed
1072 1073 1074 1075 1076 1077 1078 1079
/*
 * transformInhRelation
 *
 * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
 * column definitions which recreate the user defined column portions of <subtable>.
 */
static void
transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1080
					 InhRelation *inhRelation)
Bruce Momjian's avatar
Bruce Momjian committed
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
{
	AttrNumber	parent_attno;

	Relation	relation;
	TupleDesc	tupleDesc;
	TupleConstr *constr;
	AclResult	aclresult;

	relation = heap_openrv(inhRelation->relation, AccessShareLock);

	if (relation->rd_rel->relkind != RELKIND_RELATION)
1092 1093 1094 1095
		ereport(ERROR,
				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
				 errmsg("inherited relation \"%s\" is not a table",
						inhRelation->relation->relname)));
Bruce Momjian's avatar
Bruce Momjian committed
1096 1097

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1098
	 * Check for SELECT privilages
Bruce Momjian's avatar
Bruce Momjian committed
1099 1100 1101 1102
	 */
	aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
								  ACL_SELECT);
	if (aclresult != ACLCHECK_OK)
1103 1104
		aclcheck_error(aclresult, ACL_KIND_CLASS,
					   RelationGetRelationName(relation));
Bruce Momjian's avatar
Bruce Momjian committed
1105 1106 1107 1108 1109

	tupleDesc = RelationGetDescr(relation);
	constr = tupleDesc->constr;

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1110 1111
	 * Insert the inherited attributes into the cxt for the new table
	 * definition.
Bruce Momjian's avatar
Bruce Momjian committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
	 */
	for (parent_attno = 1; parent_attno <= tupleDesc->natts;
		 parent_attno++)
	{
		Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
		char	   *attributeName = NameStr(attribute->attname);
		ColumnDef  *def;
		TypeName   *typename;

		/*
		 * Ignore dropped columns in the parent.
		 */
		if (attribute->attisdropped)
			continue;

		/*
		 * Create a new inherited column.
		 *
Bruce Momjian's avatar
Bruce Momjian committed
1130 1131
		 * For constraints, ONLY the NOT NULL constraint is inherited by the
		 * new column definition per SQL99.
Bruce Momjian's avatar
Bruce Momjian committed
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
		 */
		def = makeNode(ColumnDef);
		def->colname = pstrdup(attributeName);
		typename = makeNode(TypeName);
		typename->typeid = attribute->atttypid;
		typename->typmod = attribute->atttypmod;
		def->typename = typename;
		def->inhcount = 0;
		def->is_local = false;
		def->is_not_null = attribute->attnotnull;
		def->raw_default = NULL;
		def->cooked_default = NULL;
		def->constraints = NIL;
		def->support = NULL;

		/*
		 * Add to column list
		 */
		cxt->columns = lappend(cxt->columns, def);

		/*
		 * Copy default if any, and the default has been requested
		 */
		if (attribute->atthasdef && inhRelation->including_defaults)
		{
			char	   *this_default = NULL;
			AttrDefault *attrdef;
			int			i;

			/* Find default in constraint structure */
			Assert(constr != NULL);
			attrdef = constr->defval;
			for (i = 0; i < constr->num_defval; i++)
			{
				if (attrdef[i].adnum == parent_attno)
				{
					this_default = attrdef[i].adbin;
					break;
				}
			}
			Assert(this_default != NULL);

			/*
Bruce Momjian's avatar
Bruce Momjian committed
1175 1176
			 * If default expr could contain any vars, we'd need to fix
			 * 'em, but it can't; so default is ready to apply to child.
Bruce Momjian's avatar
Bruce Momjian committed
1177 1178 1179 1180 1181 1182 1183
			 */

			def->cooked_default = pstrdup(this_default);
		}
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
1184 1185 1186
	 * Close the parent rel, but keep our AccessShareLock on it until xact
	 * commit.	That will prevent someone else from deleting or ALTERing
	 * the parent before the child is committed.
Bruce Momjian's avatar
Bruce Momjian committed
1187 1188 1189 1190
	 */
	heap_close(relation, NoLock);
}

1191 1192 1193 1194 1195
static void
transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
{
	IndexStmt  *index;
	List	   *indexlist = NIL;
1196 1197
	ListCell   *listptr;
	ListCell   *l;
1198 1199

	/*
1200 1201 1202
	 * Run through the constraints that need to generate an index. For
	 * PRIMARY KEY, mark each column as NOT NULL and create an index. For
	 * UNIQUE, create an index as for PRIMARY KEY, but do not insist on
1203 1204 1205
	 * NOT NULL.
	 */
	foreach(listptr, cxt->ixconstraints)
1206
	{
1207
		Constraint *constraint = lfirst(listptr);
1208 1209
		ListCell   *keys;
		IndexElem  *iparam;
1210

1211
		Assert(IsA(constraint, Constraint));
1212
		Assert((constraint->contype == CONSTR_PRIMARY)
Bruce Momjian's avatar
Bruce Momjian committed
1213
			   || (constraint->contype == CONSTR_UNIQUE));
1214

1215 1216
		index = makeNode(IndexStmt);

1217 1218
		index->unique = true;
		index->primary = (constraint->contype == CONSTR_PRIMARY);
1219
		if (index->primary)
1220
		{
1221
			if (cxt->pkey != NULL)
1222 1223 1224 1225
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_TABLE_DEFINITION),
						 errmsg("multiple primary keys for table \"%s\" are not allowed",
								cxt->relation->relname)));
1226
			cxt->pkey = index;
Bruce Momjian's avatar
Bruce Momjian committed
1227

1228 1229 1230 1231
			/*
			 * In ALTER TABLE case, a primary index might already exist,
			 * but DefineIndex will check for it.
			 */
1232
		}
1233
		index->isconstraint = true;
1234

1235
		if (constraint->name != NULL)
1236
			index->idxname = pstrdup(constraint->name);
1237
		else
1238
			index->idxname = NULL;		/* DefineIndex will choose name */
1239

1240
		index->relation = cxt->relation;
1241
		index->accessMethod = DEFAULT_INDEX_TYPE;
1242
		index->tableSpace = constraint->indexspace;
1243 1244
		index->indexParams = NIL;
		index->whereClause = NULL;
1245

1246
		/*
1247
		 * Make sure referenced keys exist.  If we are making a PRIMARY
1248
		 * KEY index, also make sure they are NOT NULL, if possible.
Bruce Momjian's avatar
Bruce Momjian committed
1249 1250
		 * (Although we could leave it to DefineIndex to mark the columns
		 * NOT NULL, it's more efficient to get it right the first time.)
1251
		 */
1252
		foreach(keys, constraint->keys)
1253
		{
1254
			char	   *key = strVal(lfirst(keys));
1255
			bool		found = false;
1256 1257
			ColumnDef  *column = NULL;
			ListCell   *columns;
1258

1259
			foreach(columns, cxt->columns)
1260
			{
1261
				column = (ColumnDef *) lfirst(columns);
1262
				Assert(IsA(column, ColumnDef));
1263
				if (strcmp(column->colname, key) == 0)
1264 1265
				{
					found = true;
1266
					break;
1267
				}
1268
			}
1269 1270 1271 1272 1273 1274
			if (found)
			{
				/* found column in the new table; force it to be NOT NULL */
				if (constraint->contype == CONSTR_PRIMARY)
					column->is_not_null = TRUE;
			}
1275
			else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1276 1277
			{
				/*
1278 1279 1280
				 * column will be a system column in the new table, so
				 * accept it.  System columns can't ever be null, so no
				 * need to worry about PRIMARY/NOT NULL constraint.
1281 1282 1283
				 */
				found = true;
			}
1284
			else if (cxt->inhRelations)
1285 1286
			{
				/* try inherited tables */
1287
				ListCell   *inher;
1288

1289
				foreach(inher, cxt->inhRelations)
1290
				{
1291
					RangeVar   *inh = (RangeVar *) lfirst(inher);
1292 1293
					Relation	rel;
					int			count;
1294

1295
					Assert(IsA(inh, RangeVar));
1296
					rel = heap_openrv(inh, AccessShareLock);
1297
					if (rel->rd_rel->relkind != RELKIND_RELATION)
1298 1299
						ereport(ERROR,
								(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1300
						errmsg("inherited relation \"%s\" is not a table",
Bruce Momjian's avatar
Bruce Momjian committed
1301
							   inh->relname)));
1302 1303 1304
					for (count = 0; count < rel->rd_att->natts; count++)
					{
						Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1305
						char	   *inhname = NameStr(inhattr->attname);
1306

1307 1308
						if (inhattr->attisdropped)
							continue;
1309
						if (strcmp(key, inhname) == 0)
1310 1311
						{
							found = true;
Bruce Momjian's avatar
Bruce Momjian committed
1312

1313
							/*
1314
							 * We currently have no easy way to force an
Bruce Momjian's avatar
Bruce Momjian committed
1315 1316 1317 1318
							 * inherited column to be NOT NULL at
							 * creation, if its parent wasn't so already.
							 * We leave it to DefineIndex to fix things up
							 * in this case.
1319
							 */
1320 1321 1322 1323 1324 1325 1326 1327
							break;
						}
					}
					heap_close(rel, NoLock);
					if (found)
						break;
				}
			}
Bruce Momjian's avatar
Bruce Momjian committed
1328

1329 1330 1331 1332 1333 1334 1335
			/*
			 * In the ALTER TABLE case, don't complain about index keys
			 * not created in the command; they may well exist already.
			 * DefineIndex will complain about them if not, and will also
			 * take care of marking them NOT NULL.
			 */
			if (!found && !cxt->isalter)
1336 1337
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_COLUMN),
Bruce Momjian's avatar
Bruce Momjian committed
1338 1339
					  errmsg("column \"%s\" named in key does not exist",
							 key)));
1340

1341 1342 1343 1344
			/* Check for PRIMARY KEY(foo, foo) */
			foreach(columns, index->indexParams)
			{
				iparam = (IndexElem *) lfirst(columns);
1345
				if (iparam->name && strcmp(key, iparam->name) == 0)
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
				{
					if (index->primary)
						ereport(ERROR,
								(errcode(ERRCODE_DUPLICATE_COLUMN),
								 errmsg("column \"%s\" appears twice in primary key constraint",
										key)));
					else
						ereport(ERROR,
								(errcode(ERRCODE_DUPLICATE_COLUMN),
								 errmsg("column \"%s\" appears twice in unique constraint",
										key)));
				}
1358 1359 1360
			}

			/* OK, add it to the index definition */
1361
			iparam = makeNode(IndexElem);
1362
			iparam->name = pstrdup(key);
1363
			iparam->expr = NULL;
1364
			iparam->opclass = NIL;
1365 1366 1367
			index->indexParams = lappend(index->indexParams, iparam);
		}

1368
		indexlist = lappend(indexlist, index);
1369 1370
	}

1371 1372
	/*
	 * Scan the index list and remove any redundant index specifications.
Bruce Momjian's avatar
Bruce Momjian committed
1373 1374 1375 1376
	 * This can happen if, for instance, the user writes UNIQUE PRIMARY
	 * KEY. A strict reading of SQL92 would suggest raising an error
	 * instead, but that strikes me as too anal-retentive. - tgl
	 * 2001-02-14
1377 1378 1379
	 *
	 * XXX in ALTER TABLE case, it'd be nice to look for duplicate
	 * pre-existing indexes, too.
1380
	 */
1381 1382
	cxt->alist = NIL;
	if (cxt->pkey != NULL)
1383
	{
1384
		/* Make sure we keep the PKEY index in preference to others... */
1385
		cxt->alist = list_make1(cxt->pkey);
1386
	}
1387 1388

	foreach(l, indexlist)
1389
	{
1390 1391 1392 1393
		bool		keep = true;
		ListCell   *k;

		index = lfirst(l);
1394

1395
		/* if it's pkey, it's already in cxt->alist */
1396 1397 1398 1399
		if (index == cxt->pkey)
			continue;

		foreach(k, cxt->alist)
1400
		{
1401
			IndexStmt  *priorindex = lfirst(k);
1402

1403
			if (equal(index->indexParams, priorindex->indexParams))
1404
			{
1405
				/*
Bruce Momjian's avatar
Bruce Momjian committed
1406 1407 1408 1409
				 * If the prior index is as yet unnamed, and this one is
				 * named, then transfer the name to the prior index. This
				 * ensures that if we have named and unnamed constraints,
				 * we'll use (at least one of) the names for the index.
1410 1411 1412 1413 1414
				 */
				if (priorindex->idxname == NULL)
					priorindex->idxname = index->idxname;
				keep = false;
				break;
1415 1416
			}
		}
1417

1418 1419
		if (keep)
			cxt->alist = lappend(cxt->alist, index);
1420
	}
1421
}
1422

1423
static void
1424
transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1425
					   bool skipValidation, bool isAddConstraint)
1426
{
1427
	ListCell   *fkclist;
1428

1429 1430
	if (cxt->fkconstraints == NIL)
		return;
1431

1432
	/*
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
	 * If CREATE TABLE or adding a column with NULL default, we can safely
	 * skip validation of the constraint.
	 */
	if (skipValidation)
	{
		foreach(fkclist, cxt->fkconstraints)
		{
			FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);

			fkconstraint->skip_validation = true;
		}
	}

	/*
	 * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE
Bruce Momjian's avatar
Bruce Momjian committed
1448 1449 1450
	 * ADD CONSTRAINT command to execute after the basic command is
	 * complete. (If called from ADD CONSTRAINT, that routine will add the
	 * FK constraints to its own subcommand list.)
1451 1452 1453 1454 1455 1456
	 *
	 * Note: the ADD CONSTRAINT command must also execute after any index
	 * creation commands.  Thus, this should run after
	 * transformIndexConstraints, so that the CREATE INDEX commands are
	 * already in cxt->alist.
	 */
1457
	if (!isAddConstraint)
Jan Wieck's avatar
Jan Wieck committed
1458
	{
1459
		AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
Jan Wieck's avatar
Jan Wieck committed
1460

1461
		alterstmt->relation = cxt->relation;
1462
		alterstmt->cmds = NIL;
1463
		alterstmt->relkind = OBJECT_TABLE;
Jan Wieck's avatar
Jan Wieck committed
1464

1465
		foreach(fkclist, cxt->fkconstraints)
1466
		{
1467
			FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
Bruce Momjian's avatar
Bruce Momjian committed
1468
			AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1469

1470 1471 1472 1473
			altercmd->subtype = AT_ProcessedConstraint;
			altercmd->name = NULL;
			altercmd->def = (Node *) fkconstraint;
			alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
Jan Wieck's avatar
Jan Wieck committed
1474
		}
1475

1476
		cxt->alist = lappend(cxt->alist, alterstmt);
1477
	}
1478
}
Jan Wieck's avatar
Jan Wieck committed
1479

1480 1481
/*
 * transformIndexStmt -
1482
 *	  transforms the qualification of the index statement
1483
 */
1484
static Query *
1485
transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1486
{
Bruce Momjian's avatar
Bruce Momjian committed
1487
	Query	   *qry;
1488
	RangeTblEntry *rte = NULL;
1489
	ListCell   *l;
1490

Bruce Momjian's avatar
Bruce Momjian committed
1491 1492
	qry = makeNode(Query);
	qry->commandType = CMD_UTILITY;
1493

1494
	/* take care of the where clause */
1495 1496 1497
	if (stmt->whereClause)
	{
		/*
1498 1499 1500 1501 1502
		 * Put the parent table into the rtable so that the WHERE clause
		 * can refer to its fields without qualification.  Note that this
		 * only works if the parent table already exists --- so we can't
		 * easily support predicates on indexes created implicitly by
		 * CREATE TABLE. Fortunately, that's not necessary.
1503
		 */
1504
		rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1505

1506 1507
		/* no to join list, yes to namespace */
		addRTEtoQuery(pstate, rte, false, true);
1508

1509 1510
		stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
												 "WHERE");
1511
	}
1512

1513 1514 1515
	/* take care of any index expressions */
	foreach(l, stmt->indexParams)
	{
Bruce Momjian's avatar
Bruce Momjian committed
1516
		IndexElem  *ielem = (IndexElem *) lfirst(l);
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528

		if (ielem->expr)
		{
			/* Set up rtable as for predicate, see notes above */
			if (rte == NULL)
			{
				rte = addRangeTableEntry(pstate, stmt->relation, NULL,
										 false, true);
				/* no to join list, yes to namespace */
				addRTEtoQuery(pstate, rte, false, true);
			}
			ielem->expr = transformExpr(pstate, ielem->expr);
Bruce Momjian's avatar
Bruce Momjian committed
1529

1530 1531 1532 1533 1534 1535
			/*
			 * We check only that the result type is legitimate; this is
			 * for consistency with what transformWhereClause() checks for
			 * the predicate.  DefineIndex() will make more checks.
			 */
			if (expression_returns_set(ielem->expr))
1536 1537
				ereport(ERROR,
						(errcode(ERRCODE_DATATYPE_MISMATCH),
Bruce Momjian's avatar
Bruce Momjian committed
1538
					   errmsg("index expression may not return a set")));
1539 1540 1541
		}
	}

Bruce Momjian's avatar
Bruce Momjian committed
1542
	qry->hasSubLinks = pstate->p_hasSubLinks;
1543
	stmt->rangetable = pstate->p_rtable;
1544

Bruce Momjian's avatar
Bruce Momjian committed
1545
	qry->utilityStmt = (Node *) stmt;
1546

Bruce Momjian's avatar
Bruce Momjian committed
1547
	return qry;
1548 1549 1550 1551
}

/*
 * transformRuleStmt -
1552 1553
 *	  transform a Create Rule Statement. The actions is a list of parse
 *	  trees which is transformed into a list of query trees.
1554
 */
1555
static Query *
1556
transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
Bruce Momjian's avatar
Bruce Momjian committed
1557
				  List **extras_before, List **extras_after)
1558
{
Bruce Momjian's avatar
Bruce Momjian committed
1559
	Query	   *qry;
1560 1561
	RangeTblEntry *oldrte;
	RangeTblEntry *newrte;
1562

Bruce Momjian's avatar
Bruce Momjian committed
1563 1564
	qry = makeNode(Query);
	qry->commandType = CMD_UTILITY;
1565 1566
	qry->utilityStmt = (Node *) stmt;

1567 1568
	/*
	 * To avoid deadlock, make sure the first thing we do is grab
1569 1570 1571
	 * AccessExclusiveLock on the target relation.	This will be needed by
	 * DefineQueryRewrite(), and we don't want to grab a lesser lock
	 * beforehand.	We don't need to hold a refcount on the relcache
1572 1573
	 * entry, however.
	 */
1574
	heap_close(heap_openrv(stmt->relation, AccessExclusiveLock),
1575 1576
			   NoLock);

1577
	/*
1578 1579 1580
	 * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to
	 * 2.  Set up their RTEs in the main pstate for use in parsing the
	 * rule qualification.
1581 1582
	 */
	Assert(pstate->p_rtable == NIL);
1583
	oldrte = addRangeTableEntry(pstate, stmt->relation,
1584
								makeAlias("*OLD*", NIL),
1585
								false, true);
1586
	newrte = addRangeTableEntry(pstate, stmt->relation,
1587
								makeAlias("*NEW*", NIL),
1588
								false, true);
1589
	/* Must override addRangeTableEntry's default access-check flags */
1590 1591
	oldrte->requiredPerms = 0;
	newrte->requiredPerms = 0;
1592

1593
	/*
1594
	 * They must be in the namespace too for lookup purposes, but only add
1595 1596
	 * the one(s) that are relevant for the current kind of rule.  In an
	 * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1597 1598 1599 1600
	 * unambiguous, but there's no need to be so picky for INSERT &
	 * DELETE. (Note we marked the RTEs "inFromCl = true" above to allow
	 * unqualified references to their fields.)  We do not add them to the
	 * joinlist.
1601 1602 1603 1604
	 */
	switch (stmt->event)
	{
		case CMD_SELECT:
1605
			addRTEtoQuery(pstate, oldrte, false, true);
1606 1607
			break;
		case CMD_UPDATE:
1608 1609
			addRTEtoQuery(pstate, oldrte, false, true);
			addRTEtoQuery(pstate, newrte, false, true);
1610 1611
			break;
		case CMD_INSERT:
1612
			addRTEtoQuery(pstate, newrte, false, true);
1613 1614
			break;
		case CMD_DELETE:
1615
			addRTEtoQuery(pstate, oldrte, false, true);
1616 1617
			break;
		default:
1618
			elog(ERROR, "unrecognized event type: %d",
1619 1620 1621 1622 1623
				 (int) stmt->event);
			break;
	}

	/* take care of the where clause */
1624 1625
	stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
											 "WHERE");
1626

Bruce Momjian's avatar
Bruce Momjian committed
1627
	if (list_length(pstate->p_rtable) != 2)		/* naughty, naughty... */
1628 1629 1630
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
				 errmsg("rule WHERE condition may not contain references to other relations")));
1631

1632
	/* aggregates not allowed (but subselects are okay) */
1633
	if (pstate->p_hasAggs)
1634 1635 1636
		ereport(ERROR,
				(errcode(ERRCODE_GROUPING_ERROR),
				 errmsg("rule WHERE condition may not contain aggregate functions")));
1637

1638 1639
	/* save info about sublinks in where clause */
	qry->hasSubLinks = pstate->p_hasSubLinks;
1640

1641
	/*
1642
	 * 'instead nothing' rules with a qualification need a query
1643 1644
	 * rangetable so the rewrite handler can add the negated rule
	 * qualification to the original query. We create a query with the new
1645
	 * command type CMD_NOTHING here that is treated specially by the
1646
	 * rewrite system.
1647
	 */
1648 1649 1650 1651
	if (stmt->actions == NIL)
	{
		Query	   *nothing_qry = makeNode(Query);

1652 1653
		nothing_qry->commandType = CMD_NOTHING;
		nothing_qry->rtable = pstate->p_rtable;
1654
		nothing_qry->jointree = makeFromExpr(NIL, NULL);		/* no join wanted */
1655

1656
		stmt->actions = list_make1(nothing_qry);
1657
	}
1658
	else
1659
	{
1660
		ListCell   *l;
1661
		List	   *newactions = NIL;
1662

1663
		/*
1664
		 * transform each statement, like parse_sub_analyze()
1665
		 */
1666
		foreach(l, stmt->actions)
1667
		{
1668
			Node	   *action = (Node *) lfirst(l);
1669
			ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1670 1671
			Query	   *sub_qry,
					   *top_subqry;
1672 1673
			bool		has_old,
						has_new;
1674

1675
			/*
1676 1677 1678 1679 1680 1681
			 * Set up OLD/NEW in the rtable for this statement.  The
			 * entries are marked not inFromCl because we don't want them
			 * to be referred to by unqualified field names nor "*" in the
			 * rule actions.  We must add them to the namespace, however,
			 * or they won't be accessible at all.  We decide later
			 * whether to put them in the joinlist.
1682
			 */
1683
			oldrte = addRangeTableEntry(sub_pstate, stmt->relation,
1684
										makeAlias("*OLD*", NIL),
1685
										false, false);
1686
			newrte = addRangeTableEntry(sub_pstate, stmt->relation,
1687
										makeAlias("*NEW*", NIL),
1688
										false, false);
1689 1690
			oldrte->requiredPerms = 0;
			newrte->requiredPerms = 0;
1691 1692
			addRTEtoQuery(sub_pstate, oldrte, false, true);
			addRTEtoQuery(sub_pstate, newrte, false, true);
1693

1694
			/* Transform the rule action statement */
1695
			top_subqry = transformStmt(sub_pstate, action,
Bruce Momjian's avatar
Bruce Momjian committed
1696
									   extras_before, extras_after);
1697 1698 1699

			/*
			 * We cannot support utility-statement actions (eg NOTIFY)
1700 1701
			 * with nonempty rule WHERE conditions, because there's no way
			 * to make the utility action execute conditionally.
1702 1703 1704
			 */
			if (top_subqry->commandType == CMD_UTILITY &&
				stmt->whereClause != NULL)
1705 1706 1707
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
						 errmsg("rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions")));
1708 1709 1710 1711

			/*
			 * If the action is INSERT...SELECT, OLD/NEW have been pushed
			 * down into the SELECT, and that's what we need to look at.
1712 1713
			 * (Ugly kluge ... try to fix this when we redesign
			 * querytrees.)
1714 1715
			 */
			sub_qry = getInsertSelectQuery(top_subqry, NULL);
1716

1717
			/*
Bruce Momjian's avatar
Bruce Momjian committed
1718 1719 1720 1721
			 * If the sub_qry is a setop, we cannot attach any
			 * qualifications to it, because the planner won't notice
			 * them.  This could perhaps be relaxed someday, but for now,
			 * we may as well reject such a rule immediately.
1722 1723
			 */
			if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1724 1725 1726
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1727

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
			/*
			 * Validate action's use of OLD/NEW, qual too
			 */
			has_old =
				rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
				rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
			has_new =
				rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
				rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);

			switch (stmt->event)
			{
				case CMD_SELECT:
					if (has_old)
1742
						ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
1743 1744
							 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
							  errmsg("ON SELECT rule may not use OLD")));
1745
					if (has_new)
1746
						ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
1747 1748
							 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
							  errmsg("ON SELECT rule may not use NEW")));
1749 1750 1751 1752 1753 1754
					break;
				case CMD_UPDATE:
					/* both are OK */
					break;
				case CMD_INSERT:
					if (has_old)
1755
						ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
1756 1757
							 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
							  errmsg("ON INSERT rule may not use OLD")));
1758 1759 1760
					break;
				case CMD_DELETE:
					if (has_new)
1761
						ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
1762 1763
							 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
							  errmsg("ON DELETE rule may not use NEW")));
1764 1765
					break;
				default:
1766
					elog(ERROR, "unrecognized event type: %d",
1767 1768 1769 1770 1771
						 (int) stmt->event);
					break;
			}

			/*
1772 1773 1774
			 * For efficiency's sake, add OLD to the rule action's
			 * jointree only if it was actually referenced in the
			 * statement or qual.
1775 1776 1777 1778 1779 1780
			 *
			 * For INSERT, NEW is not really a relation (only a reference to
			 * the to-be-inserted tuple) and should never be added to the
			 * jointree.
			 *
			 * For UPDATE, we treat NEW as being another kind of reference to
1781 1782 1783 1784 1785 1786
			 * OLD, because it represents references to *transformed*
			 * tuples of the existing relation.  It would be wrong to
			 * enter NEW separately in the jointree, since that would
			 * cause a double join of the updated relation.  It's also
			 * wrong to fail to make a jointree entry if only NEW and not
			 * OLD is mentioned.
1787
			 */
1788
			if (has_old || (has_new && stmt->event == CMD_UPDATE))
1789
			{
1790
				/*
Bruce Momjian's avatar
Bruce Momjian committed
1791
				 * If sub_qry is a setop, manipulating its jointree will
1792 1793
				 * do no good at all, because the jointree is dummy. (This
				 * should be a can't-happen case because of prior tests.)
1794 1795
				 */
				if (sub_qry->setOperations != NULL)
1796 1797 1798
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1799
				/* hack so we can use addRTEtoQuery() */
1800 1801
				sub_pstate->p_rtable = sub_qry->rtable;
				sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1802
				addRTEtoQuery(sub_pstate, oldrte, true, false);
1803
				sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1804 1805
			}

1806
			newactions = lappend(newactions, top_subqry);
1807 1808 1809 1810

			release_pstate_resources(sub_pstate);
			pfree(sub_pstate);
		}
1811 1812

		stmt->actions = newactions;
1813
	}
1814

Bruce Momjian's avatar
Bruce Momjian committed
1815
	return qry;
1816 1817 1818 1819 1820
}


/*
 * transformSelectStmt -
1821
 *	  transforms a Select Statement
1822
 *
1823
 * Note: this is also used for DECLARE CURSOR statements.
1824
 */
1825
static Query *
Bruce Momjian's avatar
Bruce Momjian committed
1826
transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1827
{
1828
	Query	   *qry = makeNode(Query);
1829
	Node	   *qual;
1830 1831

	qry->commandType = CMD_SELECT;
1832

1833 1834 1835
	/* make FOR UPDATE clause available to addRangeTableEntry */
	pstate->p_forUpdate = stmt->forUpdate;

1836 1837
	/* process the FROM clause */
	transformFromClause(pstate, stmt->fromClause);
1838

1839
	/* transform targetlist */
1840
	qry->targetList = transformTargetList(pstate, stmt->targetList);
1841

1842 1843
	/* handle any SELECT INTO/CREATE TABLE AS spec */
	qry->into = stmt->into;
1844 1845 1846
	if (stmt->intoColNames)
		applyColumnNames(qry->targetList, stmt->intoColNames);

1847
	qry->intoHasOids = interpretOidsOption(stmt->intoHasOids);
1848

1849 1850 1851
	/* mark column origins */
	markTargetListOrigins(pstate, qry->targetList);

1852
	/* transform WHERE */
1853
	qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1854

1855 1856
	/*
	 * Initial processing of HAVING clause is just like WHERE clause.
1857
	 */
1858 1859
	qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
										   "HAVING");
1860

1861 1862 1863 1864
	/*
	 * Transform sorting/grouping stuff.  Do ORDER BY first because both
	 * transformGroupClause and transformDistinctClause need the results.
	 */
1865 1866
	qry->sortClause = transformSortClause(pstate,
										  stmt->sortClause,
1867
										  &qry->targetList,
Bruce Momjian's avatar
Bruce Momjian committed
1868
										  true /* fix unknowns */ );
1869

1870 1871
	qry->groupClause = transformGroupClause(pstate,
											stmt->groupClause,
1872
											&qry->targetList,
1873 1874
											qry->sortClause);

1875 1876
	qry->distinctClause = transformDistinctClause(pstate,
												  stmt->distinctClause,
1877
												  &qry->targetList,
1878
												  &qry->sortClause);
1879

1880 1881 1882 1883
	qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
											"OFFSET");
	qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
										   "LIMIT");
1884

1885 1886 1887
	qry->rtable = pstate->p_rtable;
	qry->jointree = makeFromExpr(pstate->p_joinlist, qual);

1888
	qry->hasSubLinks = pstate->p_hasSubLinks;
Bruce Momjian's avatar
Bruce Momjian committed
1889
	qry->hasAggs = pstate->p_hasAggs;
1890
	if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1891
		parseCheckAggregates(pstate, qry);
1892

1893
	if (stmt->forUpdate != NIL)
1894 1895 1896 1897 1898 1899 1900
		transformForUpdate(qry, stmt->forUpdate);

	return qry;
}

/*
 * transformSetOperationsStmt -
1901
 *	  transforms a set-operations tree
1902
 *
1903
 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1904 1905
 * structure to it.  We must transform each leaf SELECT and build up a top-
 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1906 1907
 * The tree of set operations is converted into the setOperations field of
 * the top-level Query.
1908
 */
1909 1910
static Query *
transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1911 1912 1913
{
	Query	   *qry = makeNode(Query);
	SelectStmt *leftmostSelect;
1914
	int			leftmostRTI;
1915
	Query	   *leftmostQuery;
1916
	SetOperationStmt *sostmt;
1917
	RangeVar   *into;
1918
	List	   *intoColNames;
1919 1920 1921 1922
	List	   *sortClause;
	Node	   *limitOffset;
	Node	   *limitCount;
	List	   *forUpdate;
1923
	Node	   *node;
1924 1925 1926
	ListCell   *left_tlist,
			   *dtlist;
	List	   *targetvars,
1927
			   *targetnames,
1928 1929 1930 1931
			   *sv_namespace,
			   *sv_rtable;
	RangeTblEntry *jrte;
	RangeTblRef *jrtr;
1932 1933 1934 1935
	int			tllen;

	qry->commandType = CMD_SELECT;

1936
	/*
1937 1938
	 * Find leftmost leaf SelectStmt; extract the one-time-only items from
	 * it and from the top-level node.
1939
	 */
1940 1941 1942 1943 1944
	leftmostSelect = stmt->larg;
	while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
		leftmostSelect = leftmostSelect->larg;
	Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
		   leftmostSelect->larg == NULL);
1945
	into = leftmostSelect->into;
1946
	intoColNames = leftmostSelect->intoColNames;
1947 1948 1949

	/* clear them to prevent complaints in transformSetOperationTree() */
	leftmostSelect->into = NULL;
1950
	leftmostSelect->intoColNames = NIL;
1951

1952 1953
	/*
	 * These are not one-time, exactly, but we want to process them here
1954 1955
	 * and not let transformSetOperationTree() see them --- else it'll
	 * just recurse right back here!
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
	 */
	sortClause = stmt->sortClause;
	limitOffset = stmt->limitOffset;
	limitCount = stmt->limitCount;
	forUpdate = stmt->forUpdate;

	stmt->sortClause = NIL;
	stmt->limitOffset = NULL;
	stmt->limitCount = NULL;
	stmt->forUpdate = NIL;

	/* We don't support forUpdate with set ops at the moment. */
1968
	if (forUpdate)
1969 1970 1971
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
1972

Bruce Momjian's avatar
Bruce Momjian committed
1973
	/*
1974
	 * Recursively transform the components of the tree.
Bruce Momjian's avatar
Bruce Momjian committed
1975
	 */
1976 1977 1978
	sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
	Assert(sostmt && IsA(sostmt, SetOperationStmt));
	qry->setOperations = (Node *) sostmt;
1979 1980 1981 1982

	/*
	 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
	 */
1983
	node = sostmt->larg;
1984 1985 1986
	while (node && IsA(node, SetOperationStmt))
		node = ((SetOperationStmt *) node)->larg;
	Assert(node && IsA(node, RangeTblRef));
1987 1988
	leftmostRTI = ((RangeTblRef *) node)->rtindex;
	leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1989
	Assert(leftmostQuery != NULL);
1990

1991 1992
	/*
	 * Generate dummy targetlist for outer query using column names of
1993
	 * leftmost select and common datatypes of topmost set operation. Also
1994 1995
	 * make lists of the dummy vars and their names for use in parsing
	 * ORDER BY.
1996
	 *
Bruce Momjian's avatar
Bruce Momjian committed
1997 1998 1999 2000
	 * Note: we use leftmostRTI as the varno of the dummy variables. It
	 * shouldn't matter too much which RT index they have, as long as they
	 * have one that corresponds to a real RT entry; else funny things may
	 * happen when the tree is mashed by rule rewriting.
2001 2002
	 */
	qry->targetList = NIL;
2003
	targetvars = NIL;
2004
	targetnames = NIL;
2005 2006
	left_tlist = list_head(leftmostQuery->targetList);

2007
	foreach(dtlist, sostmt->colTypes)
2008
	{
2009
		Oid			colType = lfirst_oid(dtlist);
2010
		Resdom	   *leftResdom;
2011
		char	   *colName;
2012
		Resdom	   *resdom;
2013
		Expr	   *expr;
2014

2015
		leftResdom = ((TargetEntry *) lfirst(left_tlist))->resdom;
2016 2017
		Assert(!leftResdom->resjunk);
		colName = pstrdup(leftResdom->resname);
2018
		resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
2019 2020
							colType,
							-1,
2021
							colName,
2022
							false);
2023
		expr = (Expr *) makeVar(leftmostRTI,
2024
								leftResdom->resno,
2025 2026 2027 2028 2029
								colType,
								-1,
								0);
		qry->targetList = lappend(qry->targetList,
								  makeTargetEntry(resdom, expr));
2030
		targetvars = lappend(targetvars, expr);
2031
		targetnames = lappend(targetnames, makeString(colName));
2032
		left_tlist = lnext(left_tlist);
2033
	}
2034

2035
	/*
2036
	 * Handle SELECT INTO/CREATE TABLE AS.
2037
	 *
Bruce Momjian's avatar
Bruce Momjian committed
2038 2039
	 * Any column names from CREATE TABLE AS need to be attached to both the
	 * top level and the leftmost subquery.  We do not do this earlier
2040 2041
	 * because we do *not* want the targetnames list to be affected.
	 */
2042
	qry->into = into;
2043
	if (intoColNames)
2044
	{
2045
		applyColumnNames(qry->targetList, intoColNames);
2046 2047
		applyColumnNames(leftmostQuery->targetList, intoColNames);
	}
2048

2049
	/*
2050 2051
	 * As a first step towards supporting sort clauses that are
	 * expressions using the output columns, generate a namespace entry
2052
	 * that makes the output columns visible.  A Join RTE node is handy
2053 2054
	 * for this, since we can easily control the Vars generated upon
	 * matches.
2055 2056 2057 2058 2059
	 *
	 * Note: we don't yet do anything useful with such cases, but at least
	 * "ORDER BY upper(foo)" will draw the right error message rather than
	 * "foo not found".
	 */
2060 2061 2062
	jrte = addRangeTableEntryForJoin(NULL,
									 targetnames,
									 JOIN_INNER,
2063
									 targetvars,
2064 2065 2066
									 NULL,
									 true);
	jrtr = makeNode(RangeTblRef);
2067
	jrtr->rtindex = 1;			/* only entry in dummy rtable */
2068 2069

	sv_rtable = pstate->p_rtable;
2070
	pstate->p_rtable = list_make1(jrte);
2071 2072

	sv_namespace = pstate->p_namespace;
2073
	pstate->p_namespace = list_make1(jrtr);
2074

2075 2076 2077 2078 2079 2080
	/*
	 * For now, we don't support resjunk sort clauses on the output of a
	 * setOperation tree --- you can only use the SQL92-spec options of
	 * selecting an output column by name or number.  Enforce by checking
	 * that transformSortClause doesn't add any items to tlist.
	 */
2081
	tllen = list_length(qry->targetList);
2082 2083 2084

	qry->sortClause = transformSortClause(pstate,
										  sortClause,
2085
										  &qry->targetList,
Bruce Momjian's avatar
Bruce Momjian committed
2086
									  false /* no unknowns expected */ );
2087

2088
	pstate->p_namespace = sv_namespace;
2089
	pstate->p_rtable = sv_rtable;
2090

2091
	if (tllen != list_length(qry->targetList))
2092 2093 2094
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns")));
2095

2096 2097 2098 2099
	qry->limitOffset = transformLimitClause(pstate, limitOffset,
											"OFFSET");
	qry->limitCount = transformLimitClause(pstate, limitCount,
										   "LIMIT");
2100

2101 2102 2103
	qry->rtable = pstate->p_rtable;
	qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);

2104 2105
	qry->hasSubLinks = pstate->p_hasSubLinks;
	qry->hasAggs = pstate->p_hasAggs;
2106
	if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2107
		parseCheckAggregates(pstate, qry);
2108

2109
	if (forUpdate != NIL)
2110
		transformForUpdate(qry, forUpdate);
2111

2112 2113 2114 2115 2116 2117 2118 2119
	return qry;
}

/*
 * transformSetOperationTree
 *		Recursively transform leaves and internal nodes of a set-op tree
 */
static Node *
2120
transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2121
{
2122
	bool		isLeaf;
2123 2124 2125 2126 2127 2128 2129

	Assert(stmt && IsA(stmt, SelectStmt));

	/*
	 * Validity-check both leaf and internal SELECTs for disallowed ops.
	 */
	if (stmt->into)
2130 2131 2132
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2133 2134
	/* We don't support forUpdate with set ops at the moment. */
	if (stmt->forUpdate)
2135 2136 2137
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150

	/*
	 * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
	 * clauses attached, we need to treat it like a leaf node to generate
	 * an independent sub-Query tree.  Otherwise, it can be represented by
	 * a SetOperationStmt node underneath the parent Query.
	 */
	if (stmt->op == SETOP_NONE)
	{
		Assert(stmt->larg == NULL && stmt->rarg == NULL);
		isLeaf = true;
	}
	else
2151
	{
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
		Assert(stmt->larg != NULL && stmt->rarg != NULL);
		if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
			stmt->forUpdate)
			isLeaf = true;
		else
			isLeaf = false;
	}

	if (isLeaf)
	{
		/* Process leaf SELECT */
2163 2164 2165
		List	   *selectList;
		Query	   *selectQuery;
		char		selectName[32];
2166 2167 2168 2169
		RangeTblEntry *rte;
		RangeTblRef *rtr;

		/*
2170 2171 2172
		 * Transform SelectStmt into a Query.
		 *
		 * Note: previously transformed sub-queries don't affect the parsing
2173 2174
		 * of this sub-query, because they are not in the toplevel
		 * pstate's namespace list.
2175
		 */
2176
		selectList = parse_sub_analyze((Node *) stmt, pstate);
2177

2178
		Assert(list_length(selectList) == 1);
2179
		selectQuery = (Query *) linitial(selectList);
2180 2181 2182 2183
		Assert(IsA(selectQuery, Query));

		/*
		 * Check for bogus references to Vars on the current query level
Bruce Momjian's avatar
Bruce Momjian committed
2184 2185 2186
		 * (but upper-level references are okay). Normally this can't
		 * happen because the namespace will be empty, but it could happen
		 * if we are inside a rule.
2187 2188 2189 2190
		 */
		if (pstate->p_namespace)
		{
			if (contain_vars_of_level((Node *) selectQuery, 1))
2191 2192 2193
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
						 errmsg("UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level")));
2194
		}
2195

2196 2197 2198
		/*
		 * Make the leaf query be a subquery in the top-level rangetable.
		 */
2199
		snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2200
				 list_length(pstate->p_rtable) + 1);
2201 2202
		rte = addRangeTableEntryForSubquery(pstate,
											selectQuery,
2203
											makeAlias(selectName, NIL),
2204
											false);
2205

2206
		/*
2207 2208
		 * Return a RangeTblRef to replace the SelectStmt in the set-op
		 * tree.
2209 2210 2211
		 */
		rtr = makeNode(RangeTblRef);
		/* assume new rte is at end */
2212
		rtr->rtindex = list_length(pstate->p_rtable);
2213 2214 2215
		Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
		return (Node *) rtr;
	}
2216
	else
2217
	{
2218 2219
		/* Process an internal node (set operation node) */
		SetOperationStmt *op = makeNode(SetOperationStmt);
2220 2221
		List	   *lcoltypes;
		List	   *rcoltypes;
2222 2223
		ListCell   *l;
		ListCell   *r;
2224 2225
		const char *context;

2226 2227
		context = (stmt->op == SETOP_UNION ? "UNION" :
				   (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2228
					"EXCEPT"));
2229 2230 2231 2232

		op->op = stmt->op;
		op->all = stmt->all;

2233 2234 2235
		/*
		 * Recursively transform the child nodes.
		 */
2236 2237
		op->larg = transformSetOperationTree(pstate, stmt->larg);
		op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2238

2239 2240 2241 2242 2243 2244
		/*
		 * Verify that the two children have the same number of non-junk
		 * columns, and determine the types of the merged output columns.
		 */
		lcoltypes = getSetColTypes(pstate, op->larg);
		rcoltypes = getSetColTypes(pstate, op->rarg);
2245
		if (list_length(lcoltypes) != list_length(rcoltypes))
2246 2247
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2248 2249
			 errmsg("each %s query must have the same number of columns",
					context)));
2250

2251
		op->colTypes = NIL;
2252
		forboth(l, lcoltypes, r, rcoltypes)
2253
		{
2254 2255
			Oid			lcoltype = lfirst_oid(l);
			Oid			rcoltype = lfirst_oid(r);
2256
			Oid			rescoltype;
2257

2258
			rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2259
											context);
2260
			op->colTypes = lappend_oid(op->colTypes, rescoltype);
2261
		}
2262

2263 2264
		return (Node *) op;
	}
2265 2266
}

2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
/*
 * getSetColTypes
 *		Get output column types of an (already transformed) set-op node
 */
static List *
getSetColTypes(ParseState *pstate, Node *node)
{
	if (IsA(node, RangeTblRef))
	{
		RangeTblRef *rtr = (RangeTblRef *) node;
		RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2278 2279
		Query	   *selectQuery = rte->subquery;
		List	   *result = NIL;
2280
		ListCell   *tl;
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290

		Assert(selectQuery != NULL);
		/* Get types of non-junk columns */
		foreach(tl, selectQuery->targetList)
		{
			TargetEntry *tle = (TargetEntry *) lfirst(tl);
			Resdom	   *resnode = tle->resdom;

			if (resnode->resjunk)
				continue;
2291
			result = lappend_oid(result, resnode->restype);
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304
		}
		return result;
	}
	else if (IsA(node, SetOperationStmt))
	{
		SetOperationStmt *op = (SetOperationStmt *) node;

		/* Result already computed during transformation of node */
		Assert(op->colTypes != NIL);
		return op->colTypes;
	}
	else
	{
2305
		elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2306 2307 2308 2309
		return NIL;				/* keep compiler quiet */
	}
}

2310 2311 2312 2313
/* Attach column names from a ColumnDef list to a TargetEntry list */
static void
applyColumnNames(List *dst, List *src)
{
2314 2315
	ListCell   *dst_item;
	ListCell   *src_item;
2316

2317
	if (list_length(src) > list_length(dst))
2318 2319
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2320
			 errmsg("CREATE TABLE AS specifies too many column names")));
2321

2322
	forboth(dst_item, dst, src_item, src)
2323
	{
2324 2325
		TargetEntry *d = (TargetEntry *) lfirst(dst_item);
		ColumnDef  *s = (ColumnDef *) lfirst(src_item);
2326 2327 2328 2329 2330 2331

		Assert(d->resdom && !d->resdom->resjunk);
		d->resdom->resname = pstrdup(s->colname);
	}
}

2332

2333 2334
/*
 * transformUpdateStmt -
2335
 *	  transforms an update statement
2336
 */
2337
static Query *
Bruce Momjian's avatar
Bruce Momjian committed
2338
transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2339
{
2340
	Query	   *qry = makeNode(Query);
2341
	Node	   *qual;
2342 2343
	ListCell   *origTargetList;
	ListCell   *tl;
2344 2345 2346

	qry->commandType = CMD_UPDATE;
	pstate->p_is_update = true;
2347

2348
	qry->resultRelation = setTargetTable(pstate, stmt->relation,
Bruce Momjian's avatar
Bruce Momjian committed
2349
							  interpretInhOption(stmt->relation->inhOpt),
2350 2351
										 true,
										 ACL_UPDATE);
2352

2353 2354 2355 2356
	/*
	 * the FROM clause is non-standard SQL syntax. We used to be able to
	 * do this with REPLACE in POSTQUEL so we keep the feature.
	 */
2357
	transformFromClause(pstate, stmt->fromClause);
2358

2359
	qry->targetList = transformTargetList(pstate, stmt->targetList);
2360

2361
	qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2362

2363
	qry->rtable = pstate->p_rtable;
2364
	qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2365

2366
	qry->hasSubLinks = pstate->p_hasSubLinks;
Bruce Momjian's avatar
Bruce Momjian committed
2367
	qry->hasAggs = pstate->p_hasAggs;
2368
	if (pstate->p_hasAggs)
2369
		parseCheckAggregates(pstate, qry);
2370

2371 2372 2373 2374 2375 2376
	/*
	 * Now we are done with SELECT-like processing, and can get on with
	 * transforming the target list to match the UPDATE target columns.
	 */

	/* Prepare to assign non-conflicting resnos to resjunk attributes */
2377 2378
	if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
		pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2379 2380

	/* Prepare non-junk columns for assignment to target table */
2381 2382
	origTargetList = list_head(stmt->targetList);

2383 2384 2385 2386 2387 2388 2389 2390
	foreach(tl, qry->targetList)
	{
		TargetEntry *tle = (TargetEntry *) lfirst(tl);
		Resdom	   *resnode = tle->resdom;
		ResTarget  *origTarget;

		if (resnode->resjunk)
		{
2391 2392
			/*
			 * Resjunk nodes need no additional processing, but be sure
Bruce Momjian's avatar
Bruce Momjian committed
2393 2394 2395
			 * they have resnos that do not match any target columns; else
			 * rewriter or planner might get confused.	They don't need a
			 * resname either.
2396
			 */
2397
			resnode->resno = (AttrNumber) pstate->p_next_resno++;
2398
			resnode->resname = NULL;
2399 2400
			continue;
		}
2401
		if (origTargetList == NULL)
2402 2403
			elog(ERROR, "UPDATE target count mismatch --- internal error");
		origTarget = (ResTarget *) lfirst(origTargetList);
2404
		Assert(IsA(origTarget, ResTarget));
2405

2406 2407
		updateTargetListEntry(pstate, tle, origTarget->name,
							  attnameAttNum(pstate->p_target_relation,
2408
											origTarget->name, true),
2409
							  origTarget->indirection);
2410

2411 2412
		origTargetList = lnext(origTargetList);
	}
2413
	if (origTargetList != NULL)
2414 2415
		elog(ERROR, "UPDATE target count mismatch --- internal error");

2416
	return qry;
2417
}
Bruce Momjian's avatar
Hi!  
Bruce Momjian committed
2418

2419 2420
/*
 * tranformAlterTableStmt -
2421
 *	transform an Alter Table Statement
2422 2423
 */
static Query *
2424 2425
transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
						List **extras_before, List **extras_after)
2426
{
2427
	CreateStmtContext cxt;
2428
	Query	   *qry;
2429
	ListCell   *lcmd,
2430 2431 2432
			   *l;
	List	   *newcmds = NIL;
	bool		skipValidation = true;
Bruce Momjian's avatar
Bruce Momjian committed
2433
	AlterTableCmd *newcmd;
2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446

	cxt.stmtType = "ALTER TABLE";
	cxt.relation = stmt->relation;
	cxt.inhRelations = NIL;
	cxt.isalter = true;
	cxt.hasoids = false;		/* need not be right */
	cxt.columns = NIL;
	cxt.ckconstraints = NIL;
	cxt.fkconstraints = NIL;
	cxt.ixconstraints = NIL;
	cxt.blist = NIL;
	cxt.alist = NIL;
	cxt.pkey = NULL;
2447 2448

	/*
2449
	 * The only subtypes that currently require parse transformation
Bruce Momjian's avatar
Bruce Momjian committed
2450 2451
	 * handling are ADD COLUMN and ADD CONSTRAINT.	These largely re-use
	 * code from CREATE TABLE.
2452
	 */
2453
	foreach(lcmd, stmt->cmds)
2454
	{
Bruce Momjian's avatar
Bruce Momjian committed
2455
		AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
2456

2457 2458 2459
		switch (cmd->subtype)
		{
			case AT_AddColumn:
Bruce Momjian's avatar
Bruce Momjian committed
2460 2461
				{
					ColumnDef  *def = (ColumnDef *) cmd->def;
2462

Bruce Momjian's avatar
Bruce Momjian committed
2463 2464 2465
					Assert(IsA(cmd->def, ColumnDef));
					transformColumnDefinition(pstate, &cxt,
											  (ColumnDef *) cmd->def);
2466

Bruce Momjian's avatar
Bruce Momjian committed
2467 2468 2469 2470 2471 2472
					/*
					 * If the column has a non-null default, we can't skip
					 * validation of foreign keys.
					 */
					if (((ColumnDef *) cmd->def)->raw_default != NULL)
						skipValidation = false;
2473

Bruce Momjian's avatar
Bruce Momjian committed
2474
					newcmds = lappend(newcmds, cmd);
2475

Bruce Momjian's avatar
Bruce Momjian committed
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498
					/*
					 * Convert an ADD COLUMN ... NOT NULL constraint to a
					 * separate command
					 */
					if (def->is_not_null)
					{
						/* Remove NOT NULL from AddColumn */
						def->is_not_null = false;

						/* Add as a separate AlterTableCmd */
						newcmd = makeNode(AlterTableCmd);
						newcmd->subtype = AT_SetNotNull;
						newcmd->name = pstrdup(def->colname);
						newcmds = lappend(newcmds, newcmd);
					}

					/*
					 * All constraints are processed in other ways. Remove
					 * the original list
					 */
					def->constraints = NIL;

					break;
2499
				}
Bruce Momjian's avatar
Bruce Momjian committed
2500
			case AT_AddConstraint:
Bruce Momjian's avatar
Bruce Momjian committed
2501

2502
				/*
Bruce Momjian's avatar
Bruce Momjian committed
2503 2504
				 * The original AddConstraint cmd node doesn't go to
				 * newcmds
2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522
				 */

				if (IsA(cmd->def, Constraint))
					transformTableConstraint(pstate, &cxt,
											 (Constraint *) cmd->def);
				else if (IsA(cmd->def, FkConstraint))
				{
					cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
					skipValidation = false;
				}
				else
					elog(ERROR, "unrecognized node type: %d",
						 (int) nodeTag(cmd->def));
				break;

			case AT_ProcessedConstraint:

				/*
Bruce Momjian's avatar
Bruce Momjian committed
2523 2524
				 * Already-transformed ADD CONSTRAINT, so just make it
				 * look like the standard case.
2525 2526 2527 2528 2529 2530 2531 2532 2533
				 */
				cmd->subtype = AT_AddConstraint;
				newcmds = lappend(newcmds, cmd);
				break;

			default:
				newcmds = lappend(newcmds, cmd);
				break;
		}
2534
	}
2535

2536 2537 2538 2539 2540 2541
	/* Postprocess index and FK constraints */
	transformIndexConstraints(pstate, &cxt);

	transformFKConstraints(pstate, &cxt, skipValidation, true);

	/*
Bruce Momjian's avatar
Bruce Momjian committed
2542 2543
	 * Push any index-creation commands into the ALTER, so that they can
	 * be scheduled nicely by tablecmds.c.
2544 2545 2546
	 */
	foreach(l, cxt.alist)
	{
Bruce Momjian's avatar
Bruce Momjian committed
2547
		Node	   *idxstmt = (Node *) lfirst(l);
2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575

		Assert(IsA(idxstmt, IndexStmt));
		newcmd = makeNode(AlterTableCmd);
		newcmd->subtype = AT_AddIndex;
		newcmd->def = idxstmt;
		newcmds = lappend(newcmds, newcmd);
	}
	cxt.alist = NIL;

	/* Append any CHECK or FK constraints to the commands list */
	foreach(l, cxt.ckconstraints)
	{
		newcmd = makeNode(AlterTableCmd);
		newcmd->subtype = AT_AddConstraint;
		newcmd->def = (Node *) lfirst(l);
		newcmds = lappend(newcmds, newcmd);
	}
	foreach(l, cxt.fkconstraints)
	{
		newcmd = makeNode(AlterTableCmd);
		newcmd->subtype = AT_AddConstraint;
		newcmd->def = (Node *) lfirst(l);
		newcmds = lappend(newcmds, newcmd);
	}

	/* Update statement's commands list */
	stmt->cmds = newcmds;

2576 2577
	qry = makeNode(Query);
	qry->commandType = CMD_UTILITY;
2578
	qry->utilityStmt = (Node *) stmt;
2579

2580 2581
	*extras_before = list_concat(*extras_before, cxt.blist);
	*extras_after = list_concat(cxt.alist, *extras_after);
2582

2583 2584 2585
	return qry;
}

2586
static Query *
2587
transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2588 2589 2590 2591 2592 2593 2594 2595
{
	Query	   *result = makeNode(Query);
	List	   *extras_before = NIL,
			   *extras_after = NIL;

	result->commandType = CMD_UTILITY;
	result->utilityStmt = (Node *) stmt;

2596 2597 2598 2599 2600
	/*
	 * Don't allow both SCROLL and NO SCROLL to be specified
	 */
	if ((stmt->options & CURSOR_OPT_SCROLL) &&
		(stmt->options & CURSOR_OPT_NO_SCROLL))
2601 2602 2603
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
				 errmsg("cannot specify both SCROLL and NO SCROLL")));
2604

2605 2606 2607 2608 2609
	stmt->query = (Node *) transformStmt(pstate, stmt->query,
										 &extras_before, &extras_after);

	/* Shouldn't get any extras, since grammar only allows SelectStmt */
	if (extras_before || extras_after)
2610
		elog(ERROR, "unexpected extra stuff in cursor statement");
2611 2612 2613 2614 2615

	return result;
}


2616 2617 2618
static Query *
transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
{
Bruce Momjian's avatar
Bruce Momjian committed
2619 2620
	Query	   *result = makeNode(Query);
	List	   *argtype_oids = NIL;		/* argtype OIDs in a list */
Bruce Momjian's avatar
Bruce Momjian committed
2621
	Oid		   *argtoids = NULL;	/* and as an array */
Bruce Momjian's avatar
Bruce Momjian committed
2622
	int			nargs;
2623
	List	   *queries;
2624 2625 2626 2627 2628

	result->commandType = CMD_UTILITY;
	result->utilityStmt = (Node *) stmt;

	/* Transform list of TypeNames to list (and array) of type OIDs */
2629
	nargs = list_length(stmt->argtypes);
2630 2631 2632

	if (nargs)
	{
2633
		ListCell   *l;
Bruce Momjian's avatar
Bruce Momjian committed
2634
		int			i = 0;
2635 2636 2637

		argtoids = (Oid *) palloc(nargs * sizeof(Oid));

Bruce Momjian's avatar
Bruce Momjian committed
2638
		foreach(l, stmt->argtypes)
2639
		{
Bruce Momjian's avatar
Bruce Momjian committed
2640 2641
			TypeName   *tn = lfirst(l);
			Oid			toid = typenameTypeId(tn);
2642

2643
			argtype_oids = lappend_oid(argtype_oids, toid);
2644 2645 2646 2647 2648 2649 2650
			argtoids[i++] = toid;
		}
	}

	stmt->argtype_oids = argtype_oids;

	/*
2651 2652
	 * Analyze the statement using these parameter types (any parameters
	 * passed in from above us will not be visible to it).
2653
	 */
2654
	queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2655

2656 2657 2658 2659
	/*
	 * Shouldn't get any extra statements, since grammar only allows
	 * OptimizableStmt
	 */
2660
	if (list_length(queries) != 1)
2661
		elog(ERROR, "unexpected extra stuff in prepared statement");
2662

2663
	stmt->query = linitial(queries);
2664 2665 2666 2667 2668 2669 2670

	return result;
}

static Query *
transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
{
Bruce Momjian's avatar
Bruce Momjian committed
2671 2672
	Query	   *result = makeNode(Query);
	List	   *paramtypes;
2673 2674 2675 2676

	result->commandType = CMD_UTILITY;
	result->utilityStmt = (Node *) stmt;

2677
	paramtypes = FetchPreparedStatementParams(stmt->name);
2678 2679 2680

	if (stmt->params || paramtypes)
	{
2681 2682
		int			nparams = list_length(stmt->params);
		int			nexpected = list_length(paramtypes);
Bruce Momjian's avatar
Bruce Momjian committed
2683 2684
		ListCell   *l,
				   *l2;
Bruce Momjian's avatar
Bruce Momjian committed
2685
		int			i = 1;
2686 2687

		if (nparams != nexpected)
2688 2689 2690 2691 2692 2693
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("wrong number of parameters for prepared statement \"%s\"",
							stmt->name),
					 errdetail("Expected %d parameters but got %d.",
							   nexpected, nparams)));
2694

2695
		forboth(l, stmt->params, l2, paramtypes)
2696
		{
Bruce Momjian's avatar
Bruce Momjian committed
2697
			Node	   *expr = lfirst(l);
2698
			Oid			expected_type_id = lfirst_oid(l2);
2699
			Oid			given_type_id;
2700

2701
			expr = transformExpr(pstate, expr);
2702 2703

			/* Cannot contain subselects or aggregates */
2704
			if (pstate->p_hasSubLinks)
2705 2706
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
Bruce Momjian's avatar
Bruce Momjian committed
2707
					errmsg("cannot use subquery in EXECUTE parameter")));
2708
			if (pstate->p_hasAggs)
2709 2710
				ereport(ERROR,
						(errcode(ERRCODE_GROUPING_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2711
						 errmsg("cannot use aggregate function in EXECUTE parameter")));
2712 2713 2714

			given_type_id = exprType(expr);

2715
			expr = coerce_to_target_type(pstate, expr, given_type_id,
2716 2717 2718 2719 2720
										 expected_type_id, -1,
										 COERCION_ASSIGNMENT,
										 COERCE_IMPLICIT_CAST);

			if (expr == NULL)
2721 2722 2723 2724 2725 2726 2727
				ereport(ERROR,
						(errcode(ERRCODE_DATATYPE_MISMATCH),
						 errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
								i,
								format_type_be(given_type_id),
								format_type_be(expected_type_id)),
						 errhint("You will need to rewrite or cast the expression.")));
2728 2729 2730 2731 2732 2733 2734 2735 2736

			lfirst(l) = expr;
			i++;
		}
	}

	return result;
}

2737
/* exported so planner can check again after rewriting, query pullup, etc */
2738 2739 2740
void
CheckSelectForUpdate(Query *qry)
{
2741
	if (qry->setOperations)
2742 2743 2744
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT")));
2745
	if (qry->distinctClause != NIL)
2746 2747
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
Bruce Momjian's avatar
Bruce Momjian committed
2748
		errmsg("SELECT FOR UPDATE is not allowed with DISTINCT clause")));
2749
	if (qry->groupClause != NIL)
2750 2751
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
Bruce Momjian's avatar
Bruce Momjian committed
2752
		errmsg("SELECT FOR UPDATE is not allowed with GROUP BY clause")));
2753 2754 2755 2756
	if (qry->havingQual != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
		errmsg("SELECT FOR UPDATE is not allowed with HAVING clause")));
2757
	if (qry->hasAggs)
2758 2759
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
Bruce Momjian's avatar
Bruce Momjian committed
2760
				 errmsg("SELECT FOR UPDATE is not allowed with aggregate functions")));
2761 2762
}

Tom Lane's avatar
Tom Lane committed
2763 2764 2765 2766 2767 2768
/*
 * Convert FOR UPDATE name list into rowMarks list of integer relids
 *
 * NB: if you need to change this, see also markQueryForUpdate()
 * in rewriteHandler.c.
 */
2769 2770 2771
static void
transformForUpdate(Query *qry, List *forUpdate)
{
2772
	List	   *rowMarks = qry->rowMarks;
2773 2774
	ListCell   *l;
	ListCell   *rt;
2775 2776
	Index		i;

2777 2778
	CheckSelectForUpdate(qry);

2779
	if (linitial(forUpdate) == NULL)
2780
	{
Tom Lane's avatar
Tom Lane committed
2781
		/* all regular tables used in query */
2782 2783
		i = 0;
		foreach(rt, qry->rtable)
2784
		{
2785 2786 2787
			RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);

			++i;
Tom Lane's avatar
Tom Lane committed
2788
			switch (rte->rtekind)
2789
			{
Tom Lane's avatar
Tom Lane committed
2790
				case RTE_RELATION:
2791 2792
					if (!list_member_int(rowMarks, i))	/* avoid duplicates */
						rowMarks = lappend_int(rowMarks, i);
2793
					rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
Tom Lane's avatar
Tom Lane committed
2794 2795
					break;
				case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
2796

Tom Lane's avatar
Tom Lane committed
2797 2798 2799 2800
					/*
					 * FOR UPDATE of subquery is propagated to subquery's
					 * rels
					 */
2801
					transformForUpdate(rte->subquery, list_make1(NULL));
Tom Lane's avatar
Tom Lane committed
2802 2803 2804 2805
					break;
				default:
					/* ignore JOIN, SPECIAL, FUNCTION RTEs */
					break;
2806
			}
2807 2808
		}
	}
2809
	else
2810
	{
2811 2812
		/* just the named tables */
		foreach(l, forUpdate)
2813
		{
2814
			char	   *relname = strVal(lfirst(l));
2815 2816 2817

			i = 0;
			foreach(rt, qry->rtable)
2818
			{
2819
				RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2820

2821
				++i;
2822
				if (strcmp(rte->eref->aliasname, relname) == 0)
2823
				{
Tom Lane's avatar
Tom Lane committed
2824
					switch (rte->rtekind)
2825
					{
Tom Lane's avatar
Tom Lane committed
2826
						case RTE_RELATION:
Bruce Momjian's avatar
Bruce Momjian committed
2827
							if (!list_member_int(rowMarks, i))	/* avoid duplicates */
2828
								rowMarks = lappend_int(rowMarks, i);
2829
							rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
Tom Lane's avatar
Tom Lane committed
2830 2831
							break;
						case RTE_SUBQUERY:
Bruce Momjian's avatar
Bruce Momjian committed
2832

Tom Lane's avatar
Tom Lane committed
2833 2834 2835 2836
							/*
							 * FOR UPDATE of subquery is propagated to
							 * subquery's rels
							 */
2837
							transformForUpdate(rte->subquery, list_make1(NULL));
Tom Lane's avatar
Tom Lane committed
2838 2839 2840
							break;
						case RTE_JOIN:
							ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
2841 2842
								 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
								  errmsg("SELECT FOR UPDATE cannot be applied to a join")));
Tom Lane's avatar
Tom Lane committed
2843 2844 2845
							break;
						case RTE_SPECIAL:
							ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
2846 2847
								 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
								  errmsg("SELECT FOR UPDATE cannot be applied to NEW or OLD")));
Tom Lane's avatar
Tom Lane committed
2848 2849 2850
							break;
						case RTE_FUNCTION:
							ereport(ERROR,
Bruce Momjian's avatar
Bruce Momjian committed
2851 2852
								 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
								  errmsg("SELECT FOR UPDATE cannot be applied to a function")));
Tom Lane's avatar
Tom Lane committed
2853 2854 2855 2856 2857
							break;
						default:
							elog(ERROR, "unrecognized RTE type: %d",
								 (int) rte->rtekind);
							break;
2858
					}
Tom Lane's avatar
Tom Lane committed
2859
					break;		/* out of foreach loop */
2860 2861
				}
			}
2862
			if (rt == NULL)
2863 2864 2865 2866
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_TABLE),
						 errmsg("relation \"%s\" in FOR UPDATE clause not found in FROM clause",
								relname)));
2867 2868 2869
		}
	}

2870
	qry->rowMarks = rowMarks;
2871
}
Jan Wieck's avatar
Jan Wieck committed
2872 2873


2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
/*
 * Preprocess a list of column constraint clauses
 * to attach constraint attributes to their primary constraint nodes
 * and detect inconsistent/misplaced constraint attributes.
 *
 * NOTE: currently, attributes are only supported for FOREIGN KEY primary
 * constraints, but someday they ought to be supported for other constraints.
 */
static void
transformConstraintAttrs(List *constraintList)
{
	Node	   *lastprimarynode = NULL;
	bool		saw_deferrability = false;
	bool		saw_initially = false;
2888
	ListCell   *clist;
2889 2890 2891

	foreach(clist, constraintList)
	{
2892
		Node	   *node = lfirst(clist);
2893

2894
		if (!IsA(node, Constraint))
2895 2896 2897 2898 2899 2900 2901 2902
		{
			lastprimarynode = node;
			/* reset flags for new primary node */
			saw_deferrability = false;
			saw_initially = false;
		}
		else
		{
2903
			Constraint *con = (Constraint *) node;
2904 2905 2906 2907 2908

			switch (con->contype)
			{
				case CONSTR_ATTR_DEFERRABLE:
					if (lastprimarynode == NULL ||
2909
						!IsA(lastprimarynode, FkConstraint))
2910 2911 2912
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
								 errmsg("misplaced DEFERRABLE clause")));
2913
					if (saw_deferrability)
2914 2915 2916
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
								 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2917 2918 2919 2920 2921
					saw_deferrability = true;
					((FkConstraint *) lastprimarynode)->deferrable = true;
					break;
				case CONSTR_ATTR_NOT_DEFERRABLE:
					if (lastprimarynode == NULL ||
2922
						!IsA(lastprimarynode, FkConstraint))
2923 2924
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2925
							 errmsg("misplaced NOT DEFERRABLE clause")));
2926
					if (saw_deferrability)
2927 2928 2929
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
								 errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
2930 2931 2932 2933
					saw_deferrability = true;
					((FkConstraint *) lastprimarynode)->deferrable = false;
					if (saw_initially &&
						((FkConstraint *) lastprimarynode)->initdeferred)
2934 2935
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
2936
								 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2937 2938 2939
					break;
				case CONSTR_ATTR_DEFERRED:
					if (lastprimarynode == NULL ||
2940
						!IsA(lastprimarynode, FkConstraint))
2941 2942
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2943
						 errmsg("misplaced INITIALLY DEFERRED clause")));
2944
					if (saw_initially)
2945 2946 2947
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
								 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2948 2949
					saw_initially = true;
					((FkConstraint *) lastprimarynode)->initdeferred = true;
2950 2951 2952 2953 2954 2955

					/*
					 * If only INITIALLY DEFERRED appears, assume
					 * DEFERRABLE
					 */
					if (!saw_deferrability)
2956
						((FkConstraint *) lastprimarynode)->deferrable = true;
2957
					else if (!((FkConstraint *) lastprimarynode)->deferrable)
2958 2959
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
2960
								 errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
2961 2962 2963
					break;
				case CONSTR_ATTR_IMMEDIATE:
					if (lastprimarynode == NULL ||
2964
						!IsA(lastprimarynode, FkConstraint))
2965 2966
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
Bruce Momjian's avatar
Bruce Momjian committed
2967
						errmsg("misplaced INITIALLY IMMEDIATE clause")));
2968
					if (saw_initially)
2969 2970 2971
						ereport(ERROR,
								(errcode(ERRCODE_SYNTAX_ERROR),
								 errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986
					saw_initially = true;
					((FkConstraint *) lastprimarynode)->initdeferred = false;
					break;
				default:
					/* Otherwise it's not an attribute */
					lastprimarynode = node;
					/* reset flags for new primary node */
					saw_deferrability = false;
					saw_initially = false;
					break;
			}
		}
	}
}

2987 2988 2989 2990
/* Build a FromExpr node */
static FromExpr *
makeFromExpr(List *fromlist, Node *quals)
{
2991
	FromExpr   *f = makeNode(FromExpr);
2992 2993 2994 2995 2996 2997

	f->fromlist = fromlist;
	f->quals = quals;
	return f;
}

2998 2999 3000 3001 3002 3003
/*
 * Special handling of type definition for a column
 */
static void
transformColumnType(ParseState *pstate, ColumnDef *column)
{
3004
	/*
3005
	 * All we really need to do here is verify that the type is valid.
3006
	 */
3007
	Type		ctype = typenameType(column->typename);
3008 3009

	ReleaseSysCache(ctype);
3010
}
3011

3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
static void
setSchemaName(char *context_schema, char **stmt_schema_name)
{
	if (*stmt_schema_name == NULL)
		*stmt_schema_name = context_schema;
	else if (strcmp(context_schema, *stmt_schema_name) != 0)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
				 errmsg("CREATE specifies a schema (%s) "
						"different from the one being created (%s)",
						*stmt_schema_name, context_schema)));
}

3025 3026 3027 3028 3029
/*
 * analyzeCreateSchemaStmt -
 *	  analyzes the "create schema" statement
 *
 * Split the schema element list into individual commands and place
3030 3031 3032 3033
 * them in the result list in an order such that there are no forward
 * references (e.g. GRANT to a table created later in the list). Note
 * that the logic we use for determining forward references is
 * presently quite incomplete.
3034 3035 3036 3037 3038 3039 3040 3041 3042
 *
 * SQL92 also allows constraints to make forward references, so thumb through
 * the table columns and move forward references to a posterior alter-table
 * command.
 *
 * The result is a list of parse nodes that still need to be analyzed ---
 * but we can't analyze the later commands until we've executed the earlier
 * ones, because of possible inter-object references.
 *
3043
 * Note: Called from commands/schemacmds.c
3044 3045 3046 3047 3048 3049
 */
List *
analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
{
	CreateSchemaStmtContext cxt;
	List	   *result;
3050
	ListCell   *elements;
3051 3052 3053 3054

	cxt.stmtType = "CREATE SCHEMA";
	cxt.schemaname = stmt->schemaname;
	cxt.authid = stmt->authid;
3055
	cxt.sequences = NIL;
3056 3057
	cxt.tables = NIL;
	cxt.views = NIL;
3058
	cxt.indexes = NIL;
3059
	cxt.grants = NIL;
3060
	cxt.triggers = NIL;
3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075
	cxt.fwconstraints = NIL;
	cxt.alters = NIL;
	cxt.blist = NIL;
	cxt.alist = NIL;

	/*
	 * Run through each schema element in the schema element list.
	 * Separate statements by type, and do preliminary analysis.
	 */
	foreach(elements, stmt->schemaElts)
	{
		Node	   *element = lfirst(elements);

		switch (nodeTag(element))
		{
3076 3077 3078 3079 3080 3081 3082 3083 3084
			case T_CreateSeqStmt:
				{
					CreateSeqStmt *elp = (CreateSeqStmt *) element;

					setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
					cxt.sequences = lappend(cxt.sequences, element);
				}
				break;

3085 3086 3087 3088
			case T_CreateStmt:
				{
					CreateStmt *elp = (CreateStmt *) element;

3089
					setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3090 3091 3092 3093 3094 3095 3096 3097 3098 3099

					/*
					 * XXX todo: deal with constraints
					 */
					cxt.tables = lappend(cxt.tables, element);
				}
				break;

			case T_ViewStmt:
				{
Bruce Momjian's avatar
Bruce Momjian committed
3100
					ViewStmt   *elp = (ViewStmt *) element;
3101

3102
					setSchemaName(cxt.schemaname, &elp->view->schemaname);
3103 3104 3105 3106 3107 3108 3109 3110

					/*
					 * XXX todo: deal with references between views
					 */
					cxt.views = lappend(cxt.views, element);
				}
				break;

3111 3112
			case T_IndexStmt:
				{
Bruce Momjian's avatar
Bruce Momjian committed
3113
					IndexStmt  *elp = (IndexStmt *) element;
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128

					setSchemaName(cxt.schemaname, &elp->relation->schemaname);
					cxt.indexes = lappend(cxt.indexes, element);
				}
				break;

			case T_CreateTrigStmt:
				{
					CreateTrigStmt *elp = (CreateTrigStmt *) element;

					setSchemaName(cxt.schemaname, &elp->relation->schemaname);
					cxt.triggers = lappend(cxt.triggers, element);
				}
				break;

3129 3130 3131 3132 3133
			case T_GrantStmt:
				cxt.grants = lappend(cxt.grants, element);
				break;

			default:
3134 3135
				elog(ERROR, "unrecognized node type: %d",
					 (int) nodeTag(element));
3136 3137 3138
		}
	}

3139
	result = NIL;
3140 3141 3142 3143 3144 3145
	result = list_concat(result, cxt.sequences);
	result = list_concat(result, cxt.tables);
	result = list_concat(result, cxt.views);
	result = list_concat(result, cxt.indexes);
	result = list_concat(result, cxt.triggers);
	result = list_concat(result, cxt.grants);
3146 3147 3148

	return result;
}
3149 3150 3151 3152 3153 3154 3155 3156 3157

/*
 * Traverse a fully-analyzed tree to verify that parameter symbols
 * match their types.  We need this because some Params might still
 * be UNKNOWN, if there wasn't anything to force their coercion,
 * and yet other instances seen later might have gotten coerced.
 */
static bool
check_parameter_resolution_walker(Node *node,
3158
							 check_parameter_resolution_context *context)
3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169
{
	if (node == NULL)
		return false;
	if (IsA(node, Param))
	{
		Param	   *param = (Param *) node;

		if (param->paramkind == PARAM_NUM)
		{
			int			paramno = param->paramid;

Bruce Momjian's avatar
Bruce Momjian committed
3170
			if (paramno <= 0 || /* shouldn't happen, but... */
3171
				paramno > context->numParams)
3172 3173 3174
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_PARAMETER),
						 errmsg("there is no parameter $%d", paramno)));
3175

Bruce Momjian's avatar
Bruce Momjian committed
3176
			if (param->paramtype != context->paramTypes[paramno - 1])
3177 3178
				ereport(ERROR,
						(errcode(ERRCODE_AMBIGUOUS_PARAMETER),
Bruce Momjian's avatar
Bruce Momjian committed
3179 3180
				 errmsg("could not determine data type of parameter $%d",
						paramno)));
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
		}
		return false;
	}
	if (IsA(node, Query))
	{
		/* Recurse into RTE subquery or not-yet-planned sublink subquery */
		return query_tree_walker((Query *) node,
								 check_parameter_resolution_walker,
								 (void *) context, 0);
	}
	return expression_tree_walker(node, check_parameter_resolution_walker,
								  (void *) context);
}