Header And Logo

PostgreSQL
| The world's most advanced open source database.

costsize.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * costsize.c
00004  *    Routines to compute (and set) relation sizes and path costs
00005  *
00006  * Path costs are measured in arbitrary units established by these basic
00007  * parameters:
00008  *
00009  *  seq_page_cost       Cost of a sequential page fetch
00010  *  random_page_cost    Cost of a non-sequential page fetch
00011  *  cpu_tuple_cost      Cost of typical CPU time to process a tuple
00012  *  cpu_index_tuple_cost  Cost of typical CPU time to process an index tuple
00013  *  cpu_operator_cost   Cost of CPU time to execute an operator or function
00014  *
00015  * We expect that the kernel will typically do some amount of read-ahead
00016  * optimization; this in conjunction with seek costs means that seq_page_cost
00017  * is normally considerably less than random_page_cost.  (However, if the
00018  * database is fully cached in RAM, it is reasonable to set them equal.)
00019  *
00020  * We also use a rough estimate "effective_cache_size" of the number of
00021  * disk pages in Postgres + OS-level disk cache.  (We can't simply use
00022  * NBuffers for this purpose because that would ignore the effects of
00023  * the kernel's disk cache.)
00024  *
00025  * Obviously, taking constants for these values is an oversimplification,
00026  * but it's tough enough to get any useful estimates even at this level of
00027  * detail.  Note that all of these parameters are user-settable, in case
00028  * the default values are drastically off for a particular platform.
00029  *
00030  * seq_page_cost and random_page_cost can also be overridden for an individual
00031  * tablespace, in case some data is on a fast disk and other data is on a slow
00032  * disk.  Per-tablespace overrides never apply to temporary work files such as
00033  * an external sort or a materialize node that overflows work_mem.
00034  *
00035  * We compute two separate costs for each path:
00036  *      total_cost: total estimated cost to fetch all tuples
00037  *      startup_cost: cost that is expended before first tuple is fetched
00038  * In some scenarios, such as when there is a LIMIT or we are implementing
00039  * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
00040  * path's result.  A caller can estimate the cost of fetching a partial
00041  * result by interpolating between startup_cost and total_cost.  In detail:
00042  *      actual_cost = startup_cost +
00043  *          (total_cost - startup_cost) * tuples_to_fetch / path->rows;
00044  * Note that a base relation's rows count (and, by extension, plan_rows for
00045  * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
00046  * that this equation works properly.  (Also, these routines guarantee not to
00047  * set the rows count to zero, so there will be no zero divide.)  The LIMIT is
00048  * applied as a top-level plan node.
00049  *
00050  * For largely historical reasons, most of the routines in this module use
00051  * the passed result Path only to store their results (rows, startup_cost and
00052  * total_cost) into.  All the input data they need is passed as separate
00053  * parameters, even though much of it could be extracted from the Path.
00054  * An exception is made for the cost_XXXjoin() routines, which expect all
00055  * the other fields of the passed XXXPath to be filled in, and similarly
00056  * cost_index() assumes the passed IndexPath is valid except for its output
00057  * values.
00058  *
00059  *
00060  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00061  * Portions Copyright (c) 1994, Regents of the University of California
00062  *
00063  * IDENTIFICATION
00064  *    src/backend/optimizer/path/costsize.c
00065  *
00066  *-------------------------------------------------------------------------
00067  */
00068 
00069 #include "postgres.h"
00070 
00071 #ifdef _MSC_VER
00072 #include <float.h> /* for _isnan */
00073 #endif
00074 #include <math.h>
00075 
00076 #include "access/htup_details.h"
00077 #include "executor/executor.h"
00078 #include "executor/nodeHash.h"
00079 #include "miscadmin.h"
00080 #include "nodes/nodeFuncs.h"
00081 #include "optimizer/clauses.h"
00082 #include "optimizer/cost.h"
00083 #include "optimizer/pathnode.h"
00084 #include "optimizer/paths.h"
00085 #include "optimizer/placeholder.h"
00086 #include "optimizer/plancat.h"
00087 #include "optimizer/planmain.h"
00088 #include "optimizer/restrictinfo.h"
00089 #include "parser/parsetree.h"
00090 #include "utils/lsyscache.h"
00091 #include "utils/selfuncs.h"
00092 #include "utils/spccache.h"
00093 #include "utils/tuplesort.h"
00094 
00095 
00096 #define LOG2(x)  (log(x) / 0.693147180559945)
00097 
00098 
00099 double      seq_page_cost = DEFAULT_SEQ_PAGE_COST;
00100 double      random_page_cost = DEFAULT_RANDOM_PAGE_COST;
00101 double      cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
00102 double      cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
00103 double      cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
00104 
00105 int         effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
00106 
00107 Cost        disable_cost = 1.0e10;
00108 
00109 bool        enable_seqscan = true;
00110 bool        enable_indexscan = true;
00111 bool        enable_indexonlyscan = true;
00112 bool        enable_bitmapscan = true;
00113 bool        enable_tidscan = true;
00114 bool        enable_sort = true;
00115 bool        enable_hashagg = true;
00116 bool        enable_nestloop = true;
00117 bool        enable_material = true;
00118 bool        enable_mergejoin = true;
00119 bool        enable_hashjoin = true;
00120 
00121 typedef struct
00122 {
00123     PlannerInfo *root;
00124     QualCost    total;
00125 } cost_qual_eval_context;
00126 
00127 static MergeScanSelCache *cached_scansel(PlannerInfo *root,
00128                RestrictInfo *rinfo,
00129                PathKey *pathkey);
00130 static void cost_rescan(PlannerInfo *root, Path *path,
00131             Cost *rescan_startup_cost, Cost *rescan_total_cost);
00132 static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
00133 static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
00134                           ParamPathInfo *param_info,
00135                           QualCost *qpqual_cost);
00136 static bool has_indexed_join_quals(NestPath *joinpath);
00137 static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
00138                    List *quals);
00139 static double calc_joinrel_size_estimate(PlannerInfo *root,
00140                            double outer_rows,
00141                            double inner_rows,
00142                            SpecialJoinInfo *sjinfo,
00143                            List *restrictlist);
00144 static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
00145 static double relation_byte_size(double tuples, int width);
00146 static double page_size(double tuples, int width);
00147 
00148 
00149 /*
00150  * clamp_row_est
00151  *      Force a row-count estimate to a sane value.
00152  */
00153 double
00154 clamp_row_est(double nrows)
00155 {
00156     /*
00157      * Force estimate to be at least one row, to make explain output look
00158      * better and to avoid possible divide-by-zero when interpolating costs.
00159      * Make it an integer, too.
00160      */
00161     if (nrows <= 1.0)
00162         nrows = 1.0;
00163     else
00164         nrows = rint(nrows);
00165 
00166     return nrows;
00167 }
00168 
00169 
00170 /*
00171  * cost_seqscan
00172  *    Determines and returns the cost of scanning a relation sequentially.
00173  *
00174  * 'baserel' is the relation to be scanned
00175  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
00176  */
00177 void
00178 cost_seqscan(Path *path, PlannerInfo *root,
00179              RelOptInfo *baserel, ParamPathInfo *param_info)
00180 {
00181     Cost        startup_cost = 0;
00182     Cost        run_cost = 0;
00183     double      spc_seq_page_cost;
00184     QualCost    qpqual_cost;
00185     Cost        cpu_per_tuple;
00186 
00187     /* Should only be applied to base relations */
00188     Assert(baserel->relid > 0);
00189     Assert(baserel->rtekind == RTE_RELATION);
00190 
00191     /* Mark the path with the correct row estimate */
00192     if (param_info)
00193         path->rows = param_info->ppi_rows;
00194     else
00195         path->rows = baserel->rows;
00196 
00197     if (!enable_seqscan)
00198         startup_cost += disable_cost;
00199 
00200     /* fetch estimated page cost for tablespace containing table */
00201     get_tablespace_page_costs(baserel->reltablespace,
00202                               NULL,
00203                               &spc_seq_page_cost);
00204 
00205     /*
00206      * disk costs
00207      */
00208     run_cost += spc_seq_page_cost * baserel->pages;
00209 
00210     /* CPU costs */
00211     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
00212 
00213     startup_cost += qpqual_cost.startup;
00214     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
00215     run_cost += cpu_per_tuple * baserel->tuples;
00216 
00217     path->startup_cost = startup_cost;
00218     path->total_cost = startup_cost + run_cost;
00219 }
00220 
00221 /*
00222  * cost_index
00223  *    Determines and returns the cost of scanning a relation using an index.
00224  *
00225  * 'path' describes the indexscan under consideration, and is complete
00226  *      except for the fields to be set by this routine
00227  * 'loop_count' is the number of repetitions of the indexscan to factor into
00228  *      estimates of caching behavior
00229  *
00230  * In addition to rows, startup_cost and total_cost, cost_index() sets the
00231  * path's indextotalcost and indexselectivity fields.  These values will be
00232  * needed if the IndexPath is used in a BitmapIndexScan.
00233  *
00234  * NOTE: path->indexquals must contain only clauses usable as index
00235  * restrictions.  Any additional quals evaluated as qpquals may reduce the
00236  * number of returned tuples, but they won't reduce the number of tuples
00237  * we have to fetch from the table, so they don't reduce the scan cost.
00238  */
00239 void
00240 cost_index(IndexPath *path, PlannerInfo *root, double loop_count)
00241 {
00242     IndexOptInfo *index = path->indexinfo;
00243     RelOptInfo *baserel = index->rel;
00244     bool        indexonly = (path->path.pathtype == T_IndexOnlyScan);
00245     List       *allclauses;
00246     Cost        startup_cost = 0;
00247     Cost        run_cost = 0;
00248     Cost        indexStartupCost;
00249     Cost        indexTotalCost;
00250     Selectivity indexSelectivity;
00251     double      indexCorrelation,
00252                 csquared;
00253     double      spc_seq_page_cost,
00254                 spc_random_page_cost;
00255     Cost        min_IO_cost,
00256                 max_IO_cost;
00257     QualCost    qpqual_cost;
00258     Cost        cpu_per_tuple;
00259     double      tuples_fetched;
00260     double      pages_fetched;
00261 
00262     /* Should only be applied to base relations */
00263     Assert(IsA(baserel, RelOptInfo) &&
00264            IsA(index, IndexOptInfo));
00265     Assert(baserel->relid > 0);
00266     Assert(baserel->rtekind == RTE_RELATION);
00267 
00268     /* Mark the path with the correct row estimate */
00269     if (path->path.param_info)
00270     {
00271         path->path.rows = path->path.param_info->ppi_rows;
00272         /* also get the set of clauses that should be enforced by the scan */
00273         allclauses = list_concat(list_copy(path->path.param_info->ppi_clauses),
00274                                  baserel->baserestrictinfo);
00275     }
00276     else
00277     {
00278         path->path.rows = baserel->rows;
00279         /* allclauses should just be the rel's restriction clauses */
00280         allclauses = baserel->baserestrictinfo;
00281     }
00282 
00283     if (!enable_indexscan)
00284         startup_cost += disable_cost;
00285     /* we don't need to check enable_indexonlyscan; indxpath.c does that */
00286 
00287     /*
00288      * Call index-access-method-specific code to estimate the processing cost
00289      * for scanning the index, as well as the selectivity of the index (ie,
00290      * the fraction of main-table tuples we will have to retrieve) and its
00291      * correlation to the main-table tuple order.
00292      */
00293     OidFunctionCall7(index->amcostestimate,
00294                      PointerGetDatum(root),
00295                      PointerGetDatum(path),
00296                      Float8GetDatum(loop_count),
00297                      PointerGetDatum(&indexStartupCost),
00298                      PointerGetDatum(&indexTotalCost),
00299                      PointerGetDatum(&indexSelectivity),
00300                      PointerGetDatum(&indexCorrelation));
00301 
00302     /*
00303      * Save amcostestimate's results for possible use in bitmap scan planning.
00304      * We don't bother to save indexStartupCost or indexCorrelation, because a
00305      * bitmap scan doesn't care about either.
00306      */
00307     path->indextotalcost = indexTotalCost;
00308     path->indexselectivity = indexSelectivity;
00309 
00310     /* all costs for touching index itself included here */
00311     startup_cost += indexStartupCost;
00312     run_cost += indexTotalCost - indexStartupCost;
00313 
00314     /* estimate number of main-table tuples fetched */
00315     tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
00316 
00317     /* fetch estimated page costs for tablespace containing table */
00318     get_tablespace_page_costs(baserel->reltablespace,
00319                               &spc_random_page_cost,
00320                               &spc_seq_page_cost);
00321 
00322     /*----------
00323      * Estimate number of main-table pages fetched, and compute I/O cost.
00324      *
00325      * When the index ordering is uncorrelated with the table ordering,
00326      * we use an approximation proposed by Mackert and Lohman (see
00327      * index_pages_fetched() for details) to compute the number of pages
00328      * fetched, and then charge spc_random_page_cost per page fetched.
00329      *
00330      * When the index ordering is exactly correlated with the table ordering
00331      * (just after a CLUSTER, for example), the number of pages fetched should
00332      * be exactly selectivity * table_size.  What's more, all but the first
00333      * will be sequential fetches, not the random fetches that occur in the
00334      * uncorrelated case.  So if the number of pages is more than 1, we
00335      * ought to charge
00336      *      spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
00337      * For partially-correlated indexes, we ought to charge somewhere between
00338      * these two estimates.  We currently interpolate linearly between the
00339      * estimates based on the correlation squared (XXX is that appropriate?).
00340      *
00341      * If it's an index-only scan, then we will not need to fetch any heap
00342      * pages for which the visibility map shows all tuples are visible.
00343      * Hence, reduce the estimated number of heap fetches accordingly.
00344      * We use the measured fraction of the entire heap that is all-visible,
00345      * which might not be particularly relevant to the subset of the heap
00346      * that this query will fetch; but it's not clear how to do better.
00347      *----------
00348      */
00349     if (loop_count > 1)
00350     {
00351         /*
00352          * For repeated indexscans, the appropriate estimate for the
00353          * uncorrelated case is to scale up the number of tuples fetched in
00354          * the Mackert and Lohman formula by the number of scans, so that we
00355          * estimate the number of pages fetched by all the scans; then
00356          * pro-rate the costs for one scan.  In this case we assume all the
00357          * fetches are random accesses.
00358          */
00359         pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
00360                                             baserel->pages,
00361                                             (double) index->pages,
00362                                             root);
00363 
00364         if (indexonly)
00365             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
00366 
00367         max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
00368 
00369         /*
00370          * In the perfectly correlated case, the number of pages touched by
00371          * each scan is selectivity * table_size, and we can use the Mackert
00372          * and Lohman formula at the page level to estimate how much work is
00373          * saved by caching across scans.  We still assume all the fetches are
00374          * random, though, which is an overestimate that's hard to correct for
00375          * without double-counting the cache effects.  (But in most cases
00376          * where such a plan is actually interesting, only one page would get
00377          * fetched per scan anyway, so it shouldn't matter much.)
00378          */
00379         pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
00380 
00381         pages_fetched = index_pages_fetched(pages_fetched * loop_count,
00382                                             baserel->pages,
00383                                             (double) index->pages,
00384                                             root);
00385 
00386         if (indexonly)
00387             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
00388 
00389         min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
00390     }
00391     else
00392     {
00393         /*
00394          * Normal case: apply the Mackert and Lohman formula, and then
00395          * interpolate between that and the correlation-derived result.
00396          */
00397         pages_fetched = index_pages_fetched(tuples_fetched,
00398                                             baserel->pages,
00399                                             (double) index->pages,
00400                                             root);
00401 
00402         if (indexonly)
00403             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
00404 
00405         /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
00406         max_IO_cost = pages_fetched * spc_random_page_cost;
00407 
00408         /* min_IO_cost is for the perfectly correlated case (csquared=1) */
00409         pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
00410 
00411         if (indexonly)
00412             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
00413 
00414         if (pages_fetched > 0)
00415         {
00416             min_IO_cost = spc_random_page_cost;
00417             if (pages_fetched > 1)
00418                 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
00419         }
00420         else
00421             min_IO_cost = 0;
00422     }
00423 
00424     /*
00425      * Now interpolate based on estimated index order correlation to get total
00426      * disk I/O cost for main table accesses.
00427      */
00428     csquared = indexCorrelation * indexCorrelation;
00429 
00430     run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
00431 
00432     /*
00433      * Estimate CPU costs per tuple.
00434      *
00435      * What we want here is cpu_tuple_cost plus the evaluation costs of any
00436      * qual clauses that we have to evaluate as qpquals.  We approximate that
00437      * list as allclauses minus any clauses appearing in indexquals.  (We
00438      * assume that pointer equality is enough to recognize duplicate
00439      * RestrictInfos.)  This method neglects some considerations such as
00440      * clauses that needn't be checked because they are implied by a partial
00441      * index's predicate.  It does not seem worth the cycles to try to factor
00442      * those things in at this stage, even though createplan.c will take pains
00443      * to remove such unnecessary clauses from the qpquals list if this path
00444      * is selected for use.
00445      */
00446     cost_qual_eval(&qpqual_cost,
00447                    list_difference_ptr(allclauses, path->indexquals),
00448                    root);
00449 
00450     startup_cost += qpqual_cost.startup;
00451     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
00452 
00453     run_cost += cpu_per_tuple * tuples_fetched;
00454 
00455     path->path.startup_cost = startup_cost;
00456     path->path.total_cost = startup_cost + run_cost;
00457 }
00458 
00459 /*
00460  * index_pages_fetched
00461  *    Estimate the number of pages actually fetched after accounting for
00462  *    cache effects.
00463  *
00464  * We use an approximation proposed by Mackert and Lohman, "Index Scans
00465  * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
00466  * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
00467  * The Mackert and Lohman approximation is that the number of pages
00468  * fetched is
00469  *  PF =
00470  *      min(2TNs/(2T+Ns), T)            when T <= b
00471  *      2TNs/(2T+Ns)                    when T > b and Ns <= 2Tb/(2T-b)
00472  *      b + (Ns - 2Tb/(2T-b))*(T-b)/T   when T > b and Ns > 2Tb/(2T-b)
00473  * where
00474  *      T = # pages in table
00475  *      N = # tuples in table
00476  *      s = selectivity = fraction of table to be scanned
00477  *      b = # buffer pages available (we include kernel space here)
00478  *
00479  * We assume that effective_cache_size is the total number of buffer pages
00480  * available for the whole query, and pro-rate that space across all the
00481  * tables in the query and the index currently under consideration.  (This
00482  * ignores space needed for other indexes used by the query, but since we
00483  * don't know which indexes will get used, we can't estimate that very well;
00484  * and in any case counting all the tables may well be an overestimate, since
00485  * depending on the join plan not all the tables may be scanned concurrently.)
00486  *
00487  * The product Ns is the number of tuples fetched; we pass in that
00488  * product rather than calculating it here.  "pages" is the number of pages
00489  * in the object under consideration (either an index or a table).
00490  * "index_pages" is the amount to add to the total table space, which was
00491  * computed for us by query_planner.
00492  *
00493  * Caller is expected to have ensured that tuples_fetched is greater than zero
00494  * and rounded to integer (see clamp_row_est).  The result will likewise be
00495  * greater than zero and integral.
00496  */
00497 double
00498 index_pages_fetched(double tuples_fetched, BlockNumber pages,
00499                     double index_pages, PlannerInfo *root)
00500 {
00501     double      pages_fetched;
00502     double      total_pages;
00503     double      T,
00504                 b;
00505 
00506     /* T is # pages in table, but don't allow it to be zero */
00507     T = (pages > 1) ? (double) pages : 1.0;
00508 
00509     /* Compute number of pages assumed to be competing for cache space */
00510     total_pages = root->total_table_pages + index_pages;
00511     total_pages = Max(total_pages, 1.0);
00512     Assert(T <= total_pages);
00513 
00514     /* b is pro-rated share of effective_cache_size */
00515     b = (double) effective_cache_size *T / total_pages;
00516 
00517     /* force it positive and integral */
00518     if (b <= 1.0)
00519         b = 1.0;
00520     else
00521         b = ceil(b);
00522 
00523     /* This part is the Mackert and Lohman formula */
00524     if (T <= b)
00525     {
00526         pages_fetched =
00527             (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
00528         if (pages_fetched >= T)
00529             pages_fetched = T;
00530         else
00531             pages_fetched = ceil(pages_fetched);
00532     }
00533     else
00534     {
00535         double      lim;
00536 
00537         lim = (2.0 * T * b) / (2.0 * T - b);
00538         if (tuples_fetched <= lim)
00539         {
00540             pages_fetched =
00541                 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
00542         }
00543         else
00544         {
00545             pages_fetched =
00546                 b + (tuples_fetched - lim) * (T - b) / T;
00547         }
00548         pages_fetched = ceil(pages_fetched);
00549     }
00550     return pages_fetched;
00551 }
00552 
00553 /*
00554  * get_indexpath_pages
00555  *      Determine the total size of the indexes used in a bitmap index path.
00556  *
00557  * Note: if the same index is used more than once in a bitmap tree, we will
00558  * count it multiple times, which perhaps is the wrong thing ... but it's
00559  * not completely clear, and detecting duplicates is difficult, so ignore it
00560  * for now.
00561  */
00562 static double
00563 get_indexpath_pages(Path *bitmapqual)
00564 {
00565     double      result = 0;
00566     ListCell   *l;
00567 
00568     if (IsA(bitmapqual, BitmapAndPath))
00569     {
00570         BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
00571 
00572         foreach(l, apath->bitmapquals)
00573         {
00574             result += get_indexpath_pages((Path *) lfirst(l));
00575         }
00576     }
00577     else if (IsA(bitmapqual, BitmapOrPath))
00578     {
00579         BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
00580 
00581         foreach(l, opath->bitmapquals)
00582         {
00583             result += get_indexpath_pages((Path *) lfirst(l));
00584         }
00585     }
00586     else if (IsA(bitmapqual, IndexPath))
00587     {
00588         IndexPath  *ipath = (IndexPath *) bitmapqual;
00589 
00590         result = (double) ipath->indexinfo->pages;
00591     }
00592     else
00593         elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
00594 
00595     return result;
00596 }
00597 
00598 /*
00599  * cost_bitmap_heap_scan
00600  *    Determines and returns the cost of scanning a relation using a bitmap
00601  *    index-then-heap plan.
00602  *
00603  * 'baserel' is the relation to be scanned
00604  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
00605  * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
00606  * 'loop_count' is the number of repetitions of the indexscan to factor into
00607  *      estimates of caching behavior
00608  *
00609  * Note: the component IndexPaths in bitmapqual should have been costed
00610  * using the same loop_count.
00611  */
00612 void
00613 cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
00614                       ParamPathInfo *param_info,
00615                       Path *bitmapqual, double loop_count)
00616 {
00617     Cost        startup_cost = 0;
00618     Cost        run_cost = 0;
00619     Cost        indexTotalCost;
00620     Selectivity indexSelectivity;
00621     QualCost    qpqual_cost;
00622     Cost        cpu_per_tuple;
00623     Cost        cost_per_page;
00624     double      tuples_fetched;
00625     double      pages_fetched;
00626     double      spc_seq_page_cost,
00627                 spc_random_page_cost;
00628     double      T;
00629 
00630     /* Should only be applied to base relations */
00631     Assert(IsA(baserel, RelOptInfo));
00632     Assert(baserel->relid > 0);
00633     Assert(baserel->rtekind == RTE_RELATION);
00634 
00635     /* Mark the path with the correct row estimate */
00636     if (param_info)
00637         path->rows = param_info->ppi_rows;
00638     else
00639         path->rows = baserel->rows;
00640 
00641     if (!enable_bitmapscan)
00642         startup_cost += disable_cost;
00643 
00644     /*
00645      * Fetch total cost of obtaining the bitmap, as well as its total
00646      * selectivity.
00647      */
00648     cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
00649 
00650     startup_cost += indexTotalCost;
00651 
00652     /* Fetch estimated page costs for tablespace containing table. */
00653     get_tablespace_page_costs(baserel->reltablespace,
00654                               &spc_random_page_cost,
00655                               &spc_seq_page_cost);
00656 
00657     /*
00658      * Estimate number of main-table pages fetched.
00659      */
00660     tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
00661 
00662     T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
00663 
00664     if (loop_count > 1)
00665     {
00666         /*
00667          * For repeated bitmap scans, scale up the number of tuples fetched in
00668          * the Mackert and Lohman formula by the number of scans, so that we
00669          * estimate the number of pages fetched by all the scans. Then
00670          * pro-rate for one scan.
00671          */
00672         pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
00673                                             baserel->pages,
00674                                             get_indexpath_pages(bitmapqual),
00675                                             root);
00676         pages_fetched /= loop_count;
00677     }
00678     else
00679     {
00680         /*
00681          * For a single scan, the number of heap pages that need to be fetched
00682          * is the same as the Mackert and Lohman formula for the case T <= b
00683          * (ie, no re-reads needed).
00684          */
00685         pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
00686     }
00687     if (pages_fetched >= T)
00688         pages_fetched = T;
00689     else
00690         pages_fetched = ceil(pages_fetched);
00691 
00692     /*
00693      * For small numbers of pages we should charge spc_random_page_cost
00694      * apiece, while if nearly all the table's pages are being read, it's more
00695      * appropriate to charge spc_seq_page_cost apiece.  The effect is
00696      * nonlinear, too. For lack of a better idea, interpolate like this to
00697      * determine the cost per page.
00698      */
00699     if (pages_fetched >= 2.0)
00700         cost_per_page = spc_random_page_cost -
00701             (spc_random_page_cost - spc_seq_page_cost)
00702             * sqrt(pages_fetched / T);
00703     else
00704         cost_per_page = spc_random_page_cost;
00705 
00706     run_cost += pages_fetched * cost_per_page;
00707 
00708     /*
00709      * Estimate CPU costs per tuple.
00710      *
00711      * Often the indexquals don't need to be rechecked at each tuple ... but
00712      * not always, especially not if there are enough tuples involved that the
00713      * bitmaps become lossy.  For the moment, just assume they will be
00714      * rechecked always.  This means we charge the full freight for all the
00715      * scan clauses.
00716      */
00717     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
00718 
00719     startup_cost += qpqual_cost.startup;
00720     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
00721 
00722     run_cost += cpu_per_tuple * tuples_fetched;
00723 
00724     path->startup_cost = startup_cost;
00725     path->total_cost = startup_cost + run_cost;
00726 }
00727 
00728 /*
00729  * cost_bitmap_tree_node
00730  *      Extract cost and selectivity from a bitmap tree node (index/and/or)
00731  */
00732 void
00733 cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
00734 {
00735     if (IsA(path, IndexPath))
00736     {
00737         *cost = ((IndexPath *) path)->indextotalcost;
00738         *selec = ((IndexPath *) path)->indexselectivity;
00739 
00740         /*
00741          * Charge a small amount per retrieved tuple to reflect the costs of
00742          * manipulating the bitmap.  This is mostly to make sure that a bitmap
00743          * scan doesn't look to be the same cost as an indexscan to retrieve a
00744          * single tuple.
00745          */
00746         *cost += 0.1 * cpu_operator_cost * path->rows;
00747     }
00748     else if (IsA(path, BitmapAndPath))
00749     {
00750         *cost = path->total_cost;
00751         *selec = ((BitmapAndPath *) path)->bitmapselectivity;
00752     }
00753     else if (IsA(path, BitmapOrPath))
00754     {
00755         *cost = path->total_cost;
00756         *selec = ((BitmapOrPath *) path)->bitmapselectivity;
00757     }
00758     else
00759     {
00760         elog(ERROR, "unrecognized node type: %d", nodeTag(path));
00761         *cost = *selec = 0;     /* keep compiler quiet */
00762     }
00763 }
00764 
00765 /*
00766  * cost_bitmap_and_node
00767  *      Estimate the cost of a BitmapAnd node
00768  *
00769  * Note that this considers only the costs of index scanning and bitmap
00770  * creation, not the eventual heap access.  In that sense the object isn't
00771  * truly a Path, but it has enough path-like properties (costs in particular)
00772  * to warrant treating it as one.  We don't bother to set the path rows field,
00773  * however.
00774  */
00775 void
00776 cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
00777 {
00778     Cost        totalCost;
00779     Selectivity selec;
00780     ListCell   *l;
00781 
00782     /*
00783      * We estimate AND selectivity on the assumption that the inputs are
00784      * independent.  This is probably often wrong, but we don't have the info
00785      * to do better.
00786      *
00787      * The runtime cost of the BitmapAnd itself is estimated at 100x
00788      * cpu_operator_cost for each tbm_intersect needed.  Probably too small,
00789      * definitely too simplistic?
00790      */
00791     totalCost = 0.0;
00792     selec = 1.0;
00793     foreach(l, path->bitmapquals)
00794     {
00795         Path       *subpath = (Path *) lfirst(l);
00796         Cost        subCost;
00797         Selectivity subselec;
00798 
00799         cost_bitmap_tree_node(subpath, &subCost, &subselec);
00800 
00801         selec *= subselec;
00802 
00803         totalCost += subCost;
00804         if (l != list_head(path->bitmapquals))
00805             totalCost += 100.0 * cpu_operator_cost;
00806     }
00807     path->bitmapselectivity = selec;
00808     path->path.rows = 0;        /* per above, not used */
00809     path->path.startup_cost = totalCost;
00810     path->path.total_cost = totalCost;
00811 }
00812 
00813 /*
00814  * cost_bitmap_or_node
00815  *      Estimate the cost of a BitmapOr node
00816  *
00817  * See comments for cost_bitmap_and_node.
00818  */
00819 void
00820 cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
00821 {
00822     Cost        totalCost;
00823     Selectivity selec;
00824     ListCell   *l;
00825 
00826     /*
00827      * We estimate OR selectivity on the assumption that the inputs are
00828      * non-overlapping, since that's often the case in "x IN (list)" type
00829      * situations.  Of course, we clamp to 1.0 at the end.
00830      *
00831      * The runtime cost of the BitmapOr itself is estimated at 100x
00832      * cpu_operator_cost for each tbm_union needed.  Probably too small,
00833      * definitely too simplistic?  We are aware that the tbm_unions are
00834      * optimized out when the inputs are BitmapIndexScans.
00835      */
00836     totalCost = 0.0;
00837     selec = 0.0;
00838     foreach(l, path->bitmapquals)
00839     {
00840         Path       *subpath = (Path *) lfirst(l);
00841         Cost        subCost;
00842         Selectivity subselec;
00843 
00844         cost_bitmap_tree_node(subpath, &subCost, &subselec);
00845 
00846         selec += subselec;
00847 
00848         totalCost += subCost;
00849         if (l != list_head(path->bitmapquals) &&
00850             !IsA(subpath, IndexPath))
00851             totalCost += 100.0 * cpu_operator_cost;
00852     }
00853     path->bitmapselectivity = Min(selec, 1.0);
00854     path->path.rows = 0;        /* per above, not used */
00855     path->path.startup_cost = totalCost;
00856     path->path.total_cost = totalCost;
00857 }
00858 
00859 /*
00860  * cost_tidscan
00861  *    Determines and returns the cost of scanning a relation using TIDs.
00862  *
00863  * 'baserel' is the relation to be scanned
00864  * 'tidquals' is the list of TID-checkable quals
00865  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
00866  */
00867 void
00868 cost_tidscan(Path *path, PlannerInfo *root,
00869              RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
00870 {
00871     Cost        startup_cost = 0;
00872     Cost        run_cost = 0;
00873     bool        isCurrentOf = false;
00874     QualCost    qpqual_cost;
00875     Cost        cpu_per_tuple;
00876     QualCost    tid_qual_cost;
00877     int         ntuples;
00878     ListCell   *l;
00879     double      spc_random_page_cost;
00880 
00881     /* Should only be applied to base relations */
00882     Assert(baserel->relid > 0);
00883     Assert(baserel->rtekind == RTE_RELATION);
00884 
00885     /* Mark the path with the correct row estimate */
00886     if (param_info)
00887         path->rows = param_info->ppi_rows;
00888     else
00889         path->rows = baserel->rows;
00890 
00891     /* Count how many tuples we expect to retrieve */
00892     ntuples = 0;
00893     foreach(l, tidquals)
00894     {
00895         if (IsA(lfirst(l), ScalarArrayOpExpr))
00896         {
00897             /* Each element of the array yields 1 tuple */
00898             ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) lfirst(l);
00899             Node       *arraynode = (Node *) lsecond(saop->args);
00900 
00901             ntuples += estimate_array_length(arraynode);
00902         }
00903         else if (IsA(lfirst(l), CurrentOfExpr))
00904         {
00905             /* CURRENT OF yields 1 tuple */
00906             isCurrentOf = true;
00907             ntuples++;
00908         }
00909         else
00910         {
00911             /* It's just CTID = something, count 1 tuple */
00912             ntuples++;
00913         }
00914     }
00915 
00916     /*
00917      * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
00918      * understands how to do it correctly.  Therefore, honor enable_tidscan
00919      * only when CURRENT OF isn't present.  Also note that cost_qual_eval
00920      * counts a CurrentOfExpr as having startup cost disable_cost, which we
00921      * subtract off here; that's to prevent other plan types such as seqscan
00922      * from winning.
00923      */
00924     if (isCurrentOf)
00925     {
00926         Assert(baserel->baserestrictcost.startup >= disable_cost);
00927         startup_cost -= disable_cost;
00928     }
00929     else if (!enable_tidscan)
00930         startup_cost += disable_cost;
00931 
00932     /*
00933      * The TID qual expressions will be computed once, any other baserestrict
00934      * quals once per retrived tuple.
00935      */
00936     cost_qual_eval(&tid_qual_cost, tidquals, root);
00937 
00938     /* fetch estimated page cost for tablespace containing table */
00939     get_tablespace_page_costs(baserel->reltablespace,
00940                               &spc_random_page_cost,
00941                               NULL);
00942 
00943     /* disk costs --- assume each tuple on a different page */
00944     run_cost += spc_random_page_cost * ntuples;
00945 
00946     /* Add scanning CPU costs */
00947     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
00948 
00949     /* XXX currently we assume TID quals are a subset of qpquals */
00950     startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
00951     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
00952         tid_qual_cost.per_tuple;
00953     run_cost += cpu_per_tuple * ntuples;
00954 
00955     path->startup_cost = startup_cost;
00956     path->total_cost = startup_cost + run_cost;
00957 }
00958 
00959 /*
00960  * cost_subqueryscan
00961  *    Determines and returns the cost of scanning a subquery RTE.
00962  *
00963  * 'baserel' is the relation to be scanned
00964  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
00965  */
00966 void
00967 cost_subqueryscan(Path *path, PlannerInfo *root,
00968                   RelOptInfo *baserel, ParamPathInfo *param_info)
00969 {
00970     Cost        startup_cost;
00971     Cost        run_cost;
00972     QualCost    qpqual_cost;
00973     Cost        cpu_per_tuple;
00974 
00975     /* Should only be applied to base relations that are subqueries */
00976     Assert(baserel->relid > 0);
00977     Assert(baserel->rtekind == RTE_SUBQUERY);
00978 
00979     /* Mark the path with the correct row estimate */
00980     if (param_info)
00981         path->rows = param_info->ppi_rows;
00982     else
00983         path->rows = baserel->rows;
00984 
00985     /*
00986      * Cost of path is cost of evaluating the subplan, plus cost of evaluating
00987      * any restriction clauses that will be attached to the SubqueryScan node,
00988      * plus cpu_tuple_cost to account for selection and projection overhead.
00989      */
00990     path->startup_cost = baserel->subplan->startup_cost;
00991     path->total_cost = baserel->subplan->total_cost;
00992 
00993     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
00994 
00995     startup_cost = qpqual_cost.startup;
00996     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
00997     run_cost = cpu_per_tuple * baserel->tuples;
00998 
00999     path->startup_cost += startup_cost;
01000     path->total_cost += startup_cost + run_cost;
01001 }
01002 
01003 /*
01004  * cost_functionscan
01005  *    Determines and returns the cost of scanning a function RTE.
01006  *
01007  * 'baserel' is the relation to be scanned
01008  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
01009  */
01010 void
01011 cost_functionscan(Path *path, PlannerInfo *root,
01012                   RelOptInfo *baserel, ParamPathInfo *param_info)
01013 {
01014     Cost        startup_cost = 0;
01015     Cost        run_cost = 0;
01016     QualCost    qpqual_cost;
01017     Cost        cpu_per_tuple;
01018     RangeTblEntry *rte;
01019     QualCost    exprcost;
01020 
01021     /* Should only be applied to base relations that are functions */
01022     Assert(baserel->relid > 0);
01023     rte = planner_rt_fetch(baserel->relid, root);
01024     Assert(rte->rtekind == RTE_FUNCTION);
01025 
01026     /* Mark the path with the correct row estimate */
01027     if (param_info)
01028         path->rows = param_info->ppi_rows;
01029     else
01030         path->rows = baserel->rows;
01031 
01032     /*
01033      * Estimate costs of executing the function expression.
01034      *
01035      * Currently, nodeFunctionscan.c always executes the function to
01036      * completion before returning any rows, and caches the results in a
01037      * tuplestore.  So the function eval cost is all startup cost, and per-row
01038      * costs are minimal.
01039      *
01040      * XXX in principle we ought to charge tuplestore spill costs if the
01041      * number of rows is large.  However, given how phony our rowcount
01042      * estimates for functions tend to be, there's not a lot of point in that
01043      * refinement right now.
01044      */
01045     cost_qual_eval_node(&exprcost, rte->funcexpr, root);
01046 
01047     startup_cost += exprcost.startup + exprcost.per_tuple;
01048 
01049     /* Add scanning CPU costs */
01050     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
01051 
01052     startup_cost += qpqual_cost.startup;
01053     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
01054     run_cost += cpu_per_tuple * baserel->tuples;
01055 
01056     path->startup_cost = startup_cost;
01057     path->total_cost = startup_cost + run_cost;
01058 }
01059 
01060 /*
01061  * cost_valuesscan
01062  *    Determines and returns the cost of scanning a VALUES RTE.
01063  *
01064  * 'baserel' is the relation to be scanned
01065  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
01066  */
01067 void
01068 cost_valuesscan(Path *path, PlannerInfo *root,
01069                 RelOptInfo *baserel, ParamPathInfo *param_info)
01070 {
01071     Cost        startup_cost = 0;
01072     Cost        run_cost = 0;
01073     QualCost    qpqual_cost;
01074     Cost        cpu_per_tuple;
01075 
01076     /* Should only be applied to base relations that are values lists */
01077     Assert(baserel->relid > 0);
01078     Assert(baserel->rtekind == RTE_VALUES);
01079 
01080     /* Mark the path with the correct row estimate */
01081     if (param_info)
01082         path->rows = param_info->ppi_rows;
01083     else
01084         path->rows = baserel->rows;
01085 
01086     /*
01087      * For now, estimate list evaluation cost at one operator eval per list
01088      * (probably pretty bogus, but is it worth being smarter?)
01089      */
01090     cpu_per_tuple = cpu_operator_cost;
01091 
01092     /* Add scanning CPU costs */
01093     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
01094 
01095     startup_cost += qpqual_cost.startup;
01096     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
01097     run_cost += cpu_per_tuple * baserel->tuples;
01098 
01099     path->startup_cost = startup_cost;
01100     path->total_cost = startup_cost + run_cost;
01101 }
01102 
01103 /*
01104  * cost_ctescan
01105  *    Determines and returns the cost of scanning a CTE RTE.
01106  *
01107  * Note: this is used for both self-reference and regular CTEs; the
01108  * possible cost differences are below the threshold of what we could
01109  * estimate accurately anyway.  Note that the costs of evaluating the
01110  * referenced CTE query are added into the final plan as initplan costs,
01111  * and should NOT be counted here.
01112  */
01113 void
01114 cost_ctescan(Path *path, PlannerInfo *root,
01115              RelOptInfo *baserel, ParamPathInfo *param_info)
01116 {
01117     Cost        startup_cost = 0;
01118     Cost        run_cost = 0;
01119     QualCost    qpqual_cost;
01120     Cost        cpu_per_tuple;
01121 
01122     /* Should only be applied to base relations that are CTEs */
01123     Assert(baserel->relid > 0);
01124     Assert(baserel->rtekind == RTE_CTE);
01125 
01126     /* Mark the path with the correct row estimate */
01127     if (param_info)
01128         path->rows = param_info->ppi_rows;
01129     else
01130         path->rows = baserel->rows;
01131 
01132     /* Charge one CPU tuple cost per row for tuplestore manipulation */
01133     cpu_per_tuple = cpu_tuple_cost;
01134 
01135     /* Add scanning CPU costs */
01136     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
01137 
01138     startup_cost += qpqual_cost.startup;
01139     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
01140     run_cost += cpu_per_tuple * baserel->tuples;
01141 
01142     path->startup_cost = startup_cost;
01143     path->total_cost = startup_cost + run_cost;
01144 }
01145 
01146 /*
01147  * cost_recursive_union
01148  *    Determines and returns the cost of performing a recursive union,
01149  *    and also the estimated output size.
01150  *
01151  * We are given Plans for the nonrecursive and recursive terms.
01152  *
01153  * Note that the arguments and output are Plans, not Paths as in most of
01154  * the rest of this module.  That's because we don't bother setting up a
01155  * Path representation for recursive union --- we have only one way to do it.
01156  */
01157 void
01158 cost_recursive_union(Plan *runion, Plan *nrterm, Plan *rterm)
01159 {
01160     Cost        startup_cost;
01161     Cost        total_cost;
01162     double      total_rows;
01163 
01164     /* We probably have decent estimates for the non-recursive term */
01165     startup_cost = nrterm->startup_cost;
01166     total_cost = nrterm->total_cost;
01167     total_rows = nrterm->plan_rows;
01168 
01169     /*
01170      * We arbitrarily assume that about 10 recursive iterations will be
01171      * needed, and that we've managed to get a good fix on the cost and output
01172      * size of each one of them.  These are mighty shaky assumptions but it's
01173      * hard to see how to do better.
01174      */
01175     total_cost += 10 * rterm->total_cost;
01176     total_rows += 10 * rterm->plan_rows;
01177 
01178     /*
01179      * Also charge cpu_tuple_cost per row to account for the costs of
01180      * manipulating the tuplestores.  (We don't worry about possible
01181      * spill-to-disk costs.)
01182      */
01183     total_cost += cpu_tuple_cost * total_rows;
01184 
01185     runion->startup_cost = startup_cost;
01186     runion->total_cost = total_cost;
01187     runion->plan_rows = total_rows;
01188     runion->plan_width = Max(nrterm->plan_width, rterm->plan_width);
01189 }
01190 
01191 /*
01192  * cost_sort
01193  *    Determines and returns the cost of sorting a relation, including
01194  *    the cost of reading the input data.
01195  *
01196  * If the total volume of data to sort is less than sort_mem, we will do
01197  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
01198  * comparisons for t tuples.
01199  *
01200  * If the total volume exceeds sort_mem, we switch to a tape-style merge
01201  * algorithm.  There will still be about t*log2(t) tuple comparisons in
01202  * total, but we will also need to write and read each tuple once per
01203  * merge pass.  We expect about ceil(logM(r)) merge passes where r is the
01204  * number of initial runs formed and M is the merge order used by tuplesort.c.
01205  * Since the average initial run should be about twice sort_mem, we have
01206  *      disk traffic = 2 * relsize * ceil(logM(p / (2*sort_mem)))
01207  *      cpu = comparison_cost * t * log2(t)
01208  *
01209  * If the sort is bounded (i.e., only the first k result tuples are needed)
01210  * and k tuples can fit into sort_mem, we use a heap method that keeps only
01211  * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
01212  *
01213  * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
01214  * accesses (XXX can't we refine that guess?)
01215  *
01216  * By default, we charge two operator evals per tuple comparison, which should
01217  * be in the right ballpark in most cases.  The caller can tweak this by
01218  * specifying nonzero comparison_cost; typically that's used for any extra
01219  * work that has to be done to prepare the inputs to the comparison operators.
01220  *
01221  * 'pathkeys' is a list of sort keys
01222  * 'input_cost' is the total cost for reading the input data
01223  * 'tuples' is the number of tuples in the relation
01224  * 'width' is the average tuple width in bytes
01225  * 'comparison_cost' is the extra cost per comparison, if any
01226  * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
01227  * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
01228  *
01229  * NOTE: some callers currently pass NIL for pathkeys because they
01230  * can't conveniently supply the sort keys.  Since this routine doesn't
01231  * currently do anything with pathkeys anyway, that doesn't matter...
01232  * but if it ever does, it should react gracefully to lack of key data.
01233  * (Actually, the thing we'd most likely be interested in is just the number
01234  * of sort keys, which all callers *could* supply.)
01235  */
01236 void
01237 cost_sort(Path *path, PlannerInfo *root,
01238           List *pathkeys, Cost input_cost, double tuples, int width,
01239           Cost comparison_cost, int sort_mem,
01240           double limit_tuples)
01241 {
01242     Cost        startup_cost = input_cost;
01243     Cost        run_cost = 0;
01244     double      input_bytes = relation_byte_size(tuples, width);
01245     double      output_bytes;
01246     double      output_tuples;
01247     long        sort_mem_bytes = sort_mem * 1024L;
01248 
01249     if (!enable_sort)
01250         startup_cost += disable_cost;
01251 
01252     path->rows = tuples;
01253 
01254     /*
01255      * We want to be sure the cost of a sort is never estimated as zero, even
01256      * if passed-in tuple count is zero.  Besides, mustn't do log(0)...
01257      */
01258     if (tuples < 2.0)
01259         tuples = 2.0;
01260 
01261     /* Include the default cost-per-comparison */
01262     comparison_cost += 2.0 * cpu_operator_cost;
01263 
01264     /* Do we have a useful LIMIT? */
01265     if (limit_tuples > 0 && limit_tuples < tuples)
01266     {
01267         output_tuples = limit_tuples;
01268         output_bytes = relation_byte_size(output_tuples, width);
01269     }
01270     else
01271     {
01272         output_tuples = tuples;
01273         output_bytes = input_bytes;
01274     }
01275 
01276     if (output_bytes > sort_mem_bytes)
01277     {
01278         /*
01279          * We'll have to use a disk-based sort of all the tuples
01280          */
01281         double      npages = ceil(input_bytes / BLCKSZ);
01282         double      nruns = (input_bytes / sort_mem_bytes) * 0.5;
01283         double      mergeorder = tuplesort_merge_order(sort_mem_bytes);
01284         double      log_runs;
01285         double      npageaccesses;
01286 
01287         /*
01288          * CPU costs
01289          *
01290          * Assume about N log2 N comparisons
01291          */
01292         startup_cost += comparison_cost * tuples * LOG2(tuples);
01293 
01294         /* Disk costs */
01295 
01296         /* Compute logM(r) as log(r) / log(M) */
01297         if (nruns > mergeorder)
01298             log_runs = ceil(log(nruns) / log(mergeorder));
01299         else
01300             log_runs = 1.0;
01301         npageaccesses = 2.0 * npages * log_runs;
01302         /* Assume 3/4ths of accesses are sequential, 1/4th are not */
01303         startup_cost += npageaccesses *
01304             (seq_page_cost * 0.75 + random_page_cost * 0.25);
01305     }
01306     else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
01307     {
01308         /*
01309          * We'll use a bounded heap-sort keeping just K tuples in memory, for
01310          * a total number of tuple comparisons of N log2 K; but the constant
01311          * factor is a bit higher than for quicksort.  Tweak it so that the
01312          * cost curve is continuous at the crossover point.
01313          */
01314         startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
01315     }
01316     else
01317     {
01318         /* We'll use plain quicksort on all the input tuples */
01319         startup_cost += comparison_cost * tuples * LOG2(tuples);
01320     }
01321 
01322     /*
01323      * Also charge a small amount (arbitrarily set equal to operator cost) per
01324      * extracted tuple.  We don't charge cpu_tuple_cost because a Sort node
01325      * doesn't do qual-checking or projection, so it has less overhead than
01326      * most plan nodes.  Note it's correct to use tuples not output_tuples
01327      * here --- the upper LIMIT will pro-rate the run cost so we'd be double
01328      * counting the LIMIT otherwise.
01329      */
01330     run_cost += cpu_operator_cost * tuples;
01331 
01332     path->startup_cost = startup_cost;
01333     path->total_cost = startup_cost + run_cost;
01334 }
01335 
01336 /*
01337  * cost_merge_append
01338  *    Determines and returns the cost of a MergeAppend node.
01339  *
01340  * MergeAppend merges several pre-sorted input streams, using a heap that
01341  * at any given instant holds the next tuple from each stream.  If there
01342  * are N streams, we need about N*log2(N) tuple comparisons to construct
01343  * the heap at startup, and then for each output tuple, about log2(N)
01344  * comparisons to delete the top heap entry and another log2(N) comparisons
01345  * to insert its successor from the same stream.
01346  *
01347  * (The effective value of N will drop once some of the input streams are
01348  * exhausted, but it seems unlikely to be worth trying to account for that.)
01349  *
01350  * The heap is never spilled to disk, since we assume N is not very large.
01351  * So this is much simpler than cost_sort.
01352  *
01353  * As in cost_sort, we charge two operator evals per tuple comparison.
01354  *
01355  * 'pathkeys' is a list of sort keys
01356  * 'n_streams' is the number of input streams
01357  * 'input_startup_cost' is the sum of the input streams' startup costs
01358  * 'input_total_cost' is the sum of the input streams' total costs
01359  * 'tuples' is the number of tuples in all the streams
01360  */
01361 void
01362 cost_merge_append(Path *path, PlannerInfo *root,
01363                   List *pathkeys, int n_streams,
01364                   Cost input_startup_cost, Cost input_total_cost,
01365                   double tuples)
01366 {
01367     Cost        startup_cost = 0;
01368     Cost        run_cost = 0;
01369     Cost        comparison_cost;
01370     double      N;
01371     double      logN;
01372 
01373     /*
01374      * Avoid log(0)...
01375      */
01376     N = (n_streams < 2) ? 2.0 : (double) n_streams;
01377     logN = LOG2(N);
01378 
01379     /* Assumed cost per tuple comparison */
01380     comparison_cost = 2.0 * cpu_operator_cost;
01381 
01382     /* Heap creation cost */
01383     startup_cost += comparison_cost * N * logN;
01384 
01385     /* Per-tuple heap maintenance cost */
01386     run_cost += tuples * comparison_cost * 2.0 * logN;
01387 
01388     /*
01389      * Also charge a small amount (arbitrarily set equal to operator cost) per
01390      * extracted tuple.  We don't charge cpu_tuple_cost because a MergeAppend
01391      * node doesn't do qual-checking or projection, so it has less overhead
01392      * than most plan nodes.
01393      */
01394     run_cost += cpu_operator_cost * tuples;
01395 
01396     path->startup_cost = startup_cost + input_startup_cost;
01397     path->total_cost = startup_cost + run_cost + input_total_cost;
01398 }
01399 
01400 /*
01401  * cost_material
01402  *    Determines and returns the cost of materializing a relation, including
01403  *    the cost of reading the input data.
01404  *
01405  * If the total volume of data to materialize exceeds work_mem, we will need
01406  * to write it to disk, so the cost is much higher in that case.
01407  *
01408  * Note that here we are estimating the costs for the first scan of the
01409  * relation, so the materialization is all overhead --- any savings will
01410  * occur only on rescan, which is estimated in cost_rescan.
01411  */
01412 void
01413 cost_material(Path *path,
01414               Cost input_startup_cost, Cost input_total_cost,
01415               double tuples, int width)
01416 {
01417     Cost        startup_cost = input_startup_cost;
01418     Cost        run_cost = input_total_cost - input_startup_cost;
01419     double      nbytes = relation_byte_size(tuples, width);
01420     long        work_mem_bytes = work_mem * 1024L;
01421 
01422     path->rows = tuples;
01423 
01424     /*
01425      * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
01426      * reflect bookkeeping overhead.  (This rate must be more than what
01427      * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
01428      * if it is exactly the same then there will be a cost tie between
01429      * nestloop with A outer, materialized B inner and nestloop with B outer,
01430      * materialized A inner.  The extra cost ensures we'll prefer
01431      * materializing the smaller rel.)  Note that this is normally a good deal
01432      * less than cpu_tuple_cost; which is OK because a Material plan node
01433      * doesn't do qual-checking or projection, so it's got less overhead than
01434      * most plan nodes.
01435      */
01436     run_cost += 2 * cpu_operator_cost * tuples;
01437 
01438     /*
01439      * If we will spill to disk, charge at the rate of seq_page_cost per page.
01440      * This cost is assumed to be evenly spread through the plan run phase,
01441      * which isn't exactly accurate but our cost model doesn't allow for
01442      * nonuniform costs within the run phase.
01443      */
01444     if (nbytes > work_mem_bytes)
01445     {
01446         double      npages = ceil(nbytes / BLCKSZ);
01447 
01448         run_cost += seq_page_cost * npages;
01449     }
01450 
01451     path->startup_cost = startup_cost;
01452     path->total_cost = startup_cost + run_cost;
01453 }
01454 
01455 /*
01456  * cost_agg
01457  *      Determines and returns the cost of performing an Agg plan node,
01458  *      including the cost of its input.
01459  *
01460  * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
01461  * we are using a hashed Agg node just to do grouping).
01462  *
01463  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
01464  * are for appropriately-sorted input.
01465  */
01466 void
01467 cost_agg(Path *path, PlannerInfo *root,
01468          AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
01469          int numGroupCols, double numGroups,
01470          Cost input_startup_cost, Cost input_total_cost,
01471          double input_tuples)
01472 {
01473     double      output_tuples;
01474     Cost        startup_cost;
01475     Cost        total_cost;
01476     AggClauseCosts dummy_aggcosts;
01477 
01478     /* Use all-zero per-aggregate costs if NULL is passed */
01479     if (aggcosts == NULL)
01480     {
01481         Assert(aggstrategy == AGG_HASHED);
01482         MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
01483         aggcosts = &dummy_aggcosts;
01484     }
01485 
01486     /*
01487      * The transCost.per_tuple component of aggcosts should be charged once
01488      * per input tuple, corresponding to the costs of evaluating the aggregate
01489      * transfns and their input expressions (with any startup cost of course
01490      * charged but once).  The finalCost component is charged once per output
01491      * tuple, corresponding to the costs of evaluating the finalfns.
01492      *
01493      * If we are grouping, we charge an additional cpu_operator_cost per
01494      * grouping column per input tuple for grouping comparisons.
01495      *
01496      * We will produce a single output tuple if not grouping, and a tuple per
01497      * group otherwise.  We charge cpu_tuple_cost for each output tuple.
01498      *
01499      * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
01500      * same total CPU cost, but AGG_SORTED has lower startup cost.  If the
01501      * input path is already sorted appropriately, AGG_SORTED should be
01502      * preferred (since it has no risk of memory overflow).  This will happen
01503      * as long as the computed total costs are indeed exactly equal --- but if
01504      * there's roundoff error we might do the wrong thing.  So be sure that
01505      * the computations below form the same intermediate values in the same
01506      * order.
01507      */
01508     if (aggstrategy == AGG_PLAIN)
01509     {
01510         startup_cost = input_total_cost;
01511         startup_cost += aggcosts->transCost.startup;
01512         startup_cost += aggcosts->transCost.per_tuple * input_tuples;
01513         startup_cost += aggcosts->finalCost;
01514         /* we aren't grouping */
01515         total_cost = startup_cost + cpu_tuple_cost;
01516         output_tuples = 1;
01517     }
01518     else if (aggstrategy == AGG_SORTED)
01519     {
01520         /* Here we are able to deliver output on-the-fly */
01521         startup_cost = input_startup_cost;
01522         total_cost = input_total_cost;
01523         /* calcs phrased this way to match HASHED case, see note above */
01524         total_cost += aggcosts->transCost.startup;
01525         total_cost += aggcosts->transCost.per_tuple * input_tuples;
01526         total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
01527         total_cost += aggcosts->finalCost * numGroups;
01528         total_cost += cpu_tuple_cost * numGroups;
01529         output_tuples = numGroups;
01530     }
01531     else
01532     {
01533         /* must be AGG_HASHED */
01534         startup_cost = input_total_cost;
01535         startup_cost += aggcosts->transCost.startup;
01536         startup_cost += aggcosts->transCost.per_tuple * input_tuples;
01537         startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
01538         total_cost = startup_cost;
01539         total_cost += aggcosts->finalCost * numGroups;
01540         total_cost += cpu_tuple_cost * numGroups;
01541         output_tuples = numGroups;
01542     }
01543 
01544     path->rows = output_tuples;
01545     path->startup_cost = startup_cost;
01546     path->total_cost = total_cost;
01547 }
01548 
01549 /*
01550  * cost_windowagg
01551  *      Determines and returns the cost of performing a WindowAgg plan node,
01552  *      including the cost of its input.
01553  *
01554  * Input is assumed already properly sorted.
01555  */
01556 void
01557 cost_windowagg(Path *path, PlannerInfo *root,
01558                List *windowFuncs, int numPartCols, int numOrderCols,
01559                Cost input_startup_cost, Cost input_total_cost,
01560                double input_tuples)
01561 {
01562     Cost        startup_cost;
01563     Cost        total_cost;
01564     ListCell   *lc;
01565 
01566     startup_cost = input_startup_cost;
01567     total_cost = input_total_cost;
01568 
01569     /*
01570      * Window functions are assumed to cost their stated execution cost, plus
01571      * the cost of evaluating their input expressions, per tuple.  Since they
01572      * may in fact evaluate their inputs at multiple rows during each cycle,
01573      * this could be a drastic underestimate; but without a way to know how
01574      * many rows the window function will fetch, it's hard to do better.  In
01575      * any case, it's a good estimate for all the built-in window functions,
01576      * so we'll just do this for now.
01577      */
01578     foreach(lc, windowFuncs)
01579     {
01580         WindowFunc *wfunc = (WindowFunc *) lfirst(lc);
01581         Cost        wfunccost;
01582         QualCost    argcosts;
01583 
01584         Assert(IsA(wfunc, WindowFunc));
01585 
01586         wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
01587 
01588         /* also add the input expressions' cost to per-input-row costs */
01589         cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
01590         startup_cost += argcosts.startup;
01591         wfunccost += argcosts.per_tuple;
01592 
01593         total_cost += wfunccost * input_tuples;
01594     }
01595 
01596     /*
01597      * We also charge cpu_operator_cost per grouping column per tuple for
01598      * grouping comparisons, plus cpu_tuple_cost per tuple for general
01599      * overhead.
01600      *
01601      * XXX this neglects costs of spooling the data to disk when it overflows
01602      * work_mem.  Sooner or later that should get accounted for.
01603      */
01604     total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
01605     total_cost += cpu_tuple_cost * input_tuples;
01606 
01607     path->rows = input_tuples;
01608     path->startup_cost = startup_cost;
01609     path->total_cost = total_cost;
01610 }
01611 
01612 /*
01613  * cost_group
01614  *      Determines and returns the cost of performing a Group plan node,
01615  *      including the cost of its input.
01616  *
01617  * Note: caller must ensure that input costs are for appropriately-sorted
01618  * input.
01619  */
01620 void
01621 cost_group(Path *path, PlannerInfo *root,
01622            int numGroupCols, double numGroups,
01623            Cost input_startup_cost, Cost input_total_cost,
01624            double input_tuples)
01625 {
01626     Cost        startup_cost;
01627     Cost        total_cost;
01628 
01629     startup_cost = input_startup_cost;
01630     total_cost = input_total_cost;
01631 
01632     /*
01633      * Charge one cpu_operator_cost per comparison per input tuple. We assume
01634      * all columns get compared at most of the tuples.
01635      */
01636     total_cost += cpu_operator_cost * input_tuples * numGroupCols;
01637 
01638     path->rows = numGroups;
01639     path->startup_cost = startup_cost;
01640     path->total_cost = total_cost;
01641 }
01642 
01643 /*
01644  * initial_cost_nestloop
01645  *    Preliminary estimate of the cost of a nestloop join path.
01646  *
01647  * This must quickly produce lower-bound estimates of the path's startup and
01648  * total costs.  If we are unable to eliminate the proposed path from
01649  * consideration using the lower bounds, final_cost_nestloop will be called
01650  * to obtain the final estimates.
01651  *
01652  * The exact division of labor between this function and final_cost_nestloop
01653  * is private to them, and represents a tradeoff between speed of the initial
01654  * estimate and getting a tight lower bound.  We choose to not examine the
01655  * join quals here, since that's by far the most expensive part of the
01656  * calculations.  The end result is that CPU-cost considerations must be
01657  * left for the second phase.
01658  *
01659  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
01660  *      other data to be used by final_cost_nestloop
01661  * 'jointype' is the type of join to be performed
01662  * 'outer_path' is the outer input to the join
01663  * 'inner_path' is the inner input to the join
01664  * 'sjinfo' is extra info about the join for selectivity estimation
01665  * 'semifactors' contains valid data if jointype is SEMI or ANTI
01666  */
01667 void
01668 initial_cost_nestloop(PlannerInfo *root, JoinCostWorkspace *workspace,
01669                       JoinType jointype,
01670                       Path *outer_path, Path *inner_path,
01671                       SpecialJoinInfo *sjinfo,
01672                       SemiAntiJoinFactors *semifactors)
01673 {
01674     Cost        startup_cost = 0;
01675     Cost        run_cost = 0;
01676     double      outer_path_rows = outer_path->rows;
01677     Cost        inner_rescan_start_cost;
01678     Cost        inner_rescan_total_cost;
01679     Cost        inner_run_cost;
01680     Cost        inner_rescan_run_cost;
01681 
01682     /* estimate costs to rescan the inner relation */
01683     cost_rescan(root, inner_path,
01684                 &inner_rescan_start_cost,
01685                 &inner_rescan_total_cost);
01686 
01687     /* cost of source data */
01688 
01689     /*
01690      * NOTE: clearly, we must pay both outer and inner paths' startup_cost
01691      * before we can start returning tuples, so the join's startup cost is
01692      * their sum.  We'll also pay the inner path's rescan startup cost
01693      * multiple times.
01694      */
01695     startup_cost += outer_path->startup_cost + inner_path->startup_cost;
01696     run_cost += outer_path->total_cost - outer_path->startup_cost;
01697     if (outer_path_rows > 1)
01698         run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
01699 
01700     inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
01701     inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
01702 
01703     if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
01704     {
01705         double      outer_matched_rows;
01706         Selectivity inner_scan_frac;
01707 
01708         /*
01709          * SEMI or ANTI join: executor will stop after first match.
01710          *
01711          * For an outer-rel row that has at least one match, we can expect the
01712          * inner scan to stop after a fraction 1/(match_count+1) of the inner
01713          * rows, if the matches are evenly distributed.  Since they probably
01714          * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
01715          * that fraction.  (If we used a larger fuzz factor, we'd have to
01716          * clamp inner_scan_frac to at most 1.0; but since match_count is at
01717          * least 1, no such clamp is needed now.)
01718          *
01719          * A complicating factor is that rescans may be cheaper than first
01720          * scans.  If we never scan all the way to the end of the inner rel,
01721          * it might be (depending on the plan type) that we'd never pay the
01722          * whole inner first-scan run cost.  However it is difficult to
01723          * estimate whether that will happen, so be conservative and always
01724          * charge the whole first-scan cost once.
01725          */
01726         run_cost += inner_run_cost;
01727 
01728         outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
01729         inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
01730 
01731         /* Add inner run cost for additional outer tuples having matches */
01732         if (outer_matched_rows > 1)
01733             run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
01734 
01735         /*
01736          * The cost of processing unmatched rows varies depending on the
01737          * details of the joinclauses, so we leave that part for later.
01738          */
01739 
01740         /* Save private data for final_cost_nestloop */
01741         workspace->outer_matched_rows = outer_matched_rows;
01742         workspace->inner_scan_frac = inner_scan_frac;
01743     }
01744     else
01745     {
01746         /* Normal case; we'll scan whole input rel for each outer row */
01747         run_cost += inner_run_cost;
01748         if (outer_path_rows > 1)
01749             run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
01750     }
01751 
01752     /* CPU costs left for later */
01753 
01754     /* Public result fields */
01755     workspace->startup_cost = startup_cost;
01756     workspace->total_cost = startup_cost + run_cost;
01757     /* Save private data for final_cost_nestloop */
01758     workspace->run_cost = run_cost;
01759     workspace->inner_rescan_run_cost = inner_rescan_run_cost;
01760 }
01761 
01762 /*
01763  * final_cost_nestloop
01764  *    Final estimate of the cost and result size of a nestloop join path.
01765  *
01766  * 'path' is already filled in except for the rows and cost fields
01767  * 'workspace' is the result from initial_cost_nestloop
01768  * 'sjinfo' is extra info about the join for selectivity estimation
01769  * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
01770  */
01771 void
01772 final_cost_nestloop(PlannerInfo *root, NestPath *path,
01773                     JoinCostWorkspace *workspace,
01774                     SpecialJoinInfo *sjinfo,
01775                     SemiAntiJoinFactors *semifactors)
01776 {
01777     Path       *outer_path = path->outerjoinpath;
01778     Path       *inner_path = path->innerjoinpath;
01779     double      outer_path_rows = outer_path->rows;
01780     double      inner_path_rows = inner_path->rows;
01781     Cost        startup_cost = workspace->startup_cost;
01782     Cost        run_cost = workspace->run_cost;
01783     Cost        inner_rescan_run_cost = workspace->inner_rescan_run_cost;
01784     Cost        cpu_per_tuple;
01785     QualCost    restrict_qual_cost;
01786     double      ntuples;
01787 
01788     /* Mark the path with the correct row estimate */
01789     if (path->path.param_info)
01790         path->path.rows = path->path.param_info->ppi_rows;
01791     else
01792         path->path.rows = path->path.parent->rows;
01793 
01794     /*
01795      * We could include disable_cost in the preliminary estimate, but that
01796      * would amount to optimizing for the case where the join method is
01797      * disabled, which doesn't seem like the way to bet.
01798      */
01799     if (!enable_nestloop)
01800         startup_cost += disable_cost;
01801 
01802     /* cost of source data */
01803 
01804     if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI)
01805     {
01806         double      outer_matched_rows = workspace->outer_matched_rows;
01807         Selectivity inner_scan_frac = workspace->inner_scan_frac;
01808 
01809         /*
01810          * SEMI or ANTI join: executor will stop after first match.
01811          */
01812 
01813         /* Compute number of tuples processed (not number emitted!) */
01814         ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
01815 
01816         /*
01817          * For unmatched outer-rel rows, there are two cases.  If the inner
01818          * path is an indexscan using all the joinquals as indexquals, then an
01819          * unmatched row results in an indexscan returning no rows, which is
01820          * probably quite cheap.  We estimate this case as the same cost to
01821          * return the first tuple of a nonempty scan.  Otherwise, the executor
01822          * will have to scan the whole inner rel; not so cheap.
01823          */
01824         if (has_indexed_join_quals(path))
01825         {
01826             run_cost += (outer_path_rows - outer_matched_rows) *
01827                 inner_rescan_run_cost / inner_path_rows;
01828 
01829             /*
01830              * We won't be evaluating any quals at all for these rows, so
01831              * don't add them to ntuples.
01832              */
01833         }
01834         else
01835         {
01836             run_cost += (outer_path_rows - outer_matched_rows) *
01837                 inner_rescan_run_cost;
01838             ntuples += (outer_path_rows - outer_matched_rows) *
01839                 inner_path_rows;
01840         }
01841     }
01842     else
01843     {
01844         /* Normal-case source costs were included in preliminary estimate */
01845 
01846         /* Compute number of tuples processed (not number emitted!) */
01847         ntuples = outer_path_rows * inner_path_rows;
01848     }
01849 
01850     /* CPU costs */
01851     cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
01852     startup_cost += restrict_qual_cost.startup;
01853     cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
01854     run_cost += cpu_per_tuple * ntuples;
01855 
01856     path->path.startup_cost = startup_cost;
01857     path->path.total_cost = startup_cost + run_cost;
01858 }
01859 
01860 /*
01861  * initial_cost_mergejoin
01862  *    Preliminary estimate of the cost of a mergejoin path.
01863  *
01864  * This must quickly produce lower-bound estimates of the path's startup and
01865  * total costs.  If we are unable to eliminate the proposed path from
01866  * consideration using the lower bounds, final_cost_mergejoin will be called
01867  * to obtain the final estimates.
01868  *
01869  * The exact division of labor between this function and final_cost_mergejoin
01870  * is private to them, and represents a tradeoff between speed of the initial
01871  * estimate and getting a tight lower bound.  We choose to not examine the
01872  * join quals here, except for obtaining the scan selectivity estimate which
01873  * is really essential (but fortunately, use of caching keeps the cost of
01874  * getting that down to something reasonable).
01875  * We also assume that cost_sort is cheap enough to use here.
01876  *
01877  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
01878  *      other data to be used by final_cost_mergejoin
01879  * 'jointype' is the type of join to be performed
01880  * 'mergeclauses' is the list of joinclauses to be used as merge clauses
01881  * 'outer_path' is the outer input to the join
01882  * 'inner_path' is the inner input to the join
01883  * 'outersortkeys' is the list of sort keys for the outer path
01884  * 'innersortkeys' is the list of sort keys for the inner path
01885  * 'sjinfo' is extra info about the join for selectivity estimation
01886  *
01887  * Note: outersortkeys and innersortkeys should be NIL if no explicit
01888  * sort is needed because the respective source path is already ordered.
01889  */
01890 void
01891 initial_cost_mergejoin(PlannerInfo *root, JoinCostWorkspace *workspace,
01892                        JoinType jointype,
01893                        List *mergeclauses,
01894                        Path *outer_path, Path *inner_path,
01895                        List *outersortkeys, List *innersortkeys,
01896                        SpecialJoinInfo *sjinfo)
01897 {
01898     Cost        startup_cost = 0;
01899     Cost        run_cost = 0;
01900     double      outer_path_rows = outer_path->rows;
01901     double      inner_path_rows = inner_path->rows;
01902     Cost        inner_run_cost;
01903     double      outer_rows,
01904                 inner_rows,
01905                 outer_skip_rows,
01906                 inner_skip_rows;
01907     Selectivity outerstartsel,
01908                 outerendsel,
01909                 innerstartsel,
01910                 innerendsel;
01911     Path        sort_path;      /* dummy for result of cost_sort */
01912 
01913     /* Protect some assumptions below that rowcounts aren't zero or NaN */
01914     if (outer_path_rows <= 0 || isnan(outer_path_rows))
01915         outer_path_rows = 1;
01916     if (inner_path_rows <= 0 || isnan(inner_path_rows))
01917         inner_path_rows = 1;
01918 
01919     /*
01920      * A merge join will stop as soon as it exhausts either input stream
01921      * (unless it's an outer join, in which case the outer side has to be
01922      * scanned all the way anyway).  Estimate fraction of the left and right
01923      * inputs that will actually need to be scanned.  Likewise, we can
01924      * estimate the number of rows that will be skipped before the first join
01925      * pair is found, which should be factored into startup cost. We use only
01926      * the first (most significant) merge clause for this purpose. Since
01927      * mergejoinscansel() is a fairly expensive computation, we cache the
01928      * results in the merge clause RestrictInfo.
01929      */
01930     if (mergeclauses && jointype != JOIN_FULL)
01931     {
01932         RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
01933         List       *opathkeys;
01934         List       *ipathkeys;
01935         PathKey    *opathkey;
01936         PathKey    *ipathkey;
01937         MergeScanSelCache *cache;
01938 
01939         /* Get the input pathkeys to determine the sort-order details */
01940         opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
01941         ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
01942         Assert(opathkeys);
01943         Assert(ipathkeys);
01944         opathkey = (PathKey *) linitial(opathkeys);
01945         ipathkey = (PathKey *) linitial(ipathkeys);
01946         /* debugging check */
01947         if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
01948             opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
01949             opathkey->pk_strategy != ipathkey->pk_strategy ||
01950             opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
01951             elog(ERROR, "left and right pathkeys do not match in mergejoin");
01952 
01953         /* Get the selectivity with caching */
01954         cache = cached_scansel(root, firstclause, opathkey);
01955 
01956         if (bms_is_subset(firstclause->left_relids,
01957                           outer_path->parent->relids))
01958         {
01959             /* left side of clause is outer */
01960             outerstartsel = cache->leftstartsel;
01961             outerendsel = cache->leftendsel;
01962             innerstartsel = cache->rightstartsel;
01963             innerendsel = cache->rightendsel;
01964         }
01965         else
01966         {
01967             /* left side of clause is inner */
01968             outerstartsel = cache->rightstartsel;
01969             outerendsel = cache->rightendsel;
01970             innerstartsel = cache->leftstartsel;
01971             innerendsel = cache->leftendsel;
01972         }
01973         if (jointype == JOIN_LEFT ||
01974             jointype == JOIN_ANTI)
01975         {
01976             outerstartsel = 0.0;
01977             outerendsel = 1.0;
01978         }
01979         else if (jointype == JOIN_RIGHT)
01980         {
01981             innerstartsel = 0.0;
01982             innerendsel = 1.0;
01983         }
01984     }
01985     else
01986     {
01987         /* cope with clauseless or full mergejoin */
01988         outerstartsel = innerstartsel = 0.0;
01989         outerendsel = innerendsel = 1.0;
01990     }
01991 
01992     /*
01993      * Convert selectivities to row counts.  We force outer_rows and
01994      * inner_rows to be at least 1, but the skip_rows estimates can be zero.
01995      */
01996     outer_skip_rows = rint(outer_path_rows * outerstartsel);
01997     inner_skip_rows = rint(inner_path_rows * innerstartsel);
01998     outer_rows = clamp_row_est(outer_path_rows * outerendsel);
01999     inner_rows = clamp_row_est(inner_path_rows * innerendsel);
02000 
02001     Assert(outer_skip_rows <= outer_rows);
02002     Assert(inner_skip_rows <= inner_rows);
02003 
02004     /*
02005      * Readjust scan selectivities to account for above rounding.  This is
02006      * normally an insignificant effect, but when there are only a few rows in
02007      * the inputs, failing to do this makes for a large percentage error.
02008      */
02009     outerstartsel = outer_skip_rows / outer_path_rows;
02010     innerstartsel = inner_skip_rows / inner_path_rows;
02011     outerendsel = outer_rows / outer_path_rows;
02012     innerendsel = inner_rows / inner_path_rows;
02013 
02014     Assert(outerstartsel <= outerendsel);
02015     Assert(innerstartsel <= innerendsel);
02016 
02017     /* cost of source data */
02018 
02019     if (outersortkeys)          /* do we need to sort outer? */
02020     {
02021         cost_sort(&sort_path,
02022                   root,
02023                   outersortkeys,
02024                   outer_path->total_cost,
02025                   outer_path_rows,
02026                   outer_path->parent->width,
02027                   0.0,
02028                   work_mem,
02029                   -1.0);
02030         startup_cost += sort_path.startup_cost;
02031         startup_cost += (sort_path.total_cost - sort_path.startup_cost)
02032             * outerstartsel;
02033         run_cost += (sort_path.total_cost - sort_path.startup_cost)
02034             * (outerendsel - outerstartsel);
02035     }
02036     else
02037     {
02038         startup_cost += outer_path->startup_cost;
02039         startup_cost += (outer_path->total_cost - outer_path->startup_cost)
02040             * outerstartsel;
02041         run_cost += (outer_path->total_cost - outer_path->startup_cost)
02042             * (outerendsel - outerstartsel);
02043     }
02044 
02045     if (innersortkeys)          /* do we need to sort inner? */
02046     {
02047         cost_sort(&sort_path,
02048                   root,
02049                   innersortkeys,
02050                   inner_path->total_cost,
02051                   inner_path_rows,
02052                   inner_path->parent->width,
02053                   0.0,
02054                   work_mem,
02055                   -1.0);
02056         startup_cost += sort_path.startup_cost;
02057         startup_cost += (sort_path.total_cost - sort_path.startup_cost)
02058             * innerstartsel;
02059         inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
02060             * (innerendsel - innerstartsel);
02061     }
02062     else
02063     {
02064         startup_cost += inner_path->startup_cost;
02065         startup_cost += (inner_path->total_cost - inner_path->startup_cost)
02066             * innerstartsel;
02067         inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
02068             * (innerendsel - innerstartsel);
02069     }
02070 
02071     /*
02072      * We can't yet determine whether rescanning occurs, or whether
02073      * materialization of the inner input should be done.  The minimum
02074      * possible inner input cost, regardless of rescan and materialization
02075      * considerations, is inner_run_cost.  We include that in
02076      * workspace->total_cost, but not yet in run_cost.
02077      */
02078 
02079     /* CPU costs left for later */
02080 
02081     /* Public result fields */
02082     workspace->startup_cost = startup_cost;
02083     workspace->total_cost = startup_cost + run_cost + inner_run_cost;
02084     /* Save private data for final_cost_mergejoin */
02085     workspace->run_cost = run_cost;
02086     workspace->inner_run_cost = inner_run_cost;
02087     workspace->outer_rows = outer_rows;
02088     workspace->inner_rows = inner_rows;
02089     workspace->outer_skip_rows = outer_skip_rows;
02090     workspace->inner_skip_rows = inner_skip_rows;
02091 }
02092 
02093 /*
02094  * final_cost_mergejoin
02095  *    Final estimate of the cost and result size of a mergejoin path.
02096  *
02097  * Unlike other costsize functions, this routine makes one actual decision:
02098  * whether we should materialize the inner path.  We do that either because
02099  * the inner path can't support mark/restore, or because it's cheaper to
02100  * use an interposed Material node to handle mark/restore.  When the decision
02101  * is cost-based it would be logically cleaner to build and cost two separate
02102  * paths with and without that flag set; but that would require repeating most
02103  * of the cost calculations, which are not all that cheap.  Since the choice
02104  * will not affect output pathkeys or startup cost, only total cost, there is
02105  * no possibility of wanting to keep both paths.  So it seems best to make
02106  * the decision here and record it in the path's materialize_inner field.
02107  *
02108  * 'path' is already filled in except for the rows and cost fields and
02109  *      materialize_inner
02110  * 'workspace' is the result from initial_cost_mergejoin
02111  * 'sjinfo' is extra info about the join for selectivity estimation
02112  */
02113 void
02114 final_cost_mergejoin(PlannerInfo *root, MergePath *path,
02115                      JoinCostWorkspace *workspace,
02116                      SpecialJoinInfo *sjinfo)
02117 {
02118     Path       *outer_path = path->jpath.outerjoinpath;
02119     Path       *inner_path = path->jpath.innerjoinpath;
02120     double      inner_path_rows = inner_path->rows;
02121     List       *mergeclauses = path->path_mergeclauses;
02122     List       *innersortkeys = path->innersortkeys;
02123     Cost        startup_cost = workspace->startup_cost;
02124     Cost        run_cost = workspace->run_cost;
02125     Cost        inner_run_cost = workspace->inner_run_cost;
02126     double      outer_rows = workspace->outer_rows;
02127     double      inner_rows = workspace->inner_rows;
02128     double      outer_skip_rows = workspace->outer_skip_rows;
02129     double      inner_skip_rows = workspace->inner_skip_rows;
02130     Cost        cpu_per_tuple,
02131                 bare_inner_cost,
02132                 mat_inner_cost;
02133     QualCost    merge_qual_cost;
02134     QualCost    qp_qual_cost;
02135     double      mergejointuples,
02136                 rescannedtuples;
02137     double      rescanratio;
02138 
02139     /* Protect some assumptions below that rowcounts aren't zero or NaN */
02140     if (inner_path_rows <= 0 || isnan(inner_path_rows))
02141         inner_path_rows = 1;
02142 
02143     /* Mark the path with the correct row estimate */
02144     if (path->jpath.path.param_info)
02145         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
02146     else
02147         path->jpath.path.rows = path->jpath.path.parent->rows;
02148 
02149     /*
02150      * We could include disable_cost in the preliminary estimate, but that
02151      * would amount to optimizing for the case where the join method is
02152      * disabled, which doesn't seem like the way to bet.
02153      */
02154     if (!enable_mergejoin)
02155         startup_cost += disable_cost;
02156 
02157     /*
02158      * Compute cost of the mergequals and qpquals (other restriction clauses)
02159      * separately.
02160      */
02161     cost_qual_eval(&merge_qual_cost, mergeclauses, root);
02162     cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
02163     qp_qual_cost.startup -= merge_qual_cost.startup;
02164     qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
02165 
02166     /*
02167      * Get approx # tuples passing the mergequals.  We use approx_tuple_count
02168      * here because we need an estimate done with JOIN_INNER semantics.
02169      */
02170     mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
02171 
02172     /*
02173      * When there are equal merge keys in the outer relation, the mergejoin
02174      * must rescan any matching tuples in the inner relation. This means
02175      * re-fetching inner tuples; we have to estimate how often that happens.
02176      *
02177      * For regular inner and outer joins, the number of re-fetches can be
02178      * estimated approximately as size of merge join output minus size of
02179      * inner relation. Assume that the distinct key values are 1, 2, ..., and
02180      * denote the number of values of each key in the outer relation as m1,
02181      * m2, ...; in the inner relation, n1, n2, ...  Then we have
02182      *
02183      * size of join = m1 * n1 + m2 * n2 + ...
02184      *
02185      * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
02186      * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
02187      * relation
02188      *
02189      * This equation works correctly for outer tuples having no inner match
02190      * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
02191      * are effectively subtracting those from the number of rescanned tuples,
02192      * when we should not.  Can we do better without expensive selectivity
02193      * computations?
02194      *
02195      * The whole issue is moot if we are working from a unique-ified outer
02196      * input.
02197      */
02198     if (IsA(outer_path, UniquePath))
02199         rescannedtuples = 0;
02200     else
02201     {
02202         rescannedtuples = mergejointuples - inner_path_rows;
02203         /* Must clamp because of possible underestimate */
02204         if (rescannedtuples < 0)
02205             rescannedtuples = 0;
02206     }
02207     /* We'll inflate various costs this much to account for rescanning */
02208     rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
02209 
02210     /*
02211      * Decide whether we want to materialize the inner input to shield it from
02212      * mark/restore and performing re-fetches.  Our cost model for regular
02213      * re-fetches is that a re-fetch costs the same as an original fetch,
02214      * which is probably an overestimate; but on the other hand we ignore the
02215      * bookkeeping costs of mark/restore.  Not clear if it's worth developing
02216      * a more refined model.  So we just need to inflate the inner run cost by
02217      * rescanratio.
02218      */
02219     bare_inner_cost = inner_run_cost * rescanratio;
02220 
02221     /*
02222      * When we interpose a Material node the re-fetch cost is assumed to be
02223      * just cpu_operator_cost per tuple, independently of the underlying
02224      * plan's cost; and we charge an extra cpu_operator_cost per original
02225      * fetch as well.  Note that we're assuming the materialize node will
02226      * never spill to disk, since it only has to remember tuples back to the
02227      * last mark.  (If there are a huge number of duplicates, our other cost
02228      * factors will make the path so expensive that it probably won't get
02229      * chosen anyway.)  So we don't use cost_rescan here.
02230      *
02231      * Note: keep this estimate in sync with create_mergejoin_plan's labeling
02232      * of the generated Material node.
02233      */
02234     mat_inner_cost = inner_run_cost +
02235         cpu_operator_cost * inner_path_rows * rescanratio;
02236 
02237     /*
02238      * Prefer materializing if it looks cheaper, unless the user has asked to
02239      * suppress materialization.
02240      */
02241     if (enable_material && mat_inner_cost < bare_inner_cost)
02242         path->materialize_inner = true;
02243 
02244     /*
02245      * Even if materializing doesn't look cheaper, we *must* do it if the
02246      * inner path is to be used directly (without sorting) and it doesn't
02247      * support mark/restore.
02248      *
02249      * Since the inner side must be ordered, and only Sorts and IndexScans can
02250      * create order to begin with, and they both support mark/restore, you
02251      * might think there's no problem --- but you'd be wrong.  Nestloop and
02252      * merge joins can *preserve* the order of their inputs, so they can be
02253      * selected as the input of a mergejoin, and they don't support
02254      * mark/restore at present.
02255      *
02256      * We don't test the value of enable_material here, because
02257      * materialization is required for correctness in this case, and turning
02258      * it off does not entitle us to deliver an invalid plan.
02259      */
02260     else if (innersortkeys == NIL &&
02261              !ExecSupportsMarkRestore(inner_path->pathtype))
02262         path->materialize_inner = true;
02263 
02264     /*
02265      * Also, force materializing if the inner path is to be sorted and the
02266      * sort is expected to spill to disk.  This is because the final merge
02267      * pass can be done on-the-fly if it doesn't have to support mark/restore.
02268      * We don't try to adjust the cost estimates for this consideration,
02269      * though.
02270      *
02271      * Since materialization is a performance optimization in this case,
02272      * rather than necessary for correctness, we skip it if enable_material is
02273      * off.
02274      */
02275     else if (enable_material && innersortkeys != NIL &&
02276              relation_byte_size(inner_path_rows, inner_path->parent->width) >
02277              (work_mem * 1024L))
02278         path->materialize_inner = true;
02279     else
02280         path->materialize_inner = false;
02281 
02282     /* Charge the right incremental cost for the chosen case */
02283     if (path->materialize_inner)
02284         run_cost += mat_inner_cost;
02285     else
02286         run_cost += bare_inner_cost;
02287 
02288     /* CPU costs */
02289 
02290     /*
02291      * The number of tuple comparisons needed is approximately number of outer
02292      * rows plus number of inner rows plus number of rescanned tuples (can we
02293      * refine this?).  At each one, we need to evaluate the mergejoin quals.
02294      */
02295     startup_cost += merge_qual_cost.startup;
02296     startup_cost += merge_qual_cost.per_tuple *
02297         (outer_skip_rows + inner_skip_rows * rescanratio);
02298     run_cost += merge_qual_cost.per_tuple *
02299         ((outer_rows - outer_skip_rows) +
02300          (inner_rows - inner_skip_rows) * rescanratio);
02301 
02302     /*
02303      * For each tuple that gets through the mergejoin proper, we charge
02304      * cpu_tuple_cost plus the cost of evaluating additional restriction
02305      * clauses that are to be applied at the join.  (This is pessimistic since
02306      * not all of the quals may get evaluated at each tuple.)
02307      *
02308      * Note: we could adjust for SEMI/ANTI joins skipping some qual
02309      * evaluations here, but it's probably not worth the trouble.
02310      */
02311     startup_cost += qp_qual_cost.startup;
02312     cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
02313     run_cost += cpu_per_tuple * mergejointuples;
02314 
02315     path->jpath.path.startup_cost = startup_cost;
02316     path->jpath.path.total_cost = startup_cost + run_cost;
02317 }
02318 
02319 /*
02320  * run mergejoinscansel() with caching
02321  */
02322 static MergeScanSelCache *
02323 cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
02324 {
02325     MergeScanSelCache *cache;
02326     ListCell   *lc;
02327     Selectivity leftstartsel,
02328                 leftendsel,
02329                 rightstartsel,
02330                 rightendsel;
02331     MemoryContext oldcontext;
02332 
02333     /* Do we have this result already? */
02334     foreach(lc, rinfo->scansel_cache)
02335     {
02336         cache = (MergeScanSelCache *) lfirst(lc);
02337         if (cache->opfamily == pathkey->pk_opfamily &&
02338             cache->collation == pathkey->pk_eclass->ec_collation &&
02339             cache->strategy == pathkey->pk_strategy &&
02340             cache->nulls_first == pathkey->pk_nulls_first)
02341             return cache;
02342     }
02343 
02344     /* Nope, do the computation */
02345     mergejoinscansel(root,
02346                      (Node *) rinfo->clause,
02347                      pathkey->pk_opfamily,
02348                      pathkey->pk_strategy,
02349                      pathkey->pk_nulls_first,
02350                      &leftstartsel,
02351                      &leftendsel,
02352                      &rightstartsel,
02353                      &rightendsel);
02354 
02355     /* Cache the result in suitably long-lived workspace */
02356     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
02357 
02358     cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
02359     cache->opfamily = pathkey->pk_opfamily;
02360     cache->collation = pathkey->pk_eclass->ec_collation;
02361     cache->strategy = pathkey->pk_strategy;
02362     cache->nulls_first = pathkey->pk_nulls_first;
02363     cache->leftstartsel = leftstartsel;
02364     cache->leftendsel = leftendsel;
02365     cache->rightstartsel = rightstartsel;
02366     cache->rightendsel = rightendsel;
02367 
02368     rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
02369 
02370     MemoryContextSwitchTo(oldcontext);
02371 
02372     return cache;
02373 }
02374 
02375 /*
02376  * initial_cost_hashjoin
02377  *    Preliminary estimate of the cost of a hashjoin path.
02378  *
02379  * This must quickly produce lower-bound estimates of the path's startup and
02380  * total costs.  If we are unable to eliminate the proposed path from
02381  * consideration using the lower bounds, final_cost_hashjoin will be called
02382  * to obtain the final estimates.
02383  *
02384  * The exact division of labor between this function and final_cost_hashjoin
02385  * is private to them, and represents a tradeoff between speed of the initial
02386  * estimate and getting a tight lower bound.  We choose to not examine the
02387  * join quals here (other than by counting the number of hash clauses),
02388  * so we can't do much with CPU costs.  We do assume that
02389  * ExecChooseHashTableSize is cheap enough to use here.
02390  *
02391  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
02392  *      other data to be used by final_cost_hashjoin
02393  * 'jointype' is the type of join to be performed
02394  * 'hashclauses' is the list of joinclauses to be used as hash clauses
02395  * 'outer_path' is the outer input to the join
02396  * 'inner_path' is the inner input to the join
02397  * 'sjinfo' is extra info about the join for selectivity estimation
02398  * 'semifactors' contains valid data if jointype is SEMI or ANTI
02399  */
02400 void
02401 initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
02402                       JoinType jointype,
02403                       List *hashclauses,
02404                       Path *outer_path, Path *inner_path,
02405                       SpecialJoinInfo *sjinfo,
02406                       SemiAntiJoinFactors *semifactors)
02407 {
02408     Cost        startup_cost = 0;
02409     Cost        run_cost = 0;
02410     double      outer_path_rows = outer_path->rows;
02411     double      inner_path_rows = inner_path->rows;
02412     int         num_hashclauses = list_length(hashclauses);
02413     int         numbuckets;
02414     int         numbatches;
02415     int         num_skew_mcvs;
02416 
02417     /* cost of source data */
02418     startup_cost += outer_path->startup_cost;
02419     run_cost += outer_path->total_cost - outer_path->startup_cost;
02420     startup_cost += inner_path->total_cost;
02421 
02422     /*
02423      * Cost of computing hash function: must do it once per input tuple. We
02424      * charge one cpu_operator_cost for each column's hash function.  Also,
02425      * tack on one cpu_tuple_cost per inner row, to model the costs of
02426      * inserting the row into the hashtable.
02427      *
02428      * XXX when a hashclause is more complex than a single operator, we really
02429      * should charge the extra eval costs of the left or right side, as
02430      * appropriate, here.  This seems more work than it's worth at the moment.
02431      */
02432     startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
02433         * inner_path_rows;
02434     run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
02435 
02436     /*
02437      * Get hash table size that executor would use for inner relation.
02438      *
02439      * XXX for the moment, always assume that skew optimization will be
02440      * performed.  As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
02441      * trying to determine that for sure.
02442      *
02443      * XXX at some point it might be interesting to try to account for skew
02444      * optimization in the cost estimate, but for now, we don't.
02445      */
02446     ExecChooseHashTableSize(inner_path_rows,
02447                             inner_path->parent->width,
02448                             true,       /* useskew */
02449                             &numbuckets,
02450                             &numbatches,
02451                             &num_skew_mcvs);
02452 
02453     /*
02454      * If inner relation is too big then we will need to "batch" the join,
02455      * which implies writing and reading most of the tuples to disk an extra
02456      * time.  Charge seq_page_cost per page, since the I/O should be nice and
02457      * sequential.  Writing the inner rel counts as startup cost, all the rest
02458      * as run cost.
02459      */
02460     if (numbatches > 1)
02461     {
02462         double      outerpages = page_size(outer_path_rows,
02463                                            outer_path->parent->width);
02464         double      innerpages = page_size(inner_path_rows,
02465                                            inner_path->parent->width);
02466 
02467         startup_cost += seq_page_cost * innerpages;
02468         run_cost += seq_page_cost * (innerpages + 2 * outerpages);
02469     }
02470 
02471     /* CPU costs left for later */
02472 
02473     /* Public result fields */
02474     workspace->startup_cost = startup_cost;
02475     workspace->total_cost = startup_cost + run_cost;
02476     /* Save private data for final_cost_hashjoin */
02477     workspace->run_cost = run_cost;
02478     workspace->numbuckets = numbuckets;
02479     workspace->numbatches = numbatches;
02480 }
02481 
02482 /*
02483  * final_cost_hashjoin
02484  *    Final estimate of the cost and result size of a hashjoin path.
02485  *
02486  * Note: the numbatches estimate is also saved into 'path' for use later
02487  *
02488  * 'path' is already filled in except for the rows and cost fields and
02489  *      num_batches
02490  * 'workspace' is the result from initial_cost_hashjoin
02491  * 'sjinfo' is extra info about the join for selectivity estimation
02492  * 'semifactors' contains valid data if path->jointype is SEMI or ANTI
02493  */
02494 void
02495 final_cost_hashjoin(PlannerInfo *root, HashPath *path,
02496                     JoinCostWorkspace *workspace,
02497                     SpecialJoinInfo *sjinfo,
02498                     SemiAntiJoinFactors *semifactors)
02499 {
02500     Path       *outer_path = path->jpath.outerjoinpath;
02501     Path       *inner_path = path->jpath.innerjoinpath;
02502     double      outer_path_rows = outer_path->rows;
02503     double      inner_path_rows = inner_path->rows;
02504     List       *hashclauses = path->path_hashclauses;
02505     Cost        startup_cost = workspace->startup_cost;
02506     Cost        run_cost = workspace->run_cost;
02507     int         numbuckets = workspace->numbuckets;
02508     int         numbatches = workspace->numbatches;
02509     Cost        cpu_per_tuple;
02510     QualCost    hash_qual_cost;
02511     QualCost    qp_qual_cost;
02512     double      hashjointuples;
02513     double      virtualbuckets;
02514     Selectivity innerbucketsize;
02515     ListCell   *hcl;
02516 
02517     /* Mark the path with the correct row estimate */
02518     if (path->jpath.path.param_info)
02519         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
02520     else
02521         path->jpath.path.rows = path->jpath.path.parent->rows;
02522 
02523     /*
02524      * We could include disable_cost in the preliminary estimate, but that
02525      * would amount to optimizing for the case where the join method is
02526      * disabled, which doesn't seem like the way to bet.
02527      */
02528     if (!enable_hashjoin)
02529         startup_cost += disable_cost;
02530 
02531     /* mark the path with estimated # of batches */
02532     path->num_batches = numbatches;
02533 
02534     /* and compute the number of "virtual" buckets in the whole join */
02535     virtualbuckets = (double) numbuckets *(double) numbatches;
02536 
02537     /*
02538      * Determine bucketsize fraction for inner relation.  We use the smallest
02539      * bucketsize estimated for any individual hashclause; this is undoubtedly
02540      * conservative.
02541      *
02542      * BUT: if inner relation has been unique-ified, we can assume it's good
02543      * for hashing.  This is important both because it's the right answer, and
02544      * because we avoid contaminating the cache with a value that's wrong for
02545      * non-unique-ified paths.
02546      */
02547     if (IsA(inner_path, UniquePath))
02548         innerbucketsize = 1.0 / virtualbuckets;
02549     else
02550     {
02551         innerbucketsize = 1.0;
02552         foreach(hcl, hashclauses)
02553         {
02554             RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(hcl);
02555             Selectivity thisbucketsize;
02556 
02557             Assert(IsA(restrictinfo, RestrictInfo));
02558 
02559             /*
02560              * First we have to figure out which side of the hashjoin clause
02561              * is the inner side.
02562              *
02563              * Since we tend to visit the same clauses over and over when
02564              * planning a large query, we cache the bucketsize estimate in the
02565              * RestrictInfo node to avoid repeated lookups of statistics.
02566              */
02567             if (bms_is_subset(restrictinfo->right_relids,
02568                               inner_path->parent->relids))
02569             {
02570                 /* righthand side is inner */
02571                 thisbucketsize = restrictinfo->right_bucketsize;
02572                 if (thisbucketsize < 0)
02573                 {
02574                     /* not cached yet */
02575                     thisbucketsize =
02576                         estimate_hash_bucketsize(root,
02577                                            get_rightop(restrictinfo->clause),
02578                                                  virtualbuckets);
02579                     restrictinfo->right_bucketsize = thisbucketsize;
02580                 }
02581             }
02582             else
02583             {
02584                 Assert(bms_is_subset(restrictinfo->left_relids,
02585                                      inner_path->parent->relids));
02586                 /* lefthand side is inner */
02587                 thisbucketsize = restrictinfo->left_bucketsize;
02588                 if (thisbucketsize < 0)
02589                 {
02590                     /* not cached yet */
02591                     thisbucketsize =
02592                         estimate_hash_bucketsize(root,
02593                                             get_leftop(restrictinfo->clause),
02594                                                  virtualbuckets);
02595                     restrictinfo->left_bucketsize = thisbucketsize;
02596                 }
02597             }
02598 
02599             if (innerbucketsize > thisbucketsize)
02600                 innerbucketsize = thisbucketsize;
02601         }
02602     }
02603 
02604     /*
02605      * Compute cost of the hashquals and qpquals (other restriction clauses)
02606      * separately.
02607      */
02608     cost_qual_eval(&hash_qual_cost, hashclauses, root);
02609     cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
02610     qp_qual_cost.startup -= hash_qual_cost.startup;
02611     qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
02612 
02613     /* CPU costs */
02614 
02615     if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI)
02616     {
02617         double      outer_matched_rows;
02618         Selectivity inner_scan_frac;
02619 
02620         /*
02621          * SEMI or ANTI join: executor will stop after first match.
02622          *
02623          * For an outer-rel row that has at least one match, we can expect the
02624          * bucket scan to stop after a fraction 1/(match_count+1) of the
02625          * bucket's rows, if the matches are evenly distributed.  Since they
02626          * probably aren't quite evenly distributed, we apply a fuzz factor of
02627          * 2.0 to that fraction.  (If we used a larger fuzz factor, we'd have
02628          * to clamp inner_scan_frac to at most 1.0; but since match_count is
02629          * at least 1, no such clamp is needed now.)
02630          */
02631         outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
02632         inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
02633 
02634         startup_cost += hash_qual_cost.startup;
02635         run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
02636             clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
02637 
02638         /*
02639          * For unmatched outer-rel rows, the picture is quite a lot different.
02640          * In the first place, there is no reason to assume that these rows
02641          * preferentially hit heavily-populated buckets; instead assume they
02642          * are uncorrelated with the inner distribution and so they see an
02643          * average bucket size of inner_path_rows / virtualbuckets.  In the
02644          * second place, it seems likely that they will have few if any exact
02645          * hash-code matches and so very few of the tuples in the bucket will
02646          * actually require eval of the hash quals.  We don't have any good
02647          * way to estimate how many will, but for the moment assume that the
02648          * effective cost per bucket entry is one-tenth what it is for
02649          * matchable tuples.
02650          */
02651         run_cost += hash_qual_cost.per_tuple *
02652             (outer_path_rows - outer_matched_rows) *
02653             clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
02654 
02655         /* Get # of tuples that will pass the basic join */
02656         if (path->jpath.jointype == JOIN_SEMI)
02657             hashjointuples = outer_matched_rows;
02658         else
02659             hashjointuples = outer_path_rows - outer_matched_rows;
02660     }
02661     else
02662     {
02663         /*
02664          * The number of tuple comparisons needed is the number of outer
02665          * tuples times the typical number of tuples in a hash bucket, which
02666          * is the inner relation size times its bucketsize fraction.  At each
02667          * one, we need to evaluate the hashjoin quals.  But actually,
02668          * charging the full qual eval cost at each tuple is pessimistic,
02669          * since we don't evaluate the quals unless the hash values match
02670          * exactly.  For lack of a better idea, halve the cost estimate to
02671          * allow for that.
02672          */
02673         startup_cost += hash_qual_cost.startup;
02674         run_cost += hash_qual_cost.per_tuple * outer_path_rows *
02675             clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
02676 
02677         /*
02678          * Get approx # tuples passing the hashquals.  We use
02679          * approx_tuple_count here because we need an estimate done with
02680          * JOIN_INNER semantics.
02681          */
02682         hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
02683     }
02684 
02685     /*
02686      * For each tuple that gets through the hashjoin proper, we charge
02687      * cpu_tuple_cost plus the cost of evaluating additional restriction
02688      * clauses that are to be applied at the join.  (This is pessimistic since
02689      * not all of the quals may get evaluated at each tuple.)
02690      */
02691     startup_cost += qp_qual_cost.startup;
02692     cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
02693     run_cost += cpu_per_tuple * hashjointuples;
02694 
02695     path->jpath.path.startup_cost = startup_cost;
02696     path->jpath.path.total_cost = startup_cost + run_cost;
02697 }
02698 
02699 
02700 /*
02701  * cost_subplan
02702  *      Figure the costs for a SubPlan (or initplan).
02703  *
02704  * Note: we could dig the subplan's Plan out of the root list, but in practice
02705  * all callers have it handy already, so we make them pass it.
02706  */
02707 void
02708 cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
02709 {
02710     QualCost    sp_cost;
02711 
02712     /* Figure any cost for evaluating the testexpr */
02713     cost_qual_eval(&sp_cost,
02714                    make_ands_implicit((Expr *) subplan->testexpr),
02715                    root);
02716 
02717     if (subplan->useHashTable)
02718     {
02719         /*
02720          * If we are using a hash table for the subquery outputs, then the
02721          * cost of evaluating the query is a one-time cost.  We charge one
02722          * cpu_operator_cost per tuple for the work of loading the hashtable,
02723          * too.
02724          */
02725         sp_cost.startup += plan->total_cost +
02726             cpu_operator_cost * plan->plan_rows;
02727 
02728         /*
02729          * The per-tuple costs include the cost of evaluating the lefthand
02730          * expressions, plus the cost of probing the hashtable.  We already
02731          * accounted for the lefthand expressions as part of the testexpr, and
02732          * will also have counted one cpu_operator_cost for each comparison
02733          * operator.  That is probably too low for the probing cost, but it's
02734          * hard to make a better estimate, so live with it for now.
02735          */
02736     }
02737     else
02738     {
02739         /*
02740          * Otherwise we will be rescanning the subplan output on each
02741          * evaluation.  We need to estimate how much of the output we will
02742          * actually need to scan.  NOTE: this logic should agree with the
02743          * tuple_fraction estimates used by make_subplan() in
02744          * plan/subselect.c.
02745          */
02746         Cost        plan_run_cost = plan->total_cost - plan->startup_cost;
02747 
02748         if (subplan->subLinkType == EXISTS_SUBLINK)
02749         {
02750             /* we only need to fetch 1 tuple */
02751             sp_cost.per_tuple += plan_run_cost / plan->plan_rows;
02752         }
02753         else if (subplan->subLinkType == ALL_SUBLINK ||
02754                  subplan->subLinkType == ANY_SUBLINK)
02755         {
02756             /* assume we need 50% of the tuples */
02757             sp_cost.per_tuple += 0.50 * plan_run_cost;
02758             /* also charge a cpu_operator_cost per row examined */
02759             sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
02760         }
02761         else
02762         {
02763             /* assume we need all tuples */
02764             sp_cost.per_tuple += plan_run_cost;
02765         }
02766 
02767         /*
02768          * Also account for subplan's startup cost. If the subplan is
02769          * uncorrelated or undirect correlated, AND its topmost node is one
02770          * that materializes its output, assume that we'll only need to pay
02771          * its startup cost once; otherwise assume we pay the startup cost
02772          * every time.
02773          */
02774         if (subplan->parParam == NIL &&
02775             ExecMaterializesOutput(nodeTag(plan)))
02776             sp_cost.startup += plan->startup_cost;
02777         else
02778             sp_cost.per_tuple += plan->startup_cost;
02779     }
02780 
02781     subplan->startup_cost = sp_cost.startup;
02782     subplan->per_call_cost = sp_cost.per_tuple;
02783 }
02784 
02785 
02786 /*
02787  * cost_rescan
02788  *      Given a finished Path, estimate the costs of rescanning it after
02789  *      having done so the first time.  For some Path types a rescan is
02790  *      cheaper than an original scan (if no parameters change), and this
02791  *      function embodies knowledge about that.  The default is to return
02792  *      the same costs stored in the Path.  (Note that the cost estimates
02793  *      actually stored in Paths are always for first scans.)
02794  *
02795  * This function is not currently intended to model effects such as rescans
02796  * being cheaper due to disk block caching; what we are concerned with is
02797  * plan types wherein the executor caches results explicitly, or doesn't
02798  * redo startup calculations, etc.
02799  */
02800 static void
02801 cost_rescan(PlannerInfo *root, Path *path,
02802             Cost *rescan_startup_cost,  /* output parameters */
02803             Cost *rescan_total_cost)
02804 {
02805     switch (path->pathtype)
02806     {
02807         case T_FunctionScan:
02808 
02809             /*
02810              * Currently, nodeFunctionscan.c always executes the function to
02811              * completion before returning any rows, and caches the results in
02812              * a tuplestore.  So the function eval cost is all startup cost
02813              * and isn't paid over again on rescans. However, all run costs
02814              * will be paid over again.
02815              */
02816             *rescan_startup_cost = 0;
02817             *rescan_total_cost = path->total_cost - path->startup_cost;
02818             break;
02819         case T_HashJoin:
02820 
02821             /*
02822              * Assume that all of the startup cost represents hash table
02823              * building, which we won't have to do over.
02824              */
02825             *rescan_startup_cost = 0;
02826             *rescan_total_cost = path->total_cost - path->startup_cost;
02827             break;
02828         case T_CteScan:
02829         case T_WorkTableScan:
02830             {
02831                 /*
02832                  * These plan types materialize their final result in a
02833                  * tuplestore or tuplesort object.  So the rescan cost is only
02834                  * cpu_tuple_cost per tuple, unless the result is large enough
02835                  * to spill to disk.
02836                  */
02837                 Cost        run_cost = cpu_tuple_cost * path->rows;
02838                 double      nbytes = relation_byte_size(path->rows,
02839                                                         path->parent->width);
02840                 long        work_mem_bytes = work_mem * 1024L;
02841 
02842                 if (nbytes > work_mem_bytes)
02843                 {
02844                     /* It will spill, so account for re-read cost */
02845                     double      npages = ceil(nbytes / BLCKSZ);
02846 
02847                     run_cost += seq_page_cost * npages;
02848                 }
02849                 *rescan_startup_cost = 0;
02850                 *rescan_total_cost = run_cost;
02851             }
02852             break;
02853         case T_Material:
02854         case T_Sort:
02855             {
02856                 /*
02857                  * These plan types not only materialize their results, but do
02858                  * not implement qual filtering or projection.  So they are
02859                  * even cheaper to rescan than the ones above.  We charge only
02860                  * cpu_operator_cost per tuple.  (Note: keep that in sync with
02861                  * the run_cost charge in cost_sort, and also see comments in
02862                  * cost_material before you change it.)
02863                  */
02864                 Cost        run_cost = cpu_operator_cost * path->rows;
02865                 double      nbytes = relation_byte_size(path->rows,
02866                                                         path->parent->width);
02867                 long        work_mem_bytes = work_mem * 1024L;
02868 
02869                 if (nbytes > work_mem_bytes)
02870                 {
02871                     /* It will spill, so account for re-read cost */
02872                     double      npages = ceil(nbytes / BLCKSZ);
02873 
02874                     run_cost += seq_page_cost * npages;
02875                 }
02876                 *rescan_startup_cost = 0;
02877                 *rescan_total_cost = run_cost;
02878             }
02879             break;
02880         default:
02881             *rescan_startup_cost = path->startup_cost;
02882             *rescan_total_cost = path->total_cost;
02883             break;
02884     }
02885 }
02886 
02887 
02888 /*
02889  * cost_qual_eval
02890  *      Estimate the CPU costs of evaluating a WHERE clause.
02891  *      The input can be either an implicitly-ANDed list of boolean
02892  *      expressions, or a list of RestrictInfo nodes.  (The latter is
02893  *      preferred since it allows caching of the results.)
02894  *      The result includes both a one-time (startup) component,
02895  *      and a per-evaluation component.
02896  */
02897 void
02898 cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
02899 {
02900     cost_qual_eval_context context;
02901     ListCell   *l;
02902 
02903     context.root = root;
02904     context.total.startup = 0;
02905     context.total.per_tuple = 0;
02906 
02907     /* We don't charge any cost for the implicit ANDing at top level ... */
02908 
02909     foreach(l, quals)
02910     {
02911         Node       *qual = (Node *) lfirst(l);
02912 
02913         cost_qual_eval_walker(qual, &context);
02914     }
02915 
02916     *cost = context.total;
02917 }
02918 
02919 /*
02920  * cost_qual_eval_node
02921  *      As above, for a single RestrictInfo or expression.
02922  */
02923 void
02924 cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
02925 {
02926     cost_qual_eval_context context;
02927 
02928     context.root = root;
02929     context.total.startup = 0;
02930     context.total.per_tuple = 0;
02931 
02932     cost_qual_eval_walker(qual, &context);
02933 
02934     *cost = context.total;
02935 }
02936 
02937 static bool
02938 cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
02939 {
02940     if (node == NULL)
02941         return false;
02942 
02943     /*
02944      * RestrictInfo nodes contain an eval_cost field reserved for this
02945      * routine's use, so that it's not necessary to evaluate the qual clause's
02946      * cost more than once.  If the clause's cost hasn't been computed yet,
02947      * the field's startup value will contain -1.
02948      */
02949     if (IsA(node, RestrictInfo))
02950     {
02951         RestrictInfo *rinfo = (RestrictInfo *) node;
02952 
02953         if (rinfo->eval_cost.startup < 0)
02954         {
02955             cost_qual_eval_context locContext;
02956 
02957             locContext.root = context->root;
02958             locContext.total.startup = 0;
02959             locContext.total.per_tuple = 0;
02960 
02961             /*
02962              * For an OR clause, recurse into the marked-up tree so that we
02963              * set the eval_cost for contained RestrictInfos too.
02964              */
02965             if (rinfo->orclause)
02966                 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
02967             else
02968                 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
02969 
02970             /*
02971              * If the RestrictInfo is marked pseudoconstant, it will be tested
02972              * only once, so treat its cost as all startup cost.
02973              */
02974             if (rinfo->pseudoconstant)
02975             {
02976                 /* count one execution during startup */
02977                 locContext.total.startup += locContext.total.per_tuple;
02978                 locContext.total.per_tuple = 0;
02979             }
02980             rinfo->eval_cost = locContext.total;
02981         }
02982         context->total.startup += rinfo->eval_cost.startup;
02983         context->total.per_tuple += rinfo->eval_cost.per_tuple;
02984         /* do NOT recurse into children */
02985         return false;
02986     }
02987 
02988     /*
02989      * For each operator or function node in the given tree, we charge the
02990      * estimated execution cost given by pg_proc.procost (remember to multiply
02991      * this by cpu_operator_cost).
02992      *
02993      * Vars and Consts are charged zero, and so are boolean operators (AND,
02994      * OR, NOT). Simplistic, but a lot better than no model at all.
02995      *
02996      * Should we try to account for the possibility of short-circuit
02997      * evaluation of AND/OR?  Probably *not*, because that would make the
02998      * results depend on the clause ordering, and we are not in any position
02999      * to expect that the current ordering of the clauses is the one that's
03000      * going to end up being used.  The above per-RestrictInfo caching would
03001      * not mix well with trying to re-order clauses anyway.
03002      *
03003      * Another issue that is entirely ignored here is that if a set-returning
03004      * function is below top level in the tree, the functions/operators above
03005      * it will need to be evaluated multiple times.  In practical use, such
03006      * cases arise so seldom as to not be worth the added complexity needed;
03007      * moreover, since our rowcount estimates for functions tend to be pretty
03008      * phony, the results would also be pretty phony.
03009      */
03010     if (IsA(node, FuncExpr))
03011     {
03012         context->total.per_tuple +=
03013             get_func_cost(((FuncExpr *) node)->funcid) * cpu_operator_cost;
03014     }
03015     else if (IsA(node, OpExpr) ||
03016              IsA(node, DistinctExpr) ||
03017              IsA(node, NullIfExpr))
03018     {
03019         /* rely on struct equivalence to treat these all alike */
03020         set_opfuncid((OpExpr *) node);
03021         context->total.per_tuple +=
03022             get_func_cost(((OpExpr *) node)->opfuncid) * cpu_operator_cost;
03023     }
03024     else if (IsA(node, ScalarArrayOpExpr))
03025     {
03026         /*
03027          * Estimate that the operator will be applied to about half of the
03028          * array elements before the answer is determined.
03029          */
03030         ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
03031         Node       *arraynode = (Node *) lsecond(saop->args);
03032 
03033         set_sa_opfuncid(saop);
03034         context->total.per_tuple += get_func_cost(saop->opfuncid) *
03035             cpu_operator_cost * estimate_array_length(arraynode) * 0.5;
03036     }
03037     else if (IsA(node, Aggref) ||
03038              IsA(node, WindowFunc))
03039     {
03040         /*
03041          * Aggref and WindowFunc nodes are (and should be) treated like Vars,
03042          * ie, zero execution cost in the current model, because they behave
03043          * essentially like Vars in execQual.c.  We disregard the costs of
03044          * their input expressions for the same reason.  The actual execution
03045          * costs of the aggregate/window functions and their arguments have to
03046          * be factored into plan-node-specific costing of the Agg or WindowAgg
03047          * plan node.
03048          */
03049         return false;           /* don't recurse into children */
03050     }
03051     else if (IsA(node, CoerceViaIO))
03052     {
03053         CoerceViaIO *iocoerce = (CoerceViaIO *) node;
03054         Oid         iofunc;
03055         Oid         typioparam;
03056         bool        typisvarlena;
03057 
03058         /* check the result type's input function */
03059         getTypeInputInfo(iocoerce->resulttype,
03060                          &iofunc, &typioparam);
03061         context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
03062         /* check the input type's output function */
03063         getTypeOutputInfo(exprType((Node *) iocoerce->arg),
03064                           &iofunc, &typisvarlena);
03065         context->total.per_tuple += get_func_cost(iofunc) * cpu_operator_cost;
03066     }
03067     else if (IsA(node, ArrayCoerceExpr))
03068     {
03069         ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
03070         Node       *arraynode = (Node *) acoerce->arg;
03071 
03072         if (OidIsValid(acoerce->elemfuncid))
03073             context->total.per_tuple += get_func_cost(acoerce->elemfuncid) *
03074                 cpu_operator_cost * estimate_array_length(arraynode);
03075     }
03076     else if (IsA(node, RowCompareExpr))
03077     {
03078         /* Conservatively assume we will check all the columns */
03079         RowCompareExpr *rcexpr = (RowCompareExpr *) node;
03080         ListCell   *lc;
03081 
03082         foreach(lc, rcexpr->opnos)
03083         {
03084             Oid         opid = lfirst_oid(lc);
03085 
03086             context->total.per_tuple += get_func_cost(get_opcode(opid)) *
03087                 cpu_operator_cost;
03088         }
03089     }
03090     else if (IsA(node, CurrentOfExpr))
03091     {
03092         /* Report high cost to prevent selection of anything but TID scan */
03093         context->total.startup += disable_cost;
03094     }
03095     else if (IsA(node, SubLink))
03096     {
03097         /* This routine should not be applied to un-planned expressions */
03098         elog(ERROR, "cannot handle unplanned sub-select");
03099     }
03100     else if (IsA(node, SubPlan))
03101     {
03102         /*
03103          * A subplan node in an expression typically indicates that the
03104          * subplan will be executed on each evaluation, so charge accordingly.
03105          * (Sub-selects that can be executed as InitPlans have already been
03106          * removed from the expression.)
03107          */
03108         SubPlan    *subplan = (SubPlan *) node;
03109 
03110         context->total.startup += subplan->startup_cost;
03111         context->total.per_tuple += subplan->per_call_cost;
03112 
03113         /*
03114          * We don't want to recurse into the testexpr, because it was already
03115          * counted in the SubPlan node's costs.  So we're done.
03116          */
03117         return false;
03118     }
03119     else if (IsA(node, AlternativeSubPlan))
03120     {
03121         /*
03122          * Arbitrarily use the first alternative plan for costing.  (We should
03123          * certainly only include one alternative, and we don't yet have
03124          * enough information to know which one the executor is most likely to
03125          * use.)
03126          */
03127         AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
03128 
03129         return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
03130                                      context);
03131     }
03132 
03133     /* recurse into children */
03134     return expression_tree_walker(node, cost_qual_eval_walker,
03135                                   (void *) context);
03136 }
03137 
03138 /*
03139  * get_restriction_qual_cost
03140  *    Compute evaluation costs of a baserel's restriction quals, plus any
03141  *    movable join quals that have been pushed down to the scan.
03142  *    Results are returned into *qpqual_cost.
03143  *
03144  * This is a convenience subroutine that works for seqscans and other cases
03145  * where all the given quals will be evaluated the hard way.  It's not useful
03146  * for cost_index(), for example, where the index machinery takes care of
03147  * some of the quals.  We assume baserestrictcost was previously set by
03148  * set_baserel_size_estimates().
03149  */
03150 static void
03151 get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
03152                           ParamPathInfo *param_info,
03153                           QualCost *qpqual_cost)
03154 {
03155     if (param_info)
03156     {
03157         /* Include costs of pushed-down clauses */
03158         cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
03159 
03160         qpqual_cost->startup += baserel->baserestrictcost.startup;
03161         qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
03162     }
03163     else
03164         *qpqual_cost = baserel->baserestrictcost;
03165 }
03166 
03167 
03168 /*
03169  * compute_semi_anti_join_factors
03170  *    Estimate how much of the inner input a SEMI or ANTI join
03171  *    can be expected to scan.
03172  *
03173  * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
03174  * inner rows as soon as it finds a match to the current outer row.
03175  * We should therefore adjust some of the cost components for this effect.
03176  * This function computes some estimates needed for these adjustments.
03177  * These estimates will be the same regardless of the particular paths used
03178  * for the outer and inner relation, so we compute these once and then pass
03179  * them to all the join cost estimation functions.
03180  *
03181  * Input parameters:
03182  *  outerrel: outer relation under consideration
03183  *  innerrel: inner relation under consideration
03184  *  jointype: must be JOIN_SEMI or JOIN_ANTI
03185  *  sjinfo: SpecialJoinInfo relevant to this join
03186  *  restrictlist: join quals
03187  * Output parameters:
03188  *  *semifactors is filled in (see relation.h for field definitions)
03189  */
03190 void
03191 compute_semi_anti_join_factors(PlannerInfo *root,
03192                                RelOptInfo *outerrel,
03193                                RelOptInfo *innerrel,
03194                                JoinType jointype,
03195                                SpecialJoinInfo *sjinfo,
03196                                List *restrictlist,
03197                                SemiAntiJoinFactors *semifactors)
03198 {
03199     Selectivity jselec;
03200     Selectivity nselec;
03201     Selectivity avgmatch;
03202     SpecialJoinInfo norm_sjinfo;
03203     List       *joinquals;
03204     ListCell   *l;
03205 
03206     /* Should only be called in these cases */
03207     Assert(jointype == JOIN_SEMI || jointype == JOIN_ANTI);
03208 
03209     /*
03210      * In an ANTI join, we must ignore clauses that are "pushed down", since
03211      * those won't affect the match logic.  In a SEMI join, we do not
03212      * distinguish joinquals from "pushed down" quals, so just use the whole
03213      * restrictinfo list.
03214      */
03215     if (jointype == JOIN_ANTI)
03216     {
03217         joinquals = NIL;
03218         foreach(l, restrictlist)
03219         {
03220             RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
03221 
03222             Assert(IsA(rinfo, RestrictInfo));
03223             if (!rinfo->is_pushed_down)
03224                 joinquals = lappend(joinquals, rinfo);
03225         }
03226     }
03227     else
03228         joinquals = restrictlist;
03229 
03230     /*
03231      * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
03232      */
03233     jselec = clauselist_selectivity(root,
03234                                     joinquals,
03235                                     0,
03236                                     jointype,
03237                                     sjinfo);
03238 
03239     /*
03240      * Also get the normal inner-join selectivity of the join clauses.
03241      */
03242     norm_sjinfo.type = T_SpecialJoinInfo;
03243     norm_sjinfo.min_lefthand = outerrel->relids;
03244     norm_sjinfo.min_righthand = innerrel->relids;
03245     norm_sjinfo.syn_lefthand = outerrel->relids;
03246     norm_sjinfo.syn_righthand = innerrel->relids;
03247     norm_sjinfo.jointype = JOIN_INNER;
03248     /* we don't bother trying to make the remaining fields valid */
03249     norm_sjinfo.lhs_strict = false;
03250     norm_sjinfo.delay_upper_joins = false;
03251     norm_sjinfo.join_quals = NIL;
03252 
03253     nselec = clauselist_selectivity(root,
03254                                     joinquals,
03255                                     0,
03256                                     JOIN_INNER,
03257                                     &norm_sjinfo);
03258 
03259     /* Avoid leaking a lot of ListCells */
03260     if (jointype == JOIN_ANTI)
03261         list_free(joinquals);
03262 
03263     /*
03264      * jselec can be interpreted as the fraction of outer-rel rows that have
03265      * any matches (this is true for both SEMI and ANTI cases).  And nselec is
03266      * the fraction of the Cartesian product that matches.  So, the average
03267      * number of matches for each outer-rel row that has at least one match is
03268      * nselec * inner_rows / jselec.
03269      *
03270      * Note: it is correct to use the inner rel's "rows" count here, even
03271      * though we might later be considering a parameterized inner path with
03272      * fewer rows.  This is because we have included all the join clauses in
03273      * the selectivity estimate.
03274      */
03275     if (jselec > 0)             /* protect against zero divide */
03276     {
03277         avgmatch = nselec * innerrel->rows / jselec;
03278         /* Clamp to sane range */
03279         avgmatch = Max(1.0, avgmatch);
03280     }
03281     else
03282         avgmatch = 1.0;
03283 
03284     semifactors->outer_match_frac = jselec;
03285     semifactors->match_count = avgmatch;
03286 }
03287 
03288 /*
03289  * has_indexed_join_quals
03290  *    Check whether all the joinquals of a nestloop join are used as
03291  *    inner index quals.
03292  *
03293  * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
03294  * indexscan) that uses all the joinquals as indexquals, we can assume that an
03295  * unmatched outer tuple is cheap to process, whereas otherwise it's probably
03296  * expensive.
03297  */
03298 static bool
03299 has_indexed_join_quals(NestPath *joinpath)
03300 {
03301     Relids      joinrelids = joinpath->path.parent->relids;
03302     Path       *innerpath = joinpath->innerjoinpath;
03303     List       *indexclauses;
03304     bool        found_one;
03305     ListCell   *lc;
03306 
03307     /* If join still has quals to evaluate, it's not fast */
03308     if (joinpath->joinrestrictinfo != NIL)
03309         return false;
03310     /* Nor if the inner path isn't parameterized at all */
03311     if (innerpath->param_info == NULL)
03312         return false;
03313 
03314     /* Find the indexclauses list for the inner scan */
03315     switch (innerpath->pathtype)
03316     {
03317         case T_IndexScan:
03318         case T_IndexOnlyScan:
03319             indexclauses = ((IndexPath *) innerpath)->indexclauses;
03320             break;
03321         case T_BitmapHeapScan:
03322             {
03323                 /* Accept only a simple bitmap scan, not AND/OR cases */
03324                 Path       *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
03325 
03326                 if (IsA(bmqual, IndexPath))
03327                     indexclauses = ((IndexPath *) bmqual)->indexclauses;
03328                 else
03329                     return false;
03330                 break;
03331             }
03332         default:
03333 
03334             /*
03335              * If it's not a simple indexscan, it probably doesn't run quickly
03336              * for zero rows out, even if it's a parameterized path using all
03337              * the joinquals.
03338              */
03339             return false;
03340     }
03341 
03342     /*
03343      * Examine the inner path's param clauses.  Any that are from the outer
03344      * path must be found in the indexclauses list, either exactly or in an
03345      * equivalent form generated by equivclass.c.  Also, we must find at least
03346      * one such clause, else it's a clauseless join which isn't fast.
03347      */
03348     found_one = false;
03349     foreach(lc, innerpath->param_info->ppi_clauses)
03350     {
03351         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
03352 
03353         if (join_clause_is_movable_into(rinfo,
03354                                         innerpath->parent->relids,
03355                                         joinrelids))
03356         {
03357             if (!(list_member_ptr(indexclauses, rinfo) ||
03358                   is_redundant_derived_clause(rinfo, indexclauses)))
03359                 return false;
03360             found_one = true;
03361         }
03362     }
03363     return found_one;
03364 }
03365 
03366 
03367 /*
03368  * approx_tuple_count
03369  *      Quick-and-dirty estimation of the number of join rows passing
03370  *      a set of qual conditions.
03371  *
03372  * The quals can be either an implicitly-ANDed list of boolean expressions,
03373  * or a list of RestrictInfo nodes (typically the latter).
03374  *
03375  * We intentionally compute the selectivity under JOIN_INNER rules, even
03376  * if it's some type of outer join.  This is appropriate because we are
03377  * trying to figure out how many tuples pass the initial merge or hash
03378  * join step.
03379  *
03380  * This is quick-and-dirty because we bypass clauselist_selectivity, and
03381  * simply multiply the independent clause selectivities together.  Now
03382  * clauselist_selectivity often can't do any better than that anyhow, but
03383  * for some situations (such as range constraints) it is smarter.  However,
03384  * we can't effectively cache the results of clauselist_selectivity, whereas
03385  * the individual clause selectivities can be and are cached.
03386  *
03387  * Since we are only using the results to estimate how many potential
03388  * output tuples are generated and passed through qpqual checking, it
03389  * seems OK to live with the approximation.
03390  */
03391 static double
03392 approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
03393 {
03394     double      tuples;
03395     double      outer_tuples = path->outerjoinpath->rows;
03396     double      inner_tuples = path->innerjoinpath->rows;
03397     SpecialJoinInfo sjinfo;
03398     Selectivity selec = 1.0;
03399     ListCell   *l;
03400 
03401     /*
03402      * Make up a SpecialJoinInfo for JOIN_INNER semantics.
03403      */
03404     sjinfo.type = T_SpecialJoinInfo;
03405     sjinfo.min_lefthand = path->outerjoinpath->parent->relids;
03406     sjinfo.min_righthand = path->innerjoinpath->parent->relids;
03407     sjinfo.syn_lefthand = path->outerjoinpath->parent->relids;
03408     sjinfo.syn_righthand = path->innerjoinpath->parent->relids;
03409     sjinfo.jointype = JOIN_INNER;
03410     /* we don't bother trying to make the remaining fields valid */
03411     sjinfo.lhs_strict = false;
03412     sjinfo.delay_upper_joins = false;
03413     sjinfo.join_quals = NIL;
03414 
03415     /* Get the approximate selectivity */
03416     foreach(l, quals)
03417     {
03418         Node       *qual = (Node *) lfirst(l);
03419 
03420         /* Note that clause_selectivity will be able to cache its result */
03421         selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
03422     }
03423 
03424     /* Apply it to the input relation sizes */
03425     tuples = selec * outer_tuples * inner_tuples;
03426 
03427     return clamp_row_est(tuples);
03428 }
03429 
03430 
03431 /*
03432  * set_baserel_size_estimates
03433  *      Set the size estimates for the given base relation.
03434  *
03435  * The rel's targetlist and restrictinfo list must have been constructed
03436  * already, and rel->tuples must be set.
03437  *
03438  * We set the following fields of the rel node:
03439  *  rows: the estimated number of output tuples (after applying
03440  *        restriction clauses).
03441  *  width: the estimated average output tuple width in bytes.
03442  *  baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
03443  */
03444 void
03445 set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
03446 {
03447     double      nrows;
03448 
03449     /* Should only be applied to base relations */
03450     Assert(rel->relid > 0);
03451 
03452     nrows = rel->tuples *
03453         clauselist_selectivity(root,
03454                                rel->baserestrictinfo,
03455                                0,
03456                                JOIN_INNER,
03457                                NULL);
03458 
03459     rel->rows = clamp_row_est(nrows);
03460 
03461     cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
03462 
03463     set_rel_width(root, rel);
03464 }
03465 
03466 /*
03467  * get_parameterized_baserel_size
03468  *      Make a size estimate for a parameterized scan of a base relation.
03469  *
03470  * 'param_clauses' lists the additional join clauses to be used.
03471  *
03472  * set_baserel_size_estimates must have been applied already.
03473  */
03474 double
03475 get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel,
03476                                List *param_clauses)
03477 {
03478     List       *allclauses;
03479     double      nrows;
03480 
03481     /*
03482      * Estimate the number of rows returned by the parameterized scan, knowing
03483      * that it will apply all the extra join clauses as well as the rel's own
03484      * restriction clauses.  Note that we force the clauses to be treated as
03485      * non-join clauses during selectivity estimation.
03486      */
03487     allclauses = list_concat(list_copy(param_clauses),
03488                              rel->baserestrictinfo);
03489     nrows = rel->tuples *
03490         clauselist_selectivity(root,
03491                                allclauses,
03492                                rel->relid,      /* do not use 0! */
03493                                JOIN_INNER,
03494                                NULL);
03495     nrows = clamp_row_est(nrows);
03496     /* For safety, make sure result is not more than the base estimate */
03497     if (nrows > rel->rows)
03498         nrows = rel->rows;
03499     return nrows;
03500 }
03501 
03502 /*
03503  * set_joinrel_size_estimates
03504  *      Set the size estimates for the given join relation.
03505  *
03506  * The rel's targetlist must have been constructed already, and a
03507  * restriction clause list that matches the given component rels must
03508  * be provided.
03509  *
03510  * Since there is more than one way to make a joinrel for more than two
03511  * base relations, the results we get here could depend on which component
03512  * rel pair is provided.  In theory we should get the same answers no matter
03513  * which pair is provided; in practice, since the selectivity estimation
03514  * routines don't handle all cases equally well, we might not.  But there's
03515  * not much to be done about it.  (Would it make sense to repeat the
03516  * calculations for each pair of input rels that's encountered, and somehow
03517  * average the results?  Probably way more trouble than it's worth, and
03518  * anyway we must keep the rowcount estimate the same for all paths for the
03519  * joinrel.)
03520  *
03521  * We set only the rows field here.  The width field was already set by
03522  * build_joinrel_tlist, and baserestrictcost is not used for join rels.
03523  */
03524 void
03525 set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
03526                            RelOptInfo *outer_rel,
03527                            RelOptInfo *inner_rel,
03528                            SpecialJoinInfo *sjinfo,
03529                            List *restrictlist)
03530 {
03531     rel->rows = calc_joinrel_size_estimate(root,
03532                                            outer_rel->rows,
03533                                            inner_rel->rows,
03534                                            sjinfo,
03535                                            restrictlist);
03536 }
03537 
03538 /*
03539  * get_parameterized_joinrel_size
03540  *      Make a size estimate for a parameterized scan of a join relation.
03541  *
03542  * 'rel' is the joinrel under consideration.
03543  * 'outer_rows', 'inner_rows' are the sizes of the (probably also
03544  *      parameterized) join inputs under consideration.
03545  * 'sjinfo' is any SpecialJoinInfo relevant to this join.
03546  * 'restrict_clauses' lists the join clauses that need to be applied at the
03547  * join node (including any movable clauses that were moved down to this join,
03548  * and not including any movable clauses that were pushed down into the
03549  * child paths).
03550  *
03551  * set_joinrel_size_estimates must have been applied already.
03552  */
03553 double
03554 get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel,
03555                                double outer_rows,
03556                                double inner_rows,
03557                                SpecialJoinInfo *sjinfo,
03558                                List *restrict_clauses)
03559 {
03560     double      nrows;
03561 
03562     /*
03563      * Estimate the number of rows returned by the parameterized join as the
03564      * sizes of the input paths times the selectivity of the clauses that have
03565      * ended up at this join node.
03566      *
03567      * As with set_joinrel_size_estimates, the rowcount estimate could depend
03568      * on the pair of input paths provided, though ideally we'd get the same
03569      * estimate for any pair with the same parameterization.
03570      */
03571     nrows = calc_joinrel_size_estimate(root,
03572                                        outer_rows,
03573                                        inner_rows,
03574                                        sjinfo,
03575                                        restrict_clauses);
03576     /* For safety, make sure result is not more than the base estimate */
03577     if (nrows > rel->rows)
03578         nrows = rel->rows;
03579     return nrows;
03580 }
03581 
03582 /*
03583  * calc_joinrel_size_estimate
03584  *      Workhorse for set_joinrel_size_estimates and
03585  *      get_parameterized_joinrel_size.
03586  */
03587 static double
03588 calc_joinrel_size_estimate(PlannerInfo *root,
03589                            double outer_rows,
03590                            double inner_rows,
03591                            SpecialJoinInfo *sjinfo,
03592                            List *restrictlist)
03593 {
03594     JoinType    jointype = sjinfo->jointype;
03595     Selectivity jselec;
03596     Selectivity pselec;
03597     double      nrows;
03598 
03599     /*
03600      * Compute joinclause selectivity.  Note that we are only considering
03601      * clauses that become restriction clauses at this join level; we are not
03602      * double-counting them because they were not considered in estimating the
03603      * sizes of the component rels.
03604      *
03605      * For an outer join, we have to distinguish the selectivity of the join's
03606      * own clauses (JOIN/ON conditions) from any clauses that were "pushed
03607      * down".  For inner joins we just count them all as joinclauses.
03608      */
03609     if (IS_OUTER_JOIN(jointype))
03610     {
03611         List       *joinquals = NIL;
03612         List       *pushedquals = NIL;
03613         ListCell   *l;
03614 
03615         /* Grovel through the clauses to separate into two lists */
03616         foreach(l, restrictlist)
03617         {
03618             RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
03619 
03620             Assert(IsA(rinfo, RestrictInfo));
03621             if (rinfo->is_pushed_down)
03622                 pushedquals = lappend(pushedquals, rinfo);
03623             else
03624                 joinquals = lappend(joinquals, rinfo);
03625         }
03626 
03627         /* Get the separate selectivities */
03628         jselec = clauselist_selectivity(root,
03629                                         joinquals,
03630                                         0,
03631                                         jointype,
03632                                         sjinfo);
03633         pselec = clauselist_selectivity(root,
03634                                         pushedquals,
03635                                         0,
03636                                         jointype,
03637                                         sjinfo);
03638 
03639         /* Avoid leaking a lot of ListCells */
03640         list_free(joinquals);
03641         list_free(pushedquals);
03642     }
03643     else
03644     {
03645         jselec = clauselist_selectivity(root,
03646                                         restrictlist,
03647                                         0,
03648                                         jointype,
03649                                         sjinfo);
03650         pselec = 0.0;           /* not used, keep compiler quiet */
03651     }
03652 
03653     /*
03654      * Basically, we multiply size of Cartesian product by selectivity.
03655      *
03656      * If we are doing an outer join, take that into account: the joinqual
03657      * selectivity has to be clamped using the knowledge that the output must
03658      * be at least as large as the non-nullable input.  However, any
03659      * pushed-down quals are applied after the outer join, so their
03660      * selectivity applies fully.
03661      *
03662      * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
03663      * of LHS rows that have matches, and we apply that straightforwardly.
03664      */
03665     switch (jointype)
03666     {
03667         case JOIN_INNER:
03668             nrows = outer_rows * inner_rows * jselec;
03669             break;
03670         case JOIN_LEFT:
03671             nrows = outer_rows * inner_rows * jselec;
03672             if (nrows < outer_rows)
03673                 nrows = outer_rows;
03674             nrows *= pselec;
03675             break;
03676         case JOIN_FULL:
03677             nrows = outer_rows * inner_rows * jselec;
03678             if (nrows < outer_rows)
03679                 nrows = outer_rows;
03680             if (nrows < inner_rows)
03681                 nrows = inner_rows;
03682             nrows *= pselec;
03683             break;
03684         case JOIN_SEMI:
03685             nrows = outer_rows * jselec;
03686             /* pselec not used */
03687             break;
03688         case JOIN_ANTI:
03689             nrows = outer_rows * (1.0 - jselec);
03690             nrows *= pselec;
03691             break;
03692         default:
03693             /* other values not expected here */
03694             elog(ERROR, "unrecognized join type: %d", (int) jointype);
03695             nrows = 0;          /* keep compiler quiet */
03696             break;
03697     }
03698 
03699     return clamp_row_est(nrows);
03700 }
03701 
03702 /*
03703  * set_subquery_size_estimates
03704  *      Set the size estimates for a base relation that is a subquery.
03705  *
03706  * The rel's targetlist and restrictinfo list must have been constructed
03707  * already, and the plan for the subquery must have been completed.
03708  * We look at the subquery's plan and PlannerInfo to extract data.
03709  *
03710  * We set the same fields as set_baserel_size_estimates.
03711  */
03712 void
03713 set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
03714 {
03715     PlannerInfo *subroot = rel->subroot;
03716     RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
03717     ListCell   *lc;
03718 
03719     /* Should only be applied to base relations that are subqueries */
03720     Assert(rel->relid > 0);
03721     rte = planner_rt_fetch(rel->relid, root);
03722     Assert(rte->rtekind == RTE_SUBQUERY);
03723 
03724     /* Copy raw number of output rows from subplan */
03725     rel->tuples = rel->subplan->plan_rows;
03726 
03727     /*
03728      * Compute per-output-column width estimates by examining the subquery's
03729      * targetlist.  For any output that is a plain Var, get the width estimate
03730      * that was made while planning the subquery.  Otherwise, we leave it to
03731      * set_rel_width to fill in a datatype-based default estimate.
03732      */
03733     foreach(lc, subroot->parse->targetList)
03734     {
03735         TargetEntry *te = (TargetEntry *) lfirst(lc);
03736         Node       *texpr = (Node *) te->expr;
03737         int32       item_width = 0;
03738 
03739         Assert(IsA(te, TargetEntry));
03740         /* junk columns aren't visible to upper query */
03741         if (te->resjunk)
03742             continue;
03743 
03744         /*
03745          * The subquery could be an expansion of a view that's had columns
03746          * added to it since the current query was parsed, so that there are
03747          * non-junk tlist columns in it that don't correspond to any column
03748          * visible at our query level.  Ignore such columns.
03749          */
03750         if (te->resno < rel->min_attr || te->resno > rel->max_attr)
03751             continue;
03752 
03753         /*
03754          * XXX This currently doesn't work for subqueries containing set
03755          * operations, because the Vars in their tlists are bogus references
03756          * to the first leaf subquery, which wouldn't give the right answer
03757          * even if we could still get to its PlannerInfo.
03758          *
03759          * Also, the subquery could be an appendrel for which all branches are
03760          * known empty due to constraint exclusion, in which case
03761          * set_append_rel_pathlist will have left the attr_widths set to zero.
03762          *
03763          * In either case, we just leave the width estimate zero until
03764          * set_rel_width fixes it.
03765          */
03766         if (IsA(texpr, Var) &&
03767             subroot->parse->setOperations == NULL)
03768         {
03769             Var        *var = (Var *) texpr;
03770             RelOptInfo *subrel = find_base_rel(subroot, var->varno);
03771 
03772             item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
03773         }
03774         rel->attr_widths[te->resno - rel->min_attr] = item_width;
03775     }
03776 
03777     /* Now estimate number of output rows, etc */
03778     set_baserel_size_estimates(root, rel);
03779 }
03780 
03781 /*
03782  * set_function_size_estimates
03783  *      Set the size estimates for a base relation that is a function call.
03784  *
03785  * The rel's targetlist and restrictinfo list must have been constructed
03786  * already.
03787  *
03788  * We set the same fields as set_baserel_size_estimates.
03789  */
03790 void
03791 set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
03792 {
03793     RangeTblEntry *rte;
03794 
03795     /* Should only be applied to base relations that are functions */
03796     Assert(rel->relid > 0);
03797     rte = planner_rt_fetch(rel->relid, root);
03798     Assert(rte->rtekind == RTE_FUNCTION);
03799 
03800     /* Estimate number of rows the function itself will return */
03801     rel->tuples = expression_returns_set_rows(rte->funcexpr);
03802 
03803     /* Now estimate number of output rows, etc */
03804     set_baserel_size_estimates(root, rel);
03805 }
03806 
03807 /*
03808  * set_values_size_estimates
03809  *      Set the size estimates for a base relation that is a values list.
03810  *
03811  * The rel's targetlist and restrictinfo list must have been constructed
03812  * already.
03813  *
03814  * We set the same fields as set_baserel_size_estimates.
03815  */
03816 void
03817 set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
03818 {
03819     RangeTblEntry *rte;
03820 
03821     /* Should only be applied to base relations that are values lists */
03822     Assert(rel->relid > 0);
03823     rte = planner_rt_fetch(rel->relid, root);
03824     Assert(rte->rtekind == RTE_VALUES);
03825 
03826     /*
03827      * Estimate number of rows the values list will return. We know this
03828      * precisely based on the list length (well, barring set-returning
03829      * functions in list items, but that's a refinement not catered for
03830      * anywhere else either).
03831      */
03832     rel->tuples = list_length(rte->values_lists);
03833 
03834     /* Now estimate number of output rows, etc */
03835     set_baserel_size_estimates(root, rel);
03836 }
03837 
03838 /*
03839  * set_cte_size_estimates
03840  *      Set the size estimates for a base relation that is a CTE reference.
03841  *
03842  * The rel's targetlist and restrictinfo list must have been constructed
03843  * already, and we need the completed plan for the CTE (if a regular CTE)
03844  * or the non-recursive term (if a self-reference).
03845  *
03846  * We set the same fields as set_baserel_size_estimates.
03847  */
03848 void
03849 set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, Plan *cteplan)
03850 {
03851     RangeTblEntry *rte;
03852 
03853     /* Should only be applied to base relations that are CTE references */
03854     Assert(rel->relid > 0);
03855     rte = planner_rt_fetch(rel->relid, root);
03856     Assert(rte->rtekind == RTE_CTE);
03857 
03858     if (rte->self_reference)
03859     {
03860         /*
03861          * In a self-reference, arbitrarily assume the average worktable size
03862          * is about 10 times the nonrecursive term's size.
03863          */
03864         rel->tuples = 10 * cteplan->plan_rows;
03865     }
03866     else
03867     {
03868         /* Otherwise just believe the CTE plan's output estimate */
03869         rel->tuples = cteplan->plan_rows;
03870     }
03871 
03872     /* Now estimate number of output rows, etc */
03873     set_baserel_size_estimates(root, rel);
03874 }
03875 
03876 /*
03877  * set_foreign_size_estimates
03878  *      Set the size estimates for a base relation that is a foreign table.
03879  *
03880  * There is not a whole lot that we can do here; the foreign-data wrapper
03881  * is responsible for producing useful estimates.  We can do a decent job
03882  * of estimating baserestrictcost, so we set that, and we also set up width
03883  * using what will be purely datatype-driven estimates from the targetlist.
03884  * There is no way to do anything sane with the rows value, so we just put
03885  * a default estimate and hope that the wrapper can improve on it.  The
03886  * wrapper's GetForeignRelSize function will be called momentarily.
03887  *
03888  * The rel's targetlist and restrictinfo list must have been constructed
03889  * already.
03890  */
03891 void
03892 set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
03893 {
03894     /* Should only be applied to base relations */
03895     Assert(rel->relid > 0);
03896 
03897     rel->rows = 1000;           /* entirely bogus default estimate */
03898 
03899     cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
03900 
03901     set_rel_width(root, rel);
03902 }
03903 
03904 
03905 /*
03906  * set_rel_width
03907  *      Set the estimated output width of a base relation.
03908  *
03909  * The estimated output width is the sum of the per-attribute width estimates
03910  * for the actually-referenced columns, plus any PHVs or other expressions
03911  * that have to be calculated at this relation.  This is the amount of data
03912  * we'd need to pass upwards in case of a sort, hash, etc.
03913  *
03914  * NB: this works best on plain relations because it prefers to look at
03915  * real Vars.  For subqueries, set_subquery_size_estimates will already have
03916  * copied up whatever per-column estimates were made within the subquery,
03917  * and for other types of rels there isn't much we can do anyway.  We fall
03918  * back on (fairly stupid) datatype-based width estimates if we can't get
03919  * any better number.
03920  *
03921  * The per-attribute width estimates are cached for possible re-use while
03922  * building join relations.
03923  */
03924 static void
03925 set_rel_width(PlannerInfo *root, RelOptInfo *rel)
03926 {
03927     Oid         reloid = planner_rt_fetch(rel->relid, root)->relid;
03928     int32       tuple_width = 0;
03929     bool        have_wholerow_var = false;
03930     ListCell   *lc;
03931 
03932     foreach(lc, rel->reltargetlist)
03933     {
03934         Node       *node = (Node *) lfirst(lc);
03935 
03936         /*
03937          * Ordinarily, a Var in a rel's reltargetlist must belong to that rel;
03938          * but there are corner cases involving LATERAL references in
03939          * appendrel members where that isn't so (see set_append_rel_size()).
03940          * If the Var has the wrong varno, fall through to the generic case
03941          * (it doesn't seem worth the trouble to be any smarter).
03942          */
03943         if (IsA(node, Var) &&
03944             ((Var *) node)->varno == rel->relid)
03945         {
03946             Var        *var = (Var *) node;
03947             int         ndx;
03948             int32       item_width;
03949 
03950             Assert(var->varattno >= rel->min_attr);
03951             Assert(var->varattno <= rel->max_attr);
03952 
03953             ndx = var->varattno - rel->min_attr;
03954 
03955             /*
03956              * If it's a whole-row Var, we'll deal with it below after we have
03957              * already cached as many attr widths as possible.
03958              */
03959             if (var->varattno == 0)
03960             {
03961                 have_wholerow_var = true;
03962                 continue;
03963             }
03964 
03965             /*
03966              * The width may have been cached already (especially if it's a
03967              * subquery), so don't duplicate effort.
03968              */
03969             if (rel->attr_widths[ndx] > 0)
03970             {
03971                 tuple_width += rel->attr_widths[ndx];
03972                 continue;
03973             }
03974 
03975             /* Try to get column width from statistics */
03976             if (reloid != InvalidOid && var->varattno > 0)
03977             {
03978                 item_width = get_attavgwidth(reloid, var->varattno);
03979                 if (item_width > 0)
03980                 {
03981                     rel->attr_widths[ndx] = item_width;
03982                     tuple_width += item_width;
03983                     continue;
03984                 }
03985             }
03986 
03987             /*
03988              * Not a plain relation, or can't find statistics for it. Estimate
03989              * using just the type info.
03990              */
03991             item_width = get_typavgwidth(var->vartype, var->vartypmod);
03992             Assert(item_width > 0);
03993             rel->attr_widths[ndx] = item_width;
03994             tuple_width += item_width;
03995         }
03996         else if (IsA(node, PlaceHolderVar))
03997         {
03998             PlaceHolderVar *phv = (PlaceHolderVar *) node;
03999             PlaceHolderInfo *phinfo = find_placeholder_info(root, phv, false);
04000 
04001             tuple_width += phinfo->ph_width;
04002         }
04003         else
04004         {
04005             /*
04006              * We could be looking at an expression pulled up from a subquery,
04007              * or a ROW() representing a whole-row child Var, etc.  Do what we
04008              * can using the expression type information.
04009              */
04010             int32       item_width;
04011 
04012             item_width = get_typavgwidth(exprType(node), exprTypmod(node));
04013             Assert(item_width > 0);
04014             tuple_width += item_width;
04015         }
04016     }
04017 
04018     /*
04019      * If we have a whole-row reference, estimate its width as the sum of
04020      * per-column widths plus sizeof(HeapTupleHeaderData).
04021      */
04022     if (have_wholerow_var)
04023     {
04024         int32       wholerow_width = sizeof(HeapTupleHeaderData);
04025 
04026         if (reloid != InvalidOid)
04027         {
04028             /* Real relation, so estimate true tuple width */
04029             wholerow_width += get_relation_data_width(reloid,
04030                                            rel->attr_widths - rel->min_attr);
04031         }
04032         else
04033         {
04034             /* Do what we can with info for a phony rel */
04035             AttrNumber  i;
04036 
04037             for (i = 1; i <= rel->max_attr; i++)
04038                 wholerow_width += rel->attr_widths[i - rel->min_attr];
04039         }
04040 
04041         rel->attr_widths[0 - rel->min_attr] = wholerow_width;
04042 
04043         /*
04044          * Include the whole-row Var as part of the output tuple.  Yes, that
04045          * really is what happens at runtime.
04046          */
04047         tuple_width += wholerow_width;
04048     }
04049 
04050     Assert(tuple_width >= 0);
04051     rel->width = tuple_width;
04052 }
04053 
04054 /*
04055  * relation_byte_size
04056  *    Estimate the storage space in bytes for a given number of tuples
04057  *    of a given width (size in bytes).
04058  */
04059 static double
04060 relation_byte_size(double tuples, int width)
04061 {
04062     return tuples * (MAXALIGN(width) + MAXALIGN(sizeof(HeapTupleHeaderData)));
04063 }
04064 
04065 /*
04066  * page_size
04067  *    Returns an estimate of the number of pages covered by a given
04068  *    number of tuples of a given width (size in bytes).
04069  */
04070 static double
04071 page_size(double tuples, int width)
04072 {
04073     return ceil(relation_byte_size(tuples, width) / BLCKSZ);
04074 }