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