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