rewriteHandler.c 69.1 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * rewriteHandler.c
4 5 6 7 8
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
B
Bruce Momjian 已提交
9
 *	  $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.52 1999/07/16 03:13:22 momjian Exp $
10 11 12
 *
 *-------------------------------------------------------------------------
 */
M
Marc G. Fournier 已提交
13
#include <string.h>
14 15
#include "postgres.h"
#include "miscadmin.h"
16
#include "parser/parse_type.h"
B
Bruce Momjian 已提交
17
#include "parser/parsetree.h"
M
 
Marc G. Fournier 已提交
18
#include "parser/parse_relation.h"
19

B
Hi!  
Bruce Momjian 已提交
20 21 22
#include "parser/parse_target.h"

#include "parser/analyze.h"
23
#include "optimizer/clauses.h"
B
Hi!  
Bruce Momjian 已提交
24 25
#include "optimizer/prep.h"

26 27 28 29 30
#include "rewrite/rewriteManip.h"
#include "rewrite/locks.h"

#include "access/heapam.h"

31
#include "utils/lsyscache.h"
M
Marc G. Fournier 已提交
32
#include "utils/acl.h"
33 34 35 36 37 38 39 40 41 42 43
#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 已提交
44 45 46 47 48
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);
49
static bool checkQueryHasAggs(Node *node);
50 51 52
static bool checkQueryHasAggs_walker(Node *node, void *context);
static bool checkQueryHasSubLink(Node *node);
static bool checkQueryHasSubLink_walker(Node *node, void *context);
53
static Query *fireRIRrules(Query *parsetree);
54 55 56 57 58 59
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);
60 61 62

/*
 * gatherRewriteMeta -
63 64 65
 *	  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
66 67
 */
static RewriteInfo *
68 69 70
gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
71 72
				  int rt_index,
				  CmdType event,
73
				  bool *instead_flag)
74
{
75 76 77
	RewriteInfo *info;
	int			rt_length;
	int			result_reln;
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

	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 已提交
94
		info->rt = nconc(info->rt, copyObject(info->rule_action->rtable));
95 96

		info->new_varno = PRS2_NEW_VARNO + rt_length;
B
Bruce Momjian 已提交
97 98 99
		OffsetVarNodes(info->rule_action->qual, rt_length, 0);
		OffsetVarNodes((Node *) info->rule_action->targetList, rt_length, 0);
		OffsetVarNodes(info->rule_qual, rt_length, 0);
100
		ChangeVarNodes((Node *) info->rule_action->qual,
101
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
102
		ChangeVarNodes((Node *) info->rule_action->targetList,
103
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
104
		ChangeVarNodes(info->rule_qual,
105
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
106 107 108 109 110 111 112 113

		/*
		 * 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 */
114
			int			new_result_reln = 0;
115 116 117 118

			result_reln = info->rule_action->resultRelation;
			switch (result_reln)
			{
119 120 121 122 123 124 125
				case PRS2_CURRENT_VARNO:
					new_result_reln = rt_index;
					break;
				case PRS2_NEW_VARNO:	/* XXX */
				default:
					new_result_reln = result_reln + rt_length;
					break;
126 127 128 129 130
			}
			info->rule_action->resultRelation = new_result_reln;
		}
	}
	return info;
131 132 133 134
}


/*
135 136 137
 * rangeTableEntry_used -
 *	we need to process a RTE for RIR rules only if it is
 *	referenced somewhere in var nodes of the query.
138
 */
139 140
static bool
rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
141
{
142 143
	if (node == NULL)
		return FALSE;
144

B
Bruce Momjian 已提交
145 146
	switch (nodeTag(node))
	{
147 148
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
149
				TargetEntry *tle = (TargetEntry *) node;
150

151
				return rangeTableEntry_used(
B
Bruce Momjian 已提交
152 153 154
											(Node *) (tle->expr),
											rt_index,
											sublevels_up);
155 156
			}
			break;
157

B
Bruce Momjian 已提交
158
		case T_Aggref:
159
			{
B
Bruce Momjian 已提交
160
				Aggref	   *aggref = (Aggref *) node;
161

162
				return rangeTableEntry_used(
B
Bruce Momjian 已提交
163 164 165
											(Node *) (aggref->target),
											rt_index,
											sublevels_up);
166 167
			}
			break;
168

169
		case T_GroupClause:
170
			return FALSE;
171

172 173
		case T_Expr:
			{
B
Bruce Momjian 已提交
174
				Expr	   *exp = (Expr *) node;
175 176

				return rangeTableEntry_used(
B
Bruce Momjian 已提交
177 178 179
											(Node *) (exp->args),
											rt_index,
											sublevels_up);
180 181
			}
			break;
182

183 184
		case T_Iter:
			{
B
Bruce Momjian 已提交
185
				Iter	   *iter = (Iter *) node;
186

187
				return rangeTableEntry_used(
B
Bruce Momjian 已提交
188 189 190
											(Node *) (iter->iterexpr),
											rt_index,
											sublevels_up);
191 192
			}
			break;
193

194 195
		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
196
				ArrayRef   *ref = (ArrayRef *) node;
197 198

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
199 200 201
										 (Node *) (ref->refupperindexpr),
										 rt_index,
										 sublevels_up))
202
					return TRUE;
B
Bruce Momjian 已提交
203

204
				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
205 206 207
										 (Node *) (ref->reflowerindexpr),
										 rt_index,
										 sublevels_up))
208
					return TRUE;
B
Bruce Momjian 已提交
209

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

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

222 223 224 225 226 227
				return FALSE;
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
228
				Var		   *var = (Var *) node;
229 230 231 232 233 234 235 236 237 238

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

		case T_Param:
			return FALSE;
239

240 241 242 243
		case T_Const:
			return FALSE;

		case T_List:
244
			{
B
Bruce Momjian 已提交
245
				List	   *l;
246

B
Bruce Momjian 已提交
247 248
				foreach(l, (List *) node)
				{
249
					if (rangeTableEntry_used(
B
Bruce Momjian 已提交
250 251 252
											 (Node *) lfirst(l),
											 rt_index,
											 sublevels_up))
253 254 255
						return TRUE;
				}
				return FALSE;
256
			}
257 258 259
			break;

		case T_SubLink:
260
			{
B
Bruce Momjian 已提交
261
				SubLink    *sub = (SubLink *) node;
262 263

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
264 265 266
										 (Node *) (sub->lefthand),
										 rt_index,
										 sublevels_up))
267 268 269
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
270 271 272
										 (Node *) (sub->subselect),
										 rt_index,
										 sublevels_up + 1))
273 274 275
					return TRUE;

				return FALSE;
276
			}
277 278
			break;

T
Thomas G. Lockhart 已提交
279 280
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
281
				CaseExpr   *exp = (CaseExpr *) node;
T
Thomas G. Lockhart 已提交
282 283

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
284 285 286
										 (Node *) (exp->args),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
287 288 289
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
290 291 292
										 (Node *) (exp->defresult),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
293 294 295 296 297 298 299 300
					return TRUE;

				return FALSE;
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
301
				CaseWhen   *when = (CaseWhen *) node;
T
Thomas G. Lockhart 已提交
302 303

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
304 305 306
										 (Node *) (when->expr),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
307 308 309
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
310 311 312
										 (Node *) (when->result),
										 rt_index,
										 sublevels_up))
T
Thomas G. Lockhart 已提交
313 314 315 316 317 318
					return TRUE;

				return FALSE;
			}
			break;

319
		case T_Query:
320
			{
B
Bruce Momjian 已提交
321
				Query	   *qry = (Query *) node;
322 323

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
324 325 326
										 (Node *) (qry->targetList),
										 rt_index,
										 sublevels_up))
327 328 329
					return TRUE;

				if (rangeTableEntry_used(
B
Bruce Momjian 已提交
330 331 332
										 (Node *) (qry->qual),
										 rt_index,
										 sublevels_up))
333 334 335
					return TRUE;

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

				return FALSE;
342
			}
343 344 345 346 347 348 349 350
			break;

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


351
	}
352 353

	return FALSE;
354
}
355 356


357 358 359 360
/*
 * attribute_used -
 *	Check if a specific attribute number of a RTE is used
 *	somewhere in the query
361
 */
362 363
static bool
attribute_used(Node *node, int rt_index, int attno, int sublevels_up)
364
{
365 366
	if (node == NULL)
		return FALSE;
367

B
Bruce Momjian 已提交
368 369
	switch (nodeTag(node))
	{
370 371
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
372
				TargetEntry *tle = (TargetEntry *) node;
373

374
				return attribute_used(
B
Bruce Momjian 已提交
375 376 377 378
									  (Node *) (tle->expr),
									  rt_index,
									  attno,
									  sublevels_up);
379 380
			}
			break;
381

B
Bruce Momjian 已提交
382
		case T_Aggref:
383
			{
B
Bruce Momjian 已提交
384
				Aggref	   *aggref = (Aggref *) node;
385

386
				return attribute_used(
B
Bruce Momjian 已提交
387 388 389 390
									  (Node *) (aggref->target),
									  rt_index,
									  attno,
									  sublevels_up);
391 392
			}
			break;
M
Marc G. Fournier 已提交
393

394
		case T_GroupClause:
395
			return FALSE;
396

397 398
		case T_Expr:
			{
B
Bruce Momjian 已提交
399
				Expr	   *exp = (Expr *) node;
400

401
				return attribute_used(
B
Bruce Momjian 已提交
402 403 404 405
									  (Node *) (exp->args),
									  rt_index,
									  attno,
									  sublevels_up);
406 407
			}
			break;
408

409 410
		case T_Iter:
			{
B
Bruce Momjian 已提交
411
				Iter	   *iter = (Iter *) node;
412

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

421 422
		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
423
				ArrayRef   *ref = (ArrayRef *) node;
424 425

				if (attribute_used(
B
Bruce Momjian 已提交
426 427 428 429
								   (Node *) (ref->refupperindexpr),
								   rt_index,
								   attno,
								   sublevels_up))
430 431 432
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
433 434 435 436
								   (Node *) (ref->reflowerindexpr),
								   rt_index,
								   attno,
								   sublevels_up))
437 438 439
					return TRUE;

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

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

				return FALSE;
			}
			break;
456

457 458
		case T_Var:
			{
B
Bruce Momjian 已提交
459
				Var		   *var = (Var *) node;
460

461 462 463 464 465 466
				if (var->varlevelsup == sublevels_up)
					return var->varno == rt_index;
				else
					return FALSE;
			}
			break;
467

468 469
		case T_Param:
			return FALSE;
470

471 472
		case T_Const:
			return FALSE;
473

474 475
		case T_List:
			{
B
Bruce Momjian 已提交
476
				List	   *l;
477

B
Bruce Momjian 已提交
478 479
				foreach(l, (List *) node)
				{
480
					if (attribute_used(
B
Bruce Momjian 已提交
481 482 483 484
									   (Node *) lfirst(l),
									   rt_index,
									   attno,
									   sublevels_up))
485 486 487 488 489 490 491 492
						return TRUE;
				}
				return FALSE;
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
493
				SubLink    *sub = (SubLink *) node;
494 495

				if (attribute_used(
B
Bruce Momjian 已提交
496 497 498 499
								   (Node *) (sub->lefthand),
								   rt_index,
								   attno,
								   sublevels_up))
500 501 502
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
503 504 505 506
								   (Node *) (sub->subselect),
								   rt_index,
								   attno,
								   sublevels_up + 1))
507 508 509 510 511 512 513 514
					return TRUE;

				return FALSE;
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
515
				Query	   *qry = (Query *) node;
516 517

				if (attribute_used(
B
Bruce Momjian 已提交
518 519 520 521
								   (Node *) (qry->targetList),
								   rt_index,
								   attno,
								   sublevels_up))
522 523 524
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
525 526 527 528
								   (Node *) (qry->qual),
								   rt_index,
								   attno,
								   sublevels_up))
529 530 531
					return TRUE;

				if (attribute_used(
B
Bruce Momjian 已提交
532 533 534 535
								   (Node *) (qry->havingQual),
								   rt_index,
								   attno,
								   sublevels_up))
536 537 538 539 540 541 542 543 544 545
					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;
546 547


548 549
	}

550 551
	return FALSE;
}
552

553

554
/*
B
Bruce Momjian 已提交
555
 * modifyAggrefUplevel -
556 557 558 559 560
 *	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 已提交
561
modifyAggrefUplevel(Node *node)
562 563 564 565
{
	if (node == NULL)
		return;

B
Bruce Momjian 已提交
566 567
	switch (nodeTag(node))
	{
568 569
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
570
				TargetEntry *tle = (TargetEntry *) node;
571

B
Bruce Momjian 已提交
572
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
573
									(Node *) (tle->expr));
574 575 576
			}
			break;

B
Bruce Momjian 已提交
577
		case T_Aggref:
578
			{
B
Bruce Momjian 已提交
579
				Aggref	   *aggref = (Aggref *) node;
580

B
Bruce Momjian 已提交
581
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
582
									(Node *) (aggref->target));
583 584 585 586 587
			}
			break;

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

B
Bruce Momjian 已提交
590
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
591
									(Node *) (exp->args));
592 593 594 595 596
			}
			break;

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

B
Bruce Momjian 已提交
599
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
600
									(Node *) (iter->iterexpr));
601 602 603 604 605
			}
			break;

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

B
Bruce Momjian 已提交
608
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
609
									(Node *) (ref->refupperindexpr));
B
Bruce Momjian 已提交
610
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
611
									(Node *) (ref->reflowerindexpr));
B
Bruce Momjian 已提交
612
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
613
									(Node *) (ref->refexpr));
B
Bruce Momjian 已提交
614
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
615
									(Node *) (ref->refassgnexpr));
616 617 618 619 620
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
621
				Var		   *var = (Var *) node;
622 623 624 625 626 627 628 629 630 631 632 633 634

				var->varlevelsup++;
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
635
				List	   *l;
636

B
Bruce Momjian 已提交
637
				foreach(l, (List *) node)
B
Bruce Momjian 已提交
638
					modifyAggrefUplevel(
B
Bruce Momjian 已提交
639
										(Node *) lfirst(l));
640 641 642 643 644
			}
			break;

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

B
Bruce Momjian 已提交
647
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
648
									(Node *) (sub->lefthand));
649

B
Bruce Momjian 已提交
650
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
651
									(Node *) (sub->oper));
652

B
Bruce Momjian 已提交
653
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
654
									(Node *) (sub->subselect));
655 656 657 658 659
			}
			break;

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

B
Bruce Momjian 已提交
662
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
663
									(Node *) (qry->targetList));
664

B
Bruce Momjian 已提交
665
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
666
									(Node *) (qry->qual));
667

B
Bruce Momjian 已提交
668
				modifyAggrefUplevel(
B
Bruce Momjian 已提交
669
									(Node *) (qry->havingQual));
670 671 672 673 674

			}
			break;

		default:
B
Bruce Momjian 已提交
675
			elog(NOTICE, "unknown node tag %d in modifyAggrefUplevel()", nodeTag(node));
676 677 678 679 680 681 682 683 684
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
685
 * modifyAggrefChangeVarnodes -
686 687 688 689 690
 *	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 已提交
691
modifyAggrefChangeVarnodes(Node **nodePtr, int rt_index, int new_index, int sublevels_up)
692
{
B
Bruce Momjian 已提交
693
	Node	   *node = *nodePtr;
694 695 696 697

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
698 699
	switch (nodeTag(node))
	{
700 701
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
702
				TargetEntry *tle = (TargetEntry *) node;
703

B
Bruce Momjian 已提交
704
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
705 706 707 708
										   (Node **) (&(tle->expr)),
										   rt_index,
										   new_index,
										   sublevels_up);
709 710 711
			}
			break;

B
Bruce Momjian 已提交
712
		case T_Aggref:
713
			{
B
Bruce Momjian 已提交
714
				Aggref	   *aggref = (Aggref *) node;
715

B
Bruce Momjian 已提交
716
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
717 718 719 720
										   (Node **) (&(aggref->target)),
										   rt_index,
										   new_index,
										   sublevels_up);
721 722 723 724 725 726 727 728
			}
			break;

		case T_GroupClause:
			break;

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

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

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

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

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

B
Bruce Momjian 已提交
755
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
756 757 758 759
									 (Node **) (&(ref->refupperindexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
B
Bruce Momjian 已提交
760
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
761 762 763 764
									 (Node **) (&(ref->reflowerindexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
B
Bruce Momjian 已提交
765
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
766 767 768 769
										   (Node **) (&(ref->refexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
B
Bruce Momjian 已提交
770
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
771 772 773 774
										(Node **) (&(ref->refassgnexpr)),
										   rt_index,
										   new_index,
										   sublevels_up);
775 776 777 778 779
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
780
				Var		   *var = (Var *) node;
781 782

				if (var->varlevelsup == sublevels_up &&
B
Bruce Momjian 已提交
783 784
					var->varno == rt_index)
				{
785 786 787 788 789
					var = copyObject(var);
					var->varno = new_index;
					var->varnoold = new_index;
					var->varlevelsup = 0;

B
Bruce Momjian 已提交
790
					*nodePtr = (Node *) var;
791 792 793 794 795 796 797 798 799 800 801 802
				}
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
803
				List	   *l;
804

B
Bruce Momjian 已提交
805
				foreach(l, (List *) node)
B
Bruce Momjian 已提交
806
					modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
807 808 809 810
											   (Node **) (&lfirst(l)),
											   rt_index,
											   new_index,
											   sublevels_up);
811 812 813 814 815
			}
			break;

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

B
Bruce Momjian 已提交
818
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
819 820 821 822
										   (Node **) (&(sub->lefthand)),
										   rt_index,
										   new_index,
										   sublevels_up);
823

B
Bruce Momjian 已提交
824
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
825 826 827 828
										   (Node **) (&(sub->oper)),
										   rt_index,
										   new_index,
										   sublevels_up);
829

B
Bruce Momjian 已提交
830
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
831 832 833 834
										   (Node **) (&(sub->subselect)),
										   rt_index,
										   new_index,
										   sublevels_up + 1);
835 836 837 838 839
			}
			break;

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

B
Bruce Momjian 已提交
842
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
843 844 845 846
										   (Node **) (&(qry->targetList)),
										   rt_index,
										   new_index,
										   sublevels_up);
847

B
Bruce Momjian 已提交
848
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
849 850 851 852
										   (Node **) (&(qry->qual)),
										   rt_index,
										   new_index,
										   sublevels_up);
853

B
Bruce Momjian 已提交
854
				modifyAggrefChangeVarnodes(
B
Bruce Momjian 已提交
855 856 857 858
										   (Node **) (&(qry->havingQual)),
										   rt_index,
										   new_index,
										   sublevels_up);
859 860 861 862
			}
			break;

		default:
B
Bruce Momjian 已提交
863
			elog(NOTICE, "unknown node tag %d in modifyAggrefChangeVarnodes()", nodeTag(node));
864 865 866 867 868 869 870 871 872
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
873 874
 * modifyAggrefDropQual -
 *	remove the pure aggref clase from a qualification
875 876
 */
static void
B
Bruce Momjian 已提交
877
modifyAggrefDropQual(Node **nodePtr, Node *orignode, Expr *expr)
878
{
B
Bruce Momjian 已提交
879
	Node	   *node = *nodePtr;
880 881 882 883

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
884 885
	switch (nodeTag(node))
	{
886 887 888
		case T_Var:
			break;

B
Bruce Momjian 已提交
889
		case T_Aggref:
890
			{
B
Bruce Momjian 已提交
891 892
				Aggref	   *aggref = (Aggref *) node;
				Aggref	   *oaggref = (Aggref *) orignode;
893

B
Bruce Momjian 已提交
894
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
895 896 897
									 (Node **) (&(aggref->target)),
									 (Node *) (oaggref->target),
									 expr);
898 899 900 901 902 903 904 905 906 907 908 909 910 911
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
912 913
				Expr	   *this_expr = (Expr *) node;
				Expr	   *orig_expr = (Expr *) orignode;
914

B
Bruce Momjian 已提交
915 916 917
				if (orig_expr == expr)
				{
					Const	   *ctrue;
918 919 920

					if (expr->typeOid != BOOLOID)
						elog(ERROR,
B
Bruce Momjian 已提交
921
							 "aggregate expression in qualification isn't of type bool");
922 923 924 925
					ctrue = makeNode(Const);
					ctrue->consttype = BOOLOID;
					ctrue->constlen = 1;
					ctrue->constisnull = FALSE;
B
Bruce Momjian 已提交
926
					ctrue->constvalue = (Datum) TRUE;
927 928
					ctrue->constbyval = TRUE;

B
Bruce Momjian 已提交
929
					*nodePtr = (Node *) ctrue;
930 931
				}
				else
B
Bruce Momjian 已提交
932
					modifyAggrefDropQual(
B
Bruce Momjian 已提交
933 934 935
										 (Node **) (&(this_expr->args)),
										 (Node *) (orig_expr->args),
										 expr);
936 937 938 939 940
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
941 942
				Iter	   *iter = (Iter *) node;
				Iter	   *oiter = (Iter *) orignode;
943

B
Bruce Momjian 已提交
944
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
945 946 947
									 (Node **) (&(iter->iterexpr)),
									 (Node *) (oiter->iterexpr),
									 expr);
948 949 950 951 952
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
953 954
				ArrayRef   *ref = (ArrayRef *) node;
				ArrayRef   *oref = (ArrayRef *) orignode;
955

B
Bruce Momjian 已提交
956
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
957 958 959
									 (Node **) (&(ref->refupperindexpr)),
									 (Node *) (oref->refupperindexpr),
									 expr);
B
Bruce Momjian 已提交
960
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
961 962 963
									 (Node **) (&(ref->reflowerindexpr)),
									 (Node *) (oref->reflowerindexpr),
									 expr);
B
Bruce Momjian 已提交
964
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
965 966 967
									 (Node **) (&(ref->refexpr)),
									 (Node *) (oref->refexpr),
									 expr);
B
Bruce Momjian 已提交
968
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
969 970 971
									 (Node **) (&(ref->refassgnexpr)),
									 (Node *) (oref->refassgnexpr),
									 expr);
972 973 974 975 976
			}
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
977 978 979
				List	   *l;
				List	   *ol = (List *) orignode;
				int			li = 0;
980

B
Bruce Momjian 已提交
981 982
				foreach(l, (List *) node)
				{
B
Bruce Momjian 已提交
983
					modifyAggrefDropQual(
B
Bruce Momjian 已提交
984 985 986
										 (Node **) (&(lfirst(l))),
										 (Node *) nth(li, ol),
										 expr);
987 988 989 990 991 992 993
					li++;
				}
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
994 995
				SubLink    *sub = (SubLink *) node;
				SubLink    *osub = (SubLink *) orignode;
996

B
Bruce Momjian 已提交
997
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
998 999 1000
									 (Node **) (&(sub->subselect)),
									 (Node *) (osub->subselect),
									 expr);
1001 1002 1003 1004 1005
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
1006 1007
				Query	   *qry = (Query *) node;
				Query	   *oqry = (Query *) orignode;
1008

B
Bruce Momjian 已提交
1009
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
1010 1011 1012
									 (Node **) (&(qry->qual)),
									 (Node *) (oqry->qual),
									 expr);
1013

B
Bruce Momjian 已提交
1014
				modifyAggrefDropQual(
B
Bruce Momjian 已提交
1015 1016 1017
									 (Node **) (&(qry->havingQual)),
									 (Node *) (oqry->havingQual),
									 expr);
1018 1019 1020 1021
			}
			break;

		default:
B
Bruce Momjian 已提交
1022
			elog(NOTICE, "unknown node tag %d in modifyAggrefDropQual()", nodeTag(node));
1023 1024 1025 1026 1027 1028 1029 1030 1031
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
1032
 * modifyAggrefMakeSublink -
1033 1034 1035 1036
 *	Create a sublink node for a qualification expression that
 *	uses an aggregate column of a view
 */
static SubLink *
B
Bruce Momjian 已提交
1037
modifyAggrefMakeSublink(Expr *origexp, Query *parsetree)
1038
{
B
Bruce Momjian 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047
	SubLink    *sublink;
	Query	   *subquery;
	Node	   *subqual;
	RangeTblEntry *rte;
	Aggref	   *aggref;
	Var		   *target;
	TargetEntry *tle;
	Resdom	   *resdom;
	Expr	   *exp = copyObject(origexp);
1048

B
Bruce Momjian 已提交
1049
	if (nodeTag(nth(0, exp->args)) == T_Aggref)
T
Thomas G. Lockhart 已提交
1050
	{
B
Bruce Momjian 已提交
1051
		if (nodeTag(nth(1, exp->args)) == T_Aggref)
1052 1053 1054
			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 已提交
1055
	}
1056

B
Bruce Momjian 已提交
1057 1058 1059 1060 1061
	aggref = (Aggref *) nth(1, exp->args);
	target = (Var *) (aggref->target);
	rte = (RangeTblEntry *) nth(target->varno - 1, parsetree->rtable);
	tle = makeNode(TargetEntry);
	resdom = makeNode(Resdom);
1062

B
Bruce Momjian 已提交
1063
	aggref->usenulls = TRUE;
1064

B
Bruce Momjian 已提交
1065 1066
	resdom->resno = 1;
	resdom->restype = ((Oper *) (exp->oper))->opresulttype;
1067 1068
	resdom->restypmod = -1;
	resdom->resname = pstrdup("<noname>");
B
Bruce Momjian 已提交
1069
	resdom->reskey = 0;
1070
	resdom->reskeyop = 0;
B
Bruce Momjian 已提交
1071
	resdom->resjunk = false;
1072

B
Bruce Momjian 已提交
1073 1074
	tle->resdom = resdom;
	tle->expr = (Node *) aggref;
1075 1076

	subqual = copyObject(parsetree->qual);
B
Bruce Momjian 已提交
1077
	modifyAggrefDropQual((Node **) &subqual, (Node *) parsetree->qual, origexp);
1078 1079

	sublink = makeNode(SubLink);
B
Bruce Momjian 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
	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);
1117 1118 1119 1120 1121 1122

	return sublink;
}


/*
B
Bruce Momjian 已提交
1123
 * modifyAggrefQual -
1124 1125 1126 1127 1128 1129
 *	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 已提交
1130
modifyAggrefQual(Node **nodePtr, Query *parsetree)
1131
{
B
Bruce Momjian 已提交
1132
	Node	   *node = *nodePtr;
1133 1134 1135 1136

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
1137 1138
	switch (nodeTag(node))
	{
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
		case T_Var:
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1153 1154
				Expr	   *exp = (Expr *) node;
				SubLink    *sub;
1155 1156


B
Bruce Momjian 已提交
1157 1158
				if (length(exp->args) != 2)
				{
B
Bruce Momjian 已提交
1159
					modifyAggrefQual(
B
Bruce Momjian 已提交
1160 1161
									 (Node **) (&(exp->args)),
									 parsetree);
1162 1163 1164
					break;
				}

B
Bruce Momjian 已提交
1165
				if (nodeTag(nth(0, exp->args)) != T_Aggref &&
B
Bruce Momjian 已提交
1166 1167
					nodeTag(nth(1, exp->args)) != T_Aggref)
				{
1168

B
Bruce Momjian 已提交
1169
					modifyAggrefQual(
B
Bruce Momjian 已提交
1170 1171
									 (Node **) (&(exp->args)),
									 parsetree);
1172 1173 1174
					break;
				}

B
Bruce Momjian 已提交
1175
				sub = modifyAggrefMakeSublink(exp,
B
Bruce Momjian 已提交
1176
											  parsetree);
1177

B
Bruce Momjian 已提交
1178
				*nodePtr = (Node *) sub;
1179 1180 1181 1182
				parsetree->hasSubLinks = TRUE;
			}
			break;

T
Thomas G. Lockhart 已提交
1183 1184
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
1185 1186 1187 1188 1189 1190

				/*
				 * 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 已提交
1191
				modifyAggrefQual(
B
Bruce Momjian 已提交
1192 1193
								 (Node **) (&(((CaseExpr *) node)->args)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1194

B
Bruce Momjian 已提交
1195
				modifyAggrefQual(
B
Bruce Momjian 已提交
1196 1197
						   (Node **) (&(((CaseExpr *) node)->defresult)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1198 1199 1200 1201 1202
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
1203
				modifyAggrefQual(
B
Bruce Momjian 已提交
1204 1205
								 (Node **) (&(((CaseWhen *) node)->expr)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1206

B
Bruce Momjian 已提交
1207
				modifyAggrefQual(
B
Bruce Momjian 已提交
1208 1209
							  (Node **) (&(((CaseWhen *) node)->result)),
								 parsetree);
T
Thomas G. Lockhart 已提交
1210 1211 1212
			}
			break;

1213 1214
		case T_Iter:
			{
B
Bruce Momjian 已提交
1215
				Iter	   *iter = (Iter *) node;
1216

B
Bruce Momjian 已提交
1217
				modifyAggrefQual(
B
Bruce Momjian 已提交
1218 1219
								 (Node **) (&(iter->iterexpr)),
								 parsetree);
1220 1221 1222 1223 1224
			}
			break;

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

B
Bruce Momjian 已提交
1227
				modifyAggrefQual(
B
Bruce Momjian 已提交
1228 1229
								 (Node **) (&(ref->refupperindexpr)),
								 parsetree);
B
Bruce Momjian 已提交
1230
				modifyAggrefQual(
B
Bruce Momjian 已提交
1231 1232
								 (Node **) (&(ref->reflowerindexpr)),
								 parsetree);
B
Bruce Momjian 已提交
1233
				modifyAggrefQual(
B
Bruce Momjian 已提交
1234 1235
								 (Node **) (&(ref->refexpr)),
								 parsetree);
B
Bruce Momjian 已提交
1236
				modifyAggrefQual(
B
Bruce Momjian 已提交
1237 1238
								 (Node **) (&(ref->refassgnexpr)),
								 parsetree);
1239 1240 1241 1242 1243
			}
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1244
				List	   *l;
1245

B
Bruce Momjian 已提交
1246
				foreach(l, (List *) node)
B
Bruce Momjian 已提交
1247
					modifyAggrefQual(
B
Bruce Momjian 已提交
1248 1249
									 (Node **) (&(lfirst(l))),
									 parsetree);
1250 1251 1252 1253 1254
			}
			break;

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

B
Bruce Momjian 已提交
1257
				modifyAggrefQual(
B
Bruce Momjian 已提交
1258 1259
								 (Node **) (&(sub->subselect)),
								 (Query *) (sub->subselect));
1260 1261 1262 1263 1264
			}
			break;

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

B
Bruce Momjian 已提交
1267
				modifyAggrefQual(
B
Bruce Momjian 已提交
1268 1269
								 (Node **) (&(qry->qual)),
								 parsetree);
1270

B
Bruce Momjian 已提交
1271
				modifyAggrefQual(
B
Bruce Momjian 已提交
1272 1273
								 (Node **) (&(qry->havingQual)),
								 parsetree);
1274 1275 1276 1277
			}
			break;

		default:
B
Bruce Momjian 已提交
1278
			elog(NOTICE, "unknown node tag %d in modifyAggrefQual()", nodeTag(node));
1279 1280 1281 1282 1283 1284 1285 1286
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


1287 1288 1289 1290 1291 1292 1293 1294
/*
 * checkQueryHasAggs -
 *	Queries marked hasAggs might not have them any longer after
 *	rewriting. Check it.
 */
static bool
checkQueryHasAggs(Node *node)
{
1295
	return checkQueryHasAggs_walker(node, NULL);
1296 1297
}

1298 1299 1300 1301 1302 1303 1304 1305 1306
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);
}
1307

1308 1309
/*
 * checkQueryHasSubLink -
1310
 *	Queries marked hasSubLinks might not have them any longer after
1311 1312 1313 1314 1315
 *	rewriting. Check it.
 */
static bool
checkQueryHasSubLink(Node *node)
{
1316 1317
	return checkQueryHasSubLink_walker(node, NULL);
}
1318

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
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);
1330 1331 1332
}


1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
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 已提交
1365
static void
B
Bruce Momjian 已提交
1366 1367 1368 1369 1370
apply_RIR_adjust_sublevel(Node *node, int sublevels_up)
{
	if (node == NULL)
		return;

B
Bruce Momjian 已提交
1371 1372
	switch (nodeTag(node))
	{
B
Bruce Momjian 已提交
1373 1374
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
1375
				TargetEntry *tle = (TargetEntry *) node;
B
Bruce Momjian 已提交
1376 1377

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1378 1379
										  (Node *) (tle->expr),
										  sublevels_up);
B
Bruce Momjian 已提交
1380 1381 1382
			}
			break;

B
Bruce Momjian 已提交
1383
		case T_Aggref:
B
Bruce Momjian 已提交
1384
			{
B
Bruce Momjian 已提交
1385
				Aggref	   *aggref = (Aggref *) node;
B
Bruce Momjian 已提交
1386 1387

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1388 1389
										  (Node *) (aggref->target),
										  sublevels_up);
B
Bruce Momjian 已提交
1390 1391 1392 1393 1394 1395 1396 1397
			}
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1398
				Expr	   *exp = (Expr *) node;
B
Bruce Momjian 已提交
1399 1400

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1401 1402
										  (Node *) (exp->args),
										  sublevels_up);
B
Bruce Momjian 已提交
1403 1404 1405 1406 1407
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
1408
				Iter	   *iter = (Iter *) node;
B
Bruce Momjian 已提交
1409 1410

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1411 1412
										  (Node *) (iter->iterexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1413 1414 1415 1416 1417
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
1418
				ArrayRef   *ref = (ArrayRef *) node;
B
Bruce Momjian 已提交
1419 1420

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1421 1422
										  (Node *) (ref->refupperindexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1423 1424

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1425 1426
										  (Node *) (ref->reflowerindexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1427 1428

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1429 1430
										  (Node *) (ref->refexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1431 1432

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1433 1434
										  (Node *) (ref->refassgnexpr),
										  sublevels_up);
B
Bruce Momjian 已提交
1435 1436 1437 1438 1439
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
1440
				Var		   *var = (Var *) node;
B
Bruce Momjian 已提交
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453

				var->varlevelsup = sublevels_up;
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1454
				List	   *l;
B
Bruce Momjian 已提交
1455

B
Bruce Momjian 已提交
1456 1457
				foreach(l, (List *) node)
				{
B
Bruce Momjian 已提交
1458
					apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1459 1460
											  (Node *) lfirst(l),
											  sublevels_up);
B
Bruce Momjian 已提交
1461 1462 1463 1464
				}
			}
			break;

1465 1466
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
1467
				CaseExpr   *exp = (CaseExpr *) node;
1468 1469

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1470 1471
										  (Node *) (exp->args),
										  sublevels_up);
1472 1473

				apply_RIR_adjust_sublevel(
B
Bruce Momjian 已提交
1474 1475
										  (Node *) (exp->defresult),
										  sublevels_up);
1476 1477 1478 1479 1480
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
1481
				CaseWhen   *exp = (CaseWhen *) node;
1482 1483

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

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

B
Bruce Momjian 已提交
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
		default:
			elog(NOTICE, "unknown node tag %d in attribute_used()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


1503 1504 1505
static void
apply_RIR_view(Node **nodePtr, int rt_index, RangeTblEntry *rte, List *tlist, int *modified, int sublevels_up)
{
B
Bruce Momjian 已提交
1506
	Node	   *node = *nodePtr;
1507 1508 1509 1510

	if (node == NULL)
		return;

B
Bruce Momjian 已提交
1511 1512
	switch (nodeTag(node))
	{
1513 1514
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
1515
				TargetEntry *tle = (TargetEntry *) node;
1516 1517

				apply_RIR_view(
B
Bruce Momjian 已提交
1518 1519 1520 1521 1522 1523
							   (Node **) (&(tle->expr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1524 1525 1526
			}
			break;

B
Bruce Momjian 已提交
1527
		case T_Aggref:
1528
			{
B
Bruce Momjian 已提交
1529
				Aggref	   *aggref = (Aggref *) node;
1530 1531

				apply_RIR_view(
B
Bruce Momjian 已提交
1532 1533 1534 1535 1536 1537
							   (Node **) (&(aggref->target)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1538 1539 1540 1541 1542 1543 1544 1545
			}
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1546
				Expr	   *exp = (Expr *) node;
1547 1548

				apply_RIR_view(
B
Bruce Momjian 已提交
1549 1550 1551 1552 1553 1554
							   (Node **) (&(exp->args)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1555 1556 1557 1558 1559
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
1560
				Iter	   *iter = (Iter *) node;
1561 1562

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

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
1574
				ArrayRef   *ref = (ArrayRef *) node;
1575 1576

				apply_RIR_view(
B
Bruce Momjian 已提交
1577 1578 1579 1580 1581 1582
							   (Node **) (&(ref->refupperindexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1583
				apply_RIR_view(
B
Bruce Momjian 已提交
1584 1585 1586 1587 1588 1589
							   (Node **) (&(ref->reflowerindexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1590
				apply_RIR_view(
B
Bruce Momjian 已提交
1591 1592 1593 1594 1595 1596
							   (Node **) (&(ref->refexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1597
				apply_RIR_view(
B
Bruce Momjian 已提交
1598 1599 1600 1601 1602 1603
							   (Node **) (&(ref->refassgnexpr)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1604 1605 1606 1607 1608
			}
			break;

		case T_Var:
			{
B
Bruce Momjian 已提交
1609
				Var		   *var = (Var *) node;
1610 1611

				if (var->varlevelsup == sublevels_up &&
B
Bruce Momjian 已提交
1612 1613 1614
					var->varno == rt_index)
				{
					Node	   *exp;
1615

B
 
Bruce Momjian 已提交
1616 1617
					if (var->varattno < 0)
						elog(ERROR, "system column %s not available - %s is a view", get_attname(rte->relid, var->varattno), rte->relname);
1618
					exp = FindMatchingTLEntry(
B
Bruce Momjian 已提交
1619 1620 1621
											  tlist,
											  get_attname(rte->relid,
														  var->varattno));
1622

B
Bruce Momjian 已提交
1623 1624
					if (exp == NULL)
					{
1625 1626 1627 1628
						*nodePtr = make_null(var->vartype);
						return;
					}

B
Bruce Momjian 已提交
1629
					exp = copyObject(exp);
B
Bruce Momjian 已提交
1630 1631
					if (var->varlevelsup > 0)
						apply_RIR_adjust_sublevel(exp, var->varlevelsup);
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
					*nodePtr = exp;
					*modified = TRUE;
				}
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1646
				List	   *l;
1647

B
Bruce Momjian 已提交
1648
				foreach(l, (List *) node)
1649
					apply_RIR_view(
B
Bruce Momjian 已提交
1650 1651 1652 1653 1654 1655
								   (Node **) (&(lfirst(l))),
								   rt_index,
								   rte,
								   tlist,
								   modified,
								   sublevels_up);
1656 1657 1658 1659 1660
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
1661 1662 1663
				SubLink    *sub = (SubLink *) node;
				List	   *tmp_lefthand,
						   *tmp_oper;
1664 1665

				apply_RIR_view(
B
Bruce Momjian 已提交
1666 1667 1668 1669 1670 1671
							   (Node **) (&(sub->lefthand)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1672 1673

				apply_RIR_view(
B
Bruce Momjian 已提交
1674 1675 1676 1677 1678 1679
							   (Node **) (&(sub->subselect)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up + 1);
B
Hi!  
Bruce Momjian 已提交
1680

B
Bruce Momjian 已提交
1681
				tmp_lefthand = sub->lefthand;
B
Hi!  
Bruce Momjian 已提交
1682
				foreach(tmp_oper, sub->oper)
B
Bruce Momjian 已提交
1683 1684 1685 1686 1687
				{
					lfirst(((Expr *) lfirst(tmp_oper))->args) =
						lfirst(tmp_lefthand);
					tmp_lefthand = lnext(tmp_lefthand);
				}
1688 1689 1690 1691 1692
			}
			break;

		case T_Query:
			{
B
Bruce Momjian 已提交
1693
				Query	   *qry = (Query *) node;
1694 1695

				apply_RIR_view(
B
Bruce Momjian 已提交
1696 1697 1698 1699 1700 1701
							   (Node **) (&(qry->targetList)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1702 1703

				apply_RIR_view(
B
Bruce Momjian 已提交
1704 1705 1706 1707 1708 1709
							   (Node **) (&(qry->qual)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1710 1711

				apply_RIR_view(
B
Bruce Momjian 已提交
1712 1713 1714 1715 1716 1717
							   (Node **) (&(qry->havingQual)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1718 1719 1720
			}
			break;

1721 1722
		case T_CaseExpr:
			{
B
Bruce Momjian 已提交
1723
				CaseExpr   *exp = (CaseExpr *) node;
1724 1725

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

				apply_RIR_view(
B
Bruce Momjian 已提交
1734 1735 1736 1737 1738 1739
							   (Node **) (&(exp->defresult)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1740 1741 1742 1743 1744
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
1745
				CaseWhen   *exp = (CaseWhen *) node;
1746 1747

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

				apply_RIR_view(
B
Bruce Momjian 已提交
1756 1757 1758 1759 1760 1761
							   (Node **) (&(exp->result)),
							   rt_index,
							   rte,
							   tlist,
							   modified,
							   sublevels_up);
1762 1763 1764
			}
			break;

1765 1766 1767 1768 1769 1770 1771
		default:
			elog(NOTICE, "unknown node tag %d in apply_RIR_view()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;
	}
}

B
Bruce Momjian 已提交
1772
extern void CheckSelectForUpdate(Query *rule_action);	/* in analyze.c */
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784

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,
1785 1786
			   *rt,
			   *l;
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
	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;

1821
	/* FOR UPDATE of view... */
B
Bruce Momjian 已提交
1822
	foreach(l, parsetree->rowMark)
1823
	{
B
Bruce Momjian 已提交
1824
		if (((RowMark *) lfirst(l))->rti == rt_index)
1825 1826
			break;
	}
B
Bruce Momjian 已提交
1827
	if (l != NULL)				/* oh, hell -:) */
1828
	{
B
Bruce Momjian 已提交
1829
		RowMark    *newrm;
1830 1831 1832
		Index		rti = 1;
		List	   *l2;

1833
		CheckSelectForUpdate(rule_action);
B
Bruce Momjian 已提交
1834 1835 1836 1837 1838 1839

		/*
		 * 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.
1840
		 */
B
Bruce Momjian 已提交
1841 1842
		((RowMark *) lfirst(l))->info &= ~ROW_MARK_FOR_UPDATE;
		foreach(l2, rule_action->rtable)
1843
		{
B
Bruce Momjian 已提交
1844

1845
			/*
B
Bruce Momjian 已提交
1846 1847
			 * RTable of VIEW has two entries of VIEW itself - we use
			 * relid to skip them.
1848
			 */
B
Bruce Momjian 已提交
1849
			if (relation->rd_id != ((RangeTblEntry *) lfirst(l2))->relid)
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
			{
				newrm = makeNode(RowMark);
				newrm->rti = rti + rt_length;
				newrm->info = ROW_MARK_FOR_UPDATE;
				lnext(l) = lcons(newrm, lnext(l));
				l = lnext(l);
			}
			rti++;
		}
	}

1861
	rule_action->rtable = rtable;
B
Bruce Momjian 已提交
1862
	OffsetVarNodes((Node *) rule_qual, rt_length, 0);
B
Bruce Momjian 已提交
1863
	OffsetVarNodes((Node *) rule_action, rt_length, 0);
1864

B
Bruce Momjian 已提交
1865
	ChangeVarNodes((Node *) rule_qual,
1866
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
B
Bruce Momjian 已提交
1867
	ChangeVarNodes((Node *) rule_action,
1868 1869 1870 1871
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);

	if (relation_level)
	{
B
Bruce Momjian 已提交
1872 1873 1874 1875 1876 1877
		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);
1878 1879 1880
	}
	else
	{
B
Bruce Momjian 已提交
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
		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);
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
	}
}


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

B
Bruce Momjian 已提交
1902 1903
	switch (nodeTag(node))
	{
1904 1905
		case T_TargetEntry:
			{
B
Bruce Momjian 已提交
1906
				TargetEntry *tle = (TargetEntry *) node;
1907 1908

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1909
								   (Node *) (tle->expr));
1910 1911 1912
			}
			break;

B
Bruce Momjian 已提交
1913
		case T_Aggref:
1914
			{
B
Bruce Momjian 已提交
1915
				Aggref	   *aggref = (Aggref *) node;
1916 1917

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1918
								   (Node *) (aggref->target));
1919 1920 1921 1922 1923 1924 1925 1926
			}
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
B
Bruce Momjian 已提交
1927
				Expr	   *exp = (Expr *) node;
1928 1929

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1930
								   (Node *) (exp->args));
1931 1932 1933 1934 1935
			}
			break;

		case T_Iter:
			{
B
Bruce Momjian 已提交
1936
				Iter	   *iter = (Iter *) node;
1937 1938

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1939
								   (Node *) (iter->iterexpr));
1940 1941 1942 1943 1944
			}
			break;

		case T_ArrayRef:
			{
B
Bruce Momjian 已提交
1945
				ArrayRef   *ref = (ArrayRef *) node;
1946 1947

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1948
								   (Node *) (ref->refupperindexpr));
1949
				fireRIRonSubselect(
B
Bruce Momjian 已提交
1950
								   (Node *) (ref->reflowerindexpr));
1951
				fireRIRonSubselect(
B
Bruce Momjian 已提交
1952
								   (Node *) (ref->refexpr));
1953
				fireRIRonSubselect(
B
Bruce Momjian 已提交
1954
								   (Node *) (ref->refassgnexpr));
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968
			}
			break;

		case T_Var:
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
B
Bruce Momjian 已提交
1969
				List	   *l;
1970

B
Bruce Momjian 已提交
1971
				foreach(l, (List *) node)
1972
					fireRIRonSubselect(
B
Bruce Momjian 已提交
1973
									   (Node *) (lfirst(l)));
1974 1975 1976 1977 1978
			}
			break;

		case T_SubLink:
			{
B
Bruce Momjian 已提交
1979 1980
				SubLink    *sub = (SubLink *) node;
				Query	   *qry;
1981 1982

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

B
Bruce Momjian 已提交
1985
				qry = fireRIRrules((Query *) (sub->subselect));
1986 1987

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1988
								   (Node *) qry);
1989 1990 1991 1992 1993

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

T
Thomas G. Lockhart 已提交
1994
		case T_CaseExpr:
1995
			{
B
Bruce Momjian 已提交
1996
				CaseExpr   *exp = (CaseExpr *) node;
1997 1998

				fireRIRonSubselect(
B
Bruce Momjian 已提交
1999
								   (Node *) (exp->args));
2000 2001

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2002
								   (Node *) (exp->defresult));
2003 2004 2005
			}
			break;

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

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

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2014
								   (Node *) (exp->result));
2015
			}
T
Thomas G. Lockhart 已提交
2016 2017
			break;

2018 2019
		case T_Query:
			{
B
Bruce Momjian 已提交
2020
				Query	   *qry = (Query *) node;
2021 2022

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2023
								   (Node *) (qry->targetList));
2024 2025

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2026
								   (Node *) (qry->qual));
2027 2028

				fireRIRonSubselect(
B
Bruce Momjian 已提交
2029
								   (Node *) (qry->havingQual));
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
			}
			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 已提交
2050 2051
	int			rt_index;
	RangeTblEntry *rte;
2052
	Relation	rel;
B
Bruce Momjian 已提交
2053 2054 2055 2056 2057 2058 2059
	List	   *locks;
	RuleLock   *rules;
	RewriteRule *rule;
	RewriteRule RIRonly;
	int			modified;
	int			i;
	List	   *l;
2060 2061

	rt_index = 0;
B
Bruce Momjian 已提交
2062 2063
	while (rt_index < length(parsetree->rtable))
	{
2064 2065
		++rt_index;

2066 2067
		rte = nth(rt_index - 1, parsetree->rtable);

B
Bruce Momjian 已提交
2068
		if (!rangeTableEntry_used((Node *) parsetree, rt_index, 0))
2069
		{
B
Bruce Momjian 已提交
2070

2071 2072
			/*
			 * Unused range table entries must not be marked as coming
B
Bruce Momjian 已提交
2073 2074 2075
			 * 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
2076 2077 2078 2079 2080
			 *
			 * Jan
			 *
			 */
			rte->inFromCl = FALSE;
2081
			continue;
2082
		}
B
Bruce Momjian 已提交
2083

2084
		rel = heap_openr(rte->relname);
B
Bruce Momjian 已提交
2085 2086
		if (rel->rd_rules == NULL)
		{
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
			heap_close(rel);
			continue;
		}

		rules = rel->rd_rules;
		locks = NIL;

		/*
		 * Collect the RIR rules that we must apply
		 */
B
Bruce Momjian 已提交
2097 2098
		for (i = 0; i < rules->numLocks; i++)
		{
2099 2100 2101
			rule = rules->rules[i];
			if (rule->event != CMD_SELECT)
				continue;
B
Bruce Momjian 已提交
2102

2103
			if (rule->attrno > 0 &&
B
Bruce Momjian 已提交
2104 2105 2106
				!attribute_used((Node *) parsetree,
								rt_index,
								rule->attrno, 0))
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
				continue;

			locks = lappend(locks, rule);
		}

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

		/*
		 * Now apply them
		 */
B
Bruce Momjian 已提交
2120 2121
		foreach(l, locks)
		{
2122 2123
			rule = lfirst(l);

B
Bruce Momjian 已提交
2124 2125 2126 2127
			RIRonly.event = rule->event;
			RIRonly.attrno = rule->attrno;
			RIRonly.qual = rule->qual;
			RIRonly.actions = rule->actions;
2128 2129

			ApplyRetrieveRule(parsetree,
B
Bruce Momjian 已提交
2130 2131 2132 2133 2134
							  &RIRonly,
							  rt_index,
							  RIRonly.attrno == -1,
							  rel,
							  &modified);
2135 2136 2137 2138 2139 2140
		}

		heap_close(rel);
	}

	fireRIRonSubselect((Node *) parsetree);
B
Bruce Momjian 已提交
2141
	modifyAggrefQual((Node **) &(parsetree->qual), parsetree);
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168

	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);
2169
		}
2170 2171
		else
			regular = lappend(regular, rule_lock);
2172
	}
2173 2174
	regular = nconc(regular, instead_qualified);
	return nconc(regular, instead_rules);
2175 2176
}

2177 2178


2179
static Query *
2180 2181 2182
CopyAndAddQual(Query *parsetree,
			   List *actions,
			   Node *rule_qual,
2183 2184
			   int rt_index,
			   CmdType event)
2185
{
2186 2187 2188
	Query	   *new_tree = (Query *) copyObject(parsetree);
	Node	   *new_qual = NULL;
	Query	   *rule_action = NULL;
2189 2190 2191 2192 2193 2194 2195

	if (actions)
		rule_action = lfirst(actions);
	if (rule_qual != NULL)
		new_qual = (Node *) copyObject(rule_qual);
	if (rule_action != NULL)
	{
2196 2197
		List	   *rtable;
		int			rt_length;
2198 2199 2200

		rtable = new_tree->rtable;
		rt_length = length(rtable);
B
Bruce Momjian 已提交
2201
		rtable = nconc(rtable, copyObject(rule_action->rtable));
2202
		new_tree->rtable = rtable;
B
Bruce Momjian 已提交
2203
		OffsetVarNodes(new_qual, rt_length, 0);
2204
		ChangeVarNodes(new_qual, PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
2205 2206 2207 2208 2209
	}
	/* XXX -- where current doesn't work for instead nothing.... yet */
	AddNotQual(new_tree, new_qual);

	return new_tree;
2210 2211 2212
}


2213

2214
/*
2215
 *	fireRules -
M
 
Marc G. Fournier 已提交
2216 2217 2218 2219 2220
 *	   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.
2221
 *
M
 
Marc G. Fournier 已提交
2222
 *	   remember: reality is for dead birds -- glass
2223 2224
 *
 */
2225
static List *
2226
fireRules(Query *parsetree,
2227 2228
		  int rt_index,
		  CmdType event,
2229 2230 2231
		  bool *instead_flag,
		  List *locks,
		  List **qual_products)
2232
{
2233 2234 2235
	RewriteInfo *info;
	List	   *results = NIL;
	List	   *i;
2236 2237 2238

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

M
 
Marc G. Fournier 已提交
2241
	locks = orderRules(locks);	/* real instead rules last */
2242 2243
	foreach(i, locks)
	{
2244 2245 2246 2247 2248
		RewriteRule *rule_lock = (RewriteRule *) lfirst(i);
		Node	   *qual,
				   *event_qual;
		List	   *actions;
		List	   *r;
2249

2250
		/*
2251 2252 2253 2254 2255 2256
		 * 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.
2257
		 */
2258 2259 2260 2261
		if (rule_lock->isInstead &&
			parsetree->commandType != CMD_SELECT)
		{
			RangeTblEntry *rte;
2262 2263 2264
			int32		acl_rc;
			int32		reqperm;

2265 2266
			switch (parsetree->commandType)
			{
2267 2268 2269 2270 2271 2272 2273
				case CMD_INSERT:
					reqperm = ACL_AP;
					break;
				default:
					reqperm = ACL_WR;
					break;
			}
2274 2275 2276 2277 2278

			rte = (RangeTblEntry *) nth(parsetree->resultRelation - 1,
										parsetree->rtable);
			if (!rte->skipAcl)
			{
2279
				acl_rc = pg_aclcheck(rte->relname,
2280 2281 2282
									 GetPgUserName(), reqperm);
				if (acl_rc != ACLCHECK_OK)
				{
2283
					elog(ERROR, "%s: %s",
2284 2285
						 rte->relname,
						 aclcheck_error_strings[acl_rc]);
2286 2287 2288 2289
				}
			}
		}

2290 2291 2292 2293
		/* multiple rule action time */
		*instead_flag = rule_lock->isInstead;
		event_qual = rule_lock->qual;
		actions = rule_lock->actions;
2294 2295 2296 2297
		if (event_qual != NULL && *instead_flag)
		{
			Query	   *qual_product;
			RewriteInfo qual_info;
M
 
Marc G. Fournier 已提交
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310

			/* ----------
			 * 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.
			 * ----------
			 */
2311
			if (*qual_products == NIL)
M
 
Marc G. Fournier 已提交
2312
				qual_product = parsetree;
2313 2314
			else
				qual_product = (Query *) nth(0, *qual_products);
M
 
Marc G. Fournier 已提交
2315

2316 2317 2318 2319 2320 2321 2322 2323 2324
			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 已提交
2325 2326 2327 2328 2329 2330 2331

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

			*qual_products = lappend(NIL, qual_product);
		}

2332 2333
		foreach(r, actions)
		{
2334 2335
			Query	   *rule_action = lfirst(r);
			Node	   *rule_qual = copyObject(event_qual);
2336

M
 
Marc G. Fournier 已提交
2337 2338 2339
			if (rule_action->commandType == CMD_NOTHING)
				continue;

B
Bruce Momjian 已提交
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
			/*--------------------------------------------------
			 * 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;

2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
			/*--------------------------------------------------
			 * 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 已提交
2383
			 * Event Qualification forces copying of parsetree and
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
			 * 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 已提交
2408

2409
			/*
B
Bruce Momjian 已提交
2410 2411 2412
			 * ProcessRetrieveQuery(info->rule_action, info->rt,
			 * &orig_instead_flag, TRUE);
			 */
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423

			/*--------------------------------------------------
			 * 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 已提交
2424 2425 2426 2427 2428 2429

		/* ----------
		 * If this was an unqualified instead rule,
		 * throw away an eventually saved 'default' parsetree
		 * ----------
		 */
2430
		if (event_qual == NULL && *instead_flag)
M
 
Marc G. Fournier 已提交
2431
			*qual_products = NIL;
2432 2433
	}
	return results;
2434 2435
}

M
 
Marc G. Fournier 已提交
2436 2437


2438
static List *
2439
RewriteQuery(Query *parsetree, bool *instead_flag, List **qual_products)
2440
{
2441
	CmdType		event;
B
Bruce Momjian 已提交
2442 2443 2444
	List	   *product_queries = NIL;
	int			result_relation = 0;
	RangeTblEntry *rt_entry;
2445
	Relation	rt_entry_relation = NULL;
B
Bruce Momjian 已提交
2446
	RuleLock   *rt_entry_locks = NULL;
2447

2448 2449 2450 2451
	Assert(parsetree != NULL);

	event = parsetree->commandType;

2452
	/*
B
Bruce Momjian 已提交
2453 2454
	 * SELECT rules are handled later when we have all the queries that
	 * should get executed
2455 2456 2457 2458 2459 2460 2461
	 */
	if (event == CMD_SELECT)
		return NIL;

	/*
	 * Utilities aren't rewritten at all - why is this here?
	 */
2462 2463
	if (event == CMD_UTILITY)
		return NIL;
2464 2465

	/*
2466
	 * only for a delete may the targetlist be NULL
2467
	 */
2468 2469 2470 2471 2472
	if (event != CMD_DELETE)
		Assert(parsetree->targetList != NULL);

	result_relation = parsetree->resultRelation;

2473
	/*
B
Bruce Momjian 已提交
2474
	 * the statement is an update, insert or delete - fire rules on it.
2475 2476 2477 2478 2479
	 */
	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 已提交
2480

2481
	if (rt_entry_locks != NULL)
2482
	{
2483
		List	   *locks = matchLocks(event, rt_entry_locks, result_relation, parsetree);
2484

2485
		product_queries = fireRules(parsetree,
B
Bruce Momjian 已提交
2486 2487 2488 2489 2490
									result_relation,
									event,
									instead_flag,
									locks,
									qual_products);
2491
	}
2492

2493
	return product_queries;
B
Bruce Momjian 已提交
2494

2495 2496
}

2497

2498 2499 2500 2501 2502
/*
 * 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
2503
#define REWRITE_INVOKE_MAX		10
2504 2505
#endif

2506
static int	numQueryRewriteInvoked = 0;
2507 2508 2509

/*
 * deepRewriteQuery -
2510
 *	  rewrites the query and apply the rules again on the queries rewritten
2511
 */
2512
static List *
2513
deepRewriteQuery(Query *parsetree)
2514
{
2515 2516 2517 2518 2519
	List	   *n;
	List	   *rewritten = NIL;
	List	   *result = NIL;
	bool		instead;
	List	   *qual_products = NIL;
2520

2521 2522


2523 2524
	if (++numQueryRewriteInvoked > REWRITE_INVOKE_MAX)
	{
2525
		elog(ERROR, "query rewritten %d times, may contain cycles",
2526 2527 2528 2529 2530
			 numQueryRewriteInvoked - 1);
	}

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

2532 2533
	foreach(n, result)
	{
2534 2535
		Query	   *pt = lfirst(n);
		List	   *newstuff = NIL;
2536 2537 2538 2539 2540

		newstuff = deepRewriteQuery(pt);
		if (newstuff != NIL)
			rewritten = nconc(rewritten, newstuff);
	}
M
 
Marc G. Fournier 已提交
2541 2542 2543 2544 2545 2546

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

M
 
Marc G. Fournier 已提交
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
	/* ----------
	 * 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);

2563 2564
	return rewritten;
}
2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597


/*
 * 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.
2598 2599
	 * resjunk targets are somewhat arbitrarily given a resno of 0;
	 * this is to prevent FixNew() from matching them to var nodes.
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
	 * ----------
	 */
	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)
		{
2614 2615 2616 2617 2618 2619
			TargetEntry *tle = (TargetEntry *) lfirst(tl);

			if (! tle->resdom->resjunk)
				tle->resdom->resno = attnameAttNum(rd, tle->resdom->resname);
			else
				tle->resdom->resno = 0;
2620 2621 2622 2623 2624 2625 2626 2627
		}

		heap_close(rd);
	}
}


/*
2628
 * BasicQueryRewrite -
2629 2630 2631
 *	  rewrite one query via query rewrite system, possibly returning 0
 *	  or many queries
 */
2632 2633
static List *
BasicQueryRewrite(Query *parsetree)
2634
{
B
Bruce Momjian 已提交
2635 2636 2637 2638
	List	   *querylist;
	List	   *results = NIL;
	List	   *l;
	Query	   *query;
2639 2640 2641 2642

	/*
	 * Step 1
	 *
B
Bruce Momjian 已提交
2643 2644
	 * There still seems something broken with the resdom numbers so we
	 * reassign them first.
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
	 */
	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 已提交
2660 2661 2662 2663
	foreach(l, querylist)
	{
		query = fireRIRrules((Query *) lfirst(l));

2664
		/*
B
Bruce Momjian 已提交
2665 2666 2667 2668
		 * 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.
2669 2670
		 */
		if (query->hasAggs)
B
Bruce Momjian 已提交
2671 2672 2673 2674
			query->hasAggs = checkQueryHasAggs((Node *) (query->targetList))
				| checkQueryHasAggs((Node *) (query->havingQual));
		query->hasSubLinks = checkQueryHasSubLink((Node *) (query->qual))
			| checkQueryHasSubLink((Node *) (query->havingQual));
2675
		results = lappend(results, query);
2676 2677 2678
	}
	return results;
}
2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689

/*
 * 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 已提交
2690
 */
2691 2692 2693 2694 2695 2696
List *
QueryRewrite(Query *parsetree)
{
	List	   *rewritten,
			   *rewritten_item;

B
Bruce Momjian 已提交
2697 2698 2699 2700
	/*
	 * Rewrite Union, Intersect and Except Queries to normal Union Queries
	 * using IN and NOT IN subselects
	 */
2701 2702 2703 2704 2705 2706 2707 2708 2709
	if (parsetree->intersectClause)
		parsetree = Except_Intersect_Rewrite(parsetree);

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

	/*
	 * Rewrite the UNIONS.
	 */
B
Bruce Momjian 已提交
2710
	foreach(rewritten_item, rewritten)
2711 2712 2713 2714 2715
	{
		Query	   *qry = (Query *) lfirst(rewritten_item);
		List	   *union_result = NIL;
		List	   *union_item;

B
Bruce Momjian 已提交
2716
		foreach(union_item, qry->unionClause)
2717 2718
		{
			union_result = nconc(union_result,
B
Bruce Momjian 已提交
2719
						BasicQueryRewrite((Query *) lfirst(union_item)));
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
		}
		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 */
2730
static void
B
Bruce Momjian 已提交
2731
check_targetlists_are_compatible(List *prev_target, List *current_target)
B
Hi!  
Bruce Momjian 已提交
2732
{
B
Bruce Momjian 已提交
2733 2734 2735 2736
	List	   *tl,
			   *next_target;
	int			prev_len = 0,
				next_len = 0;
2737

B
Bruce Momjian 已提交
2738 2739
	foreach(tl, prev_target)
		if (!((TargetEntry *) lfirst(tl))->resdom->resjunk)
2740 2741
		prev_len++;

B
Bruce Momjian 已提交
2742 2743
	foreach(next_target, current_target)
		if (!((TargetEntry *) lfirst(next_target))->resdom->resjunk)
2744
		next_len++;
B
Bruce Momjian 已提交
2745 2746 2747 2748 2749

	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 已提交
2750
	{
B
Bruce Momjian 已提交
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
		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 已提交
2763
#ifdef NOT_USED
B
Bruce Momjian 已提交
2764 2765 2766 2767 2768
			else
			{
				((TargetEntry *) lfirst(prev_target))->resdom->restype = UNKNOWNOID;
				((TargetEntry *) lfirst(next_target))->resdom->restype = UNKNOWNOID;
			}
B
Hi!  
Bruce Momjian 已提交
2769
#endif
B
Bruce Momjian 已提交
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
		}
		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 已提交
2799 2800 2801 2802
	}
}

/* Rewrites UNION INTERSECT and EXCEPT queries to semantiacally equivalent
B
Bruce Momjian 已提交
2803 2804
 * queries that use IN and NOT IN subselects.
 *
B
Hi!  
Bruce Momjian 已提交
2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
 * 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 已提交
2817
 * (sortClause etc) are attached to the new top Node (Note that the
B
Hi!  
Bruce Momjian 已提交
2818 2819 2820
 * 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!) */
2821
static Query *
B
Bruce Momjian 已提交
2822
Except_Intersect_Rewrite(Query *parsetree)
B
Hi!  
Bruce Momjian 已提交
2823
{
B
Bruce Momjian 已提交
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 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

	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 已提交
2881
	}
B
Bruce Momjian 已提交
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 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

	/*
	 * 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;
2948
		create_intersect_list((Node *) lfirst(intersect), &intersect_list);
B
Bruce Momjian 已提交
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 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

		/*
		 * 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 已提交
3102 3103 3104 3105 3106 3107 3108
}

/* 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 */

3109 3110
static void
create_intersect_list(Node *ptr, List **intersect_list)
B
Hi!  
Bruce Momjian 已提交
3111
{
B
Bruce Momjian 已提交
3112 3113 3114
	List	   *arg;

	if (IsA(ptr, Query))
B
Hi!  
Bruce Momjian 已提交
3115
	{
B
Bruce Momjian 已提交
3116 3117 3118
		/* The non negated node is attached at the beginning (lcons) */
		*intersect_list = lcons(ptr, *intersect_list);
		return;
B
Hi!  
Bruce Momjian 已提交
3119
	}
B
Bruce Momjian 已提交
3120 3121

	if (IsA(ptr, Expr))
B
Hi!  
Bruce Momjian 已提交
3122
	{
B
Bruce Momjian 已提交
3123 3124 3125 3126 3127 3128 3129 3130 3131
		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)
3132
				create_intersect_list(lfirst(arg), intersect_list);
B
Bruce Momjian 已提交
3133 3134 3135
			return;
		}
		return;
B
Hi!  
Bruce Momjian 已提交
3136 3137 3138 3139 3140
	}
}

/* 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 已提交
3141
 * it again but return a pointer to the previously cooked version given in 'parsetree'
B
Hi!  
Bruce Momjian 已提交
3142
 * instead. */
3143
static Node *
B
Bruce Momjian 已提交
3144
intersect_tree_analyze(Node *tree, Node *first_select, Node *parsetree)
B
Hi!  
Bruce Momjian 已提交
3145
{
B
Bruce Momjian 已提交
3146 3147
	Node	   *result = (Node *) NIL;
	List	   *arg;
3148 3149

	if (IsA(tree, SelectStmt))
B
Bruce Momjian 已提交
3150 3151 3152 3153 3154 3155
	{

		/*
		 * If we get to the tree given in first_select return parsetree
		 * instead of performing parse_analyze()
		 */
3156 3157 3158
		if (tree == first_select)
			result = parsetree;
		else
B
Bruce Momjian 已提交
3159 3160 3161 3162
		{
			/* transform the 'raw' nodes to 'cooked' Query nodes */
			List	   *qtree = parse_analyze(lcons(tree, NIL), NULL);

3163 3164
			result = (Node *) lfirst(qtree);
		}
B
Bruce Momjian 已提交
3165
	}
3166

B
Bruce Momjian 已提交
3167
	if (IsA(tree, Expr))
B
Hi!  
Bruce Momjian 已提交
3168
	{
B
Bruce Momjian 已提交
3169 3170 3171 3172
		/* 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 已提交
3173
	}
B
Bruce Momjian 已提交
3174
	return result;
B
Hi!  
Bruce Momjian 已提交
3175
}