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