]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/path/costsize.c
Third round of fmgr updates: eliminate calls using fmgr() and
[postgresql] / src / backend / optimizer / path / costsize.c
1 /*-------------------------------------------------------------------------
2  *
3  * costsize.c
4  *        Routines to compute (and set) relation sizes and path costs
5  *
6  * Path costs are measured in units of disk accesses: one sequential page
7  * fetch has cost 1.  All else is scaled relative to a page fetch, using
8  * the scaling parameters
9  *
10  *      random_page_cost        Cost of a non-sequential page fetch
11  *      cpu_tuple_cost          Cost of typical CPU time to process a tuple
12  *      cpu_index_tuple_cost  Cost of typical CPU time to process an index tuple
13  *      cpu_operator_cost       Cost of CPU time to process a typical WHERE operator
14  *
15  * We also use a rough estimate "effective_cache_size" of the number of
16  * disk pages in Postgres + OS-level disk cache.  (We can't simply use
17  * NBuffers for this purpose because that would ignore the effects of
18  * the kernel's disk cache.)
19  *
20  * Obviously, taking constants for these values is an oversimplification,
21  * but it's tough enough to get any useful estimates even at this level of
22  * detail.      Note that all of these parameters are user-settable, in case
23  * the default values are drastically off for a particular platform.
24  *
25  * We compute two separate costs for each path:
26  *              total_cost: total estimated cost to fetch all tuples
27  *              startup_cost: cost that is expended before first tuple is fetched
28  * In some scenarios, such as when there is a LIMIT or we are implementing
29  * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
30  * path's result.  A caller can estimate the cost of fetching a partial
31  * result by interpolating between startup_cost and total_cost.  In detail:
32  *              actual_cost = startup_cost +
33  *                      (total_cost - startup_cost) * tuples_to_fetch / path->parent->rows;
34  * Note that a relation's rows count (and, by extension, a Plan's plan_rows)
35  * are set without regard to any LIMIT, so that this equation works properly.
36  * (Also, these routines guarantee not to set the rows count to zero, so there
37  * will be no zero divide.)  RelOptInfos, Paths, and Plans themselves never
38  * account for LIMIT.
39  *
40  *
41  * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
42  * Portions Copyright (c) 1994, Regents of the University of California
43  *
44  * IDENTIFICATION
45  *        $Header: /cvsroot/pgsql/src/backend/optimizer/path/costsize.c,v 1.60 2000/05/30 04:24:47 tgl Exp $
46  *
47  *-------------------------------------------------------------------------
48  */
49
50 #include "postgres.h"
51
52 #include <math.h>
53
54 #include "executor/nodeHash.h"
55 #include "miscadmin.h"
56 #include "optimizer/clauses.h"
57 #include "optimizer/cost.h"
58 #include "optimizer/internal.h"
59 #include "utils/lsyscache.h"
60
61
62 #define LOG2(x)  (log(x) / 0.693147180559945)
63 #define LOG6(x)  (log(x) / 1.79175946922805)
64
65
66 double          effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
67 Cost            random_page_cost = DEFAULT_RANDOM_PAGE_COST;
68 Cost            cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
69 Cost            cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
70 Cost            cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
71
72 Cost            disable_cost = 100000000.0;
73
74 bool            enable_seqscan = true;
75 bool            enable_indexscan = true;
76 bool            enable_tidscan = true;
77 bool            enable_sort = true;
78 bool            enable_nestloop = true;
79 bool            enable_mergejoin = true;
80 bool            enable_hashjoin = true;
81
82
83 static bool cost_qual_eval_walker(Node *node, Cost *total);
84 static void set_rel_width(Query *root, RelOptInfo *rel);
85 static int      compute_attribute_width(TargetEntry *tlistentry);
86 static double relation_byte_size(double tuples, int width);
87 static double page_size(double tuples, int width);
88
89
90 /*
91  * cost_seqscan
92  *        Determines and returns the cost of scanning a relation sequentially.
93  *
94  * If the relation is a temporary to be materialized from a query
95  * embedded within a data field (determined by 'relid' containing an
96  * attribute reference), then a predetermined constant is returned (we
97  * have NO IDEA how big the result of a POSTQUEL procedure is going to be).
98  *
99  * Note: for historical reasons, this routine and the others in this module
100  * use the passed result Path only to store their startup_cost and total_cost
101  * results into.  All the input data they need is passed as separate
102  * parameters, even though much of it could be extracted from the result Path.
103  */
104 void
105 cost_seqscan(Path *path, RelOptInfo *baserel)
106 {
107         Cost            startup_cost = 0;
108         Cost            run_cost = 0;
109         Cost            cpu_per_tuple;
110
111         /* Should only be applied to base relations */
112         Assert(length(baserel->relids) == 1);
113
114         if (!enable_seqscan)
115                 startup_cost += disable_cost;
116
117         /* disk costs */
118         if (lfirsti(baserel->relids) < 0)
119         {
120
121                 /*
122                  * cost of sequentially scanning a materialized temporary relation
123                  */
124                 run_cost += _NONAME_SCAN_COST_;
125         }
126         else
127         {
128
129                 /*
130                  * The cost of reading a page sequentially is 1.0, by definition.
131                  * Note that the Unix kernel will typically do some amount of
132                  * read-ahead optimization, so that this cost is less than the
133                  * true cost of reading a page from disk.  We ignore that issue
134                  * here, but must take it into account when estimating the cost of
135                  * non-sequential accesses!
136                  */
137                 run_cost += baserel->pages;             /* sequential fetches with cost
138                                                                                  * 1.0 */
139         }
140
141         /* CPU costs */
142         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
143         run_cost += cpu_per_tuple * baserel->tuples;
144
145         path->startup_cost = startup_cost;
146         path->total_cost = startup_cost + run_cost;
147 }
148
149 /*
150  * cost_nonsequential_access
151  *        Estimate the cost of accessing one page at random from a relation
152  *        (or sort temp file) of the given size in pages.
153  *
154  * The simplistic model that the cost is random_page_cost is what we want
155  * to use for large relations; but for small ones that is a serious
156  * overestimate because of the effects of caching.      This routine tries to
157  * account for that.
158  *
159  * Unfortunately we don't have any good way of estimating the effective cache
160  * size we are working with --- we know that Postgres itself has NBuffers
161  * internal buffers, but the size of the kernel's disk cache is uncertain,
162  * and how much of it we get to use is even less certain.  We punt the problem
163  * for now by assuming we are given an effective_cache_size parameter.
164  *
165  * Given a guesstimated cache size, we estimate the actual I/O cost per page
166  * with the entirely ad-hoc equations:
167  *      for rel_size <= effective_cache_size:
168  *              1 + (random_page_cost/2-1) * (rel_size/effective_cache_size) ** 2
169  *      for rel_size >= effective_cache_size:
170  *              random_page_cost * (1 - (effective_cache_size/rel_size)/2)
171  * These give the right asymptotic behavior (=> 1.0 as rel_size becomes
172  * small, => random_page_cost as it becomes large) and meet in the middle
173  * with the estimate that the cache is about 50% effective for a relation
174  * of the same size as effective_cache_size.  (XXX this is probably all
175  * wrong, but I haven't been able to find any theory about how effective
176  * a disk cache should be presumed to be.)
177  */
178 static Cost
179 cost_nonsequential_access(double relpages)
180 {
181         double          relsize;
182
183         /* don't crash on bad input data */
184         if (relpages <= 0.0 || effective_cache_size <= 0.0)
185                 return random_page_cost;
186
187         relsize = relpages / effective_cache_size;
188
189         if (relsize >= 1.0)
190                 return random_page_cost * (1.0 - 0.5 / relsize);
191         else
192                 return 1.0 + (random_page_cost * 0.5 - 1.0) * relsize * relsize;
193 }
194
195 /*
196  * cost_index
197  *        Determines and returns the cost of scanning a relation using an index.
198  *
199  *        NOTE: an indexscan plan node can actually represent several passes,
200  *        but here we consider the cost of just one pass.
201  *
202  * 'root' is the query root
203  * 'baserel' is the base relation the index is for
204  * 'index' is the index to be used
205  * 'indexQuals' is the list of applicable qual clauses (implicit AND semantics)
206  * 'is_injoin' is T if we are considering using the index scan as the inside
207  *              of a nestloop join (hence, some of the indexQuals are join clauses)
208  *
209  * NOTE: 'indexQuals' must contain only clauses usable as index restrictions.
210  * Any additional quals evaluated as qpquals may reduce the number of returned
211  * tuples, but they won't reduce the number of tuples we have to fetch from
212  * the table, so they don't reduce the scan cost.
213  */
214 void
215 cost_index(Path *path, Query *root,
216                    RelOptInfo *baserel,
217                    IndexOptInfo *index,
218                    List *indexQuals,
219                    bool is_injoin)
220 {
221         Cost            startup_cost = 0;
222         Cost            run_cost = 0;
223         Cost            cpu_per_tuple;
224         Cost            indexStartupCost;
225         Cost            indexTotalCost;
226         Selectivity indexSelectivity;
227         double          tuples_fetched;
228         double          pages_fetched;
229
230         /* Should only be applied to base relations */
231         Assert(IsA(baserel, RelOptInfo) &&IsA(index, IndexOptInfo));
232         Assert(length(baserel->relids) == 1);
233
234         if (!enable_indexscan && !is_injoin)
235                 startup_cost += disable_cost;
236
237         /*
238          * Call index-access-method-specific code to estimate the processing
239          * cost for scanning the index, as well as the selectivity of the
240          * index (ie, the fraction of main-table tuples we will have to
241          * retrieve).
242          */
243         OidFunctionCall7(index->amcostestimate,
244                                          PointerGetDatum(root),
245                                          PointerGetDatum(baserel),
246                                          PointerGetDatum(index),
247                                          PointerGetDatum(indexQuals),
248                                          PointerGetDatum(&indexStartupCost),
249                                          PointerGetDatum(&indexTotalCost),
250                                          PointerGetDatum(&indexSelectivity));
251
252         /* all costs for touching index itself included here */
253         startup_cost += indexStartupCost;
254         run_cost += indexTotalCost - indexStartupCost;
255
256         /*
257          * Estimate number of main-table tuples and pages fetched.
258          *
259          * If the number of tuples is much smaller than the number of pages in
260          * the relation, each tuple will cost a separate nonsequential fetch.
261          * If it is comparable or larger, then probably we will be able to
262          * avoid some fetches.  We use a growth rate of log(#tuples/#pages +
263          * 1) --- probably totally bogus, but intuitively it gives the right
264          * shape of curve at least.
265          *
266          * XXX if the relation has recently been "clustered" using this index,
267          * then in fact the target tuples will be highly nonuniformly
268          * distributed, and we will be seriously overestimating the scan cost!
269          * Currently we have no way to know whether the relation has been
270          * clustered, nor how much it's been modified since the last
271          * clustering, so we ignore this effect.  Would be nice to do better
272          * someday.
273          */
274
275         tuples_fetched = indexSelectivity * baserel->tuples;
276         /* Don't believe estimates less than 1... */
277         if (tuples_fetched < 1.0)
278                 tuples_fetched = 1.0;
279
280         if (baserel->pages > 0)
281                 pages_fetched = ceil(baserel->pages *
282                                                          log(tuples_fetched / baserel->pages + 1.0));
283         else
284                 pages_fetched = tuples_fetched;
285
286         /*
287          * Now estimate one nonsequential access per page fetched, plus
288          * appropriate CPU costs per tuple.
289          */
290
291         /* disk costs for main table */
292         run_cost += pages_fetched * cost_nonsequential_access(baserel->pages);
293
294         /* CPU costs */
295         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
296
297         /*
298          * Normally the indexquals will be removed from the list of
299          * restriction clauses that we have to evaluate as qpquals, so we
300          * should subtract their costs from baserestrictcost.  For a lossy
301          * index, however, we will have to recheck all the quals and so
302          * mustn't subtract anything. Also, if we are doing a join then some
303          * of the indexquals are join clauses and shouldn't be subtracted.
304          * Rather than work out exactly how much to subtract, we don't
305          * subtract anything in that case either.
306          */
307         if (!index->lossy && !is_injoin)
308                 cpu_per_tuple -= cost_qual_eval(indexQuals);
309
310         run_cost += cpu_per_tuple * tuples_fetched;
311
312         path->startup_cost = startup_cost;
313         path->total_cost = startup_cost + run_cost;
314 }
315
316 /*
317  * cost_tidscan
318  *        Determines and returns the cost of scanning a relation using tid-s.
319  */
320 void
321 cost_tidscan(Path *path, RelOptInfo *baserel, List *tideval)
322 {
323         Cost            startup_cost = 0;
324         Cost            run_cost = 0;
325         Cost            cpu_per_tuple;
326         int                     ntuples = length(tideval);
327
328         if (!enable_tidscan)
329                 startup_cost += disable_cost;
330
331         /* disk costs --- assume each tuple on a different page */
332         run_cost += random_page_cost * ntuples;
333
334         /* CPU costs */
335         cpu_per_tuple = cpu_tuple_cost + baserel->baserestrictcost;
336         run_cost += cpu_per_tuple * ntuples;
337
338         path->startup_cost = startup_cost;
339         path->total_cost = startup_cost + run_cost;
340 }
341
342 /*
343  * cost_sort
344  *        Determines and returns the cost of sorting a relation.
345  *
346  * The cost of supplying the input data is NOT included; the caller should
347  * add that cost to both startup and total costs returned from this routine!
348  *
349  * If the total volume of data to sort is less than SortMem, we will do
350  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
351  * comparisons for t tuples.
352  *
353  * If the total volume exceeds SortMem, we switch to a tape-style merge
354  * algorithm.  There will still be about t*log2(t) tuple comparisons in
355  * total, but we will also need to write and read each tuple once per
356  * merge pass.  We expect about ceil(log6(r)) merge passes where r is the
357  * number of initial runs formed (log6 because tuplesort.c uses six-tape
358  * merging).  Since the average initial run should be about twice SortMem,
359  * we have
360  *              disk traffic = 2 * relsize * ceil(log6(p / (2*SortMem)))
361  *              cpu = comparison_cost * t * log2(t)
362  *
363  * The disk traffic is assumed to be half sequential and half random
364  * accesses (XXX can't we refine that guess?)
365  *
366  * We charge two operator evals per tuple comparison, which should be in
367  * the right ballpark in most cases.
368  *
369  * 'pathkeys' is a list of sort keys
370  * 'tuples' is the number of tuples in the relation
371  * 'width' is the average tuple width in bytes
372  *
373  * NOTE: some callers currently pass NIL for pathkeys because they
374  * can't conveniently supply the sort keys.  Since this routine doesn't
375  * currently do anything with pathkeys anyway, that doesn't matter...
376  * but if it ever does, it should react gracefully to lack of key data.
377  */
378 void
379 cost_sort(Path *path, List *pathkeys, double tuples, int width)
380 {
381         Cost            startup_cost = 0;
382         Cost            run_cost = 0;
383         double          nbytes = relation_byte_size(tuples, width);
384         long            sortmembytes = SortMem * 1024L;
385
386         if (!enable_sort)
387                 startup_cost += disable_cost;
388
389         /*
390          * We want to be sure the cost of a sort is never estimated as zero,
391          * even if passed-in tuple count is zero.  Besides, mustn't do
392          * log(0)...
393          */
394         if (tuples < 2.0)
395                 tuples = 2.0;
396
397         /*
398          * CPU costs
399          *
400          * Assume about two operator evals per tuple comparison and N log2 N
401          * comparisons
402          */
403         startup_cost += 2.0 * cpu_operator_cost * tuples * LOG2(tuples);
404
405         /* disk costs */
406         if (nbytes > sortmembytes)
407         {
408                 double          npages = ceil(nbytes / BLCKSZ);
409                 double          nruns = nbytes / (sortmembytes * 2);
410                 double          log_runs = ceil(LOG6(nruns));
411                 double          npageaccesses;
412
413                 if (log_runs < 1.0)
414                         log_runs = 1.0;
415                 npageaccesses = 2.0 * npages * log_runs;
416                 /* Assume half are sequential (cost 1), half are not */
417                 startup_cost += npageaccesses *
418                         (1.0 + cost_nonsequential_access(npages)) * 0.5;
419         }
420
421         /*
422          * Note: should we bother to assign a nonzero run_cost to reflect the
423          * overhead of extracting tuples from the sort result?  Probably not
424          * worth worrying about.
425          */
426         path->startup_cost = startup_cost;
427         path->total_cost = startup_cost + run_cost;
428 }
429
430
431 /*
432  * cost_nestloop
433  *        Determines and returns the cost of joining two relations using the
434  *        nested loop algorithm.
435  *
436  * 'outer_path' is the path for the outer relation
437  * 'inner_path' is the path for the inner relation
438  * 'restrictlist' are the RestrictInfo nodes to be applied at the join
439  */
440 void
441 cost_nestloop(Path *path,
442                           Path *outer_path,
443                           Path *inner_path,
444                           List *restrictlist)
445 {
446         Cost            startup_cost = 0;
447         Cost            run_cost = 0;
448         Cost            cpu_per_tuple;
449         double          ntuples;
450
451         if (!enable_nestloop)
452                 startup_cost += disable_cost;
453
454         /* cost of source data */
455
456         /*
457          * NOTE: we assume that the inner path's startup_cost is paid once,
458          * not over again on each restart.      This is certainly correct if the
459          * inner path is materialized.  Are there any cases where it is wrong?
460          */
461         startup_cost += outer_path->startup_cost + inner_path->startup_cost;
462         run_cost += outer_path->total_cost - outer_path->startup_cost;
463         run_cost += outer_path->parent->rows *
464                 (inner_path->total_cost - inner_path->startup_cost);
465
466         /*
467          * Number of tuples processed (not number emitted!).  If inner path is
468          * an indexscan, be sure to use its estimated output row count, which
469          * may be lower than the restriction-clause-only row count of its
470          * parent.
471          */
472         if (IsA(inner_path, IndexPath))
473                 ntuples = ((IndexPath *) inner_path)->rows;
474         else
475                 ntuples = inner_path->parent->rows;
476         ntuples *= outer_path->parent->rows;
477
478         /* CPU costs */
479         cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
480         run_cost += cpu_per_tuple * ntuples;
481
482         path->startup_cost = startup_cost;
483         path->total_cost = startup_cost + run_cost;
484 }
485
486 /*
487  * cost_mergejoin
488  *        Determines and returns the cost of joining two relations using the
489  *        merge join algorithm.
490  *
491  * 'outer_path' is the path for the outer relation
492  * 'inner_path' is the path for the inner relation
493  * 'restrictlist' are the RestrictInfo nodes to be applied at the join
494  * 'outersortkeys' and 'innersortkeys' are lists of the keys to be used
495  *                              to sort the outer and inner relations, or NIL if no explicit
496  *                              sort is needed because the source path is already ordered
497  */
498 void
499 cost_mergejoin(Path *path,
500                            Path *outer_path,
501                            Path *inner_path,
502                            List *restrictlist,
503                            List *outersortkeys,
504                            List *innersortkeys)
505 {
506         Cost            startup_cost = 0;
507         Cost            run_cost = 0;
508         Cost            cpu_per_tuple;
509         double          ntuples;
510         Path            sort_path;              /* dummy for result of cost_sort */
511
512         if (!enable_mergejoin)
513                 startup_cost += disable_cost;
514
515         /* cost of source data */
516
517         /*
518          * Note we are assuming that each source tuple is fetched just once,
519          * which is not right in the presence of equal keys.  If we had a way
520          * of estimating the proportion of equal keys, we could apply a
521          * correction factor...
522          */
523         if (outersortkeys)                      /* do we need to sort outer? */
524         {
525                 startup_cost += outer_path->total_cost;
526                 cost_sort(&sort_path,
527                                   outersortkeys,
528                                   outer_path->parent->rows,
529                                   outer_path->parent->width);
530                 startup_cost += sort_path.startup_cost;
531                 run_cost += sort_path.total_cost - sort_path.startup_cost;
532         }
533         else
534         {
535                 startup_cost += outer_path->startup_cost;
536                 run_cost += outer_path->total_cost - outer_path->startup_cost;
537         }
538
539         if (innersortkeys)                      /* do we need to sort inner? */
540         {
541                 startup_cost += inner_path->total_cost;
542                 cost_sort(&sort_path,
543                                   innersortkeys,
544                                   inner_path->parent->rows,
545                                   inner_path->parent->width);
546                 startup_cost += sort_path.startup_cost;
547                 run_cost += sort_path.total_cost - sort_path.startup_cost;
548         }
549         else
550         {
551                 startup_cost += inner_path->startup_cost;
552                 run_cost += inner_path->total_cost - inner_path->startup_cost;
553         }
554
555         /*
556          * Estimate the number of tuples to be processed in the mergejoin
557          * itself as one per tuple in the two source relations.  This could be
558          * a drastic underestimate if there are many equal-keyed tuples in
559          * either relation, but we have no good way of estimating that...
560          */
561         ntuples = outer_path->parent->rows + inner_path->parent->rows;
562
563         /* CPU costs */
564         cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
565         run_cost += cpu_per_tuple * ntuples;
566
567         path->startup_cost = startup_cost;
568         path->total_cost = startup_cost + run_cost;
569 }
570
571 /*
572  * cost_hashjoin
573  *        Determines and returns the cost of joining two relations using the
574  *        hash join algorithm.
575  *
576  * 'outer_path' is the path for the outer relation
577  * 'inner_path' is the path for the inner relation
578  * 'restrictlist' are the RestrictInfo nodes to be applied at the join
579  * 'innerdisbursion' is an estimate of the disbursion statistic
580  *                              for the inner hash key.
581  */
582 void
583 cost_hashjoin(Path *path,
584                           Path *outer_path,
585                           Path *inner_path,
586                           List *restrictlist,
587                           Selectivity innerdisbursion)
588 {
589         Cost            startup_cost = 0;
590         Cost            run_cost = 0;
591         Cost            cpu_per_tuple;
592         double          ntuples;
593         double          outerbytes = relation_byte_size(outer_path->parent->rows,
594                                                                                           outer_path->parent->width);
595         double          innerbytes = relation_byte_size(inner_path->parent->rows,
596                                                                                           inner_path->parent->width);
597         long            hashtablebytes = SortMem * 1024L;
598
599         if (!enable_hashjoin)
600                 startup_cost += disable_cost;
601
602         /* cost of source data */
603         startup_cost += outer_path->startup_cost;
604         run_cost += outer_path->total_cost - outer_path->startup_cost;
605         startup_cost += inner_path->total_cost;
606
607         /* cost of computing hash function: must do it once per input tuple */
608         startup_cost += cpu_operator_cost * inner_path->parent->rows;
609         run_cost += cpu_operator_cost * outer_path->parent->rows;
610
611         /*
612          * The number of tuple comparisons needed is the number of outer
613          * tuples times the typical hash bucket size.  nodeHash.c tries for
614          * average bucket loading of NTUP_PER_BUCKET, but that goal will
615          * be reached only if data values are uniformly distributed among
616          * the buckets.  To be conservative, we scale up the target bucket
617          * size by the number of inner rows times inner disbursion, giving
618          * an estimate of the typical number of duplicates of each value.
619          * We then charge one cpu_operator_cost per tuple comparison.
620          */
621         run_cost += cpu_operator_cost * outer_path->parent->rows *
622                 NTUP_PER_BUCKET * ceil(inner_path->parent->rows * innerdisbursion);
623
624         /*
625          * Estimate the number of tuples that get through the hashing filter
626          * as one per tuple in the two source relations.  This could be a
627          * drastic underestimate if there are many equal-keyed tuples in
628          * either relation, but we have no good way of estimating that...
629          */
630         ntuples = outer_path->parent->rows + inner_path->parent->rows;
631
632         /* CPU costs */
633         cpu_per_tuple = cpu_tuple_cost + cost_qual_eval(restrictlist);
634         run_cost += cpu_per_tuple * ntuples;
635
636         /*
637          * if inner relation is too big then we will need to "batch" the join,
638          * which implies writing and reading most of the tuples to disk an
639          * extra time.  Charge one cost unit per page of I/O (correct since it
640          * should be nice and sequential...).  Writing the inner rel counts as
641          * startup cost, all the rest as run cost.
642          */
643         if (innerbytes > hashtablebytes)
644         {
645                 double          outerpages = page_size(outer_path->parent->rows,
646                                                                                    outer_path->parent->width);
647                 double          innerpages = page_size(inner_path->parent->rows,
648                                                                                    inner_path->parent->width);
649
650                 startup_cost += innerpages;
651                 run_cost += innerpages + 2 * outerpages;
652         }
653
654         /*
655          * Bias against putting larger relation on inside.      We don't want an
656          * absolute prohibition, though, since larger relation might have
657          * better disbursion --- and we can't trust the size estimates
658          * unreservedly, anyway.  Instead, inflate the startup cost by the
659          * square root of the size ratio.  (Why square root?  No real good
660          * reason, but it seems reasonable...)
661          */
662         if (innerbytes > outerbytes && outerbytes > 0)
663                 startup_cost *= sqrt(innerbytes / outerbytes);
664
665         path->startup_cost = startup_cost;
666         path->total_cost = startup_cost + run_cost;
667 }
668
669
670 /*
671  * cost_qual_eval
672  *              Estimate the CPU cost of evaluating a WHERE clause (once).
673  *              The input can be either an implicitly-ANDed list of boolean
674  *              expressions, or a list of RestrictInfo nodes.
675  */
676 Cost
677 cost_qual_eval(List *quals)
678 {
679         Cost            total = 0;
680
681         cost_qual_eval_walker((Node *) quals, &total);
682         return total;
683 }
684
685 static bool
686 cost_qual_eval_walker(Node *node, Cost *total)
687 {
688         if (node == NULL)
689                 return false;
690
691         /*
692          * Our basic strategy is to charge one cpu_operator_cost for each
693          * operator or function node in the given tree.  Vars and Consts are
694          * charged zero, and so are boolean operators (AND, OR, NOT).
695          * Simplistic, but a lot better than no model at all.
696          *
697          * Should we try to account for the possibility of short-circuit
698          * evaluation of AND/OR?
699          */
700         if (IsA(node, Expr))
701         {
702                 Expr       *expr = (Expr *) node;
703
704                 switch (expr->opType)
705                 {
706                         case OP_EXPR:
707                         case FUNC_EXPR:
708                                 *total += cpu_operator_cost;
709                                 break;
710                         case OR_EXPR:
711                         case AND_EXPR:
712                         case NOT_EXPR:
713                                 break;
714                         case SUBPLAN_EXPR:
715
716                                 /*
717                                  * A subplan node in an expression indicates that the
718                                  * subplan will be executed on each evaluation, so charge
719                                  * accordingly. (We assume that sub-selects that can be
720                                  * executed as InitPlans have already been removed from
721                                  * the expression.)
722                                  *
723                                  * NOTE: this logic should agree with the estimates used by
724                                  * make_subplan() in plan/subselect.c.
725                                  */
726                                 {
727                                         SubPlan    *subplan = (SubPlan *) expr->oper;
728                                         Plan       *plan = subplan->plan;
729                                         Cost            subcost;
730
731                                         if (subplan->sublink->subLinkType == EXISTS_SUBLINK)
732                                         {
733                                                 /* we only need to fetch 1 tuple */
734                                                 subcost = plan->startup_cost +
735                                                         (plan->total_cost - plan->startup_cost) / plan->plan_rows;
736                                         }
737                                         else if (subplan->sublink->subLinkType == ALL_SUBLINK ||
738                                                          subplan->sublink->subLinkType == ANY_SUBLINK)
739                                         {
740                                                 /* assume we need 50% of the tuples */
741                                                 subcost = plan->startup_cost +
742                                                         0.50 * (plan->total_cost - plan->startup_cost);
743                                                 /* XXX what if subplan has been materialized? */
744                                         }
745                                         else
746                                         {
747                                                 /* assume we need all tuples */
748                                                 subcost = plan->total_cost;
749                                         }
750                                         *total += subcost;
751                                 }
752                                 break;
753                 }
754                 /* fall through to examine args of Expr node */
755         }
756
757         /*
758          * expression_tree_walker doesn't know what to do with RestrictInfo
759          * nodes, but we just want to recurse through them.
760          */
761         if (IsA(node, RestrictInfo))
762         {
763                 RestrictInfo *restrictinfo = (RestrictInfo *) node;
764
765                 return cost_qual_eval_walker((Node *) restrictinfo->clause, total);
766         }
767         /* Otherwise, recurse. */
768         return expression_tree_walker(node, cost_qual_eval_walker,
769                                                                   (void *) total);
770 }
771
772
773 /*
774  * set_baserel_size_estimates
775  *              Set the size estimates for the given base relation.
776  *
777  * The rel's targetlist and restrictinfo list must have been constructed
778  * already.
779  *
780  * We set the following fields of the rel node:
781  *      rows: the estimated number of output tuples (after applying
782  *                restriction clauses).
783  *      width: the estimated average output tuple width in bytes.
784  *      baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
785  */
786 void
787 set_baserel_size_estimates(Query *root, RelOptInfo *rel)
788 {
789         /* Should only be applied to base relations */
790         Assert(length(rel->relids) == 1);
791
792         rel->rows = rel->tuples *
793                 restrictlist_selectivity(root,
794                                                                  rel->baserestrictinfo,
795                                                                  lfirsti(rel->relids));
796
797         /*
798          * Force estimate to be at least one row, to make explain output look
799          * better and to avoid possible divide-by-zero when interpolating
800          * cost.
801          */
802         if (rel->rows < 1.0)
803                 rel->rows = 1.0;
804
805         rel->baserestrictcost = cost_qual_eval(rel->baserestrictinfo);
806
807         set_rel_width(root, rel);
808 }
809
810 /*
811  * set_joinrel_size_estimates
812  *              Set the size estimates for the given join relation.
813  *
814  * The rel's targetlist must have been constructed already, and a
815  * restriction clause list that matches the given component rels must
816  * be provided.
817  *
818  * Since there is more than one way to make a joinrel for more than two
819  * base relations, the results we get here could depend on which component
820  * rel pair is provided.  In theory we should get the same answers no matter
821  * which pair is provided; in practice, since the selectivity estimation
822  * routines don't handle all cases equally well, we might not.  But there's
823  * not much to be done about it.  (Would it make sense to repeat the
824  * calculations for each pair of input rels that's encountered, and somehow
825  * average the results?  Probably way more trouble than it's worth.)
826  *
827  * We set the same relnode fields as set_baserel_size_estimates() does.
828  */
829 void
830 set_joinrel_size_estimates(Query *root, RelOptInfo *rel,
831                                                    RelOptInfo *outer_rel,
832                                                    RelOptInfo *inner_rel,
833                                                    List *restrictlist)
834 {
835         double          temp;
836
837         /* cartesian product */
838         temp = outer_rel->rows * inner_rel->rows;
839
840         /*
841          * Apply join restrictivity.  Note that we are only considering
842          * clauses that become restriction clauses at this join level; we are
843          * not double-counting them because they were not considered in
844          * estimating the sizes of the component rels.
845          */
846         temp *= restrictlist_selectivity(root,
847                                                                          restrictlist,
848                                                                          0);
849
850         /*
851          * Force estimate to be at least one row, to make explain output look
852          * better and to avoid possible divide-by-zero when interpolating
853          * cost.
854          */
855         if (temp < 1.0)
856                 temp = 1.0;
857         rel->rows = temp;
858
859         /*
860          * We could apply set_rel_width() to compute the output tuple width
861          * from scratch, but at present it's always just the sum of the input
862          * widths, so why work harder than necessary?  If relnode.c is ever
863          * taught to remove unneeded columns from join targetlists, go back to
864          * using set_rel_width here.
865          */
866         rel->width = outer_rel->width + inner_rel->width;
867 }
868
869 /*
870  * set_rel_width
871  *              Set the estimated output width of the relation.
872  */
873 static void
874 set_rel_width(Query *root, RelOptInfo *rel)
875 {
876         int                     tuple_width = 0;
877         List       *tle;
878
879         foreach(tle, rel->targetlist)
880                 tuple_width += compute_attribute_width((TargetEntry *) lfirst(tle));
881         Assert(tuple_width >= 0);
882         rel->width = tuple_width;
883 }
884
885 /*
886  * compute_attribute_width
887  *        Given a target list entry, find the size in bytes of the attribute.
888  *
889  *        If a field is variable-length, we make a default assumption.  Would be
890  *        better if VACUUM recorded some stats about the average field width...
891  *        also, we have access to the atttypmod, but fail to use it...
892  */
893 static int
894 compute_attribute_width(TargetEntry *tlistentry)
895 {
896         int                     width = get_typlen(tlistentry->resdom->restype);
897
898         if (width < 0)
899                 return _DEFAULT_ATTRIBUTE_WIDTH_;
900         else
901                 return width;
902 }
903
904 /*
905  * relation_byte_size
906  *        Estimate the storage space in bytes for a given number of tuples
907  *        of a given width (size in bytes).
908  */
909 static double
910 relation_byte_size(double tuples, int width)
911 {
912         return tuples * ((double) (width + sizeof(HeapTupleData)));
913 }
914
915 /*
916  * page_size
917  *        Returns an estimate of the number of pages covered by a given
918  *        number of tuples of a given width (size in bytes).
919  */
920 static double
921 page_size(double tuples, int width)
922 {
923         return ceil(relation_byte_size(tuples, width) / BLCKSZ);
924 }