rewriteHandler.c 25.4 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * rewriteHandler.c
4
 *
5
 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
6
 * 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.92 2001/04/17 00:32:58 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
#include "rewrite/rewriteManip.h"
#include "utils/lsyscache.h"
32 33 34 35 36 37 38


static RewriteInfo *gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
				  int rt_index,
				  CmdType event,
39
				  bool instead_flag);
40
static List *adjustJoinTreeList(Query *parsetree, bool removert, int rt_index);
41
static void markQueryForUpdate(Query *qry, bool skipOldNew);
42
static List *matchLocks(CmdType event, RuleLock *rulelocks,
B
Bruce Momjian 已提交
43
		   int varno, Query *parsetree);
44
static Query *fireRIRrules(Query *parsetree);
45

46 47 48

/*
 * gatherRewriteMeta -
49 50 51
 *	  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
52 53
 */
static RewriteInfo *
54 55 56
gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
57 58
				  int rt_index,
				  CmdType event,
59
				  bool instead_flag)
60
{
61
	RewriteInfo *info;
62 63
	Query	   *sub_action;
	Query	  **sub_action_ptr;
64
	int			rt_length;
65 66 67 68

	info = (RewriteInfo *) palloc(sizeof(RewriteInfo));
	info->rt_index = rt_index;
	info->event = event;
69
	info->instead_flag = instead_flag;
70 71 72 73
	info->rule_action = (Query *) copyObject(rule_action);
	info->rule_qual = (Node *) copyObject(rule_qual);
	if (info->rule_action == NULL)
	{
74 75 76 77 78 79 80 81
		info->nothing = TRUE;
		return info;
	}
	info->nothing = FALSE;
	info->action = info->rule_action->commandType;
	info->current_varno = rt_index;
	rt_length = length(parsetree->rtable);
	info->new_varno = PRS2_NEW_VARNO + rt_length;
82

83 84 85 86
	/*
	 * Adjust rule action and qual to offset its varnos, so that we can
	 * merge its rtable into the main parsetree's rtable.
	 *
B
Bruce Momjian 已提交
87 88 89
	 * If the rule action is an INSERT...SELECT, the OLD/NEW rtable entries
	 * will be in the SELECT part, and we have to modify that rather than
	 * the top-level INSERT (kluge!).
90 91
	 */
	sub_action = getInsertSelectQuery(info->rule_action, &sub_action_ptr);
92

93 94 95 96 97 98 99 100 101 102 103
	OffsetVarNodes((Node *) sub_action, rt_length, 0);
	OffsetVarNodes(info->rule_qual, rt_length, 0);
	/* but references to *OLD* should point at original rt_index */
	ChangeVarNodes((Node *) sub_action,
				   PRS2_OLD_VARNO + rt_length, rt_index, 0);
	ChangeVarNodes(info->rule_qual,
				   PRS2_OLD_VARNO + rt_length, rt_index, 0);

	/*
	 * We want the main parsetree's rtable to end up as the concatenation
	 * of its original contents plus those of all the relevant rule
B
Bruce Momjian 已提交
104 105 106 107 108
	 * 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.
109
	 *
B
Bruce Momjian 已提交
110 111
	 * 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?).
112 113 114 115 116 117 118
	 * 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,
							  sub_action->rtable);
	sub_action->rtable = parsetree->rtable;
119

120 121
	/*
	 * Each rule action's jointree should be the main parsetree's jointree
B
Bruce Momjian 已提交
122 123 124 125 126 127 128 129 130
	 * plus that rule's jointree, but usually *without* the original
	 * rtindex that we're replacing (if present, which it won't be for
	 * INSERT). Note that if the rule action refers to OLD, its jointree
	 * will add a reference to rt_index.  If the rule action doesn't refer
	 * to OLD, but either the rule_qual or the user query quals do, then
	 * we need to keep the original rtindex in the jointree to provide
	 * data for the quals.	We don't want the original rtindex to be
	 * joined twice, however, so avoid keeping it if the rule action
	 * mentions it.
131
	 */
132
	if (sub_action->jointree != NULL)
133
	{
B
Bruce Momjian 已提交
134 135
		bool		keeporig;
		List	   *newjointree;
136

B
Bruce Momjian 已提交
137 138
		keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
										  rt_index, 0)) &&
139
			(rangeTableEntry_used(info->rule_qual, rt_index, 0) ||
B
Bruce Momjian 已提交
140
		  rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
141
		newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
		sub_action->jointree->fromlist =
			nconc(newjointree, sub_action->jointree->fromlist);
	}

	/*
	 * We copy the qualifications of the parsetree to the action and vice
	 * versa. So force hasSubLinks if one of them has it. If this is not
	 * right, the flag will get cleared later, but we mustn't risk having
	 * it not set when it needs to be.
	 */
	if (parsetree->hasSubLinks)
		sub_action->hasSubLinks = TRUE;
	else if (sub_action->hasSubLinks)
		parsetree->hasSubLinks = TRUE;

	/*
B
Bruce Momjian 已提交
158 159 160
	 * Event Qualification forces copying of parsetree and splitting into
	 * two queries one w/rule_qual, one w/NOT rule_qual. Also add user
	 * query qual onto rule action
161 162 163 164 165 166
	 */
	AddQual(sub_action, info->rule_qual);

	AddQual(sub_action, parsetree->jointree->quals);

	/*
B
Bruce Momjian 已提交
167 168
	 * Rewrite new.attribute w/ right hand side of target-list entry for
	 * appropriate field name in insert/update.
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
	 *
	 * KLUGE ALERT: since ResolveNew returns a mutated copy, we can't just
	 * apply it to sub_action; we have to remember to update the sublink
	 * inside info->rule_action, too.
	 */
	if (info->event == CMD_INSERT || info->event == CMD_UPDATE)
	{
		sub_action = (Query *) ResolveNew((Node *) sub_action,
										  info->new_varno,
										  0,
										  parsetree->targetList,
										  info->event,
										  info->current_varno);
		if (sub_action_ptr)
			*sub_action_ptr = sub_action;
		else
			info->rule_action = sub_action;
186
	}
187

188
	return info;
189 190
}

191
/*
192 193 194 195 196 197
 * Copy the query's jointree list, and optionally attempt to remove any
 * occurrence of the given rt_index as a top-level join item (we do not look
 * for it within join items; this is OK because we are only expecting to find
 * it as an UPDATE or DELETE target relation, which will be at the top level
 * of the join).  Returns modified jointree list --- original list is not
 * changed.
198
 */
199
static List *
200
adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
201
{
202
	List	   *newjointree = listCopy(parsetree->jointree->fromlist);
203
	List	   *jjt;
204

205
	if (removert)
B
Bruce Momjian 已提交
206
	{
207
		foreach(jjt, newjointree)
208
		{
209 210
			RangeTblRef *rtr = lfirst(jjt);

B
Bruce Momjian 已提交
211
			if (IsA(rtr, RangeTblRef) &&rtr->rtindex == rt_index)
212 213 214 215
			{
				newjointree = lremove(rtr, newjointree);
				break;
			}
216
		}
217
	}
218
	return newjointree;
219
}
220

221

222
/*
223 224
 * matchLocks -
 *	  match the list of locks and returns the matching rules
225
 */
226 227 228 229 230
static List *
matchLocks(CmdType event,
		   RuleLock *rulelocks,
		   int varno,
		   Query *parsetree)
231
{
232 233 234
	List	   *real_locks = NIL;
	int			nlocks;
	int			i;
235

236 237
	Assert(rulelocks != NULL);	/* we get called iff there is some lock */
	Assert(parsetree != NULL);
238

239
	if (parsetree->commandType != CMD_SELECT)
240
	{
241 242
		if (parsetree->resultRelation != varno)
			return NIL;
243
	}
244

245
	nlocks = rulelocks->numLocks;
246

247
	for (i = 0; i < nlocks; i++)
B
Bruce Momjian 已提交
248
	{
249
		RewriteRule *oneLock = rulelocks->rules[i];
250

251
		if (oneLock->event == event)
252
		{
253 254 255 256 257 258
			if (parsetree->commandType != CMD_SELECT ||
				(oneLock->attrno == -1 ?
				 rangeTableEntry_used((Node *) parsetree, varno, 0) :
				 attribute_used((Node *) parsetree,
								varno, oneLock->attrno, 0)))
				real_locks = lappend(real_locks, oneLock);
259
		}
260
	}
261 262

	return real_locks;
263 264
}

265

266 267 268 269 270 271 272 273 274 275 276
static Query *
ApplyRetrieveRule(Query *parsetree,
				  RewriteRule *rule,
				  int rt_index,
				  bool relation_level,
				  Relation relation,
				  bool relIsUsed)
{
	Query	   *rule_action;
	RangeTblEntry *rte,
			   *subrte;
277

278 279 280 281
	if (length(rule->actions) != 1)
		elog(ERROR, "ApplyRetrieveRule: expected just one rule action");
	if (rule->qual != NULL)
		elog(ERROR, "ApplyRetrieveRule: can't handle qualified ON SELECT rule");
B
Bruce Momjian 已提交
282
	if (!relation_level)
283
		elog(ERROR, "ApplyRetrieveRule: can't handle per-attribute ON SELECT rule");
284

285
	/*
286 287
	 * Make a modifiable copy of the view query, and recursively expand
	 * any view references inside it.
288
	 */
289
	rule_action = copyObject(lfirst(rule->actions));
290

291
	rule_action = fireRIRrules(rule_action);
292

293
	/*
B
Bruce Momjian 已提交
294 295
	 * VIEWs are really easy --- just plug the view query in as a
	 * subselect, replacing the relation's original RTE.
296
	 */
297
	rte = rt_fetch(rt_index, parsetree->rtable);
298

299 300 301 302
	rte->relname = NULL;
	rte->relid = InvalidOid;
	rte->subquery = rule_action;
	rte->inh = false;			/* must not be set for a subquery */
303

304
	/*
305 306
	 * We move the view's permission check data down to its rangetable.
	 * The checks will actually be done against the *OLD* entry therein.
307
	 */
308 309 310 311
	subrte = rt_fetch(PRS2_OLD_VARNO, rule_action->rtable);
	Assert(subrte->relid == relation->rd_id);
	subrte->checkForRead = rte->checkForRead;
	subrte->checkForWrite = rte->checkForWrite;
312

313 314
	rte->checkForRead = false;	/* no permission check on subquery itself */
	rte->checkForWrite = false;
315

316
	/*
317
	 * FOR UPDATE of view?
318
	 */
319
	if (intMember(rt_index, parsetree->rowMarks))
320
	{
B
Bruce Momjian 已提交
321

322
		/*
323 324 325
		 * Remove the view from the list of rels that will actually be
		 * marked FOR UPDATE by the executor.  It will still be access-
		 * checked for write access, though.
326
		 */
327
		parsetree->rowMarks = lremovei(rt_index, parsetree->rowMarks);
B
Bruce Momjian 已提交
328 329

		/*
330
		 * Set up the view's referenced tables as if FOR UPDATE.
331
		 */
332
		markQueryForUpdate(rule_action, true);
333 334
	}

335
	return parsetree;
336 337
}

338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
/*
 * Recursively mark all relations used by a view as FOR UPDATE.
 *
 * This may generate an invalid query, eg if some sub-query uses an
 * aggregate.  We leave it to the planner to detect that.
 *
 * NB: this must agree with the parser's transformForUpdate() routine.
 */
static void
markQueryForUpdate(Query *qry, bool skipOldNew)
{
	Index		rti = 0;
	List	   *l;

	foreach(l, qry->rtable)
	{
		RangeTblEntry *rte = (RangeTblEntry *) lfirst(l);

		rti++;

		/* Ignore OLD and NEW entries if we are at top level of view */
		if (skipOldNew &&
			(rti == PRS2_OLD_VARNO || rti == PRS2_NEW_VARNO))
			continue;

		if (rte->subquery)
		{
			/* FOR UPDATE of subquery is propagated to subquery's rels */
			markQueryForUpdate(rte->subquery, false);
		}
		else
		{
			if (!intMember(rti, qry->rowMarks))
				qry->rowMarks = lappendi(qry->rowMarks, rti);
			rte->checkForWrite = true;
		}
	}
}

377

378
/*
379 380 381
 * fireRIRonSubLink -
 *	Apply fireRIRrules() to each SubLink (subselect in expression) found
 *	in the given tree.
382 383
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
384
 * SubLink nodes in-place.	It is caller's responsibility to ensure that
385
 * no unwanted side-effects occur!
386 387 388 389
 *
 * 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.
390 391
 */
static bool
392
fireRIRonSubLink(Node *node, void *context)
393 394
{
	if (node == NULL)
395 396
		return false;
	if (IsA(node, SubLink))
B
Bruce Momjian 已提交
397
	{
398 399 400
		SubLink    *sub = (SubLink *) node;

		/* Do what we came for */
401 402
		sub->subselect = (Node *) fireRIRrules((Query *) (sub->subselect));
		/* Fall through to process lefthand args of SubLink */
403
	}
B
Bruce Momjian 已提交
404

405 406
	/*
	 * Do NOT recurse into Query nodes, because fireRIRrules already
407
	 * processed subselects of subselects for us.
408
	 */
409
	return expression_tree_walker(node, fireRIRonSubLink,
410
								  (void *) context);
411 412 413 414 415 416 417 418 419 420
}


/*
 * fireRIRrules -
 *	Apply all RIR rules on each rangetable entry in a query
 */
static Query *
fireRIRrules(Query *parsetree)
{
B
Bruce Momjian 已提交
421
	int			rt_index;
422

423 424 425
	/*
	 * don't try to convert this into a foreach loop, because rtable list
	 * can get changed each time through...
426
	 */
427
	rt_index = 0;
B
Bruce Momjian 已提交
428 429
	while (rt_index < length(parsetree->rtable))
	{
430 431 432 433 434 435 436 437 438 439
		RangeTblEntry *rte;
		Relation	rel;
		List	   *locks;
		RuleLock   *rules;
		RewriteRule *rule;
		LOCKMODE	lockmode;
		bool		relIsUsed;
		int			i;
		List	   *l;

440 441
		++rt_index;

442
		rte = rt_fetch(rt_index, parsetree->rtable);
443

444 445 446 447 448 449 450 451 452 453 454
		/*
		 * A subquery RTE can't have associated rules, so there's nothing
		 * to do to this level of the query, but we must recurse into the
		 * subquery to expand any rule references in it.
		 */
		if (rte->subquery)
		{
			rte->subquery = fireRIRrules(rte->subquery);
			continue;
		}

455
		/*
456 457 458
		 * 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
459 460
		 * part of the join set (a source table), or is referenced by any
		 * Var nodes, or is the result table.
461
		 */
462 463 464
		relIsUsed = rangeTableEntry_used((Node *) parsetree, rt_index, 0);

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

467
		/*
B
Bruce Momjian 已提交
468 469 470 471 472 473
		 * This may well be the first access to the relation during the
		 * current statement (it will be, if this Query was extracted from
		 * a rule or somehow got here other than via the parser).
		 * Therefore, grab the appropriate lock type for the relation, and
		 * do not release it until end of transaction.	This protects the
		 * rewriter and planner against schema changes mid-query.
474
		 *
B
Bruce Momjian 已提交
475 476 477 478
		 * If the relation is the query's result relation, then
		 * RewriteQuery() already got the right lock on it, so we need no
		 * additional lock. Otherwise, check to see if the relation is
		 * accessed FOR UPDATE or not.
479 480 481 482 483 484 485 486 487 488
		 */
		if (rt_index == parsetree->resultRelation)
			lockmode = NoLock;
		else if (intMember(rt_index, parsetree->rowMarks))
			lockmode = RowShareLock;
		else
			lockmode = AccessShareLock;

		rel = heap_openr(rte->relname, lockmode);

489 490 491 492 493 494 495 496 497 498 499 500 501
		/*
		 * Check to see if relation's OID matches the RTE.  If not, the RTE
		 * actually refers to an older relation that had the same name.
		 * Eventually we might want to reparse the referencing rule, but
		 * for now all we can do is punt.
		 */
		if (RelationGetRelid(rel) != rte->relid)
			elog(ERROR, "Relation \"%s\" with OID %u no longer exists",
				 rte->relname, rte->relid);

		/*
		 * Collect the RIR rules that we must apply
		 */
502 503
		rules = rel->rd_rules;
		if (rules == NULL)
B
Bruce Momjian 已提交
504
		{
505
			heap_close(rel, NoLock);
506 507
			continue;
		}
508
		locks = NIL;
B
Bruce Momjian 已提交
509 510
		for (i = 0; i < rules->numLocks; i++)
		{
511 512 513
			rule = rules->rules[i];
			if (rule->event != CMD_SELECT)
				continue;
B
Bruce Momjian 已提交
514

515 516 517
			if (rule->attrno > 0)
			{
				/* per-attr rule; do we need it? */
518
				if (!attribute_used((Node *) parsetree, rt_index,
519
									rule->attrno, 0))
520 521
					continue;
			}
522 523 524 525 526 527 528

			locks = lappend(locks, rule);
		}

		/*
		 * Now apply them
		 */
B
Bruce Momjian 已提交
529 530
		foreach(l, locks)
		{
531 532
			rule = lfirst(l);

533
			parsetree = ApplyRetrieveRule(parsetree,
534
										  rule,
535
										  rt_index,
536
										  rule->attrno == -1,
537
										  rel,
538
										  relIsUsed);
539 540
		}

541
		heap_close(rel, NoLock);
542 543
	}

544 545 546 547
	/*
	 * Recurse into sublink subqueries, too.
	 */
	if (parsetree->hasSubLinks)
548
		query_tree_walker(parsetree, fireRIRonSubLink, NULL,
B
Bruce Momjian 已提交
549
						false /* already handled the ones in rtable */ );
550

551
	/*
B
Bruce Momjian 已提交
552 553 554 555 556
	 * If the query was marked having aggregates, check if this is still
	 * true after rewriting.  Ditto for sublinks.  Note there should be no
	 * aggs in the qual at this point.	(Does this code still do anything
	 * useful?	The view-becomes-subselect-in-FROM approach doesn't look
	 * like it could remove aggs or sublinks...)
557 558 559 560 561 562 563 564
	 */
	if (parsetree->hasAggs)
	{
		parsetree->hasAggs = checkExprHasAggs((Node *) parsetree);
		if (parsetree->hasAggs)
			if (checkExprHasAggs((Node *) parsetree->jointree))
				elog(ERROR, "fireRIRrules: failed to remove aggs from qual");
	}
565
	if (parsetree->hasSubLinks)
566
		parsetree->hasSubLinks = checkExprHasSubLink((Node *) parsetree);
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
	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);
594
		}
595 596
		else
			regular = lappend(regular, rule_lock);
597
	}
598
	return nconc(nconc(regular, instead_qualified), instead_rules);
599 600
}

601

602 603 604 605 606
/*
 * Modify the given query by adding 'AND NOT rule_qual' to its qualification.
 * This is used to generate suitable "else clauses" for conditional INSTEAD
 * rules.
 *
B
Bruce Momjian 已提交
607
 * The rule_qual may contain references to OLD or NEW.	OLD references are
608 609 610 611 612
 * replaced by references to the specified rt_index (the relation that the
 * rule applies to).  NEW references are only possible for INSERT and UPDATE
 * queries on the relation itself, and so they should be replaced by copies
 * of the related entries in the query's own targetlist.
 */
613
static Query *
614 615
CopyAndAddQual(Query *parsetree,
			   Node *rule_qual,
616 617
			   int rt_index,
			   CmdType event)
618
{
619
	Query	   *new_tree = (Query *) copyObject(parsetree);
620 621 622 623 624 625 626 627 628 629 630 631 632
	Node	   *new_qual = (Node *) copyObject(rule_qual);

	/* Fix references to OLD */
	ChangeVarNodes(new_qual, PRS2_OLD_VARNO, rt_index, 0);
	/* Fix references to NEW */
	if (event == CMD_INSERT || event == CMD_UPDATE)
		new_qual = ResolveNew(new_qual,
							  PRS2_NEW_VARNO,
							  0,
							  parsetree->targetList,
							  event,
							  rt_index);
	/* And attach the fixed qual */
633 634 635
	AddNotQual(new_tree, new_qual);

	return new_tree;
636 637 638
}


639

640
/*
641
 *	fireRules -
M
 
Marc G. Fournier 已提交
642 643 644 645 646
 *	   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.
647
 *
M
 
Marc G. Fournier 已提交
648
 *	   remember: reality is for dead birds -- glass
649 650
 *
 */
651
static List *
652
fireRules(Query *parsetree,
653 654
		  int rt_index,
		  CmdType event,
655 656 657
		  bool *instead_flag,
		  List *locks,
		  List **qual_products)
658
{
659 660
	List	   *results = NIL;
	List	   *i;
661 662 663

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

M
 
Marc G. Fournier 已提交
666
	locks = orderRules(locks);	/* real instead rules last */
667

668 669
	foreach(i, locks)
	{
670
		RewriteRule *rule_lock = (RewriteRule *) lfirst(i);
671
		Node	   *event_qual;
672 673
		List	   *actions;
		List	   *r;
674 675 676 677 678

		/* multiple rule action time */
		*instead_flag = rule_lock->isInstead;
		event_qual = rule_lock->qual;
		actions = rule_lock->actions;
679

680 681 682
		if (event_qual != NULL && *instead_flag)
		{
			Query	   *qual_product;
M
 
Marc G. Fournier 已提交
683

684 685 686 687 688 689 690 691 692
			/*
			 * If there are instead rules with qualifications, the
			 * original query is still performed. But all the negated rule
			 * qualifications of the instead rules are added so it does
			 * its actions only 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.
M
 
Marc G. Fournier 已提交
693
			 */
694
			if (*qual_products == NIL)
M
 
Marc G. Fournier 已提交
695
				qual_product = parsetree;
696
			else
697
				qual_product = (Query *) lfirst(*qual_products);
M
 
Marc G. Fournier 已提交
698

699 700 701 702 703
			qual_product = CopyAndAddQual(qual_product,
										  event_qual,
										  rt_index,
										  event);

704
			*qual_products = makeList1(qual_product);
M
 
Marc G. Fournier 已提交
705 706
		}

707 708
		foreach(r, actions)
		{
709
			Query	   *rule_action = lfirst(r);
710
			RewriteInfo *info;
711

M
 
Marc G. Fournier 已提交
712 713 714
			if (rule_action->commandType == CMD_NOTHING)
				continue;

715
			info = gatherRewriteMeta(parsetree, rule_action, event_qual,
716
									 rt_index, event, *instead_flag);
717 718 719 720 721 722 723 724 725 726 727 728 729 730

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

			results = lappend(results, info->rule_action);

			pfree(info);
		}
M
 
Marc G. Fournier 已提交
731

732 733 734
		/*
		 * If this was an unqualified instead rule, throw away an
		 * eventually saved 'default' parsetree
M
 
Marc G. Fournier 已提交
735
		 */
736
		if (event_qual == NULL && *instead_flag)
M
 
Marc G. Fournier 已提交
737
			*qual_products = NIL;
738 739
	}
	return results;
740 741
}

M
 
Marc G. Fournier 已提交
742 743


744
static List *
745
RewriteQuery(Query *parsetree, bool *instead_flag, List **qual_products)
746
{
747
	CmdType		event;
B
Bruce Momjian 已提交
748
	List	   *product_queries = NIL;
749
	int			result_relation;
B
Bruce Momjian 已提交
750
	RangeTblEntry *rt_entry;
751 752
	Relation	rt_entry_relation;
	RuleLock   *rt_entry_locks;
753

754 755 756 757
	Assert(parsetree != NULL);

	event = parsetree->commandType;

758
	/*
B
Bruce Momjian 已提交
759 760
	 * SELECT rules are handled later when we have all the queries that
	 * should get executed
761 762 763 764 765 766 767
	 */
	if (event == CMD_SELECT)
		return NIL;

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

771
	/*
B
Bruce Momjian 已提交
772
	 * the statement is an update, insert or delete - fire rules on it.
773
	 */
774
	result_relation = parsetree->resultRelation;
775
	Assert(result_relation != 0);
776
	rt_entry = rt_fetch(result_relation, parsetree->rtable);
777 778

	/*
B
Bruce Momjian 已提交
779 780 781 782 783 784
	 * This may well be the first access to the result relation during the
	 * current statement (it will be, if this Query was extracted from a
	 * rule or somehow got here other than via the parser). Therefore,
	 * grab the appropriate lock type for a result relation, and do not
	 * release it until end of transaction.  This protects the rewriter
	 * and planner against schema changes mid-query.
785 786 787
	 */
	rt_entry_relation = heap_openr(rt_entry->relname, RowExclusiveLock);

788 789 790 791 792 793 794 795 796 797 798 799 800
	/*
	 * Check to see if relation's OID matches the RTE.  If not, the RTE
	 * actually refers to an older relation that had the same name.
	 * Eventually we might want to reparse the referencing rule, but
	 * for now all we can do is punt.
	 */
	if (RelationGetRelid(rt_entry_relation) != rt_entry->relid)
		elog(ERROR, "Relation \"%s\" with OID %u no longer exists",
			 rt_entry->relname, rt_entry->relid);

	/*
	 * Collect and apply the appropriate rules.
	 */
801
	rt_entry_locks = rt_entry_relation->rd_rules;
M
 
Marc G. Fournier 已提交
802

803
	if (rt_entry_locks != NULL)
804
	{
805 806
		List	   *locks = matchLocks(event, rt_entry_locks,
									   result_relation, parsetree);
807

808
		product_queries = fireRules(parsetree,
B
Bruce Momjian 已提交
809 810 811 812 813
									result_relation,
									event,
									instead_flag,
									locks,
									qual_products);
814
	}
815

B
Bruce Momjian 已提交
816
	heap_close(rt_entry_relation, NoLock);		/* keep lock! */
817

818
	return product_queries;
819 820
}

821

822 823
/*
 * to avoid infinite recursion, we restrict the number of times a query
824
 * can be rewritten. Detecting cycles is left for the reader as an exercise.
825 826
 */
#ifndef REWRITE_INVOKE_MAX
827
#define REWRITE_INVOKE_MAX		10
828 829
#endif

830
static int	numQueryRewriteInvoked = 0;
831 832 833

/*
 * deepRewriteQuery -
834
 *	  rewrites the query and apply the rules again on the queries rewritten
835
 */
836
static List *
837
deepRewriteQuery(Query *parsetree)
838
{
839 840
	List	   *n;
	List	   *rewritten = NIL;
841
	List	   *result;
842 843
	bool		instead;
	List	   *qual_products = NIL;
844 845 846

	if (++numQueryRewriteInvoked > REWRITE_INVOKE_MAX)
	{
847
		elog(ERROR, "query rewritten %d times, may contain cycles",
848 849 850 851 852
			 numQueryRewriteInvoked - 1);
	}

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

854 855
	foreach(n, result)
	{
856
		Query	   *pt = lfirst(n);
857
		List	   *newstuff;
858 859 860 861 862

		newstuff = deepRewriteQuery(pt);
		if (newstuff != NIL)
			rewritten = nconc(rewritten, newstuff);
	}
M
 
Marc G. Fournier 已提交
863

864 865 866
	/*
	 * qual_products are the original query with the negated rule
	 * qualification of an instead rule
M
 
Marc G. Fournier 已提交
867
	 */
868 869 870
	if (qual_products != NIL)
		rewritten = nconc(rewritten, qual_products);

871 872 873 874 875 876 877
	/*
	 * The original query is appended last (if no "instead" rule) 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.
M
 
Marc G. Fournier 已提交
878 879 880 881
	 */
	if (!instead)
		rewritten = lappend(rewritten, parsetree);

882 883
	return rewritten;
}
884 885 886


/*
887
 * QueryRewriteOne -
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
 *	  rewrite one query
 */
static List *
QueryRewriteOne(Query *parsetree)
{
	numQueryRewriteInvoked = 0;

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


/*
903 904 905 906 907 908 909
 * 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.
910
 */
911 912
List *
QueryRewrite(Query *parsetree)
913
{
B
Bruce Momjian 已提交
914 915 916
	List	   *querylist;
	List	   *results = NIL;
	List	   *l;
917 918 919 920 921 922 923 924 925

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

	/*
926
	 * Step 2
927 928 929
	 *
	 * Apply all the RIR rules on each query
	 */
B
Bruce Momjian 已提交
930 931
	foreach(l, querylist)
	{
B
Bruce Momjian 已提交
932
		Query	   *query = (Query *) lfirst(l);
B
Bruce Momjian 已提交
933

934
		query = fireRIRrules(query);
935

B
Bruce Momjian 已提交
936
		/*
937
		 * If the query target was rewritten as a view, complain.
B
Bruce Momjian 已提交
938
		 */
939
		if (query->resultRelation)
B
Bruce Momjian 已提交
940
		{
941 942
			RangeTblEntry *rte = rt_fetch(query->resultRelation,
										  query->rtable);
B
Bruce Momjian 已提交
943

944
			if (rte->subquery)
B
Bruce Momjian 已提交
945
			{
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
				switch (query->commandType)
				{
					case CMD_INSERT:
						elog(ERROR, "Cannot insert into a view without an appropriate rule");
						break;
					case CMD_UPDATE:
						elog(ERROR, "Cannot update a view without an appropriate rule");
						break;
					case CMD_DELETE:
						elog(ERROR, "Cannot delete from a view without an appropriate rule");
						break;
					default:
						elog(ERROR, "QueryRewrite: unexpected commandType %d",
							 (int) query->commandType);
						break;
				}
B
Bruce Momjian 已提交
962 963 964
			}
		}

965
		results = lappend(results, query);
B
Bruce Momjian 已提交
966
	}
967

968
	return results;
B
Hi!  
Bruce Momjian 已提交
969
}