xfunc.c 40.5 KB
Newer Older
1 2 3
/*-------------------------------------------------------------------------
 *
 * xfunc.c--
4 5 6 7
 *	  Utility routines to handle expensive function optimization.
 *	  Includes xfunc_trypullup(), which attempts early pullup of predicates
 *	  to allow for maximal pruning.
 *
8 9 10 11
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
12
 *	  $Header: /cvsroot/pgsql/src/backend/optimizer/path/Attic/xfunc.c,v 1.17 1998/08/04 16:44:11 momjian Exp $
13 14 15
 *
 *-------------------------------------------------------------------------
 */
16
#include <math.h>				/* for MAXFLOAT on most systems */
17

18
#include <values.h>				/* for MAXFLOAT on SunOS */
19 20 21
#include <string.h>

#include "postgres.h"
22 23 24 25 26 27

#include "access/heapam.h"
#include "catalog/pg_language.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "lib/lispsort.h"
28
#include "nodes/nodes.h"
29
#include "nodes/pg_list.h"
30 31
#include "nodes/primnodes.h"
#include "nodes/relation.h"
32 33
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
34
#include "optimizer/internal.h"
35
#include "optimizer/keys.h"
36
#include "optimizer/pathnode.h"
37
#include "optimizer/tlist.h"	/* for get_expr */
38
#include "optimizer/xfunc.h"
39
#include "storage/buf_internals.h"		/* for NBuffers */
40 41
#include "tcop/dest.h"
#include "utils/syscache.h"
42 43 44 45

#define ever ; 1 ;

/* local funcs */
46
static int
47 48
xfunc_card_unreferenced(Query *queryInfo,
						Expr *clause, Relid referenced);
49 50

*/
51 52 53

/*
** xfunc_trypullup --
54
**	  Preliminary pullup of predicates, to allow for maximal pruning.
55 56 57 58
** Given a relation, check each of its paths and see if you can
** pullup clauses from its inner and outer.
*/

59
void
Bruce Momjian's avatar
Bruce Momjian committed
60
xfunc_trypullup(RelOptInfo rel)
61
{
62 63
	LispValue	y;				/* list ptr */
	CInfo		maxcinfo;		/* The CInfo to pull up, as calculated by
64
								 * xfunc_shouldpull() */
65 66
	JoinPath	curpath;		/* current path in list */
	int			progress;		/* has progress been made this time
67
								 * through? */
68
	int			clausetype;
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

	do
	{
		progress = false;		/* no progress yet in this iteration */
		foreach(y, get_pathlist(rel))
		{
			curpath = (JoinPath) lfirst(y);

			/*
			 * * for each operand, attempt to pullup predicates until
			 * first * failure.
			 */
			for (ever)
			{
				/* No, the following should NOT be '=='  !! */
				if (clausetype =
					xfunc_shouldpull((Path) get_innerjoinpath(curpath),
									 curpath, INNER, &maxcinfo))
				{

					xfunc_pullup((Path) get_innerjoinpath(curpath),
								 curpath, maxcinfo, INNER, clausetype);
					progress = true;
				}
				else
					break;
			}
			for (ever)
			{

				/* No, the following should NOT be '=='  !! */
				if (clausetype =
					xfunc_shouldpull((Path) get_outerjoinpath(curpath),
									 curpath, OUTER, &maxcinfo))
				{

					xfunc_pullup((Path) get_outerjoinpath(curpath),
								 curpath, maxcinfo, OUTER, clausetype);
					progress = true;
				}
				else
					break;
			}

			/*
			 * * make sure the unpruneable flag bubbles up, i.e. * if
			 * anywhere below us in the path pruneable is false, * then
			 * pruneable should be false here
			 */
			if (get_pruneable(get_parent(curpath)) &&
				(!get_pruneable(get_parent
								((Path) get_innerjoinpath(curpath))) ||
				 !get_pruneable(get_parent((Path)
										   get_outerjoinpath(curpath)))))
			{

				set_pruneable(get_parent(curpath), false);
				progress = true;
			}
		}
	} while (progress);
130 131 132 133 134 135 136 137 138 139 140 141
}

/*
 ** xfunc_shouldpull --
 **    find clause with highest rank, and decide whether to pull it up
 ** from child to parent.  Currently we only pullup secondary join clauses
 ** that are in the pathclauseinfo.  Secondary hash and sort clauses are
 ** left where they are.
 **    If we find an expensive function but decide *not* to pull it up,
 ** we'd better set the unpruneable flag.  -- JMH, 11/11/92
 **
 ** Returns:  0 if nothing left to pullup
142 143
 **			  XFUNC_LOCPRD if a local predicate is to be pulled up
 **			  XFUNC_JOINPRD if a secondary join predicate is to be pulled up
144
 */
145
int
146
xfunc_shouldpull(Query *queryInfo,
147 148 149
				 Path childpath,
				 JoinPath parentpath,
				 int whichchild,
150
				 CInfo *maxcinfopt)		/* Out: pointer to clause to
151
										 * pullup */
152
{
153 154 155 156
	LispValue	clauselist,
				tmplist;		/* lists of clauses */
	CInfo		maxcinfo;		/* clause to pullup */
	LispValue	primjoinclause	/* primary join clause */
157
	= xfunc_primary_join(parentpath);
158 159 160 161 162
	Cost		tmprank,
				maxrank = (-1 * MAXFLOAT);		/* ranks of clauses */
	Cost		joinselec = 0;	/* selectivity of the join predicate */
	Cost		joincost = 0;	/* join cost + primjoinclause cost */
	int			retval = XFUNC_LOCPRD;
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182

	clauselist = get_locclauseinfo(childpath);

	if (clauselist != LispNil)
	{
		/* find local predicate with maximum rank */
		for (tmplist = clauselist,
			 maxcinfo = (CInfo) lfirst(tmplist),
			 maxrank = xfunc_rank(get_clause(maxcinfo));
			 tmplist != LispNil;
			 tmplist = lnext(tmplist))
		{

			if ((tmprank = xfunc_rank(get_clause((CInfo) lfirst(tmplist))))
				> maxrank)
			{
				maxcinfo = (CInfo) lfirst(tmplist);
				maxrank = tmprank;
			}
		}
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 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

	/*
	 * * If child is a join path, and there are multiple join clauses, *
	 * see if any join clause has even higher rank than the highest *
	 * local predicate
	 */
	if (is_join(childpath) && xfunc_num_join_clauses((JoinPath) childpath) > 1)
		for (tmplist = get_pathclauseinfo((JoinPath) childpath);
			 tmplist != LispNil;
			 tmplist = lnext(tmplist))
		{

			if (tmplist != LispNil &&
			  (tmprank = xfunc_rank(get_clause((CInfo) lfirst(tmplist))))
				> maxrank)
			{
				maxcinfo = (CInfo) lfirst(tmplist);
				maxrank = tmprank;
				retval = XFUNC_JOINPRD;
			}
		}
	if (maxrank == (-1 * MAXFLOAT))		/* no expensive clauses */
		return (0);

	/*
	 * * Pullup over join if clause is higher rank than join, or if * join
	 * is nested loop and current path is inner child (note that *
	 * restrictions on the inner of a nested loop don't buy you anything
	 * -- * you still have to scan the entire inner relation each time). *
	 * Note that the cost of a secondary join clause is only what's *
	 * calculated by xfunc_expense(), since the actual joining * (i.e. the
	 * usual path_cost) is paid for by the primary join clause.
	 */
	if (primjoinclause != LispNil)
	{
		joinselec = compute_clause_selec(queryInfo, primjoinclause, LispNil);
		joincost = xfunc_join_expense(parentpath, whichchild);

		if (XfuncMode == XFUNC_PULLALL ||
			(XfuncMode != XFUNC_WAIT &&
			 ((joincost != 0 &&
			   (maxrank = xfunc_rank(get_clause(maxcinfo))) >
			   ((joinselec - 1.0) / joincost))
			  || (joincost == 0 && joinselec < 1)
			  || (!is_join(childpath)
				  && (whichchild == INNER)
				  && IsA(parentpath, JoinPath)
231 232
				  &&!IsA(parentpath, HashPath)
				  &&!IsA(parentpath, MergePath)))))
233 234 235 236 237 238 239 240 241 242 243 244
		{

			*maxcinfopt = maxcinfo;
			return (retval);

		}
		else if (maxrank != -(MAXFLOAT))
		{

			/*
			 * * we've left an expensive restriction below a join.  Since *
			 * we may pullup this restriction in predmig.c, we'd best *
Bruce Momjian's avatar
Bruce Momjian committed
245
			 * set the RelOptInfo of this join to be unpruneable
246 247 248 249
			 */
			set_pruneable(get_parent(parentpath), false);
			/* and fall through */
		}
250
	}
251
	return (0);
252 253 254 255 256
}


/*
 ** xfunc_pullup --
257
 **    move clause from child pathnode to parent pathnode.	 This operation
258
 ** makes the child pathnode produce a larger relation than it used to.
Bruce Momjian's avatar
Bruce Momjian committed
259 260
 ** This means that we must construct a new RelOptInfo just for the childpath,
 ** although this RelOptInfo will not be added to the list of Rels to be joined up
261 262 263 264 265
 ** in the query; it's merely a parent for the new childpath.
 **    We also have to fix up the path costs of the child and parent.
 **
 ** Now returns a pointer to the new pulled-up CInfo. -- JMH, 11/18/92
 */
266
CInfo
267
xfunc_pullup(Query *queryInfo,
268 269 270 271 272
			 Path childpath,
			 JoinPath parentpath,
			 CInfo cinfo,		/* clause to pull up */
			 int whichchild,	/* whether child is INNER or OUTER of join */
			 int clausetype)	/* whether clause to pull is join or local */
273
{
274
	Path		newkid;
Bruce Momjian's avatar
Bruce Momjian committed
275
	RelOptInfo			newrel;
276 277 278
	Cost		pulled_selec;
	Cost		cost;
	CInfo		newinfo;
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

	/* remove clause from childpath */
	newkid = (Path) copyObject((Node) childpath);
	if (clausetype == XFUNC_LOCPRD)
	{
		set_locclauseinfo(newkid,
						  xfunc_LispRemove((LispValue) cinfo,
									  (List) get_locclauseinfo(newkid)));
	}
	else
	{
		set_pathclauseinfo
			((JoinPath) newkid,
			 xfunc_LispRemove((LispValue) cinfo,
						  (List) get_pathclauseinfo((JoinPath) newkid)));
	}

	/*
Bruce Momjian's avatar
Bruce Momjian committed
297
	 * * give the new child path its own RelOptInfo node that reflects the * lack
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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
	 * of the pulled-up predicate
	 */
	pulled_selec = compute_clause_selec(queryInfo,
										get_clause(cinfo), LispNil);
	xfunc_copyrel(get_parent(newkid), &newrel);
	set_parent(newkid, newrel);
	set_pathlist(newrel, lcons(newkid, NIL));
	set_unorderedpath(newrel, (PathPtr) newkid);
	set_cheapestpath(newrel, (PathPtr) newkid);
	set_size(newrel,
		(Count) ((Cost) get_size(get_parent(childpath)) / pulled_selec));

	/*
	 * * fix up path cost of newkid.  To do this we subtract away all the *
	 * xfunc_costs of childpath, then recompute the xfunc_costs of newkid
	 */
	cost = get_path_cost(newkid) - xfunc_get_path_cost(childpath);
	Assert(cost >= 0);
	set_path_cost(newkid, cost);
	cost = get_path_cost(newkid) + xfunc_get_path_cost(newkid);
	set_path_cost(newkid, cost);

	/*
	 * * We copy the cinfo, since it may appear in other plans, and we're
	 * going * to munge it.  -- JMH, 7/22/92
	 */
	newinfo = (CInfo) copyObject((Node) cinfo);

	/*
	 * * Fix all vars in the clause * to point to the right varno and
	 * varattno in parentpath
	 */
	xfunc_fixvars(get_clause(newinfo), newrel, whichchild);

	/* add clause to parentpath, and fix up its cost. */
	set_locclauseinfo(parentpath,
					  lispCons((LispValue) newinfo,
							 (LispValue) get_locclauseinfo(parentpath)));
	/* put new childpath into the path tree */
	if (whichchild == INNER)
		set_innerjoinpath(parentpath, (pathPtr) newkid);
	else
		set_outerjoinpath(parentpath, (pathPtr) newkid);

	/*
	 * * recompute parentpath cost from scratch -- the cost * of the join
	 * method has changed
	 */
	cost = xfunc_total_path_cost(parentpath);
	set_path_cost(parentpath, cost);

	return (newinfo);
350 351 352
}

/*
353
 ** calculate (selectivity-1)/cost.
354
 */
355
Cost
356
xfunc_rank(Query *queryInfo, LispValue clause)
357
{
358 359
	Cost		selec = compute_clause_selec(queryInfo, clause, LispNil);
	Cost		cost = xfunc_expense(queryInfo, clause);
360 361 362 363 364 365 366

	if (cost == 0)
		if (selec > 1)
			return (MAXFLOAT);
		else
			return (-(MAXFLOAT));
	return ((selec - 1) / cost);
367 368 369 370 371 372 373
}

/*
 ** Find the "global" expense of a clause; i.e. the local expense divided
 ** by the cardinalities of all the base relations of the query that are *not*
 ** referenced in the clause.
 */
374
Cost
375
xfunc_expense(Query *queryInfo, clause)
376
LispValue	clause;
377
{
378
	Cost		cost = xfunc_local_expense(clause);
379 380

	if (cost)
381
	{
382
		Count		card = xfunc_card_unreferenced(queryInfo, clause, LispNil);
383 384 385

		if (card)
			cost /= card;
386
	}
387 388

	return (cost);
389 390 391 392 393 394
}

/*
 ** xfunc_join_expense --
 **    Find global expense of a join clause
 */
395
Cost
396
xfunc_join_expense(Query *queryInfo, JoinPath path, int whichchild)
397
{
398
	LispValue	primjoinclause = xfunc_primary_join(path);
399 400 401 402

	/*
	 * * the second argument to xfunc_card_unreferenced reflects all the *
	 * relations involved in the join clause, i.e. all the relids in the
Bruce Momjian's avatar
Bruce Momjian committed
403
	 * RelOptInfo * of the join clause
404
	 */
405 406
	Count		card = 0;
	Cost		cost = xfunc_expense_per_tuple(path, whichchild);
407 408 409 410 411 412 413 414 415 416 417

	card = xfunc_card_unreferenced(queryInfo,
								   primjoinclause,
								   get_relids(get_parent(path)));
	if (primjoinclause)
		cost += xfunc_local_expense(primjoinclause);

	if (card)
		cost /= card;

	return (cost);
418 419 420 421 422 423
}

/*
 ** Recursively find the per-tuple expense of a clause.  See
 ** xfunc_func_expense for more discussion.
 */
424 425
Cost
xfunc_local_expense(LispValue clause)
426
{
427 428
	Cost		cost = 0;		/* running expense */
	LispValue	tmpclause;
429 430

	/* First handle the base case */
431
	if (IsA(clause, Const) ||IsA(clause, Var) ||IsA(clause, Param))
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
		return (0);
	/* now other stuff */
	else if (IsA(clause, Iter))
		/* Too low. Should multiply by the expected number of iterations. */
		return (xfunc_local_expense(get_iterexpr((Iter) clause)));
	else if (IsA(clause, ArrayRef))
		return (xfunc_local_expense(get_refexpr((ArrayRef) clause)));
	else if (fast_is_clause(clause))
		return (xfunc_func_expense((LispValue) get_op(clause),
								   (LispValue) get_opargs(clause)));
	else if (fast_is_funcclause(clause))
		return (xfunc_func_expense((LispValue) get_function(clause),
								   (LispValue) get_funcargs(clause)));
	else if (fast_not_clause(clause))
		return (xfunc_local_expense(lsecond(clause)));
447
	else if (fast_or_clause(clause) || fast_and_clause(clause))
448 449 450 451 452 453 454 455 456
	{
		/* find cost of evaluating each disjunct */
		for (tmpclause = lnext(clause); tmpclause != LispNil;
			 tmpclause = lnext(tmpclause))
			cost += xfunc_local_expense(lfirst(tmpclause));
		return (cost);
	}
	else
	{
457
		elog(ERROR, "Clause node of undetermined type");
458 459
		return (-1);
	}
460 461 462 463 464 465
}

/*
 ** xfunc_func_expense --
 **    given a Func or Oper and its args, find its expense.
 ** Note: in Stonebraker's SIGMOD '91 paper, he uses a more complicated metric
466
 ** than the one here.	We can ignore the expected number of tuples for
467 468 469 470 471 472 473 474 475
 ** our calculations; we just need the per-tuple expense.  But he also
 ** proposes components to take into account the costs of accessing disk and
 ** archive.  We didn't adopt that scheme here; eventually the vacuum
 ** cleaner should be able to tell us what percentage of bytes to find on
 ** which storage level, and that should be multiplied in appropriately
 ** in the cost function below.  Right now we don't model the cost of
 ** accessing secondary or tertiary storage, since we don't have sufficient
 ** stats to do it right.
 */
476 477
Cost
xfunc_func_expense(LispValue node, LispValue args)
478
{
479 480
	HeapTuple	tupl;			/* the pg_proc tuple for each function */
	Form_pg_proc proc;			/* a data structure to hold the pg_proc
481
								 * tuple */
482
	int			width = 0;		/* byte width of the field referenced by
483
								 * each clause */
484 485 486 487
	RegProcedure funcid;		/* ID of function associate with node */
	Cost		cost = 0;		/* running expense */
	LispValue	tmpclause;
	LispValue	operand;		/* one operand of an operator */
488 489 490 491 492

	if (IsA(node, Oper))
	{
		/* don't trust the opid in the Oper node.  Use the opno. */
		if (!(funcid = get_opcode(get_opno((Oper) node))))
493
			elog(ERROR, "Oper's function is undefined");
494
	}
495 496 497 498 499 500
	else
		funcid = get_funcid((Func) node);

	/* look up tuple in cache */
	tupl = SearchSysCacheTuple(PROOID, ObjectIdGetDatum(funcid), 0, 0, 0);
	if (!HeapTupleIsValid(tupl))
501
		elog(ERROR, "Cache lookup failed for procedure %d", funcid);
502 503
	proc = (Form_pg_proc) GETSTRUCT(tupl);

504
	/*
505 506
	 * * if it's a Postquel function, its cost is stored in the *
	 * associated plan.
507
	 */
508 509
	if (proc->prolang == SQLlanguageId)
	{
510 511
		LispValue	tmpplan;
		List		planlist;
512

513
		if (IsA(node, Oper) ||get_func_planlist((Func) node) == LispNil)
514
		{
515 516 517 518
			Oid		   *argOidVect;		/* vector of argtypes */
			char	   *pq_src; /* text of PQ function */
			int			nargs;	/* num args to PQ function */
			QueryTreeList *queryTree_list;		/* dummy variable */
519 520 521 522 523 524 525 526 527

			/*
			 * * plan the function, storing it in the Func node for later *
			 * use by the executor.
			 */
			pq_src = (char *) textout(&(proc->prosrc));
			nargs = proc->pronargs;
			if (nargs > 0)
				argOidVect = proc->proargtypes;
528
			planlist = (List) pg_parse_and_plan(pq_src, argOidVect, nargs,
529
												&parseTree_list, None);
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 578 579 580
			if (IsA(node, Func))
				set_func_planlist((Func) node, planlist);

		}
		else
		{						/* plan has been cached inside the Func
								 * node already */
			planlist = get_func_planlist((Func) node);
		}

		/*
		 * * Return the sum of the costs of the plans (the PQ function *
		 * may have many queries in its body).
		 */
		foreach(tmpplan, planlist)
			cost += get_cost((Plan) lfirst(tmpplan));
		return (cost);
	}
	else
	{							/* it's a C function */

		/*
		 * *  find the cost of evaluating the function's arguments *  and
		 * the width of the operands
		 */
		for (tmpclause = args; tmpclause != LispNil;
			 tmpclause = lnext(tmpclause))
		{

			if ((operand = lfirst(tmpclause)) != LispNil)
			{
				cost += xfunc_local_expense(operand);
				width += xfunc_width(operand);
			}
		}

		/*
		 * * when stats become available, add in cost of accessing
		 * secondary * and tertiary storage here.
		 */
		return (cost +
				(Cost) proc->propercall_cpu +
		(Cost) proc->properbyte_cpu * (Cost) proc->probyte_pct / 100.00 *
				(Cost) width

		/*
		 * Pct_of_obj_in_mem DISK_COST * proc->probyte_pct/100.00 * width
		 * Pct_of_obj_on_disk + ARCH_COST * proc->probyte_pct/100.00 *
		 * width Pct_of_obj_on_arch
		 */
			);
581 582 583
	}
}

584
/*
585 586 587 588
 ** xfunc_width --
 **    recursively find the width of a expression
 */

589 590
int
xfunc_width(LispValue clause)
591
{
592 593 594 595
	Relation	rd;				/* Relation Descriptor */
	HeapTuple	tupl;			/* structure to hold a cached tuple */
	TypeTupleForm type;			/* structure to hold a type tuple */
	int			retval = 0;
596 597 598 599 600 601

	if (IsA(clause, Const))
	{
		/* base case: width is the width of this constant */
		retval = get_constlen((Const) clause);
		goto exit;
602
	}
603 604 605 606 607
	else if (IsA(clause, ArrayRef))
	{
		/* base case: width is width of the refelem within the array */
		retval = get_refelemlength((ArrayRef) clause);
		goto exit;
608
	}
609 610 611 612 613 614 615
	else if (IsA(clause, Var))
	{
		/* base case: width is width of this attribute */
		tupl = SearchSysCacheTuple(TYPOID,
							  PointerGetDatum(get_vartype((Var) clause)),
								   0, 0, 0);
		if (!HeapTupleIsValid(tupl))
616
			elog(ERROR, "Cache lookup failed for type %d",
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
				 get_vartype((Var) clause));
		type = (TypeTupleForm) GETSTRUCT(tupl);
		if (get_varattno((Var) clause) == 0)
		{
			/* clause is a tuple.  Get its width */
			rd = heap_open(type->typrelid);
			retval = xfunc_tuple_width(rd);
			heap_close(rd);
		}
		else
		{
			/* attribute is a base type */
			retval = type->typlen;
		}
		goto exit;
	}
	else if (IsA(clause, Param))
	{
635
		if (typeidTypeRelid(get_paramtype((Param) clause)))
636 637
		{
			/* Param node returns a tuple.	Find its width */
638
			rd = heap_open(typeidTypeRelid(get_paramtype((Param) clause)));
639 640 641 642 643 644 645 646 647 648 649 650 651 652
			retval = xfunc_tuple_width(rd);
			heap_close(rd);
		}
		else if (get_param_tlist((Param) clause) != LispNil)
		{
			/* Param node projects a complex type */
			Assert(length(get_param_tlist((Param) clause)) == 1);		/* sanity */
			retval =
				xfunc_width((LispValue)
					  get_expr(lfirst(get_param_tlist((Param) clause))));
		}
		else
		{
			/* Param node returns a base type */
653
			retval = typeLen(typeidType(get_paramtype((Param) clause)));
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
		}
		goto exit;
	}
	else if (IsA(clause, Iter))
	{

		/*
		 * * An Iter returns a setof things, so return the width of a
		 * single * thing. * Note:	THIS MAY NOT WORK RIGHT WHEN AGGS GET
		 * FIXED, * SINCE AGG FUNCTIONS CHEW ON THE WHOLE SETOF THINGS!!!! *
		 * This whole Iter business is bogus, anyway.
		 */
		retval = xfunc_width(get_iterexpr((Iter) clause));
		goto exit;
	}
	else if (fast_is_clause(clause))
	{

		/*
		 * * get function associated with this Oper, and treat this as * a
		 * Func
		 */
		tupl = SearchSysCacheTuple(OPROID,
					   ObjectIdGetDatum(get_opno((Oper) get_op(clause))),
								   0, 0, 0);
		if (!HeapTupleIsValid(tupl))
680
			elog(ERROR, "Cache lookup failed for procedure %d",
681 682 683 684 685 686 687
				 get_opno((Oper) get_op(clause)));
		return (xfunc_func_width
				((RegProcedure) (((OperatorTupleForm) (GETSTRUCT(tupl)))->oprcode),
				 (LispValue) get_opargs(clause)));
	}
	else if (fast_is_funcclause(clause))
	{
688
		Func		func = (Func) get_function(clause);
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710

		if (get_func_tlist(func) != LispNil)
		{

			/*
			 * this function has a projection on it.  Get the length of
			 * the projected attribute
			 */
			Assert(length(get_func_tlist(func)) == 1);	/* sanity */
			retval =
				xfunc_width((LispValue)
							get_expr(lfirst(get_func_tlist(func))));
			goto exit;
		}
		else
		{
			return (xfunc_func_width((RegProcedure) get_funcid(func),
									 (LispValue) get_funcargs(clause)));
		}
	}
	else
	{
711
		elog(ERROR, "Clause node of undetermined type");
712
		return (-1);
713
	}
714 715 716 717 718

exit:
	if (retval == -1)
		retval = VARLEN_DEFAULT;
	return (retval);
719 720 721 722
}

/*
 ** xfunc_card_unreferenced:
723 724
 **   find all relations not referenced in clause, and multiply their
 ** cardinalities.	Ignore relation of cardinality 0.
725 726 727
 ** User may pass in referenced list, if they know it (useful
 ** for joins).
 */
728
static Count
729
xfunc_card_unreferenced(Query *queryInfo,
730
						LispValue clause, Relid referenced)
731
{
732 733 734
	Relid		unreferenced,
				allrelids = LispNil;
	LispValue	temp;
735 736 737

	/* find all relids of base relations referenced in query */
	foreach(temp, queryInfo->base_relation_list_)
738
	{
Bruce Momjian's avatar
Bruce Momjian committed
739
		Assert(lnext(get_relids((RelOptInfo) lfirst(temp))) == LispNil);
740
		allrelids = lappend(allrelids,
Bruce Momjian's avatar
Bruce Momjian committed
741
							lfirst(get_relids((RelOptInfo) lfirst(temp))));
742
	}
743 744 745 746 747 748 749

	/* find all relids referenced in query but not in clause */
	if (!referenced)
		referenced = xfunc_find_references(clause);
	unreferenced = set_difference(allrelids, referenced);

	return (xfunc_card_product(unreferenced));
750 751 752
}

/*
753
 ** xfunc_card_product
754 755
 **   multiple together cardinalities of a list relations.
 */
756
Count
757
xfunc_card_product(Query *queryInfo, Relid relids)
758
{
759 760
	LispValue	cinfonode;
	LispValue	temp;
Bruce Momjian's avatar
Bruce Momjian committed
761
	RelOptInfo			currel;
762 763
	Cost		tuples;
	Count		retval = 0;
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786

	foreach(temp, relids)
	{
		currel = get_rel(lfirst(temp));
		tuples = get_tuples(currel);

		if (tuples)
		{						/* not of cardinality 0 */
			/* factor in the selectivity of all zero-cost clauses */
			foreach(cinfonode, get_clauseinfo(currel))
			{
				if (!xfunc_expense(queryInfo, get_clause((CInfo) lfirst(cinfonode))))
					tuples *=
						compute_clause_selec(queryInfo,
								   get_clause((CInfo) lfirst(cinfonode)),
											 LispNil);
			}

			if (retval == 0)
				retval = tuples;
			else
				retval *= tuples;
		}
787
	}
788 789 790
	if (retval == 0)
		retval = 1;				/* saves caller from dividing by zero */
	return (retval);
791 792 793 794 795 796 797
}


/*
 ** xfunc_find_references:
 **   Traverse a clause and find all relids referenced in the clause.
 */
798 799
List
xfunc_find_references(LispValue clause)
800
{
801 802
	List		retval = (List) LispNil;
	LispValue	tmpclause;
803 804 805 806

	/* Base cases */
	if (IsA(clause, Var))
		return (lispCons(lfirst(get_varid((Var) clause)), LispNil));
807
	else if (IsA(clause, Const) ||IsA(clause, Param))
808 809 810 811 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
		return ((List) LispNil);

	/* recursion */
	else if (IsA(clause, Iter))

		/*
		 * Too low. Should multiply by the expected number of iterations.
		 * maybe
		 */
		return (xfunc_find_references(get_iterexpr((Iter) clause)));
	else if (IsA(clause, ArrayRef))
		return (xfunc_find_references(get_refexpr((ArrayRef) clause)));
	else if (fast_is_clause(clause))
	{
		/* string together result of all operands of Oper */
		for (tmpclause = (LispValue) get_opargs(clause); tmpclause != LispNil;
			 tmpclause = lnext(tmpclause))
			retval = nconc(retval, xfunc_find_references(lfirst(tmpclause)));
		return (retval);
	}
	else if (fast_is_funcclause(clause))
	{
		/* string together result of all args of Func */
		for (tmpclause = (LispValue) get_funcargs(clause);
			 tmpclause != LispNil;
			 tmpclause = lnext(tmpclause))
			retval = nconc(retval, xfunc_find_references(lfirst(tmpclause)));
		return (retval);
	}
	else if (fast_not_clause(clause))
		return (xfunc_find_references(lsecond(clause)));
839
	else if (fast_or_clause(clause) || fast_and_clause(clause))
840 841 842 843 844 845 846 847 848
	{
		/* string together result of all operands of OR */
		for (tmpclause = lnext(clause); tmpclause != LispNil;
			 tmpclause = lnext(tmpclause))
			retval = nconc(retval, xfunc_find_references(lfirst(tmpclause)));
		return (retval);
	}
	else
	{
849
		elog(ERROR, "Clause node of undetermined type");
850 851
		return ((List) LispNil);
	}
852 853 854 855 856 857 858 859
}

/*
 ** xfunc_primary_join:
 **   Find the primary join clause: for Hash and Merge Joins, this is the
 ** min rank Hash or Merge clause, while for Nested Loop it's the
 ** min rank pathclause
 */
860 861
LispValue
xfunc_primary_join(JoinPath pathnode)
862
{
863 864 865 866 867 868
	LispValue	joinclauselist = get_pathclauseinfo(pathnode);
	CInfo		mincinfo;
	LispValue	tmplist;
	LispValue	minclause = LispNil;
	Cost		minrank,
				tmprank;
869 870

	if (IsA(pathnode, MergePath))
871
	{
872 873 874 875 876 877 878 879 880 881 882 883
		for (tmplist = get_path_mergeclauses((MergePath) pathnode),
			 minclause = lfirst(tmplist),
			 minrank = xfunc_rank(minclause);
			 tmplist != LispNil;
			 tmplist = lnext(tmplist))
			if ((tmprank = xfunc_rank(lfirst(tmplist)))
				< minrank)
			{
				minrank = tmprank;
				minclause = lfirst(tmplist);
			}
		return (minclause);
884
	}
885
	else if (IsA(pathnode, HashPath))
886
	{
887 888 889 890 891 892 893 894 895 896 897 898
		for (tmplist = get_path_hashclauses((HashPath) pathnode),
			 minclause = lfirst(tmplist),
			 minrank = xfunc_rank(minclause);
			 tmplist != LispNil;
			 tmplist = lnext(tmplist))
			if ((tmprank = xfunc_rank(lfirst(tmplist)))
				< minrank)
			{
				minrank = tmprank;
				minclause = lfirst(tmplist);
			}
		return (minclause);
899
	}
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915

	/* if we drop through, it's nested loop join */
	if (joinclauselist == LispNil)
		return (LispNil);

	for (tmplist = joinclauselist, mincinfo = (CInfo) lfirst(joinclauselist),
		 minrank = xfunc_rank(get_clause((CInfo) lfirst(tmplist)));
		 tmplist != LispNil;
		 tmplist = lnext(tmplist))
		if ((tmprank = xfunc_rank(get_clause((CInfo) lfirst(tmplist))))
			< minrank)
		{
			minrank = tmprank;
			mincinfo = (CInfo) lfirst(tmplist);
		}
	return ((LispValue) get_clause(mincinfo));
916 917 918 919 920 921
}

/*
 ** xfunc_get_path_cost
 **   get the expensive function costs of the path
 */
922
Cost
923
xfunc_get_path_cost(Query *queryInfo, Path pathnode)
924
{
925 926 927
	Cost		cost = 0;
	LispValue	tmplist;
	Cost		selec = 1.0;
928 929 930 931 932 933 934 935 936 937 938 939 940 941

	/*
	 * * first add in the expensive local function costs. * We ensure that
	 * the clauses are sorted by rank, so that we * know (via
	 * selectivities) the number of tuples that will be checked * by each
	 * function.  If we're not doing any optimization of expensive *
	 * functions, we don't sort.
	 */
	if (XfuncMode != XFUNC_OFF)
		set_locclauseinfo(pathnode, lisp_qsort(get_locclauseinfo(pathnode),
											   xfunc_cinfo_compare));
	for (tmplist = get_locclauseinfo(pathnode), selec = 1.0;
		 tmplist != LispNil;
		 tmplist = lnext(tmplist))
942
	{
943 944 945 946 947
		cost += (Cost) (xfunc_local_expense(get_clause((CInfo) lfirst(tmplist)))
					  * (Cost) get_tuples(get_parent(pathnode)) * selec);
		selec *= compute_clause_selec(queryInfo,
									  get_clause((CInfo) lfirst(tmplist)),
									  LispNil);
948
	}
949 950 951 952 953 954

	/*
	 * * Now add in any node-specific expensive function costs. * Again,
	 * we must ensure that the clauses are sorted by rank.
	 */
	if (IsA(pathnode, JoinPath))
955
	{
956 957 958 959 960 961 962
		if (XfuncMode != XFUNC_OFF)
			set_pathclauseinfo((JoinPath) pathnode, lisp_qsort
							   (get_pathclauseinfo((JoinPath) pathnode),
								xfunc_cinfo_compare));
		for (tmplist = get_pathclauseinfo((JoinPath) pathnode), selec = 1.0;
			 tmplist != LispNil;
			 tmplist = lnext(tmplist))
963
		{
964 965 966 967 968
			cost += (Cost) (xfunc_local_expense(get_clause((CInfo) lfirst(tmplist)))
					  * (Cost) get_tuples(get_parent(pathnode)) * selec);
			selec *= compute_clause_selec(queryInfo,
									 get_clause((CInfo) lfirst(tmplist)),
										  LispNil);
969 970
		}
	}
971
	if (IsA(pathnode, HashPath))
972
	{
973 974 975 976 977 978 979 980
		if (XfuncMode != XFUNC_OFF)
			set_path_hashclauses
				((HashPath) pathnode,
				 lisp_qsort(get_path_hashclauses((HashPath) pathnode),
							xfunc_clause_compare));
		for (tmplist = get_path_hashclauses((HashPath) pathnode), selec = 1.0;
			 tmplist != LispNil;
			 tmplist = lnext(tmplist))
981
		{
982 983 984 985
			cost += (Cost) (xfunc_local_expense(lfirst(tmplist))
					  * (Cost) get_tuples(get_parent(pathnode)) * selec);
			selec *= compute_clause_selec(queryInfo,
										  lfirst(tmplist), LispNil);
986 987
		}
	}
988
	if (IsA(pathnode, MergePath))
989
	{
990 991 992 993 994 995 996 997
		if (XfuncMode != XFUNC_OFF)
			set_path_mergeclauses
				((MergePath) pathnode,
				 lisp_qsort(get_path_mergeclauses((MergePath) pathnode),
							xfunc_clause_compare));
		for (tmplist = get_path_mergeclauses((MergePath) pathnode), selec = 1.0;
			 tmplist != LispNil;
			 tmplist = lnext(tmplist))
998
		{
999 1000 1001 1002
			cost += (Cost) (xfunc_local_expense(lfirst(tmplist))
					  * (Cost) get_tuples(get_parent(pathnode)) * selec);
			selec *= compute_clause_selec(queryInfo,
										  lfirst(tmplist), LispNil);
1003 1004
		}
	}
1005 1006
	Assert(cost >= 0);
	return (cost);
1007 1008 1009
}

/*
1010
 ** Recalculate the cost of a path node.  This includes the basic cost of the
1011 1012 1013 1014
 ** node, as well as the cost of its expensive functions.
 ** We need to do this to the parent after pulling a clause from a child into a
 ** parent.  Thus we should only be calling this function on JoinPaths.
 */
1015 1016
Cost
xfunc_total_path_cost(JoinPath pathnode)
1017
{
1018
	Cost		cost = xfunc_get_path_cost((Path) pathnode);
1019 1020 1021

	Assert(IsA(pathnode, JoinPath));
	if (IsA(pathnode, MergePath))
1022
	{
1023
		MergePath	mrgnode = (MergePath) pathnode;
1024

1025
		cost += cost_mergejoin(get_path_cost((Path) get_outerjoinpath(mrgnode)),
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
						get_path_cost((Path) get_innerjoinpath(mrgnode)),
							   get_outersortkeys(mrgnode),
							   get_innersortkeys(mrgnode),
						   get_tuples(get_parent((Path) get_outerjoinpath
												 (mrgnode))),
						   get_tuples(get_parent((Path) get_innerjoinpath
												 (mrgnode))),
							get_width(get_parent((Path) get_outerjoinpath
												 (mrgnode))),
							get_width(get_parent((Path) get_innerjoinpath
												 (mrgnode))));
		Assert(cost >= 0);
		return (cost);
1039
	}
1040
	else if (IsA(pathnode, HashPath))
1041
	{
1042
		HashPath hashnode = (HashPath) pathnode;
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

		cost += cost_hashjoin(get_path_cost((Path) get_outerjoinpath(hashnode)),
					   get_path_cost((Path) get_innerjoinpath(hashnode)),
							  get_outerhashkeys(hashnode),
							  get_innerhashkeys(hashnode),
						   get_tuples(get_parent((Path) get_outerjoinpath
												 (hashnode))),
						   get_tuples(get_parent((Path) get_innerjoinpath
												 (hashnode))),
							get_width(get_parent((Path) get_outerjoinpath
												 (hashnode))),
							get_width(get_parent((Path) get_innerjoinpath
												 (hashnode))));
		Assert(cost >= 0);
		return (cost);
1058
	}
1059 1060
	else
/* Nested Loop Join */
1061
	{
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
		cost += cost_nestloop(get_path_cost((Path) get_outerjoinpath(pathnode)),
					   get_path_cost((Path) get_innerjoinpath(pathnode)),
						   get_tuples(get_parent((Path) get_outerjoinpath
												 (pathnode))),
						   get_tuples(get_parent((Path) get_innerjoinpath
												 (pathnode))),
							get_pages(get_parent((Path) get_outerjoinpath
												 (pathnode))),
							IsA(get_innerjoinpath(pathnode), IndexPath));
		Assert(cost >= 0);
		return (cost);
1073 1074 1075 1076 1077 1078 1079 1080
	}
}


/*
 ** xfunc_expense_per_tuple --
 **    return the expense of the join *per-tuple* of the input relation.
 ** The cost model here is that a join costs
1081
 **		k*card(outer)*card(inner) + l*card(outer) + m*card(inner) + n
1082 1083 1084 1085 1086 1087 1088
 **
 ** We treat the l and m terms by considering them to be like restrictions
 ** constrained to be right under the join.  Thus the cost per inner and
 ** cost per outer of the join is different, reflecting these virtual nodes.
 **
 ** The cost per tuple of outer is k + l/referenced(inner).  Cost per tuple
 ** of inner is k + m/referenced(outer).
1089
 ** The constants k, l, m and n depend on the join method.	Measures here are
1090 1091 1092
 ** based on the costs in costsize.c, with fudging for HashJoin and Sorts to
 ** make it fit our model (the 'q' in HashJoin results in a
 ** card(outer)/card(inner) term, and sorting results in a log term.
1093

1094
 */
1095 1096
Cost
xfunc_expense_per_tuple(JoinPath joinnode, int whichchild)
1097
{
Bruce Momjian's avatar
Bruce Momjian committed
1098 1099
	RelOptInfo			outerrel = get_parent((Path) get_outerjoinpath(joinnode));
	RelOptInfo			innerrel = get_parent((Path) get_innerjoinpath(joinnode));
1100 1101
	Count		outerwidth = get_width(outerrel);
	Count		outers_per_page = ceil(BLCKSZ / (outerwidth + sizeof(HeapTupleData)));
1102 1103

	if (IsA(joinnode, HashPath))
1104
	{
1105 1106 1107 1108 1109 1110
		if (whichchild == INNER)
			return ((1 + _CPU_PAGE_WEIGHT_) * outers_per_page / NBuffers);
		else
			return (((1 + _CPU_PAGE_WEIGHT_) * outers_per_page / NBuffers)
					+ _CPU_PAGE_WEIGHT_
					/ xfunc_card_product(get_relids(innerrel)));
1111
	}
1112
	else if (IsA(joinnode, MergePath))
1113
	{
1114 1115 1116 1117 1118 1119 1120
		/* assumes sort exists, and costs one (I/O + CPU) per tuple */
		if (whichchild == INNER)
			return ((2 * _CPU_PAGE_WEIGHT_ + 1)
					/ xfunc_card_product(get_relids(outerrel)));
		else
			return ((2 * _CPU_PAGE_WEIGHT_ + 1)
					/ xfunc_card_product(get_relids(innerrel)));
1121
	}
1122 1123
	else
/* nestloop */
1124
	{
1125 1126
		Assert(IsA(joinnode, JoinPath));
		return (_CPU_PAGE_WEIGHT_);
1127 1128 1129 1130 1131
	}
}

/*
 ** xfunc_fixvars --
1132
 ** After pulling up a clause, we must walk its expression tree, fixing Var
1133
 ** nodes to point to the correct varno (either INNER or OUTER, depending
1134
 ** on which child the clause was pulled from), and the right varattno in the
1135
 ** target list of the child's former relation.  If the target list of the
Bruce Momjian's avatar
Bruce Momjian committed
1136
 ** child RelOptInfo does not contain the attribute we need, we add it.
1137
 */
1138 1139
void
xfunc_fixvars(LispValue clause, /* clause being pulled up */
Bruce Momjian's avatar
Bruce Momjian committed
1140
			  RelOptInfo rel,			/* rel it's being pulled from */
1141
			  int varno)		/* whether rel is INNER or OUTER of join */
1142
{
1143 1144
	LispValue	tmpclause;		/* temporary variable */
	TargetEntry *tle;			/* tlist member corresponding to var */
1145 1146


1147
	if (IsA(clause, Const) ||IsA(clause, Param))
1148 1149
		return;
	else if (IsA(clause, Var))
1150
	{
1151 1152 1153
		/* here's the meat */
		tle = tlistentry_member((Var) clause, get_targetlist(rel));
		if (tle == LispNil)
1154
		{
1155 1156 1157 1158 1159 1160 1161 1162

			/*
			 * * The attribute we need is not in the target list, * so we
			 * have to add it. *
			 *
			 */
			add_tl_element(rel, (Var) clause);
			tle = tlistentry_member((Var) clause, get_targetlist(rel));
1163
		}
1164 1165
		set_varno(((Var) clause), varno);
		set_varattno(((Var) clause), get_resno(get_resdom(get_entry(tle))));
1166
	}
1167 1168 1169
	else if (IsA(clause, Iter))
		xfunc_fixvars(get_iterexpr((Iter) clause), rel, varno);
	else if (fast_is_clause(clause))
1170
	{
1171 1172
		xfunc_fixvars(lfirst(lnext(clause)), rel, varno);
		xfunc_fixvars(lfirst(lnext(lnext(clause))), rel, varno);
1173
	}
1174 1175 1176 1177 1178 1179
	else if (fast_is_funcclause(clause))
		for (tmpclause = lnext(clause); tmpclause != LispNil;
			 tmpclause = lnext(tmpclause))
			xfunc_fixvars(lfirst(tmpclause), rel, varno);
	else if (fast_not_clause(clause))
		xfunc_fixvars(lsecond(clause), rel, varno);
1180
	else if (fast_or_clause(clause) || fast_and_clause(clause))
1181 1182 1183 1184
		for (tmpclause = lnext(clause); tmpclause != LispNil;
			 tmpclause = lnext(tmpclause))
			xfunc_fixvars(lfirst(tmpclause), rel, varno);
	else
1185
		elog(ERROR, "Clause node of undetermined type");
1186 1187 1188 1189 1190
}


/*
 ** Comparison function for lisp_qsort() on a list of CInfo's.
1191
 ** arg1 and arg2 should really be of type (CInfo *).
1192
 */
1193 1194
int
xfunc_cinfo_compare(void *arg1, void *arg2)
1195
{
1196 1197
	CInfo		info1 = *(CInfo *) arg1;
	CInfo		info2 = *(CInfo *) arg2;
1198

1199 1200
	LispValue	clause1 = (LispValue) get_clause(info1),
				clause2 = (LispValue) get_clause(info2);
1201 1202

	return (xfunc_clause_compare((void *) &clause1, (void *) &clause2));
1203 1204 1205
}

/*
1206
 ** xfunc_clause_compare: comparison function for lisp_qsort() that compares two
1207 1208 1209
 ** clauses based on expense/(1 - selectivity)
 ** arg1 and arg2 are really pointers to clauses.
 */
1210 1211
int
xfunc_clause_compare(void *arg1, void *arg2)
1212
{
1213 1214 1215 1216
	LispValue	clause1 = *(LispValue *) arg1;
	LispValue	clause2 = *(LispValue *) arg2;
	Cost		rank1,			/* total xfunc rank of clause1 */
				rank2;			/* total xfunc rank of clause2 */
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

	rank1 = xfunc_rank(clause1);
	rank2 = xfunc_rank(clause2);

	if (rank1 < rank2)
		return (-1);
	else if (rank1 == rank2)
		return (0);
	else
		return (1);
1227 1228 1229 1230 1231 1232 1233 1234
}

/*
 ** xfunc_disjunct_sort --
 **   given a list of clauses, for each clause sort the disjuncts by cost
 **   (this assumes the predicates have been converted to Conjunctive NF)
 **   Modifies the clause list!
 */
1235 1236
void
xfunc_disjunct_sort(LispValue clause_list)
1237
{
1238
	LispValue	temp;
1239 1240 1241 1242 1243

	foreach(temp, clause_list)
		if (or_clause(lfirst(temp)))
		lnext(lfirst(temp)) =
			lisp_qsort(lnext(lfirst(temp)), xfunc_disjunct_compare);
1244 1245 1246 1247
}


/*
1248
 ** xfunc_disjunct_compare: comparison function for qsort() that compares two
1249 1250 1251
 ** disjuncts based on cost/selec.
 ** arg1 and arg2 are really pointers to disjuncts
 */
1252
int
1253
xfunc_disjunct_compare(Query *queryInfo, void *arg1, void *arg2)
1254
{
1255 1256 1257 1258 1259 1260 1261 1262
	LispValue	disjunct1 = *(LispValue *) arg1;
	LispValue	disjunct2 = *(LispValue *) arg2;
	Cost		cost1,			/* total cost of disjunct1 */
				cost2,			/* total cost of disjunct2 */
				selec1,
				selec2;
	Cost		rank1,
				rank2;
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290

	cost1 = xfunc_expense(queryInfo, disjunct1);
	cost2 = xfunc_expense(queryInfo, disjunct2);
	selec1 = compute_clause_selec(queryInfo,
								  disjunct1, LispNil);
	selec2 = compute_clause_selec(queryInfo,
								  disjunct2, LispNil);

	if (selec1 == 0)
		rank1 = MAXFLOAT;
	else if (cost1 == 0)
		rank1 = 0;
	else
		rank1 = cost1 / selec1;

	if (selec2 == 0)
		rank2 = MAXFLOAT;
	else if (cost2 == 0)
		rank2 = 0;
	else
		rank2 = cost2 / selec2;

	if (rank1 < rank2)
		return (-1);
	else if (rank1 == rank2)
		return (0);
	else
		return (1);
1291 1292 1293 1294 1295 1296 1297
}

/* ------------------------ UTILITY FUNCTIONS ------------------------------- */
/*
 ** xfunc_func_width --
 **    Given a function OID and operands, find the width of the return value.
 */
1298 1299
int
xfunc_func_width(RegProcedure funcid, LispValue args)
1300
{
1301 1302 1303 1304 1305 1306
	Relation	rd;				/* Relation Descriptor */
	HeapTuple	tupl;			/* structure to hold a cached tuple */
	Form_pg_proc proc;			/* structure to hold the pg_proc tuple */
	TypeTupleForm type;			/* structure to hold the pg_type tuple */
	LispValue	tmpclause;
	int			retval;
1307 1308 1309 1310 1311

	/* lookup function and find its return type */
	Assert(RegProcedureIsValid(funcid));
	tupl = SearchSysCacheTuple(PROOID, ObjectIdGetDatum(funcid), 0, 0, 0);
	if (!HeapTupleIsValid(tupl))
1312
		elog(ERROR, "Cache lookup failed for procedure %d", funcid);
1313 1314 1315
	proc = (Form_pg_proc) GETSTRUCT(tupl);

	/* if function returns a tuple, get the width of that */
1316
	if (typeidTypeRelid(proc->prorettype))
1317
	{
1318
		rd = heap_open(typeidTypeRelid(proc->prorettype));
1319 1320 1321
		retval = xfunc_tuple_width(rd);
		heap_close(rd);
		goto exit;
1322
	}
1323 1324
	else
/* function returns a base type */
1325
	{
1326 1327 1328 1329
		tupl = SearchSysCacheTuple(TYPOID,
								   ObjectIdGetDatum(proc->prorettype),
								   0, 0, 0);
		if (!HeapTupleIsValid(tupl))
1330
			elog(ERROR, "Cache lookup failed for type %d", proc->prorettype);
1331 1332 1333
		type = (TypeTupleForm) GETSTRUCT(tupl);
		/* if the type length is known, return that */
		if (type->typlen != -1)
1334
		{
1335 1336
			retval = type->typlen;
			goto exit;
1337
		}
1338 1339
		else
/* estimate the return size */
1340
		{
1341 1342 1343 1344 1345 1346 1347
			/* find width of the function's arguments */
			for (tmpclause = args; tmpclause != LispNil;
				 tmpclause = lnext(tmpclause))
				retval += xfunc_width(lfirst(tmpclause));
			/* multiply by outin_ratio */
			retval = (int) (proc->prooutin_ratio / 100.0 * retval);
			goto exit;
1348 1349
		}
	}
1350 1351
exit:
	return (retval);
1352 1353 1354 1355
}

/*
 ** xfunc_tuple_width --
1356
 **		Return the sum of the lengths of all the attributes of a given relation
1357
 */
1358 1359
int
xfunc_tuple_width(Relation rd)
1360
{
1361 1362 1363
	int			i;
	int			retval = 0;
	TupleDesc	tdesc = RelationGetTupleDescriptor(rd);
1364 1365

	for (i = 0; i < tdesc->natts; i++)
1366
	{
1367 1368 1369 1370
		if (tdesc->attrs[i]->attlen != -1)
			retval += tdesc->attrs[i]->attlen;
		else
			retval += VARLEN_DEFAULT;
1371
	}
1372 1373

	return (retval);
1374 1375 1376 1377 1378 1379
}

/*
 ** xfunc_num_join_clauses --
 **   Find the number of join clauses associated with this join path
 */
1380 1381
int
xfunc_num_join_clauses(JoinPath path)
1382
{
1383
	int			num = length(get_pathclauseinfo(path));
1384 1385 1386 1387 1388 1389 1390

	if (IsA(path, MergePath))
		return (num + length(get_path_mergeclauses((MergePath) path)));
	else if (IsA(path, HashPath))
		return (num + length(get_path_hashclauses((HashPath) path)));
	else
		return (num);
1391 1392 1393 1394 1395 1396
}

/*
 ** xfunc_LispRemove --
 **   Just like LispRemove, but it whines if the item to be removed ain't there
 */
1397 1398
LispValue
xfunc_LispRemove(LispValue foo, List bar)
1399
{
1400 1401 1402
	LispValue	temp = LispNil;
	LispValue	result = LispNil;
	int			sanity = false;
1403 1404 1405 1406 1407 1408 1409 1410

	for (temp = bar; !null(temp); temp = lnext(temp))
		if (!equal((Node) (foo), (Node) (lfirst(temp))))
			result = lappend(result, lfirst(temp));
		else
			sanity = true;		/* found a matching item to remove! */

	if (!sanity)
1411
		elog(ERROR, "xfunc_LispRemove: didn't find a match!");
1412 1413

	return (result);
1414 1415 1416
}

#define Node_Copy(a, b, c, d) \
1417 1418 1419 1420 1421 1422
do { \
	if (NodeCopy((Node)((a)->d), (Node*)&((b)->d), c) != true) \
	{ \
		return false; \
	} \
} while(0)
1423 1424 1425 1426 1427

/*
 ** xfunc_copyrel --
 **   Just like _copyRel, but doesn't copy the paths
 */
1428
bool
Bruce Momjian's avatar
Bruce Momjian committed
1429
xfunc_copyrel(RelOptInfo from, RelOptInfo *to)
1430
{
Bruce Momjian's avatar
Bruce Momjian committed
1431
	RelOptInfo			newnode;
1432

1433
	Pointer		(*alloc) () = palloc;
1434 1435 1436 1437 1438 1439 1440

	/* COPY_CHECKARGS() */
	if (to == NULL)
		return false;

	/* COPY_CHECKNULL() */
	if (from == NULL)
1441
	{
1442 1443 1444 1445 1446
		(*to) = NULL;
		return true;
	}

	/* COPY_NEW(c) */
Bruce Momjian's avatar
Bruce Momjian committed
1447
	newnode = (RelOptInfo) (*alloc) (classSize(RelOptInfo));
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
	if (newnode == NULL)
		return false;

	/* ----------------
	 *	copy node superclass fields
	 * ----------------
	 */
	CopyNodeFields((Node) from, (Node) newnode, alloc);

	/* ----------------
	 *	copy remainder of node
	 * ----------------
	 */
	Node_Copy(from, newnode, alloc, relids);

	newnode->indexed = from->indexed;
	newnode->pages = from->pages;
	newnode->tuples = from->tuples;
	newnode->size = from->size;
	newnode->width = from->width;

	Node_Copy(from, newnode, alloc, targetlist);

	/*
	 * No!!!!	 Node_Copy(from, newnode, alloc, pathlist);
	 * Node_Copy(from, newnode, alloc, unorderedpath); Node_Copy(from,
	 * newnode, alloc, cheapestpath);
	 */
#if 0							/* can't use Node_copy now. 2/95 -ay */
	Node_Copy(from, newnode, alloc, classlist);
	Node_Copy(from, newnode, alloc, indexkeys);
	Node_Copy(from, newnode, alloc, ordering);
1480
#endif
1481 1482 1483 1484 1485 1486 1487
	Node_Copy(from, newnode, alloc, clauseinfo);
	Node_Copy(from, newnode, alloc, joininfo);
	Node_Copy(from, newnode, alloc, innerjoin);
	Node_Copy(from, newnode, alloc, superrels);

	(*to) = newnode;
	return true;
1488
}