rewriteHandler.c 25.5 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.94 2001/06/12 18:54:22 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
	/*
	 * Adjust rule action and qual to offset its varnos, so that we can
85
	 * merge its rtable with the main parsetree's rtable.
86
	 *
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
	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);

	/*
102 103 104 105 106 107
	 * Generate expanded rtable consisting of main parsetree's rtable
	 * plus rule action's rtable; this becomes the complete rtable for the
	 * rule action.  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.
108
	 *
109 110 111
	 * NOTE: because planner will destructively alter rtable, we must ensure
	 * that rule action's rtable is separate and shares no substructure with
	 * the main rtable.  Hence do a deep copy here.
112
	 */
113 114
	sub_action->rtable = nconc((List *) copyObject(parsetree->rtable),
							   sub_action->rtable);
115

116 117
	/*
	 * Each rule action's jointree should be the main parsetree's jointree
B
Bruce Momjian 已提交
118 119 120 121 122 123 124 125 126
	 * 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.
127 128 129
	 *
	 * As above, the action's jointree must not share substructure with
	 * the main parsetree's.
130
	 */
131
	if (sub_action->jointree != NULL)
132
	{
B
Bruce Momjian 已提交
133 134
		bool		keeporig;
		List	   *newjointree;
135

B
Bruce Momjian 已提交
136 137
		keeporig = (!rangeTableEntry_used((Node *) sub_action->jointree,
										  rt_index, 0)) &&
138
			(rangeTableEntry_used(info->rule_qual, rt_index, 0) ||
B
Bruce Momjian 已提交
139
		  rangeTableEntry_used(parsetree->jointree->quals, rt_index, 0));
140
		newjointree = adjustJoinTreeList(parsetree, !keeporig, rt_index);
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
		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 已提交
157 158 159
	 * 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
160 161 162 163 164 165
	 */
	AddQual(sub_action, info->rule_qual);

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

	/*
B
Bruce Momjian 已提交
166 167
	 * Rewrite new.attribute w/ right hand side of target-list entry for
	 * appropriate field name in insert/update.
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
	 *
	 * 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;
185
	}
186

187
	return info;
188 189
}

190
/*
191 192 193 194
 * 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
195 196
 * of the join).  Returns modified jointree list --- this is a separate copy
 * sharing no nodes with the original.
197
 */
198
static List *
199
adjustJoinTreeList(Query *parsetree, bool removert, int rt_index)
200
{
201
	List	   *newjointree = copyObject(parsetree->jointree->fromlist);
202
	List	   *jjt;
203

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

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

220

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

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

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

244
	nlocks = rulelocks->numLocks;
245

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

250
		if (oneLock->event == event)
251
		{
252 253 254 255 256 257
			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);
258
		}
259
	}
260 261

	return real_locks;
262 263
}

264

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

277 278 279 280
	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 已提交
281
	if (!relation_level)
282
		elog(ERROR, "ApplyRetrieveRule: can't handle per-attribute ON SELECT rule");
283

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

290
	rule_action = fireRIRrules(rule_action);
291

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

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

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

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

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

323
		/*
324 325 326
		 * 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.
327
		 */
328
		parsetree->rowMarks = lremovei(rt_index, parsetree->rowMarks);
B
Bruce Momjian 已提交
329 330

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

336
	return parsetree;
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 377
/*
 * 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;
		}
	}
}

378

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

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

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


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

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

441 442
		++rt_index;

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

445 446 447 448 449 450 451 452 453 454 455
		/*
		 * 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;
		}

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

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

468
		/*
B
Bruce Momjian 已提交
469 470 471 472 473 474
		 * 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.
475
		 *
B
Bruce Momjian 已提交
476 477 478 479
		 * 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.
480 481 482 483 484 485 486 487 488 489
		 */
		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);

490 491 492 493 494 495 496 497 498 499 500 501 502
		/*
		 * 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
		 */
503 504
		rules = rel->rd_rules;
		if (rules == NULL)
B
Bruce Momjian 已提交
505
		{
506
			heap_close(rel, NoLock);
507 508
			continue;
		}
509
		locks = NIL;
B
Bruce Momjian 已提交
510 511
		for (i = 0; i < rules->numLocks; i++)
		{
512 513 514
			rule = rules->rules[i];
			if (rule->event != CMD_SELECT)
				continue;
B
Bruce Momjian 已提交
515

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

			locks = lappend(locks, rule);
		}

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

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

542
		heap_close(rel, NoLock);
543 544
	}

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

552
	/*
B
Bruce Momjian 已提交
553 554 555 556 557
	 * 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...)
558 559 560 561 562 563 564 565
	 */
	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");
	}
566
	if (parsetree->hasSubLinks)
567
		parsetree->hasSubLinks = checkExprHasSubLink((Node *) parsetree);
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 594
	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);
595
		}
596 597
		else
			regular = lappend(regular, rule_lock);
598
	}
599
	return nconc(nconc(regular, instead_qualified), instead_rules);
600 601
}

602

603 604 605 606 607
/*
 * 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 已提交
608
 * The rule_qual may contain references to OLD or NEW.	OLD references are
609 610 611 612 613
 * 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.
 */
614
static Query *
615 616
CopyAndAddQual(Query *parsetree,
			   Node *rule_qual,
617 618
			   int rt_index,
			   CmdType event)
619
{
620
	Query	   *new_tree = (Query *) copyObject(parsetree);
621 622 623 624 625 626 627 628 629 630 631 632 633
	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 */
634 635 636
	AddNotQual(new_tree, new_qual);

	return new_tree;
637 638 639
}


640

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

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

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

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

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

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

685 686 687 688 689 690 691 692 693
			/*
			 * 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 已提交
694
			 */
695
			if (*qual_products == NIL)
M
 
Marc G. Fournier 已提交
696
				qual_product = parsetree;
697
			else
698
				qual_product = (Query *) lfirst(*qual_products);
M
 
Marc G. Fournier 已提交
699

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

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

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

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

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

			/* 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 已提交
732

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

M
 
Marc G. Fournier 已提交
743 744


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

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

	event = parsetree->commandType;

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

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

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

	/*
B
Bruce Momjian 已提交
780 781 782 783 784 785
	 * 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.
786 787 788
	 */
	rt_entry_relation = heap_openr(rt_entry->relname, RowExclusiveLock);

789 790 791 792 793 794 795 796 797 798 799 800 801
	/*
	 * 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.
	 */
802
	rt_entry_locks = rt_entry_relation->rd_rules;
M
 
Marc G. Fournier 已提交
803

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

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

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

819
	return product_queries;
820 821
}

822

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

831
static int	numQueryRewriteInvoked = 0;
832 833 834

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

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

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

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

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

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

872 873 874 875 876 877 878
	/*
	 * 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 已提交
879 880 881 882
	 */
	if (!instead)
		rewritten = lappend(rewritten, parsetree);

883 884
	return rewritten;
}
885 886 887


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

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


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

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

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

935
		query = fireRIRrules(query);
936

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

945
			if (rte->subquery)
B
Bruce Momjian 已提交
946
			{
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
				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 已提交
963 964 965
			}
		}

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

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