rewriteHandler.c 50.8 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * rewriteHandler.c
4
 *
B
Add:  
Bruce Momjian 已提交
5 6
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
7 8 9
 *
 *
 * IDENTIFICATION
10
 *	  $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.80 2000/09/12 21:07:03 tgl Exp $
11 12 13 14 15
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

B
Bruce Momjian 已提交
16
#include "access/heapam.h"
17
#include "catalog/pg_operator.h"
18
#include "catalog/pg_type.h"
B
Bruce Momjian 已提交
19
#include "miscadmin.h"
20
#include "nodes/makefuncs.h"
B
Bruce Momjian 已提交
21 22
#include "optimizer/clauses.h"
#include "optimizer/prep.h"
23
#include "optimizer/var.h"
B
Bruce Momjian 已提交
24
#include "parser/analyze.h"
25 26
#include "parser/parse_expr.h"
#include "parser/parse_oper.h"
B
Bruce Momjian 已提交
27 28
#include "parser/parse_target.h"
#include "parser/parsetree.h"
B
Bruce Momjian 已提交
29
#include "parser/parse_type.h"
B
Bruce Momjian 已提交
30 31 32 33
#include "rewrite/locks.h"
#include "rewrite/rewriteManip.h"
#include "utils/acl.h"
#include "utils/lsyscache.h"
34 35


36 37 38 39 40 41 42 43 44 45 46 47 48
extern void CheckSelectForUpdate(Query *rule_action);	/* in analyze.c */


/* macros borrowed from expression_tree_mutator */

#define FLATCOPY(newnode, node, nodetype)  \
	( (newnode) = makeNode(nodetype), \
	  memcpy((newnode), (node), sizeof(nodetype)) )

#define MUTATE(newfield, oldfield, fieldtype, mutator, context)  \
		( (newfield) = (fieldtype) mutator((Node *) (oldfield), (context)) )


49 50 51 52 53
static RewriteInfo *gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
				  int rt_index,
				  CmdType event,
54 55 56 57 58
				  bool instead_flag);
static List *adjustJoinTree(Query *parsetree, int rt_index, bool *found);
static bool modifyAggrefChangeVarnodes(Query *query,
									   int rt_index, int new_index,
									   int sublevels_up, int new_sublevels_up);
59
static Node *modifyAggrefDropQual(Node *node, Node *targetNode);
60
static SubLink *modifyAggrefMakeSublink(Aggref *aggref, Query *parsetree);
61
static Node *modifyAggrefQual(Node *node, Query *parsetree);
62
static Query *fireRIRrules(Query *parsetree);
63 64
static Query *Except_Intersect_Rewrite(Query *parsetree);
static void check_targetlists_are_compatible(List *prev_target,
65
								 List *current_target);
66 67
static void create_intersect_list(Node *ptr, List **intersect_list);
static Node *intersect_tree_analyze(Node *tree, Node *first_select,
68
					   Node *parsetree);
69 70 71

/*
 * gatherRewriteMeta -
72 73 74
 *	  Gather meta information about parsetree, and rule. Fix rule body
 *	  and qualifier so that they can be mixed with the parsetree and
 *	  maintain semantic validity
75 76
 */
static RewriteInfo *
77 78 79
gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
80 81
				  int rt_index,
				  CmdType event,
82
				  bool instead_flag)
83
{
84 85
	RewriteInfo *info;
	int			rt_length;
86 87 88 89

	info = (RewriteInfo *) palloc(sizeof(RewriteInfo));
	info->rt_index = rt_index;
	info->event = event;
90
	info->instead_flag = instead_flag;
91 92 93 94 95 96 97 98 99
	info->rule_action = (Query *) copyObject(rule_action);
	info->rule_qual = (Node *) copyObject(rule_qual);
	if (info->rule_action == NULL)
		info->nothing = TRUE;
	else
	{
		info->nothing = FALSE;
		info->action = info->rule_action->commandType;
		info->current_varno = rt_index;
100
		rt_length = length(parsetree->rtable);
101

102
		/* Adjust rule action and qual to offset its varnos */
103
		info->new_varno = PRS2_NEW_VARNO + rt_length;
104
		OffsetVarNodes((Node *) info->rule_action, rt_length, 0);
B
Bruce Momjian 已提交
105
		OffsetVarNodes(info->rule_qual, rt_length, 0);
106 107
		/* but its references to *OLD* should point at original rt_index */
		ChangeVarNodes((Node *) info->rule_action,
108
					   PRS2_OLD_VARNO + rt_length, rt_index, 0);
109
		ChangeVarNodes(info->rule_qual,
110
					   PRS2_OLD_VARNO + rt_length, rt_index, 0);
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
		/*
		 * We want the main parsetree's rtable to end up as the concatenation
		 * of its original contents plus those of all the relevant rule
		 * actions.  Also store same into all the rule_action rtables.
		 * Some of the entries may be unused after we finish rewriting, but
		 * if we tried to clean those out we'd have a much harder job to
		 * adjust RT indexes in the query's Vars.  It's OK to have unused
		 * RT entries, since planner will ignore them.
		 *
		 * NOTE KLUGY HACK: we assume the parsetree rtable had at least one
		 * entry to begin with (OK enough, else where'd the rule come from?).
		 * Because of this, if multiple rules nconc() their rtable additions
		 * onto parsetree->rtable, they'll all see the same rtable because
		 * they all have the same list head pointer.
		 */
		parsetree->rtable = nconc(parsetree->rtable,
								  info->rule_action->rtable);
		info->rule_action->rtable = parsetree->rtable;

		/*
		 * Each rule action's jointree should be the main parsetree's jointree
		 * plus that rule's jointree, but *without* the original rtindex
		 * that we're replacing (if present, which it won't be for INSERT).
		 * Note that if the rule refers to OLD, its jointree will add back
		 * a reference to rt_index.
		 *
		 * XXX This might be wrong for subselect-in-FROM?
		 */
		{
			bool	found;
			List   *newjointree = adjustJoinTree(parsetree, rt_index, &found);

			info->rule_action->jointree = nconc(newjointree,
												info->rule_action->jointree);
		}

148 149 150 151 152 153 154
		/*
		 * bug here about replace CURRENT  -- sort of replace current is
		 * deprecated now so this code shouldn't really need to be so
		 * clutzy but.....
		 */
		if (info->action != CMD_SELECT)
		{						/* i.e update XXXXX */
155 156
			int			result_reln;
			int			new_result_reln;
157 158 159 160

			result_reln = info->rule_action->resultRelation;
			switch (result_reln)
			{
161
				case PRS2_OLD_VARNO:
162 163 164 165 166 167
					new_result_reln = rt_index;
					break;
				case PRS2_NEW_VARNO:	/* XXX */
				default:
					new_result_reln = result_reln + rt_length;
					break;
168 169 170 171 172
			}
			info->rule_action->resultRelation = new_result_reln;
		}
	}
	return info;
173 174
}

175
/*
176 177 178 179
 * Copy the query's jointree list, and attempt to remove any occurrence
 * of the given rt_index as a top-level join item (we do not look for it
 * within JoinExprs).  Returns modified jointree list --- original list
 * is not changed.  *found is set to indicate if we found the rt_index.
180
 */
181 182
static List *
adjustJoinTree(Query *parsetree, int rt_index, bool *found)
183
{
184 185
	List	   *newjointree = listCopy(parsetree->jointree);
	List	   *jjt;
186

187 188
	*found = false;
	foreach(jjt, newjointree)
B
Bruce Momjian 已提交
189
	{
190
		RangeTblRef *rtr = lfirst(jjt);
191

192 193 194 195 196 197
		if (IsA(rtr, RangeTblRef) && rtr->rtindex == rt_index)
		{
			newjointree = lremove(rtr, newjointree);
			*found = true;
			break;
		}
198
	}
199
	return newjointree;
200
}
201

202

203
/*
B
Bruce Momjian 已提交
204
 * modifyAggrefChangeVarnodes -
205
 *	Change the var nodes in a sublink created for an aggregate column
206 207
 *	used in the qualification to point to the correct local RTE.
 *
208 209 210 211
 * XXX if we still need this after redoing querytree design, it should
 * be combined with ChangeVarNodes, which is the same thing except for
 * not having the option to adjust the vars' varlevelsup.
 *
212
 * NOTE: although this has the form of a walker, we cheat and modify the
213
 * Var nodes in-place.	The given expression tree should have been copied
214
 * earlier to ensure that no unwanted side-effects occur!
215 216
 */

217 218
typedef struct
{
219 220 221
	int			rt_index;
	int			new_index;
	int			sublevels_up;
222
	int			new_sublevels_up;
223
} modifyAggrefChangeVarnodes_context;
224

225 226
static bool
modifyAggrefChangeVarnodes_walker(Node *node,
227
							 modifyAggrefChangeVarnodes_context *context)
228 229 230 231
{
	if (node == NULL)
		return false;
	if (IsA(node, Var))
B
Bruce Momjian 已提交
232
	{
233
		Var		   *var = (Var *) node;
234

235 236 237 238 239
		if (var->varlevelsup == context->sublevels_up &&
			var->varno == context->rt_index)
		{
			var->varno = context->new_index;
			var->varnoold = context->new_index;
240
			var->varlevelsup = context->new_sublevels_up;
241 242 243 244 245
		}
		return false;
	}
	if (IsA(node, Query))
	{
246 247 248 249 250 251 252 253 254 255 256
		/* Recurse into subselects */
		bool		result;

		context->sublevels_up++;
		context->new_sublevels_up++;
		result = query_tree_walker((Query *) node,
								   modifyAggrefChangeVarnodes_walker,
								   (void *) context);
		context->sublevels_up--;
		context->new_sublevels_up--;
		return result;
257 258 259 260
	}
	return expression_tree_walker(node, modifyAggrefChangeVarnodes_walker,
								  (void *) context);
}
261

262
static bool
263
modifyAggrefChangeVarnodes(Query *query, int rt_index, int new_index,
264
						   int sublevels_up, int new_sublevels_up)
265 266
{
	modifyAggrefChangeVarnodes_context context;
267

268 269 270
	context.rt_index = rt_index;
	context.new_index = new_index;
	context.sublevels_up = sublevels_up;
271
	context.new_sublevels_up = new_sublevels_up;
272 273
	return query_tree_walker(query, modifyAggrefChangeVarnodes_walker,
							 (void *) &context);
274 275 276 277
}


/*
B
Bruce Momjian 已提交
278
 * modifyAggrefDropQual -
279 280
 *	remove the pure aggref clause from a qualification
 *
281 282 283
 * targetNode is an Aggref node somewhere within the given expression tree.
 * Find the boolean operator that's presumably somewhere above it, and replace
 * that whole operator expression with a constant TRUE.  (This is NOT really
284
 * quite the right thing, but it handles simple cases.	This whole set of
285 286 287
 * Aggref-in-qual routines needs to be thrown away when we can do subselects
 * in FROM.)
 *
288 289 290 291 292 293
 * The return tree is a modified copy of the given tree; the given tree
 * is not altered.
 *
 * Note: we don't recurse into subselects looking for targetNode; that's
 * not necessary in the current usage, since in fact targetNode will be
 * within the same select level as the given toplevel node.
294
 */
295 296
static Node *
modifyAggrefDropQual(Node *node, Node *targetNode)
297 298
{
	if (node == NULL)
299 300
		return NULL;
	if (node == targetNode)
301 302 303 304 305
	{
		/* Oops, it's not inside an Expr we can rearrange... */
		elog(ERROR, "Cannot handle aggregate function inserted at this place in WHERE clause");
	}
	if (IsA(node, Expr))
B
Bruce Momjian 已提交
306
	{
307
		Expr	   *expr = (Expr *) node;
308
		List	   *i;
309

310 311 312 313 314 315 316 317 318 319 320 321 322
		foreach(i, expr->args)
		{
			if (((Node *) lfirst(i)) == targetNode)
			{
				/* Found the parent expression containing the Aggref */
				if (expr->typeOid != BOOLOID)
					elog(ERROR,
						 "aggregate function in qual must be argument of boolean operator");
				return (Node *) makeConst(BOOLOID, 1, (Datum) true,
										  false, true, false, false);
			}
		}
		/* else this isn't the expr we want, keep going */
323
	}
324 325
	return expression_tree_mutator(node, modifyAggrefDropQual,
								   (void *) targetNode);
326 327 328
}

/*
B
Bruce Momjian 已提交
329
 * modifyAggrefMakeSublink -
330 331 332 333
 *	Create a sublink node for a qualification expression that
 *	uses an aggregate column of a view
 */
static SubLink *
334
modifyAggrefMakeSublink(Aggref *aggref, Query *parsetree)
335
{
336
	List	   *aggVarNos;
337

338
	/* rte points to old structure: */
339
	RangeTblEntry *rte;
340

341 342 343
	/* these point to newly-created structures: */
	Query	   *subquery;
	SubLink    *sublink;
B
Bruce Momjian 已提交
344 345
	TargetEntry *tle;
	Resdom	   *resdom;
346
	RangeTblRef *rtr;
347

348 349 350 351
	aggVarNos = pull_varnos(aggref->target);
	if (length(aggVarNos) != 1)
		elog(ERROR, "rewrite: aggregates of views only allowed on single tables for now");
	rte = rt_fetch(lfirsti(aggVarNos), parsetree->rtable);
352

B
Bruce Momjian 已提交
353 354
	resdom = makeNode(Resdom);
	resdom->resno = 1;
355
	resdom->restype = aggref->aggtype;
356 357
	resdom->restypmod = -1;
	resdom->resname = pstrdup("<noname>");
B
Bruce Momjian 已提交
358
	resdom->reskey = 0;
359
	resdom->reskeyop = 0;
B
Bruce Momjian 已提交
360
	resdom->resjunk = false;
361

362
	tle = makeNode(TargetEntry);
B
Bruce Momjian 已提交
363
	tle->resdom = resdom;
364
	tle->expr = copyObject(aggref);		/* make a modifiable copy! */
365 366

	subquery = makeNode(Query);
367 368

	sublink = makeNode(SubLink);
B
Bruce Momjian 已提交
369
	sublink->subLinkType = EXPR_SUBLINK;
370
	sublink->useor = false;
371 372
	sublink->lefthand = NIL;
	sublink->oper = NIL;
B
Bruce Momjian 已提交
373 374 375 376 377 378 379 380 381
	sublink->subselect = (Node *) subquery;

	subquery->commandType = CMD_SELECT;
	subquery->utilityStmt = NULL;
	subquery->resultRelation = 0;
	subquery->into = NULL;
	subquery->isPortal = FALSE;
	subquery->isBinary = FALSE;
	subquery->isTemp = FALSE;
382
	subquery->unionall = FALSE;
383 384
	subquery->distinctClause = NIL;
	subquery->sortClause = NIL;
385
	subquery->rtable = lcons(copyObject(rte), NIL);
386 387 388
	rtr = makeNode(RangeTblRef);
	rtr->rtindex = 1;
	subquery->jointree = lcons(rtr, NIL);
389 390
	subquery->targetList = lcons(tle, NIL);
	subquery->qual = modifyAggrefDropQual((Node *) parsetree->qual,
391
										  (Node *) aggref);
392

393
	/*
394 395 396
	 * If there are still aggs in the subselect's qual, give up. Recursing
	 * would be a bad idea --- we'd likely produce an infinite recursion.
	 * This whole technique is a crock, really...
397
	 */
398
	if (checkExprHasAggs(subquery->qual))
399
		elog(ERROR, "Cannot handle multiple aggregate functions in WHERE clause");
400 401 402
	subquery->groupClause = NIL;
	subquery->havingQual = NULL;
	subquery->hasAggs = TRUE;
403
	subquery->hasSubLinks = checkExprHasSubLink(subquery->qual);
404
	subquery->unionClause = NULL;
405

406
	/* Increment all varlevelsup fields in the new subquery */
407
	IncrementVarSublevelsUp((Node *) subquery, 1, 0);
408

409 410
	/*
	 * Replace references to the target table with correct local varno, 1.
411 412
	 * Note that because of previous line, these references have
	 * varlevelsup = 1, which must be changed to 0.
413
	 */
414
	modifyAggrefChangeVarnodes(subquery,
415 416
							   lfirsti(aggVarNos), 1,
							   1, 0);
417

418 419
	return sublink;
}
420 421


422 423 424 425 426 427 428 429 430 431 432 433 434 435
/*
 * modifyAggrefQual -
 *	Search for qualification expressions that contain aggregate
 *	functions and substitute them by sublinks. These expressions
 *	originally come from qualifications that use aggregate columns
 *	of a view.
 *
 *	The return value is a modified copy of the given expression tree.
 */
static Node *
modifyAggrefQual(Node *node, Query *parsetree)
{
	if (node == NULL)
		return NULL;
436 437
	if (IsA(node, Aggref))
	{
438 439 440 441
		SubLink    *sub = modifyAggrefMakeSublink((Aggref *) node, parsetree);

		parsetree->hasSubLinks = true;
		return (Node *) sub;
442
	}
443

444 445 446
	/*
	 * Otherwise, fall through and copy the expr normally.
	 *
447 448
	 * We do NOT recurse into subselects in this routine.  It's sufficient to
	 * get rid of aggregates that are in the qual expression proper.
449 450 451
	 */
	return expression_tree_mutator(node, modifyAggrefQual,
								   (void *) parsetree);
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
}


static Node *
FindMatchingTLEntry(List *tlist, char *e_attname)
{
	List	   *i;

	foreach(i, tlist)
	{
		TargetEntry *tle = lfirst(i);
		char	   *resname;

		resname = tle->resdom->resname;
		if (!strcmp(e_attname, resname))
			return (tle->expr);
	}
	return NULL;
}


static Node *
make_null(Oid type)
{
	Const	   *c = makeNode(Const);

	c->consttype = type;
	c->constlen = get_typlen(type);
	c->constvalue = PointerGetDatum(NULL);
	c->constisnull = true;
	c->constbyval = get_typbyval(type);
	return (Node *) c;
}


487 488 489 490
/*
 * apply_RIR_view
 *	Replace Vars matching a given RT index with copies of TL expressions.
 */
491

492 493 494 495 496 497 498
typedef struct
{
	int			rt_index;
	int			sublevels_up;
	RangeTblEntry *rte;
	List	   *tlist;
	int		   *modified;
499
} apply_RIR_view_context;
500

501 502 503 504 505 506 507 508 509
static Node *
apply_RIR_view_mutator(Node *node,
					   apply_RIR_view_context *context)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;
510

511 512 513 514
		if (var->varlevelsup == context->sublevels_up &&
			var->varno == context->rt_index)
		{
			Node	   *expr;
515

516 517 518 519
			if (var->varattno < 0)
				elog(ERROR, "system column %s not available - %s is a view",
					 get_attname(context->rte->relid, var->varattno),
					 context->rte->relname);
520

521 522 523 524
			expr = FindMatchingTLEntry(context->tlist,
									   get_attname(context->rte->relid,
												   var->varattno));
			if (expr == NULL)
525
			{
526 527
				/* XXX shouldn't this be an error condition? */
				return make_null(var->vartype);
528 529
			}

530
			/* Make a copy of the tlist item to return */
531
			expr = copyObject(expr);
532
			/* Adjust varlevelsup if tlist item is from higher query level */
533
			if (var->varlevelsup > 0)
534 535
				IncrementVarSublevelsUp(expr, var->varlevelsup, 0);

536 537 538 539 540
			*(context->modified) = true;
			return (Node *) expr;
		}
		/* otherwise fall through to copy the var normally */
	}
541

542 543 544 545 546 547
	/*
	 * Since expression_tree_mutator won't touch subselects, we have to
	 * handle them specially.
	 */
	if (IsA(node, SubLink))
	{
548 549
		SubLink    *sublink = (SubLink *) node;
		SubLink    *newnode;
550 551 552 553 554 555 556 557 558 559 560 561

		FLATCOPY(newnode, sublink, SubLink);
		MUTATE(newnode->lefthand, sublink->lefthand, List *,
			   apply_RIR_view_mutator, context);
		context->sublevels_up++;
		MUTATE(newnode->subselect, sublink->subselect, Node *,
			   apply_RIR_view_mutator, context);
		context->sublevels_up--;
		return (Node *) newnode;
	}
	if (IsA(node, Query))
	{
562 563
		Query	   *query = (Query *) node;
		Query	   *newnode;
564 565 566 567 568 569 570 571

		FLATCOPY(newnode, query, Query);
		MUTATE(newnode->targetList, query->targetList, List *,
			   apply_RIR_view_mutator, context);
		MUTATE(newnode->qual, query->qual, Node *,
			   apply_RIR_view_mutator, context);
		MUTATE(newnode->havingQual, query->havingQual, Node *,
			   apply_RIR_view_mutator, context);
572 573
		MUTATE(newnode->jointree, query->jointree, List *,
			   apply_RIR_view_mutator, context);
574 575 576 577 578
		return (Node *) newnode;
	}
	return expression_tree_mutator(node, apply_RIR_view_mutator,
								   (void *) context);
}
579

580 581 582 583
static Node *
apply_RIR_view(Node *node, int rt_index, RangeTblEntry *rte, List *tlist,
			   int *modified, int sublevels_up)
{
584
	apply_RIR_view_context context;
585

586 587 588 589 590
	context.rt_index = rt_index;
	context.sublevels_up = sublevels_up;
	context.rte = rte;
	context.tlist = tlist;
	context.modified = modified;
591

592
	return apply_RIR_view_mutator(node, &context);
593 594 595
}


596
static Query *
597 598 599 600 601
ApplyRetrieveRule(Query *parsetree,
				  RewriteRule *rule,
				  int rt_index,
				  int relation_level,
				  Relation relation,
602
				  bool relIsUsed)
603 604 605 606
{
	Query	   *rule_action = NULL;
	Node	   *rule_qual;
	List	   *rtable,
607
			   *addedrtable,
608
			   *l;
609 610
	int			nothing,
				rt_length;
611
	int			modified = false;
612
	int			badsql = false;
613 614 615 616 617 618 619 620

	rule_qual = rule->qual;
	if (rule->actions)
	{
		if (length(rule->actions) > 1)	/* ??? because we don't handle
										 * rules with more than one
										 * action? -ay */

621
			return parsetree;
622 623 624 625 626 627 628
		rule_action = copyObject(lfirst(rule->actions));
		nothing = FALSE;
	}
	else
		nothing = TRUE;

	rtable = copyObject(parsetree->rtable);
629
	rt_length = length(rtable); /* original length, not counting rule */
630

631 632
	addedrtable = copyObject(rule_action->rtable);

633
	/*
634 635 636
	 * If the original rel wasn't in the join set (which'd be the case
	 * for the target of an INSERT, for example), none of its spawn is.
	 * If it was, then the spawn has to be added to the join set.
637
	 */
638
	if (relIsUsed)
639
	{
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
		/*
		 * QUICK HACK: this all needs to be replaced, but for now, find
		 * the original rel in the jointree, remove it, and add the rule
		 * action's jointree.  This will not work for views referenced
		 * in JoinExprs!!
		 *
		 * Note: it is possible that the old rel is referenced in the query
		 * but isn't present in the jointree; this should only happen for
		 * *OLD* and *NEW*.  We must not fail if so, but add the rule's
		 * jointree anyway.  (This is a major crock ... should fix rule
		 * representation ...)
		 */
		bool	found;
		List   *newjointree = adjustJoinTree(parsetree, rt_index, &found);
		List   *addedjointree = (List *) copyObject(rule_action->jointree);

		if (!found)
			elog(DEBUG, "ApplyRetrieveRule: can't find old rel %s (%d) in jointree",
				 rt_fetch(rt_index, rtable)->eref->relname, rt_index);
		OffsetVarNodes((Node *) addedjointree, rt_length, 0);
		newjointree = nconc(newjointree, addedjointree);
		parsetree->jointree = newjointree;
662 663
	}

664
	rtable = nconc(rtable, addedrtable);
665 666
	parsetree->rtable = rtable;

667
	/* FOR UPDATE of view... */
B
Bruce Momjian 已提交
668
	foreach(l, parsetree->rowMark)
669
	{
B
Bruce Momjian 已提交
670
		if (((RowMark *) lfirst(l))->rti == rt_index)
671 672
			break;
	}
B
Bruce Momjian 已提交
673
	if (l != NULL)				/* oh, hell -:) */
674
	{
B
Bruce Momjian 已提交
675
		RowMark    *newrm;
676 677 678
		Index		rti = 1;
		List	   *l2;

679
		CheckSelectForUpdate(rule_action);
B
Bruce Momjian 已提交
680 681 682 683 684 685

		/*
		 * We believe that rt_index is VIEW - nothing should be marked for
		 * VIEW, but ACL check must be done. As for real tables of VIEW -
		 * their rows must be marked, but we have to skip ACL check for
		 * them.
686
		 */
B
Bruce Momjian 已提交
687
		((RowMark *) lfirst(l))->info &= ~ROW_MARK_FOR_UPDATE;
688

B
Bruce Momjian 已提交
689
		foreach(l2, rule_action->rtable)
690
		{
B
Bruce Momjian 已提交
691

692
			/*
B
Bruce Momjian 已提交
693 694
			 * RTable of VIEW has two entries of VIEW itself - we use
			 * relid to skip them.
695
			 */
B
Bruce Momjian 已提交
696
			if (relation->rd_id != ((RangeTblEntry *) lfirst(l2))->relid)
697 698 699 700 701 702 703 704 705 706 707
			{
				newrm = makeNode(RowMark);
				newrm->rti = rti + rt_length;
				newrm->info = ROW_MARK_FOR_UPDATE;
				lnext(l) = lcons(newrm, lnext(l));
				l = lnext(l);
			}
			rti++;
		}
	}

708
	rule_action->rtable = rtable;
B
Bruce Momjian 已提交
709
	OffsetVarNodes((Node *) rule_qual, rt_length, 0);
B
Bruce Momjian 已提交
710
	OffsetVarNodes((Node *) rule_action, rt_length, 0);
711

B
Bruce Momjian 已提交
712
	ChangeVarNodes((Node *) rule_qual,
713
				   PRS2_OLD_VARNO + rt_length, rt_index, 0);
B
Bruce Momjian 已提交
714
	ChangeVarNodes((Node *) rule_action,
715
				   PRS2_OLD_VARNO + rt_length, rt_index, 0);
716 717 718

	if (relation_level)
	{
719
		RangeTblEntry *rte = rt_fetch(rt_index, rtable);
720 721 722 723

		parsetree = (Query *) apply_RIR_view((Node *) parsetree,
											 rt_index, rte,
											 rule_action->targetList,
724
											 &modified, 0);
725 726 727
		rule_action = (Query *) apply_RIR_view((Node *) rule_action,
											   rt_index, rte,
											   rule_action->targetList,
728 729 730 731 732
											   &modified, 0);
		/* always apply quals of relation-level rules, whether we found a
		 * var to substitute or not.
		 */
		modified = true;
733 734 735
	}
	else
	{
B
Bruce Momjian 已提交
736
		HandleRIRAttributeRule(parsetree, rtable, rule_action->targetList,
737 738
							   rt_index, rule->attrno, &modified, &badsql);
		/* quals will be inserted only if we found uses of the attribute */
B
Bruce Momjian 已提交
739
	}
740
	if (modified && !badsql)
B
Bruce Momjian 已提交
741 742 743 744 745 746 747
	{
		AddQual(parsetree, rule_action->qual);
		AddGroupClause(parsetree, rule_action->groupClause,
					   rule_action->targetList);
		AddHavingQual(parsetree, rule_action->havingQual);
		parsetree->hasAggs = (rule_action->hasAggs || parsetree->hasAggs);
		parsetree->hasSubLinks = (rule_action->hasSubLinks || parsetree->hasSubLinks);
748
	}
749 750

	return parsetree;
751 752 753
}


754 755 756 757 758
/*
 * fireRIRonSubselect -
 *	Apply fireRIRrules() to each subselect found in the given tree.
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
759
 * SubLink nodes in-place.	It is caller's responsibility to ensure that
760
 * no unwanted side-effects occur!
761 762 763 764
 *
 * This is unlike most of the other routines that recurse into subselects,
 * because we must take control at the SubLink node in order to replace
 * the SubLink's subselect link with the possibly-rewritten subquery.
765 766 767
 */
static bool
fireRIRonSubselect(Node *node, void *context)
768 769
{
	if (node == NULL)
770 771
		return false;
	if (IsA(node, SubLink))
B
Bruce Momjian 已提交
772
	{
773 774 775
		SubLink    *sub = (SubLink *) node;

		/* Do what we came for */
776 777
		sub->subselect = (Node *) fireRIRrules((Query *) (sub->subselect));
		/* Fall through to process lefthand args of SubLink */
778
	}
779 780 781 782
	/*
	 * Do NOT recurse into Query nodes, because fireRIRrules already
	 * processed subselects for us.
	 */
783 784
	return expression_tree_walker(node, fireRIRonSubselect,
								  (void *) context);
785 786 787 788 789 790 791 792 793 794
}


/*
 * fireRIRrules -
 *	Apply all RIR rules on each rangetable entry in a query
 */
static Query *
fireRIRrules(Query *parsetree)
{
B
Bruce Momjian 已提交
795 796
	int			rt_index;
	RangeTblEntry *rte;
797
	Relation	rel;
B
Bruce Momjian 已提交
798 799 800 801
	List	   *locks;
	RuleLock   *rules;
	RewriteRule *rule;
	RewriteRule RIRonly;
802
	bool		relIsUsed;
B
Bruce Momjian 已提交
803 804
	int			i;
	List	   *l;
805

806 807 808
	/*
	 * don't try to convert this into a foreach loop, because rtable list
	 * can get changed each time through...
809
	 */
810
	rt_index = 0;
B
Bruce Momjian 已提交
811 812
	while (rt_index < length(parsetree->rtable))
	{
813 814
		++rt_index;

815
		rte = rt_fetch(rt_index, parsetree->rtable);
816

817
		/*
818 819 820
		 * If the table is not referenced in the query, then we ignore it.
		 * This prevents infinite expansion loop due to new rtable entries
		 * inserted by expansion of a rule. A table is referenced if it is
821 822
		 * part of the join set (a source table), or is referenced by any
		 * Var nodes, or is the result table.
823
		 */
824 825 826
		relIsUsed = rangeTableEntry_used((Node *) parsetree, rt_index, 0);

		if (!relIsUsed && rt_index != parsetree->resultRelation)
827
			continue;
B
Bruce Momjian 已提交
828

829
		rel = heap_openr(rte->relname, AccessShareLock);
830 831
		rules = rel->rd_rules;
		if (rules == NULL)
B
Bruce Momjian 已提交
832
		{
833
			heap_close(rel, AccessShareLock);
834 835 836 837 838 839
			continue;
		}

		/*
		 * Collect the RIR rules that we must apply
		 */
840
		locks = NIL;
B
Bruce Momjian 已提交
841 842
		for (i = 0; i < rules->numLocks; i++)
		{
843 844 845
			rule = rules->rules[i];
			if (rule->event != CMD_SELECT)
				continue;
B
Bruce Momjian 已提交
846

847 848 849
			if (rule->attrno > 0)
			{
				/* per-attr rule; do we need it? */
850
				if (!attribute_used((Node *) parsetree, rt_index,
851
									rule->attrno, 0))
852 853
					continue;
			}
854 855 856 857 858 859 860 861 862 863 864 865

			locks = lappend(locks, rule);
		}

		/*
		 * Check permissions
		 */
		checkLockPerms(locks, parsetree, rt_index);

		/*
		 * Now apply them
		 */
B
Bruce Momjian 已提交
866 867
		foreach(l, locks)
		{
868 869
			rule = lfirst(l);

B
Bruce Momjian 已提交
870 871 872 873
			RIRonly.event = rule->event;
			RIRonly.attrno = rule->attrno;
			RIRonly.qual = rule->qual;
			RIRonly.actions = rule->actions;
874

875 876 877 878 879
			parsetree = ApplyRetrieveRule(parsetree,
										  &RIRonly,
										  rt_index,
										  RIRonly.attrno == -1,
										  rel,
880
										  relIsUsed);
881 882
		}

883
		heap_close(rel, AccessShareLock);
884 885
	}

886 887
	if (parsetree->hasAggs)
		parsetree->qual = modifyAggrefQual(parsetree->qual, parsetree);
888

889
	if (parsetree->hasSubLinks)
890
		query_tree_walker(parsetree, fireRIRonSubselect, NULL);
891

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
	return parsetree;
}


/*
 * idea is to fire regular rules first, then qualified instead
 * rules and unqualified instead rules last. Any lemming is counted for.
 */
static List *
orderRules(List *locks)
{
	List	   *regular = NIL;
	List	   *instead_rules = NIL;
	List	   *instead_qualified = NIL;
	List	   *i;

	foreach(i, locks)
	{
		RewriteRule *rule_lock = (RewriteRule *) lfirst(i);

		if (rule_lock->isInstead)
		{
			if (rule_lock->qual == NULL)
				instead_rules = lappend(instead_rules, rule_lock);
			else
				instead_qualified = lappend(instead_qualified, rule_lock);
918
		}
919 920
		else
			regular = lappend(regular, rule_lock);
921
	}
922 923
	regular = nconc(regular, instead_qualified);
	return nconc(regular, instead_rules);
924 925
}

926 927


928
static Query *
929 930 931
CopyAndAddQual(Query *parsetree,
			   List *actions,
			   Node *rule_qual,
932 933
			   int rt_index,
			   CmdType event)
934
{
935 936 937
	Query	   *new_tree = (Query *) copyObject(parsetree);
	Node	   *new_qual = NULL;
	Query	   *rule_action = NULL;
938 939 940 941 942 943 944

	if (actions)
		rule_action = lfirst(actions);
	if (rule_qual != NULL)
		new_qual = (Node *) copyObject(rule_qual);
	if (rule_action != NULL)
	{
945 946
		List	   *rtable;
		int			rt_length;
947
		List	   *jointree;
948 949 950

		rtable = new_tree->rtable;
		rt_length = length(rtable);
B
Bruce Momjian 已提交
951
		rtable = nconc(rtable, copyObject(rule_action->rtable));
952
		/* XXX above possibly wrong for subselect-in-FROM */
953
		new_tree->rtable = rtable;
B
Bruce Momjian 已提交
954
		OffsetVarNodes(new_qual, rt_length, 0);
955
		ChangeVarNodes(new_qual, PRS2_OLD_VARNO + rt_length, rt_index, 0);
956 957 958 959 960
		jointree = copyObject(rule_action->jointree);
		OffsetVarNodes((Node *) jointree, rt_length, 0);
		ChangeVarNodes((Node *) jointree, PRS2_OLD_VARNO + rt_length,
					   rt_index, 0);
		new_tree->jointree = nconc(new_tree->jointree, jointree);
961 962 963 964 965
	}
	/* XXX -- where current doesn't work for instead nothing.... yet */
	AddNotQual(new_tree, new_qual);

	return new_tree;
966 967 968
}


969

970
/*
971
 *	fireRules -
M
 
Marc G. Fournier 已提交
972 973 974 975 976
 *	   Iterate through rule locks applying rules.
 *	   All rules create their own parsetrees. Instead rules
 *	   with rule qualification save the original parsetree
 *	   and add their negated qualification to it. Real instead
 *	   rules finally throw away the original parsetree.
977
 *
M
 
Marc G. Fournier 已提交
978
 *	   remember: reality is for dead birds -- glass
979 980
 *
 */
981
static List *
982
fireRules(Query *parsetree,
983 984
		  int rt_index,
		  CmdType event,
985 986 987
		  bool *instead_flag,
		  List *locks,
		  List **qual_products)
988
{
989 990 991
	RewriteInfo *info;
	List	   *results = NIL;
	List	   *i;
992 993 994

	/* choose rule to fire from list of rules */
	if (locks == NIL)
995
		return NIL;
996

M
 
Marc G. Fournier 已提交
997
	locks = orderRules(locks);	/* real instead rules last */
998 999
	foreach(i, locks)
	{
1000
		RewriteRule *rule_lock = (RewriteRule *) lfirst(i);
1001
		Node	   *event_qual;
1002 1003
		List	   *actions;
		List	   *r;
1004

1005
		/*
1006 1007 1008 1009 1010 1011
		 * Instead rules change the resultRelation of the query. So the
		 * permission checks on the initial resultRelation would never be
		 * done (this is normally done in the executor deep down). So we
		 * must do it here. The result relations resulting from earlier
		 * rewrites are already checked against the rules eventrelation
		 * owner (during matchLocks) and have the skipAcl flag set.
1012
		 */
1013 1014 1015 1016
		if (rule_lock->isInstead &&
			parsetree->commandType != CMD_SELECT)
		{
			RangeTblEntry *rte;
1017 1018 1019
			int32		acl_rc;
			int32		reqperm;

1020 1021
			switch (parsetree->commandType)
			{
1022 1023 1024 1025 1026 1027 1028
				case CMD_INSERT:
					reqperm = ACL_AP;
					break;
				default:
					reqperm = ACL_WR;
					break;
			}
1029

1030
			rte = rt_fetch(parsetree->resultRelation, parsetree->rtable);
1031 1032
			if (!rte->skipAcl)
			{
1033
				acl_rc = pg_aclcheck(rte->relname,
1034
									 GetUserId(), reqperm);
1035 1036
				if (acl_rc != ACLCHECK_OK)
				{
1037
					elog(ERROR, "%s: %s",
1038 1039
						 rte->relname,
						 aclcheck_error_strings[acl_rc]);
1040 1041 1042 1043
				}
			}
		}

1044 1045 1046 1047
		/* multiple rule action time */
		*instead_flag = rule_lock->isInstead;
		event_qual = rule_lock->qual;
		actions = rule_lock->actions;
1048 1049 1050 1051
		if (event_qual != NULL && *instead_flag)
		{
			Query	   *qual_product;
			RewriteInfo qual_info;
M
 
Marc G. Fournier 已提交
1052 1053 1054 1055 1056

			/* ----------
			 * If there are instead rules with qualifications,
			 * the original query is still performed. But all
			 * the negated rule qualifications of the instead
B
Bruce Momjian 已提交
1057
			 * rules are added so it does its actions only
M
 
Marc G. Fournier 已提交
1058 1059 1060 1061 1062 1063 1064
			 * in cases where the rule quals of all instead
			 * rules are false. Think of it as the default
			 * action in a case. We save this in *qual_products
			 * so deepRewriteQuery() can add it to the query
			 * list after we mangled it up enough.
			 * ----------
			 */
1065
			if (*qual_products == NIL)
M
 
Marc G. Fournier 已提交
1066
				qual_product = parsetree;
1067 1068
			else
				qual_product = (Query *) nth(0, *qual_products);
M
 
Marc G. Fournier 已提交
1069

1070
			MemSet(&qual_info, 0, sizeof(qual_info));
1071
			qual_info.event = qual_product->commandType;
1072
			qual_info.current_varno = rt_index;
1073
			qual_info.new_varno = length(qual_product->rtable) + 2;
1074

1075 1076 1077 1078 1079 1080 1081
			qual_product = CopyAndAddQual(qual_product,
										  actions,
										  event_qual,
										  rt_index,
										  event);

			qual_info.rule_action = qual_product;
M
 
Marc G. Fournier 已提交
1082 1083 1084 1085 1086 1087 1088

			if (event == CMD_INSERT || event == CMD_UPDATE)
				FixNew(&qual_info, qual_product);

			*qual_products = lappend(NIL, qual_product);
		}

1089 1090
		foreach(r, actions)
		{
1091 1092
			Query	   *rule_action = lfirst(r);
			Node	   *rule_qual = copyObject(event_qual);
1093

M
 
Marc G. Fournier 已提交
1094 1095 1096
			if (rule_action->commandType == CMD_NOTHING)
				continue;

B
Bruce Momjian 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
			/*--------------------------------------------------
			 * We copy the qualifications of the parsetree
			 * to the action and vice versa. So force
			 * hasSubLinks if one of them has it.
			 *
			 * As of 6.4 only parsetree qualifications can
			 * have sublinks. If this changes, we must make
			 * this a node lookup at the end of rewriting.
			 *
			 * Jan
			 *--------------------------------------------------
			 */
			if (parsetree->hasSubLinks && !rule_action->hasSubLinks)
			{
				rule_action = copyObject(rule_action);
				rule_action->hasSubLinks = TRUE;
			}
			if (!parsetree->hasSubLinks && rule_action->hasSubLinks)
				parsetree->hasSubLinks = TRUE;

1117 1118 1119 1120 1121 1122 1123
			/*--------------------------------------------------
			 * Step 1:
			 *	  Rewrite current.attribute or current to tuple variable
			 *	  this appears to be done in parser?
			 *--------------------------------------------------
			 */
			info = gatherRewriteMeta(parsetree, rule_action, rule_qual,
1124
									 rt_index, event, *instead_flag);
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

			/* handle escapable cases, or those handled by other code */
			if (info->nothing)
			{
				if (*instead_flag)
					return NIL;
				else
					continue;
			}

			if (info->action == info->event &&
				info->event == CMD_SELECT)
				continue;

			/*
M
 
Marc G. Fournier 已提交
1140
			 * Event Qualification forces copying of parsetree and
1141 1142 1143
			 * splitting into two queries one w/rule_qual, one w/NOT
			 * rule_qual. Also add user query qual onto rule action
			 */
1144
			AddQual(info->rule_action, parsetree->qual);
1145

1146
			AddQual(info->rule_action, info->rule_qual);
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166

			/*--------------------------------------------------
			 * Step 2:
			 *	  Rewrite new.attribute w/ right hand side of target-list
			 *	  entry for appropriate field name in insert/update
			 *--------------------------------------------------
			 */
			if ((info->event == CMD_INSERT) || (info->event == CMD_UPDATE))
				FixNew(info, parsetree);

			/*--------------------------------------------------
			 * Step 3:
			 *	  Simplify? hey, no algorithm for simplification... let
			 *	  the planner do it.
			 *--------------------------------------------------
			 */
			results = lappend(results, info->rule_action);

			pfree(info);
		}
M
 
Marc G. Fournier 已提交
1167 1168 1169 1170 1171 1172

		/* ----------
		 * If this was an unqualified instead rule,
		 * throw away an eventually saved 'default' parsetree
		 * ----------
		 */
1173
		if (event_qual == NULL && *instead_flag)
M
 
Marc G. Fournier 已提交
1174
			*qual_products = NIL;
1175 1176
	}
	return results;
1177 1178
}

M
 
Marc G. Fournier 已提交
1179 1180


1181
static List *
1182
RewriteQuery(Query *parsetree, bool *instead_flag, List **qual_products)
1183
{
1184
	CmdType		event;
B
Bruce Momjian 已提交
1185 1186 1187
	List	   *product_queries = NIL;
	int			result_relation = 0;
	RangeTblEntry *rt_entry;
1188
	Relation	rt_entry_relation = NULL;
B
Bruce Momjian 已提交
1189
	RuleLock   *rt_entry_locks = NULL;
1190

1191 1192 1193 1194
	Assert(parsetree != NULL);

	event = parsetree->commandType;

1195
	/*
B
Bruce Momjian 已提交
1196 1197
	 * SELECT rules are handled later when we have all the queries that
	 * should get executed
1198 1199 1200 1201 1202 1203 1204
	 */
	if (event == CMD_SELECT)
		return NIL;

	/*
	 * Utilities aren't rewritten at all - why is this here?
	 */
1205 1206
	if (event == CMD_UTILITY)
		return NIL;
1207

1208
	/*
B
Bruce Momjian 已提交
1209
	 * the statement is an update, insert or delete - fire rules on it.
1210
	 */
1211
	result_relation = parsetree->resultRelation;
1212
	rt_entry = rt_fetch(result_relation, parsetree->rtable);
1213
	rt_entry_relation = heap_openr(rt_entry->relname, AccessShareLock);
1214
	rt_entry_locks = rt_entry_relation->rd_rules;
M
 
Marc G. Fournier 已提交
1215

1216
	if (rt_entry_locks != NULL)
1217
	{
1218 1219
		List	   *locks = matchLocks(event, rt_entry_locks,
									   result_relation, parsetree);
1220

1221
		product_queries = fireRules(parsetree,
B
Bruce Momjian 已提交
1222 1223 1224 1225 1226
									result_relation,
									event,
									instead_flag,
									locks,
									qual_products);
1227
	}
1228

1229 1230
	heap_close(rt_entry_relation, AccessShareLock);

1231
	return product_queries;
1232 1233
}

1234

1235 1236
/*
 * to avoid infinite recursion, we restrict the number of times a query
1237
 * can be rewritten. Detecting cycles is left for the reader as an exercise.
1238 1239
 */
#ifndef REWRITE_INVOKE_MAX
1240
#define REWRITE_INVOKE_MAX		10
1241 1242
#endif

1243
static int	numQueryRewriteInvoked = 0;
1244 1245 1246

/*
 * deepRewriteQuery -
1247
 *	  rewrites the query and apply the rules again on the queries rewritten
1248
 */
1249
static List *
1250
deepRewriteQuery(Query *parsetree)
1251
{
1252 1253 1254 1255 1256
	List	   *n;
	List	   *rewritten = NIL;
	List	   *result = NIL;
	bool		instead;
	List	   *qual_products = NIL;
1257 1258 1259

	if (++numQueryRewriteInvoked > REWRITE_INVOKE_MAX)
	{
1260
		elog(ERROR, "query rewritten %d times, may contain cycles",
1261 1262 1263 1264 1265
			 numQueryRewriteInvoked - 1);
	}

	instead = FALSE;
	result = RewriteQuery(parsetree, &instead, &qual_products);
1266

1267 1268
	foreach(n, result)
	{
1269 1270
		Query	   *pt = lfirst(n);
		List	   *newstuff = NIL;
1271 1272 1273 1274 1275

		newstuff = deepRewriteQuery(pt);
		if (newstuff != NIL)
			rewritten = nconc(rewritten, newstuff);
	}
M
 
Marc G. Fournier 已提交
1276 1277 1278 1279 1280 1281

	/* ----------
	 * qual_products are the original query with the negated
	 * rule qualification of an instead rule
	 * ----------
	 */
1282 1283 1284
	if (qual_products != NIL)
		rewritten = nconc(rewritten, qual_products);

M
 
Marc G. Fournier 已提交
1285
	/* ----------
1286
	 * The original query is appended last (if no "instead" rule)
M
 
Marc G. Fournier 已提交
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
	 * because update and delete rule actions might not do
	 * anything if they are invoked after the update or
	 * delete is performed. The command counter increment
	 * between the query execution makes the deleted (and
	 * maybe the updated) tuples disappear so the scans
	 * for them in the rule actions cannot find them.
	 * ----------
	 */
	if (!instead)
		rewritten = lappend(rewritten, parsetree);

1298 1299
	return rewritten;
}
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318


/*
 * QueryOneRewrite -
 *	  rewrite one query
 */
static List *
QueryRewriteOne(Query *parsetree)
{
	numQueryRewriteInvoked = 0;

	/*
	 * take a deep breath and apply all the rewrite rules - ay
	 */
	return deepRewriteQuery(parsetree);
}


/*
1319
 * BasicQueryRewrite -
1320 1321 1322
 *	  rewrite one query via query rewrite system, possibly returning 0
 *	  or many queries
 */
1323 1324
static List *
BasicQueryRewrite(Query *parsetree)
1325
{
B
Bruce Momjian 已提交
1326 1327 1328 1329
	List	   *querylist;
	List	   *results = NIL;
	List	   *l;
	Query	   *query;
1330 1331 1332 1333 1334 1335 1336 1337 1338

	/*
	 * Step 1
	 *
	 * Apply all non-SELECT rules possibly getting 0 or many queries
	 */
	querylist = QueryRewriteOne(parsetree);

	/*
1339
	 * Step 2
1340 1341 1342
	 *
	 * Apply all the RIR rules on each query
	 */
B
Bruce Momjian 已提交
1343 1344 1345 1346
	foreach(l, querylist)
	{
		query = fireRIRrules((Query *) lfirst(l));

1347
		/*
B
Bruce Momjian 已提交
1348
		 * If the query was marked having aggregates, check if this is
1349
		 * still true after rewriting.	Ditto for sublinks.  Note there
1350
		 * should be no aggs in the qual at this point.
1351 1352
		 */
		if (query->hasAggs)
1353
		{
1354 1355 1356 1357
			query->hasAggs = checkExprHasAggs((Node *) query);
			if (query->hasAggs)
				if (checkExprHasAggs(query->qual))
					elog(ERROR, "BasicQueryRewrite: failed to remove aggs from qual");
1358
		}
1359
		if (query->hasSubLinks)
1360 1361 1362
		{
			query->hasSubLinks = checkExprHasSubLink((Node *) query);
		}
1363
		results = lappend(results, query);
1364
	}
1365

1366 1367
	return results;
}
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378

/*
 * QueryRewrite -
 *	  Primary entry point to the query rewriter.
 *	  Rewrite one query via query rewrite system, possibly returning 0
 *	  or many queries.
 *
 * NOTE: The code in QueryRewrite was formerly in pg_parse_and_plan(), and was
 * moved here so that it would be invoked during EXPLAIN.  The division of
 * labor between this routine and BasicQueryRewrite is not obviously correct
 * ... at least not to me ... tgl 5/99.
B
Hi!  
Bruce Momjian 已提交
1379
 */
1380 1381 1382 1383 1384 1385
List *
QueryRewrite(Query *parsetree)
{
	List	   *rewritten,
			   *rewritten_item;

B
Bruce Momjian 已提交
1386 1387 1388 1389
	/*
	 * Rewrite Union, Intersect and Except Queries to normal Union Queries
	 * using IN and NOT IN subselects
	 */
1390 1391 1392 1393 1394 1395 1396 1397 1398
	if (parsetree->intersectClause)
		parsetree = Except_Intersect_Rewrite(parsetree);

	/* Rewrite basic queries (retrieve, append, delete, replace) */
	rewritten = BasicQueryRewrite(parsetree);

	/*
	 * Rewrite the UNIONS.
	 */
B
Bruce Momjian 已提交
1399
	foreach(rewritten_item, rewritten)
1400 1401 1402 1403 1404
	{
		Query	   *qry = (Query *) lfirst(rewritten_item);
		List	   *union_result = NIL;
		List	   *union_item;

B
Bruce Momjian 已提交
1405
		foreach(union_item, qry->unionClause)
1406 1407
		{
			union_result = nconc(union_result,
B
Bruce Momjian 已提交
1408
						BasicQueryRewrite((Query *) lfirst(union_item)));
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
		}
		qry->unionClause = union_result;
	}

	return rewritten;
}

/* This function takes two targetlists as arguments and checks if the
 * targetlists are compatible (i.e. both select for the same number of
 * attributes and the types are compatible */
1419
static void
B
Bruce Momjian 已提交
1420
check_targetlists_are_compatible(List *prev_target, List *current_target)
B
Hi!  
Bruce Momjian 已提交
1421
{
1422
	List	   *tl;
B
Bruce Momjian 已提交
1423 1424
	int			prev_len = 0,
				next_len = 0;
1425

B
Bruce Momjian 已提交
1426 1427
	foreach(tl, prev_target)
		if (!((TargetEntry *) lfirst(tl))->resdom->resjunk)
1428
			prev_len++;
1429

1430 1431 1432
	foreach(tl, current_target)
		if (!((TargetEntry *) lfirst(tl))->resdom->resjunk)
			next_len++;
B
Bruce Momjian 已提交
1433 1434 1435 1436

	if (prev_len != next_len)
		elog(ERROR, "Each UNION | EXCEPT | INTERSECT query must have the same number of columns.");

1437
	foreach(tl, current_target)
B
Hi!  
Bruce Momjian 已提交
1438
	{
1439 1440 1441 1442 1443 1444 1445
		TargetEntry	   *next_tle = (TargetEntry *) lfirst(tl);
		TargetEntry	   *prev_tle;
		Oid				itype;
		Oid				otype;

		if (next_tle->resdom->resjunk)
			continue;
B
Bruce Momjian 已提交
1446

1447 1448 1449 1450 1451 1452 1453 1454 1455
		/* This loop must find an entry, since we counted them above. */
		do
		{
			prev_tle = (TargetEntry *) lfirst(prev_target);
			prev_target = lnext(prev_target);
		} while (prev_tle->resdom->resjunk);

		itype = next_tle->resdom->restype;
		otype = prev_tle->resdom->restype;
B
Bruce Momjian 已提交
1456 1457 1458 1459 1460 1461

		/* one or both is a NULL column? then don't convert... */
		if (otype == InvalidOid)
		{
			/* propagate a known type forward, if available */
			if (itype != InvalidOid)
1462
				prev_tle->resdom->restype = itype;
M
 
Marc G. Fournier 已提交
1463
#ifdef NOT_USED
B
Bruce Momjian 已提交
1464 1465
			else
			{
1466 1467
				prev_tle->resdom->restype = UNKNOWNOID;
				next_tle->resdom->restype = UNKNOWNOID;
B
Bruce Momjian 已提交
1468
			}
B
Hi!  
Bruce Momjian 已提交
1469
#endif
B
Bruce Momjian 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478
		}
		else if (itype == InvalidOid)
		{
		}
		/* they don't match in type? then convert... */
		else if (itype != otype)
		{
			Node	   *expr;

1479
			expr = next_tle->expr;
1480
			expr = CoerceTargetExpr(NULL, expr, itype, otype, -1);
B
Bruce Momjian 已提交
1481 1482 1483 1484 1485 1486 1487
			if (expr == NULL)
			{
				elog(ERROR, "Unable to transform %s to %s"
					 "\n\tEach UNION | EXCEPT | INTERSECT clause must have compatible target types",
					 typeidTypeName(itype),
					 typeidTypeName(otype));
			}
1488 1489
			next_tle->expr = expr;
			next_tle->resdom->restype = otype;
B
Bruce Momjian 已提交
1490 1491 1492 1493 1494
		}

		/* both are UNKNOWN? then evaluate as text... */
		else if (itype == UNKNOWNOID)
		{
1495 1496
			next_tle->resdom->restype = TEXTOID;
			prev_tle->resdom->restype = TEXTOID;
B
Bruce Momjian 已提交
1497
		}
B
Hi!  
Bruce Momjian 已提交
1498 1499 1500 1501
	}
}

/* Rewrites UNION INTERSECT and EXCEPT queries to semantiacally equivalent
B
Bruce Momjian 已提交
1502 1503
 * queries that use IN and NOT IN subselects.
 *
B
Hi!  
Bruce Momjian 已提交
1504 1505 1506
 * The operator tree is attached to 'intersectClause' (see rule
 * 'SelectStmt' in gram.y) of the 'parsetree' given as an
 * argument. First we remember some clauses (the sortClause, the
1507
 * distinctClause etc.)  Then we translate the operator tree to DNF
B
Hi!  
Bruce Momjian 已提交
1508 1509 1510 1511 1512 1513 1514 1515
 * (disjunctive normal form) by 'cnfify'. (Note that 'cnfify' produces
 * CNF but as we exchanged ANDs with ORs in function A_Expr_to_Expr()
 * earlier we get DNF after exchanging ANDs and ORs again in the
 * result.) Now we create a new query by evaluating the new operator
 * tree which is in DNF now. For every AND we create an entry in the
 * union list and for every OR we create an IN subselect. (NOT IN
 * subselects are created for OR NOT nodes). The first entry of the
 * union list is handed back but before that the remembered clauses
B
Bruce Momjian 已提交
1516
 * (sortClause etc) are attached to the new top Node (Note that the
B
Hi!  
Bruce Momjian 已提交
1517
 * new top Node can differ from the parsetree given as argument because of
1518 1519
 * the translation to DNF. That's why we have to remember the sortClause
 * and so on!) */
1520
static Query *
B
Bruce Momjian 已提交
1521
Except_Intersect_Rewrite(Query *parsetree)
B
Hi!  
Bruce Momjian 已提交
1522
{
B
Bruce Momjian 已提交
1523 1524 1525 1526 1527 1528 1529 1530 1531

	SubLink    *n;
	Query	   *result,
			   *intersect_node;
	List	   *elist,
			   *intersect_list = NIL,
			   *intersect,
			   *intersectClause;
	List	   *union_list = NIL,
1532 1533
			   *sortClause,
			   *distinctClause;
B
Bruce Momjian 已提交
1534 1535 1536 1537 1538 1539 1540
	List	   *left_expr,
			   *resnames = NIL;
	char	   *op,
			   *into;
	bool		isBinary,
				isPortal,
				isTemp;
1541 1542
	Node	   *limitOffset,
			   *limitCount;
B
Bruce Momjian 已提交
1543
	CmdType		commandType = CMD_SELECT;
1544
	RangeTblEntry *rtable_insert = NULL;
B
Bruce Momjian 已提交
1545 1546 1547 1548 1549 1550 1551 1552
	List	   *prev_target = NIL;

	/*
	 * Remember the Resnames of the given parsetree's targetlist (these
	 * are the resnames of the first Select Statement of the query
	 * formulated by the user and he wants the columns named by these
	 * strings. The transformation to DNF can cause another Select
	 * Statment to be the top one which uses other names for its columns.
1553
	 * Therefore we remember the original names and attach them to the
B
Bruce Momjian 已提交
1554 1555 1556 1557 1558 1559
	 * targetlist of the new topmost Node at the end of this function
	 */
	foreach(elist, parsetree->targetList)
	{
		TargetEntry *tent = (TargetEntry *) lfirst(elist);

1560 1561
		if (! tent->resdom->resjunk)
			resnames = lappend(resnames, tent->resdom->resname);
B
Bruce Momjian 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
	}

	/*
	 * If the Statement is an INSERT INTO ... (SELECT...) statement using
	 * UNIONs, INTERSECTs or EXCEPTs and the transformation to DNF makes
	 * another Node to the top node we have to transform the new top node
	 * to an INSERT node and the original INSERT node to a SELECT node
	 */
	if (parsetree->commandType == CMD_INSERT)
	{
1572

B
Bruce Momjian 已提交
1573 1574 1575 1576
		/*
		 * The result relation ( = the one to insert into) has to be
		 * attached to the rtable list of the new top node
		 */
1577 1578 1579 1580 1581
		rtable_insert = rt_fetch(parsetree->resultRelation, parsetree->rtable);

		parsetree->commandType = CMD_SELECT;
		commandType = CMD_INSERT;
		parsetree->resultRelation = 0;
B
Hi!  
Bruce Momjian 已提交
1582
	}
B
Bruce Momjian 已提交
1583 1584 1585 1586 1587 1588

	/*
	 * Save some items, to be able to attach them to the resulting top
	 * node at the end of the function
	 */
	sortClause = parsetree->sortClause;
1589
	distinctClause = parsetree->distinctClause;
B
Bruce Momjian 已提交
1590 1591 1592 1593
	into = parsetree->into;
	isBinary = parsetree->isBinary;
	isPortal = parsetree->isPortal;
	isTemp = parsetree->isTemp;
1594 1595
	limitOffset = parsetree->limitOffset;
	limitCount = parsetree->limitCount;
B
Bruce Momjian 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650

	/*
	 * The operator tree attached to parsetree->intersectClause is still
	 * 'raw' ( = the leaf nodes are still SelectStmt nodes instead of
	 * Query nodes) So step through the tree and transform the nodes using
	 * parse_analyze().
	 *
	 * The parsetree (given as an argument to Except_Intersect_Rewrite()) has
	 * already been transformed and transforming it again would cause
	 * troubles.  So we give the 'raw' version (of the cooked parsetree)
	 * to the function to prevent an additional transformation. Instead we
	 * hand back the 'cooked' version also given as an argument to
	 * intersect_tree_analyze()
	 */
	intersectClause =
		(List *) intersect_tree_analyze((Node *) parsetree->intersectClause,
								 (Node *) lfirst(parsetree->unionClause),
										(Node *) parsetree);

	/* intersectClause is no longer needed so set it to NIL */
	parsetree->intersectClause = NIL;

	/*
	 * unionClause will be needed later on but the list it delivered is no
	 * longer needed, so set it to NIL
	 */
	parsetree->unionClause = NIL;

	/*
	 * Transform the operator tree to DNF (remember ANDs and ORs have been
	 * exchanged, that's why we get DNF by using cnfify)
	 *
	 * After the call, explicit ANDs are removed and all AND operands are
	 * simply items in the intersectClause list
	 */
	intersectClause = cnfify((Expr *) intersectClause, true);

	/*
	 * For every entry of the intersectClause list we generate one entry
	 * in the union_list
	 */
	foreach(intersect, intersectClause)
	{

		/*
		 * for every OR we create an IN subselect and for every OR NOT we
		 * create a NOT IN subselect, so first extract all the Select
		 * Query nodes from the tree (that contains only OR or OR NOTs any
		 * more because we did a transformation to DNF
		 *
		 * There must be at least one node that is not negated (i.e. just OR
		 * and not OR NOT) and this node will be the first in the list
		 * returned
		 */
		intersect_list = NIL;
1651
		create_intersect_list((Node *) lfirst(intersect), &intersect_list);
B
Bruce Momjian 已提交
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721

		/*
		 * This one will become the Select Query node, all other nodes are
		 * transformed into subselects under this node!
		 */
		intersect_node = (Query *) lfirst(intersect_list);
		intersect_list = lnext(intersect_list);

		/*
		 * Check if all Select Statements use the same number of
		 * attributes and if all corresponding attributes are of the same
		 * type
		 */
		if (prev_target)
			check_targetlists_are_compatible(prev_target, intersect_node->targetList);
		prev_target = intersect_node->targetList;

		/*
		 * Transform all nodes remaining into subselects and add them to
		 * the qualifications of the Select Query node
		 */
		while (intersect_list != NIL)
		{

			n = makeNode(SubLink);

			/* Here we got an OR so transform it to an IN subselect */
			if (IsA(lfirst(intersect_list), Query))
			{

				/*
				 * Check if all Select Statements use the same number of
				 * attributes and if all corresponding attributes are of
				 * the same type
				 */
				check_targetlists_are_compatible(prev_target,
						 ((Query *) lfirst(intersect_list))->targetList);

				n->subselect = lfirst(intersect_list);
				op = "=";
				n->subLinkType = ANY_SUBLINK;
				n->useor = false;
			}

			/*
			 * Here we got an OR NOT node so transform it to a NOT IN
			 * subselect
			 */
			else
			{

				/*
				 * Check if all Select Statements use the same number of
				 * attributes and if all corresponding attributes are of
				 * the same type
				 */
				check_targetlists_are_compatible(prev_target,
												 ((Query *) lfirst(((Expr *) lfirst(intersect_list))->args))->targetList);

				n->subselect = (Node *) lfirst(((Expr *) lfirst(intersect_list))->args);
				op = "<>";
				n->subLinkType = ALL_SUBLINK;
				n->useor = true;
			}

			/*
			 * Prepare the lefthand side of the Sublinks: All the entries
			 * of the targetlist must be (IN) or must not be (NOT IN) the
			 * subselect
			 */
1722
			n->lefthand = NIL;
B
Bruce Momjian 已提交
1723 1724
			foreach(elist, intersect_node->targetList)
			{
1725
				TargetEntry *tent = (TargetEntry *) lfirst(elist);
B
Bruce Momjian 已提交
1726

1727 1728
				if (! tent->resdom->resjunk)
					n->lefthand = lappend(n->lefthand, tent->expr);
B
Bruce Momjian 已提交
1729 1730 1731
			}

			/*
1732
			 * Also prepare the list of Opers that must be used for the
1733 1734
			 * comparisons (they depend on the specific datatypes
			 * involved!)
B
Bruce Momjian 已提交
1735 1736
			 */
			left_expr = n->lefthand;
1737
			n->oper = NIL;
B
Bruce Momjian 已提交
1738

1739
			foreach(elist, ((Query *) (n->subselect))->targetList)
B
Bruce Momjian 已提交
1740
			{
1741 1742
				TargetEntry *tent = (TargetEntry *) lfirst(elist);
				Node	   *lexpr;
1743 1744 1745 1746
				Operator	optup;
				Form_pg_operator opform;
				Oper	   *newop;

1747 1748 1749 1750 1751
				if (tent->resdom->resjunk)
					continue;

				lexpr = lfirst(left_expr);

1752 1753 1754 1755 1756 1757 1758 1759 1760
				optup = oper(op,
							 exprType(lexpr),
							 exprType(tent->expr),
							 FALSE);
				opform = (Form_pg_operator) GETSTRUCT(optup);

				if (opform->oprresult != BOOLOID)
					elog(ERROR, "parser: '%s' must return 'bool' to be used with quantified predicate subquery", op);

1761 1762
				newop = makeOper(oprid(optup),	/* opno */
								 InvalidOid,	/* opid */
1763
								 opform->oprresult);
B
Bruce Momjian 已提交
1764

1765
				n->oper = lappend(n->oper, newop);
B
Bruce Momjian 已提交
1766

1767
				left_expr = lnext(left_expr);
B
Bruce Momjian 已提交
1768 1769
			}

1770 1771
			Assert(left_expr == NIL); /* should have used 'em all */

B
Bruce Momjian 已提交
1772 1773 1774 1775
			/*
			 * If the Select Query node has aggregates in use add all the
			 * subselects to the HAVING qual else to the WHERE qual
			 */
1776
			if (intersect_node->hasAggs)
B
Bruce Momjian 已提交
1777
				AddHavingQual(intersect_node, (Node *) n);
1778 1779
			else
				AddQual(intersect_node, (Node *) n);
B
Bruce Momjian 已提交
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794

			/* Now we got sublinks */
			intersect_node->hasSubLinks = true;
			intersect_list = lnext(intersect_list);
		}
		intersect_node->intersectClause = NIL;
		union_list = lappend(union_list, intersect_node);
	}

	/* The first entry to union_list is our new top node */
	result = (Query *) lfirst(union_list);
	/* attach the rest to unionClause */
	result->unionClause = lnext(union_list);
	/* Attach all the items remembered in the beginning of the function */
	result->sortClause = sortClause;
1795
	result->distinctClause = distinctClause;
B
Bruce Momjian 已提交
1796 1797 1798 1799
	result->into = into;
	result->isPortal = isPortal;
	result->isBinary = isBinary;
	result->isTemp = isTemp;
1800 1801
	result->limitOffset = limitOffset;
	result->limitCount = limitCount;
B
Bruce Momjian 已提交
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821

	/*
	 * The relation to insert into is attached to the range table of the
	 * new top node
	 */
	if (commandType == CMD_INSERT)
	{
		result->rtable = lappend(result->rtable, rtable_insert);
		result->resultRelation = length(result->rtable);
		result->commandType = commandType;
	}

	/*
	 * The resnames of the originally first SelectStatement are attached
	 * to the new first SelectStatement
	 */
	foreach(elist, result->targetList)
	{
		TargetEntry *tent = (TargetEntry *) lfirst(elist);

1822 1823 1824
		if (tent->resdom->resjunk)
			continue;

B
Bruce Momjian 已提交
1825 1826 1827
		tent->resdom->resname = lfirst(resnames);
		resnames = lnext(resnames);
	}
1828

B
Bruce Momjian 已提交
1829
	return result;
B
Hi!  
Bruce Momjian 已提交
1830 1831 1832 1833 1834 1835 1836
}

/* Create a list of nodes that are either Query nodes of NOT Expr
 * nodes followed by a Query node. The tree given in ptr contains at
 * least one non negated Query node. This node is attached to the
 * beginning of the list */

1837 1838
static void
create_intersect_list(Node *ptr, List **intersect_list)
B
Hi!  
Bruce Momjian 已提交
1839
{
B
Bruce Momjian 已提交
1840 1841 1842
	List	   *arg;

	if (IsA(ptr, Query))
B
Hi!  
Bruce Momjian 已提交
1843
	{
B
Bruce Momjian 已提交
1844 1845 1846
		/* The non negated node is attached at the beginning (lcons) */
		*intersect_list = lcons(ptr, *intersect_list);
		return;
B
Hi!  
Bruce Momjian 已提交
1847
	}
B
Bruce Momjian 已提交
1848 1849

	if (IsA(ptr, Expr))
B
Hi!  
Bruce Momjian 已提交
1850
	{
B
Bruce Momjian 已提交
1851 1852 1853 1854 1855 1856 1857 1858 1859
		if (((Expr *) ptr)->opType == NOT_EXPR)
		{
			/* negated nodes are appended to the end (lappend) */
			*intersect_list = lappend(*intersect_list, ptr);
			return;
		}
		else
		{
			foreach(arg, ((Expr *) ptr)->args)
1860
				create_intersect_list(lfirst(arg), intersect_list);
B
Bruce Momjian 已提交
1861 1862 1863
			return;
		}
		return;
B
Hi!  
Bruce Momjian 已提交
1864 1865 1866 1867 1868
	}
}

/* The nodes given in 'tree' are still 'raw' so 'cook' them using parse_analyze().
 * The node given in first_select has already been cooked, so don't transform
B
Bruce Momjian 已提交
1869
 * it again but return a pointer to the previously cooked version given in 'parsetree'
B
Hi!  
Bruce Momjian 已提交
1870
 * instead. */
1871
static Node *
B
Bruce Momjian 已提交
1872
intersect_tree_analyze(Node *tree, Node *first_select, Node *parsetree)
B
Hi!  
Bruce Momjian 已提交
1873
{
B
Bruce Momjian 已提交
1874 1875
	Node	   *result = (Node *) NIL;
	List	   *arg;
1876 1877

	if (IsA(tree, SelectStmt))
B
Bruce Momjian 已提交
1878 1879 1880 1881 1882 1883
	{

		/*
		 * If we get to the tree given in first_select return parsetree
		 * instead of performing parse_analyze()
		 */
1884 1885 1886
		if (tree == first_select)
			result = parsetree;
		else
B
Bruce Momjian 已提交
1887 1888 1889 1890
		{
			/* transform the 'raw' nodes to 'cooked' Query nodes */
			List	   *qtree = parse_analyze(lcons(tree, NIL), NULL);

1891 1892
			result = (Node *) lfirst(qtree);
		}
B
Bruce Momjian 已提交
1893
	}
1894

B
Bruce Momjian 已提交
1895
	if (IsA(tree, Expr))
B
Hi!  
Bruce Momjian 已提交
1896
	{
B
Bruce Momjian 已提交
1897 1898 1899 1900
		/* Call recursively for every argument of the node */
		foreach(arg, ((Expr *) tree)->args)
			lfirst(arg) = intersect_tree_analyze(lfirst(arg), first_select, parsetree);
		result = tree;
B
Hi!  
Bruce Momjian 已提交
1901
	}
B
Bruce Momjian 已提交
1902
	return result;
B
Hi!  
Bruce Momjian 已提交
1903
}