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