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.93 2001/05/03 17:47:49 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
	subrte->checkAsUser = rte->checkAsUser;
313

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

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

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

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

337
	return parsetree;
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 378
/*
 * 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;
		}
	}
}

379

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

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

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


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

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

442 443
		++rt_index;

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

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

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

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

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

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

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

			locks = lappend(locks, rule);
		}

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

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

543
		heap_close(rel, NoLock);
544 545
	}

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

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

603

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

	return new_tree;
638 639 640
}


641

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

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

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

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

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

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

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

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

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

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

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

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

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

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

M
 
Marc G. Fournier 已提交
744 745


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

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

	event = parsetree->commandType;

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

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

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

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

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

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

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

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

820
	return product_queries;
821 822
}

823

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

832
static int	numQueryRewriteInvoked = 0;
833 834 835

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

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

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

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

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

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

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

884 885
	return rewritten;
}
886 887 888


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

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


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

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

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

936
		query = fireRIRrules(query);
937

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

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

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

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