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