]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/costsize.c
Support expressions of the form 'scalar op ANY (array)' and
[postgresql] / src / backend / optimizer / path / costsize.c
1 /*-------------------------------------------------------------------------
2  *
3  * costsize.c
4  *        Routines to compute (and set) relation sizes and path costs
5  *
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
9  *
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
14  *
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.)
19  *
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.
24  *
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 base relation's rows count (and, by extension, plan_rows for
35  * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
36  * that this equation works properly.  (Also, these routines guarantee not to
37  * set the rows count to zero, so there will be no zero divide.)  The LIMIT is
38  * applied as a top-level plan node.
39  *
40  * For largely historical reasons, most of the routines in this module use
41  * the passed result Path only to store their startup_cost and total_cost
42  * results into.  All the input data they need is passed as separate
43  * parameters, even though much of it could be extracted from the Path.
44  * An exception is made for the cost_XXXjoin() routines, which expect all
45  * the non-cost fields of the passed XXXPath to be filled in.
46  *
47  *
48  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
49  * Portions Copyright (c) 1994, Regents of the University of California
50  *
51  * IDENTIFICATION
52  *        $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.108 2003/06/29 00:33:43 tgl Exp $
53  *
54  *-------------------------------------------------------------------------
55  */
56
57 #include "postgres.h"
58
59 #include <math.h>
60
61 #include "catalog/pg_statistic.h"
62 #include "executor/nodeHash.h"
63 #include "miscadmin.h"
64 #include "optimizer/clauses.h"
65 #include "optimizer/cost.h"
66 #include "optimizer/pathnode.h"
67 #include "parser/parsetree.h"
68 #include "utils/selfuncs.h"
69 #include "utils/lsyscache.h"
70 #include "utils/syscache.h"
71
72
73 #define LOG2(x)  (log(x) / 0.693147180559945)
74 #define LOG6(x)  (log(x) / 1.79175946922805)
75
76 /*
77  * Some Paths return less than the nominal number of rows of their parent
78  * relations; join nodes need to do this to get the correct input count:
79  */
80 #define PATH_ROWS(path) \
81         (IsA(path, UniquePath) ? \
82          ((UniquePath *) (path))->rows : \
83          (path)->parent->rows)
84
85
86 double          effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
87 double          random_page_cost = DEFAULT_RANDOM_PAGE_COST;
88 double          cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
89 double          cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
90 double          cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
91
92 Cost            disable_cost = 100000000.0;
93
94 bool            enable_seqscan = true;
95 bool            enable_indexscan = true;
96 bool            enable_tidscan = true;
97 bool            enable_sort = true;
98 bool            enable_hashagg = true;
99 bool            enable_nestloop = true;
100 bool            enable_mergejoin = true;
101 bool            enable_hashjoin = true;
102
103
104 static Selectivity estimate_hash_bucketsize(Query *root, Var *var,
105                                                                                         int nbuckets);
106 static bool cost_qual_eval_walker(Node *node, QualCost *total);
107 static Selectivity approx_selectivity(Query *root, List *quals,
108                                                                           JoinType jointype);
109 static void set_rel_width(Query *root, RelOptInfo *rel);
110 static double relation_byte_size(double tuples, int width);
111 static double page_size(double tuples, int width);
112
113
114 /*
115  * cost_seqscan
116  *        Determines and returns the cost of scanning a relation sequentially.
117  */
118 void
119 cost_seqscan(Path *path, Query *root,
120                          RelOptInfo *baserel)
121 {
122         Cost            startup_cost = 0;
123         Cost            run_cost = 0;
124         Cost            cpu_per_tuple;
125
126         /* Should only be applied to base relations */
127         Assert(baserel->relid > 0);
128         Assert(baserel->rtekind == RTE_RELATION);
129
130         if (!enable_seqscan)
131                 startup_cost += disable_cost;
132
133         /*
134          * disk costs
135          *
136          * The cost of reading a page sequentially is 1.0, by definition. Note
137          * that the Unix kernel will typically do some amount of read-ahead
138          * optimization, so that this cost is less than the true cost of
139          * reading a page from disk.  We ignore that issue here, but must take
140          * it into account when estimating the cost of non-sequential
141          * accesses!
142          */
143         run_cost += baserel->pages; /* sequential fetches with cost 1.0 */
144
145         /* CPU costs */
146         startup_cost += baserel->baserestrictcost.startup;
147         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
148         run_cost += cpu_per_tuple * baserel->tuples;
149
150         path->startup_cost = startup_cost;
151         path->total_cost = startup_cost + run_cost;
152 }
153
154 /*
155  * cost_nonsequential_access
156  *        Estimate the cost of accessing one page at random from a relation
157  *        (or sort temp file) of the given size in pages.
158  *
159  * The simplistic model that the cost is random_page_cost is what we want
160  * to use for large relations; but for small ones that is a serious
161  * overestimate because of the effects of caching.      This routine tries to
162  * account for that.
163  *
164  * Unfortunately we don't have any good way of estimating the effective cache
165  * size we are working with --- we know that Postgres itself has NBuffers
166  * internal buffers, but the size of the kernel's disk cache is uncertain,
167  * and how much of it we get to use is even less certain.  We punt the problem
168  * for now by assuming we are given an effective_cache_size parameter.
169  *
170  * Given a guesstimated cache size, we estimate the actual I/O cost per page
171  * with the entirely ad-hoc equations:
172  *      if relpages >= effective_cache_size:
173  *              random_page_cost * (1 - (effective_cache_size/relpages)/2)
174  *      if relpages < effective_cache_size:
175  *              1 + (random_page_cost/2-1) * (relpages/effective_cache_size) ** 2
176  * These give the right asymptotic behavior (=> 1.0 as relpages becomes
177  * small, => random_page_cost as it becomes large) and meet in the middle
178  * with the estimate that the cache is about 50% effective for a relation
179  * of the same size as effective_cache_size.  (XXX this is probably all
180  * wrong, but I haven't been able to find any theory about how effective
181  * a disk cache should be presumed to be.)
182  */
183 static Cost
184 cost_nonsequential_access(double relpages)
185 {
186         double          relsize;
187
188         /* don't crash on bad input data */
189         if (relpages <= 0.0 || effective_cache_size <= 0.0)
190                 return random_page_cost;
191
192         relsize = relpages / effective_cache_size;
193
194         if (relsize >= 1.0)
195                 return random_page_cost * (1.0 - 0.5 / relsize);
196         else
197                 return 1.0 + (random_page_cost * 0.5 - 1.0) * relsize * relsize;
198 }
199
200 /*
201  * cost_index
202  *        Determines and returns the cost of scanning a relation using an index.
203  *
204  *        NOTE: an indexscan plan node can actually represent several passes,
205  *        but here we consider the cost of just one pass.
206  *
207  * 'root' is the query root
208  * 'baserel' is the base relation the index is for
209  * 'index' is the index to be used
210  * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
211  * 'is_injoin' is T if we are considering using the index scan as the inside
212  *              of a nestloop join (hence, some of the indexQuals are join clauses)
213  *
214  * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
215  * Any additional quals evaluated as qpquals may reduce the number of returned
216  * tuples, but they won't reduce the number of tuples we have to fetch from
217  * the table, so they don't reduce the scan cost.
218  */
219 void
220 cost_index(Path *path, Query *root,
221                    RelOptInfo *baserel,
222                    IndexOptInfo *index,
223                    List *indexQuals,
224                    bool is_injoin)
225 {
226         Cost            startup_cost = 0;
227         Cost            run_cost = 0;
228         Cost            indexStartupCost;
229         Cost            indexTotalCost;
230         Selectivity indexSelectivity;
231         double          indexCorrelation,
232                                 csquared;
233         Cost            min_IO_cost,
234                                 max_IO_cost;
235         Cost            cpu_per_tuple;
236         double          tuples_fetched;
237         double          pages_fetched;
238         double          T,
239                                 b;
240
241         /* Should only be applied to base relations */
242         Assert(IsA(baserel, RelOptInfo) &&
243                    IsA(index, IndexOptInfo));
244         Assert(baserel->relid > 0);
245         Assert(baserel->rtekind == RTE_RELATION);
246
247         if (!enable_indexscan)
248                 startup_cost += disable_cost;
249
250         /*
251          * Call index-access-method-specific code to estimate the processing
252          * cost for scanning the index, as well as the selectivity of the
253          * index (ie, the fraction of main-table tuples we will have to
254          * retrieve) and its correlation to the main-table tuple order.
255          */
256         OidFunctionCall8(index->amcostestimate,
257                                          PointerGetDatum(root),
258                                          PointerGetDatum(baserel),
259                                          PointerGetDatum(index),
260                                          PointerGetDatum(indexQuals),
261                                          PointerGetDatum(&indexStartupCost),
262                                          PointerGetDatum(&indexTotalCost),
263                                          PointerGetDatum(&indexSelectivity),
264                                          PointerGetDatum(&indexCorrelation));
265
266         /* all costs for touching index itself included here */
267         startup_cost += indexStartupCost;
268         run_cost += indexTotalCost - indexStartupCost;
269
270         /*----------
271          * Estimate number of main-table tuples and pages fetched.
272          *
273          * When the index ordering is uncorrelated with the table ordering,
274          * we use an approximation proposed by Mackert and Lohman, "Index Scans
275          * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
276          * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
277          * The Mackert and Lohman approximation is that the number of pages
278          * fetched is
279          *      PF =
280          *              min(2TNs/(2T+Ns), T)                    when T <= b
281          *              2TNs/(2T+Ns)                                    when T > b and Ns <= 2Tb/(2T-b)
282          *              b + (Ns - 2Tb/(2T-b))*(T-b)/T   when T > b and Ns > 2Tb/(2T-b)
283          * where
284          *              T = # pages in table
285          *              N = # tuples in table
286          *              s = selectivity = fraction of table to be scanned
287          *              b = # buffer pages available (we include kernel space here)
288          *
289          * When the index ordering is exactly correlated with the table ordering
290          * (just after a CLUSTER, for example), the number of pages fetched should
291          * be just sT.  What's more, these will be sequential fetches, not the
292          * random fetches that occur in the uncorrelated case.  So, depending on
293          * the extent of correlation, we should estimate the actual I/O cost
294          * somewhere between s * T * 1.0 and PF * random_cost.  We currently
295          * interpolate linearly between these two endpoints based on the
296          * correlation squared (XXX is that appropriate?).
297          *
298          * In any case the number of tuples fetched is Ns.
299          *----------
300          */
301
302         tuples_fetched = indexSelectivity * baserel->tuples;
303         /* Don't believe estimates less than 1... */
304         if (tuples_fetched < 1.0)
305                 tuples_fetched = 1.0;
306
307         /* This part is the Mackert and Lohman formula */
308
309         T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
310         b = (effective_cache_size > 1) ? effective_cache_size : 1.0;
311
312         if (T <= b)
313         {
314                 pages_fetched =
315                         (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
316                 if (pages_fetched > T)
317                         pages_fetched = T;
318         }
319         else
320         {
321                 double          lim;
322
323                 lim = (2.0 * T * b) / (2.0 * T - b);
324                 if (tuples_fetched <= lim)
325                 {
326                         pages_fetched =
327                                 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
328                 }
329                 else
330                 {
331                         pages_fetched =
332                                 b + (tuples_fetched - lim) * (T - b) / T;
333                 }
334         }
335
336         /*
337          * min_IO_cost corresponds to the perfectly correlated case
338          * (csquared=1), max_IO_cost to the perfectly uncorrelated case
339          * (csquared=0).  Note that we just charge random_page_cost per page
340          * in the uncorrelated case, rather than using
341          * cost_nonsequential_access, since we've already accounted for
342          * caching effects by using the Mackert model.
343          */
344         min_IO_cost = ceil(indexSelectivity * T);
345         max_IO_cost = pages_fetched * random_page_cost;
346
347         /*
348          * Now interpolate based on estimated index order correlation to get
349          * total disk I/O cost for main table accesses.
350          */
351         csquared = indexCorrelation * indexCorrelation;
352
353         run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
354
355         /*
356          * Estimate CPU costs per tuple.
357          *
358          * Normally the indexquals will be removed from the list of restriction
359          * clauses that we have to evaluate as qpquals, so we should subtract
360          * their costs from baserestrictcost.  But if we are doing a join then
361          * some of the indexquals are join clauses and shouldn't be subtracted.
362          * Rather than work out exactly how much to subtract, we don't subtract
363          * anything.
364          *
365          * XXX For a lossy index, not all the quals will be removed and so we
366          * really shouldn't subtract their costs; but detecting that seems more
367          * expensive than it's worth.
368          */
369         startup_cost += baserel->baserestrictcost.startup;
370         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
371
372         if (!is_injoin)
373         {
374                 QualCost        index_qual_cost;
375
376                 cost_qual_eval(&index_qual_cost, indexQuals);
377                 cpu_per_tuple -= index_qual_cost.per_tuple;
378         }
379
380         run_cost += cpu_per_tuple * tuples_fetched;
381
382         path->startup_cost = startup_cost;
383         path->total_cost = startup_cost + run_cost;
384 }
385
386 /*
387  * cost_tidscan
388  *        Determines and returns the cost of scanning a relation using TIDs.
389  */
390 void
391 cost_tidscan(Path *path, Query *root,
392                          RelOptInfo *baserel, List *tideval)
393 {
394         Cost            startup_cost = 0;
395         Cost            run_cost = 0;
396         Cost            cpu_per_tuple;
397         int                     ntuples = length(tideval);
398
399         /* Should only be applied to base relations */
400         Assert(baserel->relid > 0);
401         Assert(baserel->rtekind == RTE_RELATION);
402
403         if (!enable_tidscan)
404                 startup_cost += disable_cost;
405
406         /* disk costs --- assume each tuple on a different page */
407         run_cost += random_page_cost * ntuples;
408
409         /* CPU costs */
410         startup_cost += baserel->baserestrictcost.startup;
411         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
412         run_cost += cpu_per_tuple * ntuples;
413
414         path->startup_cost = startup_cost;
415         path->total_cost = startup_cost + run_cost;
416 }
417
418 /*
419  * cost_functionscan
420  *        Determines and returns the cost of scanning a function RTE.
421  */
422 void
423 cost_functionscan(Path *path, Query *root, RelOptInfo *baserel)
424 {
425         Cost            startup_cost = 0;
426         Cost            run_cost = 0;
427         Cost            cpu_per_tuple;
428
429         /* Should only be applied to base relations that are functions */
430         Assert(baserel->relid > 0);
431         Assert(baserel->rtekind == RTE_FUNCTION);
432
433         /*
434          * For now, estimate function's cost at one operator eval per function
435          * call.  Someday we should revive the function cost estimate columns
436          * in pg_proc...
437          */
438         cpu_per_tuple = cpu_operator_cost;
439
440         /* Add scanning CPU costs */
441         startup_cost += baserel->baserestrictcost.startup;
442         cpu_per_tuple += cpu_tuple_cost + baserel->baserestrictcost.per_tuple;
443         run_cost += cpu_per_tuple * baserel->tuples;
444
445         path->startup_cost = startup_cost;
446         path->total_cost = startup_cost + run_cost;
447 }
448
449 /*
450  * cost_sort
451  *        Determines and returns the cost of sorting a relation, including
452  *        the cost of reading the input data.
453  *
454  * If the total volume of data to sort is less than SortMem, we will do
455  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
456  * comparisons for t tuples.
457  *
458  * If the total volume exceeds SortMem, we switch to a tape-style merge
459  * algorithm.  There will still be about t*log2(t) tuple comparisons in
460  * total, but we will also need to write and read each tuple once per
461  * merge pass.  We expect about ceil(log6(r)) merge passes where r is the
462  * number of initial runs formed (log6 because tuplesort.c uses six-tape
463  * merging).  Since the average initial run should be about twice SortMem,
464  * we have
465  *              disk traffic = 2 * relsize * ceil(log6(p / (2*SortMem)))
466  *              cpu = comparison_cost * t * log2(t)
467  *
468  * The disk traffic is assumed to be half sequential and half random
469  * accesses (XXX can't we refine that guess?)
470  *
471  * We charge two operator evals per tuple comparison, which should be in
472  * the right ballpark in most cases.
473  *
474  * 'pathkeys' is a list of sort keys
475  * 'input_cost' is the total cost for reading the input data
476  * 'tuples' is the number of tuples in the relation
477  * 'width' is the average tuple width in bytes
478  *
479  * NOTE: some callers currently pass NIL for pathkeys because they
480  * can't conveniently supply the sort keys.  Since this routine doesn't
481  * currently do anything with pathkeys anyway, that doesn't matter...
482  * but if it ever does, it should react gracefully to lack of key data.
483  * (Actually, the thing we'd most likely be interested in is just the number
484  * of sort keys, which all callers *could* supply.)
485  */
486 void
487 cost_sort(Path *path, Query *root,
488                   List *pathkeys, Cost input_cost, double tuples, int width)
489 {
490         Cost            startup_cost = input_cost;
491         Cost            run_cost = 0;
492         double          nbytes = relation_byte_size(tuples, width);
493         long            sortmembytes = SortMem * 1024L;
494
495         if (!enable_sort)
496                 startup_cost += disable_cost;
497
498         /*
499          * We want to be sure the cost of a sort is never estimated as zero,
500          * even if passed-in tuple count is zero.  Besides, mustn't do
501          * log(0)...
502          */
503         if (tuples < 2.0)
504                 tuples = 2.0;
505
506         /*
507          * CPU costs
508          *
509          * Assume about two operator evals per tuple comparison and N log2 N
510          * comparisons
511          */
512         startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
513
514         /* disk costs */
515         if (nbytes > sortmembytes)
516         {
517                 double          npages = ceil(nbytes / BLCKSZ);
518                 double          nruns = nbytes / (sortmembytes * 2);
519                 double          log_runs = ceil(LOG6(nruns));
520                 double          npageaccesses;
521
522                 if (log_runs < 1.0)
523                         log_runs = 1.0;
524                 npageaccesses = 2.0 * npages * log_runs;
525                 /* Assume half are sequential (cost 1), half are not */
526                 startup_cost += npageaccesses *
527                         (1.0 + cost_nonsequential_access(npages)) * 0.5;
528         }
529
530         /*
531          * Also charge a small amount (arbitrarily set equal to operator cost)
532          * per extracted tuple.
533          */
534         run_cost += cpu_operator_cost * tuples;
535
536         path->startup_cost = startup_cost;
537         path->total_cost = startup_cost + run_cost;
538 }
539
540 /*
541  * cost_material
542  *        Determines and returns the cost of materializing a relation, including
543  *        the cost of reading the input data.
544  *
545  * If the total volume of data to materialize exceeds SortMem, we will need
546  * to write it to disk, so the cost is much higher in that case.
547  */
548 void
549 cost_material(Path *path,
550                           Cost input_cost, double tuples, int width)
551 {
552         Cost            startup_cost = input_cost;
553         Cost            run_cost = 0;
554         double          nbytes = relation_byte_size(tuples, width);
555         long            sortmembytes = SortMem * 1024L;
556
557         /* disk costs */
558         if (nbytes > sortmembytes)
559         {
560                 double          npages = ceil(nbytes / BLCKSZ);
561
562                 /* We'll write during startup and read during retrieval */
563                 startup_cost += npages;
564                 run_cost += npages;
565         }
566
567         /*
568          * Also charge a small amount per extracted tuple.  We use cpu_tuple_cost
569          * so that it doesn't appear worthwhile to materialize a bare seqscan.
570          */
571         run_cost += cpu_tuple_cost * tuples;
572
573         path->startup_cost = startup_cost;
574         path->total_cost = startup_cost + run_cost;
575 }
576
577 /*
578  * cost_agg
579  *              Determines and returns the cost of performing an Agg plan node,
580  *              including the cost of its input.
581  *
582  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
583  * are for appropriately-sorted input.
584  */
585 void
586 cost_agg(Path *path, Query *root,
587                  AggStrategy aggstrategy, int numAggs,
588                  int numGroupCols, double numGroups,
589                  Cost input_startup_cost, Cost input_total_cost,
590                  double input_tuples)
591 {
592         Cost            startup_cost;
593         Cost            total_cost;
594
595         /*
596          * We charge one cpu_operator_cost per aggregate function per input
597          * tuple, and another one per output tuple (corresponding to transfn
598          * and finalfn calls respectively).  If we are grouping, we charge an
599          * additional cpu_operator_cost per grouping column per input tuple
600          * for grouping comparisons.
601          *
602          * We will produce a single output tuple if not grouping,
603          * and a tuple per group otherwise.
604          *
605          * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
606          * same total CPU cost, but AGG_SORTED has lower startup cost.  If the
607          * input path is already sorted appropriately, AGG_SORTED should be
608          * preferred (since it has no risk of memory overflow).  This will happen
609          * as long as the computed total costs are indeed exactly equal --- but
610          * if there's roundoff error we might do the wrong thing.  So be sure
611          * that the computations below form the same intermediate values in the
612          * same order.
613          */
614         if (aggstrategy == AGG_PLAIN)
615         {
616                 startup_cost = input_total_cost;
617                 startup_cost += cpu_operator_cost * (input_tuples + 1) * numAggs;
618                 /* we aren't grouping */
619                 total_cost = startup_cost;
620         }
621         else if (aggstrategy == AGG_SORTED)
622         {
623                 /* Here we are able to deliver output on-the-fly */
624                 startup_cost = input_startup_cost;
625                 total_cost = input_total_cost;
626                 /* calcs phrased this way to match HASHED case, see note above */
627                 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
628                 total_cost += cpu_operator_cost * input_tuples * numAggs;
629                 total_cost += cpu_operator_cost * numGroups * numAggs;
630         }
631         else
632         {
633                 /* must be AGG_HASHED */
634                 startup_cost = input_total_cost;
635                 startup_cost += cpu_operator_cost * input_tuples * numGroupCols;
636                 startup_cost += cpu_operator_cost * input_tuples * numAggs;
637                 total_cost = startup_cost;
638                 total_cost += cpu_operator_cost * numGroups * numAggs;
639         }
640
641         path->startup_cost = startup_cost;
642         path->total_cost = total_cost;
643 }
644
645 /*
646  * cost_group
647  *              Determines and returns the cost of performing a Group plan node,
648  *              including the cost of its input.
649  *
650  * Note: caller must ensure that input costs are for appropriately-sorted
651  * input.
652  */
653 void
654 cost_group(Path *path, Query *root,
655                    int numGroupCols, double numGroups,
656                    Cost input_startup_cost, Cost input_total_cost,
657                    double input_tuples)
658 {
659         Cost            startup_cost;
660         Cost            total_cost;
661
662         startup_cost = input_startup_cost;
663         total_cost = input_total_cost;
664
665         /*
666          * Charge one cpu_operator_cost per comparison per input tuple. We
667          * assume all columns get compared at most of the tuples.
668          */
669         total_cost += cpu_operator_cost * input_tuples * numGroupCols;
670
671         path->startup_cost = startup_cost;
672         path->total_cost = total_cost;
673 }
674
675 /*
676  * cost_nestloop
677  *        Determines and returns the cost of joining two relations using the
678  *        nested loop algorithm.
679  *
680  * 'path' is already filled in except for the cost fields
681  */
682 void
683 cost_nestloop(NestPath *path, Query *root)
684 {
685         Path       *outer_path = path->outerjoinpath;
686         Path       *inner_path = path->innerjoinpath;
687         List       *restrictlist = path->joinrestrictinfo;
688         Cost            startup_cost = 0;
689         Cost            run_cost = 0;
690         Cost            cpu_per_tuple;
691         QualCost        restrict_qual_cost;
692         double          outer_path_rows = PATH_ROWS(outer_path);
693         double          inner_path_rows = PATH_ROWS(inner_path);
694         double          ntuples;
695         Selectivity     joininfactor;
696
697         if (!enable_nestloop)
698                 startup_cost += disable_cost;
699
700         /*
701          * If we're doing JOIN_IN then we will stop scanning inner tuples for an
702          * outer tuple as soon as we have one match.  Account for the effects of
703          * this by scaling down the cost estimates in proportion to the expected
704          * output size.  (This assumes that all the quals attached to the join are
705          * IN quals, which should be true.)
706          *
707          * Note: it's probably bogus to use the normal selectivity calculation
708          * here when either the outer or inner path is a UniquePath.
709          */
710         if (path->jointype == JOIN_IN)
711         {
712                 Selectivity     qual_selec = approx_selectivity(root, restrictlist,
713                                                                                                         path->jointype);
714                 double  qptuples;
715
716                 qptuples = ceil(qual_selec * outer_path_rows * inner_path_rows);
717                 if (qptuples > path->path.parent->rows)
718                         joininfactor = path->path.parent->rows / qptuples;
719                 else
720                         joininfactor = 1.0;
721         }
722         else
723                 joininfactor = 1.0;
724
725         /* cost of source data */
726
727         /*
728          * NOTE: clearly, we must pay both outer and inner paths' startup_cost
729          * before we can start returning tuples, so the join's startup cost is
730          * their sum.  What's not so clear is whether the inner path's
731          * startup_cost must be paid again on each rescan of the inner path.
732          * This is not true if the inner path is materialized or is a hashjoin,
733          * but probably is true otherwise.
734          */
735         startup_cost += outer_path->startup_cost + inner_path->startup_cost;
736         run_cost += outer_path->total_cost - outer_path->startup_cost;
737         if (IsA(inner_path, MaterialPath) ||
738                 IsA(inner_path, HashPath))
739         {
740                 /* charge only run cost for each iteration of inner path */
741         }
742         else
743         {
744                 /*
745                  * charge startup cost for each iteration of inner path, except we
746                  * already charged the first startup_cost in our own startup
747                  */
748                 run_cost += (outer_path_rows - 1) * inner_path->startup_cost;
749         }
750         run_cost += outer_path_rows *
751                 (inner_path->total_cost - inner_path->startup_cost) * joininfactor;
752
753         /*
754          * Compute number of tuples processed (not number emitted!).
755          * If inner path is an indexscan, be sure to use its estimated output row
756          * count, which may be lower than the restriction-clause-only row count of
757          * its parent.  (We don't include this case in the PATH_ROWS macro because
758          * it applies *only* to a nestloop's inner relation.)  Note: it is correct
759          * to use the unadjusted inner_path_rows in the above calculation for
760          * joininfactor, since otherwise we'd be double-counting the selectivity
761          * of the join clause being used for the index.
762          */
763         if (IsA(inner_path, IndexPath))
764                 inner_path_rows = ((IndexPath *) inner_path)->rows;
765
766         ntuples = inner_path_rows * outer_path_rows;
767
768         /* CPU costs */
769         cost_qual_eval(&restrict_qual_cost, restrictlist);
770         startup_cost += restrict_qual_cost.startup;
771         cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
772         run_cost += cpu_per_tuple * ntuples;
773
774         path->path.startup_cost = startup_cost;
775         path->path.total_cost = startup_cost + run_cost;
776 }
777
778 /*
779  * cost_mergejoin
780  *        Determines and returns the cost of joining two relations using the
781  *        merge join algorithm.
782  *
783  * 'path' is already filled in except for the cost fields
784  *
785  * Notes: path's mergeclauses should be a subset of the joinrestrictinfo list;
786  * outersortkeys and innersortkeys are lists of the keys to be used
787  * to sort the outer and inner relations, or NIL if no explicit
788  * sort is needed because the source path is already ordered.
789  */
790 void
791 cost_mergejoin(MergePath *path, Query *root)
792 {
793         Path       *outer_path = path->jpath.outerjoinpath;
794         Path       *inner_path = path->jpath.innerjoinpath;
795         List       *restrictlist = path->jpath.joinrestrictinfo;
796         List       *mergeclauses = path->path_mergeclauses;
797         List       *outersortkeys = path->outersortkeys;
798         List       *innersortkeys = path->innersortkeys;
799         Cost            startup_cost = 0;
800         Cost            run_cost = 0;
801         Cost            cpu_per_tuple;
802         Selectivity     merge_selec;
803         Selectivity     qp_selec;
804         QualCost        merge_qual_cost;
805         QualCost        qp_qual_cost;
806         RestrictInfo *firstclause;
807         List       *qpquals;
808         double          outer_path_rows = PATH_ROWS(outer_path);
809         double          inner_path_rows = PATH_ROWS(inner_path);
810         double          outer_rows,
811                                 inner_rows;
812         double          mergejointuples,
813                                 rescannedtuples;
814         double          qptuples;
815         double          rescanratio;
816         Selectivity outerscansel,
817                                 innerscansel;
818         Selectivity     joininfactor;
819         Path            sort_path;              /* dummy for result of cost_sort */
820
821         if (!enable_mergejoin)
822                 startup_cost += disable_cost;
823
824         /*
825          * Compute cost and selectivity of the mergequals and qpquals (other
826          * restriction clauses) separately.  We use approx_selectivity here
827          * for speed --- in most cases, any errors won't affect the result much.
828          *
829          * Note: it's probably bogus to use the normal selectivity calculation
830          * here when either the outer or inner path is a UniquePath.
831          */
832         merge_selec = approx_selectivity(root, mergeclauses,
833                                                                          path->jpath.jointype);
834         cost_qual_eval(&merge_qual_cost, mergeclauses);
835         qpquals = set_ptrDifference(restrictlist, mergeclauses);
836         qp_selec = approx_selectivity(root, qpquals,
837                                                                   path->jpath.jointype);
838         cost_qual_eval(&qp_qual_cost, qpquals);
839         freeList(qpquals);
840
841         /* approx # tuples passing the merge quals */
842         mergejointuples = ceil(merge_selec * outer_path_rows * inner_path_rows);
843         /* approx # tuples passing qpquals as well */
844         qptuples = ceil(mergejointuples * qp_selec);
845
846         /*
847          * When there are equal merge keys in the outer relation, the mergejoin
848          * must rescan any matching tuples in the inner relation.  This means
849          * re-fetching inner tuples.  Our cost model for this is that a re-fetch
850          * costs the same as an original fetch, which is probably an overestimate;
851          * but on the other hand we ignore the bookkeeping costs of mark/restore.
852          * Not clear if it's worth developing a more refined model.
853          *
854          * The number of re-fetches can be estimated approximately as size of
855          * merge join output minus size of inner relation.  Assume that the
856          * distinct key values are 1, 2, ..., and denote the number of values of
857          * each key in the outer relation as m1, m2, ...; in the inner relation,
858          * n1, n2, ...  Then we have
859          *
860          *      size of join = m1 * n1 + m2 * n2 + ...
861          *
862          *      number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ...
863          *              = m1 * n1 + m2 * n2 + ... - (n1 + n2 + ...)
864          *              = size of join - size of inner relation
865          *
866          * This equation works correctly for outer tuples having no inner match
867          * (nk = 0), but not for inner tuples having no outer match (mk = 0);
868          * we are effectively subtracting those from the number of rescanned
869          * tuples, when we should not.  Can we do better without expensive
870          * selectivity computations?
871          */
872         if (IsA(outer_path, UniquePath))
873                 rescannedtuples = 0;
874         else
875         {
876                 rescannedtuples = mergejointuples - inner_path_rows;
877                 /* Must clamp because of possible underestimate */
878                 if (rescannedtuples < 0)
879                         rescannedtuples = 0;
880         }
881         /* We'll inflate inner run cost this much to account for rescanning */
882         rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
883
884         /*
885          * A merge join will stop as soon as it exhausts either input stream.
886          * Estimate fraction of the left and right inputs that will actually
887          * need to be scanned.  We use only the first (most significant) merge
888          * clause for this purpose.
889          *
890          * Since this calculation is somewhat expensive, and will be the same for
891          * all mergejoin paths associated with the merge clause, we cache the
892          * results in the RestrictInfo node.
893          */
894         firstclause = (RestrictInfo *) lfirst(mergeclauses);
895         if (firstclause->left_mergescansel < 0)         /* not computed yet? */
896                 mergejoinscansel(root, (Node *) firstclause->clause,
897                                                  &firstclause->left_mergescansel,
898                                                  &firstclause->right_mergescansel);
899
900         if (bms_is_subset(firstclause->left_relids, outer_path->parent->relids))
901         {
902                 /* left side of clause is outer */
903                 outerscansel = firstclause->left_mergescansel;
904                 innerscansel = firstclause->right_mergescansel;
905         }
906         else
907         {
908                 /* left side of clause is inner */
909                 outerscansel = firstclause->right_mergescansel;
910                 innerscansel = firstclause->left_mergescansel;
911         }
912
913         /* convert selectivity to row count; must scan at least one row */
914
915         outer_rows = ceil(outer_path_rows * outerscansel);
916         if (outer_rows < 1)
917                 outer_rows = 1;
918         inner_rows = ceil(inner_path_rows * innerscansel);
919         if (inner_rows < 1)
920                 inner_rows = 1;
921
922         /*
923          * Readjust scan selectivities to account for above rounding.  This is
924          * normally an insignificant effect, but when there are only a few rows
925          * in the inputs, failing to do this makes for a large percentage error.
926          */
927         outerscansel = outer_rows / outer_path_rows;
928         innerscansel = inner_rows / inner_path_rows;
929
930         /* cost of source data */
931
932         if (outersortkeys)                      /* do we need to sort outer? */
933         {
934                 cost_sort(&sort_path,
935                                   root,
936                                   outersortkeys,
937                                   outer_path->total_cost,
938                                   outer_path_rows,
939                                   outer_path->parent->width);
940                 startup_cost += sort_path.startup_cost;
941                 run_cost += (sort_path.total_cost - sort_path.startup_cost)
942                         * outerscansel;
943         }
944         else
945         {
946                 startup_cost += outer_path->startup_cost;
947                 run_cost += (outer_path->total_cost - outer_path->startup_cost)
948                         * outerscansel;
949         }
950
951         if (innersortkeys)                      /* do we need to sort inner? */
952         {
953                 cost_sort(&sort_path,
954                                   root,
955                                   innersortkeys,
956                                   inner_path->total_cost,
957                                   inner_path_rows,
958                                   inner_path->parent->width);
959                 startup_cost += sort_path.startup_cost;
960                 run_cost += (sort_path.total_cost - sort_path.startup_cost)
961                         * innerscansel * rescanratio;
962         }
963         else
964         {
965                 startup_cost += inner_path->startup_cost;
966                 run_cost += (inner_path->total_cost - inner_path->startup_cost)
967                         * innerscansel * rescanratio;
968         }
969
970         /* CPU costs */
971
972         /*
973          * If we're doing JOIN_IN then we will stop outputting inner
974          * tuples for an outer tuple as soon as we have one match.  Account for
975          * the effects of this by scaling down the cost estimates in proportion
976          * to the expected output size.  (This assumes that all the quals attached
977          * to the join are IN quals, which should be true.)
978          */
979         if (path->jpath.jointype == JOIN_IN &&
980                 qptuples > path->jpath.path.parent->rows)
981                 joininfactor = path->jpath.path.parent->rows / qptuples;
982         else
983                 joininfactor = 1.0;
984
985         /*
986          * The number of tuple comparisons needed is approximately number of
987          * outer rows plus number of inner rows plus number of rescanned
988          * tuples (can we refine this?).  At each one, we need to evaluate
989          * the mergejoin quals.  NOTE: JOIN_IN mode does not save any work
990          * here, so do NOT include joininfactor.
991          */
992         startup_cost += merge_qual_cost.startup;
993         run_cost += merge_qual_cost.per_tuple *
994                 (outer_rows + inner_rows * rescanratio);
995
996         /*
997          * For each tuple that gets through the mergejoin proper, we charge
998          * cpu_tuple_cost plus the cost of evaluating additional restriction
999          * clauses that are to be applied at the join.  (This is pessimistic
1000          * since not all of the quals may get evaluated at each tuple.)  This
1001          * work is skipped in JOIN_IN mode, so apply the factor.
1002          */
1003         startup_cost += qp_qual_cost.startup;
1004         cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
1005         run_cost += cpu_per_tuple * mergejointuples * joininfactor;
1006
1007         path->jpath.path.startup_cost = startup_cost;
1008         path->jpath.path.total_cost = startup_cost + run_cost;
1009 }
1010
1011 /*
1012  * cost_hashjoin
1013  *        Determines and returns the cost of joining two relations using the
1014  *        hash join algorithm.
1015  *
1016  * 'path' is already filled in except for the cost fields
1017  *
1018  * Note: path's hashclauses should be a subset of the joinrestrictinfo list
1019  */
1020 void
1021 cost_hashjoin(HashPath *path, Query *root)
1022 {
1023         Path       *outer_path = path->jpath.outerjoinpath;
1024         Path       *inner_path = path->jpath.innerjoinpath;
1025         List       *restrictlist = path->jpath.joinrestrictinfo;
1026         List       *hashclauses = path->path_hashclauses;
1027         Cost            startup_cost = 0;
1028         Cost            run_cost = 0;
1029         Cost            cpu_per_tuple;
1030         Selectivity     hash_selec;
1031         Selectivity     qp_selec;
1032         QualCost        hash_qual_cost;
1033         QualCost        qp_qual_cost;
1034         double          hashjointuples;
1035         double          qptuples;
1036         double          outer_path_rows = PATH_ROWS(outer_path);
1037         double          inner_path_rows = PATH_ROWS(inner_path);
1038         double          outerbytes = relation_byte_size(outer_path_rows,
1039                                                                                           outer_path->parent->width);
1040         double          innerbytes = relation_byte_size(inner_path_rows,
1041                                                                                           inner_path->parent->width);
1042         int                     num_hashclauses = length(hashclauses);
1043         int                     virtualbuckets;
1044         int                     physicalbuckets;
1045         int                     numbatches;
1046         Selectivity innerbucketsize;
1047         Selectivity     joininfactor;
1048         List       *hcl;
1049         List       *qpquals;
1050
1051         if (!enable_hashjoin)
1052                 startup_cost += disable_cost;
1053
1054         /*
1055          * Compute cost and selectivity of the hashquals and qpquals (other
1056          * restriction clauses) separately.  We use approx_selectivity here
1057          * for speed --- in most cases, any errors won't affect the result much.
1058          *
1059          * Note: it's probably bogus to use the normal selectivity calculation
1060          * here when either the outer or inner path is a UniquePath.
1061          */
1062         hash_selec = approx_selectivity(root, hashclauses,
1063                                                                         path->jpath.jointype);
1064         cost_qual_eval(&hash_qual_cost, hashclauses);
1065         qpquals = set_ptrDifference(restrictlist, hashclauses);
1066         qp_selec = approx_selectivity(root, qpquals,
1067                                                                   path->jpath.jointype);
1068         cost_qual_eval(&qp_qual_cost, qpquals);
1069         freeList(qpquals);
1070
1071         /* approx # tuples passing the hash quals */
1072         hashjointuples = ceil(hash_selec * outer_path_rows * inner_path_rows);
1073         /* approx # tuples passing qpquals as well */
1074         qptuples = ceil(hashjointuples * qp_selec);
1075
1076         /* cost of source data */
1077         startup_cost += outer_path->startup_cost;
1078         run_cost += outer_path->total_cost - outer_path->startup_cost;
1079         startup_cost += inner_path->total_cost;
1080
1081         /*
1082          * Cost of computing hash function: must do it once per input tuple.
1083          * We charge one cpu_operator_cost for each column's hash function.
1084          *
1085          * XXX when a hashclause is more complex than a single operator,
1086          * we really should charge the extra eval costs of the left or right
1087          * side, as appropriate, here.  This seems more work than it's worth
1088          * at the moment.
1089          */
1090         startup_cost += cpu_operator_cost * num_hashclauses * inner_path_rows;
1091         run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
1092
1093         /* Get hash table size that executor would use for inner relation */
1094         ExecChooseHashTableSize(inner_path_rows,
1095                                                         inner_path->parent->width,
1096                                                         &virtualbuckets,
1097                                                         &physicalbuckets,
1098                                                         &numbatches);
1099
1100         /*
1101          * Determine bucketsize fraction for inner relation.  We use the
1102          * smallest bucketsize estimated for any individual hashclause;
1103          * this is undoubtedly conservative.
1104          *
1105          * BUT: if inner relation has been unique-ified, we can assume it's
1106          * good for hashing.  This is important both because it's the right
1107          * answer, and because we avoid contaminating the cache with a value
1108          * that's wrong for non-unique-ified paths.
1109          */
1110         if (IsA(inner_path, UniquePath))
1111                 innerbucketsize = 1.0 / virtualbuckets;
1112         else
1113         {
1114                 innerbucketsize = 1.0;
1115                 foreach(hcl, hashclauses)
1116                 {
1117                         RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
1118                         Selectivity thisbucketsize;
1119
1120                         Assert(IsA(restrictinfo, RestrictInfo));
1121
1122                         /*
1123                          * First we have to figure out which side of the hashjoin clause
1124                          * is the inner side.
1125                          *
1126                          * Since we tend to visit the same clauses over and over when
1127                          * planning a large query, we cache the bucketsize estimate in the
1128                          * RestrictInfo node to avoid repeated lookups of statistics.
1129                          */
1130                         if (bms_is_subset(restrictinfo->right_relids,
1131                                                           inner_path->parent->relids))
1132                         {
1133                                 /* righthand side is inner */
1134                                 thisbucketsize = restrictinfo->right_bucketsize;
1135                                 if (thisbucketsize < 0)
1136                                 {
1137                                         /* not cached yet */
1138                                         thisbucketsize =
1139                                                 estimate_hash_bucketsize(root,
1140                                                                         (Var *) get_rightop(restrictinfo->clause),
1141                                                                                                  virtualbuckets);
1142                                         restrictinfo->right_bucketsize = thisbucketsize;
1143                                 }
1144                         }
1145                         else
1146                         {
1147                                 Assert(bms_is_subset(restrictinfo->left_relids,
1148                                                                          inner_path->parent->relids));
1149                                 /* lefthand side is inner */
1150                                 thisbucketsize = restrictinfo->left_bucketsize;
1151                                 if (thisbucketsize < 0)
1152                                 {
1153                                         /* not cached yet */
1154                                         thisbucketsize =
1155                                                 estimate_hash_bucketsize(root,
1156                                                                         (Var *) get_leftop(restrictinfo->clause),
1157                                                                                                  virtualbuckets);
1158                                         restrictinfo->left_bucketsize = thisbucketsize;
1159                                 }
1160                         }
1161
1162                         if (innerbucketsize > thisbucketsize)
1163                                 innerbucketsize = thisbucketsize;
1164                 }
1165         }
1166
1167         /*
1168          * if inner relation is too big then we will need to "batch" the join,
1169          * which implies writing and reading most of the tuples to disk an
1170          * extra time.  Charge one cost unit per page of I/O (correct since it
1171          * should be nice and sequential...).  Writing the inner rel counts as
1172          * startup cost, all the rest as run cost.
1173          */
1174         if (numbatches)
1175         {
1176                 double          outerpages = page_size(outer_path_rows,
1177                                                                                    outer_path->parent->width);
1178                 double          innerpages = page_size(inner_path_rows,
1179                                                                                    inner_path->parent->width);
1180
1181                 startup_cost += innerpages;
1182                 run_cost += innerpages + 2 * outerpages;
1183         }
1184
1185         /* CPU costs */
1186
1187         /*
1188          * If we're doing JOIN_IN then we will stop comparing inner
1189          * tuples to an outer tuple as soon as we have one match.  Account for
1190          * the effects of this by scaling down the cost estimates in proportion
1191          * to the expected output size.  (This assumes that all the quals attached
1192          * to the join are IN quals, which should be true.)
1193          */
1194         if (path->jpath.jointype == JOIN_IN &&
1195                 qptuples > path->jpath.path.parent->rows)
1196                 joininfactor = path->jpath.path.parent->rows / qptuples;
1197         else
1198                 joininfactor = 1.0;
1199
1200         /*
1201          * The number of tuple comparisons needed is the number of outer
1202          * tuples times the typical number of tuples in a hash bucket, which
1203          * is the inner relation size times its bucketsize fraction.  At each
1204          * one, we need to evaluate the hashjoin quals.
1205          */
1206         startup_cost += hash_qual_cost.startup;
1207         run_cost += hash_qual_cost.per_tuple *
1208                 outer_path_rows * ceil(inner_path_rows * innerbucketsize) *
1209                 joininfactor;
1210
1211         /*
1212          * For each tuple that gets through the hashjoin proper, we charge
1213          * cpu_tuple_cost plus the cost of evaluating additional restriction
1214          * clauses that are to be applied at the join.  (This is pessimistic
1215          * since not all of the quals may get evaluated at each tuple.)
1216          */
1217         startup_cost += qp_qual_cost.startup;
1218         cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
1219         run_cost += cpu_per_tuple * hashjointuples * joininfactor;
1220
1221         /*
1222          * Bias against putting larger relation on inside.      We don't want an
1223          * absolute prohibition, though, since larger relation might have
1224          * better bucketsize --- and we can't trust the size estimates
1225          * unreservedly, anyway.  Instead, inflate the run cost by the
1226          * square root of the size ratio.  (Why square root?  No real good
1227          * reason, but it seems reasonable...)
1228          *
1229          * Note: before 7.4 we implemented this by inflating startup cost;
1230          * but if there's a disable_cost component in the input paths'
1231          * startup cost, that unfairly penalizes the hash.  Probably it'd
1232          * be better to keep track of disable penalty separately from cost.
1233          */
1234         if (innerbytes > outerbytes && outerbytes > 0)
1235                 run_cost *= sqrt(innerbytes / outerbytes);
1236
1237         path->jpath.path.startup_cost = startup_cost;
1238         path->jpath.path.total_cost = startup_cost + run_cost;
1239 }
1240
1241 /*
1242  * Estimate hash bucketsize fraction (ie, number of entries in a bucket
1243  * divided by total tuples in relation) if the specified Var is used
1244  * as a hash key.
1245  *
1246  * XXX This is really pretty bogus since we're effectively assuming that the
1247  * distribution of hash keys will be the same after applying restriction
1248  * clauses as it was in the underlying relation.  However, we are not nearly
1249  * smart enough to figure out how the restrict clauses might change the
1250  * distribution, so this will have to do for now.
1251  *
1252  * We are passed the number of buckets the executor will use for the given
1253  * input relation.      If the data were perfectly distributed, with the same
1254  * number of tuples going into each available bucket, then the bucketsize
1255  * fraction would be 1/nbuckets.  But this happy state of affairs will occur
1256  * only if (a) there are at least nbuckets distinct data values, and (b)
1257  * we have a not-too-skewed data distribution.  Otherwise the buckets will
1258  * be nonuniformly occupied.  If the other relation in the join has a key
1259  * distribution similar to this one's, then the most-loaded buckets are
1260  * exactly those that will be probed most often.  Therefore, the "average"
1261  * bucket size for costing purposes should really be taken as something close
1262  * to the "worst case" bucket size.  We try to estimate this by adjusting the
1263  * fraction if there are too few distinct data values, and then scaling up
1264  * by the ratio of the most common value's frequency to the average frequency.
1265  *
1266  * If no statistics are available, use a default estimate of 0.1.  This will
1267  * discourage use of a hash rather strongly if the inner relation is large,
1268  * which is what we want.  We do not want to hash unless we know that the
1269  * inner rel is well-dispersed (or the alternatives seem much worse).
1270  */
1271 static Selectivity
1272 estimate_hash_bucketsize(Query *root, Var *var, int nbuckets)
1273 {
1274         Oid                     relid;
1275         RelOptInfo *rel;
1276         HeapTuple       tuple;
1277         Form_pg_statistic stats;
1278         double          estfract,
1279                                 ndistinct,
1280                                 mcvfreq,
1281                                 avgfreq;
1282         float4     *numbers;
1283         int                     nnumbers;
1284
1285         /*
1286          * Lookup info about var's relation and attribute; if none available,
1287          * return default estimate.
1288          */
1289         if (var == NULL || !IsA(var, Var))
1290                 return 0.1;
1291
1292         relid = getrelid(var->varno, root->rtable);
1293         if (relid == InvalidOid)
1294                 return 0.1;
1295
1296         rel = find_base_rel(root, var->varno);
1297
1298         if (rel->tuples <= 0.0 || rel->rows <= 0.0)
1299                 return 0.1;                             /* ensure we can divide below */
1300
1301         tuple = SearchSysCache(STATRELATT,
1302                                                    ObjectIdGetDatum(relid),
1303                                                    Int16GetDatum(var->varattno),
1304                                                    0, 0);
1305         if (!HeapTupleIsValid(tuple))
1306         {
1307                 /*
1308                  * Perhaps the Var is a system attribute; if so, it will have no
1309                  * entry in pg_statistic, but we may be able to guess something
1310                  * about its distribution anyway.
1311                  */
1312                 switch (var->varattno)
1313                 {
1314                         case ObjectIdAttributeNumber:
1315                         case SelfItemPointerAttributeNumber:
1316                                 /* these are unique, so buckets should be well-distributed */
1317                                 return 1.0 / (double) nbuckets;
1318                         case TableOidAttributeNumber:
1319                                 /* hashing this is a terrible idea... */
1320                                 return 1.0;
1321                 }
1322                 return 0.1;
1323         }
1324         stats = (Form_pg_statistic) GETSTRUCT(tuple);
1325
1326         /*
1327          * Obtain number of distinct data values in raw relation.
1328          */
1329         ndistinct = stats->stadistinct;
1330         if (ndistinct < 0.0)
1331                 ndistinct = -ndistinct * rel->tuples;
1332
1333         if (ndistinct <= 0.0)           /* ensure we can divide */
1334         {
1335                 ReleaseSysCache(tuple);
1336                 return 0.1;
1337         }
1338
1339         /* Also compute avg freq of all distinct data values in raw relation */
1340         avgfreq = (1.0 - stats->stanullfrac) / ndistinct;
1341
1342         /*
1343          * Adjust ndistinct to account for restriction clauses.  Observe we
1344          * are assuming that the data distribution is affected uniformly by
1345          * the restriction clauses!
1346          *
1347          * XXX Possibly better way, but much more expensive: multiply by
1348          * selectivity of rel's restriction clauses that mention the target
1349          * Var.
1350          */
1351         ndistinct *= rel->rows / rel->tuples;
1352
1353         /*
1354          * Initial estimate of bucketsize fraction is 1/nbuckets as long as
1355          * the number of buckets is less than the expected number of distinct
1356          * values; otherwise it is 1/ndistinct.
1357          */
1358         if (ndistinct > (double) nbuckets)
1359                 estfract = 1.0 / (double) nbuckets;
1360         else
1361                 estfract = 1.0 / ndistinct;
1362
1363         /*
1364          * Look up the frequency of the most common value, if available.
1365          */
1366         mcvfreq = 0.0;
1367
1368         if (get_attstatsslot(tuple, var->vartype, var->vartypmod,
1369                                                  STATISTIC_KIND_MCV, InvalidOid,
1370                                                  NULL, NULL, &numbers, &nnumbers))
1371         {
1372                 /*
1373                  * The first MCV stat is for the most common value.
1374                  */
1375                 if (nnumbers > 0)
1376                         mcvfreq = numbers[0];
1377                 free_attstatsslot(var->vartype, NULL, 0,
1378                                                   numbers, nnumbers);
1379         }
1380
1381         /*
1382          * Adjust estimated bucketsize upward to account for skewed
1383          * distribution.
1384          */
1385         if (avgfreq > 0.0 && mcvfreq > avgfreq)
1386                 estfract *= mcvfreq / avgfreq;
1387
1388         /*
1389          * Clamp bucketsize to sane range (the above adjustment could easily
1390          * produce an out-of-range result).  We set the lower bound a little
1391          * above zero, since zero isn't a very sane result.
1392          */
1393         if (estfract < 1.0e-6)
1394                 estfract = 1.0e-6;
1395         else if (estfract > 1.0)
1396                 estfract = 1.0;
1397
1398         ReleaseSysCache(tuple);
1399
1400         return (Selectivity) estfract;
1401 }
1402
1403
1404 /*
1405  * cost_qual_eval
1406  *              Estimate the CPU costs of evaluating a WHERE clause.
1407  *              The input can be either an implicitly-ANDed list of boolean
1408  *              expressions, or a list of RestrictInfo nodes.
1409  *              The result includes both a one-time (startup) component,
1410  *              and a per-evaluation component.
1411  */
1412 void
1413 cost_qual_eval(QualCost *cost, List *quals)
1414 {
1415         List       *l;
1416
1417         cost->startup = 0;
1418         cost->per_tuple = 0;
1419
1420         /* We don't charge any cost for the implicit ANDing at top level ... */
1421
1422         foreach(l, quals)
1423         {
1424                 Node       *qual = (Node *) lfirst(l);
1425
1426                 /*
1427                  * RestrictInfo nodes contain an eval_cost field reserved for this
1428                  * routine's use, so that it's not necessary to evaluate the qual
1429                  * clause's cost more than once.  If the clause's cost hasn't been
1430                  * computed yet, the field's startup value will contain -1.
1431                  */
1432                 if (qual && IsA(qual, RestrictInfo))
1433                 {
1434                         RestrictInfo *restrictinfo = (RestrictInfo *) qual;
1435
1436                         if (restrictinfo->eval_cost.startup < 0)
1437                         {
1438                                 restrictinfo->eval_cost.startup = 0;
1439                                 restrictinfo->eval_cost.per_tuple = 0;
1440                                 cost_qual_eval_walker((Node *) restrictinfo->clause,
1441                                                                           &restrictinfo->eval_cost);
1442                         }
1443                         cost->startup += restrictinfo->eval_cost.startup;
1444                         cost->per_tuple += restrictinfo->eval_cost.per_tuple;
1445                 }
1446                 else
1447                 {
1448                         /* If it's a bare expression, must always do it the hard way */
1449                         cost_qual_eval_walker(qual, cost);
1450                 }
1451         }
1452 }
1453
1454 static bool
1455 cost_qual_eval_walker(Node *node, QualCost *total)
1456 {
1457         if (node == NULL)
1458                 return false;
1459
1460         /*
1461          * Our basic strategy is to charge one cpu_operator_cost for each
1462          * operator or function node in the given tree.  Vars and Consts are
1463          * charged zero, and so are boolean operators (AND, OR, NOT).
1464          * Simplistic, but a lot better than no model at all.
1465          *
1466          * Should we try to account for the possibility of short-circuit
1467          * evaluation of AND/OR?
1468          */
1469         if (IsA(node, FuncExpr) ||
1470                 IsA(node, OpExpr) ||
1471                 IsA(node, DistinctExpr) ||
1472                 IsA(node, NullIfExpr))
1473         {
1474                 total->per_tuple += cpu_operator_cost;
1475         }
1476         else if (IsA(node, ScalarArrayOpExpr))
1477         {
1478                 /* should charge more than 1 op cost, but how many? */
1479                 total->per_tuple += cpu_operator_cost * 10;
1480         }
1481         else if (IsA(node, SubLink))
1482         {
1483                 /* This routine should not be applied to un-planned expressions */
1484                 elog(ERROR, "cost_qual_eval: can't handle unplanned sub-select");
1485         }
1486         else if (IsA(node, SubPlan))
1487         {
1488                 /*
1489                  * A subplan node in an expression typically indicates that the
1490                  * subplan will be executed on each evaluation, so charge accordingly.
1491                  * (Sub-selects that can be executed as InitPlans have already been
1492                  * removed from the expression.)
1493                  *
1494                  * An exception occurs when we have decided we can implement the
1495                  * subplan by hashing.
1496                  *
1497                  */
1498                 SubPlan    *subplan = (SubPlan *) node;
1499                 Plan       *plan = subplan->plan;
1500
1501                 if (subplan->useHashTable)
1502                 {
1503                         /*
1504                          * If we are using a hash table for the subquery outputs, then
1505                          * the cost of evaluating the query is a one-time cost.
1506                          * We charge one cpu_operator_cost per tuple for the work of
1507                          * loading the hashtable, too.
1508                          */
1509                         total->startup += plan->total_cost +
1510                                 cpu_operator_cost * plan->plan_rows;
1511                         /*
1512                          * The per-tuple costs include the cost of evaluating the
1513                          * lefthand expressions, plus the cost of probing the hashtable.
1514                          * Recursion into the exprs list will handle the lefthand
1515                          * expressions properly, and will count one cpu_operator_cost
1516                          * for each comparison operator.  That is probably too low for
1517                          * the probing cost, but it's hard to make a better estimate,
1518                          * so live with it for now.
1519                          */
1520                 }
1521                 else
1522                 {
1523                         /*
1524                          * Otherwise we will be rescanning the subplan output on each
1525                          * evaluation.  We need to estimate how much of the output
1526                          * we will actually need to scan.  NOTE: this logic should
1527                          * agree with the estimates used by make_subplan() in
1528                          * plan/subselect.c.
1529                          */
1530                         Cost    plan_run_cost = plan->total_cost - plan->startup_cost;
1531
1532                         if (subplan->subLinkType == EXISTS_SUBLINK)
1533                         {
1534                                 /* we only need to fetch 1 tuple */
1535                                 total->per_tuple += plan_run_cost / plan->plan_rows;
1536                         }
1537                         else if (subplan->subLinkType == ALL_SUBLINK ||
1538                                          subplan->subLinkType == ANY_SUBLINK)
1539                         {
1540                                 /* assume we need 50% of the tuples */
1541                                 total->per_tuple += 0.50 * plan_run_cost;
1542                                 /* also charge a cpu_operator_cost per row examined */
1543                                 total->per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
1544                         }
1545                         else
1546                         {
1547                                 /* assume we need all tuples */
1548                                 total->per_tuple += plan_run_cost;
1549                         }
1550                         /*
1551                          * Also account for subplan's startup cost.
1552                          * If the subplan is uncorrelated or undirect correlated,
1553                          * AND its topmost node is a Sort or Material node, assume
1554                          * that we'll only need to pay its startup cost once;
1555                          * otherwise assume we pay the startup cost every time.
1556                          */
1557                         if (subplan->parParam == NIL &&
1558                                 (IsA(plan, Sort) ||
1559                                  IsA(plan, Material)))
1560                         {
1561                                 total->startup += plan->startup_cost;
1562                         }
1563                         else
1564                         {
1565                                 total->per_tuple += plan->startup_cost;
1566                         }
1567                 }
1568         }
1569
1570         return expression_tree_walker(node, cost_qual_eval_walker,
1571                                                                   (void *) total);
1572 }
1573
1574
1575 /*
1576  * approx_selectivity
1577  *              Quick-and-dirty estimation of clause selectivities.
1578  *              The input can be either an implicitly-ANDed list of boolean
1579  *              expressions, or a list of RestrictInfo nodes (typically the latter).
1580  *
1581  * The "quick" part comes from caching the selectivity estimates so we can
1582  * avoid recomputing them later.  (Since the same clauses are typically
1583  * examined over and over in different possible join trees, this makes a
1584  * big difference.)
1585  *
1586  * The "dirty" part comes from the fact that the selectivities of multiple
1587  * clauses are estimated independently and multiplied together.  Now
1588  * clauselist_selectivity often can't do any better than that anyhow, but
1589  * for some situations (such as range constraints) it is smarter.
1590  *
1591  * Since we are only using the results to estimate how many potential
1592  * output tuples are generated and passed through qpqual checking, it
1593  * seems OK to live with the approximation.
1594  */
1595 static Selectivity
1596 approx_selectivity(Query *root, List *quals, JoinType jointype)
1597 {
1598         Selectivity total = 1.0;
1599         List       *l;
1600
1601         foreach(l, quals)
1602         {
1603                 Node       *qual = (Node *) lfirst(l);
1604                 Selectivity selec;
1605
1606                 /*
1607                  * RestrictInfo nodes contain a this_selec field reserved for this
1608                  * routine's use, so that it's not necessary to evaluate the qual
1609                  * clause's selectivity more than once.  If the clause's
1610                  * selectivity hasn't been computed yet, the field will contain
1611                  * -1.
1612                  */
1613                 if (qual && IsA(qual, RestrictInfo))
1614                 {
1615                         RestrictInfo *restrictinfo = (RestrictInfo *) qual;
1616
1617                         if (restrictinfo->this_selec < 0)
1618                                 restrictinfo->this_selec =
1619                                         clause_selectivity(root,
1620                                                                            (Node *) restrictinfo->clause,
1621                                                                            0,
1622                                                                            jointype);
1623                         selec = restrictinfo->this_selec;
1624                 }
1625                 else
1626                 {
1627                         /* If it's a bare expression, must always do it the hard way */
1628                         selec = clause_selectivity(root, qual, 0, jointype);
1629                 }
1630                 total *= selec;
1631         }
1632         return total;
1633 }
1634
1635
1636 /*
1637  * set_baserel_size_estimates
1638  *              Set the size estimates for the given base relation.
1639  *
1640  * The rel's targetlist and restrictinfo list must have been constructed
1641  * already.
1642  *
1643  * We set the following fields of the rel node:
1644  *      rows: the estimated number of output tuples (after applying
1645  *                restriction clauses).
1646  *      width: the estimated average output tuple width in bytes.
1647  *      baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
1648  */
1649 void
1650 set_baserel_size_estimates(Query *root, RelOptInfo *rel)
1651 {
1652         double          temp;
1653
1654         /* Should only be applied to base relations */
1655         Assert(rel->relid > 0);
1656
1657         temp = rel->tuples *
1658                 restrictlist_selectivity(root,
1659                                                                  rel->baserestrictinfo,
1660                                                                  rel->relid,
1661                                                                  JOIN_INNER);
1662
1663         /*
1664          * Force estimate to be at least one row, to make explain output look
1665          * better and to avoid possible divide-by-zero when interpolating
1666          * cost.  Make it an integer, too.
1667          */
1668         if (temp < 1.0)
1669                 temp = 1.0;
1670         else
1671                 temp = ceil(temp);
1672
1673         rel->rows = temp;
1674
1675         cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo);
1676
1677         set_rel_width(root, rel);
1678 }
1679
1680 /*
1681  * set_joinrel_size_estimates
1682  *              Set the size estimates for the given join relation.
1683  *
1684  * The rel's targetlist must have been constructed already, and a
1685  * restriction clause list that matches the given component rels must
1686  * be provided.
1687  *
1688  * Since there is more than one way to make a joinrel for more than two
1689  * base relations, the results we get here could depend on which component
1690  * rel pair is provided.  In theory we should get the same answers no matter
1691  * which pair is provided; in practice, since the selectivity estimation
1692  * routines don't handle all cases equally well, we might not.  But there's
1693  * not much to be done about it.  (Would it make sense to repeat the
1694  * calculations for each pair of input rels that's encountered, and somehow
1695  * average the results?  Probably way more trouble than it's worth.)
1696  *
1697  * It's important that the results for symmetric JoinTypes be symmetric,
1698  * eg, (rel1, rel2, JOIN_LEFT) should produce the same result as (rel2,
1699  * rel1, JOIN_RIGHT).  Also, JOIN_IN should produce the same result as
1700  * JOIN_UNIQUE_INNER, likewise JOIN_REVERSE_IN == JOIN_UNIQUE_OUTER.
1701  *
1702  * We set the same relnode fields as set_baserel_size_estimates() does.
1703  */
1704 void
1705 set_joinrel_size_estimates(Query *root, RelOptInfo *rel,
1706                                                    RelOptInfo *outer_rel,
1707                                                    RelOptInfo *inner_rel,
1708                                                    JoinType jointype,
1709                                                    List *restrictlist)
1710 {
1711         Selectivity selec;
1712         double          temp;
1713         UniquePath *upath;
1714
1715         /*
1716          * Compute joinclause selectivity.  Note that we are only considering
1717          * clauses that become restriction clauses at this join level; we are
1718          * not double-counting them because they were not considered in
1719          * estimating the sizes of the component rels.
1720          */
1721         selec = restrictlist_selectivity(root,
1722                                                                          restrictlist,
1723                                                                          0,
1724                                                                          jointype);
1725
1726         /*
1727          * Basically, we multiply size of Cartesian product by selectivity.
1728          *
1729          * If we are doing an outer join, take that into account: the output
1730          * must be at least as large as the non-nullable input.  (Is there any
1731          * chance of being even smarter?)
1732          *
1733          * For JOIN_IN and variants, the Cartesian product is figured with
1734          * respect to a unique-ified input, and then we can clamp to the size
1735          * of the other input.
1736          */
1737         switch (jointype)
1738         {
1739                 case JOIN_INNER:
1740                         temp = outer_rel->rows * inner_rel->rows * selec;
1741                         break;
1742                 case JOIN_LEFT:
1743                         temp = outer_rel->rows * inner_rel->rows * selec;
1744                         if (temp < outer_rel->rows)
1745                                 temp = outer_rel->rows;
1746                         break;
1747                 case JOIN_RIGHT:
1748                         temp = outer_rel->rows * inner_rel->rows * selec;
1749                         if (temp < inner_rel->rows)
1750                                 temp = inner_rel->rows;
1751                         break;
1752                 case JOIN_FULL:
1753                         temp = outer_rel->rows * inner_rel->rows * selec;
1754                         if (temp < outer_rel->rows)
1755                                 temp = outer_rel->rows;
1756                         if (temp < inner_rel->rows)
1757                                 temp = inner_rel->rows;
1758                         break;
1759                 case JOIN_IN:
1760                 case JOIN_UNIQUE_INNER:
1761                         upath = create_unique_path(root, inner_rel,
1762                                                                            inner_rel->cheapest_total_path);
1763                         temp = outer_rel->rows * upath->rows * selec;
1764                         if (temp > outer_rel->rows)
1765                                 temp = outer_rel->rows;
1766                         break;
1767                 case JOIN_REVERSE_IN:
1768                 case JOIN_UNIQUE_OUTER:
1769                         upath = create_unique_path(root, outer_rel,
1770                                                                            outer_rel->cheapest_total_path);
1771                         temp = upath->rows * inner_rel->rows * selec;
1772                         if (temp > inner_rel->rows)
1773                                 temp = inner_rel->rows;
1774                         break;
1775                 default:
1776                         elog(ERROR, "set_joinrel_size_estimates: unsupported join type %d",
1777                                  (int) jointype);
1778                         temp = 0;                       /* keep compiler quiet */
1779                         break;
1780         }
1781
1782         /*
1783          * Force estimate to be at least one row, to make explain output look
1784          * better and to avoid possible divide-by-zero when interpolating
1785          * cost.  Make it an integer, too.
1786          */
1787         if (temp < 1.0)
1788                 temp = 1.0;
1789         else
1790                 temp = ceil(temp);
1791
1792         rel->rows = temp;
1793
1794         /*
1795          * We could apply set_rel_width() to compute the output tuple width
1796          * from scratch, but at present it's always just the sum of the input
1797          * widths, so why work harder than necessary?  If relnode.c is ever
1798          * taught to remove unneeded columns from join targetlists, go back to
1799          * using set_rel_width here.
1800          */
1801         rel->width = outer_rel->width + inner_rel->width;
1802 }
1803
1804 /*
1805  * set_function_size_estimates
1806  *              Set the size estimates for a base relation that is a function call.
1807  *
1808  * The rel's targetlist and restrictinfo list must have been constructed
1809  * already.
1810  *
1811  * We set the following fields of the rel node:
1812  *      rows: the estimated number of output tuples (after applying
1813  *                restriction clauses).
1814  *      width: the estimated average output tuple width in bytes.
1815  *      baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
1816  */
1817 void
1818 set_function_size_estimates(Query *root, RelOptInfo *rel)
1819 {
1820         double          temp;
1821
1822         /* Should only be applied to base relations that are functions */
1823         Assert(rel->relid > 0);
1824         Assert(rel->rtekind == RTE_FUNCTION);
1825
1826         /*
1827          * Estimate number of rows the function itself will return.
1828          *
1829          * XXX no idea how to do this yet; but should at least check whether
1830          * function returns set or not...
1831          */
1832         rel->tuples = 1000;
1833
1834         /* Now estimate number of output rows */
1835         temp = rel->tuples *
1836                 restrictlist_selectivity(root,
1837                                                                  rel->baserestrictinfo,
1838                                                                  rel->relid,
1839                                                                  JOIN_INNER);
1840
1841         /*
1842          * Force estimate to be at least one row, to make explain output look
1843          * better and to avoid possible divide-by-zero when interpolating
1844          * cost.  Make it an integer, too.
1845          */
1846         if (temp < 1.0)
1847                 temp = 1.0;
1848         else
1849                 temp = ceil(temp);
1850
1851         rel->rows = temp;
1852
1853         cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo);
1854
1855         set_rel_width(root, rel);
1856 }
1857
1858
1859 /*
1860  * set_rel_width
1861  *              Set the estimated output width of the relation.
1862  *
1863  * NB: this works best on base relations because it prefers to look at
1864  * real Vars.  It will fail to make use of pg_statistic info when applied
1865  * to a subquery relation, even if the subquery outputs are simple vars
1866  * that we could have gotten info for.  Is it worth trying to be smarter
1867  * about subqueries?
1868  */
1869 static void
1870 set_rel_width(Query *root, RelOptInfo *rel)
1871 {
1872         int32           tuple_width = 0;
1873         List       *tllist;
1874
1875         foreach(tllist, rel->targetlist)
1876         {
1877                 TargetEntry *tle = (TargetEntry *) lfirst(tllist);
1878                 int32           item_width;
1879
1880                 /*
1881                  * If it's a Var, try to get statistical info from pg_statistic.
1882                  */
1883                 if (tle->expr && IsA(tle->expr, Var))
1884                 {
1885                         Var                *var = (Var *) tle->expr;
1886                         Oid                     relid;
1887
1888                         relid = getrelid(var->varno, root->rtable);
1889                         if (relid != InvalidOid)
1890                         {
1891                                 item_width = get_attavgwidth(relid, var->varattno);
1892                                 if (item_width > 0)
1893                                 {
1894                                         tuple_width += item_width;
1895                                         continue;
1896                                 }
1897                         }
1898                 }
1899
1900                 /*
1901                  * Not a Var, or can't find statistics for it.  Estimate using
1902                  * just the type info.
1903                  */
1904                 item_width = get_typavgwidth(tle->resdom->restype,
1905                                                                          tle->resdom->restypmod);
1906                 Assert(item_width > 0);
1907                 tuple_width += item_width;
1908         }
1909         Assert(tuple_width >= 0);
1910         rel->width = tuple_width;
1911 }
1912
1913 /*
1914  * relation_byte_size
1915  *        Estimate the storage space in bytes for a given number of tuples
1916  *        of a given width (size in bytes).
1917  */
1918 static double
1919 relation_byte_size(double tuples, int width)
1920 {
1921         return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleData)));
1922 }
1923
1924 /*
1925  * page_size
1926  *        Returns an estimate of the number of pages covered by a given
1927  *        number of tuples of a given width (size in bytes).
1928  */
1929 static double
1930 page_size(double tuples, int width)
1931 {
1932         return ceil(relation_byte_size(tuples, width) / BLCKSZ);
1933 }