]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/costsize.c
Further work on making use of new statistics in planner. Adjust APIs
[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  *
41  * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
42  * Portions Copyright (c) 1994, Regents of the University of California
43  *
44  * IDENTIFICATION
45  *        $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.75 2001/06/05 05:26:04 tgl Exp $
46  *
47  *-------------------------------------------------------------------------
48  */
49
50 #include "postgres.h"
51
52 #include <math.h>
53
54 #include "catalog/pg_statistic.h"
55 #include "executor/nodeHash.h"
56 #include "miscadmin.h"
57 #include "optimizer/clauses.h"
58 #include "optimizer/cost.h"
59 #include "optimizer/pathnode.h"
60 #include "parser/parsetree.h"
61 #include "utils/lsyscache.h"
62 #include "utils/syscache.h"
63
64
65 #define LOG2(x)  (log(x) / 0.693147180559945)
66 #define LOG6(x)  (log(x) / 1.79175946922805)
67
68
69 double          effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
70 double          random_page_cost = DEFAULT_RANDOM_PAGE_COST;
71 double          cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
72 double          cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
73 double          cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
74
75 Cost            disable_cost = 100000000.0;
76
77 bool            enable_seqscan = true;
78 bool            enable_indexscan = true;
79 bool            enable_tidscan = true;
80 bool            enable_sort = true;
81 bool            enable_nestloop = true;
82 bool            enable_mergejoin = true;
83 bool            enable_hashjoin = true;
84
85
86 static Selectivity estimate_hash_bucketsize(Query *root, Var *var);
87 static bool cost_qual_eval_walker(Node *node, Cost *total);
88 static Selectivity approx_selectivity(Query *root, List *quals);
89 static void set_rel_width(Query *root, RelOptInfo *rel);
90 static double relation_byte_size(double tuples, int width);
91 static double page_size(double tuples, int width);
92
93
94 /*
95  * cost_seqscan
96  *        Determines and returns the cost of scanning a relation sequentially.
97  *
98  * Note: for historical reasons, this routine and the others in this module
99  * use the passed result Path only to store their startup_cost and total_cost
100  * results into.  All the input data they need is passed as separate
101  * parameters, even though much of it could be extracted from the Path.
102  */
103 void
104 cost_seqscan(Path *path, Query *root,
105                          RelOptInfo *baserel)
106 {
107         Cost            startup_cost = 0;
108         Cost            run_cost = 0;
109         Cost            cpu_per_tuple;
110
111         /* Should only be applied to base relations */
112         Assert(length(baserel->relids) == 1);
113         Assert(!baserel->issubquery);
114
115         if (!enable_seqscan)
116                 startup_cost += disable_cost;
117
118         /*
119          * disk costs
120          *
121          * The cost of reading a page sequentially is 1.0, by definition. Note
122          * that the Unix kernel will typically do some amount of read-ahead
123          * optimization, so that this cost is less than the true cost of
124          * reading a page from disk.  We ignore that issue here, but must take
125          * it into account when estimating the cost of non-sequential
126          * accesses!
127          */
128         run_cost += baserel->pages; /* sequential fetches with cost 1.0 */
129
130         /* CPU costs */
131         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
132         run_cost += cpu_per_tuple * baserel->tuples;
133
134         path->startup_cost = startup_cost;
135         path->total_cost = startup_cost + run_cost;
136 }
137
138 /*
139  * cost_nonsequential_access
140  *        Estimate the cost of accessing one page at random from a relation
141  *        (or sort temp file) of the given size in pages.
142  *
143  * The simplistic model that the cost is random_page_cost is what we want
144  * to use for large relations; but for small ones that is a serious
145  * overestimate because of the effects of caching.      This routine tries to
146  * account for that.
147  *
148  * Unfortunately we don't have any good way of estimating the effective cache
149  * size we are working with --- we know that Postgres itself has NBuffers
150  * internal buffers, but the size of the kernel's disk cache is uncertain,
151  * and how much of it we get to use is even less certain.  We punt the problem
152  * for now by assuming we are given an effective_cache_size parameter.
153  *
154  * Given a guesstimated cache size, we estimate the actual I/O cost per page
155  * with the entirely ad-hoc equations:
156  *      for rel_size <= effective_cache_size:
157  *              1 + (random_page_cost/2-1) * (rel_size/effective_cache_size) ** 2
158  *      for rel_size >= effective_cache_size:
159  *              random_page_cost * (1 - (effective_cache_size/rel_size)/2)
160  * These give the right asymptotic behavior (=> 1.0 as rel_size becomes
161  * small, => random_page_cost as it becomes large) and meet in the middle
162  * with the estimate that the cache is about 50% effective for a relation
163  * of the same size as effective_cache_size.  (XXX this is probably all
164  * wrong, but I haven't been able to find any theory about how effective
165  * a disk cache should be presumed to be.)
166  */
167 static Cost
168 cost_nonsequential_access(double relpages)
169 {
170         double          relsize;
171
172         /* don't crash on bad input data */
173         if (relpages <= 0.0 || effective_cache_size <= 0.0)
174                 return random_page_cost;
175
176         relsize = relpages / effective_cache_size;
177
178         if (relsize >= 1.0)
179                 return random_page_cost * (1.0 - 0.5 / relsize);
180         else
181                 return 1.0 + (random_page_cost * 0.5 - 1.0) * relsize * relsize;
182 }
183
184 /*
185  * cost_index
186  *        Determines and returns the cost of scanning a relation using an index.
187  *
188  *        NOTE: an indexscan plan node can actually represent several passes,
189  *        but here we consider the cost of just one pass.
190  *
191  * 'root' is the query root
192  * 'baserel' is the base relation the index is for
193  * 'index' is the index to be used
194  * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
195  * 'is_injoin' is T if we are considering using the index scan as the inside
196  *              of a nestloop join (hence, some of the indexQuals are join clauses)
197  *
198  * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
199  * Any additional quals evaluated as qpquals may reduce the number of returned
200  * tuples, but they won't reduce the number of tuples we have to fetch from
201  * the table, so they don't reduce the scan cost.
202  */
203 void
204 cost_index(Path *path, Query *root,
205                    RelOptInfo *baserel,
206                    IndexOptInfo *index,
207                    List *indexQuals,
208                    bool is_injoin)
209 {
210         Cost            startup_cost = 0;
211         Cost            run_cost = 0;
212         Cost            indexStartupCost;
213         Cost            indexTotalCost;
214         Selectivity indexSelectivity;
215         double          indexCorrelation,
216                                 csquared;
217         Cost            min_IO_cost,
218                                 max_IO_cost;
219         Cost            cpu_per_tuple;
220         double          tuples_fetched;
221         double          pages_fetched;
222         double          T,
223                                 b;
224
225         /* Should only be applied to base relations */
226         Assert(IsA(baserel, RelOptInfo) &&IsA(index, IndexOptInfo));
227         Assert(length(baserel->relids) == 1);
228         Assert(!baserel->issubquery);
229
230         if (!enable_indexscan && !is_injoin)
231                 startup_cost += disable_cost;
232
233         /*
234          * Call index-access-method-specific code to estimate the processing
235          * cost for scanning the index, as well as the selectivity of the
236          * index (ie, the fraction of main-table tuples we will have to
237          * retrieve) and its correlation to the main-table tuple order.
238          */
239         OidFunctionCall8(index->amcostestimate,
240                                          PointerGetDatum(root),
241                                          PointerGetDatum(baserel),
242                                          PointerGetDatum(index),
243                                          PointerGetDatum(indexQuals),
244                                          PointerGetDatum(&indexStartupCost),
245                                          PointerGetDatum(&indexTotalCost),
246                                          PointerGetDatum(&indexSelectivity),
247                                          PointerGetDatum(&indexCorrelation));
248
249         /* all costs for touching index itself included here */
250         startup_cost += indexStartupCost;
251         run_cost += indexTotalCost - indexStartupCost;
252
253         /*----------
254          * Estimate number of main-table tuples and pages fetched.
255          *
256          * When the index ordering is uncorrelated with the table ordering,
257          * we use an approximation proposed by Mackert and Lohman, "Index Scans
258          * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
259          * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
260          * The Mackert and Lohman approximation is that the number of pages
261          * fetched is
262          *      PF =
263          *              min(2TNs/(2T+Ns), T)                    when T <= b
264          *              2TNs/(2T+Ns)                                    when T > b and Ns <= 2Tb/(2T-b)
265          *              b + (Ns - 2Tb/(2T-b))*(T-b)/T   when T > b and Ns > 2Tb/(2T-b)
266          * where
267          *              T = # pages in table
268          *              N = # tuples in table
269          *              s = selectivity = fraction of table to be scanned
270          *              b = # buffer pages available (we include kernel space here)
271          *
272          * When the index ordering is exactly correlated with the table ordering
273          * (just after a CLUSTER, for example), the number of pages fetched should
274          * be just sT.  What's more, these will be sequential fetches, not the
275          * random fetches that occur in the uncorrelated case.  So, depending on
276          * the extent of correlation, we should estimate the actual I/O cost
277          * somewhere between s * T * 1.0 and PF * random_cost.  We currently
278          * interpolate linearly between these two endpoints based on the
279          * correlation squared (XXX is that appropriate?).
280          *
281          * In any case the number of tuples fetched is Ns.
282          *----------
283          */
284
285         tuples_fetched = indexSelectivity * baserel->tuples;
286         /* Don't believe estimates less than 1... */
287         if (tuples_fetched < 1.0)
288                 tuples_fetched = 1.0;
289
290         /* This part is the Mackert and Lohman formula */
291
292         T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
293         b = (effective_cache_size > 1) ? effective_cache_size : 1.0;
294
295         if (T <= b)
296         {
297                 pages_fetched =
298                         (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
299                 if (pages_fetched > T)
300                         pages_fetched = T;
301         }
302         else
303         {
304                 double  lim;
305
306                 lim = (2.0 * T * b) / (2.0 * T - b);
307                 if (tuples_fetched <= lim)
308                 {
309                         pages_fetched =
310                                 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
311                 }
312                 else
313                 {
314                         pages_fetched =
315                                 b + (tuples_fetched - lim) * (T - b) / T;
316                 }
317         }
318
319         /*
320          * min_IO_cost corresponds to the perfectly correlated case (csquared=1),
321          * max_IO_cost to the perfectly uncorrelated case (csquared=0).  Note
322          * that we just charge random_page_cost per page in the uncorrelated
323          * case, rather than using cost_nonsequential_access, since we've already
324          * accounted for caching effects by using the Mackert model.
325          */
326         min_IO_cost = ceil(indexSelectivity * T);
327         max_IO_cost = pages_fetched * random_page_cost;
328
329         /*
330          * Now interpolate based on estimated index order correlation
331          * to get total disk I/O cost for main table accesses.
332          */
333         csquared = indexCorrelation * indexCorrelation;
334
335         run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
336
337         /*
338          * Estimate CPU costs per tuple.
339          *
340          * Normally the indexquals will be removed from the list of
341          * restriction clauses that we have to evaluate as qpquals, so we
342          * should subtract their costs from baserestrictcost.  For a lossy
343          * index, however, we will have to recheck all the quals and so
344          * mustn't subtract anything. Also, if we are doing a join then some
345          * of the indexquals are join clauses and shouldn't be subtracted.
346          * Rather than work out exactly how much to subtract, we don't
347          * subtract anything in that case either.
348          */
349         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
350
351         if (!index->lossy && !is_injoin)
352                 cpu_per_tuple -= cost_qual_eval(indexQuals);
353
354         run_cost += cpu_per_tuple * tuples_fetched;
355
356         path->startup_cost = startup_cost;
357         path->total_cost = startup_cost + run_cost;
358 }
359
360 /*
361  * cost_tidscan
362  *        Determines and returns the cost of scanning a relation using TIDs.
363  */
364 void
365 cost_tidscan(Path *path, Query *root,
366                          RelOptInfo *baserel, List *tideval)
367 {
368         Cost            startup_cost = 0;
369         Cost            run_cost = 0;
370         Cost            cpu_per_tuple;
371         int                     ntuples = length(tideval);
372
373         if (!enable_tidscan)
374                 startup_cost += disable_cost;
375
376         /* disk costs --- assume each tuple on a different page */
377         run_cost += random_page_cost * ntuples;
378
379         /* CPU costs */
380         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
381         run_cost += cpu_per_tuple * ntuples;
382
383         path->startup_cost = startup_cost;
384         path->total_cost = startup_cost + run_cost;
385 }
386
387 /*
388  * cost_sort
389  *        Determines and returns the cost of sorting a relation.
390  *
391  * The cost of supplying the input data is NOT included; the caller should
392  * add that cost to both startup and total costs returned from this routine!
393  *
394  * If the total volume of data to sort is less than SortMem, we will do
395  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
396  * comparisons for t tuples.
397  *
398  * If the total volume exceeds SortMem, we switch to a tape-style merge
399  * algorithm.  There will still be about t*log2(t) tuple comparisons in
400  * total, but we will also need to write and read each tuple once per
401  * merge pass.  We expect about ceil(log6(r)) merge passes where r is the
402  * number of initial runs formed (log6 because tuplesort.c uses six-tape
403  * merging).  Since the average initial run should be about twice SortMem,
404  * we have
405  *              disk traffic = 2 * relsize * ceil(log6(p / (2*SortMem)))
406  *              cpu = comparison_cost * t * log2(t)
407  *
408  * The disk traffic is assumed to be half sequential and half random
409  * accesses (XXX can't we refine that guess?)
410  *
411  * We charge two operator evals per tuple comparison, which should be in
412  * the right ballpark in most cases.
413  *
414  * 'pathkeys' is a list of sort keys
415  * 'tuples' is the number of tuples in the relation
416  * 'width' is the average tuple width in bytes
417  *
418  * NOTE: some callers currently pass NIL for pathkeys because they
419  * can't conveniently supply the sort keys.  Since this routine doesn't
420  * currently do anything with pathkeys anyway, that doesn't matter...
421  * but if it ever does, it should react gracefully to lack of key data.
422  */
423 void
424 cost_sort(Path *path, Query *root,
425                   List *pathkeys, double tuples, int width)
426 {
427         Cost            startup_cost = 0;
428         Cost            run_cost = 0;
429         double          nbytes = relation_byte_size(tuples, width);
430         long            sortmembytes = SortMem * 1024L;
431
432         if (!enable_sort)
433                 startup_cost += disable_cost;
434
435         /*
436          * We want to be sure the cost of a sort is never estimated as zero,
437          * even if passed-in tuple count is zero.  Besides, mustn't do
438          * log(0)...
439          */
440         if (tuples < 2.0)
441                 tuples = 2.0;
442
443         /*
444          * CPU costs
445          *
446          * Assume about two operator evals per tuple comparison and N log2 N
447          * comparisons
448          */
449         startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
450
451         /* disk costs */
452         if (nbytes > sortmembytes)
453         {
454                 double          npages = ceil(nbytes / BLCKSZ);
455                 double          nruns = nbytes / (sortmembytes * 2);
456                 double          log_runs = ceil(LOG6(nruns));
457                 double          npageaccesses;
458
459                 if (log_runs < 1.0)
460                         log_runs = 1.0;
461                 npageaccesses = 2.0 * npages * log_runs;
462                 /* Assume half are sequential (cost 1), half are not */
463                 startup_cost += npageaccesses *
464                         (1.0 + cost_nonsequential_access(npages)) * 0.5;
465         }
466
467         /*
468          * Note: should we bother to assign a nonzero run_cost to reflect the
469          * overhead of extracting tuples from the sort result?  Probably not
470          * worth worrying about.
471          */
472         path->startup_cost = startup_cost;
473         path->total_cost = startup_cost + run_cost;
474 }
475
476
477 /*
478  * cost_nestloop
479  *        Determines and returns the cost of joining two relations using the
480  *        nested loop algorithm.
481  *
482  * 'outer_path' is the path for the outer relation
483  * 'inner_path' is the path for the inner relation
484  * 'restrictlist' are the RestrictInfo nodes to be applied at the join
485  */
486 void
487 cost_nestloop(Path *path, Query *root,
488                           Path *outer_path,
489                           Path *inner_path,
490                           List *restrictlist)
491 {
492         Cost            startup_cost = 0;
493         Cost            run_cost = 0;
494         Cost            cpu_per_tuple;
495         double          ntuples;
496
497         if (!enable_nestloop)
498                 startup_cost += disable_cost;
499
500         /* cost of source data */
501
502         /*
503          * NOTE: clearly, we must pay both outer and inner paths' startup_cost
504          * before we can start returning tuples, so the join's startup cost
505          * is their sum.  What's not so clear is whether the inner path's
506          * startup_cost must be paid again on each rescan of the inner path.
507          * This is not true if the inner path is materialized, but probably
508          * is true otherwise.  Since we don't yet have clean handling of the
509          * decision whether to materialize a path, we can't tell here which
510          * will happen.  As a compromise, charge 50% of the inner startup cost
511          * for each restart.
512          */
513         startup_cost += outer_path->startup_cost + inner_path->startup_cost;
514         run_cost += outer_path->total_cost - outer_path->startup_cost;
515         run_cost += outer_path->parent->rows *
516                 (inner_path->total_cost - inner_path->startup_cost);
517         if (outer_path->parent->rows > 1)
518                 run_cost += (outer_path->parent->rows - 1) *
519                         inner_path->startup_cost * 0.5;
520
521         /*
522          * Number of tuples processed (not number emitted!).  If inner path is
523          * an indexscan, be sure to use its estimated output row count, which
524          * may be lower than the restriction-clause-only row count of its
525          * parent.
526          */
527         if (IsA(inner_path, IndexPath))
528                 ntuples = ((IndexPath *) inner_path)->rows;
529         else
530                 ntuples = inner_path->parent->rows;
531         ntuples *= outer_path->parent->rows;
532
533         /* CPU costs */
534         cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
535         run_cost += cpu_per_tuple * ntuples;
536
537         path->startup_cost = startup_cost;
538         path->total_cost = startup_cost + run_cost;
539 }
540
541 /*
542  * cost_mergejoin
543  *        Determines and returns the cost of joining two relations using the
544  *        merge join algorithm.
545  *
546  * 'outer_path' is the path for the outer relation
547  * 'inner_path' is the path for the inner relation
548  * 'restrictlist' are the RestrictInfo nodes to be applied at the join
549  * 'mergeclauses' are the RestrictInfo nodes to use as merge clauses
550  *              (this should be a subset of the restrictlist)
551  * 'outersortkeys' and 'innersortkeys' are lists of the keys to be used
552  *                              to sort the outer and inner relations, or NIL if no explicit
553  *                              sort is needed because the source path is already ordered
554  */
555 void
556 cost_mergejoin(Path *path, Query *root,
557                            Path *outer_path,
558                            Path *inner_path,
559                            List *restrictlist,
560                            List *mergeclauses,
561                            List *outersortkeys,
562                            List *innersortkeys)
563 {
564         Cost            startup_cost = 0;
565         Cost            run_cost = 0;
566         Cost            cpu_per_tuple;
567         double          ntuples;
568         Path            sort_path;              /* dummy for result of cost_sort */
569
570         if (!enable_mergejoin)
571                 startup_cost += disable_cost;
572
573         /* cost of source data */
574
575         /*
576          * Note we are assuming that each source tuple is fetched just once,
577          * which is not right in the presence of equal keys.  If we had a way
578          * of estimating the proportion of equal keys, we could apply a
579          * correction factor...
580          */
581         if (outersortkeys)                      /* do we need to sort outer? */
582         {
583                 startup_cost += outer_path->total_cost;
584                 cost_sort(&sort_path,
585                                   root,
586                                   outersortkeys,
587                                   outer_path->parent->rows,
588                                   outer_path->parent->width);
589                 startup_cost += sort_path.startup_cost;
590                 run_cost += sort_path.total_cost - sort_path.startup_cost;
591         }
592         else
593         {
594                 startup_cost += outer_path->startup_cost;
595                 run_cost += outer_path->total_cost - outer_path->startup_cost;
596         }
597
598         if (innersortkeys)                      /* do we need to sort inner? */
599         {
600                 startup_cost += inner_path->total_cost;
601                 cost_sort(&sort_path,
602                                   root,
603                                   innersortkeys,
604                                   inner_path->parent->rows,
605                                   inner_path->parent->width);
606                 startup_cost += sort_path.startup_cost;
607                 run_cost += sort_path.total_cost - sort_path.startup_cost;
608         }
609         else
610         {
611                 startup_cost += inner_path->startup_cost;
612                 run_cost += inner_path->total_cost - inner_path->startup_cost;
613         }
614
615         /*
616          * The number of tuple comparisons needed depends drastically on the
617          * number of equal keys in the two source relations, which we have no
618          * good way of estimating.  Somewhat arbitrarily, we charge one
619          * tuple comparison (one cpu_operator_cost) for each tuple in the
620          * two source relations.  This is probably a lower bound.
621          */
622         run_cost += cpu_operator_cost *
623                 (outer_path->parent->rows + inner_path->parent->rows);
624
625         /*
626          * For each tuple that gets through the mergejoin proper, we charge
627          * cpu_tuple_cost plus the cost of evaluating additional restriction
628          * clauses that are to be applied at the join.  It's OK to use an
629          * approximate selectivity here, since in most cases this is a minor
630          * component of the cost.
631          */
632         ntuples = approx_selectivity(root, mergeclauses) *
633                 outer_path->parent->rows * inner_path->parent->rows;
634
635         /* CPU costs */
636         cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
637         run_cost += cpu_per_tuple * ntuples;
638
639         path->startup_cost = startup_cost;
640         path->total_cost = startup_cost + run_cost;
641 }
642
643 /*
644  * cost_hashjoin
645  *        Determines and returns the cost of joining two relations using the
646  *        hash join algorithm.
647  *
648  * 'outer_path' is the path for the outer relation
649  * 'inner_path' is the path for the inner relation
650  * 'restrictlist' are the RestrictInfo nodes to be applied at the join
651  * 'hashclauses' is a list of the hash join clause (always a 1-element list)
652  *              (this should be a subset of the restrictlist)
653  */
654 void
655 cost_hashjoin(Path *path, Query *root,
656                           Path *outer_path,
657                           Path *inner_path,
658                           List *restrictlist,
659                           List *hashclauses)
660 {
661         Cost            startup_cost = 0;
662         Cost            run_cost = 0;
663         Cost            cpu_per_tuple;
664         double          ntuples;
665         double          outerbytes = relation_byte_size(outer_path->parent->rows,
666                                                                                           outer_path->parent->width);
667         double          innerbytes = relation_byte_size(inner_path->parent->rows,
668                                                                                           inner_path->parent->width);
669         long            hashtablebytes = SortMem * 1024L;
670         RestrictInfo *restrictinfo;
671         Var                *left,
672                            *right;
673         Selectivity innerbucketsize;
674
675         if (!enable_hashjoin)
676                 startup_cost += disable_cost;
677
678         /* cost of source data */
679         startup_cost += outer_path->startup_cost;
680         run_cost += outer_path->total_cost - outer_path->startup_cost;
681         startup_cost += inner_path->total_cost;
682
683         /* cost of computing hash function: must do it once per input tuple */
684         startup_cost += cpu_operator_cost * inner_path->parent->rows;
685         run_cost += cpu_operator_cost * outer_path->parent->rows;
686
687         /*
688          * Determine bucketsize fraction for inner relation.  First we have
689          * to figure out which side of the hashjoin clause is the inner side.
690          */
691         Assert(length(hashclauses) == 1);
692         Assert(IsA(lfirst(hashclauses), RestrictInfo));
693         restrictinfo = (RestrictInfo *) lfirst(hashclauses);
694         /* these must be OK, since check_hashjoinable accepted the clause */
695         left = get_leftop(restrictinfo->clause);
696         right = get_rightop(restrictinfo->clause);
697
698         /*
699          * Since we tend to visit the same clauses over and over when
700          * planning a large query, we cache the bucketsize estimate in
701          * the RestrictInfo node to avoid repeated lookups of statistics.
702          */
703         if (intMember(right->varno, inner_path->parent->relids))
704         {
705                 /* righthand side is inner */
706                 innerbucketsize = restrictinfo->right_bucketsize;
707                 if (innerbucketsize < 0)
708                 {
709                         /* not cached yet */
710                         innerbucketsize = estimate_hash_bucketsize(root, right);
711                         restrictinfo->right_bucketsize = innerbucketsize;
712                 }
713         }
714         else
715         {
716                 Assert(intMember(left->varno, inner_path->parent->relids));
717                 /* lefthand side is inner */
718                 innerbucketsize = restrictinfo->left_bucketsize;
719                 if (innerbucketsize < 0)
720                 {
721                         /* not cached yet */
722                         innerbucketsize = estimate_hash_bucketsize(root, left);
723                         restrictinfo->left_bucketsize = innerbucketsize;
724                 }
725         }
726
727         /*
728          * The number of tuple comparisons needed is the number of outer
729          * tuples times the typical number of tuples in a hash bucket,
730          * which is the inner relation size times its bucketsize fraction.
731          * We charge one cpu_operator_cost per tuple comparison.
732          */
733         run_cost += cpu_operator_cost * outer_path->parent->rows *
734                 ceil(inner_path->parent->rows * innerbucketsize);
735
736         /*
737          * For each tuple that gets through the hashjoin proper, we charge
738          * cpu_tuple_cost plus the cost of evaluating additional restriction
739          * clauses that are to be applied at the join.  It's OK to use an
740          * approximate selectivity here, since in most cases this is a minor
741          * component of the cost.
742          */
743         ntuples = approx_selectivity(root, hashclauses) *
744                 outer_path->parent->rows * inner_path->parent->rows;
745
746         /* CPU costs */
747         cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
748         run_cost += cpu_per_tuple * ntuples;
749
750         /*
751          * if inner relation is too big then we will need to "batch" the join,
752          * which implies writing and reading most of the tuples to disk an
753          * extra time.  Charge one cost unit per page of I/O (correct since it
754          * should be nice and sequential...).  Writing the inner rel counts as
755          * startup cost, all the rest as run cost.
756          */
757         if (innerbytes > hashtablebytes)
758         {
759                 double          outerpages = page_size(outer_path->parent->rows,
760                                                                                    outer_path->parent->width);
761                 double          innerpages = page_size(inner_path->parent->rows,
762                                                                                    inner_path->parent->width);
763
764                 startup_cost += innerpages;
765                 run_cost += innerpages + 2 * outerpages;
766         }
767
768         /*
769          * Bias against putting larger relation on inside.      We don't want an
770          * absolute prohibition, though, since larger relation might have
771          * better bucketsize --- and we can't trust the size estimates
772          * unreservedly, anyway.  Instead, inflate the startup cost by the
773          * square root of the size ratio.  (Why square root?  No real good
774          * reason, but it seems reasonable...)
775          */
776         if (innerbytes > outerbytes && outerbytes > 0)
777                 startup_cost *= sqrt(innerbytes / outerbytes);
778
779         path->startup_cost = startup_cost;
780         path->total_cost = startup_cost + run_cost;
781 }
782
783 /*
784  * Estimate hash bucketsize fraction (ie, number of entries in a bucket
785  * divided by total tuples in relation) if the specified Var is used
786  * as a hash key.
787  *
788  * XXX This is really pretty bogus since we're effectively assuming that the
789  * distribution of hash keys will be the same after applying restriction
790  * clauses as it was in the underlying relation.  However, we are not nearly
791  * smart enough to figure out how the restrict clauses might change the
792  * distribution, so this will have to do for now.
793  *
794  * The executor tries for average bucket loading of NTUP_PER_BUCKET by setting
795  * number of buckets equal to ntuples / NTUP_PER_BUCKET, which would yield
796  * a bucketsize fraction of NTUP_PER_BUCKET / ntuples.  But that goal will
797  * be reached only if the data values are uniformly distributed among the
798  * buckets, which requires (a) at least ntuples / NTUP_PER_BUCKET distinct
799  * data values, and (b) a not-too-skewed data distribution.  Otherwise the
800  * buckets will be nonuniformly occupied.  If the other relation in the join
801  * has a similar distribution, the most-loaded buckets are exactly those
802  * that will be probed most often.  Therefore, the "average" bucket size for
803  * costing purposes should really be taken as something close to the "worst
804  * case" bucket size.  We try to estimate this by first scaling up if there
805  * are too few distinct data values, and then scaling up again by the
806  * ratio of the most common value's frequency to the average frequency.
807  *
808  * If no statistics are available, use a default estimate of 0.1.  This will
809  * discourage use of a hash rather strongly if the inner relation is large,
810  * which is what we want.  We do not want to hash unless we know that the
811  * inner rel is well-dispersed (or the alternatives seem much worse).
812  */
813 static Selectivity
814 estimate_hash_bucketsize(Query *root, Var *var)
815 {
816         Oid                     relid;
817         RelOptInfo *rel;
818         HeapTuple       tuple;
819         Form_pg_statistic stats;
820         double          estfract,
821                                 ndistinct,
822                                 needdistinct,
823                                 mcvfreq,
824                                 avgfreq;
825         float4     *numbers;
826         int                     nnumbers;
827
828         /*
829          * Lookup info about var's relation and attribute;
830          * if none available, return default estimate.
831          */
832         if (!IsA(var, Var))
833                 return 0.1;
834
835         relid = getrelid(var->varno, root->rtable);
836         if (relid == InvalidOid)
837                 return 0.1;
838
839         rel = find_base_rel(root, var->varno);
840
841         if (rel->tuples <= 0.0 || rel->rows <= 0.0)
842                 return 0.1;                             /* ensure we can divide below */
843
844         tuple = SearchSysCache(STATRELATT,
845                                                    ObjectIdGetDatum(relid),
846                                                    Int16GetDatum(var->varattno),
847                                                    0, 0);
848         if (!HeapTupleIsValid(tuple))
849         {
850                 /*
851                  * Perhaps the Var is a system attribute; if so, it will have no
852                  * entry in pg_statistic, but we may be able to guess something
853                  * about its distribution anyway.
854                  */
855                 switch (var->varattno)
856                 {
857                         case ObjectIdAttributeNumber:
858                         case SelfItemPointerAttributeNumber:
859                                 /* these are unique, so buckets should be well-distributed */
860                                 return (double) NTUP_PER_BUCKET / rel->rows;
861                         case TableOidAttributeNumber:
862                                 /* hashing this is a terrible idea... */
863                                 return 1.0;
864                 }
865                 return 0.1;
866         }
867         stats = (Form_pg_statistic) GETSTRUCT(tuple);
868
869         /*
870          * Obtain number of distinct data values in raw relation.
871          */
872         ndistinct = stats->stadistinct;
873         if (ndistinct < 0.0)
874                 ndistinct = -ndistinct * rel->tuples;
875
876         /*
877          * Adjust ndistinct to account for restriction clauses.  Observe we are
878          * assuming that the data distribution is affected uniformly by the
879          * restriction clauses!
880          *
881          * XXX Possibly better way, but much more expensive: multiply by
882          * selectivity of rel's restriction clauses that mention the target Var.
883          */
884         ndistinct *= rel->rows / rel->tuples;
885
886         /*
887          * Discourage use of hash join if there seem not to be very many distinct
888          * data values.  The threshold here is somewhat arbitrary, as is the
889          * fraction used to "discourage" the choice.
890          */
891         if (ndistinct < 50.0)
892         {
893                 ReleaseSysCache(tuple);
894                 return 0.5;
895         }
896
897         /*
898          * Form initial estimate of bucketsize fraction.  Here we use rel->rows,
899          * ie the number of rows after applying restriction clauses, because
900          * that's what the fraction will eventually be multiplied by in
901          * cost_heapjoin.
902          */
903         estfract = (double) NTUP_PER_BUCKET / rel->rows;
904
905         /*
906          * Adjust estimated bucketsize if too few distinct values to fill
907          * all the buckets.
908          */
909         needdistinct = rel->rows / (double) NTUP_PER_BUCKET;
910         if (ndistinct < needdistinct)
911                 estfract *= needdistinct / ndistinct;
912
913         /*
914          * Look up the frequency of the most common value, if available.
915          */
916         mcvfreq = 0.0;
917
918         if (get_attstatsslot(tuple, var->vartype, var->vartypmod,
919                                                  STATISTIC_KIND_MCV, InvalidOid,
920                                                  NULL, NULL, &numbers, &nnumbers))
921         {
922                 /*
923                  * The first MCV stat is for the most common value.
924                  */
925                 if (nnumbers > 0)
926                         mcvfreq = numbers[0];
927                 free_attstatsslot(var->vartype, NULL, 0,
928                                                   numbers, nnumbers);
929         }
930
931         /*
932          * Adjust estimated bucketsize upward to account for skewed distribution.
933          */
934         avgfreq = (1.0 - stats->stanullfrac) / ndistinct;
935
936         if (avgfreq > 0.0 && mcvfreq > avgfreq)
937                 estfract *= mcvfreq / avgfreq;
938
939         ReleaseSysCache(tuple);
940
941         return (Selectivity) estfract;
942 }
943
944
945 /*
946  * cost_qual_eval
947  *              Estimate the CPU cost of evaluating a WHERE clause (once).
948  *              The input can be either an implicitly-ANDed list of boolean
949  *              expressions, or a list of RestrictInfo nodes.
950  */
951 Cost
952 cost_qual_eval(List *quals)
953 {
954         Cost            total = 0;
955         List       *l;
956
957         /* We don't charge any cost for the implicit ANDing at top level ... */
958
959         foreach(l, quals)
960         {
961                 Node       *qual = (Node *) lfirst(l);
962
963                 /*
964                  * RestrictInfo nodes contain an eval_cost field reserved for this
965                  * routine's use, so that it's not necessary to evaluate the qual
966                  * clause's cost more than once.  If the clause's cost hasn't been
967                  * computed yet, the field will contain -1.
968                  */
969                 if (qual && IsA(qual, RestrictInfo))
970                 {
971                         RestrictInfo *restrictinfo = (RestrictInfo *) qual;
972
973                         if (restrictinfo->eval_cost < 0)
974                         {
975                                 restrictinfo->eval_cost = 0;
976                                 cost_qual_eval_walker((Node *) restrictinfo->clause,
977                                                                           &restrictinfo->eval_cost);
978                         }
979                         total += restrictinfo->eval_cost;
980                 }
981                 else
982                 {
983                         /* If it's a bare expression, must always do it the hard way */
984                         cost_qual_eval_walker(qual, &total);
985                 }
986         }
987         return total;
988 }
989
990 static bool
991 cost_qual_eval_walker(Node *node, Cost *total)
992 {
993         if (node == NULL)
994                 return false;
995
996         /*
997          * Our basic strategy is to charge one cpu_operator_cost for each
998          * operator or function node in the given tree.  Vars and Consts are
999          * charged zero, and so are boolean operators (AND, OR, NOT).
1000          * Simplistic, but a lot better than no model at all.
1001          *
1002          * Should we try to account for the possibility of short-circuit
1003          * evaluation of AND/OR?
1004          */
1005         if (IsA(node, Expr))
1006         {
1007                 Expr       *expr = (Expr *) node;
1008
1009                 switch (expr->opType)
1010                 {
1011                         case OP_EXPR:
1012                         case FUNC_EXPR:
1013                                 *total += cpu_operator_cost;
1014                                 break;
1015                         case OR_EXPR:
1016                         case AND_EXPR:
1017                         case NOT_EXPR:
1018                                 break;
1019                         case SUBPLAN_EXPR:
1020
1021                                 /*
1022                                  * A subplan node in an expression indicates that the
1023                                  * subplan will be executed on each evaluation, so charge
1024                                  * accordingly. (We assume that sub-selects that can be
1025                                  * executed as InitPlans have already been removed from
1026                                  * the expression.)
1027                                  *
1028                                  * NOTE: this logic should agree with the estimates used by
1029                                  * make_subplan() in plan/subselect.c.
1030                                  */
1031                                 {
1032                                         SubPlan    *subplan = (SubPlan *) expr->oper;
1033                                         Plan       *plan = subplan->plan;
1034                                         Cost            subcost;
1035
1036                                         if (subplan->sublink->subLinkType == EXISTS_SUBLINK)
1037                                         {
1038                                                 /* we only need to fetch 1 tuple */
1039                                                 subcost = plan->startup_cost +
1040                                                         (plan->total_cost - plan->startup_cost) / plan->plan_rows;
1041                                         }
1042                                         else if (subplan->sublink->subLinkType == ALL_SUBLINK ||
1043                                                          subplan->sublink->subLinkType == ANY_SUBLINK)
1044                                         {
1045                                                 /* assume we need 50% of the tuples */
1046                                                 subcost = plan->startup_cost +
1047                                                         0.50 * (plan->total_cost - plan->startup_cost);
1048                                                 /* XXX what if subplan has been materialized? */
1049                                         }
1050                                         else
1051                                         {
1052                                                 /* assume we need all tuples */
1053                                                 subcost = plan->total_cost;
1054                                         }
1055                                         *total += subcost;
1056                                 }
1057                                 break;
1058                 }
1059                 /* fall through to examine args of Expr node */
1060         }
1061         return expression_tree_walker(node, cost_qual_eval_walker,
1062                                                                   (void *) total);
1063 }
1064
1065
1066 /*
1067  * approx_selectivity
1068  *              Quick-and-dirty estimation of clause selectivities.
1069  *              The input can be either an implicitly-ANDed list of boolean
1070  *              expressions, or a list of RestrictInfo nodes (typically the latter).
1071  *
1072  * The "quick" part comes from caching the selectivity estimates so we can
1073  * avoid recomputing them later.  (Since the same clauses are typically
1074  * examined over and over in different possible join trees, this makes a
1075  * big difference.)
1076  *
1077  * The "dirty" part comes from the fact that the selectivities of multiple
1078  * clauses are estimated independently and multiplied together.  Currently,
1079  * clauselist_selectivity can seldom do any better than that anyhow, but
1080  * someday it might be smarter.
1081  *
1082  * Since we are only using the results to estimate how many potential
1083  * output tuples are generated and passed through qpqual checking, it
1084  * seems OK to live with the approximation.
1085  */
1086 static Selectivity
1087 approx_selectivity(Query *root, List *quals)
1088 {
1089         Selectivity     total = 1.0;
1090         List       *l;
1091
1092         foreach(l, quals)
1093         {
1094                 Node       *qual = (Node *) lfirst(l);
1095                 Selectivity     selec;
1096
1097                 /*
1098                  * RestrictInfo nodes contain a this_selec field reserved for this
1099                  * routine's use, so that it's not necessary to evaluate the qual
1100                  * clause's selectivity more than once.  If the clause's selectivity
1101                  * hasn't been computed yet, the field will contain -1.
1102                  */
1103                 if (qual && IsA(qual, RestrictInfo))
1104                 {
1105                         RestrictInfo *restrictinfo = (RestrictInfo *) qual;
1106
1107                         if (restrictinfo->this_selec < 0)
1108                                 restrictinfo->this_selec =
1109                                         clause_selectivity(root,
1110                                                                            (Node *) restrictinfo->clause,
1111                                                                            0);
1112                         selec = restrictinfo->this_selec;
1113                 }
1114                 else
1115                 {
1116                         /* If it's a bare expression, must always do it the hard way */
1117                         selec = clause_selectivity(root, qual, 0);
1118                 }
1119                 total *= selec;
1120         }
1121         return total;
1122 }
1123
1124
1125 /*
1126  * set_baserel_size_estimates
1127  *              Set the size estimates for the given base relation.
1128  *
1129  * The rel's targetlist and restrictinfo list must have been constructed
1130  * already.
1131  *
1132  * We set the following fields of the rel node:
1133  *      rows: the estimated number of output tuples (after applying
1134  *                restriction clauses).
1135  *      width: the estimated average output tuple width in bytes.
1136  *      baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
1137  */
1138 void
1139 set_baserel_size_estimates(Query *root, RelOptInfo *rel)
1140 {
1141         /* Should only be applied to base relations */
1142         Assert(length(rel->relids) == 1);
1143
1144         rel->rows = rel->tuples *
1145                 restrictlist_selectivity(root,
1146                                                                  rel->baserestrictinfo,
1147                                                                  lfirsti(rel->relids));
1148
1149         /*
1150          * Force estimate to be at least one row, to make explain output look
1151          * better and to avoid possible divide-by-zero when interpolating
1152          * cost.
1153          */
1154         if (rel->rows < 1.0)
1155                 rel->rows = 1.0;
1156
1157         rel->baserestrictcost = cost_qual_eval(rel->baserestrictinfo);
1158
1159         set_rel_width(root, rel);
1160 }
1161
1162 /*
1163  * set_joinrel_size_estimates
1164  *              Set the size estimates for the given join relation.
1165  *
1166  * The rel's targetlist must have been constructed already, and a
1167  * restriction clause list that matches the given component rels must
1168  * be provided.
1169  *
1170  * Since there is more than one way to make a joinrel for more than two
1171  * base relations, the results we get here could depend on which component
1172  * rel pair is provided.  In theory we should get the same answers no matter
1173  * which pair is provided; in practice, since the selectivity estimation
1174  * routines don't handle all cases equally well, we might not.  But there's
1175  * not much to be done about it.  (Would it make sense to repeat the
1176  * calculations for each pair of input rels that's encountered, and somehow
1177  * average the results?  Probably way more trouble than it's worth.)
1178  *
1179  * We set the same relnode fields as set_baserel_size_estimates() does.
1180  */
1181 void
1182 set_joinrel_size_estimates(Query *root, RelOptInfo *rel,
1183                                                    RelOptInfo *outer_rel,
1184                                                    RelOptInfo *inner_rel,
1185                                                    JoinType jointype,
1186                                                    List *restrictlist)
1187 {
1188         double          temp;
1189
1190         /* Start with the Cartesian product */
1191         temp = outer_rel->rows * inner_rel->rows;
1192
1193         /*
1194          * Apply join restrictivity.  Note that we are only considering
1195          * clauses that become restriction clauses at this join level; we are
1196          * not double-counting them because they were not considered in
1197          * estimating the sizes of the component rels.
1198          */
1199         temp *= restrictlist_selectivity(root,
1200                                                                          restrictlist,
1201                                                                          0);
1202
1203         /*
1204          * If we are doing an outer join, take that into account: the output
1205          * must be at least as large as the non-nullable input.  (Is there any
1206          * chance of being even smarter?)
1207          */
1208         switch (jointype)
1209         {
1210                 case JOIN_INNER:
1211                         break;
1212                 case JOIN_LEFT:
1213                         if (temp < outer_rel->rows)
1214                                 temp = outer_rel->rows;
1215                         break;
1216                 case JOIN_RIGHT:
1217                         if (temp < inner_rel->rows)
1218                                 temp = inner_rel->rows;
1219                         break;
1220                 case JOIN_FULL:
1221                         if (temp < outer_rel->rows)
1222                                 temp = outer_rel->rows;
1223                         if (temp < inner_rel->rows)
1224                                 temp = inner_rel->rows;
1225                         break;
1226                 default:
1227                         elog(ERROR, "set_joinrel_size_estimates: unsupported join type %d",
1228                                  (int) jointype);
1229                         break;
1230         }
1231
1232         /*
1233          * Force estimate to be at least one row, to make explain output look
1234          * better and to avoid possible divide-by-zero when interpolating
1235          * cost.
1236          */
1237         if (temp < 1.0)
1238                 temp = 1.0;
1239
1240         rel->rows = temp;
1241
1242         /*
1243          * We could apply set_rel_width() to compute the output tuple width
1244          * from scratch, but at present it's always just the sum of the input
1245          * widths, so why work harder than necessary?  If relnode.c is ever
1246          * taught to remove unneeded columns from join targetlists, go back to
1247          * using set_rel_width here.
1248          */
1249         rel->width = outer_rel->width + inner_rel->width;
1250 }
1251
1252 /*
1253  * set_rel_width
1254  *              Set the estimated output width of the relation.
1255  *
1256  * NB: this works best on base relations because it prefers to look at
1257  * real Vars.  It will fail to make use of pg_statistic info when applied
1258  * to a subquery relation, even if the subquery outputs are simple vars
1259  * that we could have gotten info for.  Is it worth trying to be smarter
1260  * about subqueries?
1261  */
1262 static void
1263 set_rel_width(Query *root, RelOptInfo *rel)
1264 {
1265         int32           tuple_width = 0;
1266         List       *tllist;
1267
1268         foreach(tllist, rel->targetlist)
1269         {
1270                 TargetEntry *tle = (TargetEntry *) lfirst(tllist);
1271                 int32   item_width;
1272
1273                 /*
1274                  * If it's a Var, try to get statistical info from pg_statistic.
1275                  */
1276                 if (tle->expr && IsA(tle->expr, Var))
1277                 {
1278                         Var        *var = (Var *) tle->expr;
1279                         Oid             relid;
1280
1281                         relid = getrelid(var->varno, root->rtable);
1282                         if (relid != InvalidOid)
1283                         {
1284                                 item_width = get_attavgwidth(relid, var->varattno);
1285                                 if (item_width > 0)
1286                                 {
1287                                         tuple_width += item_width;
1288                                         continue;
1289                                 }
1290                         }
1291                 }
1292                 /*
1293                  * Not a Var, or can't find statistics for it.  Estimate using
1294                  * just the type info.
1295                  */
1296                 item_width = get_typavgwidth(tle->resdom->restype,
1297                                                                          tle->resdom->restypmod);
1298                 Assert(item_width > 0);
1299                 tuple_width += item_width;
1300         }
1301         Assert(tuple_width >= 0);
1302         rel->width = tuple_width;
1303 }
1304
1305 /*
1306  * relation_byte_size
1307  *        Estimate the storage space in bytes for a given number of tuples
1308  *        of a given width (size in bytes).
1309  */
1310 static double
1311 relation_byte_size(double tuples, int width)
1312 {
1313         return tuples * ((double) MAXALIGN(width + sizeof(HeapTupleData)));
1314 }
1315
1316 /*
1317  * page_size
1318  *        Returns an estimate of the number of pages covered by a given
1319  *        number of tuples of a given width (size in bytes).
1320  */
1321 static double
1322 page_size(double tuples, int width)
1323 {
1324         return ceil(relation_byte_size(tuples, width) / BLCKSZ);
1325 }