rewriteHandler.c 69.5 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * rewriteHandler.c
4 5 6 7 8
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
9
 *	  $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.49 1999/07/13 21:17:35 momjian Exp $
10 11 12
 *
 *-------------------------------------------------------------------------
 */
M
Marc G. Fournier 已提交
13
#include <string.h>
14 15 16 17 18
#include "postgres.h"
#include "miscadmin.h"
#include "utils/palloc.h"
#include "utils/elog.h"
#include "utils/rel.h"
19
#include "nodes/pg_list.h"
20
#include "nodes/primnodes.h"
21
#include "nodes/relation.h"
22

23
#include "parser/parsetree.h"	/* for parsetree manipulation */
M
 
Marc G. Fournier 已提交
24
#include "parser/parse_relation.h"
25 26
#include "nodes/parsenodes.h"

B
Hi!  
Bruce Momjian 已提交
27 28 29 30
#include "parser/parse_node.h"
#include "parser/parse_target.h"

#include "parser/analyze.h"
31
#include "optimizer/clauses.h"
B
Hi!  
Bruce Momjian 已提交
32 33
#include "optimizer/prep.h"

34
#include "rewrite/rewriteSupport.h"
35 36 37 38 39 40 41
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "rewrite/locks.h"

#include "commands/creatinh.h"
#include "access/heapam.h"

42
#include "utils/lsyscache.h"
M
Marc G. Fournier 已提交
43 44
#include "utils/syscache.h"
#include "utils/acl.h"
45
#include "catalog/pg_shadow.h"
46 47 48 49 50 51 52 53 54 55 56
#include "catalog/pg_type.h"


static RewriteInfo *gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
				  int rt_index,
				  CmdType event,
				  bool *instead_flag);
static bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up);
static bool attribute_used(Node *node, int rt_index, int attno, int sublevels_up);
B
Bruce Momjian 已提交
57 58 59 60 61
static void modifyAggrefUplevel(Node *node);
static void modifyAggrefChangeVarnodes(Node **nodePtr, int rt_index, int new_index, int sublevels_up);
static void modifyAggrefDropQual(Node **nodePtr, Node *orignode, Expr *expr);
static SubLink *modifyAggrefMakeSublink(Expr *origexp, Query *parsetree);
static void modifyAggrefQual(Node **nodePtr, Query *parsetree);
62
static bool checkQueryHasAggs(Node *node);
63 64 65
static bool checkQueryHasAggs_walker(Node *node, void *context);
static bool checkQueryHasSubLink(Node *node);
static bool checkQueryHasSubLink_walker(Node *node, void *context);
66
static Query *fireRIRrules(Query *parsetree);
67 68 69 70 71 72
static Query *Except_Intersect_Rewrite(Query *parsetree);
static void check_targetlists_are_compatible(List *prev_target,
											 List *current_target);
static void create_intersect_list(Node *ptr, List **intersect_list);
static Node *intersect_tree_analyze(Node *tree, Node *first_select,
									Node *parsetree);
73 74 75

/*
 * gatherRewriteMeta -
76 77 78
 *	  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
79 80
 */
static RewriteInfo *
81 82 83
gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
84 85
				  int rt_index,
				  CmdType event,
86
				  bool *instead_flag)
87
{
88 89 90
	RewriteInfo *info;
	int			rt_length;
	int			result_reln;
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

	info = (RewriteInfo *) palloc(sizeof(RewriteInfo));
	info->rt_index = rt_index;
	info->event = event;
	info->instead_flag = *instead_flag;
	info->rule_action = (Query *) copyObject(rule_action);
	info->rule_qual = (Node *) copyObject(rule_qual);
	if (info->rule_action == NULL)
		info->nothing = TRUE;
	else
	{
		info->nothing = FALSE;
		info->action = info->rule_action->commandType;
		info->current_varno = rt_index;
		info->rt = parsetree->rtable;
		rt_length = length(info->rt);
B
Bruce Momjian 已提交
107
		info->rt = nconc(info->rt, copyObject(info->rule_action->rtable));
108 109

		info->new_varno = PRS2_NEW_VARNO + rt_length;
B
Bruce Momjian 已提交
110 111 112
		OffsetVarNodes(info->rule_action->qual, rt_length, 0);
		OffsetVarNodes((Node *) info->rule_action->targetList, rt_length, 0);
		OffsetVarNodes(info->rule_qual, rt_length, 0);
113
		ChangeVarNodes((Node *) info->rule_action->qual,
114
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
115
		ChangeVarNodes((Node *) info->rule_action->targetList,
116
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
117
		ChangeVarNodes(info->rule_qual,
118
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
119 120 121 122 123 124 125 126

		/*
		 * bug here about replace CURRENT  -- sort of replace current is
		 * deprecated now so this code shouldn't really need to be so
		 * clutzy but.....
		 */
		if (info->action != CMD_SELECT)
		{						/* i.e update XXXXX */
127
			int			new_result_reln = 0;
128 129 130 131

			result_reln = info->rule_action->resultRelation;
			switch (result_reln)
			{
132 133 134 135 136 137 138
				case PRS2_CURRENT_VARNO:
					new_result_reln = rt_index;
					break;
				case PRS2_NEW_VARNO:	/* XXX */
				default:
					new_result_reln = result_reln + rt_length;
					break;
139 140 141 142 143
			}
			info->rule_action->resultRelation = new_result_reln;
		}
	}
	return info;
144 145 146 147
}


/*
148 149 150
 * rangeTableEntry_used -
 *	we need to process a RTE for RIR rules only if it is
 *	referenced somewhere in var nodes of the query.
151
 */
152 153
static bool
rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
154
{
155 156
	if (node == NULL)
		return FALSE;
157

B
Bruce Momjian 已提交
158 159
	switch (nodeTag(node))
	{
160 161
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
162
				TargetEntry *tle = (TargetEntry *) node;
163

164
				return rangeTableEntry_used(
B
Bruce Momjian 已提交
165 166 167
											(Node *) (tle->expr),
											rt_index,
											sublevels_up);
168 169
			}
			break;
170

B
Bruce Momjian 已提交
171
		case T_Aggref:
172
			{
B
Bruce Momjian 已提交
173
				Aggref	   *aggref = (Aggref *) node;
174

175
				return rangeTableEntry_used(
B
Bruce Momjian 已提交
176 177 178
											(Node *) (aggref->target),
											rt_index,
											sublevels_up);
179 180
			}
			break;
181

182
		case T_GroupClause:
183
			return FALSE;
184

185 186
		case T_Expr:
			{
B
Bruce Momjian 已提交
187
				Expr	   *exp = (Expr *) node;
188 189

				return rangeTableEntry_used(
B
Bruce Momjian 已提交
190 191 192
											(Node *) (exp->args),
											rt_index,
											sublevels_up);
193 194
			}
			break;
195

196 197
		case T_Iter:
			{
B
Bruce Momjian 已提交
198
				Iter	   *iter = (Iter *) node;
199

200
				return rangeTableEntry_used(
B
Bruce Momjian 已提交
201 202 203
											(Node *) (iter->iterexpr),
											rt_index,
											sublevels_up);
204 205
			}
			break;
206

207 208
		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
209
				ArrayRef   *ref = (ArrayRef *) node;
210 211

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
212 213 214
										 (Node *) (ref->refupperindexpr),
										 rt_index,
										 sublevels_up))
215
					return TRUE;
B
Bruce Momjian 已提交
216

217
				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
218 219 220
										 (Node *) (ref->reflowerindexpr),
										 rt_index,
										 sublevels_up))
221
					return TRUE;
B
Bruce Momjian 已提交
222

223
				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
224 225 226
										 (Node *) (ref->refexpr),
										 rt_index,
										 sublevels_up))
227
					return TRUE;
B
Bruce Momjian 已提交
228

229
				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
230 231 232
										 (Node *) (ref->refassgnexpr),
										 rt_index,
										 sublevels_up))
233
					return TRUE;
B
Bruce Momjian 已提交
234

235 236 237 238 239 240
				return FALSE;
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
241
				Var		   *var = (Var *) node;
242 243 244 245 246 247 248 249 250 251

				if (var->varlevelsup == sublevels_up)
					return var->varno == rt_index;
				else
					return FALSE;
			}
			break;

		case T_Param:
			return FALSE;
252

253 254 255 256
		case T_Const:
			return FALSE;

		case T_List:
257
			{
B
Bruce Momjian 已提交
258
				List	   *l;
259

B
Bruce Momjian 已提交
260 261
				foreach(l, (List *) node)
				{
262
					if (rangeTableEntry_used(
B
Bruce Momjian 已提交
263 264 265
											 (Node *) lfirst(l),
											 rt_index,
											 sublevels_up))
266 267 268
						return TRUE;
				}
				return FALSE;
269
			}
270 271 272
			break;

		case T_SubLink:
273
			{
B
Bruce Momjian 已提交
274
				SubLink    *sub = (SubLink *) node;
275 276

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
277 278 279
										 (Node *) (sub->lefthand),
										 rt_index,
										 sublevels_up))
280 281 282
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
283 284 285
										 (Node *) (sub->subselect),
										 rt_index,
										 sublevels_up + 1))
286 287 288
					return TRUE;

				return FALSE;
289
			}
290 291
			break;

T
Thomas G. Lockhart 已提交
292 293
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
294
				CaseExpr   *exp = (CaseExpr *) node;
T
Thomas G. Lockhart 已提交
295 296

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
297 298 299
										 (Node *) (exp->args),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
300 301 302
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
303 304 305
										 (Node *) (exp->defresult),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
306 307 308 309 310 311 312 313
					return TRUE;

				return FALSE;
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
314
				CaseWhen   *when = (CaseWhen *) node;
T
Thomas G. Lockhart 已提交
315 316

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
317 318 319
										 (Node *) (when->expr),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
320 321 322
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
323 324 325
										 (Node *) (when->result),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
326 327 328 329 330 331
					return TRUE;

				return FALSE;
			}
			break;

332
		case T_Query:
333
			{
B
Bruce Momjian 已提交
334
				Query	   *qry = (Query *) node;
335 336

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
337 338 339
										 (Node *) (qry->targetList),
										 rt_index,
										 sublevels_up))
340 341 342
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
343 344 345
										 (Node *) (qry->qual),
										 rt_index,
										 sublevels_up))
346 347 348
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
349 350 351
										 (Node *) (qry->havingQual),
										 rt_index,
										 sublevels_up))
352 353 354
					return TRUE;

				return FALSE;
355
			}
356 357 358 359 360 361 362 363
			break;

		default:
			elog(NOTICE, "unknown node tag %d in rangeTableEntry_used()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


364
	}
365 366

	return FALSE;
367
}
368 369


370 371 372 373
/*
 * attribute_used -
 *	Check if a specific attribute number of a RTE is used
 *	somewhere in the query
374
 */
375 376
static bool
attribute_used(Node *node, int rt_index, int attno, int sublevels_up)
377
{
378 379
	if (node == NULL)
		return FALSE;
380

B
Bruce Momjian 已提交
381 382
	switch (nodeTag(node))
	{
383 384
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
385
				TargetEntry *tle = (TargetEntry *) node;
386

387
				return attribute_used(
B
Bruce Momjian 已提交
388 389 390 391
									  (Node *) (tle->expr),
									  rt_index,
									  attno,
									  sublevels_up);
392 393
			}
			break;
394

B
Bruce Momjian 已提交
395
		case T_Aggref:
396
			{
B
Bruce Momjian 已提交
397
				Aggref	   *aggref = (Aggref *) node;
398

399
				return attribute_used(
B
Bruce Momjian 已提交
400 401 402 403
									  (Node *) (aggref->target),
									  rt_index,
									  attno,
									  sublevels_up);
404 405
			}
			break;
M
Marc G. Fournier 已提交
406

407
		case T_GroupClause:
408
			return FALSE;
409

410 411
		case T_Expr:
			{
B
Bruce Momjian 已提交
412
				Expr	   *exp = (Expr *) node;
413

414
				return attribute_used(
B
Bruce Momjian 已提交
415 416 417 418
									  (Node *) (exp->args),
									  rt_index,
									  attno,
									  sublevels_up);
419 420
			}
			break;
421

422 423
		case T_Iter:
			{
B
Bruce Momjian 已提交
424
				Iter	   *iter = (Iter *) node;
425

426
				return attribute_used(
B
Bruce Momjian 已提交
427 428 429 430
									  (Node *) (iter->iterexpr),
									  rt_index,
									  attno,
									  sublevels_up);
431 432
			}
			break;
433

434 435
		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
436
				ArrayRef   *ref = (ArrayRef *) node;
437 438

				if (attribute_used(
B
Bruce Momjian 已提交
439 440 441 442
								   (Node *) (ref->refupperindexpr),
								   rt_index,
								   attno,
								   sublevels_up))
443 444 445
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
446 447 448 449
								   (Node *) (ref->reflowerindexpr),
								   rt_index,
								   attno,
								   sublevels_up))
450 451 452
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
453 454 455 456
								   (Node *) (ref->refexpr),
								   rt_index,
								   attno,
								   sublevels_up))
457 458 459
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
460 461 462 463
								   (Node *) (ref->refassgnexpr),
								   rt_index,
								   attno,
								   sublevels_up))
464 465 466 467 468
					return TRUE;

				return FALSE;
			}
			break;
469

470 471
		case T_Var:
			{
B
Bruce Momjian 已提交
472
				Var		   *var = (Var *) node;
473

474 475 476 477 478 479
				if (var->varlevelsup == sublevels_up)
					return var->varno == rt_index;
				else
					return FALSE;
			}
			break;
480

481 482
		case T_Param:
			return FALSE;
483

484 485
		case T_Const:
			return FALSE;
486

487 488
		case T_List:
			{
B
Bruce Momjian 已提交
489
				List	   *l;
490

B
Bruce Momjian 已提交
491 492
				foreach(l, (List *) node)
				{
493
					if (attribute_used(
B
Bruce Momjian 已提交
494 495 496 497
									   (Node *) lfirst(l),
									   rt_index,
									   attno,
									   sublevels_up))
498 499 500 501 502 503 504 505
						return TRUE;
				}
				return FALSE;
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
506
				SubLink    *sub = (SubLink *) node;
507 508

				if (attribute_used(
B
Bruce Momjian 已提交
509 510 511 512
								   (Node *) (sub->lefthand),
								   rt_index,
								   attno,
								   sublevels_up))
513 514 515
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
516 517 518 519
								   (Node *) (sub->subselect),
								   rt_index,
								   attno,
								   sublevels_up + 1))
520 521 522 523 524 525 526 527
					return TRUE;

				return FALSE;
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
528
				Query	   *qry = (Query *) node;
529 530

				if (attribute_used(
B
Bruce Momjian 已提交
531 532 533 534
								   (Node *) (qry->targetList),
								   rt_index,
								   attno,
								   sublevels_up))
535 536 537
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
538 539 540 541
								   (Node *) (qry->qual),
								   rt_index,
								   attno,
								   sublevels_up))
542 543 544
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
545 546 547 548
								   (Node *) (qry->havingQual),
								   rt_index,
								   attno,
								   sublevels_up))
549 550 551 552 553 554 555 556 557 558
					return TRUE;

				return FALSE;
			}
			break;

		default:
			elog(NOTICE, "unknown node tag %d in attribute_used()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;
559 560


561 562
	}

563 564
	return FALSE;
}
565

566

567
/*
B
Bruce Momjian 已提交
568
 * modifyAggrefUplevel -
569 570 571 572 573
 *	In the newly created sublink for an aggregate column used in
 *	the qualification, we must adjust the varlevelsup in all the
 *	var nodes.
 */
static void
B
Bruce Momjian 已提交
574
modifyAggrefUplevel(Node *node)
575 576 577 578
{
	if (node == NULL)
		return;

B
Bruce Momjian 已提交
579 580
	switch (nodeTag(node))
	{
581 582
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
583
				TargetEntry *tle = (TargetEntry *) node;
584

B
Bruce Momjian 已提交
585
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
586
									(Node *) (tle->expr));
587 588 589
			}
			break;

B
Bruce Momjian 已提交
590
		case T_Aggref:
591
			{
B
Bruce Momjian 已提交
592
				Aggref	   *aggref = (Aggref *) node;
593

B
Bruce Momjian 已提交
594
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
595
									(Node *) (aggref->target));
596 597 598 599 600
			}
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
601
				Expr	   *exp = (Expr *) node;
602

B
Bruce Momjian 已提交
603
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
604
									(Node *) (exp->args));
605 606 607 608 609
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
610
				Iter	   *iter = (Iter *) node;
611

B
Bruce Momjian 已提交
612
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
613
									(Node *) (iter->iterexpr));
614 615 616 617 618
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
619
				ArrayRef   *ref = (ArrayRef *) node;
620

B
Bruce Momjian 已提交
621
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
622
									(Node *) (ref->refupperindexpr));
B
Bruce Momjian 已提交
623
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
624
									(Node *) (ref->reflowerindexpr));
B
Bruce Momjian 已提交
625
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
626
									(Node *) (ref->refexpr));
B
Bruce Momjian 已提交
627
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
628
									(Node *) (ref->refassgnexpr));
629 630 631 632 633
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
634
				Var		   *var = (Var *) node;
635 636 637 638 639 640 641 642 643 644 645 646 647

				var->varlevelsup++;
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
648
				List	   *l;
649

B
Bruce Momjian 已提交
650
				foreach(l, (List *) node)
B
Bruce Momjian 已提交
651
					modifyAggrefUplevel(
B
Bruce Momjian 已提交
652
										(Node *) lfirst(l));
653 654 655 656 657
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
658
				SubLink    *sub = (SubLink *) node;
659

B
Bruce Momjian 已提交
660
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
661
									(Node *) (sub->lefthand));
662

B
Bruce Momjian 已提交
663
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
664
									(Node *) (sub->oper));
665

B
Bruce Momjian 已提交
666
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
667
									(Node *) (sub->subselect));
668 669 670 671 672
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
673
				Query	   *qry = (Query *) node;
674

B
Bruce Momjian 已提交
675
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
676
									(Node *) (qry->targetList));
677

B
Bruce Momjian 已提交
678
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
679
									(Node *) (qry->qual));
680

B
Bruce Momjian 已提交
681
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
682
									(Node *) (qry->havingQual));
683 684 685 686 687

			}
			break;

		default:
B
Bruce Momjian 已提交
688
			elog(NOTICE, "unknown node tag %d in modifyAggrefUplevel()", nodeTag(node));
689 690 691 692 693 694 695 696 697
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
698
 * modifyAggrefChangeVarnodes -
699 700 701 702 703
 *	Change the var nodes in a sublink created for an aggregate column
 *	used in the qualification that is subject of the aggregate
 *	function to point to the correct local RTE.
 */
static void
B
Bruce Momjian 已提交
704
modifyAggrefChangeVarnodes(Node **nodePtr, int rt_index, int new_index, int sublevels_up)
705
{
B
Bruce Momjian 已提交
706
	Node	   *node = *nodePtr;
707 708 709 710

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
711 712
	switch (nodeTag(node))
	{
713 714
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
715
				TargetEntry *tle = (TargetEntry *) node;
716

B
Bruce Momjian 已提交
717
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
718 719 720 721
										   (Node **) (&(tle->expr)),
										   rt_index,
										   new_index,
										   sublevels_up);
722 723 724
			}
			break;

B
Bruce Momjian 已提交
725
		case T_Aggref:
726
			{
B
Bruce Momjian 已提交
727
				Aggref	   *aggref = (Aggref *) node;
728

B
Bruce Momjian 已提交
729
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
730 731 732 733
										   (Node **) (&(aggref->target)),
										   rt_index,
										   new_index,
										   sublevels_up);
734 735 736 737 738 739 740 741
			}
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
742
				Expr	   *exp = (Expr *) node;
743

B
Bruce Momjian 已提交
744
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
745 746 747 748
										   (Node **) (&(exp->args)),
										   rt_index,
										   new_index,
										   sublevels_up);
749 750 751 752 753
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
754
				Iter	   *iter = (Iter *) node;
755

B
Bruce Momjian 已提交
756
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
757 758 759 760
										   (Node **) (&(iter->iterexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
761 762 763 764 765
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
766
				ArrayRef   *ref = (ArrayRef *) node;
767

B
Bruce Momjian 已提交
768
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
769 770 771 772
									 (Node **) (&(ref->refupperindexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
B
Bruce Momjian 已提交
773
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
774 775 776 777
									 (Node **) (&(ref->reflowerindexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
B
Bruce Momjian 已提交
778
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
779 780 781 782
										   (Node **) (&(ref->refexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
B
Bruce Momjian 已提交
783
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
784 785 786 787
										(Node **) (&(ref->refassgnexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
788 789 790 791 792
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
793
				Var		   *var = (Var *) node;
794 795

				if (var->varlevelsup == sublevels_up &&
B
Bruce Momjian 已提交
796 797
					var->varno == rt_index)
				{
798 799 800 801 802
					var = copyObject(var);
					var->varno = new_index;
					var->varnoold = new_index;
					var->varlevelsup = 0;

B
Bruce Momjian 已提交
803
					*nodePtr = (Node *) var;
804 805 806 807 808 809 810 811 812 813 814 815
				}
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
816
				List	   *l;
817

B
Bruce Momjian 已提交
818
				foreach(l, (List *) node)
B
Bruce Momjian 已提交
819
					modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
820 821 822 823
											   (Node **) (&lfirst(l)),
											   rt_index,
											   new_index,
											   sublevels_up);
824 825 826 827 828
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
829
				SubLink    *sub = (SubLink *) node;
830

B
Bruce Momjian 已提交
831
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
832 833 834 835
										   (Node **) (&(sub->lefthand)),
										   rt_index,
										   new_index,
										   sublevels_up);
836

B
Bruce Momjian 已提交
837
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
838 839 840 841
										   (Node **) (&(sub->oper)),
										   rt_index,
										   new_index,
										   sublevels_up);
842

B
Bruce Momjian 已提交
843
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
844 845 846 847
										   (Node **) (&(sub->subselect)),
										   rt_index,
										   new_index,
										   sublevels_up + 1);
848 849 850 851 852
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
853
				Query	   *qry = (Query *) node;
854

B
Bruce Momjian 已提交
855
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
856 857 858 859
										   (Node **) (&(qry->targetList)),
										   rt_index,
										   new_index,
										   sublevels_up);
860

B
Bruce Momjian 已提交
861
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
862 863 864 865
										   (Node **) (&(qry->qual)),
										   rt_index,
										   new_index,
										   sublevels_up);
866

B
Bruce Momjian 已提交
867
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
868 869 870 871
										   (Node **) (&(qry->havingQual)),
										   rt_index,
										   new_index,
										   sublevels_up);
872 873 874 875
			}
			break;

		default:
B
Bruce Momjian 已提交
876
			elog(NOTICE, "unknown node tag %d in modifyAggrefChangeVarnodes()", nodeTag(node));
877 878 879 880 881 882 883 884 885
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
886 887
 * modifyAggrefDropQual -
 *	remove the pure aggref clase from a qualification
888 889
 */
static void
B
Bruce Momjian 已提交
890
modifyAggrefDropQual(Node **nodePtr, Node *orignode, Expr *expr)
891
{
B
Bruce Momjian 已提交
892
	Node	   *node = *nodePtr;
893 894 895 896

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
897 898
	switch (nodeTag(node))
	{
899 900 901
		case T_Var:
			break;

B
Bruce Momjian 已提交
902
		case T_Aggref:
903
			{
B
Bruce Momjian 已提交
904 905
				Aggref	   *aggref = (Aggref *) node;
				Aggref	   *oaggref = (Aggref *) orignode;
906

B
Bruce Momjian 已提交
907
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
908 909 910
									 (Node **) (&(aggref->target)),
									 (Node *) (oaggref->target),
									 expr);
911 912 913 914 915 916 917 918 919 920 921 922 923 924
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
925 926
				Expr	   *this_expr = (Expr *) node;
				Expr	   *orig_expr = (Expr *) orignode;
927

B
Bruce Momjian 已提交
928 929 930
				if (orig_expr == expr)
				{
					Const	   *ctrue;
931 932 933

					if (expr->typeOid != BOOLOID)
						elog(ERROR,
B
Bruce Momjian 已提交
934
							 "aggregate expression in qualification isn't of type bool");
935 936 937 938
					ctrue = makeNode(Const);
					ctrue->consttype = BOOLOID;
					ctrue->constlen = 1;
					ctrue->constisnull = FALSE;
B
Bruce Momjian 已提交
939
					ctrue->constvalue = (Datum) TRUE;
940 941
					ctrue->constbyval = TRUE;

B
Bruce Momjian 已提交
942
					*nodePtr = (Node *) ctrue;
943 944
				}
				else
B
Bruce Momjian 已提交
945
					modifyAggrefDropQual(
B
Bruce Momjian 已提交
946 947 948
										 (Node **) (&(this_expr->args)),
										 (Node *) (orig_expr->args),
										 expr);
949 950 951 952 953
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
954 955
				Iter	   *iter = (Iter *) node;
				Iter	   *oiter = (Iter *) orignode;
956

B
Bruce Momjian 已提交
957
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
958 959 960
									 (Node **) (&(iter->iterexpr)),
									 (Node *) (oiter->iterexpr),
									 expr);
961 962 963 964 965
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
966 967
				ArrayRef   *ref = (ArrayRef *) node;
				ArrayRef   *oref = (ArrayRef *) orignode;
968

B
Bruce Momjian 已提交
969
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
970 971 972
									 (Node **) (&(ref->refupperindexpr)),
									 (Node *) (oref->refupperindexpr),
									 expr);
B
Bruce Momjian 已提交
973
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
974 975 976
									 (Node **) (&(ref->reflowerindexpr)),
									 (Node *) (oref->reflowerindexpr),
									 expr);
B
Bruce Momjian 已提交
977
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
978 979 980
									 (Node **) (&(ref->refexpr)),
									 (Node *) (oref->refexpr),
									 expr);
B
Bruce Momjian 已提交
981
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
982 983 984
									 (Node **) (&(ref->refassgnexpr)),
									 (Node *) (oref->refassgnexpr),
									 expr);
985 986 987 988 989
			}
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
990 991 992
				List	   *l;
				List	   *ol = (List *) orignode;
				int			li = 0;
993

B
Bruce Momjian 已提交
994 995
				foreach(l, (List *) node)
				{
B
Bruce Momjian 已提交
996
					modifyAggrefDropQual(
B
Bruce Momjian 已提交
997 998 999
										 (Node **) (&(lfirst(l))),
										 (Node *) nth(li, ol),
										 expr);
1000 1001 1002 1003 1004 1005 1006
					li++;
				}
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
1007 1008
				SubLink    *sub = (SubLink *) node;
				SubLink    *osub = (SubLink *) orignode;
1009

B
Bruce Momjian 已提交
1010
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
1011 1012 1013
									 (Node **) (&(sub->subselect)),
									 (Node *) (osub->subselect),
									 expr);
1014 1015 1016 1017 1018
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
1019 1020
				Query	   *qry = (Query *) node;
				Query	   *oqry = (Query *) orignode;
1021

B
Bruce Momjian 已提交
1022
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
1023 1024 1025
									 (Node **) (&(qry->qual)),
									 (Node *) (oqry->qual),
									 expr);
1026

B
Bruce Momjian 已提交
1027
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
1028 1029 1030
									 (Node **) (&(qry->havingQual)),
									 (Node *) (oqry->havingQual),
									 expr);
1031 1032 1033 1034
			}
			break;

		default:
B
Bruce Momjian 已提交
1035
			elog(NOTICE, "unknown node tag %d in modifyAggrefDropQual()", nodeTag(node));
1036 1037 1038 1039 1040 1041 1042 1043 1044
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
1045
 * modifyAggrefMakeSublink -
1046 1047 1048 1049
 *	Create a sublink node for a qualification expression that
 *	uses an aggregate column of a view
 */
static SubLink *
B
Bruce Momjian 已提交
1050
modifyAggrefMakeSublink(Expr *origexp, Query *parsetree)
1051
{
B
Bruce Momjian 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060
	SubLink    *sublink;
	Query	   *subquery;
	Node	   *subqual;
	RangeTblEntry *rte;
	Aggref	   *aggref;
	Var		   *target;
	TargetEntry *tle;
	Resdom	   *resdom;
	Expr	   *exp = copyObject(origexp);
1061

B
Bruce Momjian 已提交
1062
	if (nodeTag(nth(0, exp->args)) == T_Aggref)
T
Thomas G. Lockhart 已提交
1063
	{
B
Bruce Momjian 已提交
1064
		if (nodeTag(nth(1, exp->args)) == T_Aggref)
1065 1066 1067
			elog(ERROR, "rewrite: comparision of 2 aggregate columns not supported");
		else
			elog(ERROR, "rewrite: aggregate column of view must be at rigth side in qual");
T
Thomas G. Lockhart 已提交
1068
	}
1069

B
Bruce Momjian 已提交
1070 1071 1072 1073 1074
	aggref = (Aggref *) nth(1, exp->args);
	target = (Var *) (aggref->target);
	rte = (RangeTblEntry *) nth(target->varno - 1, parsetree->rtable);
	tle = makeNode(TargetEntry);
	resdom = makeNode(Resdom);
1075

B
Bruce Momjian 已提交
1076
	aggref->usenulls = TRUE;
1077

B
Bruce Momjian 已提交
1078 1079
	resdom->resno = 1;
	resdom->restype = ((Oper *) (exp->oper))->opresulttype;
1080 1081
	resdom->restypmod = -1;
	resdom->resname = pstrdup("<noname>");
B
Bruce Momjian 已提交
1082
	resdom->reskey = 0;
1083
	resdom->reskeyop = 0;
B
Bruce Momjian 已提交
1084
	resdom->resjunk = false;
1085

B
Bruce Momjian 已提交
1086 1087
	tle->resdom = resdom;
	tle->expr = (Node *) aggref;
1088 1089

	subqual = copyObject(parsetree->qual);
B
Bruce Momjian 已提交
1090
	modifyAggrefDropQual((Node **) &subqual, (Node *) parsetree->qual, origexp);
1091 1092

	sublink = makeNode(SubLink);
B
Bruce Momjian 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
	sublink->subLinkType = EXPR_SUBLINK;
	sublink->useor = FALSE;
	sublink->lefthand = lappend(NIL, copyObject(lfirst(exp->args)));
	sublink->oper = lappend(NIL, copyObject(exp));
	sublink->subselect = NULL;

	subquery = makeNode(Query);
	sublink->subselect = (Node *) subquery;

	subquery->commandType = CMD_SELECT;
	subquery->utilityStmt = NULL;
	subquery->resultRelation = 0;
	subquery->into = NULL;
	subquery->isPortal = FALSE;
	subquery->isBinary = FALSE;
	subquery->isTemp = FALSE;
	subquery->unionall = FALSE;
	subquery->uniqueFlag = NULL;
	subquery->sortClause = NULL;
	subquery->rtable = lappend(NIL, rte);
	subquery->targetList = lappend(NIL, tle);
	subquery->qual = subqual;
	subquery->groupClause = NIL;
	subquery->havingQual = NULL;
	subquery->hasAggs = TRUE;
	subquery->hasSubLinks = FALSE;
	subquery->unionClause = NULL;


	modifyAggrefUplevel((Node *) sublink);

	modifyAggrefChangeVarnodes((Node **) &(sublink->lefthand), target->varno,
							   1, target->varlevelsup);
	modifyAggrefChangeVarnodes((Node **) &(sublink->oper), target->varno,
							   1, target->varlevelsup);
	modifyAggrefChangeVarnodes((Node **) &(sublink->subselect), target->varno,
							   1, target->varlevelsup);
1130 1131 1132 1133 1134 1135

	return sublink;
}


/*
B
Bruce Momjian 已提交
1136
 * modifyAggrefQual -
1137 1138 1139 1140 1141 1142
 *	Search for qualification expressions that contain aggregate
 *	functions and substiture them by sublinks. These expressions
 *	originally come from qualifications that use aggregate columns
 *	of a view.
 */
static void
B
Bruce Momjian 已提交
1143
modifyAggrefQual(Node **nodePtr, Query *parsetree)
1144
{
B
Bruce Momjian 已提交
1145
	Node	   *node = *nodePtr;
1146 1147 1148 1149

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
1150 1151
	switch (nodeTag(node))
	{
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
		case T_Var:
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1166 1167
				Expr	   *exp = (Expr *) node;
				SubLink    *sub;
1168 1169


B
Bruce Momjian 已提交
1170 1171
				if (length(exp->args) != 2)
				{
B
Bruce Momjian 已提交
1172
					modifyAggrefQual(
B
Bruce Momjian 已提交
1173 1174
									 (Node **) (&(exp->args)),
									 parsetree);
1175 1176 1177
					break;
				}

B
Bruce Momjian 已提交
1178
				if (nodeTag(nth(0, exp->args)) != T_Aggref &&
B
Bruce Momjian 已提交
1179 1180
					nodeTag(nth(1, exp->args)) != T_Aggref)
				{
1181

B
Bruce Momjian 已提交
1182
					modifyAggrefQual(
B
Bruce Momjian 已提交
1183 1184
									 (Node **) (&(exp->args)),
									 parsetree);
1185 1186 1187
					break;
				}

B
Bruce Momjian 已提交
1188
				sub = modifyAggrefMakeSublink(exp,
B
Bruce Momjian 已提交
1189
											  parsetree);
1190

B
Bruce Momjian 已提交
1191
				*nodePtr = (Node *) sub;
1192 1193 1194 1195
				parsetree->hasSubLinks = TRUE;
			}
			break;

T
Thomas G. Lockhart 已提交
1196 1197
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
1198 1199 1200 1201 1202 1203

				/*
				 * We're calling recursively, and this routine knows how
				 * to handle lists so let it do the work to handle the
				 * WHEN clauses...
				 */
B
Bruce Momjian 已提交
1204
				modifyAggrefQual(
B
Bruce Momjian 已提交
1205 1206
								 (Node **) (&(((CaseExpr *) node)->args)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1207

B
Bruce Momjian 已提交
1208
				modifyAggrefQual(
B
Bruce Momjian 已提交
1209 1210
						   (Node **) (&(((CaseExpr *) node)->defresult)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1211 1212 1213 1214 1215
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
1216
				modifyAggrefQual(
B
Bruce Momjian 已提交
1217 1218
								 (Node **) (&(((CaseWhen *) node)->expr)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1219

B
Bruce Momjian 已提交
1220
				modifyAggrefQual(
B
Bruce Momjian 已提交
1221 1222
							  (Node **) (&(((CaseWhen *) node)->result)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1223 1224 1225
			}
			break;

1226 1227
		case T_Iter:
			{
B
Bruce Momjian 已提交
1228
				Iter	   *iter = (Iter *) node;
1229

B
Bruce Momjian 已提交
1230
				modifyAggrefQual(
B
Bruce Momjian 已提交
1231 1232
								 (Node **) (&(iter->iterexpr)),
								 parsetree);
1233 1234 1235 1236 1237
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
1238
				ArrayRef   *ref = (ArrayRef *) node;
1239

B
Bruce Momjian 已提交
1240
				modifyAggrefQual(
B
Bruce Momjian 已提交
1241 1242
								 (Node **) (&(ref->refupperindexpr)),
								 parsetree);
B
Bruce Momjian 已提交
1243
				modifyAggrefQual(
B
Bruce Momjian 已提交
1244 1245
								 (Node **) (&(ref->reflowerindexpr)),
								 parsetree);
B
Bruce Momjian 已提交
1246
				modifyAggrefQual(
B
Bruce Momjian 已提交
1247 1248
								 (Node **) (&(ref->refexpr)),
								 parsetree);
B
Bruce Momjian 已提交
1249
				modifyAggrefQual(
B
Bruce Momjian 已提交
1250 1251
								 (Node **) (&(ref->refassgnexpr)),
								 parsetree);
1252 1253 1254 1255 1256
			}
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1257
				List	   *l;
1258

B
Bruce Momjian 已提交
1259
				foreach(l, (List *) node)
B
Bruce Momjian 已提交
1260
					modifyAggrefQual(
B
Bruce Momjian 已提交
1261 1262
									 (Node **) (&(lfirst(l))),
									 parsetree);
1263 1264 1265 1266 1267
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
1268
				SubLink    *sub = (SubLink *) node;
1269

B
Bruce Momjian 已提交
1270
				modifyAggrefQual(
B
Bruce Momjian 已提交
1271 1272
								 (Node **) (&(sub->subselect)),
								 (Query *) (sub->subselect));
1273 1274 1275 1276 1277
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
1278
				Query	   *qry = (Query *) node;
1279

B
Bruce Momjian 已提交
1280
				modifyAggrefQual(
B
Bruce Momjian 已提交
1281 1282
								 (Node **) (&(qry->qual)),
								 parsetree);
1283

B
Bruce Momjian 已提交
1284
				modifyAggrefQual(
B
Bruce Momjian 已提交
1285 1286
								 (Node **) (&(qry->havingQual)),
								 parsetree);
1287 1288 1289 1290
			}
			break;

		default:
B
Bruce Momjian 已提交
1291
			elog(NOTICE, "unknown node tag %d in modifyAggrefQual()", nodeTag(node));
1292 1293 1294 1295 1296 1297 1298 1299
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


1300 1301 1302 1303 1304 1305 1306 1307
/*
 * checkQueryHasAggs -
 *	Queries marked hasAggs might not have them any longer after
 *	rewriting. Check it.
 */
static bool
checkQueryHasAggs(Node *node)
{
1308
	return checkQueryHasAggs_walker(node, NULL);
1309 1310
}

1311 1312 1313 1314 1315 1316 1317 1318 1319
static bool
checkQueryHasAggs_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, Aggref))
		return true;			/* abort the tree traversal and return true */
	return expression_tree_walker(node, checkQueryHasAggs_walker, context);
}
1320

1321 1322
/*
 * checkQueryHasSubLink -
1323
 *	Queries marked hasSubLinks might not have them any longer after
1324 1325 1326 1327 1328
 *	rewriting. Check it.
 */
static bool
checkQueryHasSubLink(Node *node)
{
1329 1330
	return checkQueryHasSubLink_walker(node, NULL);
}
1331

1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
static bool
checkQueryHasSubLink_walker(Node *node, void *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, SubLink))
		return true;			/* abort the tree traversal and return true */
	/* Note: we assume the tree has not yet been rewritten by subselect.c,
	 * therefore we will find bare SubLink nodes and not SUBPLAN nodes.
	 */
	return expression_tree_walker(node, checkQueryHasSubLink_walker, context);
1343 1344 1345
}


1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
static Node *
FindMatchingTLEntry(List *tlist, char *e_attname)
{
	List	   *i;

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

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


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

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


B
Bruce Momjian 已提交
1378
static void
B
Bruce Momjian 已提交
1379 1380 1381 1382 1383
apply_RIR_adjust_sublevel(Node *node, int sublevels_up)
{
	if (node == NULL)
		return;

B
Bruce Momjian 已提交
1384 1385
	switch (nodeTag(node))
	{
B
Bruce Momjian 已提交
1386 1387
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
1388
				TargetEntry *tle = (TargetEntry *) node;
B
Bruce Momjian 已提交
1389 1390

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1391 1392
										  (Node *) (tle->expr),
										  sublevels_up);
B
Bruce Momjian 已提交
1393 1394 1395
			}
			break;

B
Bruce Momjian 已提交
1396
		case T_Aggref:
B
Bruce Momjian 已提交
1397
			{
B
Bruce Momjian 已提交
1398
				Aggref	   *aggref = (Aggref *) node;
B
Bruce Momjian 已提交
1399 1400

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1401 1402
										  (Node *) (aggref->target),
										  sublevels_up);
B
Bruce Momjian 已提交
1403 1404 1405 1406 1407 1408 1409 1410
			}
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1411
				Expr	   *exp = (Expr *) node;
B
Bruce Momjian 已提交
1412 1413

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1414 1415
										  (Node *) (exp->args),
										  sublevels_up);
B
Bruce Momjian 已提交
1416 1417 1418 1419 1420
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
1421
				Iter	   *iter = (Iter *) node;
B
Bruce Momjian 已提交
1422 1423

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1424 1425
										  (Node *) (iter->iterexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1426 1427 1428 1429 1430
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
1431
				ArrayRef   *ref = (ArrayRef *) node;
B
Bruce Momjian 已提交
1432 1433

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1434 1435
										  (Node *) (ref->refupperindexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1436 1437

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1438 1439
										  (Node *) (ref->reflowerindexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1440 1441

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1442 1443
										  (Node *) (ref->refexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1444 1445

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1446 1447
										  (Node *) (ref->refassgnexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1448 1449 1450 1451 1452
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
1453
				Var		   *var = (Var *) node;
B
Bruce Momjian 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466

				var->varlevelsup = sublevels_up;
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1467
				List	   *l;
B
Bruce Momjian 已提交
1468

B
Bruce Momjian 已提交
1469 1470
				foreach(l, (List *) node)
				{
B
Bruce Momjian 已提交
1471
					apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1472 1473
											  (Node *) lfirst(l),
											  sublevels_up);
B
Bruce Momjian 已提交
1474 1475 1476 1477
				}
			}
			break;

1478 1479
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
1480
				CaseExpr   *exp = (CaseExpr *) node;
1481 1482

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1483 1484
										  (Node *) (exp->args),
										  sublevels_up);
1485 1486

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1487 1488
										  (Node *) (exp->defresult),
										  sublevels_up);
1489 1490 1491 1492 1493
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
1494
				CaseWhen   *exp = (CaseWhen *) node;
1495 1496

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1497 1498
										  (Node *) (exp->expr),
										  sublevels_up);
1499 1500

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1501 1502
										  (Node *) (exp->result),
										  sublevels_up);
1503 1504 1505
			}
			break;

B
Bruce Momjian 已提交
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
		default:
			elog(NOTICE, "unknown node tag %d in attribute_used()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


1516 1517 1518
static void
apply_RIR_view(Node **nodePtr, int rt_index, RangeTblEntry *rte, List *tlist, int *modified, int sublevels_up)
{
B
Bruce Momjian 已提交
1519
	Node	   *node = *nodePtr;
1520 1521 1522 1523

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
1524 1525
	switch (nodeTag(node))
	{
1526 1527
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
1528
				TargetEntry *tle = (TargetEntry *) node;
1529 1530

				apply_RIR_view(
B
Bruce Momjian 已提交
1531 1532 1533 1534 1535 1536
							   (Node **) (&(tle->expr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1537 1538 1539
			}
			break;

B
Bruce Momjian 已提交
1540
		case T_Aggref:
1541
			{
B
Bruce Momjian 已提交
1542
				Aggref	   *aggref = (Aggref *) node;
1543 1544

				apply_RIR_view(
B
Bruce Momjian 已提交
1545 1546 1547 1548 1549 1550
							   (Node **) (&(aggref->target)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1551 1552 1553 1554 1555 1556 1557 1558
			}
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1559
				Expr	   *exp = (Expr *) node;
1560 1561

				apply_RIR_view(
B
Bruce Momjian 已提交
1562 1563 1564 1565 1566 1567
							   (Node **) (&(exp->args)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1568 1569 1570 1571 1572
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
1573
				Iter	   *iter = (Iter *) node;
1574 1575

				apply_RIR_view(
B
Bruce Momjian 已提交
1576 1577 1578 1579 1580 1581
							   (Node **) (&(iter->iterexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1582 1583 1584 1585 1586
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
1587
				ArrayRef   *ref = (ArrayRef *) node;
1588 1589

				apply_RIR_view(
B
Bruce Momjian 已提交
1590 1591 1592 1593 1594 1595
							   (Node **) (&(ref->refupperindexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1596
				apply_RIR_view(
B
Bruce Momjian 已提交
1597 1598 1599 1600 1601 1602
							   (Node **) (&(ref->reflowerindexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1603
				apply_RIR_view(
B
Bruce Momjian 已提交
1604 1605 1606 1607 1608 1609
							   (Node **) (&(ref->refexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1610
				apply_RIR_view(
B
Bruce Momjian 已提交
1611 1612 1613 1614 1615 1616
							   (Node **) (&(ref->refassgnexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1617 1618 1619 1620 1621
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
1622
				Var		   *var = (Var *) node;
1623 1624

				if (var->varlevelsup == sublevels_up &&
B
Bruce Momjian 已提交
1625 1626 1627
					var->varno == rt_index)
				{
					Node	   *exp;
1628

B
 
Bruce Momjian 已提交
1629 1630
					if (var->varattno < 0)
						elog(ERROR, "system column %s not available - %s is a view", get_attname(rte->relid, var->varattno), rte->relname);
1631
					exp = FindMatchingTLEntry(
B
Bruce Momjian 已提交
1632 1633 1634
											  tlist,
											  get_attname(rte->relid,
														  var->varattno));
1635

B
Bruce Momjian 已提交
1636 1637
					if (exp == NULL)
					{
1638 1639 1640 1641
						*nodePtr = make_null(var->vartype);
						return;
					}

B
Bruce Momjian 已提交
1642
					exp = copyObject(exp);
B
Bruce Momjian 已提交
1643 1644
					if (var->varlevelsup > 0)
						apply_RIR_adjust_sublevel(exp, var->varlevelsup);
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
					*nodePtr = exp;
					*modified = TRUE;
				}
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1659
				List	   *l;
1660

B
Bruce Momjian 已提交
1661
				foreach(l, (List *) node)
1662
					apply_RIR_view(
B
Bruce Momjian 已提交
1663 1664 1665 1666 1667 1668
								   (Node **) (&(lfirst(l))),
								   rt_index,
								   rte,
								   tlist,
								   modified,
								   sublevels_up);
1669 1670 1671 1672 1673
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
1674 1675 1676
				SubLink    *sub = (SubLink *) node;
				List	   *tmp_lefthand,
						   *tmp_oper;
1677 1678

				apply_RIR_view(
B
Bruce Momjian 已提交
1679 1680 1681 1682 1683 1684
							   (Node **) (&(sub->lefthand)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1685 1686

				apply_RIR_view(
B
Bruce Momjian 已提交
1687 1688 1689 1690 1691 1692
							   (Node **) (&(sub->subselect)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up + 1);
B
Hi!  
Bruce Momjian 已提交
1693

B
Bruce Momjian 已提交
1694
				tmp_lefthand = sub->lefthand;
B
Hi!  
Bruce Momjian 已提交
1695
				foreach(tmp_oper, sub->oper)
B
Bruce Momjian 已提交
1696 1697 1698 1699 1700
				{
					lfirst(((Expr *) lfirst(tmp_oper))->args) =
						lfirst(tmp_lefthand);
					tmp_lefthand = lnext(tmp_lefthand);
				}
1701 1702 1703 1704 1705
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
1706
				Query	   *qry = (Query *) node;
1707 1708

				apply_RIR_view(
B
Bruce Momjian 已提交
1709 1710 1711 1712 1713 1714
							   (Node **) (&(qry->targetList)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1715 1716

				apply_RIR_view(
B
Bruce Momjian 已提交
1717 1718 1719 1720 1721 1722
							   (Node **) (&(qry->qual)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1723 1724

				apply_RIR_view(
B
Bruce Momjian 已提交
1725 1726 1727 1728 1729 1730
							   (Node **) (&(qry->havingQual)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1731 1732 1733
			}
			break;

1734 1735
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
1736
				CaseExpr   *exp = (CaseExpr *) node;
1737 1738

				apply_RIR_view(
B
Bruce Momjian 已提交
1739 1740 1741 1742 1743 1744
							   (Node **) (&(exp->args)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1745 1746

				apply_RIR_view(
B
Bruce Momjian 已提交
1747 1748 1749 1750 1751 1752
							   (Node **) (&(exp->defresult)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1753 1754 1755 1756 1757
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
1758
				CaseWhen   *exp = (CaseWhen *) node;
1759 1760

				apply_RIR_view(
B
Bruce Momjian 已提交
1761 1762 1763 1764 1765 1766
							   (Node **) (&(exp->expr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1767 1768

				apply_RIR_view(
B
Bruce Momjian 已提交
1769 1770 1771 1772 1773 1774
							   (Node **) (&(exp->result)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1775 1776 1777
			}
			break;

1778 1779 1780 1781 1782 1783 1784
		default:
			elog(NOTICE, "unknown node tag %d in apply_RIR_view()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;
	}
}

B
Bruce Momjian 已提交
1785
extern void CheckSelectForUpdate(Query *rule_action);	/* in analyze.c */
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797

static void
ApplyRetrieveRule(Query *parsetree,
				  RewriteRule *rule,
				  int rt_index,
				  int relation_level,
				  Relation relation,
				  int *modified)
{
	Query	   *rule_action = NULL;
	Node	   *rule_qual;
	List	   *rtable,
1798 1799
			   *rt,
			   *l;
1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
	int			nothing,
				rt_length;
	int			badsql = FALSE;

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

			return;
		rule_action = copyObject(lfirst(rule->actions));
		nothing = FALSE;
	}
	else
		nothing = TRUE;

	rtable = copyObject(parsetree->rtable);
	foreach(rt, rtable)
	{
		RangeTblEntry *rte = lfirst(rt);

		/*
		 * this is to prevent add_missing_vars_to_base_rels() from adding
		 * a bogus entry to the new target list.
		 */
		rte->inFromCl = false;
	}
	rt_length = length(rtable);

	rtable = nconc(rtable, copyObject(rule_action->rtable));
	parsetree->rtable = rtable;

1834
	/* FOR UPDATE of view... */
B
Bruce Momjian 已提交
1835
	foreach(l, parsetree->rowMark)
1836
	{
B
Bruce Momjian 已提交
1837
		if (((RowMark *) lfirst(l))->rti == rt_index)
1838 1839
			break;
	}
B
Bruce Momjian 已提交
1840
	if (l != NULL)				/* oh, hell -:) */
1841
	{
B
Bruce Momjian 已提交
1842
		RowMark    *newrm;
1843 1844 1845
		Index		rti = 1;
		List	   *l2;

1846
		CheckSelectForUpdate(rule_action);
B
Bruce Momjian 已提交
1847 1848 1849 1850 1851 1852

		/*
		 * We believe that rt_index is VIEW - nothing should be marked for
		 * VIEW, but ACL check must be done. As for real tables of VIEW -
		 * their rows must be marked, but we have to skip ACL check for
		 * them.
1853
		 */
B
Bruce Momjian 已提交
1854 1855
		((RowMark *) lfirst(l))->info &= ~ROW_MARK_FOR_UPDATE;
		foreach(l2, rule_action->rtable)
1856
		{
B
Bruce Momjian 已提交
1857

1858
			/*
B
Bruce Momjian 已提交
1859 1860
			 * RTable of VIEW has two entries of VIEW itself - we use
			 * relid to skip them.
1861
			 */
B
Bruce Momjian 已提交
1862
			if (relation->rd_id != ((RangeTblEntry *) lfirst(l2))->relid)
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
			{
				newrm = makeNode(RowMark);
				newrm->rti = rti + rt_length;
				newrm->info = ROW_MARK_FOR_UPDATE;
				lnext(l) = lcons(newrm, lnext(l));
				l = lnext(l);
			}
			rti++;
		}
	}

1874
	rule_action->rtable = rtable;
B
Bruce Momjian 已提交
1875
	OffsetVarNodes((Node *) rule_qual, rt_length, 0);
B
Bruce Momjian 已提交
1876
	OffsetVarNodes((Node *) rule_action, rt_length, 0);
1877

B
Bruce Momjian 已提交
1878
	ChangeVarNodes((Node *) rule_qual,
1879
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
B
Bruce Momjian 已提交
1880
	ChangeVarNodes((Node *) rule_action,
1881 1882 1883 1884
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);

	if (relation_level)
	{
B
Bruce Momjian 已提交
1885 1886 1887 1888 1889 1890
		apply_RIR_view((Node **) &parsetree, rt_index,
					   (RangeTblEntry *) nth(rt_index - 1, rtable),
					   rule_action->targetList, modified, 0);
		apply_RIR_view((Node **) &rule_action, rt_index,
					   (RangeTblEntry *) nth(rt_index - 1, rtable),
					   rule_action->targetList, modified, 0);
1891 1892 1893
	}
	else
	{
B
Bruce Momjian 已提交
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
		HandleRIRAttributeRule(parsetree, rtable, rule_action->targetList,
							   rt_index, rule->attrno, modified, &badsql);
	}
	if (*modified && !badsql)
	{
		AddQual(parsetree, rule_action->qual);
		AddGroupClause(parsetree, rule_action->groupClause,
					   rule_action->targetList);
		AddHavingQual(parsetree, rule_action->havingQual);
		parsetree->hasAggs = (rule_action->hasAggs || parsetree->hasAggs);
		parsetree->hasSubLinks = (rule_action->hasSubLinks || parsetree->hasSubLinks);
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
	}
}


static void
fireRIRonSubselect(Node *node)
{
	if (node == NULL)
		return;

B
Bruce Momjian 已提交
1915 1916
	switch (nodeTag(node))
	{
1917 1918
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
1919
				TargetEntry *tle = (TargetEntry *) node;
1920 1921

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1922
								   (Node *) (tle->expr));
1923 1924 1925
			}
			break;

B
Bruce Momjian 已提交
1926
		case T_Aggref:
1927
			{
B
Bruce Momjian 已提交
1928
				Aggref	   *aggref = (Aggref *) node;
1929 1930

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1931
								   (Node *) (aggref->target));
1932 1933 1934 1935 1936 1937 1938 1939
			}
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1940
				Expr	   *exp = (Expr *) node;
1941 1942

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1943
								   (Node *) (exp->args));
1944 1945 1946 1947 1948
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
1949
				Iter	   *iter = (Iter *) node;
1950 1951

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1952
								   (Node *) (iter->iterexpr));
1953 1954 1955 1956 1957
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
1958
				ArrayRef   *ref = (ArrayRef *) node;
1959 1960

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1961
								   (Node *) (ref->refupperindexpr));
1962
				fireRIRonSubselect(
B
Bruce Momjian 已提交
1963
								   (Node *) (ref->reflowerindexpr));
1964
				fireRIRonSubselect(
B
Bruce Momjian 已提交
1965
								   (Node *) (ref->refexpr));
1966
				fireRIRonSubselect(
B
Bruce Momjian 已提交
1967
								   (Node *) (ref->refassgnexpr));
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
			}
			break;

		case T_Var:
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1982
				List	   *l;
1983

B
Bruce Momjian 已提交
1984
				foreach(l, (List *) node)
1985
					fireRIRonSubselect(
B
Bruce Momjian 已提交
1986
									   (Node *) (lfirst(l)));
1987 1988 1989 1990 1991
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
1992 1993
				SubLink    *sub = (SubLink *) node;
				Query	   *qry;
1994 1995

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1996
								   (Node *) (sub->lefthand));
1997

B
Bruce Momjian 已提交
1998
				qry = fireRIRrules((Query *) (sub->subselect));
1999 2000

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2001
								   (Node *) qry);
2002 2003 2004 2005 2006

				sub->subselect = (Node *) qry;
			}
			break;

T
Thomas G. Lockhart 已提交
2007
		case T_CaseExpr:
2008
			{
B
Bruce Momjian 已提交
2009
				CaseExpr   *exp = (CaseExpr *) node;
2010 2011

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2012
								   (Node *) (exp->args));
2013 2014

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2015
								   (Node *) (exp->defresult));
2016 2017 2018
			}
			break;

T
Thomas G. Lockhart 已提交
2019
		case T_CaseWhen:
2020
			{
B
Bruce Momjian 已提交
2021
				CaseWhen   *exp = (CaseWhen *) node;
2022 2023

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2024
								   (Node *) (exp->expr));
2025 2026

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2027
								   (Node *) (exp->result));
2028
			}
T
Thomas G. Lockhart 已提交
2029 2030
			break;

2031 2032
		case T_Query:
			{
B
Bruce Momjian 已提交
2033
				Query	   *qry = (Query *) node;
2034 2035

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2036
								   (Node *) (qry->targetList));
2037 2038

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2039
								   (Node *) (qry->qual));
2040 2041

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2042
								   (Node *) (qry->havingQual));
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
			}
			break;

		default:
			elog(NOTICE, "unknown node tag %d in fireRIRonSubselect()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
 * fireRIRrules -
 *	Apply all RIR rules on each rangetable entry in a query
 */
static Query *
fireRIRrules(Query *parsetree)
{
B
Bruce Momjian 已提交
2063 2064
	int			rt_index;
	RangeTblEntry *rte;
2065
	Relation	rel;
B
Bruce Momjian 已提交
2066 2067 2068 2069 2070 2071 2072
	List	   *locks;
	RuleLock   *rules;
	RewriteRule *rule;
	RewriteRule RIRonly;
	int			modified;
	int			i;
	List	   *l;
2073 2074

	rt_index = 0;
B
Bruce Momjian 已提交
2075 2076
	while (rt_index < length(parsetree->rtable))
	{
2077 2078
		++rt_index;

2079 2080
		rte = nth(rt_index - 1, parsetree->rtable);

B
Bruce Momjian 已提交
2081
		if (!rangeTableEntry_used((Node *) parsetree, rt_index, 0))
2082
		{
B
Bruce Momjian 已提交
2083

2084 2085
			/*
			 * Unused range table entries must not be marked as coming
B
Bruce Momjian 已提交
2086 2087 2088
			 * from a clause. Otherwise the planner will generate joins
			 * over relations that in fact shouldn't be scanned at all and
			 * the result will contain duplicates
2089 2090 2091 2092 2093
			 *
			 * Jan
			 *
			 */
			rte->inFromCl = FALSE;
2094
			continue;
2095
		}
B
Bruce Momjian 已提交
2096

2097
		rel = heap_openr(rte->relname);
B
Bruce Momjian 已提交
2098 2099
		if (rel->rd_rules == NULL)
		{
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
			heap_close(rel);
			continue;
		}

		rules = rel->rd_rules;
		locks = NIL;

		/*
		 * Collect the RIR rules that we must apply
		 */
B
Bruce Momjian 已提交
2110 2111
		for (i = 0; i < rules->numLocks; i++)
		{
2112 2113 2114
			rule = rules->rules[i];
			if (rule->event != CMD_SELECT)
				continue;
B
Bruce Momjian 已提交
2115

2116
			if (rule->attrno > 0 &&
B
Bruce Momjian 已提交
2117 2118 2119
				!attribute_used((Node *) parsetree,
								rt_index,
								rule->attrno, 0))
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
				continue;

			locks = lappend(locks, rule);
		}

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

		/*
		 * Now apply them
		 */
B
Bruce Momjian 已提交
2133 2134
		foreach(l, locks)
		{
2135 2136
			rule = lfirst(l);

B
Bruce Momjian 已提交
2137 2138 2139 2140
			RIRonly.event = rule->event;
			RIRonly.attrno = rule->attrno;
			RIRonly.qual = rule->qual;
			RIRonly.actions = rule->actions;
2141 2142

			ApplyRetrieveRule(parsetree,
B
Bruce Momjian 已提交
2143 2144 2145 2146 2147
							  &RIRonly,
							  rt_index,
							  RIRonly.attrno == -1,
							  rel,
							  &modified);
2148 2149 2150 2151 2152 2153
		}

		heap_close(rel);
	}

	fireRIRonSubselect((Node *) parsetree);
B
Bruce Momjian 已提交
2154
	modifyAggrefQual((Node **) &(parsetree->qual), parsetree);
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181

	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);
2182
		}
2183 2184
		else
			regular = lappend(regular, rule_lock);
2185
	}
2186 2187
	regular = nconc(regular, instead_qualified);
	return nconc(regular, instead_rules);
2188 2189
}

2190 2191


2192
static Query *
2193 2194 2195
CopyAndAddQual(Query *parsetree,
			   List *actions,
			   Node *rule_qual,
2196 2197
			   int rt_index,
			   CmdType event)
2198
{
2199 2200 2201
	Query	   *new_tree = (Query *) copyObject(parsetree);
	Node	   *new_qual = NULL;
	Query	   *rule_action = NULL;
2202 2203 2204 2205 2206 2207 2208

	if (actions)
		rule_action = lfirst(actions);
	if (rule_qual != NULL)
		new_qual = (Node *) copyObject(rule_qual);
	if (rule_action != NULL)
	{
2209 2210
		List	   *rtable;
		int			rt_length;
2211 2212 2213

		rtable = new_tree->rtable;
		rt_length = length(rtable);
B
Bruce Momjian 已提交
2214
		rtable = nconc(rtable, copyObject(rule_action->rtable));
2215
		new_tree->rtable = rtable;
B
Bruce Momjian 已提交
2216
		OffsetVarNodes(new_qual, rt_length, 0);
2217
		ChangeVarNodes(new_qual, PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
2218 2219 2220 2221 2222
	}
	/* XXX -- where current doesn't work for instead nothing.... yet */
	AddNotQual(new_tree, new_qual);

	return new_tree;
2223 2224 2225
}


2226

2227
/*
2228
 *	fireRules -
M
 
Marc G. Fournier 已提交
2229 2230 2231 2232 2233
 *	   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.
2234
 *
M
 
Marc G. Fournier 已提交
2235
 *	   remember: reality is for dead birds -- glass
2236 2237
 *
 */
2238
static List *
2239
fireRules(Query *parsetree,
2240 2241
		  int rt_index,
		  CmdType event,
2242 2243 2244
		  bool *instead_flag,
		  List *locks,
		  List **qual_products)
2245
{
2246 2247 2248
	RewriteInfo *info;
	List	   *results = NIL;
	List	   *i;
2249 2250 2251

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

M
 
Marc G. Fournier 已提交
2254
	locks = orderRules(locks);	/* real instead rules last */
2255 2256
	foreach(i, locks)
	{
2257 2258 2259 2260 2261
		RewriteRule *rule_lock = (RewriteRule *) lfirst(i);
		Node	   *qual,
				   *event_qual;
		List	   *actions;
		List	   *r;
2262

2263
		/*
2264 2265 2266 2267 2268 2269
		 * Instead rules change the resultRelation of the query. So the
		 * permission checks on the initial resultRelation would never be
		 * done (this is normally done in the executor deep down). So we
		 * must do it here. The result relations resulting from earlier
		 * rewrites are already checked against the rules eventrelation
		 * owner (during matchLocks) and have the skipAcl flag set.
2270
		 */
2271 2272 2273 2274
		if (rule_lock->isInstead &&
			parsetree->commandType != CMD_SELECT)
		{
			RangeTblEntry *rte;
2275 2276 2277
			int32		acl_rc;
			int32		reqperm;

2278 2279
			switch (parsetree->commandType)
			{
2280 2281 2282 2283 2284 2285 2286
				case CMD_INSERT:
					reqperm = ACL_AP;
					break;
				default:
					reqperm = ACL_WR;
					break;
			}
2287 2288 2289 2290 2291

			rte = (RangeTblEntry *) nth(parsetree->resultRelation - 1,
										parsetree->rtable);
			if (!rte->skipAcl)
			{
2292
				acl_rc = pg_aclcheck(rte->relname,
2293 2294 2295
									 GetPgUserName(), reqperm);
				if (acl_rc != ACLCHECK_OK)
				{
2296
					elog(ERROR, "%s: %s",
2297 2298
						 rte->relname,
						 aclcheck_error_strings[acl_rc]);
2299 2300 2301 2302
				}
			}
		}

2303 2304 2305 2306
		/* multiple rule action time */
		*instead_flag = rule_lock->isInstead;
		event_qual = rule_lock->qual;
		actions = rule_lock->actions;
2307 2308 2309 2310
		if (event_qual != NULL && *instead_flag)
		{
			Query	   *qual_product;
			RewriteInfo qual_info;
M
 
Marc G. Fournier 已提交
2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323

			/* ----------
			 * 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 it's 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.
			 * ----------
			 */
2324
			if (*qual_products == NIL)
M
 
Marc G. Fournier 已提交
2325
				qual_product = parsetree;
2326 2327
			else
				qual_product = (Query *) nth(0, *qual_products);
M
 
Marc G. Fournier 已提交
2328

2329 2330 2331 2332 2333 2334 2335 2336 2337
			qual_info.event = qual_product->commandType;
			qual_info.new_varno = length(qual_product->rtable) + 2;
			qual_product = CopyAndAddQual(qual_product,
										  actions,
										  event_qual,
										  rt_index,
										  event);

			qual_info.rule_action = qual_product;
M
 
Marc G. Fournier 已提交
2338 2339 2340 2341 2342 2343 2344

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

			*qual_products = lappend(NIL, qual_product);
		}

2345 2346
		foreach(r, actions)
		{
2347 2348
			Query	   *rule_action = lfirst(r);
			Node	   *rule_qual = copyObject(event_qual);
2349

M
 
Marc G. Fournier 已提交
2350 2351 2352
			if (rule_action->commandType == CMD_NOTHING)
				continue;

B
Bruce Momjian 已提交
2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
			/*--------------------------------------------------
			 * We copy the qualifications of the parsetree
			 * to the action and vice versa. So force
			 * hasSubLinks if one of them has it.
			 *
			 * As of 6.4 only parsetree qualifications can
			 * have sublinks. If this changes, we must make
			 * this a node lookup at the end of rewriting.
			 *
			 * Jan
			 *--------------------------------------------------
			 */
			if (parsetree->hasSubLinks && !rule_action->hasSubLinks)
			{
				rule_action = copyObject(rule_action);
				rule_action->hasSubLinks = TRUE;
			}
			if (!parsetree->hasSubLinks && rule_action->hasSubLinks)
				parsetree->hasSubLinks = TRUE;

2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
			/*--------------------------------------------------
			 * Step 1:
			 *	  Rewrite current.attribute or current to tuple variable
			 *	  this appears to be done in parser?
			 *--------------------------------------------------
			 */
			info = gatherRewriteMeta(parsetree, rule_action, rule_qual,
									 rt_index, event, instead_flag);

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

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

			/*
M
 
Marc G. Fournier 已提交
2396
			 * Event Qualification forces copying of parsetree and
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
			 * splitting into two queries one w/rule_qual, one w/NOT
			 * rule_qual. Also add user query qual onto rule action
			 */
			qual = parsetree->qual;
			AddQual(info->rule_action, qual);

			if (info->rule_qual != NULL)
				AddQual(info->rule_action, info->rule_qual);

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

			/*--------------------------------------------------
			 * Step 3:
			 *	  rewriting due to retrieve rules
			 *--------------------------------------------------
			 */
			info->rule_action->rtable = info->rt;
B
Bruce Momjian 已提交
2421

2422
			/*
B
Bruce Momjian 已提交
2423 2424 2425
			 * ProcessRetrieveQuery(info->rule_action, info->rt,
			 * &orig_instead_flag, TRUE);
			 */
2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436

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

			pfree(info);
		}
M
 
Marc G. Fournier 已提交
2437 2438 2439 2440 2441 2442

		/* ----------
		 * If this was an unqualified instead rule,
		 * throw away an eventually saved 'default' parsetree
		 * ----------
		 */
2443
		if (event_qual == NULL && *instead_flag)
M
 
Marc G. Fournier 已提交
2444
			*qual_products = NIL;
2445 2446
	}
	return results;
2447 2448
}

M
 
Marc G. Fournier 已提交
2449 2450


2451
static List *
2452
RewriteQuery(Query *parsetree, bool *instead_flag, List **qual_products)
2453
{
2454
	CmdType		event;
B
Bruce Momjian 已提交
2455 2456 2457
	List	   *product_queries = NIL;
	int			result_relation = 0;
	RangeTblEntry *rt_entry;
2458
	Relation	rt_entry_relation = NULL;
B
Bruce Momjian 已提交
2459
	RuleLock   *rt_entry_locks = NULL;
2460

2461 2462 2463 2464
	Assert(parsetree != NULL);

	event = parsetree->commandType;

2465
	/*
B
Bruce Momjian 已提交
2466 2467
	 * SELECT rules are handled later when we have all the queries that
	 * should get executed
2468 2469 2470 2471 2472 2473 2474
	 */
	if (event == CMD_SELECT)
		return NIL;

	/*
	 * Utilities aren't rewritten at all - why is this here?
	 */
2475 2476
	if (event == CMD_UTILITY)
		return NIL;
2477 2478

	/*
2479
	 * only for a delete may the targetlist be NULL
2480
	 */
2481 2482 2483 2484 2485
	if (event != CMD_DELETE)
		Assert(parsetree->targetList != NULL);

	result_relation = parsetree->resultRelation;

2486
	/*
B
Bruce Momjian 已提交
2487
	 * the statement is an update, insert or delete - fire rules on it.
2488 2489 2490 2491 2492
	 */
	rt_entry = rt_fetch(result_relation, parsetree->rtable);
	rt_entry_relation = heap_openr(rt_entry->relname);
	rt_entry_locks = rt_entry_relation->rd_rules;
	heap_close(rt_entry_relation);
M
 
Marc G. Fournier 已提交
2493

2494
	if (rt_entry_locks != NULL)
2495
	{
2496
		List	   *locks = matchLocks(event, rt_entry_locks, result_relation, parsetree);
2497

2498
		product_queries = fireRules(parsetree,
B
Bruce Momjian 已提交
2499 2500 2501 2502 2503
									result_relation,
									event,
									instead_flag,
									locks,
									qual_products);
2504
	}
2505

2506
	return product_queries;
B
Bruce Momjian 已提交
2507

2508 2509
}

2510

2511 2512 2513 2514 2515
/*
 * to avoid infinite recursion, we restrict the number of times a query
 * can be rewritten. Detecting cycles is left for the reader as an excercise.
 */
#ifndef REWRITE_INVOKE_MAX
2516
#define REWRITE_INVOKE_MAX		10
2517 2518
#endif

2519
static int	numQueryRewriteInvoked = 0;
2520 2521 2522

/*
 * deepRewriteQuery -
2523
 *	  rewrites the query and apply the rules again on the queries rewritten
2524
 */
2525
static List *
2526
deepRewriteQuery(Query *parsetree)
2527
{
2528 2529 2530 2531 2532
	List	   *n;
	List	   *rewritten = NIL;
	List	   *result = NIL;
	bool		instead;
	List	   *qual_products = NIL;
2533

2534 2535


2536 2537
	if (++numQueryRewriteInvoked > REWRITE_INVOKE_MAX)
	{
2538
		elog(ERROR, "query rewritten %d times, may contain cycles",
2539 2540 2541 2542 2543
			 numQueryRewriteInvoked - 1);
	}

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

2545 2546
	foreach(n, result)
	{
2547 2548
		Query	   *pt = lfirst(n);
		List	   *newstuff = NIL;
2549 2550 2551 2552 2553

		newstuff = deepRewriteQuery(pt);
		if (newstuff != NIL)
			rewritten = nconc(rewritten, newstuff);
	}
M
 
Marc G. Fournier 已提交
2554 2555 2556 2557 2558 2559

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

M
 
Marc G. Fournier 已提交
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
	/* ----------
	 * The original query is appended last if not instead
	 * because update and delete rule actions might not do
	 * anything if they are invoked after the update or
	 * delete is performed. The command counter increment
	 * between the query execution makes the deleted (and
	 * maybe the updated) tuples disappear so the scans
	 * for them in the rule actions cannot find them.
	 * ----------
	 */
	if (!instead)
		rewritten = lappend(rewritten, parsetree);

2576 2577
	return rewritten;
}
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610


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

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


/* ----------
 * RewritePreprocessQuery -
 *	adjust details in the parsetree, the rule system
 *	depends on
 * ----------
 */
static void
RewritePreprocessQuery(Query *parsetree)
{
	/* ----------
	 * if the query has a resultRelation, reassign the
	 * result domain numbers to the attribute numbers in the
	 * target relation. FixNew() depends on it when replacing
	 * *new* references in a rule action by the expressions
	 * from the rewritten query.
2611 2612
	 * resjunk targets are somewhat arbitrarily given a resno of 0;
	 * this is to prevent FixNew() from matching them to var nodes.
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
	 * ----------
	 */
	if (parsetree->resultRelation > 0)
	{
		RangeTblEntry *rte;
		Relation	rd;
		List	   *tl;

		rte = (RangeTblEntry *) nth(parsetree->resultRelation - 1,
									parsetree->rtable);
		rd = heap_openr(rte->relname);

		foreach(tl, parsetree->targetList)
		{
2627 2628 2629 2630 2631 2632
			TargetEntry *tle = (TargetEntry *) lfirst(tl);

			if (! tle->resdom->resjunk)
				tle->resdom->resno = attnameAttNum(rd, tle->resdom->resname);
			else
				tle->resdom->resno = 0;
2633 2634 2635 2636 2637 2638 2639 2640
		}

		heap_close(rd);
	}
}


/*
2641
 * BasicQueryRewrite -
2642 2643 2644
 *	  rewrite one query via query rewrite system, possibly returning 0
 *	  or many queries
 */
2645 2646
static List *
BasicQueryRewrite(Query *parsetree)
2647
{
B
Bruce Momjian 已提交
2648 2649 2650 2651
	List	   *querylist;
	List	   *results = NIL;
	List	   *l;
	Query	   *query;
2652 2653 2654 2655

	/*
	 * Step 1
	 *
B
Bruce Momjian 已提交
2656 2657
	 * There still seems something broken with the resdom numbers so we
	 * reassign them first.
2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
	 */
	RewritePreprocessQuery(parsetree);

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

	/*
	 * Step 3
	 *
	 * Apply all the RIR rules on each query
	 */
B
Bruce Momjian 已提交
2673 2674 2675 2676
	foreach(l, querylist)
	{
		query = fireRIRrules((Query *) lfirst(l));

2677
		/*
B
Bruce Momjian 已提交
2678 2679 2680 2681
		 * If the query was marked having aggregates, check if this is
		 * still true after rewriting. This check must get expanded when
		 * someday aggregates can appear somewhere else than in the
		 * targetlist or the having qual.
2682 2683
		 */
		if (query->hasAggs)
B
Bruce Momjian 已提交
2684 2685 2686 2687
			query->hasAggs = checkQueryHasAggs((Node *) (query->targetList))
				| checkQueryHasAggs((Node *) (query->havingQual));
		query->hasSubLinks = checkQueryHasSubLink((Node *) (query->qual))
			| checkQueryHasSubLink((Node *) (query->havingQual));
2688
		results = lappend(results, query);
2689 2690 2691
	}
	return results;
}
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702

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

B
Bruce Momjian 已提交
2710 2711 2712 2713
	/*
	 * Rewrite Union, Intersect and Except Queries to normal Union Queries
	 * using IN and NOT IN subselects
	 */
2714 2715 2716 2717 2718 2719 2720 2721 2722
	if (parsetree->intersectClause)
		parsetree = Except_Intersect_Rewrite(parsetree);

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

	/*
	 * Rewrite the UNIONS.
	 */
B
Bruce Momjian 已提交
2723
	foreach(rewritten_item, rewritten)
2724 2725 2726 2727 2728
	{
		Query	   *qry = (Query *) lfirst(rewritten_item);
		List	   *union_result = NIL;
		List	   *union_item;

B
Bruce Momjian 已提交
2729
		foreach(union_item, qry->unionClause)
2730 2731
		{
			union_result = nconc(union_result,
B
Bruce Momjian 已提交
2732
						BasicQueryRewrite((Query *) lfirst(union_item)));
2733 2734 2735 2736 2737 2738 2739 2740 2741 2742
		}
		qry->unionClause = union_result;
	}

	return rewritten;
}

/* This function takes two targetlists as arguments and checks if the
 * targetlists are compatible (i.e. both select for the same number of
 * attributes and the types are compatible */
2743
static void
B
Bruce Momjian 已提交
2744
check_targetlists_are_compatible(List *prev_target, List *current_target)
B
Hi!  
Bruce Momjian 已提交
2745
{
B
Bruce Momjian 已提交
2746 2747 2748 2749
	List	   *tl,
			   *next_target;
	int			prev_len = 0,
				next_len = 0;
2750

B
Bruce Momjian 已提交
2751 2752
	foreach(tl, prev_target)
		if (!((TargetEntry *) lfirst(tl))->resdom->resjunk)
2753 2754
		prev_len++;

B
Bruce Momjian 已提交
2755 2756
	foreach(next_target, current_target)
		if (!((TargetEntry *) lfirst(next_target))->resdom->resjunk)
2757
		next_len++;
B
Bruce Momjian 已提交
2758 2759 2760 2761 2762

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

	foreach(next_target, current_target)
B
Hi!  
Bruce Momjian 已提交
2763
	{
B
Bruce Momjian 已提交
2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
		Oid			itype;
		Oid			otype;

		otype = ((TargetEntry *) lfirst(prev_target))->resdom->restype;
		itype = ((TargetEntry *) lfirst(next_target))->resdom->restype;

		/* one or both is a NULL column? then don't convert... */
		if (otype == InvalidOid)
		{
			/* propagate a known type forward, if available */
			if (itype != InvalidOid)
				((TargetEntry *) lfirst(prev_target))->resdom->restype = itype;
M
 
Marc G. Fournier 已提交
2776
#ifdef NOT_USED
B
Bruce Momjian 已提交
2777 2778 2779 2780 2781
			else
			{
				((TargetEntry *) lfirst(prev_target))->resdom->restype = UNKNOWNOID;
				((TargetEntry *) lfirst(next_target))->resdom->restype = UNKNOWNOID;
			}
B
Hi!  
Bruce Momjian 已提交
2782
#endif
B
Bruce Momjian 已提交
2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
		}
		else if (itype == InvalidOid)
		{
		}
		/* they don't match in type? then convert... */
		else if (itype != otype)
		{
			Node	   *expr;

			expr = ((TargetEntry *) lfirst(next_target))->expr;
			expr = CoerceTargetExpr(NULL, expr, itype, otype);
			if (expr == NULL)
			{
				elog(ERROR, "Unable to transform %s to %s"
					 "\n\tEach UNION | EXCEPT | INTERSECT clause must have compatible target types",
					 typeidTypeName(itype),
					 typeidTypeName(otype));
			}
			((TargetEntry *) lfirst(next_target))->expr = expr;
			((TargetEntry *) lfirst(next_target))->resdom->restype = otype;
		}

		/* both are UNKNOWN? then evaluate as text... */
		else if (itype == UNKNOWNOID)
		{
			((TargetEntry *) lfirst(next_target))->resdom->restype = TEXTOID;
			((TargetEntry *) lfirst(prev_target))->resdom->restype = TEXTOID;
		}
		prev_target = lnext(prev_target);
B
Hi!  
Bruce Momjian 已提交
2812 2813 2814 2815
	}
}

/* Rewrites UNION INTERSECT and EXCEPT queries to semantiacally equivalent
B
Bruce Momjian 已提交
2816 2817
 * queries that use IN and NOT IN subselects.
 *
B
Hi!  
Bruce Momjian 已提交
2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829
 * The operator tree is attached to 'intersectClause' (see rule
 * 'SelectStmt' in gram.y) of the 'parsetree' given as an
 * argument. First we remember some clauses (the sortClause, the
 * unique flag etc.)  Then we translate the operator tree to DNF
 * (disjunctive normal form) by 'cnfify'. (Note that 'cnfify' produces
 * CNF but as we exchanged ANDs with ORs in function A_Expr_to_Expr()
 * earlier we get DNF after exchanging ANDs and ORs again in the
 * result.) Now we create a new query by evaluating the new operator
 * tree which is in DNF now. For every AND we create an entry in the
 * union list and for every OR we create an IN subselect. (NOT IN
 * subselects are created for OR NOT nodes). The first entry of the
 * union list is handed back but before that the remembered clauses
B
Bruce Momjian 已提交
2830
 * (sortClause etc) are attached to the new top Node (Note that the
B
Hi!  
Bruce Momjian 已提交
2831 2832 2833
 * new top Node can differ from the parsetree given as argument because of
 * the translation to DNF. That's why we have to remember the sortClause or
 * unique flag!) */
2834
static Query *
B
Bruce Momjian 已提交
2835
Except_Intersect_Rewrite(Query *parsetree)
B
Hi!  
Bruce Momjian 已提交
2836
{
B
Bruce Momjian 已提交
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893

	SubLink    *n;
	Query	   *result,
			   *intersect_node;
	List	   *elist,
			   *intersect_list = NIL,
			   *intersect,
			   *intersectClause;
	List	   *union_list = NIL,
			   *sortClause;
	List	   *left_expr,
			   *right_expr,
			   *resnames = NIL;
	char	   *op,
			   *uniqueFlag,
			   *into;
	bool		isBinary,
				isPortal,
				isTemp;
	CmdType		commandType = CMD_SELECT;
	List	   *rtable_insert = NIL;

	List	   *prev_target = NIL;

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

		resnames = lappend(resnames, tent->resdom->resname);
	}

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

		/*
		 * The result relation ( = the one to insert into) has to be
		 * attached to the rtable list of the new top node
		 */
		rtable_insert = nth(length(parsetree->rtable) - 1, parsetree->rtable);
B
Hi!  
Bruce Momjian 已提交
2894
	}
B
Bruce Momjian 已提交
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960

	/*
	 * Save some items, to be able to attach them to the resulting top
	 * node at the end of the function
	 */
	sortClause = parsetree->sortClause;
	uniqueFlag = parsetree->uniqueFlag;
	into = parsetree->into;
	isBinary = parsetree->isBinary;
	isPortal = parsetree->isPortal;
	isTemp = parsetree->isTemp;

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

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

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

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

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

		/*
		 * for every OR we create an IN subselect and for every OR NOT we
		 * create a NOT IN subselect, so first extract all the Select
		 * Query nodes from the tree (that contains only OR or OR NOTs any
		 * more because we did a transformation to DNF
		 *
		 * There must be at least one node that is not negated (i.e. just OR
		 * and not OR NOT) and this node will be the first in the list
		 * returned
		 */
		intersect_list = NIL;
2961
		create_intersect_list((Node *) lfirst(intersect), &intersect_list);
B
Bruce Momjian 已提交
2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114

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

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

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

			n = makeNode(SubLink);

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

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

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

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

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

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

			/*
			 * Prepare the lefthand side of the Sublinks: All the entries
			 * of the targetlist must be (IN) or must not be (NOT IN) the
			 * subselect
			 */
			foreach(elist, intersect_node->targetList)
			{
				Node	   *expr = lfirst(elist);
				TargetEntry *tent = (TargetEntry *) expr;

				n->lefthand = lappend(n->lefthand, tent->expr);
			}

			/*
			 * The first arguments of oper also have to be created for the
			 * sublink (they are the same as the lefthand side!)
			 */
			left_expr = n->lefthand;
			right_expr = ((Query *) (n->subselect))->targetList;

			foreach(elist, left_expr)
			{
				Node	   *lexpr = lfirst(elist);
				Node	   *rexpr = lfirst(right_expr);
				TargetEntry *tent = (TargetEntry *) rexpr;
				Expr	   *op_expr;

				op_expr = make_op(op, lexpr, tent->expr);

				n->oper = lappend(n->oper, op_expr);
				right_expr = lnext(right_expr);
			}

			/*
			 * If the Select Query node has aggregates in use add all the
			 * subselects to the HAVING qual else to the WHERE qual
			 */
			if (intersect_node->hasAggs == false)
				AddQual(intersect_node, (Node *) n);
			else
				AddHavingQual(intersect_node, (Node *) n);

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

	/* The first entry to union_list is our new top node */
	result = (Query *) lfirst(union_list);
	/* attach the rest to unionClause */
	result->unionClause = lnext(union_list);
	/* Attach all the items remembered in the beginning of the function */
	result->sortClause = sortClause;
	result->uniqueFlag = uniqueFlag;
	result->into = into;
	result->isPortal = isPortal;
	result->isBinary = isBinary;
	result->isTemp = isTemp;

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

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

		tent->resdom->resname = lfirst(resnames);
		resnames = lnext(resnames);
	}
	return result;
B
Hi!  
Bruce Momjian 已提交
3115 3116 3117 3118 3119 3120 3121
}

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

3122 3123
static void
create_intersect_list(Node *ptr, List **intersect_list)
B
Hi!  
Bruce Momjian 已提交
3124
{
B
Bruce Momjian 已提交
3125 3126 3127
	List	   *arg;

	if (IsA(ptr, Query))
B
Hi!  
Bruce Momjian 已提交
3128
	{
B
Bruce Momjian 已提交
3129 3130 3131
		/* The non negated node is attached at the beginning (lcons) */
		*intersect_list = lcons(ptr, *intersect_list);
		return;
B
Hi!  
Bruce Momjian 已提交
3132
	}
B
Bruce Momjian 已提交
3133 3134

	if (IsA(ptr, Expr))
B
Hi!  
Bruce Momjian 已提交
3135
	{
B
Bruce Momjian 已提交
3136 3137 3138 3139 3140 3141 3142 3143 3144
		if (((Expr *) ptr)->opType == NOT_EXPR)
		{
			/* negated nodes are appended to the end (lappend) */
			*intersect_list = lappend(*intersect_list, ptr);
			return;
		}
		else
		{
			foreach(arg, ((Expr *) ptr)->args)
3145
				create_intersect_list(lfirst(arg), intersect_list);
B
Bruce Momjian 已提交
3146 3147 3148
			return;
		}
		return;
B
Hi!  
Bruce Momjian 已提交
3149 3150 3151 3152 3153
	}
}

/* The nodes given in 'tree' are still 'raw' so 'cook' them using parse_analyze().
 * The node given in first_select has already been cooked, so don't transform
B
Bruce Momjian 已提交
3154
 * it again but return a pointer to the previously cooked version given in 'parsetree'
B
Hi!  
Bruce Momjian 已提交
3155
 * instead. */
3156
static Node *
B
Bruce Momjian 已提交
3157
intersect_tree_analyze(Node *tree, Node *first_select, Node *parsetree)
B
Hi!  
Bruce Momjian 已提交
3158
{
B
Bruce Momjian 已提交
3159 3160
	Node	   *result = (Node *) NIL;
	List	   *arg;
3161 3162

	if (IsA(tree, SelectStmt))
B
Bruce Momjian 已提交
3163 3164 3165 3166 3167 3168
	{

		/*
		 * If we get to the tree given in first_select return parsetree
		 * instead of performing parse_analyze()
		 */
3169 3170 3171
		if (tree == first_select)
			result = parsetree;
		else
B
Bruce Momjian 已提交
3172 3173 3174 3175
		{
			/* transform the 'raw' nodes to 'cooked' Query nodes */
			List	   *qtree = parse_analyze(lcons(tree, NIL), NULL);

3176 3177
			result = (Node *) lfirst(qtree);
		}
B
Bruce Momjian 已提交
3178
	}
3179

B
Bruce Momjian 已提交
3180
	if (IsA(tree, Expr))
B
Hi!  
Bruce Momjian 已提交
3181
	{
B
Bruce Momjian 已提交
3182 3183 3184 3185
		/* Call recursively for every argument of the node */
		foreach(arg, ((Expr *) tree)->args)
			lfirst(arg) = intersect_tree_analyze(lfirst(arg), first_select, parsetree);
		result = tree;
B
Hi!  
Bruce Momjian 已提交
3186
	}
B
Bruce Momjian 已提交
3187
	return result;
B
Hi!  
Bruce Momjian 已提交
3188
}