rewriteHandler.c 56.7 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * rewriteHandler.c
4 5 6 7 8
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
9
 *	  $Header: /cvsroot/pgsql/src/backend/rewrite/rewriteHandler.c,v 1.61 1999/10/17 23:50:43 tgl Exp $
10 11 12 13 14
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"

B
Bruce Momjian 已提交
15
#include "access/heapam.h"
16
#include "catalog/pg_operator.h"
17
#include "catalog/pg_type.h"
B
Bruce Momjian 已提交
18
#include "miscadmin.h"
19
#include "nodes/makefuncs.h"
B
Bruce Momjian 已提交
20 21 22
#include "optimizer/clauses.h"
#include "optimizer/prep.h"
#include "parser/analyze.h"
23
#include "parser/parse_expr.h"
B
Bruce Momjian 已提交
24
#include "parser/parse_relation.h"
25
#include "parser/parse_oper.h"
B
Bruce Momjian 已提交
26 27 28 29 30 31 32
#include "parser/parse_target.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
#include "rewrite/locks.h"
#include "rewrite/rewriteManip.h"
#include "utils/acl.h"
#include "utils/lsyscache.h"
33 34


35 36 37 38 39 40 41 42 43 44 45 46 47
extern void CheckSelectForUpdate(Query *rule_action);	/* in analyze.c */


/* macros borrowed from expression_tree_mutator */

#define FLATCOPY(newnode, node, nodetype)  \
	( (newnode) = makeNode(nodetype), \
	  memcpy((newnode), (node), sizeof(nodetype)) )

#define MUTATE(newfield, oldfield, fieldtype, mutator, context)  \
		( (newfield) = (fieldtype) mutator((Node *) (oldfield), (context)) )


48 49 50 51 52 53 54
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);
55 56 57 58 59 60
static bool attribute_used(Node *node, int rt_index, int attno,
						   int sublevels_up);
static bool modifyAggrefUplevel(Node *node, void *context);
static bool modifyAggrefChangeVarnodes(Node *node, int rt_index, int new_index,
									   int sublevels_up);
static Node *modifyAggrefDropQual(Node *node, Node *targetNode);
B
Bruce Momjian 已提交
61
static SubLink *modifyAggrefMakeSublink(Expr *origexp, Query *parsetree);
62
static Node *modifyAggrefQual(Node *node, Query *parsetree);
63
static bool checkQueryHasAggs(Node *node);
64 65 66
static bool checkQueryHasAggs_walker(Node *node, void *context);
static bool checkQueryHasSubLink(Node *node);
static bool checkQueryHasSubLink_walker(Node *node, void *context);
67
static Query *fireRIRrules(Query *parsetree);
68 69 70 71 72 73
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);
74 75 76

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

	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 已提交
108
		info->rt = nconc(info->rt, copyObject(info->rule_action->rtable));
109 110

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

		/*
		 * 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 */
128
			int			new_result_reln = 0;
129 130 131 132

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


/*
149 150 151
 * rangeTableEntry_used -
 *	we need to process a RTE for RIR rules only if it is
 *	referenced somewhere in var nodes of the query.
152
 */
153 154 155 156 157 158

typedef struct {
	int			rt_index;
	int			sublevels_up;
} rangeTableEntry_used_context;

159
static bool
160 161
rangeTableEntry_used_walker (Node *node,
							 rangeTableEntry_used_context *context)
162
{
163
	if (node == NULL)
164 165
		return false;
	if (IsA(node, Var))
B
Bruce Momjian 已提交
166
	{
167
		Var		   *var = (Var *) node;
168

169 170 171 172
		if (var->varlevelsup == context->sublevels_up &&
			var->varno == context->rt_index)
			return true;
		return false;
173
	}
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
	if (IsA(node, SubLink))
	{
		/*
		 * Standard expression_tree_walker will not recurse into subselect,
		 * but here we must do so.
		 */
		SubLink    *sub = (SubLink *) node;

		if (rangeTableEntry_used_walker((Node *) (sub->lefthand), context))
			return true;
		if (rangeTableEntry_used((Node *) (sub->subselect),
								 context->rt_index,
								 context->sublevels_up + 1))
			return true;
		return false;
	}
	if (IsA(node, Query))
	{
		/* Reach here after recursing down into subselect above... */
		Query	   *qry = (Query *) node;

		if (rangeTableEntry_used_walker((Node *) (qry->targetList), context))
			return true;
		if (rangeTableEntry_used_walker((Node *) (qry->qual), context))
			return true;
		if (rangeTableEntry_used_walker((Node *) (qry->havingQual), context))
			return true;
		return false;
	}
	return expression_tree_walker(node, rangeTableEntry_used_walker,
								  (void *) context);
}

static bool
rangeTableEntry_used(Node *node, int rt_index, int sublevels_up)
{
	rangeTableEntry_used_context context;
211

212 213 214
	context.rt_index = rt_index;
	context.sublevels_up = sublevels_up;
	return rangeTableEntry_used_walker(node, &context);
215
}
216 217


218 219 220 221
/*
 * attribute_used -
 *	Check if a specific attribute number of a RTE is used
 *	somewhere in the query
222
 */
223 224 225 226 227 228 229

typedef struct {
	int			rt_index;
	int			attno;
	int			sublevels_up;
} attribute_used_context;

230
static bool
231 232
attribute_used_walker (Node *node,
					   attribute_used_context *context)
233
{
234
	if (node == NULL)
235 236
		return false;
	if (IsA(node, Var))
B
Bruce Momjian 已提交
237
	{
238
		Var		   *var = (Var *) node;
239

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
		if (var->varlevelsup == context->sublevels_up &&
			var->varno == context->rt_index &&
			var->varattno == context->attno)
			return true;
		return false;
	}
	if (IsA(node, SubLink))
	{
		/*
		 * Standard expression_tree_walker will not recurse into subselect,
		 * but here we must do so.
		 */
		SubLink    *sub = (SubLink *) node;

		if (attribute_used_walker((Node *) (sub->lefthand), context))
			return true;
		if (attribute_used((Node *) (sub->subselect),
						   context->rt_index,
						   context->attno,
						   context->sublevels_up + 1))
			return true;
		return false;
	}
	if (IsA(node, Query))
	{
		/* Reach here after recursing down into subselect above... */
		Query	   *qry = (Query *) node;

		if (attribute_used_walker((Node *) (qry->targetList), context))
			return true;
		if (attribute_used_walker((Node *) (qry->qual), context))
			return true;
		if (attribute_used_walker((Node *) (qry->havingQual), context))
			return true;
		return false;
275
	}
276 277 278 279 280 281 282 283
	return expression_tree_walker(node, attribute_used_walker,
								  (void *) context);
}

static bool
attribute_used(Node *node, int rt_index, int attno, int sublevels_up)
{
	attribute_used_context context;
284

285 286 287 288
	context.rt_index = rt_index;
	context.attno = attno;
	context.sublevels_up = sublevels_up;
	return attribute_used_walker(node, &context);
289
}
290

291

292
/*
B
Bruce Momjian 已提交
293
 * modifyAggrefUplevel -
294
 *	In the newly created sublink for an aggregate column used in
295
 *	the qualification, we must increment the varlevelsup in all the
296
 *	var nodes.
297 298 299 300
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
 * Var nodes in-place.  The given expression tree should have been copied
 * earlier to ensure that no unwanted side-effects occur!
301
 */
302 303
static bool
modifyAggrefUplevel(Node *node, void *context)
304 305
{
	if (node == NULL)
306 307
		return false;
	if (IsA(node, Var))
B
Bruce Momjian 已提交
308
	{
309
		Var		   *var = (Var *) node;
310

311 312 313 314 315 316 317 318 319 320
		var->varlevelsup++;
		return false;
	}
	if (IsA(node, SubLink))
	{
		/*
		 * Standard expression_tree_walker will not recurse into subselect,
		 * but here we must do so.
		 */
		SubLink    *sub = (SubLink *) node;
321

322 323 324 325 326
		if (modifyAggrefUplevel((Node *) (sub->lefthand), context))
			return true;
		if (modifyAggrefUplevel((Node *) (sub->subselect), context))
			return true;
		return false;
327
	}
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
	if (IsA(node, Query))
	{
		/* Reach here after recursing down into subselect above... */
		Query	   *qry = (Query *) node;

		if (modifyAggrefUplevel((Node *) (qry->targetList), context))
			return true;
		if (modifyAggrefUplevel((Node *) (qry->qual), context))
			return true;
		if (modifyAggrefUplevel((Node *) (qry->havingQual), context))
			return true;
		return false;
	}
	return expression_tree_walker(node, modifyAggrefUplevel,
								  (void *) context);
343 344 345 346
}


/*
B
Bruce Momjian 已提交
347
 * modifyAggrefChangeVarnodes -
348
 *	Change the var nodes in a sublink created for an aggregate column
349 350 351 352 353
 *	used in the qualification to point to the correct local RTE.
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
 * Var nodes in-place.  The given expression tree should have been copied
 * earlier to ensure that no unwanted side-effects occur!
354 355
 */

356 357 358 359 360
typedef struct {
	int			rt_index;
	int			new_index;
	int			sublevels_up;
} modifyAggrefChangeVarnodes_context;
361

362 363 364 365 366 367 368
static bool
modifyAggrefChangeVarnodes_walker(Node *node,
								  modifyAggrefChangeVarnodes_context *context)
{
	if (node == NULL)
		return false;
	if (IsA(node, Var))
B
Bruce Momjian 已提交
369
	{
370
		Var		   *var = (Var *) node;
371

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
		if (var->varlevelsup == context->sublevels_up &&
			var->varno == context->rt_index)
		{
			var->varno = context->new_index;
			var->varnoold = context->new_index;
			var->varlevelsup = 0;
		}
		return false;
	}
	if (IsA(node, SubLink))
	{
		/*
		 * Standard expression_tree_walker will not recurse into subselect,
		 * but here we must do so.
		 */
		SubLink    *sub = (SubLink *) node;

		if (modifyAggrefChangeVarnodes_walker((Node *) (sub->lefthand),
											  context))
			return true;
		if (modifyAggrefChangeVarnodes((Node *) (sub->subselect),
									   context->rt_index,
									   context->new_index,
									   context->sublevels_up + 1))
			return true;
		return false;
	}
	if (IsA(node, Query))
	{
		/* Reach here after recursing down into subselect above... */
		Query	   *qry = (Query *) node;

		if (modifyAggrefChangeVarnodes_walker((Node *) (qry->targetList),
											  context))
			return true;
		if (modifyAggrefChangeVarnodes_walker((Node *) (qry->qual),
											  context))
			return true;
		if (modifyAggrefChangeVarnodes_walker((Node *) (qry->havingQual),
											  context))
			return true;
		return false;
	}
	return expression_tree_walker(node, modifyAggrefChangeVarnodes_walker,
								  (void *) context);
}
418

419 420 421 422 423
static bool
modifyAggrefChangeVarnodes(Node *node, int rt_index, int new_index,
						   int sublevels_up)
{
	modifyAggrefChangeVarnodes_context context;
424

425 426 427 428
	context.rt_index = rt_index;
	context.new_index = new_index;
	context.sublevels_up = sublevels_up;
	return modifyAggrefChangeVarnodes_walker(node, &context);
429 430 431 432
}


/*
B
Bruce Momjian 已提交
433
 * modifyAggrefDropQual -
434 435 436 437 438 439 440 441 442 443
 *	remove the pure aggref clause from a qualification
 *
 * targetNode is a boolean expression node somewhere within the given
 * expression tree.  When we find it, replace it with a constant TRUE.
 * The return tree is a modified copy of the given tree; the given tree
 * is not altered.
 *
 * Note: we don't recurse into subselects looking for targetNode; that's
 * not necessary in the current usage, since in fact targetNode will be
 * within the same select level as the given toplevel node.
444
 */
445 446
static Node *
modifyAggrefDropQual(Node *node, Node *targetNode)
447 448
{
	if (node == NULL)
449 450
		return NULL;
	if (node == targetNode)
B
Bruce Momjian 已提交
451
	{
452
		Expr	   *expr = (Expr *) node;
453

454 455 456 457 458
		if (! IsA(expr, Expr) || expr->typeOid != BOOLOID)
			elog(ERROR,
				 "aggregate expression in qualification isn't of type bool");
		return (Node *) makeConst(BOOLOID, 1, (Datum) true,
								  false, true, false, false);
459
	}
460 461
	return expression_tree_mutator(node, modifyAggrefDropQual,
								   (void *) targetNode);
462 463 464
}

/*
B
Bruce Momjian 已提交
465
 * modifyAggrefMakeSublink -
466 467 468 469
 *	Create a sublink node for a qualification expression that
 *	uses an aggregate column of a view
 */
static SubLink *
B
Bruce Momjian 已提交
470
modifyAggrefMakeSublink(Expr *origexp, Query *parsetree)
471
{
B
Bruce Momjian 已提交
472 473 474 475 476 477 478 479
	SubLink    *sublink;
	Query	   *subquery;
	RangeTblEntry *rte;
	Aggref	   *aggref;
	Var		   *target;
	TargetEntry *tle;
	Resdom	   *resdom;
	Expr	   *exp = copyObject(origexp);
480

481
	if (IsA(nth(0, exp->args), Aggref))
T
Thomas G. Lockhart 已提交
482
	{
483 484
		if (IsA(nth(1, exp->args), Aggref))
			elog(ERROR, "rewrite: comparison of 2 aggregate columns not supported");
485
		else
486
			elog(ERROR, "rewrite: aggregate column of view must be at right side in qual");
487
		/* XXX could try to commute operator, instead of failing */
T
Thomas G. Lockhart 已提交
488
	}
489

B
Bruce Momjian 已提交
490 491
	aggref = (Aggref *) nth(1, exp->args);
	target = (Var *) (aggref->target);
492 493
	if (! IsA(target, Var))
		elog(ERROR, "rewrite: aggregates of views only allowed on simple variables for now");
B
Bruce Momjian 已提交
494
	rte = (RangeTblEntry *) nth(target->varno - 1, parsetree->rtable);
495

B
Bruce Momjian 已提交
496 497
	resdom = makeNode(Resdom);
	resdom->resno = 1;
498
	resdom->restype = aggref->aggtype;
499 500
	resdom->restypmod = -1;
	resdom->resname = pstrdup("<noname>");
B
Bruce Momjian 已提交
501
	resdom->reskey = 0;
502
	resdom->reskeyop = 0;
B
Bruce Momjian 已提交
503
	resdom->resjunk = false;
504

505
	tle = makeNode(TargetEntry);
B
Bruce Momjian 已提交
506
	tle->resdom = resdom;
507
	tle->expr = (Node *) aggref; /* note this is from the copied expr */
508 509

	sublink = makeNode(SubLink);
B
Bruce Momjian 已提交
510
	sublink->subLinkType = EXPR_SUBLINK;
511 512
	sublink->useor = false;
	/* note lefthand and oper are made from the copied expr */
513 514
	sublink->lefthand = lcons(lfirst(exp->args), NIL);
	sublink->oper = lcons(exp->oper, NIL);
B
Bruce Momjian 已提交
515 516 517 518 519 520 521 522 523 524 525

	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;
526 527 528 529 530 531 532
	subquery->unionall = FALSE;
	subquery->uniqueFlag = NULL;
	subquery->sortClause = NULL;
	subquery->rtable = lcons(rte, NIL);
	subquery->targetList = lcons(tle, NIL);
	subquery->qual = modifyAggrefDropQual((Node *) parsetree->qual,
										  (Node *) origexp);
533 534 535 536 537 538 539
	/*
	 * If there are still aggs in the subselect's qual, give up.
	 * Recursing would be a bad idea --- we'd likely produce an
	 * infinite recursion.  This whole technique is a crock, really...
	 */
	if (checkQueryHasAggs(subquery->qual))
		elog(ERROR, "Cannot handle aggregate function inserted at this place in WHERE clause");
540 541 542 543 544
	subquery->groupClause = NIL;
	subquery->havingQual = NULL;
	subquery->hasAggs = TRUE;
	subquery->hasSubLinks = FALSE;
	subquery->unionClause = NULL;
545

546 547 548 549 550 551 552 553 554 555
	modifyAggrefUplevel((Node *) subquery, NULL);
	/*
	 * Note: it might appear that we should be passing target->varlevelsup+1
	 * here, since modifyAggrefUplevel has increased all the varlevelsup
	 * values in the subquery.  However, target itself is a pointer to a
	 * Var node in the subquery, so it's been incremented too!  What a kluge
	 * this all is ... we need to make subquery RTEs so it can go away...
	 */
	modifyAggrefChangeVarnodes((Node *) subquery, target->varno,
							   1, target->varlevelsup);
556

557 558
	return sublink;
}
559 560


561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
/*
 * modifyAggrefQual -
 *	Search for qualification expressions that contain aggregate
 *	functions and substitute them by sublinks. These expressions
 *	originally come from qualifications that use aggregate columns
 *	of a view.
 *
 *	The return value is a modified copy of the given expression tree.
 */
static Node *
modifyAggrefQual(Node *node, Query *parsetree)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Expr))
	{
		Expr	   *expr = (Expr *) node;
578

579 580 581 582 583 584 585
		if (length(expr->args) == 2 &&
			(IsA(lfirst(expr->args), Aggref) ||
			 IsA(lsecond(expr->args), Aggref)))
		{
			SubLink    *sub = modifyAggrefMakeSublink(expr,
													  parsetree);
			parsetree->hasSubLinks = true;
586 587 588
			/* check for aggs in resulting lefthand... */
			sub->lefthand = (List *) modifyAggrefQual((Node *) sub->lefthand,
													  parsetree);
589 590 591
			return (Node *) sub;
		}
		/* otherwise, fall through and copy the expr normally */
592
	}
593 594 595 596 597
	if (IsA(node, Aggref))
	{
		/* Oops, found one that's not inside an Expr we can rearrange... */
		elog(ERROR, "Cannot handle aggregate function inserted at this place in WHERE clause");
	}
598 599 600 601 602
	/* We do NOT recurse into subselects in this routine.  It's sufficient
	 * to get rid of aggregates that are in the qual expression proper.
	 */
	return expression_tree_mutator(node, modifyAggrefQual,
								   (void *) parsetree);
603 604 605
}


606 607 608 609 610 611 612 613
/*
 * checkQueryHasAggs -
 *	Queries marked hasAggs might not have them any longer after
 *	rewriting. Check it.
 */
static bool
checkQueryHasAggs(Node *node)
{
614
	return checkQueryHasAggs_walker(node, NULL);
615 616
}

617 618 619 620 621 622 623 624 625
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);
}
626

627 628
/*
 * checkQueryHasSubLink -
629
 *	Queries marked hasSubLinks might not have them any longer after
630 631 632 633 634
 *	rewriting. Check it.
 */
static bool
checkQueryHasSubLink(Node *node)
{
635 636
	return checkQueryHasSubLink_walker(node, NULL);
}
637

638 639 640 641 642 643 644 645
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 */
	return expression_tree_walker(node, checkQueryHasSubLink_walker, context);
646 647 648
}


649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
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;
}


681 682 683 684 685 686 687 688 689 690 691
/*
 * apply_RIR_adjust_sublevel -
 *	Set the varlevelsup field of all Var nodes in the given expression tree
 *	to sublevels_up.  We do NOT recurse into subselects.
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
 * Var nodes in-place.  The given expression tree should have been copied
 * earlier to ensure that no unwanted side-effects occur!
 */
static bool
apply_RIR_adjust_sublevel_walker(Node *node, int *sublevels_up)
B
Bruce Momjian 已提交
692 693
{
	if (node == NULL)
694 695
		return false;
	if (IsA(node, Var))
B
Bruce Momjian 已提交
696
	{
697
		Var		   *var = (Var *) node;
B
Bruce Momjian 已提交
698

699 700
		var->varlevelsup = *sublevels_up;
		return false;
B
Bruce Momjian 已提交
701
	}
702 703
	return expression_tree_walker(node, apply_RIR_adjust_sublevel_walker,
								  (void *) sublevels_up);
B
Bruce Momjian 已提交
704 705
}

706
static void
707
apply_RIR_adjust_sublevel(Node *node, int sublevels_up)
708
{
709 710
	apply_RIR_adjust_sublevel_walker(node, &sublevels_up);
}
711 712


713 714 715 716
/*
 * apply_RIR_view
 *	Replace Vars matching a given RT index with copies of TL expressions.
 */
717

718 719 720 721 722 723 724
typedef struct {
	int				rt_index;
	int				sublevels_up;
	RangeTblEntry  *rte;
	List		   *tlist;
	int			   *modified;
} apply_RIR_view_context;
725

726 727 728 729 730 731 732 733 734
static Node *
apply_RIR_view_mutator(Node *node,
					   apply_RIR_view_context *context)
{
	if (node == NULL)
		return NULL;
	if (IsA(node, Var))
	{
		Var		   *var = (Var *) node;
735

736 737 738 739
		if (var->varlevelsup == context->sublevels_up &&
			var->varno == context->rt_index)
		{
			Node	   *expr;
740

741 742 743 744
			if (var->varattno < 0)
				elog(ERROR, "system column %s not available - %s is a view",
					 get_attname(context->rte->relid, var->varattno),
					 context->rte->relname);
745

746 747 748 749
			expr = FindMatchingTLEntry(context->tlist,
									   get_attname(context->rte->relid,
												   var->varattno));
			if (expr == NULL)
750
			{
751 752
				/* XXX shouldn't this be an error condition? */
				return make_null(var->vartype);
753 754
			}

755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
			expr = copyObject(expr);
			if (var->varlevelsup > 0)
				apply_RIR_adjust_sublevel(expr, var->varlevelsup);
			*(context->modified) = true;
			return (Node *) expr;
		}
		/* otherwise fall through to copy the var normally */
	}
	/*
	 * Since expression_tree_mutator won't touch subselects, we have to
	 * handle them specially.
	 */
	if (IsA(node, SubLink))
	{
		SubLink   *sublink = (SubLink *) node;
		SubLink   *newnode;

		FLATCOPY(newnode, sublink, SubLink);
		MUTATE(newnode->lefthand, sublink->lefthand, List *,
			   apply_RIR_view_mutator, context);
		context->sublevels_up++;
		MUTATE(newnode->subselect, sublink->subselect, Node *,
			   apply_RIR_view_mutator, context);
		context->sublevels_up--;
		return (Node *) newnode;
	}
	if (IsA(node, Query))
	{
		Query  *query = (Query *) node;
		Query  *newnode;

		FLATCOPY(newnode, query, Query);
		MUTATE(newnode->targetList, query->targetList, List *,
			   apply_RIR_view_mutator, context);
		MUTATE(newnode->qual, query->qual, Node *,
			   apply_RIR_view_mutator, context);
		MUTATE(newnode->havingQual, query->havingQual, Node *,
			   apply_RIR_view_mutator, context);
		return (Node *) newnode;
	}
	return expression_tree_mutator(node, apply_RIR_view_mutator,
								   (void *) context);
}
798

799 800 801 802 803
static Node *
apply_RIR_view(Node *node, int rt_index, RangeTblEntry *rte, List *tlist,
			   int *modified, int sublevels_up)
{
	apply_RIR_view_context	context;
804

805 806 807 808 809
	context.rt_index = rt_index;
	context.sublevels_up = sublevels_up;
	context.rte = rte;
	context.tlist = tlist;
	context.modified = modified;
810

811
	return apply_RIR_view_mutator(node, &context);
812 813 814
}


815
static Query *
816 817 818 819 820
ApplyRetrieveRule(Query *parsetree,
				  RewriteRule *rule,
				  int rt_index,
				  int relation_level,
				  Relation relation,
821
				  bool relWasInJoinSet,
822 823 824 825 826
				  int *modified)
{
	Query	   *rule_action = NULL;
	Node	   *rule_qual;
	List	   *rtable,
827
			   *addedrtable,
828
			   *l;
829 830
	int			nothing,
				rt_length;
831
	int			badsql = false;
832 833 834 835 836 837 838 839

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

840
			return parsetree;
841 842 843 844 845 846 847
		rule_action = copyObject(lfirst(rule->actions));
		nothing = FALSE;
	}
	else
		nothing = TRUE;

	rtable = copyObject(parsetree->rtable);
848
	rt_length = length(rtable);	/* original length, not counting rule */
849

850 851 852 853 854 855 856 857 858 859 860 861
	addedrtable = copyObject(rule_action->rtable);

	/* If the original rel wasn't in the join set, none of its spawn is.
	 * If it was, then leave the spawn's flags as they are.
	 */
	if (! relWasInJoinSet)
	{
		foreach(l, addedrtable)
		{
			RangeTblEntry *rte = lfirst(l);
			rte->inJoinSet = false;
		}
862 863
	}

864
	rtable = nconc(rtable, addedrtable);
865 866
	parsetree->rtable = rtable;

867
	/* FOR UPDATE of view... */
B
Bruce Momjian 已提交
868
	foreach(l, parsetree->rowMark)
869
	{
B
Bruce Momjian 已提交
870
		if (((RowMark *) lfirst(l))->rti == rt_index)
871 872
			break;
	}
B
Bruce Momjian 已提交
873
	if (l != NULL)				/* oh, hell -:) */
874
	{
B
Bruce Momjian 已提交
875
		RowMark    *newrm;
876 877 878
		Index		rti = 1;
		List	   *l2;

879
		CheckSelectForUpdate(rule_action);
B
Bruce Momjian 已提交
880 881 882 883 884 885

		/*
		 * 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.
886
		 */
B
Bruce Momjian 已提交
887
		((RowMark *) lfirst(l))->info &= ~ROW_MARK_FOR_UPDATE;
888

B
Bruce Momjian 已提交
889
		foreach(l2, rule_action->rtable)
890
		{
B
Bruce Momjian 已提交
891

892
			/*
B
Bruce Momjian 已提交
893 894
			 * RTable of VIEW has two entries of VIEW itself - we use
			 * relid to skip them.
895
			 */
B
Bruce Momjian 已提交
896
			if (relation->rd_id != ((RangeTblEntry *) lfirst(l2))->relid)
897 898 899 900 901 902 903 904 905 906 907
			{
				newrm = makeNode(RowMark);
				newrm->rti = rti + rt_length;
				newrm->info = ROW_MARK_FOR_UPDATE;
				lnext(l) = lcons(newrm, lnext(l));
				l = lnext(l);
			}
			rti++;
		}
	}

908
	rule_action->rtable = rtable;
B
Bruce Momjian 已提交
909
	OffsetVarNodes((Node *) rule_qual, rt_length, 0);
B
Bruce Momjian 已提交
910
	OffsetVarNodes((Node *) rule_action, rt_length, 0);
911

B
Bruce Momjian 已提交
912
	ChangeVarNodes((Node *) rule_qual,
913
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
B
Bruce Momjian 已提交
914
	ChangeVarNodes((Node *) rule_action,
915 916 917 918
				   PRS2_CURRENT_VARNO + rt_length, rt_index, 0);

	if (relation_level)
	{
919 920 921 922 923 924 925 926 927 928
		RangeTblEntry  *rte = (RangeTblEntry *) nth(rt_index - 1, rtable);

		parsetree = (Query *) apply_RIR_view((Node *) parsetree,
											 rt_index, rte,
											 rule_action->targetList,
											 modified, 0);
		rule_action = (Query *) apply_RIR_view((Node *) rule_action,
											   rt_index, rte,
											   rule_action->targetList,
											   modified, 0);
929 930 931
	}
	else
	{
B
Bruce Momjian 已提交
932 933 934 935 936 937 938 939 940 941 942
		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);
943
	}
944 945

	return parsetree;
946 947 948
}


949 950 951 952 953 954 955 956 957 958
/*
 * fireRIRonSubselect -
 *	Apply fireRIRrules() to each subselect found in the given tree.
 *
 * NOTE: although this has the form of a walker, we cheat and modify the
 * SubLink nodes in-place.  It is caller's responsibility to ensure that
 * no unwanted side-effects occur!
 */
static bool
fireRIRonSubselect(Node *node, void *context)
959 960
{
	if (node == NULL)
961 962
		return false;
	if (IsA(node, SubLink))
B
Bruce Momjian 已提交
963
	{
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
		/*
		 * Standard expression_tree_walker will not recurse into subselect,
		 * but here we must do so.
		 */
		SubLink    *sub = (SubLink *) node;
		Query	   *qry;

		/* Process lefthand args */
		if (fireRIRonSubselect((Node *) (sub->lefthand), context))
			return true;
		/* Do what we came for */
		qry = fireRIRrules((Query *) (sub->subselect));
		sub->subselect = (Node *) qry;
		/* Must recurse to handle any sub-subselects! */
		if (fireRIRonSubselect((Node *) qry, context))
			return true;
		return false;
	}
	if (IsA(node, Query))
	{
		/* Reach here after recursing down into subselect above... */
		Query	   *qry = (Query *) node;

		if (fireRIRonSubselect((Node *) (qry->targetList), context))
			return true;
		if (fireRIRonSubselect((Node *) (qry->qual), context))
			return true;
		if (fireRIRonSubselect((Node *) (qry->havingQual), context))
			return true;
		return false;
994
	}
995 996
	return expression_tree_walker(node, fireRIRonSubselect,
								  (void *) context);
997 998 999 1000 1001 1002 1003 1004 1005 1006
}


/*
 * fireRIRrules -
 *	Apply all RIR rules on each rangetable entry in a query
 */
static Query *
fireRIRrules(Query *parsetree)
{
B
Bruce Momjian 已提交
1007 1008
	int			rt_index;
	RangeTblEntry *rte;
1009
	Relation	rel;
B
Bruce Momjian 已提交
1010 1011 1012 1013
	List	   *locks;
	RuleLock   *rules;
	RewriteRule *rule;
	RewriteRule RIRonly;
1014
	bool		relWasInJoinSet;
1015
	int			modified = false;
B
Bruce Momjian 已提交
1016 1017
	int			i;
	List	   *l;
1018

1019 1020 1021
	/* don't try to convert this into a foreach loop, because
	 * rtable list can get changed each time through...
	 */
1022
	rt_index = 0;
B
Bruce Momjian 已提交
1023 1024
	while (rt_index < length(parsetree->rtable))
	{
1025 1026
		++rt_index;

1027 1028
		rte = nth(rt_index - 1, parsetree->rtable);

1029 1030 1031 1032 1033 1034 1035 1036
		/*
		 * If the table is not one named in the original FROM clause
		 * then it must be referenced in the query, or we ignore it.
		 * This prevents infinite expansion loop due to new rtable
		 * entries inserted by expansion of a rule.
		 */
		if (! rte->inFromCl && rt_index != parsetree->resultRelation &&
			! rangeTableEntry_used((Node *) parsetree, rt_index, 0))
1037
		{
1038 1039
			/* Make sure the planner ignores it too... */
			rte->inJoinSet = false;
1040
			continue;
1041
		}
B
Bruce Momjian 已提交
1042

1043
		rel = heap_openr(rte->relname, AccessShareLock);
1044 1045
		rules = rel->rd_rules;
		if (rules == NULL)
B
Bruce Momjian 已提交
1046
		{
1047
			heap_close(rel, AccessShareLock);
1048 1049 1050
			continue;
		}

1051
		relWasInJoinSet = rte->inJoinSet; /* save before possibly clearing */
1052 1053 1054 1055

		/*
		 * Collect the RIR rules that we must apply
		 */
1056
		locks = NIL;
B
Bruce Momjian 已提交
1057 1058
		for (i = 0; i < rules->numLocks; i++)
		{
1059 1060 1061
			rule = rules->rules[i];
			if (rule->event != CMD_SELECT)
				continue;
B
Bruce Momjian 已提交
1062

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
			if (rule->attrno > 0)
			{
				/* per-attr rule; do we need it? */
				if (! attribute_used((Node *) parsetree,
									 rt_index,
									 rule->attrno, 0))
					continue;
			}
			else
			{
				/* Rel-wide ON SELECT DO INSTEAD means this is a view.
				 * Remove the view from the planner's join target set,
				 * or we'll get no rows out because view itself is empty!
				 */
				if (rule->isInstead)
					rte->inJoinSet = false;
			}
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091

			locks = lappend(locks, rule);
		}

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

		/*
		 * Now apply them
		 */
B
Bruce Momjian 已提交
1092 1093
		foreach(l, locks)
		{
1094 1095
			rule = lfirst(l);

B
Bruce Momjian 已提交
1096 1097 1098 1099
			RIRonly.event = rule->event;
			RIRonly.attrno = rule->attrno;
			RIRonly.qual = rule->qual;
			RIRonly.actions = rule->actions;
1100

1101 1102 1103 1104 1105
			parsetree = ApplyRetrieveRule(parsetree,
										  &RIRonly,
										  rt_index,
										  RIRonly.attrno == -1,
										  rel,
1106
										  relWasInJoinSet,
1107
										  &modified);
1108 1109
		}

1110
		heap_close(rel, AccessShareLock);
1111 1112
	}

1113 1114 1115
	fireRIRonSubselect((Node *) parsetree, NULL);

	parsetree->qual = modifyAggrefQual(parsetree->qual, parsetree);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

	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);
1143
		}
1144 1145
		else
			regular = lappend(regular, rule_lock);
1146
	}
1147 1148
	regular = nconc(regular, instead_qualified);
	return nconc(regular, instead_rules);
1149 1150
}

1151 1152


1153
static Query *
1154 1155 1156
CopyAndAddQual(Query *parsetree,
			   List *actions,
			   Node *rule_qual,
1157 1158
			   int rt_index,
			   CmdType event)
1159
{
1160 1161 1162
	Query	   *new_tree = (Query *) copyObject(parsetree);
	Node	   *new_qual = NULL;
	Query	   *rule_action = NULL;
1163 1164 1165 1166 1167 1168 1169

	if (actions)
		rule_action = lfirst(actions);
	if (rule_qual != NULL)
		new_qual = (Node *) copyObject(rule_qual);
	if (rule_action != NULL)
	{
1170 1171
		List	   *rtable;
		int			rt_length;
1172 1173 1174

		rtable = new_tree->rtable;
		rt_length = length(rtable);
B
Bruce Momjian 已提交
1175
		rtable = nconc(rtable, copyObject(rule_action->rtable));
1176
		new_tree->rtable = rtable;
B
Bruce Momjian 已提交
1177
		OffsetVarNodes(new_qual, rt_length, 0);
1178
		ChangeVarNodes(new_qual, PRS2_CURRENT_VARNO + rt_length, rt_index, 0);
1179 1180 1181 1182 1183
	}
	/* XXX -- where current doesn't work for instead nothing.... yet */
	AddNotQual(new_tree, new_qual);

	return new_tree;
1184 1185 1186
}


1187

1188
/*
1189
 *	fireRules -
M
 
Marc G. Fournier 已提交
1190 1191 1192 1193 1194
 *	   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.
1195
 *
M
 
Marc G. Fournier 已提交
1196
 *	   remember: reality is for dead birds -- glass
1197 1198
 *
 */
1199
static List *
1200
fireRules(Query *parsetree,
1201 1202
		  int rt_index,
		  CmdType event,
1203 1204 1205
		  bool *instead_flag,
		  List *locks,
		  List **qual_products)
1206
{
1207 1208 1209
	RewriteInfo *info;
	List	   *results = NIL;
	List	   *i;
1210 1211 1212

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

M
 
Marc G. Fournier 已提交
1215
	locks = orderRules(locks);	/* real instead rules last */
1216 1217
	foreach(i, locks)
	{
1218 1219 1220 1221 1222
		RewriteRule *rule_lock = (RewriteRule *) lfirst(i);
		Node	   *qual,
				   *event_qual;
		List	   *actions;
		List	   *r;
1223

1224
		/*
1225 1226 1227 1228 1229 1230
		 * 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.
1231
		 */
1232 1233 1234 1235
		if (rule_lock->isInstead &&
			parsetree->commandType != CMD_SELECT)
		{
			RangeTblEntry *rte;
1236 1237 1238
			int32		acl_rc;
			int32		reqperm;

1239 1240
			switch (parsetree->commandType)
			{
1241 1242 1243 1244 1245 1246 1247
				case CMD_INSERT:
					reqperm = ACL_AP;
					break;
				default:
					reqperm = ACL_WR;
					break;
			}
1248 1249 1250 1251 1252

			rte = (RangeTblEntry *) nth(parsetree->resultRelation - 1,
										parsetree->rtable);
			if (!rte->skipAcl)
			{
1253
				acl_rc = pg_aclcheck(rte->relname,
1254 1255 1256
									 GetPgUserName(), reqperm);
				if (acl_rc != ACLCHECK_OK)
				{
1257
					elog(ERROR, "%s: %s",
1258 1259
						 rte->relname,
						 aclcheck_error_strings[acl_rc]);
1260 1261 1262 1263
				}
			}
		}

1264 1265 1266 1267
		/* multiple rule action time */
		*instead_flag = rule_lock->isInstead;
		event_qual = rule_lock->qual;
		actions = rule_lock->actions;
1268 1269 1270 1271
		if (event_qual != NULL && *instead_flag)
		{
			Query	   *qual_product;
			RewriteInfo qual_info;
M
 
Marc G. Fournier 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284

			/* ----------
			 * 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.
			 * ----------
			 */
1285
			if (*qual_products == NIL)
M
 
Marc G. Fournier 已提交
1286
				qual_product = parsetree;
1287 1288
			else
				qual_product = (Query *) nth(0, *qual_products);
M
 
Marc G. Fournier 已提交
1289

1290 1291 1292 1293 1294 1295 1296 1297 1298
			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 已提交
1299 1300 1301 1302 1303 1304 1305

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

			*qual_products = lappend(NIL, qual_product);
		}

1306 1307
		foreach(r, actions)
		{
1308 1309
			Query	   *rule_action = lfirst(r);
			Node	   *rule_qual = copyObject(event_qual);
1310

M
 
Marc G. Fournier 已提交
1311 1312 1313
			if (rule_action->commandType == CMD_NOTHING)
				continue;

B
Bruce Momjian 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
			/*--------------------------------------------------
			 * 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;

1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
			/*--------------------------------------------------
			 * 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 已提交
1357
			 * Event Qualification forces copying of parsetree and
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
			 * 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 已提交
1382

1383
			/*
B
Bruce Momjian 已提交
1384 1385 1386
			 * ProcessRetrieveQuery(info->rule_action, info->rt,
			 * &orig_instead_flag, TRUE);
			 */
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

			/*--------------------------------------------------
			 * 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 已提交
1398 1399 1400 1401 1402 1403

		/* ----------
		 * If this was an unqualified instead rule,
		 * throw away an eventually saved 'default' parsetree
		 * ----------
		 */
1404
		if (event_qual == NULL && *instead_flag)
M
 
Marc G. Fournier 已提交
1405
			*qual_products = NIL;
1406 1407
	}
	return results;
1408 1409
}

M
 
Marc G. Fournier 已提交
1410 1411


1412
static List *
1413
RewriteQuery(Query *parsetree, bool *instead_flag, List **qual_products)
1414
{
1415
	CmdType		event;
B
Bruce Momjian 已提交
1416 1417 1418
	List	   *product_queries = NIL;
	int			result_relation = 0;
	RangeTblEntry *rt_entry;
1419
	Relation	rt_entry_relation = NULL;
B
Bruce Momjian 已提交
1420
	RuleLock   *rt_entry_locks = NULL;
1421

1422 1423 1424 1425
	Assert(parsetree != NULL);

	event = parsetree->commandType;

1426
	/*
B
Bruce Momjian 已提交
1427 1428
	 * SELECT rules are handled later when we have all the queries that
	 * should get executed
1429 1430 1431 1432 1433 1434 1435
	 */
	if (event == CMD_SELECT)
		return NIL;

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

1439
	/*
B
Bruce Momjian 已提交
1440
	 * the statement is an update, insert or delete - fire rules on it.
1441
	 */
1442
	result_relation = parsetree->resultRelation;
1443
	rt_entry = rt_fetch(result_relation, parsetree->rtable);
1444
	rt_entry_relation = heap_openr(rt_entry->relname, AccessShareLock);
1445
	rt_entry_locks = rt_entry_relation->rd_rules;
1446
	heap_close(rt_entry_relation, AccessShareLock);
M
 
Marc G. Fournier 已提交
1447

1448
	if (rt_entry_locks != NULL)
1449
	{
1450
		List	   *locks = matchLocks(event, rt_entry_locks, result_relation, parsetree);
1451

1452
		product_queries = fireRules(parsetree,
B
Bruce Momjian 已提交
1453 1454 1455 1456 1457
									result_relation,
									event,
									instead_flag,
									locks,
									qual_products);
1458
	}
1459

1460
	return product_queries;
1461 1462
}

1463

1464 1465 1466 1467 1468
/*
 * 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
1469
#define REWRITE_INVOKE_MAX		10
1470 1471
#endif

1472
static int	numQueryRewriteInvoked = 0;
1473 1474 1475

/*
 * deepRewriteQuery -
1476
 *	  rewrites the query and apply the rules again on the queries rewritten
1477
 */
1478
static List *
1479
deepRewriteQuery(Query *parsetree)
1480
{
1481 1482 1483 1484 1485
	List	   *n;
	List	   *rewritten = NIL;
	List	   *result = NIL;
	bool		instead;
	List	   *qual_products = NIL;
1486

1487 1488


1489 1490
	if (++numQueryRewriteInvoked > REWRITE_INVOKE_MAX)
	{
1491
		elog(ERROR, "query rewritten %d times, may contain cycles",
1492 1493 1494 1495 1496
			 numQueryRewriteInvoked - 1);
	}

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

1498 1499
	foreach(n, result)
	{
1500 1501
		Query	   *pt = lfirst(n);
		List	   *newstuff = NIL;
1502 1503 1504 1505 1506

		newstuff = deepRewriteQuery(pt);
		if (newstuff != NIL)
			rewritten = nconc(rewritten, newstuff);
	}
M
 
Marc G. Fournier 已提交
1507 1508 1509 1510 1511 1512

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

M
 
Marc G. Fournier 已提交
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
	/* ----------
	 * 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);

1529 1530
	return rewritten;
}
1531 1532 1533 1534 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


/*
 * 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.
1564 1565
	 * resjunk targets are somewhat arbitrarily given a resno of 0;
	 * this is to prevent FixNew() from matching them to var nodes.
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
	 * ----------
	 */
	if (parsetree->resultRelation > 0)
	{
		RangeTblEntry *rte;
		Relation	rd;
		List	   *tl;

		rte = (RangeTblEntry *) nth(parsetree->resultRelation - 1,
									parsetree->rtable);
1576
		rd = heap_openr(rte->relname, AccessShareLock);
1577 1578 1579

		foreach(tl, parsetree->targetList)
		{
1580 1581 1582 1583 1584 1585
			TargetEntry *tle = (TargetEntry *) lfirst(tl);

			if (! tle->resdom->resjunk)
				tle->resdom->resno = attnameAttNum(rd, tle->resdom->resname);
			else
				tle->resdom->resno = 0;
1586 1587
		}

1588
		heap_close(rd, AccessShareLock);
1589 1590 1591 1592 1593
	}
}


/*
1594
 * BasicQueryRewrite -
1595 1596 1597
 *	  rewrite one query via query rewrite system, possibly returning 0
 *	  or many queries
 */
1598 1599
static List *
BasicQueryRewrite(Query *parsetree)
1600
{
B
Bruce Momjian 已提交
1601 1602 1603 1604
	List	   *querylist;
	List	   *results = NIL;
	List	   *l;
	Query	   *query;
1605 1606 1607 1608

	/*
	 * Step 1
	 *
B
Bruce Momjian 已提交
1609 1610
	 * There still seems something broken with the resdom numbers so we
	 * reassign them first.
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
	 */
	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 已提交
1626 1627 1628 1629
	foreach(l, querylist)
	{
		query = fireRIRrules((Query *) lfirst(l));

1630
		/*
B
Bruce Momjian 已提交
1631 1632 1633 1634
		 * 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.
1635 1636
		 */
		if (query->hasAggs)
B
Bruce Momjian 已提交
1637
			query->hasAggs = checkQueryHasAggs((Node *) (query->targetList))
1638
				|| checkQueryHasAggs((Node *) (query->havingQual));
B
Bruce Momjian 已提交
1639
		query->hasSubLinks = checkQueryHasSubLink((Node *) (query->qual))
1640
			|| checkQueryHasSubLink((Node *) (query->havingQual));
1641
		results = lappend(results, query);
1642 1643 1644
	}
	return results;
}
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655

/*
 * 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 已提交
1656
 */
1657 1658 1659 1660 1661 1662
List *
QueryRewrite(Query *parsetree)
{
	List	   *rewritten,
			   *rewritten_item;

B
Bruce Momjian 已提交
1663 1664 1665 1666
	/*
	 * Rewrite Union, Intersect and Except Queries to normal Union Queries
	 * using IN and NOT IN subselects
	 */
1667 1668 1669 1670 1671 1672 1673 1674 1675
	if (parsetree->intersectClause)
		parsetree = Except_Intersect_Rewrite(parsetree);

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

	/*
	 * Rewrite the UNIONS.
	 */
B
Bruce Momjian 已提交
1676
	foreach(rewritten_item, rewritten)
1677 1678 1679 1680 1681
	{
		Query	   *qry = (Query *) lfirst(rewritten_item);
		List	   *union_result = NIL;
		List	   *union_item;

B
Bruce Momjian 已提交
1682
		foreach(union_item, qry->unionClause)
1683 1684
		{
			union_result = nconc(union_result,
B
Bruce Momjian 已提交
1685
						BasicQueryRewrite((Query *) lfirst(union_item)));
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
		}
		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 */
1696
static void
B
Bruce Momjian 已提交
1697
check_targetlists_are_compatible(List *prev_target, List *current_target)
B
Hi!  
Bruce Momjian 已提交
1698
{
B
Bruce Momjian 已提交
1699 1700 1701 1702
	List	   *tl,
			   *next_target;
	int			prev_len = 0,
				next_len = 0;
1703

B
Bruce Momjian 已提交
1704 1705
	foreach(tl, prev_target)
		if (!((TargetEntry *) lfirst(tl))->resdom->resjunk)
1706 1707
		prev_len++;

B
Bruce Momjian 已提交
1708 1709
	foreach(next_target, current_target)
		if (!((TargetEntry *) lfirst(next_target))->resdom->resjunk)
1710
		next_len++;
B
Bruce Momjian 已提交
1711 1712 1713 1714 1715

	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 已提交
1716
	{
B
Bruce Momjian 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
		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 已提交
1729
#ifdef NOT_USED
B
Bruce Momjian 已提交
1730 1731 1732 1733 1734
			else
			{
				((TargetEntry *) lfirst(prev_target))->resdom->restype = UNKNOWNOID;
				((TargetEntry *) lfirst(next_target))->resdom->restype = UNKNOWNOID;
			}
B
Hi!  
Bruce Momjian 已提交
1735
#endif
B
Bruce Momjian 已提交
1736 1737 1738 1739 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
		}
		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 已提交
1765 1766 1767 1768
	}
}

/* Rewrites UNION INTERSECT and EXCEPT queries to semantiacally equivalent
B
Bruce Momjian 已提交
1769 1770
 * queries that use IN and NOT IN subselects.
 *
B
Hi!  
Bruce Momjian 已提交
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
 * 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 已提交
1783
 * (sortClause etc) are attached to the new top Node (Note that the
B
Hi!  
Bruce Momjian 已提交
1784 1785 1786
 * 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!) */
1787
static Query *
B
Bruce Momjian 已提交
1788
Except_Intersect_Rewrite(Query *parsetree)
B
Hi!  
Bruce Momjian 已提交
1789
{
B
Bruce Momjian 已提交
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808

	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;
1809 1810
	Node	   *limitOffset,
			   *limitCount;
B
Bruce Momjian 已提交
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 1840 1841 1842 1843 1844 1845 1846 1847 1848
	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 已提交
1849
	}
B
Bruce Momjian 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860

	/*
	 * 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;
1861 1862
	limitOffset = parsetree->limitOffset;
	limitCount = parsetree->limitCount;
B
Bruce Momjian 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 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

	/*
	 * 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;
1918
		create_intersect_list((Node *) lfirst(intersect), &intersect_list);
B
Bruce Momjian 已提交
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 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

		/*
		 * 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
			 */
1992
			n->lefthand = NIL;
B
Bruce Momjian 已提交
1993 1994
			foreach(elist, intersect_node->targetList)
			{
1995
				TargetEntry *tent = (TargetEntry *) lfirst(elist);
B
Bruce Momjian 已提交
1996 1997 1998 1999 2000

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

			/*
2001 2002
			 * Also prepare the list of Opers that must be used for the
			 * comparisons (they depend on the specific datatypes involved!)
B
Bruce Momjian 已提交
2003 2004 2005
			 */
			left_expr = n->lefthand;
			right_expr = ((Query *) (n->subselect))->targetList;
2006
			n->oper = NIL;
B
Bruce Momjian 已提交
2007 2008 2009 2010

			foreach(elist, left_expr)
			{
				Node	   *lexpr = lfirst(elist);
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
				TargetEntry *tent = (TargetEntry *) lfirst(right_expr);
				Operator	optup;
				Form_pg_operator opform;
				Oper	   *newop;

				optup = oper(op,
							 exprType(lexpr),
							 exprType(tent->expr),
							 FALSE);
				opform = (Form_pg_operator) GETSTRUCT(optup);

				if (opform->oprresult != BOOLOID)
					elog(ERROR, "parser: '%s' must return 'bool' to be used with quantified predicate subquery", op);

				newop = makeOper(oprid(optup),/* opno */
								 InvalidOid, /* opid */
								 opform->oprresult,
								 0,
								 NULL);
B
Bruce Momjian 已提交
2030

2031
				n->oper = lappend(n->oper, newop);
B
Bruce Momjian 已提交
2032 2033 2034 2035 2036 2037 2038 2039

				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
			 */
2040
			if (intersect_node->hasAggs)
B
Bruce Momjian 已提交
2041
				AddHavingQual(intersect_node, (Node *) n);
2042 2043
			else
				AddQual(intersect_node, (Node *) n);
B
Bruce Momjian 已提交
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063

			/* 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;
2064 2065
	result->limitOffset = limitOffset;
	result->limitCount = limitCount;
B
Bruce Momjian 已提交
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088

	/*
	 * 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);
	}
2089

B
Bruce Momjian 已提交
2090
	return result;
B
Hi!  
Bruce Momjian 已提交
2091 2092 2093 2094 2095 2096 2097
}

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

2098 2099
static void
create_intersect_list(Node *ptr, List **intersect_list)
B
Hi!  
Bruce Momjian 已提交
2100
{
B
Bruce Momjian 已提交
2101 2102 2103
	List	   *arg;

	if (IsA(ptr, Query))
B
Hi!  
Bruce Momjian 已提交
2104
	{
B
Bruce Momjian 已提交
2105 2106 2107
		/* The non negated node is attached at the beginning (lcons) */
		*intersect_list = lcons(ptr, *intersect_list);
		return;
B
Hi!  
Bruce Momjian 已提交
2108
	}
B
Bruce Momjian 已提交
2109 2110

	if (IsA(ptr, Expr))
B
Hi!  
Bruce Momjian 已提交
2111
	{
B
Bruce Momjian 已提交
2112 2113 2114 2115 2116 2117 2118 2119 2120
		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)
2121
				create_intersect_list(lfirst(arg), intersect_list);
B
Bruce Momjian 已提交
2122 2123 2124
			return;
		}
		return;
B
Hi!  
Bruce Momjian 已提交
2125 2126 2127 2128 2129
	}
}

/* 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 已提交
2130
 * it again but return a pointer to the previously cooked version given in 'parsetree'
B
Hi!  
Bruce Momjian 已提交
2131
 * instead. */
2132
static Node *
B
Bruce Momjian 已提交
2133
intersect_tree_analyze(Node *tree, Node *first_select, Node *parsetree)
B
Hi!  
Bruce Momjian 已提交
2134
{
B
Bruce Momjian 已提交
2135 2136
	Node	   *result = (Node *) NIL;
	List	   *arg;
2137 2138

	if (IsA(tree, SelectStmt))
B
Bruce Momjian 已提交
2139 2140 2141 2142 2143 2144
	{

		/*
		 * If we get to the tree given in first_select return parsetree
		 * instead of performing parse_analyze()
		 */
2145 2146 2147
		if (tree == first_select)
			result = parsetree;
		else
B
Bruce Momjian 已提交
2148 2149 2150 2151
		{
			/* transform the 'raw' nodes to 'cooked' Query nodes */
			List	   *qtree = parse_analyze(lcons(tree, NIL), NULL);

2152 2153
			result = (Node *) lfirst(qtree);
		}
B
Bruce Momjian 已提交
2154
	}
2155

B
Bruce Momjian 已提交
2156
	if (IsA(tree, Expr))
B
Hi!  
Bruce Momjian 已提交
2157
	{
B
Bruce Momjian 已提交
2158 2159 2160 2161
		/* 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 已提交
2162
	}
B
Bruce Momjian 已提交
2163
	return result;
B
Hi!  
Bruce Momjian 已提交
2164
}