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

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

B
Hi!  
Bruce Momjian 已提交
27 28 29 30 31 32 33
/***S*I***/
#include "parser/parse_node.h"
#include "parser/parse_target.h"

#include "parser/analyze.h"
#include "optimizer/prep.h"

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

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

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


static RewriteInfo *gatherRewriteMeta(Query *parsetree,
				  Query *rule_action,
				  Node *rule_qual,
				  int rt_index,
				  CmdType event,
				  bool *instead_flag);
static bool rangeTableEntry_used(Node *node, int rt_index, int sublevels_up);
static bool attribute_used(Node *node, int rt_index, int attno, int sublevels_up);
B
Bruce Momjian 已提交
57 58 59 60 61
static void modifyAggrefUplevel(Node *node);
static void modifyAggrefChangeVarnodes(Node **nodePtr, int rt_index, int new_index, int sublevels_up);
static void modifyAggrefDropQual(Node **nodePtr, Node *orignode, Expr *expr);
static SubLink *modifyAggrefMakeSublink(Expr *origexp, Query *parsetree);
static void modifyAggrefQual(Node **nodePtr, Query *parsetree);
62 63 64


static Query *fireRIRrules(Query *parsetree);
M
Marc G. Fournier 已提交
65

66 67 68

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

	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);
		info->rt = append(info->rt, info->rule_action->rtable);

		info->new_varno = PRS2_NEW_VARNO + rt_length;
B
Bruce Momjian 已提交
103 104 105
		OffsetVarNodes(info->rule_action->qual, rt_length, 0);
		OffsetVarNodes((Node *) info->rule_action->targetList, rt_length, 0);
		OffsetVarNodes(info->rule_qual, rt_length, 0);
106
		ChangeVarNodes((Node *) info->rule_action->qual,
107
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
108
		ChangeVarNodes((Node *) info->rule_action->targetList,
109
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
110
		ChangeVarNodes(info->rule_qual,
111
					   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
112 113 114 115 116 117 118 119

		/*
		 * 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 */
120
			int			new_result_reln = 0;
121 122 123 124

			result_reln = info->rule_action->resultRelation;
			switch (result_reln)
			{
125 126 127 128 129 130 131
				case PRS2_CURRENT_VARNO:
					new_result_reln = rt_index;
					break;
				case PRS2_NEW_VARNO:	/* XXX */
				default:
					new_result_reln = result_reln + rt_length;
					break;
132 133 134 135 136
			}
			info->rule_action->resultRelation = new_result_reln;
		}
	}
	return info;
137 138 139 140
}


/*
141 142 143
 * rangeTableEntry_used -
 *	we need to process a RTE for RIR rules only if it is
 *	referenced somewhere in var nodes of the query.
144
 */
145 146
static bool
rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
147
{
148 149
	if (node == NULL)
		return FALSE;
150

151 152 153 154
	switch(nodeTag(node)) {
		case T_TargetEntry:
			{
				TargetEntry	*tle = (TargetEntry *)node;
155

156 157 158 159 160 161
				return rangeTableEntry_used(
						(Node *)(tle->expr),
						rt_index,
						sublevels_up);
			}
			break;
162

B
Bruce Momjian 已提交
163
		case T_Aggref:
164
			{
165
				Aggref	*aggref = (Aggref *)node;
166

167
				return rangeTableEntry_used(
168
						(Node *)(aggref->target),
169 170 171 172
						rt_index,
						sublevels_up);
			}
			break;
173

174 175 176
		case T_GroupClause:
			{
				GroupClause	*grp = (GroupClause *)node;
177

178 179 180 181 182 183
				return rangeTableEntry_used(
						(Node *)(grp->entry),
						rt_index,
						sublevels_up);
			}
			break;
184

185 186 187 188 189 190 191 192 193 194
		case T_Expr:
			{
				Expr	*exp = (Expr *)node;

				return rangeTableEntry_used(
						(Node *)(exp->args),
						rt_index,
						sublevels_up);
			}
			break;
195

196 197 198
		case T_Iter:
			{
				Iter	*iter = (Iter *)node;
199

200 201 202 203 204 205
				return rangeTableEntry_used(
						(Node *)(iter->iterexpr),
						rt_index,
						sublevels_up);
			}
			break;
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

				if (rangeTableEntry_used(
						(Node *)(ref->refupperindexpr),
						rt_index,
						sublevels_up))
					return TRUE;
				
				if (rangeTableEntry_used(
						(Node *)(ref->reflowerindexpr),
						rt_index,
						sublevels_up))
					return TRUE;
				
				if (rangeTableEntry_used(
						(Node *)(ref->refexpr),
						rt_index,
						sublevels_up))
					return TRUE;
				
				if (rangeTableEntry_used(
						(Node *)(ref->refassgnexpr),
						rt_index,
						sublevels_up))
					return TRUE;
				
				return FALSE;
			}
			break;

		case T_Var:
			{
				Var	*var = (Var *)node;

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

		case T_Param:
			return FALSE;
252

253 254 255 256
		case T_Const:
			return FALSE;

		case T_List:
257
			{
258 259 260 261 262 263 264 265 266 267
				List	*l;

				foreach (l, (List *)node) {
					if (rangeTableEntry_used(
							(Node *)lfirst(l),
							rt_index,
							sublevels_up))
						return TRUE;
				}
				return FALSE;
268
			}
269 270 271
			break;

		case T_SubLink:
272
			{
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
				SubLink	*sub = (SubLink *)node;

				if (rangeTableEntry_used(
						(Node *)(sub->lefthand),
						rt_index,
						sublevels_up))
					return TRUE;

				if (rangeTableEntry_used(
						(Node *)(sub->subselect),
						rt_index,
						sublevels_up + 1))
					return TRUE;

				return FALSE;
288
			}
289 290
			break;

T
Thomas G. Lockhart 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
		case T_CaseExpr:
			{
				CaseExpr	*exp = (CaseExpr *)node;

				if (rangeTableEntry_used(
						(Node *)(exp->args),
						rt_index,
						sublevels_up))
					return TRUE;

				if (rangeTableEntry_used(
						(Node *)(exp->defresult),
						rt_index,
						sublevels_up))
					return TRUE;

				return FALSE;
			}
			break;

		case T_CaseWhen:
			{
				CaseWhen	*when = (CaseWhen *)node;

				if (rangeTableEntry_used(
						(Node *)(when->expr),
						rt_index,
						sublevels_up))
					return TRUE;

				if (rangeTableEntry_used(
						(Node *)(when->result),
						rt_index,
						sublevels_up))
					return TRUE;

				return FALSE;
			}
			break;

331
		case T_Query:
332
			{
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
				Query	*qry = (Query *)node;

				if (rangeTableEntry_used(
						(Node *)(qry->targetList),
						rt_index,
						sublevels_up))
					return TRUE;

				if (rangeTableEntry_used(
						(Node *)(qry->qual),
						rt_index,
						sublevels_up))
					return TRUE;

				if (rangeTableEntry_used(
						(Node *)(qry->havingQual),
						rt_index,
						sublevels_up))
					return TRUE;

				if (rangeTableEntry_used(
						(Node *)(qry->groupClause),
						rt_index,
						sublevels_up))
					return TRUE;

				return FALSE;
360
			}
361 362 363 364 365 366 367 368
			break;

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


369
	}
370 371

	return FALSE;
372
}
373 374


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

386 387 388 389
	switch(nodeTag(node)) {
		case T_TargetEntry:
			{
				TargetEntry	*tle = (TargetEntry *)node;
390

391 392 393 394 395 396 397
				return attribute_used(
						(Node *)(tle->expr),
						rt_index,
						attno,
						sublevels_up);
			}
			break;
398

B
Bruce Momjian 已提交
399
		case T_Aggref:
400
			{
401
				Aggref	*aggref = (Aggref *)node;
402

403
				return attribute_used(
404
						(Node *)(aggref->target),
405 406 407 408 409
						rt_index,
						attno,
						sublevels_up);
			}
			break;
M
Marc G. Fournier 已提交
410

411 412 413
		case T_GroupClause:
			{
				GroupClause	*grp = (GroupClause *)node;
414

415 416 417 418 419 420 421
				return attribute_used(
						(Node *)(grp->entry),
						rt_index,
						attno,
						sublevels_up);
			}
			break;
422

423 424 425
		case T_Expr:
			{
				Expr	*exp = (Expr *)node;
426

427 428 429 430 431 432 433
				return attribute_used(
						(Node *)(exp->args),
						rt_index,
						attno,
						sublevels_up);
			}
			break;
434

435 436 437
		case T_Iter:
			{
				Iter	*iter = (Iter *)node;
438

439 440 441 442 443 444 445
				return attribute_used(
						(Node *)(iter->iterexpr),
						rt_index,
						attno,
						sublevels_up);
			}
			break;
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

				if (attribute_used(
						(Node *)(ref->refupperindexpr),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				if (attribute_used(
						(Node *)(ref->reflowerindexpr),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				if (attribute_used(
						(Node *)(ref->refexpr),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				if (attribute_used(
						(Node *)(ref->refassgnexpr),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				return FALSE;
			}
			break;
482

483 484 485
		case T_Var:
			{
				Var	*var = (Var *)node;
486

487 488 489 490 491 492
				if (var->varlevelsup == sublevels_up)
					return var->varno == rt_index;
				else
					return FALSE;
			}
			break;
493

494 495
		case T_Param:
			return FALSE;
496

497 498
		case T_Const:
			return FALSE;
499

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
		case T_List:
			{
				List	*l;

				foreach (l, (List *)node) {
					if (attribute_used(
							(Node *)lfirst(l),
							rt_index,
							attno,
							sublevels_up))
						return TRUE;
				}
				return FALSE;
			}
			break;

		case T_SubLink:
			{
				SubLink	*sub = (SubLink *)node;

				if (attribute_used(
						(Node *)(sub->lefthand),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				if (attribute_used(
						(Node *)(sub->subselect),
						rt_index,
						attno,
						sublevels_up + 1))
					return TRUE;

				return FALSE;
			}
			break;

		case T_Query:
			{
				Query	*qry = (Query *)node;

				if (attribute_used(
						(Node *)(qry->targetList),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				if (attribute_used(
						(Node *)(qry->qual),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				if (attribute_used(
						(Node *)(qry->havingQual),
						rt_index,
						attno,
						sublevels_up))
					return TRUE;

				if (attribute_used(
						(Node *)(qry->groupClause),
						rt_index,
						attno,
						sublevels_up))
					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;
578 579


580 581
	}

582 583
	return FALSE;
}
584

585

586
/*
B
Bruce Momjian 已提交
587
 * modifyAggrefUplevel -
588 589 590 591 592
 *	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 已提交
593
modifyAggrefUplevel(Node *node)
594 595 596 597 598 599 600 601 602
{
	if (node == NULL)
		return;

	switch(nodeTag(node)) {
		case T_TargetEntry:
			{
				TargetEntry	*tle = (TargetEntry *)node;

B
Bruce Momjian 已提交
603
				modifyAggrefUplevel(
604 605 606 607
						(Node *)(tle->expr));
			}
			break;

B
Bruce Momjian 已提交
608
		case T_Aggref:
609
			{
610
				Aggref	*aggref = (Aggref *)node;
611

B
Bruce Momjian 已提交
612
				modifyAggrefUplevel(
613
						(Node *)(aggref->target));
614 615 616 617 618 619 620
			}
			break;

		case T_Expr:
			{
				Expr	*exp = (Expr *)node;

B
Bruce Momjian 已提交
621
				modifyAggrefUplevel(
622 623 624 625 626 627 628 629
						(Node *)(exp->args));
			}
			break;

		case T_Iter:
			{
				Iter	*iter = (Iter *)node;

B
Bruce Momjian 已提交
630
				modifyAggrefUplevel(
631 632 633 634 635 636 637 638
						(Node *)(iter->iterexpr));
			}
			break;

		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

B
Bruce Momjian 已提交
639
				modifyAggrefUplevel(
640
						(Node *)(ref->refupperindexpr));
B
Bruce Momjian 已提交
641
				modifyAggrefUplevel(
642
						(Node *)(ref->reflowerindexpr));
B
Bruce Momjian 已提交
643
				modifyAggrefUplevel(
644
						(Node *)(ref->refexpr));
B
Bruce Momjian 已提交
645
				modifyAggrefUplevel(
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
						(Node *)(ref->refassgnexpr));
			}
			break;

		case T_Var:
			{
				Var	*var = (Var *)node;

				var->varlevelsup++;
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
				List	*l;

				foreach (l, (List *)node)
B
Bruce Momjian 已提交
669
					modifyAggrefUplevel(
670 671 672 673 674 675 676 677
							(Node *)lfirst(l));
			}
			break;

		case T_SubLink:
			{
				SubLink	*sub = (SubLink *)node;

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

B
Bruce Momjian 已提交
681
				modifyAggrefUplevel(
682 683
						(Node *)(sub->oper));

B
Bruce Momjian 已提交
684
				modifyAggrefUplevel(
685 686 687 688 689 690 691 692
						(Node *)(sub->subselect));
			}
			break;

		case T_Query:
			{
				Query	*qry = (Query *)node;

B
Bruce Momjian 已提交
693
				modifyAggrefUplevel(
694 695
						(Node *)(qry->targetList));

B
Bruce Momjian 已提交
696
				modifyAggrefUplevel(
697 698
						(Node *)(qry->qual));

B
Bruce Momjian 已提交
699
				modifyAggrefUplevel(
700 701
						(Node *)(qry->havingQual));

B
Bruce Momjian 已提交
702
				modifyAggrefUplevel(
703 704 705 706 707
						(Node *)(qry->groupClause));
			}
			break;

		default:
B
Bruce Momjian 已提交
708
			elog(NOTICE, "unknown node tag %d in modifyAggrefUplevel()", nodeTag(node));
709 710 711 712 713 714 715 716 717
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
718
 * modifyAggrefChangeVarnodes -
719 720 721 722 723
 *	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 已提交
724
modifyAggrefChangeVarnodes(Node **nodePtr, int rt_index, int new_index, int sublevels_up)
725 726 727 728 729 730 731 732 733 734 735
{
	Node	*node = *nodePtr;

	if (node == NULL)
		return;

	switch(nodeTag(node)) {
		case T_TargetEntry:
			{
				TargetEntry	*tle = (TargetEntry *)node;

B
Bruce Momjian 已提交
736
				modifyAggrefChangeVarnodes(
737 738 739 740 741 742 743
						(Node **)(&(tle->expr)),
						rt_index,
						new_index,
						sublevels_up);
			}
			break;

B
Bruce Momjian 已提交
744
		case T_Aggref:
745
			{
746
				Aggref	*aggref = (Aggref *)node;
747

B
Bruce Momjian 已提交
748
				modifyAggrefChangeVarnodes(
749
						(Node **)(&(aggref->target)),
750 751 752 753 754 755 756 757 758 759
						rt_index,
						new_index,
						sublevels_up);
			}
			break;

		case T_GroupClause:
			{
				GroupClause	*grp = (GroupClause *)node;

B
Bruce Momjian 已提交
760
				modifyAggrefChangeVarnodes(
761 762 763 764 765 766 767 768 769 770 771
						(Node **)(&(grp->entry)),
						rt_index,
						new_index,
						sublevels_up);
			}
			break;

		case T_Expr:
			{
				Expr	*exp = (Expr *)node;

B
Bruce Momjian 已提交
772
				modifyAggrefChangeVarnodes(
773 774 775 776 777 778 779 780 781 782 783
						(Node **)(&(exp->args)),
						rt_index,
						new_index,
						sublevels_up);
			}
			break;

		case T_Iter:
			{
				Iter	*iter = (Iter *)node;

B
Bruce Momjian 已提交
784
				modifyAggrefChangeVarnodes(
785 786 787 788 789 790 791 792 793 794 795
						(Node **)(&(iter->iterexpr)),
						rt_index,
						new_index,
						sublevels_up);
			}
			break;

		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

B
Bruce Momjian 已提交
796
				modifyAggrefChangeVarnodes(
797 798 799 800
						(Node **)(&(ref->refupperindexpr)),
						rt_index,
						new_index,
						sublevels_up);
B
Bruce Momjian 已提交
801
				modifyAggrefChangeVarnodes(
802 803 804 805
						(Node **)(&(ref->reflowerindexpr)),
						rt_index,
						new_index,
						sublevels_up);
B
Bruce Momjian 已提交
806
				modifyAggrefChangeVarnodes(
807 808 809 810
						(Node **)(&(ref->refexpr)),
						rt_index,
						new_index,
						sublevels_up);
B
Bruce Momjian 已提交
811
				modifyAggrefChangeVarnodes(
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
						(Node **)(&(ref->refassgnexpr)),
						rt_index,
						new_index,
						sublevels_up);
			}
			break;

		case T_Var:
			{
				Var	*var = (Var *)node;

				if (var->varlevelsup == sublevels_up &&
						var->varno == rt_index) {
					var = copyObject(var);
					var->varno = new_index;
					var->varnoold = new_index;
					var->varlevelsup = 0;

					*nodePtr = (Node *)var;
				}
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
				List	*l;

				foreach (l, (List *)node)
B
Bruce Momjian 已提交
846
					modifyAggrefChangeVarnodes(
847 848 849 850 851 852 853 854 855 856 857
							(Node **)(&lfirst(l)),
							rt_index,
							new_index,
							sublevels_up);
			}
			break;

		case T_SubLink:
			{
				SubLink	*sub = (SubLink *)node;

B
Bruce Momjian 已提交
858
				modifyAggrefChangeVarnodes(
859 860 861 862 863
						(Node **)(&(sub->lefthand)),
						rt_index,
						new_index,
						sublevels_up);

B
Bruce Momjian 已提交
864
				modifyAggrefChangeVarnodes(
865 866 867 868 869
						(Node **)(&(sub->oper)),
						rt_index,
						new_index,
						sublevels_up);

B
Bruce Momjian 已提交
870
				modifyAggrefChangeVarnodes(
871 872 873 874 875 876 877 878 879 880 881
						(Node **)(&(sub->subselect)),
						rt_index,
						new_index,
						sublevels_up + 1);
			}
			break;

		case T_Query:
			{
				Query	*qry = (Query *)node;

B
Bruce Momjian 已提交
882
				modifyAggrefChangeVarnodes(
883 884 885 886 887
						(Node **)(&(qry->targetList)),
						rt_index,
						new_index,
						sublevels_up);

B
Bruce Momjian 已提交
888
				modifyAggrefChangeVarnodes(
889 890 891 892 893
						(Node **)(&(qry->qual)),
						rt_index,
						new_index,
						sublevels_up);

B
Bruce Momjian 已提交
894
				modifyAggrefChangeVarnodes(
895 896 897 898 899
						(Node **)(&(qry->havingQual)),
						rt_index,
						new_index,
						sublevels_up);

B
Bruce Momjian 已提交
900
				modifyAggrefChangeVarnodes(
901 902 903 904 905 906 907 908
						(Node **)(&(qry->groupClause)),
						rt_index,
						new_index,
						sublevels_up);
			}
			break;

		default:
B
Bruce Momjian 已提交
909
			elog(NOTICE, "unknown node tag %d in modifyAggrefChangeVarnodes()", nodeTag(node));
910 911 912 913 914 915 916 917 918
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
919 920
 * modifyAggrefDropQual -
 *	remove the pure aggref clase from a qualification
921 922
 */
static void
B
Bruce Momjian 已提交
923
modifyAggrefDropQual(Node **nodePtr, Node *orignode, Expr *expr)
924 925 926 927 928 929 930 931 932 933
{
	Node	*node = *nodePtr;

	if (node == NULL)
		return;

	switch(nodeTag(node)) {
		case T_Var:
			break;

B
Bruce Momjian 已提交
934
		case T_Aggref:
935
			{
936 937
				Aggref	*aggref = (Aggref *)node;
				Aggref	*oaggref = (Aggref *)orignode;
938

B
Bruce Momjian 已提交
939
				modifyAggrefDropQual(
940 941
						(Node **)(&(aggref->target)),
						(Node *)(oaggref->target),
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
						expr);
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_GroupClause:
			break;

		case T_Expr:
			{
				Expr	*this_expr = (Expr *)node;
				Expr	*orig_expr = (Expr *)orignode;

				if (orig_expr == expr) {
					Const	*ctrue;

					if (expr->typeOid != BOOLOID)
						elog(ERROR,
							"aggregate expression in qualification isn't of type bool");
					ctrue = makeNode(Const);
					ctrue->consttype = BOOLOID;
					ctrue->constlen = 1;
					ctrue->constisnull = FALSE;
					ctrue->constvalue = (Datum)TRUE;
					ctrue->constbyval = TRUE;

					*nodePtr = (Node *)ctrue;
				}
				else
B
Bruce Momjian 已提交
976
					modifyAggrefDropQual(
977 978 979 980 981 982 983 984 985 986 987
						(Node **)(&(this_expr->args)),
						(Node *)(orig_expr->args),
						expr);
			}
			break;

		case T_Iter:
			{
				Iter	*iter = (Iter *)node;
				Iter	*oiter = (Iter *)orignode;

B
Bruce Momjian 已提交
988
				modifyAggrefDropQual(
989 990 991 992 993 994 995 996 997 998 999
						(Node **)(&(iter->iterexpr)),
						(Node *)(oiter->iterexpr),
						expr);
			}
			break;

		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;
				ArrayRef	*oref = (ArrayRef *)orignode;

B
Bruce Momjian 已提交
1000
				modifyAggrefDropQual(
1001 1002 1003
						(Node **)(&(ref->refupperindexpr)),
						(Node *)(oref->refupperindexpr),
						expr);
B
Bruce Momjian 已提交
1004
				modifyAggrefDropQual(
1005 1006 1007
						(Node **)(&(ref->reflowerindexpr)),
						(Node *)(oref->reflowerindexpr),
						expr);
B
Bruce Momjian 已提交
1008
				modifyAggrefDropQual(
1009 1010 1011
						(Node **)(&(ref->refexpr)),
						(Node *)(oref->refexpr),
						expr);
B
Bruce Momjian 已提交
1012
				modifyAggrefDropQual(
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
						(Node **)(&(ref->refassgnexpr)),
						(Node *)(oref->refassgnexpr),
						expr);
			}
			break;

		case T_List:
			{
				List	*l;
				List	*ol = (List *)orignode;
				int	li = 0;

				foreach (l, (List *)node) {
B
Bruce Momjian 已提交
1026
					modifyAggrefDropQual(
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
							(Node **)(&(lfirst(l))),
							(Node *)nth(li, ol),
							expr);
					li++;
				}
			}
			break;

		case T_SubLink:
			{
				SubLink	*sub = (SubLink *)node;
				SubLink	*osub = (SubLink *)orignode;

B
Bruce Momjian 已提交
1040
				modifyAggrefDropQual(
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
						(Node **)(&(sub->subselect)),
						(Node *)(osub->subselect),
						expr);
			}
			break;

		case T_Query:
			{
				Query	*qry = (Query *)node;
				Query	*oqry = (Query *)orignode;

B
Bruce Momjian 已提交
1052
				modifyAggrefDropQual(
1053 1054 1055 1056
						(Node **)(&(qry->qual)),
						(Node *)(oqry->qual),
						expr);

B
Bruce Momjian 已提交
1057
				modifyAggrefDropQual(
1058 1059 1060 1061 1062 1063 1064
						(Node **)(&(qry->havingQual)),
						(Node *)(oqry->havingQual),
						expr);
			}
			break;

		default:
B
Bruce Momjian 已提交
1065
			elog(NOTICE, "unknown node tag %d in modifyAggrefDropQual()", nodeTag(node));
1066 1067 1068 1069 1070 1071 1072 1073 1074
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


/*
B
Bruce Momjian 已提交
1075
 * modifyAggrefMakeSublink -
1076 1077 1078 1079
 *	Create a sublink node for a qualification expression that
 *	uses an aggregate column of a view
 */
static SubLink *
B
Bruce Momjian 已提交
1080
modifyAggrefMakeSublink(Expr *origexp, Query *parsetree)
1081 1082 1083 1084 1085
{
	SubLink		*sublink;
	Query		*subquery;
	Node		*subqual;
	RangeTblEntry	*rte;
B
Bruce Momjian 已提交
1086
	Aggref		*aggref;
1087 1088 1089 1090 1091
	Var		*target;
	TargetEntry	*tle;
	Resdom		*resdom;
	Expr		*exp = copyObject(origexp);

B
Bruce Momjian 已提交
1092
	if (nodeTag(nth(0, exp->args)) == T_Aggref)
T
Thomas G. Lockhart 已提交
1093
	{
B
Bruce Momjian 已提交
1094
		if (nodeTag(nth(1, exp->args)) == T_Aggref)
1095 1096 1097
			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 已提交
1098
	}
1099

B
Bruce Momjian 已提交
1100 1101
	aggref = (Aggref *)nth(1, exp->args);
	target	= (Var *)(aggref->target);
1102 1103 1104 1105
	rte	= (RangeTblEntry *)nth(target->varno - 1, parsetree->rtable);
	tle	= makeNode(TargetEntry);
	resdom	= makeNode(Resdom);

B
Bruce Momjian 已提交
1106
	aggref->usenulls = TRUE;
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

	resdom->resno	= 1;
	resdom->restype	= ((Oper *)(exp->oper))->opresulttype;
	resdom->restypmod = -1;
	resdom->resname = pstrdup("<noname>");
	resdom->reskey	= 0;
	resdom->reskeyop = 0;
	resdom->resjunk	= 0;

	tle->resdom	= resdom;
B
Bruce Momjian 已提交
1117
	tle->expr	= (Node *)aggref;
1118 1119

	subqual = copyObject(parsetree->qual);
B
Bruce Momjian 已提交
1120
	modifyAggrefDropQual((Node **)&subqual, (Node *)parsetree->qual, origexp);
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137

	sublink = makeNode(SubLink);
	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;
1138
	subquery->isTemp		= FALSE;
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
	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;


B
Bruce Momjian 已提交
1152
	modifyAggrefUplevel((Node *)sublink);
1153

B
Bruce Momjian 已提交
1154
	modifyAggrefChangeVarnodes((Node **)&(sublink->lefthand), target->varno,
1155
			1, target->varlevelsup);
B
Bruce Momjian 已提交
1156
	modifyAggrefChangeVarnodes((Node **)&(sublink->oper), target->varno,
1157
			1, target->varlevelsup);
B
Bruce Momjian 已提交
1158
	modifyAggrefChangeVarnodes((Node **)&(sublink->subselect), target->varno,
1159 1160 1161 1162 1163 1164 1165
			1, target->varlevelsup);

	return sublink;
}


/*
B
Bruce Momjian 已提交
1166
 * modifyAggrefQual -
1167 1168 1169 1170 1171 1172
 *	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 已提交
1173
modifyAggrefQual(Node **nodePtr, Query *parsetree)
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
{
	Node	*node = *nodePtr;

	if (node == NULL)
		return;

	switch(nodeTag(node)) {
		case T_Var:
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_GroupClause:
			{
				GroupClause	*grp = (GroupClause *)node;

B
Bruce Momjian 已提交
1194
				modifyAggrefQual(
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
						(Node **)(&(grp->entry)),
						parsetree);
			}
			break;

		case T_Expr:
			{
				Expr	*exp = (Expr *)node;
				SubLink	*sub;


				if (length(exp->args) != 2) {
B
Bruce Momjian 已提交
1207
					modifyAggrefQual(
1208 1209 1210 1211 1212
						(Node **)(&(exp->args)),
						parsetree);
					break;
				}

B
Bruce Momjian 已提交
1213 1214
				if (nodeTag(nth(0, exp->args)) != T_Aggref &&
					nodeTag(nth(1, exp->args)) != T_Aggref) {
1215

B
Bruce Momjian 已提交
1216
					modifyAggrefQual(
1217 1218 1219 1220 1221
						(Node **)(&(exp->args)),
						parsetree);
					break;
				}

B
Bruce Momjian 已提交
1222
				sub = modifyAggrefMakeSublink(exp,
1223 1224 1225 1226 1227 1228 1229
						parsetree);

				*nodePtr = (Node *)sub;
				parsetree->hasSubLinks = TRUE;
			}
			break;

T
Thomas G. Lockhart 已提交
1230 1231 1232 1233 1234
		case T_CaseExpr:
			{
				/* 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 已提交
1235
				modifyAggrefQual(
T
Thomas G. Lockhart 已提交
1236 1237 1238
						(Node **)(&(((CaseExpr *)node)->args)),
						parsetree);

B
Bruce Momjian 已提交
1239
				modifyAggrefQual(
T
Thomas G. Lockhart 已提交
1240 1241 1242 1243 1244 1245 1246
						(Node **)(&(((CaseExpr *)node)->defresult)),
						parsetree);
			}
			break;

		case T_CaseWhen:
			{
B
Bruce Momjian 已提交
1247
				modifyAggrefQual(
T
Thomas G. Lockhart 已提交
1248 1249 1250
						(Node **)(&(((CaseWhen *)node)->expr)),
						parsetree);

B
Bruce Momjian 已提交
1251
				modifyAggrefQual(
T
Thomas G. Lockhart 已提交
1252 1253 1254 1255 1256
						(Node **)(&(((CaseWhen *)node)->result)),
						parsetree);
			}
			break;

1257 1258 1259 1260
		case T_Iter:
			{
				Iter	*iter = (Iter *)node;

B
Bruce Momjian 已提交
1261
				modifyAggrefQual(
1262 1263 1264 1265 1266 1267 1268 1269 1270
						(Node **)(&(iter->iterexpr)),
						parsetree);
			}
			break;

		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

B
Bruce Momjian 已提交
1271
				modifyAggrefQual(
1272 1273
						(Node **)(&(ref->refupperindexpr)),
						parsetree);
B
Bruce Momjian 已提交
1274
				modifyAggrefQual(
1275 1276
						(Node **)(&(ref->reflowerindexpr)),
						parsetree);
B
Bruce Momjian 已提交
1277
				modifyAggrefQual(
1278 1279
						(Node **)(&(ref->refexpr)),
						parsetree);
B
Bruce Momjian 已提交
1280
				modifyAggrefQual(
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
						(Node **)(&(ref->refassgnexpr)),
						parsetree);
			}
			break;

		case T_List:
			{
				List	*l;

				foreach (l, (List *)node)
B
Bruce Momjian 已提交
1291
					modifyAggrefQual(
1292 1293 1294 1295 1296 1297 1298 1299 1300
							(Node **)(&(lfirst(l))),
							parsetree);
			}
			break;

		case T_SubLink:
			{
				SubLink	*sub = (SubLink *)node;

B
Bruce Momjian 已提交
1301
				modifyAggrefQual(
1302 1303 1304 1305 1306 1307 1308 1309 1310
						(Node **)(&(sub->subselect)),
						(Query *)(sub->subselect));
			}
			break;

		case T_Query:
			{
				Query	*qry = (Query *)node;

B
Bruce Momjian 已提交
1311
				modifyAggrefQual(
1312 1313 1314
						(Node **)(&(qry->qual)),
						parsetree);

B
Bruce Momjian 已提交
1315
				modifyAggrefQual(
1316 1317 1318 1319 1320 1321
						(Node **)(&(qry->havingQual)),
						parsetree);
			}
			break;

		default:
B
Bruce Momjian 已提交
1322
			elog(NOTICE, "unknown node tag %d in modifyAggrefQual()", nodeTag(node));
1323 1324 1325 1326 1327 1328 1329 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
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;


	}
}


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 已提交
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
static void 
apply_RIR_adjust_sublevel(Node *node, int sublevels_up)
{
	if (node == NULL)
		return;

	switch(nodeTag(node)) {
		case T_TargetEntry:
			{
				TargetEntry	*tle = (TargetEntry *)node;

				apply_RIR_adjust_sublevel(
						(Node *)(tle->expr),
						sublevels_up);
			}
			break;

B
Bruce Momjian 已提交
1380
		case T_Aggref:
B
Bruce Momjian 已提交
1381
			{
1382
				Aggref	*aggref = (Aggref *)node;
B
Bruce Momjian 已提交
1383 1384

				apply_RIR_adjust_sublevel(
1385
						(Node *)(aggref->target),
B
Bruce Momjian 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
						sublevels_up);
			}
			break;

		case T_GroupClause:
			{
				GroupClause	*grp = (GroupClause *)node;

				apply_RIR_adjust_sublevel(
						(Node *)(grp->entry),
						sublevels_up);
			}
			break;

		case T_Expr:
			{
				Expr	*exp = (Expr *)node;

				apply_RIR_adjust_sublevel(
						(Node *)(exp->args),
						sublevels_up);
			}
			break;

		case T_Iter:
			{
				Iter	*iter = (Iter *)node;

				apply_RIR_adjust_sublevel(
						(Node *)(iter->iterexpr),
						sublevels_up);
			}
			break;

		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

				apply_RIR_adjust_sublevel(
						(Node *)(ref->refupperindexpr),
						sublevels_up);

				apply_RIR_adjust_sublevel(
						(Node *)(ref->reflowerindexpr),
						sublevels_up);

				apply_RIR_adjust_sublevel(
						(Node *)(ref->refexpr),
						sublevels_up);

				apply_RIR_adjust_sublevel(
						(Node *)(ref->refassgnexpr),
						sublevels_up);
			}
			break;

		case T_Var:
			{
				Var	*var = (Var *)node;

				var->varlevelsup = sublevels_up;
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
				List	*l;

				foreach (l, (List *)node) {
					apply_RIR_adjust_sublevel(
							(Node *)lfirst(l),
							sublevels_up);
				}
			}
			break;

1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
		case T_CaseExpr:
			{
				CaseExpr	*exp = (CaseExpr *)node;

				apply_RIR_adjust_sublevel(
						(Node *)(exp->args),
						sublevels_up);

				apply_RIR_adjust_sublevel(
						(Node *)(exp->defresult),
						sublevels_up);
			}
			break;

		case T_CaseWhen:
			{
				CaseWhen	*exp = (CaseWhen *)node;

				apply_RIR_adjust_sublevel(
						(Node *)(exp->expr),
						sublevels_up);

				apply_RIR_adjust_sublevel(
						(Node *)(exp->result),
						sublevels_up);
			}
			break;

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


	}
}


1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
static void
apply_RIR_view(Node **nodePtr, int rt_index, RangeTblEntry *rte, List *tlist, int *modified, int sublevels_up)
{
	Node	*node = *nodePtr;

	if (node == NULL)
		return;

	switch(nodeTag(node)) {
		case T_TargetEntry:
			{
				TargetEntry	*tle = (TargetEntry *)node;

				apply_RIR_view(
						(Node **)(&(tle->expr)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

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

				apply_RIR_view(
1534
						(Node **)(&(aggref->target)),
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

		case T_GroupClause:
			{
				GroupClause	*grp = (GroupClause *)node;

				apply_RIR_view(
						(Node **)(&(grp->entry)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

		case T_Expr:
			{
				Expr	*exp = (Expr *)node;

				apply_RIR_view(
						(Node **)(&(exp->args)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

		case T_Iter:
			{
				Iter	*iter = (Iter *)node;

				apply_RIR_view(
						(Node **)(&(iter->iterexpr)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

				apply_RIR_view(
						(Node **)(&(ref->refupperindexpr)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
				apply_RIR_view(
						(Node **)(&(ref->reflowerindexpr)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
				apply_RIR_view(
						(Node **)(&(ref->refexpr)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
				apply_RIR_view(
						(Node **)(&(ref->refassgnexpr)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

		case T_Var:
			{
				Var	*var = (Var *)node;

				if (var->varlevelsup == sublevels_up &&
						var->varno == rt_index) {
					Node		*exp;

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

					if (exp == NULL) {
						*nodePtr = make_null(var->vartype);
						return;
					}

B
Bruce Momjian 已提交
1640
					exp = copyObject(exp);
B
Bruce Momjian 已提交
1641 1642
					if (var->varlevelsup > 0)
						apply_RIR_adjust_sublevel(exp, var->varlevelsup);
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
					*nodePtr = exp;
					*modified = TRUE;
				}
			}
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
				List	*l;

				foreach (l, (List *)node)
					apply_RIR_view(
							(Node **)(&(lfirst(l))),
							rt_index,
							rte,
							tlist,
							modified,
							sublevels_up);
			}
			break;

		case T_SubLink:
			{
B
Hi!  
Bruce Momjian 已提交
1672 1673
				SubLink *sub = (SubLink *)node;
				List *tmp_lefthand, *tmp_oper;
1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689

				apply_RIR_view(
						(Node **)(&(sub->lefthand)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);

				apply_RIR_view(
						(Node **)(&(sub->subselect)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up + 1);
B
Hi!  
Bruce Momjian 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698

				/***S*I***/
				tmp_lefthand = sub->lefthand;				
				foreach(tmp_oper, sub->oper)
				  {				    
				    lfirst(((Expr *) lfirst(tmp_oper))->args) = 
				      lfirst(tmp_lefthand);
				    tmp_lefthand = lnext(tmp_lefthand);
				  }								
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
			}
			break;

		case T_Query:
			{
				Query	*qry = (Query *)node;

				apply_RIR_view(
						(Node **)(&(qry->targetList)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);

				apply_RIR_view(
						(Node **)(&(qry->qual)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);

				apply_RIR_view(
						(Node **)(&(qry->havingQual)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);

				apply_RIR_view(
						(Node **)(&(qry->groupClause)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
		case T_CaseExpr:
			{
				CaseExpr	*exp = (CaseExpr *)node;

				apply_RIR_view(
						(Node **)(&(exp->args)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);

				apply_RIR_view(
						(Node **)(&(exp->defresult)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

		case T_CaseWhen:
			{
				CaseWhen	*exp = (CaseWhen *)node;

				apply_RIR_view(
						(Node **)(&(exp->expr)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);

				apply_RIR_view(
						(Node **)(&(exp->result)),
						rt_index,
						rte,
						tlist,
						modified,
						sublevels_up);
			}
			break;

1784 1785 1786 1787 1788 1789 1790
		default:
			elog(NOTICE, "unknown node tag %d in apply_RIR_view()", nodeTag(node));
			elog(NOTICE, "Node is: %s", nodeToString(node));
			break;
	}
}

1791
extern	void CheckSelectForUpdate(Query *rule_action);	/* in analyze.c */
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803

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,
1804 1805
			   *rt,
			   *l;
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
	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;

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
	/* FOR UPDATE of view... */
	foreach (l, parsetree->rowMark)
	{
		if (((RowMark*)lfirst(l))->rti == rt_index)
			break;
	}
	if (l != NULL)	/* oh, hell -:) */
	{
		RowMark	   *newrm;
		Index		rti = 1;
		List	   *l2;

1852
		CheckSelectForUpdate(rule_action);
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
		/* 
		 * 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.
		 */
		((RowMark*)lfirst(l))->info &= ~ROW_MARK_FOR_UPDATE;
		foreach (l2, rule_action->rtable)
		{
			/*
			 * RTable of VIEW has two entries of VIEW itself -
			 * we use relid to skip them.
			 */
			if (relation->rd_id != ((RangeTblEntry*)lfirst(l2))->relid)
			{
				newrm = makeNode(RowMark);
				newrm->rti = rti + rt_length;
				newrm->info = ROW_MARK_FOR_UPDATE;
				lnext(l) = lcons(newrm, lnext(l));
				l = lnext(l);
			}
			rti++;
		}
	}

1878
	rule_action->rtable = rtable;
B
Bruce Momjian 已提交
1879 1880
	OffsetVarNodes((Node *) rule_qual,   rt_length, 0);
	OffsetVarNodes((Node *) rule_action, rt_length, 0);
1881

B
Bruce Momjian 已提交
1882
	ChangeVarNodes((Node *) rule_qual, 
1883
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
B
Bruce Momjian 已提交
1884
	ChangeVarNodes((Node *) rule_action,
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);

	if (relation_level)
	{
	  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);
	}
	else
	{
	  HandleRIRAttributeRule(parsetree, rtable, rule_action->targetList,
				 rt_index, rule->attrno, modified, &badsql);
	}
	if (*modified && !badsql) {
	  AddQual(parsetree, rule_action->qual);
	  /* This will only work if the query made to the view defined by the following
	   * groupClause groups by the same attributes or does not use group at all! */
	  if (parsetree->groupClause == NULL)
	    parsetree->groupClause=rule_action->groupClause;
	  AddHavingQual(parsetree, rule_action->havingQual);
	  parsetree->hasAggs = (rule_action->hasAggs || parsetree->hasAggs);
	  parsetree->hasSubLinks = (rule_action->hasSubLinks ||  parsetree->hasSubLinks);
	}	
}


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

	switch(nodeTag(node)) {
		case T_TargetEntry:
			{
				TargetEntry	*tle = (TargetEntry *)node;

				fireRIRonSubselect(
						(Node *)(tle->expr));
			}
			break;

B
Bruce Momjian 已提交
1930
		case T_Aggref:
1931
			{
1932
				Aggref	*aggref = (Aggref *)node;
1933 1934

				fireRIRonSubselect(
1935
						(Node *)(aggref->target));
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
			}
			break;

		case T_GroupClause:
			{
				GroupClause	*grp = (GroupClause *)node;

				fireRIRonSubselect(
						(Node *)(grp->entry));
			}
			break;

		case T_Expr:
			{
				Expr	*exp = (Expr *)node;

				fireRIRonSubselect(
						(Node *)(exp->args));
			}
			break;

		case T_Iter:
			{
				Iter	*iter = (Iter *)node;

				fireRIRonSubselect(
						(Node *)(iter->iterexpr));
			}
			break;

		case T_ArrayRef:
			{
				ArrayRef	*ref = (ArrayRef *)node;

				fireRIRonSubselect(
						(Node *)(ref->refupperindexpr));
				fireRIRonSubselect(
						(Node *)(ref->reflowerindexpr));
				fireRIRonSubselect(
						(Node *)(ref->refexpr));
				fireRIRonSubselect(
						(Node *)(ref->refassgnexpr));
			}
			break;

		case T_Var:
			break;

		case T_Param:
			break;

		case T_Const:
			break;

		case T_List:
			{
				List	*l;

				foreach (l, (List *)node)
					fireRIRonSubselect(
							(Node *)(lfirst(l)));
			}
			break;

		case T_SubLink:
			{
				SubLink	*sub = (SubLink *)node;
				Query	*qry;

				fireRIRonSubselect(
						(Node *)(sub->lefthand));

				qry = fireRIRrules((Query *)(sub->subselect));

				fireRIRonSubselect(
						(Node *)qry);

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

T
Thomas G. Lockhart 已提交
2017
		case T_CaseExpr:
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
			{
				CaseExpr	*exp = (CaseExpr *)node;

				fireRIRonSubselect(
						(Node *)(exp->args));

				fireRIRonSubselect(
						(Node *)(exp->defresult));
			}
			break;

T
Thomas G. Lockhart 已提交
2029
		case T_CaseWhen:
2030 2031 2032 2033 2034 2035 2036 2037 2038
			{
				CaseWhen	*exp = (CaseWhen *)node;

				fireRIRonSubselect(
						(Node *)(exp->expr));

				fireRIRonSubselect(
						(Node *)(exp->result));
			}
T
Thomas G. Lockhart 已提交
2039 2040
			break;

2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
		case T_Query:
			{
				Query	*qry = (Query *)node;

				fireRIRonSubselect(
						(Node *)(qry->targetList));

				fireRIRonSubselect(
						(Node *)(qry->qual));

				fireRIRonSubselect(
						(Node *)(qry->havingQual));

				fireRIRonSubselect(
						(Node *)(qry->groupClause));
			}
			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)
{
	int		rt_index;
	RangeTblEntry	*rte;
	Relation	rel;
	List		*locks;
	RuleLock	*rules;
	RewriteRule	*rule;
	RewriteRule	RIRonly;
	int		modified;
	int		i;
	List		*l;

	rt_index = 0;
	while(rt_index < length(parsetree->rtable)) {
		++rt_index;

		if (!rangeTableEntry_used((Node *)parsetree, rt_index, 0))
			continue;
		
		rte = nth(rt_index - 1, parsetree->rtable);
		rel = heap_openr(rte->relname);
		if (rel->rd_rules == NULL) {
			heap_close(rel);
			continue;
		}

		rules = rel->rd_rules;
		locks = NIL;

		/*
		 * Collect the RIR rules that we must apply
		 */
		for (i = 0; i < rules->numLocks; i++) {
			rule = rules->rules[i];
			if (rule->event != CMD_SELECT)
				continue;
			
			if (rule->attrno > 0 &&
					!attribute_used((Node *)parsetree,
							rt_index,
							rule->attrno, 0))
				continue;

			locks = lappend(locks, rule);
		}

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

		/*
		 * Now apply them
		 */
		foreach (l, locks) {
			rule = lfirst(l);

			RIRonly.event	= rule->event;
			RIRonly.attrno	= rule->attrno;
			RIRonly.qual	= rule->qual;
			RIRonly.actions	= rule->actions;

			ApplyRetrieveRule(parsetree,
					&RIRonly,
					rt_index,
					RIRonly.attrno == -1,
					rel,
					&modified);
		}

		heap_close(rel);
	}

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

	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);
2177
		}
2178 2179
		else
			regular = lappend(regular, rule_lock);
2180
	}
2181 2182
	regular = nconc(regular, instead_qualified);
	return nconc(regular, instead_rules);
2183 2184
}

2185 2186


2187
static Query *
2188 2189 2190
CopyAndAddQual(Query *parsetree,
			   List *actions,
			   Node *rule_qual,
2191 2192
			   int rt_index,
			   CmdType event)
2193
{
2194 2195 2196
	Query	   *new_tree = (Query *) copyObject(parsetree);
	Node	   *new_qual = NULL;
	Query	   *rule_action = NULL;
2197 2198 2199 2200 2201 2202 2203

	if (actions)
		rule_action = lfirst(actions);
	if (rule_qual != NULL)
		new_qual = (Node *) copyObject(rule_qual);
	if (rule_action != NULL)
	{
2204 2205
		List	   *rtable;
		int			rt_length;
2206 2207 2208 2209 2210

		rtable = new_tree->rtable;
		rt_length = length(rtable);
		rtable = append(rtable, listCopy(rule_action->rtable));
		new_tree->rtable = rtable;
B
Bruce Momjian 已提交
2211
		OffsetVarNodes(new_qual, rt_length, 0);
2212
		ChangeVarNodes(new_qual, PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
2213 2214 2215 2216 2217
	}
	/* XXX -- where current doesn't work for instead nothing.... yet */
	AddNotQual(new_tree, new_qual);

	return new_tree;
2218 2219 2220
}


2221

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

	/* choose rule to fire from list of rules */
	if (locks == NIL)
	{
2248
		return NIL;
2249
	}
2250

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

2260
		/*
2261 2262 2263 2264 2265 2266
		 * 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.
2267
		 */
2268 2269 2270 2271
		if (rule_lock->isInstead &&
			parsetree->commandType != CMD_SELECT)
		{
			RangeTblEntry *rte;
2272 2273 2274
			int32		acl_rc;
			int32		reqperm;

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

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

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

			/* ----------
			 * 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.
			 * ----------
			 */
2321
			if (*qual_products == NIL)
M
 
Marc G. Fournier 已提交
2322
				qual_product = parsetree;
2323 2324
			else
				qual_product = (Query *) nth(0, *qual_products);
M
 
Marc G. Fournier 已提交
2325

2326 2327 2328 2329 2330 2331 2332 2333 2334
			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 已提交
2335 2336 2337 2338 2339 2340 2341

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

			*qual_products = lappend(NIL, qual_product);
		}

2342 2343
		foreach(r, actions)
		{
2344 2345
			Query	   *rule_action = lfirst(r);
			Node	   *rule_qual = copyObject(event_qual);
2346

M
 
Marc G. Fournier 已提交
2347 2348 2349
			if (rule_action->commandType == CMD_NOTHING)
				continue;

B
Bruce Momjian 已提交
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
			/*--------------------------------------------------
			 * 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;
			}

2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
			/*--------------------------------------------------
			 * 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 已提交
2395
			 * Event Qualification forces copying of parsetree and
2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419
			 * 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;
2420
			/*
2421 2422
			ProcessRetrieveQuery(info->rule_action, info->rt,
								 &orig_instead_flag, TRUE);
2423
			*/
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434

			/*--------------------------------------------------
			 * 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 已提交
2435 2436 2437 2438 2439 2440

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

M
 
Marc G. Fournier 已提交
2447 2448


2449
static List *
2450
RewriteQuery(Query *parsetree, bool *instead_flag, List **qual_products)
2451
{
2452
	CmdType		event;
2453 2454 2455 2456 2457
	List	   	*product_queries = NIL;
	int		result_relation = 0;
	RangeTblEntry	*rt_entry;
	Relation	rt_entry_relation = NULL;
	RuleLock	*rt_entry_locks = NULL;
2458

2459 2460 2461 2462
	Assert(parsetree != NULL);

	event = parsetree->commandType;

2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
	/*
	 * SELECT rules are handled later when we have all the
	 * queries that should get executed
	 */
	if (event == CMD_SELECT)
		return NIL;

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

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

	result_relation = parsetree->resultRelation;

2484 2485 2486 2487 2488 2489 2490 2491
	/*
	 * the statement is an update, insert or delete - fire rules
	 * on it.
	 */
	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 已提交
2492

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

2497
		product_queries = fireRules(parsetree,
2498 2499 2500 2501 2502 2503
					  result_relation,
					  event,
					  instead_flag,
					  locks,
					  qual_products);
	}
2504

2505
	return product_queries;
B
Bruce Momjian 已提交
2506

2507 2508
}

2509

2510 2511 2512 2513 2514
/*
 * 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
2515
#define REWRITE_INVOKE_MAX		10
2516 2517
#endif

2518
static int	numQueryRewriteInvoked = 0;
2519 2520 2521

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

2533 2534


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

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

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

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

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

M
 
Marc G. Fournier 已提交
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
	/* ----------
	 * 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);

2575 2576
	return rewritten;
}
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674


/*
 * 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.
	 * ----------
	 */
	if (parsetree->resultRelation > 0)
	{
		RangeTblEntry *rte;
		Relation	rd;
		List	   *tl;
		TargetEntry *tle;
		int			resdomno;

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

		foreach(tl, parsetree->targetList)
		{
			tle = (TargetEntry *) lfirst(tl);
			resdomno = attnameAttNum(rd, tle->resdom->resname);
			tle->resdom->resno = resdomno;
		}

		heap_close(rd);
	}
}


/*
 * QueryRewrite -
 *	  rewrite one query via query rewrite system, possibly returning 0
 *	  or many queries
 */
List *
QueryRewrite(Query *parsetree)
{
	List		*querylist;
	List		*results = NIL;
	List		*l;
	Query		*query;

	/*
	 * Step 1
	 *
	 * There still seems something broken with the resdom numbers
	 * so we reassign them first.
	 */
	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
	 */
	foreach (l, querylist) {
		query = (Query *)lfirst(l);
		results = lappend(results, fireRIRrules(query));
	}
	return results;
}
B
Hi!  
Bruce Momjian 已提交
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
/***S*I***/
/* 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 
 */
void check_targetlists_are_compatible(List *prev_target, List *current_target)
{
  List *next_target;
  
  if (length(prev_target) != 
      length(current_target))
    elog(ERROR,"Each UNION | EXCEPT | INTERSECT query must have the same number of columns.");		      
  foreach(next_target, current_target)
    {
      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;
#if FALSE
	  else
	    {
	      ((TargetEntry *) lfirst(prev_target))->resdom->restype = UNKNOWNOID;
	      ((TargetEntry *) lfirst(next_target))->resdom->restype = UNKNOWNOID;
	    }
#endif
	}
      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);
    }
}

/***S*I***/
/* Rewrites UNION INTERSECT and EXCEPT queries to semantiacally equivalent
 * queries that use IN and NOT IN subselects. 
 * 
 * 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
 * (sortClause etc) are attached to the new top Node (Note that the 
 * 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!) */
Query *
Except_Intersect_Rewrite (Query *parsetree)
{
 
  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;
2769
  bool	  isBinary, isPortal, isTemp;  
B
Hi!  
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 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
  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);	 
    }
    
  /* 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;  
2813 2814
  isTemp = parsetree->isTemp;

B
Hi!  
Bruce Momjian 已提交
2815 2816 2817 2818 2819 2820 2821 2822 2823 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 2881 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 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961
  /* 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; 
      create_list((Node *)lfirst(intersect), &intersect_list);
      
      /* 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;
2962 2963
  result->isTemp = isTemp;

B
Hi!  
Bruce Momjian 已提交
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
  /* 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;  
}

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

void create_list(Node *ptr, List **intersect_list)
{
  List *arg;
  
  if(IsA(ptr,Query))
    {
      /* The non negated node is attached at the beginning (lcons) */
      *intersect_list = lcons(ptr, *intersect_list);
      return;	   
    }
  
  if(IsA(ptr,Expr))
    {
      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)
	    {
	      create_list(lfirst(arg), intersect_list);
	    }	  
	  return;	  
	}
      return;	   
    }
}

/* 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
 * it again but return a pointer to the previously cooked version given in 'parsetree' 
 * instead. */
Node *intersect_tree_analyze(Node *tree, Node *first_select, Node *parsetree)
{
  Node *result = (Node *)NIL;
  List *arg;
  
  if(IsA(tree, SelectStmt))
    {
      QueryTreeList *qtree;
      
      /* If we get to the tree given in first_select return
       * parsetree instead of performing parse_analyze() */
      if(tree == first_select){
	result = parsetree;
      }
      else {	
	/* transform the 'raw' nodes to 'cooked' Query nodes */ 
	qtree = parse_analyze(lcons(tree, NIL), NULL);
	result = (Node *)qtree->qtrees[0];	
      }
      
    }  
  if(IsA(tree,Expr))
    {
      /* 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;	  
    }
  return result;  
}


3058 3059