1 /*-------------------------------------------------------------------------
4 * Routines to compute (and set) relation sizes and path costs
6 * Path costs are measured in units of disk accesses: one sequential page
7 * fetch has cost 1. All else is scaled relative to a page fetch, using
8 * the scaling parameters
10 * random_page_cost Cost of a non-sequential page fetch
11 * cpu_tuple_cost Cost of typical CPU time to process a tuple
12 * cpu_index_tuple_cost Cost of typical CPU time to process an index tuple
13 * cpu_operator_cost Cost of CPU time to process a typical WHERE operator
15 * We also use a rough estimate "effective_cache_size" of the number of
16 * disk pages in Postgres + OS-level disk cache. (We can't simply use
17 * NBuffers for this purpose because that would ignore the effects of
18 * the kernel's disk cache.)
20 * Obviously, taking constants for these values is an oversimplification,
21 * but it's tough enough to get any useful estimates even at this level of
22 * detail. Note that all of these parameters are user-settable, in case
23 * the default values are drastically off for a particular platform.
25 * We compute two separate costs for each path:
26 * total_cost: total estimated cost to fetch all tuples
27 * startup_cost: cost that is expended before first tuple is fetched
28 * In some scenarios, such as when there is a LIMIT or we are implementing
29 * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
30 * path's result. A caller can estimate the cost of fetching a partial
31 * result by interpolating between startup_cost and total_cost. In detail:
32 * actual_cost = startup_cost +
33 * (total_cost - startup_cost) * tuples_to_fetch / path->parent->rows;
34 * Note that a relation's rows count (and, by extension, a Plan's plan_rows)
35 * are set without regard to any LIMIT, so that this equation works properly.
36 * (Also, these routines guarantee not to set the rows count to zero, so there
37 * will be no zero divide.) RelOptInfos, Paths, and Plans themselves never
41 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
42 * Portions Copyright (c) 1994, Regents of the University of California
45 * $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.53 2000/03/14 02:23:14 tgl Exp $
47 *-------------------------------------------------------------------------
54 #include "miscadmin.h"
55 #include "nodes/plannodes.h"
56 #include "optimizer/clauses.h"
57 #include "optimizer/cost.h"
58 #include "optimizer/internal.h"
59 #include "optimizer/tlist.h"
60 #include "utils/lsyscache.h"
63 #define LOG2(x) (log(x) / 0.693147180559945)
64 #define LOG6(x) (log(x) / 1.79175946922805)
67 double effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
68 Cost random_page_cost = DEFAULT_RANDOM_PAGE_COST;
69 Cost cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
70 Cost cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
71 Cost cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
73 Cost disable_cost = 100000000.0;
75 bool enable_seqscan = true;
76 bool enable_indexscan = true;
77 bool enable_tidscan = true;
78 bool enable_sort = true;
79 bool enable_nestloop = true;
80 bool enable_mergejoin = true;
81 bool enable_hashjoin = true;
84 static bool cost_qual_eval_walker(Node *node, Cost *total);
85 static void set_rel_width(Query *root, RelOptInfo *rel);
86 static int compute_attribute_width(TargetEntry *tlistentry);
87 static double relation_byte_size(double tuples, int width);
88 static double page_size(double tuples, int width);
93 * Determines and returns the cost of scanning a relation sequentially.
95 * If the relation is a temporary to be materialized from a query
96 * embedded within a data field (determined by 'relid' containing an
97 * attribute reference), then a predetermined constant is returned (we
98 * have NO IDEA how big the result of a POSTQUEL procedure is going to be).
100 * Note: for historical reasons, this routine and the others in this module
101 * use the passed result Path only to store their startup_cost and total_cost
102 * results into. All the input data they need is passed as separate
103 * parameters, even though much of it could be extracted from the result Path.
106 cost_seqscan(Path *path, RelOptInfo *baserel)
108 Cost startup_cost = 0;
112 /* Should only be applied to base relations */
113 Assert(length(baserel->relids) == 1);
116 startup_cost += disable_cost;
119 if (lfirsti(baserel->relids) < 0)
122 * cost of sequentially scanning a materialized temporary relation
124 run_cost += _NONAME_SCAN_COST_;
129 * The cost of reading a page sequentially is 1.0, by definition.
130 * Note that the Unix kernel will typically do some amount of
131 * read-ahead optimization, so that this cost is less than the true
132 * cost of reading a page from disk. We ignore that issue here,
133 * but must take it into account when estimating the cost of
134 * non-sequential accesses!
136 run_cost += baserel->pages; /* sequential fetches with cost 1.0 */
140 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
141 run_cost += cpu_per_tuple * baserel->tuples;
143 path->startup_cost = startup_cost;
144 path->total_cost = startup_cost + run_cost;
148 * cost_nonsequential_access
149 * Estimate the cost of accessing one page at random from a relation
150 * (or sort temp file) of the given size in pages.
152 * The simplistic model that the cost is random_page_cost is what we want
153 * to use for large relations; but for small ones that is a serious
154 * overestimate because of the effects of caching. This routine tries to
157 * Unfortunately we don't have any good way of estimating the effective cache
158 * size we are working with --- we know that Postgres itself has NBuffers
159 * internal buffers, but the size of the kernel's disk cache is uncertain,
160 * and how much of it we get to use is even less certain. We punt the problem
161 * for now by assuming we are given an effective_cache_size parameter.
163 * Given a guesstimated cache size, we estimate the actual I/O cost per page
164 * with the entirely ad-hoc equations:
165 * for rel_size <= effective_cache_size:
166 * 1 + (random_page_cost/2-1) * (rel_size/effective_cache_size) ** 2
167 * for rel_size >= effective_cache_size:
168 * random_page_cost * (1 - (effective_cache_size/rel_size)/2)
169 * These give the right asymptotic behavior (=> 1.0 as rel_size becomes
170 * small, => random_page_cost as it becomes large) and meet in the middle
171 * with the estimate that the cache is about 50% effective for a relation
172 * of the same size as effective_cache_size. (XXX this is probably all
173 * wrong, but I haven't been able to find any theory about how effective
174 * a disk cache should be presumed to be.)
177 cost_nonsequential_access(double relpages)
181 /* don't crash on bad input data */
182 if (relpages <= 0.0 || effective_cache_size <= 0.0)
183 return random_page_cost;
185 relsize = relpages / effective_cache_size;
188 return random_page_cost * (1.0 - 0.5 / relsize);
190 return 1.0 + (random_page_cost * 0.5 - 1.0) * relsize * relsize;
195 * Determines and returns the cost of scanning a relation using an index.
197 * NOTE: an indexscan plan node can actually represent several passes,
198 * but here we consider the cost of just one pass.
200 * 'root' is the query root
201 * 'baserel' is the base relation the index is for
202 * 'index' is the index to be used
203 * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
204 * 'is_injoin' is T if we are considering using the index scan as the inside
205 * of a nestloop join.
207 * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
208 * Any additional quals evaluated as qpquals may reduce the number of returned
209 * tuples, but they won't reduce the number of tuples we have to fetch from
210 * the table, so they don't reduce the scan cost.
213 cost_index(Path *path, Query *root,
219 Cost startup_cost = 0;
222 Cost indexStartupCost;
224 Selectivity indexSelectivity;
225 double tuples_fetched;
226 double pages_fetched;
228 /* Should only be applied to base relations */
229 Assert(IsA(baserel, RelOptInfo) && IsA(index, IndexOptInfo));
230 Assert(length(baserel->relids) == 1);
232 if (!enable_indexscan && !is_injoin)
233 startup_cost += disable_cost;
236 * Call index-access-method-specific code to estimate the processing
237 * cost for scanning the index, as well as the selectivity of the index
238 * (ie, the fraction of main-table tuples we will have to retrieve).
240 fmgr(index->amcostestimate, root, baserel, index, indexQuals,
241 &indexStartupCost, &indexTotalCost, &indexSelectivity);
243 /* all costs for touching index itself included here */
244 startup_cost += indexStartupCost;
245 run_cost += indexTotalCost - indexStartupCost;
248 * Estimate number of main-table tuples and pages fetched.
250 * If the number of tuples is much smaller than the number of pages in
251 * the relation, each tuple will cost a separate nonsequential fetch.
252 * If it is comparable or larger, then probably we will be able to avoid
253 * some fetches. We use a growth rate of log(#tuples/#pages + 1) ---
254 * probably totally bogus, but intuitively it gives the right shape of
257 * XXX if the relation has recently been "clustered" using this index,
258 * then in fact the target tuples will be highly nonuniformly distributed,
259 * and we will be seriously overestimating the scan cost! Currently we
260 * have no way to know whether the relation has been clustered, nor how
261 * much it's been modified since the last clustering, so we ignore this
262 * effect. Would be nice to do better someday.
265 tuples_fetched = indexSelectivity * baserel->tuples;
267 if (tuples_fetched > 0 && baserel->pages > 0)
268 pages_fetched = baserel->pages *
269 log(tuples_fetched / baserel->pages + 1.0);
271 pages_fetched = tuples_fetched;
274 * Now estimate one nonsequential access per page fetched,
275 * plus appropriate CPU costs per tuple.
278 /* disk costs for main table */
279 run_cost += pages_fetched * cost_nonsequential_access(baserel->pages);
282 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
284 * Assume that the indexquals will be removed from the list of
285 * restriction clauses that we actually have to evaluate as qpquals.
286 * This is not completely right, but it's close.
287 * For a lossy index, however, we will have to recheck all the quals.
290 cpu_per_tuple -= cost_qual_eval(indexQuals);
292 run_cost += cpu_per_tuple * tuples_fetched;
294 path->startup_cost = startup_cost;
295 path->total_cost = startup_cost + run_cost;
300 * Determines and returns the cost of scanning a relation using tid-s.
303 cost_tidscan(Path *path, RelOptInfo *baserel, List *tideval)
305 Cost startup_cost = 0;
308 int ntuples = length(tideval);
311 startup_cost += disable_cost;
313 /* disk costs --- assume each tuple on a different page */
314 run_cost += random_page_cost * ntuples;
317 cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
318 run_cost += cpu_per_tuple * ntuples;
320 path->startup_cost = startup_cost;
321 path->total_cost = startup_cost + run_cost;
326 * Determines and returns the cost of sorting a relation.
328 * The cost of supplying the input data is NOT included; the caller should
329 * add that cost to both startup and total costs returned from this routine!
331 * If the total volume of data to sort is less than SortMem, we will do
332 * an in-memory sort, which requires no I/O and about t*log2(t) tuple
333 * comparisons for t tuples.
335 * If the total volume exceeds SortMem, we switch to a tape-style merge
336 * algorithm. There will still be about t*log2(t) tuple comparisons in
337 * total, but we will also need to write and read each tuple once per
338 * merge pass. We expect about ceil(log6(r)) merge passes where r is the
339 * number of initial runs formed (log6 because tuplesort.c uses six-tape
340 * merging). Since the average initial run should be about twice SortMem,
342 * disk traffic = 2 * relsize * ceil(log6(p / (2*SortMem)))
343 * cpu = comparison_cost * t * log2(t)
345 * The disk traffic is assumed to be half sequential and half random
346 * accesses (XXX can't we refine that guess?)
348 * We charge two operator evals per tuple comparison, which should be in
349 * the right ballpark in most cases.
351 * 'pathkeys' is a list of sort keys
352 * 'tuples' is the number of tuples in the relation
353 * 'width' is the average tuple width in bytes
355 * NOTE: some callers currently pass NIL for pathkeys because they
356 * can't conveniently supply the sort keys. Since this routine doesn't
357 * currently do anything with pathkeys anyway, that doesn't matter...
358 * but if it ever does, it should react gracefully to lack of key data.
361 cost_sort(Path *path, List *pathkeys, double tuples, int width)
363 Cost startup_cost = 0;
365 double nbytes = relation_byte_size(tuples, width);
366 long sortmembytes = SortMem * 1024L;
369 startup_cost += disable_cost;
372 * We want to be sure the cost of a sort is never estimated as zero,
373 * even if passed-in tuple count is zero. Besides, mustn't do
382 * Assume about two operator evals per tuple comparison
383 * and N log2 N comparisons
385 startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
388 if (nbytes > sortmembytes)
390 double npages = ceil(nbytes / BLCKSZ);
391 double nruns = nbytes / (sortmembytes * 2);
392 double log_runs = ceil(LOG6(nruns));
393 double npageaccesses;
397 npageaccesses = 2.0 * npages * log_runs;
398 /* Assume half are sequential (cost 1), half are not */
399 startup_cost += npageaccesses *
400 (1.0 + cost_nonsequential_access(npages)) * 0.5;
404 * Note: should we bother to assign a nonzero run_cost to reflect the
405 * overhead of extracting tuples from the sort result? Probably not
406 * worth worrying about.
408 path->startup_cost = startup_cost;
409 path->total_cost = startup_cost + run_cost;
415 * Determines and returns the cost of joining two relations using the
416 * nested loop algorithm.
418 * 'outer_path' is the path for the outer relation
419 * 'inner_path' is the path for the inner relation
420 * 'restrictlist' are the RestrictInfo nodes to be applied at the join
421 * 'is_indexjoin' is true if we are using an indexscan for the inner relation
422 * (not currently needed here; the indexscan adjusts its cost...)
425 cost_nestloop(Path *path,
431 Cost startup_cost = 0;
436 if (!enable_nestloop)
437 startup_cost += disable_cost;
439 /* cost of source data */
441 * NOTE: we assume that the inner path's startup_cost is paid once, not
442 * over again on each restart. This is certainly correct if the inner
443 * path is materialized. Are there any cases where it is wrong?
445 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
446 run_cost += outer_path->total_cost - outer_path->startup_cost;
447 run_cost += outer_path->parent->rows *
448 (inner_path->total_cost - inner_path->startup_cost);
450 /* number of tuples processed (not number emitted!) */
451 ntuples = outer_path->parent->rows * inner_path->parent->rows;
454 cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
455 run_cost += cpu_per_tuple * ntuples;
457 path->startup_cost = startup_cost;
458 path->total_cost = startup_cost + run_cost;
463 * Determines and returns the cost of joining two relations using the
464 * merge join algorithm.
466 * 'outer_path' is the path for the outer relation
467 * 'inner_path' is the path for the inner relation
468 * 'restrictlist' are the RestrictInfo nodes to be applied at the join
469 * 'outersortkeys' and 'innersortkeys' are lists of the keys to be used
470 * to sort the outer and inner relations, or NIL if no explicit
471 * sort is needed because the source path is already ordered
474 cost_mergejoin(Path *path,
481 Cost startup_cost = 0;
485 Path sort_path; /* dummy for result of cost_sort */
487 if (!enable_mergejoin)
488 startup_cost += disable_cost;
490 /* cost of source data */
492 * Note we are assuming that each source tuple is fetched just once,
493 * which is not right in the presence of equal keys. If we had a way of
494 * estimating the proportion of equal keys, we could apply a correction
497 if (outersortkeys) /* do we need to sort outer? */
499 startup_cost += outer_path->total_cost;
500 cost_sort(&sort_path,
502 outer_path->parent->rows,
503 outer_path->parent->width);
504 startup_cost += sort_path.startup_cost;
505 run_cost += sort_path.total_cost - sort_path.startup_cost;
509 startup_cost += outer_path->startup_cost;
510 run_cost += outer_path->total_cost - outer_path->startup_cost;
513 if (innersortkeys) /* do we need to sort inner? */
515 startup_cost += inner_path->total_cost;
516 cost_sort(&sort_path,
518 inner_path->parent->rows,
519 inner_path->parent->width);
520 startup_cost += sort_path.startup_cost;
521 run_cost += sort_path.total_cost - sort_path.startup_cost;
525 startup_cost += inner_path->startup_cost;
526 run_cost += inner_path->total_cost - inner_path->startup_cost;
530 * Estimate the number of tuples to be processed in the mergejoin itself
531 * as one per tuple in the two source relations. This could be a drastic
532 * underestimate if there are many equal-keyed tuples in either relation,
533 * but we have no good way of estimating that...
535 ntuples = outer_path->parent->rows + inner_path->parent->rows;
538 cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
539 run_cost += cpu_per_tuple * ntuples;
541 path->startup_cost = startup_cost;
542 path->total_cost = startup_cost + run_cost;
547 * Determines and returns the cost of joining two relations using the
548 * hash join algorithm.
550 * 'outer_path' is the path for the outer relation
551 * 'inner_path' is the path for the inner relation
552 * 'restrictlist' are the RestrictInfo nodes to be applied at the join
553 * 'innerdisbursion' is an estimate of the disbursion statistic
554 * for the inner hash key.
557 cost_hashjoin(Path *path,
561 Selectivity innerdisbursion)
563 Cost startup_cost = 0;
567 double outerbytes = relation_byte_size(outer_path->parent->rows,
568 outer_path->parent->width);
569 double innerbytes = relation_byte_size(inner_path->parent->rows,
570 inner_path->parent->width);
571 long hashtablebytes = SortMem * 1024L;
573 if (!enable_hashjoin)
574 startup_cost += disable_cost;
576 /* cost of source data */
577 startup_cost += outer_path->startup_cost;
578 run_cost += outer_path->total_cost - outer_path->startup_cost;
579 startup_cost += inner_path->total_cost;
581 /* cost of computing hash function: must do it once per input tuple */
582 startup_cost += cpu_operator_cost * inner_path->parent->rows;
583 run_cost += cpu_operator_cost * outer_path->parent->rows;
585 /* the number of tuple comparisons needed is the number of outer
586 * tuples times the typical hash bucket size, which we estimate
587 * conservatively as the inner disbursion times the inner tuple count.
589 run_cost += cpu_operator_cost * outer_path->parent->rows *
590 (inner_path->parent->rows * innerdisbursion);
593 * Estimate the number of tuples that get through the hashing filter
594 * as one per tuple in the two source relations. This could be a drastic
595 * underestimate if there are many equal-keyed tuples in either relation,
596 * but we have no good way of estimating that...
598 ntuples = outer_path->parent->rows + inner_path->parent->rows;
601 cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
602 run_cost += cpu_per_tuple * ntuples;
605 * if inner relation is too big then we will need to "batch" the join,
606 * which implies writing and reading most of the tuples to disk an
607 * extra time. Charge one cost unit per page of I/O (correct since
608 * it should be nice and sequential...). Writing the inner rel counts
609 * as startup cost, all the rest as run cost.
611 if (innerbytes > hashtablebytes)
613 double outerpages = page_size(outer_path->parent->rows,
614 outer_path->parent->width);
615 double innerpages = page_size(inner_path->parent->rows,
616 inner_path->parent->width);
618 startup_cost += innerpages;
619 run_cost += innerpages + 2 * outerpages;
623 * Bias against putting larger relation on inside. We don't want
624 * an absolute prohibition, though, since larger relation might have
625 * better disbursion --- and we can't trust the size estimates
626 * unreservedly, anyway. Instead, inflate the startup cost by
627 * the square root of the size ratio. (Why square root? No real good
628 * reason, but it seems reasonable...)
630 if (innerbytes > outerbytes && outerbytes > 0)
632 startup_cost *= sqrt(innerbytes / outerbytes);
635 path->startup_cost = startup_cost;
636 path->total_cost = startup_cost + run_cost;
642 * Estimate the CPU cost of evaluating a WHERE clause (once).
643 * The input can be either an implicitly-ANDed list of boolean
644 * expressions, or a list of RestrictInfo nodes.
647 cost_qual_eval(List *quals)
651 cost_qual_eval_walker((Node *) quals, &total);
656 cost_qual_eval_walker(Node *node, Cost *total)
661 * Our basic strategy is to charge one cpu_operator_cost for each
662 * operator or function node in the given tree. Vars and Consts
663 * are charged zero, and so are boolean operators (AND, OR, NOT).
664 * Simplistic, but a lot better than no model at all.
666 * Should we try to account for the possibility of short-circuit
667 * evaluation of AND/OR?
671 Expr *expr = (Expr *) node;
673 switch (expr->opType)
677 *total += cpu_operator_cost;
685 * A subplan node in an expression indicates that the subplan
686 * will be executed on each evaluation, so charge accordingly.
687 * (We assume that sub-selects that can be executed as
688 * InitPlans have already been removed from the expression.)
690 * NOTE: this logic should agree with the estimates used by
691 * make_subplan() in plan/subselect.c.
694 SubPlan *subplan = (SubPlan *) expr->oper;
695 Plan *plan = subplan->plan;
698 if (subplan->sublink->subLinkType == EXISTS_SUBLINK)
700 /* we only need to fetch 1 tuple */
701 subcost = plan->startup_cost +
702 (plan->total_cost - plan->startup_cost) / plan->plan_rows;
704 else if (subplan->sublink->subLinkType == ALL_SUBLINK ||
705 subplan->sublink->subLinkType == ANY_SUBLINK)
707 /* assume we need 50% of the tuples */
708 subcost = plan->startup_cost +
709 0.50 * (plan->total_cost - plan->startup_cost);
710 /* XXX what if subplan has been materialized? */
714 /* assume we need all tuples */
715 subcost = plan->total_cost;
721 /* fall through to examine args of Expr node */
724 * expression_tree_walker doesn't know what to do with RestrictInfo nodes,
725 * but we just want to recurse through them.
727 if (IsA(node, RestrictInfo))
729 RestrictInfo *restrictinfo = (RestrictInfo *) node;
731 return cost_qual_eval_walker((Node *) restrictinfo->clause, total);
733 /* Otherwise, recurse. */
734 return expression_tree_walker(node, cost_qual_eval_walker,
740 * set_baserel_size_estimates
741 * Set the size estimates for the given base relation.
743 * The rel's targetlist and restrictinfo list must have been constructed
746 * We set the following fields of the rel node:
747 * rows: the estimated number of output tuples (after applying
748 * restriction clauses).
749 * width: the estimated average output tuple width in bytes.
750 * baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
753 set_baserel_size_estimates(Query *root, RelOptInfo *rel)
755 /* Should only be applied to base relations */
756 Assert(length(rel->relids) == 1);
758 rel->rows = rel->tuples *
759 restrictlist_selectivity(root,
760 rel->baserestrictinfo,
761 lfirsti(rel->relids));
763 * Force estimate to be at least one row, to make explain output look
764 * better and to avoid possible divide-by-zero when interpolating cost.
769 rel->baserestrictcost = cost_qual_eval(rel->baserestrictinfo);
771 set_rel_width(root, rel);
775 * set_joinrel_size_estimates
776 * Set the size estimates for the given join relation.
778 * The rel's targetlist must have been constructed already, and a
779 * restriction clause list that matches the given component rels must
782 * Since there is more than one way to make a joinrel for more than two
783 * base relations, the results we get here could depend on which component
784 * rel pair is provided. In theory we should get the same answers no matter
785 * which pair is provided; in practice, since the selectivity estimation
786 * routines don't handle all cases equally well, we might not. But there's
787 * not much to be done about it. (Would it make sense to repeat the
788 * calculations for each pair of input rels that's encountered, and somehow
789 * average the results? Probably way more trouble than it's worth.)
791 * We set the same relnode fields as set_baserel_size_estimates() does.
794 set_joinrel_size_estimates(Query *root, RelOptInfo *rel,
795 RelOptInfo *outer_rel,
796 RelOptInfo *inner_rel,
801 /* cartesian product */
802 temp = outer_rel->rows * inner_rel->rows;
805 * Apply join restrictivity. Note that we are only considering clauses
806 * that become restriction clauses at this join level; we are not
807 * double-counting them because they were not considered in estimating
808 * the sizes of the component rels.
810 temp *= restrictlist_selectivity(root,
815 * Force estimate to be at least one row, to make explain output look
816 * better and to avoid possible divide-by-zero when interpolating cost.
823 * We could apply set_rel_width() to compute the output tuple width
824 * from scratch, but at present it's always just the sum of the input
825 * widths, so why work harder than necessary? If relnode.c is ever
826 * taught to remove unneeded columns from join targetlists, go back
827 * to using set_rel_width here.
829 rel->width = outer_rel->width + inner_rel->width;
834 * Set the estimated output width of the relation.
837 set_rel_width(Query *root, RelOptInfo *rel)
842 foreach(tle, rel->targetlist)
843 tuple_width += compute_attribute_width((TargetEntry *) lfirst(tle));
844 Assert(tuple_width >= 0);
845 rel->width = tuple_width;
849 * compute_attribute_width
850 * Given a target list entry, find the size in bytes of the attribute.
852 * If a field is variable-length, we make a default assumption. Would be
853 * better if VACUUM recorded some stats about the average field width...
854 * also, we have access to the atttypmod, but fail to use it...
857 compute_attribute_width(TargetEntry *tlistentry)
859 int width = get_typlen(tlistentry->resdom->restype);
862 return _DEFAULT_ATTRIBUTE_WIDTH_;
869 * Estimate the storage space in bytes for a given number of tuples
870 * of a given width (size in bytes).
873 relation_byte_size(double tuples, int width)
875 return tuples * ((double) (width + sizeof(HeapTupleData)));
880 * Returns an estimate of the number of pages covered by a given
881 * number of tuples of a given width (size in bytes).
884 page_size(double tuples, int width)
886 return ceil(relation_byte_size(tuples, width) / BLCKSZ);