LCOV - code coverage report
Current view: top level - src/backend/optimizer/path - costsize.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1822 1862 97.9 %
Date: 2026-01-30 01:18:27 Functions: 74 74 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * costsize.c
       4             :  *    Routines to compute (and set) relation sizes and path costs
       5             :  *
       6             :  * Path costs are measured in arbitrary units established by these basic
       7             :  * parameters:
       8             :  *
       9             :  *  seq_page_cost       Cost of a sequential page fetch
      10             :  *  random_page_cost    Cost of a non-sequential page fetch
      11             :  *  cpu_tuple_cost      Cost of typical CPU time to process a tuple
      12             :  *  cpu_index_tuple_cost  Cost of typical CPU time to process an index tuple
      13             :  *  cpu_operator_cost   Cost of CPU time to execute an operator or function
      14             :  *  parallel_tuple_cost Cost of CPU time to pass a tuple from worker to leader backend
      15             :  *  parallel_setup_cost Cost of setting up shared memory for parallelism
      16             :  *
      17             :  * We expect that the kernel will typically do some amount of read-ahead
      18             :  * optimization; this in conjunction with seek costs means that seq_page_cost
      19             :  * is normally considerably less than random_page_cost.  (However, if the
      20             :  * database is fully cached in RAM, it is reasonable to set them equal.)
      21             :  *
      22             :  * We also use a rough estimate "effective_cache_size" of the number of
      23             :  * disk pages in Postgres + OS-level disk cache.  (We can't simply use
      24             :  * NBuffers for this purpose because that would ignore the effects of
      25             :  * the kernel's disk cache.)
      26             :  *
      27             :  * Obviously, taking constants for these values is an oversimplification,
      28             :  * but it's tough enough to get any useful estimates even at this level of
      29             :  * detail.  Note that all of these parameters are user-settable, in case
      30             :  * the default values are drastically off for a particular platform.
      31             :  *
      32             :  * seq_page_cost and random_page_cost can also be overridden for an individual
      33             :  * tablespace, in case some data is on a fast disk and other data is on a slow
      34             :  * disk.  Per-tablespace overrides never apply to temporary work files such as
      35             :  * an external sort or a materialize node that overflows work_mem.
      36             :  *
      37             :  * We compute two separate costs for each path:
      38             :  *      total_cost: total estimated cost to fetch all tuples
      39             :  *      startup_cost: cost that is expended before first tuple is fetched
      40             :  * In some scenarios, such as when there is a LIMIT or we are implementing
      41             :  * an EXISTS(...) sub-select, it is not necessary to fetch all tuples of the
      42             :  * path's result.  A caller can estimate the cost of fetching a partial
      43             :  * result by interpolating between startup_cost and total_cost.  In detail:
      44             :  *      actual_cost = startup_cost +
      45             :  *          (total_cost - startup_cost) * tuples_to_fetch / path->rows;
      46             :  * Note that a base relation's rows count (and, by extension, plan_rows for
      47             :  * plan nodes below the LIMIT node) are set without regard to any LIMIT, so
      48             :  * that this equation works properly.  (Note: while path->rows is never zero
      49             :  * for ordinary relations, it is zero for paths for provably-empty relations,
      50             :  * so beware of division-by-zero.)  The LIMIT is applied as a top-level
      51             :  * plan node.
      52             :  *
      53             :  * Each path stores the total number of disabled nodes that exist at or
      54             :  * below that point in the plan tree. This is regarded as a component of
      55             :  * the cost, and paths with fewer disabled nodes should be regarded as
      56             :  * cheaper than those with more. Disabled nodes occur when the user sets
      57             :  * a GUC like enable_seqscan=false. We can't necessarily respect such a
      58             :  * setting in every part of the plan tree, but we want to respect in as many
      59             :  * parts of the plan tree as possible. Simpler schemes like storing a Boolean
      60             :  * here rather than a count fail to do that. We used to disable nodes by
      61             :  * adding a large constant to the startup cost, but that distorted planning
      62             :  * in other ways.
      63             :  *
      64             :  * For largely historical reasons, most of the routines in this module use
      65             :  * the passed result Path only to store their results (rows, startup_cost and
      66             :  * total_cost) into.  All the input data they need is passed as separate
      67             :  * parameters, even though much of it could be extracted from the Path.
      68             :  * An exception is made for the cost_XXXjoin() routines, which expect all
      69             :  * the other fields of the passed XXXPath to be filled in, and similarly
      70             :  * cost_index() assumes the passed IndexPath is valid except for its output
      71             :  * values.
      72             :  *
      73             :  *
      74             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      75             :  * Portions Copyright (c) 1994, Regents of the University of California
      76             :  *
      77             :  * IDENTIFICATION
      78             :  *    src/backend/optimizer/path/costsize.c
      79             :  *
      80             :  *-------------------------------------------------------------------------
      81             :  */
      82             : 
      83             : #include "postgres.h"
      84             : 
      85             : #include <limits.h>
      86             : #include <math.h>
      87             : 
      88             : #include "access/amapi.h"
      89             : #include "access/htup_details.h"
      90             : #include "access/tsmapi.h"
      91             : #include "executor/executor.h"
      92             : #include "executor/nodeAgg.h"
      93             : #include "executor/nodeHash.h"
      94             : #include "executor/nodeMemoize.h"
      95             : #include "miscadmin.h"
      96             : #include "nodes/makefuncs.h"
      97             : #include "nodes/nodeFuncs.h"
      98             : #include "optimizer/clauses.h"
      99             : #include "optimizer/cost.h"
     100             : #include "optimizer/optimizer.h"
     101             : #include "optimizer/pathnode.h"
     102             : #include "optimizer/paths.h"
     103             : #include "optimizer/placeholder.h"
     104             : #include "optimizer/plancat.h"
     105             : #include "optimizer/restrictinfo.h"
     106             : #include "parser/parsetree.h"
     107             : #include "utils/lsyscache.h"
     108             : #include "utils/selfuncs.h"
     109             : #include "utils/spccache.h"
     110             : #include "utils/tuplesort.h"
     111             : 
     112             : 
     113             : #define LOG2(x)  (log(x) / 0.693147180559945)
     114             : 
     115             : /*
     116             :  * Append and MergeAppend nodes are less expensive than some other operations
     117             :  * which use cpu_tuple_cost; instead of adding a separate GUC, estimate the
     118             :  * per-tuple cost as cpu_tuple_cost multiplied by this value.
     119             :  */
     120             : #define APPEND_CPU_COST_MULTIPLIER 0.5
     121             : 
     122             : /*
     123             :  * Maximum value for row estimates.  We cap row estimates to this to help
     124             :  * ensure that costs based on these estimates remain within the range of what
     125             :  * double can represent.  add_path() wouldn't act sanely given infinite or NaN
     126             :  * cost values.
     127             :  */
     128             : #define MAXIMUM_ROWCOUNT 1e100
     129             : 
     130             : double      seq_page_cost = DEFAULT_SEQ_PAGE_COST;
     131             : double      random_page_cost = DEFAULT_RANDOM_PAGE_COST;
     132             : double      cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST;
     133             : double      cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST;
     134             : double      cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST;
     135             : double      parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST;
     136             : double      parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST;
     137             : double      recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR;
     138             : 
     139             : int         effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE;
     140             : 
     141             : Cost        disable_cost = 1.0e10;
     142             : 
     143             : int         max_parallel_workers_per_gather = 2;
     144             : 
     145             : bool        enable_seqscan = true;
     146             : bool        enable_indexscan = true;
     147             : bool        enable_indexonlyscan = true;
     148             : bool        enable_bitmapscan = true;
     149             : bool        enable_tidscan = true;
     150             : bool        enable_sort = true;
     151             : bool        enable_incremental_sort = true;
     152             : bool        enable_hashagg = true;
     153             : bool        enable_nestloop = true;
     154             : bool        enable_material = true;
     155             : bool        enable_memoize = true;
     156             : bool        enable_mergejoin = true;
     157             : bool        enable_hashjoin = true;
     158             : bool        enable_gathermerge = true;
     159             : bool        enable_partitionwise_join = false;
     160             : bool        enable_partitionwise_aggregate = false;
     161             : bool        enable_parallel_append = true;
     162             : bool        enable_parallel_hash = true;
     163             : bool        enable_partition_pruning = true;
     164             : bool        enable_presorted_aggregate = true;
     165             : bool        enable_async_append = true;
     166             : 
     167             : typedef struct
     168             : {
     169             :     PlannerInfo *root;
     170             :     QualCost    total;
     171             : } cost_qual_eval_context;
     172             : 
     173             : static List *extract_nonindex_conditions(List *qual_clauses, List *indexclauses);
     174             : static MergeScanSelCache *cached_scansel(PlannerInfo *root,
     175             :                                          RestrictInfo *rinfo,
     176             :                                          PathKey *pathkey);
     177             : static void cost_rescan(PlannerInfo *root, Path *path,
     178             :                         Cost *rescan_startup_cost, Cost *rescan_total_cost);
     179             : static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context);
     180             : static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
     181             :                                       ParamPathInfo *param_info,
     182             :                                       QualCost *qpqual_cost);
     183             : static bool has_indexed_join_quals(NestPath *path);
     184             : static double approx_tuple_count(PlannerInfo *root, JoinPath *path,
     185             :                                  List *quals);
     186             : static double calc_joinrel_size_estimate(PlannerInfo *root,
     187             :                                          RelOptInfo *joinrel,
     188             :                                          RelOptInfo *outer_rel,
     189             :                                          RelOptInfo *inner_rel,
     190             :                                          double outer_rows,
     191             :                                          double inner_rows,
     192             :                                          SpecialJoinInfo *sjinfo,
     193             :                                          List *restrictlist);
     194             : static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root,
     195             :                                                     Relids outer_relids,
     196             :                                                     Relids inner_relids,
     197             :                                                     SpecialJoinInfo *sjinfo,
     198             :                                                     List **restrictlist);
     199             : static Cost append_nonpartial_cost(List *subpaths, int numpaths,
     200             :                                    int parallel_workers);
     201             : static void set_rel_width(PlannerInfo *root, RelOptInfo *rel);
     202             : static int32 get_expr_width(PlannerInfo *root, const Node *expr);
     203             : static double relation_byte_size(double tuples, int width);
     204             : static double page_size(double tuples, int width);
     205             : static double get_parallel_divisor(Path *path);
     206             : 
     207             : 
     208             : /*
     209             :  * clamp_row_est
     210             :  *      Force a row-count estimate to a sane value.
     211             :  */
     212             : double
     213    10779170 : clamp_row_est(double nrows)
     214             : {
     215             :     /*
     216             :      * Avoid infinite and NaN row estimates.  Costs derived from such values
     217             :      * are going to be useless.  Also force the estimate to be at least one
     218             :      * row, to make explain output look better and to avoid possible
     219             :      * divide-by-zero when interpolating costs.  Make it an integer, too.
     220             :      */
     221    10779170 :     if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
     222           0 :         nrows = MAXIMUM_ROWCOUNT;
     223    10779170 :     else if (nrows <= 1.0)
     224     3395402 :         nrows = 1.0;
     225             :     else
     226     7383768 :         nrows = rint(nrows);
     227             : 
     228    10779170 :     return nrows;
     229             : }
     230             : 
     231             : /*
     232             :  * clamp_width_est
     233             :  *      Force a tuple-width estimate to a sane value.
     234             :  *
     235             :  * The planner represents datatype width and tuple width estimates as int32.
     236             :  * When summing column width estimates to create a tuple width estimate,
     237             :  * it's possible to reach integer overflow in edge cases.  To ensure sane
     238             :  * behavior, we form such sums in int64 arithmetic and then apply this routine
     239             :  * to clamp to int32 range.
     240             :  */
     241             : int32
     242     2022724 : clamp_width_est(int64 tuple_width)
     243             : {
     244             :     /*
     245             :      * Anything more than MaxAllocSize is clearly bogus, since we could not
     246             :      * create a tuple that large.
     247             :      */
     248     2022724 :     if (tuple_width > MaxAllocSize)
     249           0 :         return (int32) MaxAllocSize;
     250             : 
     251             :     /*
     252             :      * Unlike clamp_row_est, we just Assert that the value isn't negative,
     253             :      * rather than masking such errors.
     254             :      */
     255             :     Assert(tuple_width >= 0);
     256             : 
     257     2022724 :     return (int32) tuple_width;
     258             : }
     259             : 
     260             : 
     261             : /*
     262             :  * cost_seqscan
     263             :  *    Determines and returns the cost of scanning a relation sequentially.
     264             :  *
     265             :  * 'baserel' is the relation to be scanned
     266             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
     267             :  */
     268             : void
     269      448482 : cost_seqscan(Path *path, PlannerInfo *root,
     270             :              RelOptInfo *baserel, ParamPathInfo *param_info)
     271             : {
     272      448482 :     Cost        startup_cost = 0;
     273             :     Cost        cpu_run_cost;
     274             :     Cost        disk_run_cost;
     275             :     double      spc_seq_page_cost;
     276             :     QualCost    qpqual_cost;
     277             :     Cost        cpu_per_tuple;
     278      448482 :     uint64      enable_mask = PGS_SEQSCAN;
     279             : 
     280             :     /* Should only be applied to base relations */
     281             :     Assert(baserel->relid > 0);
     282             :     Assert(baserel->rtekind == RTE_RELATION);
     283             : 
     284             :     /* Mark the path with the correct row estimate */
     285      448482 :     if (param_info)
     286         840 :         path->rows = param_info->ppi_rows;
     287             :     else
     288      447642 :         path->rows = baserel->rows;
     289             : 
     290             :     /* fetch estimated page cost for tablespace containing table */
     291      448482 :     get_tablespace_page_costs(baserel->reltablespace,
     292             :                               NULL,
     293             :                               &spc_seq_page_cost);
     294             : 
     295             :     /*
     296             :      * disk costs
     297             :      */
     298      448482 :     disk_run_cost = spc_seq_page_cost * baserel->pages;
     299             : 
     300             :     /* CPU costs */
     301      448482 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
     302             : 
     303      448482 :     startup_cost += qpqual_cost.startup;
     304      448482 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
     305      448482 :     cpu_run_cost = cpu_per_tuple * baserel->tuples;
     306             :     /* tlist eval costs are paid per output row, not per tuple scanned */
     307      448482 :     startup_cost += path->pathtarget->cost.startup;
     308      448482 :     cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
     309             : 
     310             :     /* Adjust costing for parallelism, if used. */
     311      448482 :     if (path->parallel_workers > 0)
     312             :     {
     313       29092 :         double      parallel_divisor = get_parallel_divisor(path);
     314             : 
     315             :         /* The CPU cost is divided among all the workers. */
     316       29092 :         cpu_run_cost /= parallel_divisor;
     317             : 
     318             :         /*
     319             :          * It may be possible to amortize some of the I/O cost, but probably
     320             :          * not very much, because most operating systems already do aggressive
     321             :          * prefetching.  For now, we assume that the disk run cost can't be
     322             :          * amortized at all.
     323             :          */
     324             : 
     325             :         /*
     326             :          * In the case of a parallel plan, the row count needs to represent
     327             :          * the number of tuples processed per worker.
     328             :          */
     329       29092 :         path->rows = clamp_row_est(path->rows / parallel_divisor);
     330             :     }
     331             :     else
     332      419390 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
     333             : 
     334      448482 :     path->disabled_nodes =
     335      448482 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
     336      448482 :     path->startup_cost = startup_cost;
     337      448482 :     path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
     338      448482 : }
     339             : 
     340             : /*
     341             :  * cost_samplescan
     342             :  *    Determines and returns the cost of scanning a relation using sampling.
     343             :  *
     344             :  * 'baserel' is the relation to be scanned
     345             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
     346             :  */
     347             : void
     348         306 : cost_samplescan(Path *path, PlannerInfo *root,
     349             :                 RelOptInfo *baserel, ParamPathInfo *param_info)
     350             : {
     351         306 :     Cost        startup_cost = 0;
     352         306 :     Cost        run_cost = 0;
     353             :     RangeTblEntry *rte;
     354             :     TableSampleClause *tsc;
     355             :     TsmRoutine *tsm;
     356             :     double      spc_seq_page_cost,
     357             :                 spc_random_page_cost,
     358             :                 spc_page_cost;
     359             :     QualCost    qpqual_cost;
     360             :     Cost        cpu_per_tuple;
     361         306 :     uint64      enable_mask = 0;
     362             : 
     363             :     /* Should only be applied to base relations with tablesample clauses */
     364             :     Assert(baserel->relid > 0);
     365         306 :     rte = planner_rt_fetch(baserel->relid, root);
     366             :     Assert(rte->rtekind == RTE_RELATION);
     367         306 :     tsc = rte->tablesample;
     368             :     Assert(tsc != NULL);
     369         306 :     tsm = GetTsmRoutine(tsc->tsmhandler);
     370             : 
     371             :     /* Mark the path with the correct row estimate */
     372         306 :     if (param_info)
     373          72 :         path->rows = param_info->ppi_rows;
     374             :     else
     375         234 :         path->rows = baserel->rows;
     376             : 
     377             :     /* fetch estimated page cost for tablespace containing table */
     378         306 :     get_tablespace_page_costs(baserel->reltablespace,
     379             :                               &spc_random_page_cost,
     380             :                               &spc_seq_page_cost);
     381             : 
     382             :     /* if NextSampleBlock is used, assume random access, else sequential */
     383         612 :     spc_page_cost = (tsm->NextSampleBlock != NULL) ?
     384         306 :         spc_random_page_cost : spc_seq_page_cost;
     385             : 
     386             :     /*
     387             :      * disk costs (recall that baserel->pages has already been set to the
     388             :      * number of pages the sampling method will visit)
     389             :      */
     390         306 :     run_cost += spc_page_cost * baserel->pages;
     391             : 
     392             :     /*
     393             :      * CPU costs (recall that baserel->tuples has already been set to the
     394             :      * number of tuples the sampling method will select).  Note that we ignore
     395             :      * execution cost of the TABLESAMPLE parameter expressions; they will be
     396             :      * evaluated only once per scan, and in most usages they'll likely be
     397             :      * simple constants anyway.  We also don't charge anything for the
     398             :      * calculations the sampling method might do internally.
     399             :      */
     400         306 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
     401             : 
     402         306 :     startup_cost += qpqual_cost.startup;
     403         306 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
     404         306 :     run_cost += cpu_per_tuple * baserel->tuples;
     405             :     /* tlist eval costs are paid per output row, not per tuple scanned */
     406         306 :     startup_cost += path->pathtarget->cost.startup;
     407         306 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
     408             : 
     409         306 :     if (path->parallel_workers == 0)
     410         306 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
     411             : 
     412         306 :     path->disabled_nodes =
     413         306 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
     414         306 :     path->startup_cost = startup_cost;
     415         306 :     path->total_cost = startup_cost + run_cost;
     416         306 : }
     417             : 
     418             : /*
     419             :  * cost_gather
     420             :  *    Determines and returns the cost of gather path.
     421             :  *
     422             :  * 'rel' is the relation to be operated upon
     423             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
     424             :  * 'rows' may be used to point to a row estimate; if non-NULL, it overrides
     425             :  * both 'rel' and 'param_info'.  This is useful when the path doesn't exactly
     426             :  * correspond to any particular RelOptInfo.
     427             :  */
     428             : void
     429       26802 : cost_gather(GatherPath *path, PlannerInfo *root,
     430             :             RelOptInfo *rel, ParamPathInfo *param_info,
     431             :             double *rows)
     432             : {
     433       26802 :     Cost        startup_cost = 0;
     434       26802 :     Cost        run_cost = 0;
     435             : 
     436             :     /* Mark the path with the correct row estimate */
     437       26802 :     if (rows)
     438        6946 :         path->path.rows = *rows;
     439       19856 :     else if (param_info)
     440           0 :         path->path.rows = param_info->ppi_rows;
     441             :     else
     442       19856 :         path->path.rows = rel->rows;
     443             : 
     444       26802 :     startup_cost = path->subpath->startup_cost;
     445             : 
     446       26802 :     run_cost = path->subpath->total_cost - path->subpath->startup_cost;
     447             : 
     448             :     /* Parallel setup and communication cost. */
     449       26802 :     startup_cost += parallel_setup_cost;
     450       26802 :     run_cost += parallel_tuple_cost * path->path.rows;
     451             : 
     452       26802 :     path->path.disabled_nodes = path->subpath->disabled_nodes
     453       26802 :         + ((rel->pgs_mask & PGS_GATHER) != 0 ? 0 : 1);
     454       26802 :     path->path.startup_cost = startup_cost;
     455       26802 :     path->path.total_cost = (startup_cost + run_cost);
     456       26802 : }
     457             : 
     458             : /*
     459             :  * cost_gather_merge
     460             :  *    Determines and returns the cost of gather merge path.
     461             :  *
     462             :  * GatherMerge merges several pre-sorted input streams, using a heap that at
     463             :  * any given instant holds the next tuple from each stream. If there are N
     464             :  * streams, we need about N*log2(N) tuple comparisons to construct the heap at
     465             :  * startup, and then for each output tuple, about log2(N) comparisons to
     466             :  * replace the top heap entry with the next tuple from the same stream.
     467             :  */
     468             : void
     469       18944 : cost_gather_merge(GatherMergePath *path, PlannerInfo *root,
     470             :                   RelOptInfo *rel, ParamPathInfo *param_info,
     471             :                   int input_disabled_nodes,
     472             :                   Cost input_startup_cost, Cost input_total_cost,
     473             :                   double *rows)
     474             : {
     475       18944 :     Cost        startup_cost = 0;
     476       18944 :     Cost        run_cost = 0;
     477             :     Cost        comparison_cost;
     478             :     double      N;
     479             :     double      logN;
     480             : 
     481             :     /* Mark the path with the correct row estimate */
     482       18944 :     if (rows)
     483       11298 :         path->path.rows = *rows;
     484        7646 :     else if (param_info)
     485           0 :         path->path.rows = param_info->ppi_rows;
     486             :     else
     487        7646 :         path->path.rows = rel->rows;
     488             : 
     489             :     /*
     490             :      * Add one to the number of workers to account for the leader.  This might
     491             :      * be overgenerous since the leader will do less work than other workers
     492             :      * in typical cases, but we'll go with it for now.
     493             :      */
     494             :     Assert(path->num_workers > 0);
     495       18944 :     N = (double) path->num_workers + 1;
     496       18944 :     logN = LOG2(N);
     497             : 
     498             :     /* Assumed cost per tuple comparison */
     499       18944 :     comparison_cost = 2.0 * cpu_operator_cost;
     500             : 
     501             :     /* Heap creation cost */
     502       18944 :     startup_cost += comparison_cost * N * logN;
     503             : 
     504             :     /* Per-tuple heap maintenance cost */
     505       18944 :     run_cost += path->path.rows * comparison_cost * logN;
     506             : 
     507             :     /* small cost for heap management, like cost_merge_append */
     508       18944 :     run_cost += cpu_operator_cost * path->path.rows;
     509             : 
     510             :     /*
     511             :      * Parallel setup and communication cost.  Since Gather Merge, unlike
     512             :      * Gather, requires us to block until a tuple is available from every
     513             :      * worker, we bump the IPC cost up a little bit as compared with Gather.
     514             :      * For lack of a better idea, charge an extra 5%.
     515             :      */
     516       18944 :     startup_cost += parallel_setup_cost;
     517       18944 :     run_cost += parallel_tuple_cost * path->path.rows * 1.05;
     518             : 
     519       18944 :     path->path.disabled_nodes = path->subpath->disabled_nodes
     520       18944 :         + ((rel->pgs_mask & PGS_GATHER_MERGE) != 0 ? 0 : 1);
     521       18944 :     path->path.startup_cost = startup_cost + input_startup_cost;
     522       18944 :     path->path.total_cost = (startup_cost + run_cost + input_total_cost);
     523       18944 : }
     524             : 
     525             : /*
     526             :  * cost_index
     527             :  *    Determines and returns the cost of scanning a relation using an index.
     528             :  *
     529             :  * 'path' describes the indexscan under consideration, and is complete
     530             :  *      except for the fields to be set by this routine
     531             :  * 'loop_count' is the number of repetitions of the indexscan to factor into
     532             :  *      estimates of caching behavior
     533             :  *
     534             :  * In addition to rows, startup_cost and total_cost, cost_index() sets the
     535             :  * path's indextotalcost and indexselectivity fields.  These values will be
     536             :  * needed if the IndexPath is used in a BitmapIndexScan.
     537             :  *
     538             :  * NOTE: path->indexquals must contain only clauses usable as index
     539             :  * restrictions.  Any additional quals evaluated as qpquals may reduce the
     540             :  * number of returned tuples, but they won't reduce the number of tuples
     541             :  * we have to fetch from the table, so they don't reduce the scan cost.
     542             :  */
     543             : void
     544      830212 : cost_index(IndexPath *path, PlannerInfo *root, double loop_count,
     545             :            bool partial_path)
     546             : {
     547      830212 :     IndexOptInfo *index = path->indexinfo;
     548      830212 :     RelOptInfo *baserel = index->rel;
     549      830212 :     bool        indexonly = (path->path.pathtype == T_IndexOnlyScan);
     550             :     amcostestimate_function amcostestimate;
     551             :     List       *qpquals;
     552      830212 :     Cost        startup_cost = 0;
     553      830212 :     Cost        run_cost = 0;
     554      830212 :     Cost        cpu_run_cost = 0;
     555             :     Cost        indexStartupCost;
     556             :     Cost        indexTotalCost;
     557             :     Selectivity indexSelectivity;
     558             :     double      indexCorrelation,
     559             :                 csquared;
     560             :     double      spc_seq_page_cost,
     561             :                 spc_random_page_cost;
     562             :     Cost        min_IO_cost,
     563             :                 max_IO_cost;
     564             :     QualCost    qpqual_cost;
     565             :     Cost        cpu_per_tuple;
     566             :     double      tuples_fetched;
     567             :     double      pages_fetched;
     568             :     double      rand_heap_pages;
     569             :     double      index_pages;
     570             :     uint64      enable_mask;
     571             : 
     572             :     /* Should only be applied to base relations */
     573             :     Assert(IsA(baserel, RelOptInfo) &&
     574             :            IsA(index, IndexOptInfo));
     575             :     Assert(baserel->relid > 0);
     576             :     Assert(baserel->rtekind == RTE_RELATION);
     577             : 
     578             :     /*
     579             :      * Mark the path with the correct row estimate, and identify which quals
     580             :      * will need to be enforced as qpquals.  We need not check any quals that
     581             :      * are implied by the index's predicate, so we can use indrestrictinfo not
     582             :      * baserestrictinfo as the list of relevant restriction clauses for the
     583             :      * rel.
     584             :      */
     585      830212 :     if (path->path.param_info)
     586             :     {
     587      159606 :         path->path.rows = path->path.param_info->ppi_rows;
     588             :         /* qpquals come from the rel's restriction clauses and ppi_clauses */
     589      159606 :         qpquals = list_concat(extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
     590             :                                                           path->indexclauses),
     591      159606 :                               extract_nonindex_conditions(path->path.param_info->ppi_clauses,
     592             :                                                           path->indexclauses));
     593             :     }
     594             :     else
     595             :     {
     596      670606 :         path->path.rows = baserel->rows;
     597             :         /* qpquals come from just the rel's restriction clauses */
     598      670606 :         qpquals = extract_nonindex_conditions(path->indexinfo->indrestrictinfo,
     599             :                                               path->indexclauses);
     600             :     }
     601             : 
     602             :     /* is this scan type disabled? */
     603      830212 :     enable_mask = (indexonly ? PGS_INDEXONLYSCAN : PGS_INDEXSCAN)
     604      830212 :         | (partial_path ? 0 : PGS_CONSIDER_NONPARTIAL);
     605      830212 :     path->path.disabled_nodes =
     606      830212 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
     607             : 
     608             :     /*
     609             :      * Call index-access-method-specific code to estimate the processing cost
     610             :      * for scanning the index, as well as the selectivity of the index (ie,
     611             :      * the fraction of main-table tuples we will have to retrieve) and its
     612             :      * correlation to the main-table tuple order.  We need a cast here because
     613             :      * pathnodes.h uses a weak function type to avoid including amapi.h.
     614             :      */
     615      830212 :     amcostestimate = (amcostestimate_function) index->amcostestimate;
     616      830212 :     amcostestimate(root, path, loop_count,
     617             :                    &indexStartupCost, &indexTotalCost,
     618             :                    &indexSelectivity, &indexCorrelation,
     619             :                    &index_pages);
     620             : 
     621             :     /*
     622             :      * Save amcostestimate's results for possible use in bitmap scan planning.
     623             :      * We don't bother to save indexStartupCost or indexCorrelation, because a
     624             :      * bitmap scan doesn't care about either.
     625             :      */
     626      830212 :     path->indextotalcost = indexTotalCost;
     627      830212 :     path->indexselectivity = indexSelectivity;
     628             : 
     629             :     /* all costs for touching index itself included here */
     630      830212 :     startup_cost += indexStartupCost;
     631      830212 :     run_cost += indexTotalCost - indexStartupCost;
     632             : 
     633             :     /* estimate number of main-table tuples fetched */
     634      830212 :     tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
     635             : 
     636             :     /* fetch estimated page costs for tablespace containing table */
     637      830212 :     get_tablespace_page_costs(baserel->reltablespace,
     638             :                               &spc_random_page_cost,
     639             :                               &spc_seq_page_cost);
     640             : 
     641             :     /*----------
     642             :      * Estimate number of main-table pages fetched, and compute I/O cost.
     643             :      *
     644             :      * When the index ordering is uncorrelated with the table ordering,
     645             :      * we use an approximation proposed by Mackert and Lohman (see
     646             :      * index_pages_fetched() for details) to compute the number of pages
     647             :      * fetched, and then charge spc_random_page_cost per page fetched.
     648             :      *
     649             :      * When the index ordering is exactly correlated with the table ordering
     650             :      * (just after a CLUSTER, for example), the number of pages fetched should
     651             :      * be exactly selectivity * table_size.  What's more, all but the first
     652             :      * will be sequential fetches, not the random fetches that occur in the
     653             :      * uncorrelated case.  So if the number of pages is more than 1, we
     654             :      * ought to charge
     655             :      *      spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
     656             :      * For partially-correlated indexes, we ought to charge somewhere between
     657             :      * these two estimates.  We currently interpolate linearly between the
     658             :      * estimates based on the correlation squared (XXX is that appropriate?).
     659             :      *
     660             :      * If it's an index-only scan, then we will not need to fetch any heap
     661             :      * pages for which the visibility map shows all tuples are visible.
     662             :      * Hence, reduce the estimated number of heap fetches accordingly.
     663             :      * We use the measured fraction of the entire heap that is all-visible,
     664             :      * which might not be particularly relevant to the subset of the heap
     665             :      * that this query will fetch; but it's not clear how to do better.
     666             :      *----------
     667             :      */
     668      830212 :     if (loop_count > 1)
     669             :     {
     670             :         /*
     671             :          * For repeated indexscans, the appropriate estimate for the
     672             :          * uncorrelated case is to scale up the number of tuples fetched in
     673             :          * the Mackert and Lohman formula by the number of scans, so that we
     674             :          * estimate the number of pages fetched by all the scans; then
     675             :          * pro-rate the costs for one scan.  In this case we assume all the
     676             :          * fetches are random accesses.
     677             :          */
     678       91622 :         pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
     679             :                                             baserel->pages,
     680       91622 :                                             (double) index->pages,
     681             :                                             root);
     682             : 
     683       91622 :         if (indexonly)
     684       11390 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
     685             : 
     686       91622 :         rand_heap_pages = pages_fetched;
     687             : 
     688       91622 :         max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
     689             : 
     690             :         /*
     691             :          * In the perfectly correlated case, the number of pages touched by
     692             :          * each scan is selectivity * table_size, and we can use the Mackert
     693             :          * and Lohman formula at the page level to estimate how much work is
     694             :          * saved by caching across scans.  We still assume all the fetches are
     695             :          * random, though, which is an overestimate that's hard to correct for
     696             :          * without double-counting the cache effects.  (But in most cases
     697             :          * where such a plan is actually interesting, only one page would get
     698             :          * fetched per scan anyway, so it shouldn't matter much.)
     699             :          */
     700       91622 :         pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
     701             : 
     702       91622 :         pages_fetched = index_pages_fetched(pages_fetched * loop_count,
     703             :                                             baserel->pages,
     704       91622 :                                             (double) index->pages,
     705             :                                             root);
     706             : 
     707       91622 :         if (indexonly)
     708       11390 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
     709             : 
     710       91622 :         min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
     711             :     }
     712             :     else
     713             :     {
     714             :         /*
     715             :          * Normal case: apply the Mackert and Lohman formula, and then
     716             :          * interpolate between that and the correlation-derived result.
     717             :          */
     718      738590 :         pages_fetched = index_pages_fetched(tuples_fetched,
     719             :                                             baserel->pages,
     720      738590 :                                             (double) index->pages,
     721             :                                             root);
     722             : 
     723      738590 :         if (indexonly)
     724       71766 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
     725             : 
     726      738590 :         rand_heap_pages = pages_fetched;
     727             : 
     728             :         /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
     729      738590 :         max_IO_cost = pages_fetched * spc_random_page_cost;
     730             : 
     731             :         /* min_IO_cost is for the perfectly correlated case (csquared=1) */
     732      738590 :         pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
     733             : 
     734      738590 :         if (indexonly)
     735       71766 :             pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
     736             : 
     737      738590 :         if (pages_fetched > 0)
     738             :         {
     739      660320 :             min_IO_cost = spc_random_page_cost;
     740      660320 :             if (pages_fetched > 1)
     741      204230 :                 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
     742             :         }
     743             :         else
     744       78270 :             min_IO_cost = 0;
     745             :     }
     746             : 
     747      830212 :     if (partial_path)
     748             :     {
     749             :         /*
     750             :          * For index only scans compute workers based on number of index pages
     751             :          * fetched; the number of heap pages we fetch might be so small as to
     752             :          * effectively rule out parallelism, which we don't want to do.
     753             :          */
     754      284714 :         if (indexonly)
     755       26496 :             rand_heap_pages = -1;
     756             : 
     757             :         /*
     758             :          * Estimate the number of parallel workers required to scan index. Use
     759             :          * the number of heap pages computed considering heap fetches won't be
     760             :          * sequential as for parallel scans the pages are accessed in random
     761             :          * order.
     762             :          */
     763      284714 :         path->path.parallel_workers = compute_parallel_worker(baserel,
     764             :                                                               rand_heap_pages,
     765             :                                                               index_pages,
     766             :                                                               max_parallel_workers_per_gather);
     767             : 
     768             :         /*
     769             :          * Fall out if workers can't be assigned for parallel scan, because in
     770             :          * such a case this path will be rejected.  So there is no benefit in
     771             :          * doing extra computation.
     772             :          */
     773      284714 :         if (path->path.parallel_workers <= 0)
     774      274474 :             return;
     775             : 
     776       10240 :         path->path.parallel_aware = true;
     777             :     }
     778             : 
     779             :     /*
     780             :      * Now interpolate based on estimated index order correlation to get total
     781             :      * disk I/O cost for main table accesses.
     782             :      */
     783      555738 :     csquared = indexCorrelation * indexCorrelation;
     784             : 
     785      555738 :     run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
     786             : 
     787             :     /*
     788             :      * Estimate CPU costs per tuple.
     789             :      *
     790             :      * What we want here is cpu_tuple_cost plus the evaluation costs of any
     791             :      * qual clauses that we have to evaluate as qpquals.
     792             :      */
     793      555738 :     cost_qual_eval(&qpqual_cost, qpquals, root);
     794             : 
     795      555738 :     startup_cost += qpqual_cost.startup;
     796      555738 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
     797             : 
     798      555738 :     cpu_run_cost += cpu_per_tuple * tuples_fetched;
     799             : 
     800             :     /* tlist eval costs are paid per output row, not per tuple scanned */
     801      555738 :     startup_cost += path->path.pathtarget->cost.startup;
     802      555738 :     cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
     803             : 
     804             :     /* Adjust costing for parallelism, if used. */
     805      555738 :     if (path->path.parallel_workers > 0)
     806             :     {
     807       10240 :         double      parallel_divisor = get_parallel_divisor(&path->path);
     808             : 
     809       10240 :         path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
     810             : 
     811             :         /* The CPU cost is divided among all the workers. */
     812       10240 :         cpu_run_cost /= parallel_divisor;
     813             :     }
     814             : 
     815      555738 :     run_cost += cpu_run_cost;
     816             : 
     817      555738 :     path->path.startup_cost = startup_cost;
     818      555738 :     path->path.total_cost = startup_cost + run_cost;
     819             : }
     820             : 
     821             : /*
     822             :  * extract_nonindex_conditions
     823             :  *
     824             :  * Given a list of quals to be enforced in an indexscan, extract the ones that
     825             :  * will have to be applied as qpquals (ie, the index machinery won't handle
     826             :  * them).  Here we detect only whether a qual clause is directly redundant
     827             :  * with some indexclause.  If the index path is chosen for use, createplan.c
     828             :  * will try a bit harder to get rid of redundant qual conditions; specifically
     829             :  * it will see if quals can be proven to be implied by the indexquals.  But
     830             :  * it does not seem worth the cycles to try to factor that in at this stage,
     831             :  * since we're only trying to estimate qual eval costs.  Otherwise this must
     832             :  * match the logic in create_indexscan_plan().
     833             :  *
     834             :  * qual_clauses, and the result, are lists of RestrictInfos.
     835             :  * indexclauses is a list of IndexClauses.
     836             :  */
     837             : static List *
     838      989818 : extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
     839             : {
     840      989818 :     List       *result = NIL;
     841             :     ListCell   *lc;
     842             : 
     843     2047840 :     foreach(lc, qual_clauses)
     844             :     {
     845     1058022 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
     846             : 
     847     1058022 :         if (rinfo->pseudoconstant)
     848       10304 :             continue;           /* we may drop pseudoconstants here */
     849     1047718 :         if (is_redundant_with_indexclauses(rinfo, indexclauses))
     850      622788 :             continue;           /* dup or derived from same EquivalenceClass */
     851             :         /* ... skip the predicate proof attempt createplan.c will try ... */
     852      424930 :         result = lappend(result, rinfo);
     853             :     }
     854      989818 :     return result;
     855             : }
     856             : 
     857             : /*
     858             :  * index_pages_fetched
     859             :  *    Estimate the number of pages actually fetched after accounting for
     860             :  *    cache effects.
     861             :  *
     862             :  * We use an approximation proposed by Mackert and Lohman, "Index Scans
     863             :  * Using a Finite LRU Buffer: A Validated I/O Model", ACM Transactions
     864             :  * on Database Systems, Vol. 14, No. 3, September 1989, Pages 401-424.
     865             :  * The Mackert and Lohman approximation is that the number of pages
     866             :  * fetched is
     867             :  *  PF =
     868             :  *      min(2TNs/(2T+Ns), T)            when T <= b
     869             :  *      2TNs/(2T+Ns)                    when T > b and Ns <= 2Tb/(2T-b)
     870             :  *      b + (Ns - 2Tb/(2T-b))*(T-b)/T   when T > b and Ns > 2Tb/(2T-b)
     871             :  * where
     872             :  *      T = # pages in table
     873             :  *      N = # tuples in table
     874             :  *      s = selectivity = fraction of table to be scanned
     875             :  *      b = # buffer pages available (we include kernel space here)
     876             :  *
     877             :  * We assume that effective_cache_size is the total number of buffer pages
     878             :  * available for the whole query, and pro-rate that space across all the
     879             :  * tables in the query and the index currently under consideration.  (This
     880             :  * ignores space needed for other indexes used by the query, but since we
     881             :  * don't know which indexes will get used, we can't estimate that very well;
     882             :  * and in any case counting all the tables may well be an overestimate, since
     883             :  * depending on the join plan not all the tables may be scanned concurrently.)
     884             :  *
     885             :  * The product Ns is the number of tuples fetched; we pass in that
     886             :  * product rather than calculating it here.  "pages" is the number of pages
     887             :  * in the object under consideration (either an index or a table).
     888             :  * "index_pages" is the amount to add to the total table space, which was
     889             :  * computed for us by make_one_rel.
     890             :  *
     891             :  * Caller is expected to have ensured that tuples_fetched is greater than zero
     892             :  * and rounded to integer (see clamp_row_est).  The result will likewise be
     893             :  * greater than zero and integral.
     894             :  */
     895             : double
     896     1169430 : index_pages_fetched(double tuples_fetched, BlockNumber pages,
     897             :                     double index_pages, PlannerInfo *root)
     898             : {
     899             :     double      pages_fetched;
     900             :     double      total_pages;
     901             :     double      T,
     902             :                 b;
     903             : 
     904             :     /* T is # pages in table, but don't allow it to be zero */
     905     1169430 :     T = (pages > 1) ? (double) pages : 1.0;
     906             : 
     907             :     /* Compute number of pages assumed to be competing for cache space */
     908     1169430 :     total_pages = root->total_table_pages + index_pages;
     909     1169430 :     total_pages = Max(total_pages, 1.0);
     910             :     Assert(T <= total_pages);
     911             : 
     912             :     /* b is pro-rated share of effective_cache_size */
     913     1169430 :     b = (double) effective_cache_size * T / total_pages;
     914             : 
     915             :     /* force it positive and integral */
     916     1169430 :     if (b <= 1.0)
     917           0 :         b = 1.0;
     918             :     else
     919     1169430 :         b = ceil(b);
     920             : 
     921             :     /* This part is the Mackert and Lohman formula */
     922     1169430 :     if (T <= b)
     923             :     {
     924     1169430 :         pages_fetched =
     925     1169430 :             (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
     926     1169430 :         if (pages_fetched >= T)
     927      686486 :             pages_fetched = T;
     928             :         else
     929      482944 :             pages_fetched = ceil(pages_fetched);
     930             :     }
     931             :     else
     932             :     {
     933             :         double      lim;
     934             : 
     935           0 :         lim = (2.0 * T * b) / (2.0 * T - b);
     936           0 :         if (tuples_fetched <= lim)
     937             :         {
     938           0 :             pages_fetched =
     939           0 :                 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
     940             :         }
     941             :         else
     942             :         {
     943           0 :             pages_fetched =
     944           0 :                 b + (tuples_fetched - lim) * (T - b) / T;
     945             :         }
     946           0 :         pages_fetched = ceil(pages_fetched);
     947             :     }
     948     1169430 :     return pages_fetched;
     949             : }
     950             : 
     951             : /*
     952             :  * get_indexpath_pages
     953             :  *      Determine the total size of the indexes used in a bitmap index path.
     954             :  *
     955             :  * Note: if the same index is used more than once in a bitmap tree, we will
     956             :  * count it multiple times, which perhaps is the wrong thing ... but it's
     957             :  * not completely clear, and detecting duplicates is difficult, so ignore it
     958             :  * for now.
     959             :  */
     960             : static double
     961      198528 : get_indexpath_pages(Path *bitmapqual)
     962             : {
     963      198528 :     double      result = 0;
     964             :     ListCell   *l;
     965             : 
     966      198528 :     if (IsA(bitmapqual, BitmapAndPath))
     967             :     {
     968       23934 :         BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
     969             : 
     970       71802 :         foreach(l, apath->bitmapquals)
     971             :         {
     972       47868 :             result += get_indexpath_pages((Path *) lfirst(l));
     973             :         }
     974             :     }
     975      174594 :     else if (IsA(bitmapqual, BitmapOrPath))
     976             :     {
     977          74 :         BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
     978             : 
     979         234 :         foreach(l, opath->bitmapquals)
     980             :         {
     981         160 :             result += get_indexpath_pages((Path *) lfirst(l));
     982             :         }
     983             :     }
     984      174520 :     else if (IsA(bitmapqual, IndexPath))
     985             :     {
     986      174520 :         IndexPath  *ipath = (IndexPath *) bitmapqual;
     987             : 
     988      174520 :         result = (double) ipath->indexinfo->pages;
     989             :     }
     990             :     else
     991           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
     992             : 
     993      198528 :     return result;
     994             : }
     995             : 
     996             : /*
     997             :  * cost_bitmap_heap_scan
     998             :  *    Determines and returns the cost of scanning a relation using a bitmap
     999             :  *    index-then-heap plan.
    1000             :  *
    1001             :  * 'baserel' is the relation to be scanned
    1002             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
    1003             :  * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
    1004             :  * 'loop_count' is the number of repetitions of the indexscan to factor into
    1005             :  *      estimates of caching behavior
    1006             :  *
    1007             :  * Note: the component IndexPaths in bitmapqual should have been costed
    1008             :  * using the same loop_count.
    1009             :  */
    1010             : void
    1011      566564 : cost_bitmap_heap_scan(Path *path, PlannerInfo *root, RelOptInfo *baserel,
    1012             :                       ParamPathInfo *param_info,
    1013             :                       Path *bitmapqual, double loop_count)
    1014             : {
    1015      566564 :     Cost        startup_cost = 0;
    1016      566564 :     Cost        run_cost = 0;
    1017             :     Cost        indexTotalCost;
    1018             :     QualCost    qpqual_cost;
    1019             :     Cost        cpu_per_tuple;
    1020             :     Cost        cost_per_page;
    1021             :     Cost        cpu_run_cost;
    1022             :     double      tuples_fetched;
    1023             :     double      pages_fetched;
    1024             :     double      spc_seq_page_cost,
    1025             :                 spc_random_page_cost;
    1026             :     double      T;
    1027      566564 :     uint64      enable_mask = PGS_BITMAPSCAN;
    1028             : 
    1029             :     /* Should only be applied to base relations */
    1030             :     Assert(IsA(baserel, RelOptInfo));
    1031             :     Assert(baserel->relid > 0);
    1032             :     Assert(baserel->rtekind == RTE_RELATION);
    1033             : 
    1034             :     /* Mark the path with the correct row estimate */
    1035      566564 :     if (param_info)
    1036      241208 :         path->rows = param_info->ppi_rows;
    1037             :     else
    1038      325356 :         path->rows = baserel->rows;
    1039             : 
    1040      566564 :     pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
    1041             :                                          loop_count, &indexTotalCost,
    1042             :                                          &tuples_fetched);
    1043             : 
    1044      566564 :     startup_cost += indexTotalCost;
    1045      566564 :     T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
    1046             : 
    1047             :     /* Fetch estimated page costs for tablespace containing table. */
    1048      566564 :     get_tablespace_page_costs(baserel->reltablespace,
    1049             :                               &spc_random_page_cost,
    1050             :                               &spc_seq_page_cost);
    1051             : 
    1052             :     /*
    1053             :      * For small numbers of pages we should charge spc_random_page_cost
    1054             :      * apiece, while if nearly all the table's pages are being read, it's more
    1055             :      * appropriate to charge spc_seq_page_cost apiece.  The effect is
    1056             :      * nonlinear, too. For lack of a better idea, interpolate like this to
    1057             :      * determine the cost per page.
    1058             :      */
    1059      566564 :     if (pages_fetched >= 2.0)
    1060      119994 :         cost_per_page = spc_random_page_cost -
    1061      119994 :             (spc_random_page_cost - spc_seq_page_cost)
    1062      119994 :             * sqrt(pages_fetched / T);
    1063             :     else
    1064      446570 :         cost_per_page = spc_random_page_cost;
    1065             : 
    1066      566564 :     run_cost += pages_fetched * cost_per_page;
    1067             : 
    1068             :     /*
    1069             :      * Estimate CPU costs per tuple.
    1070             :      *
    1071             :      * Often the indexquals don't need to be rechecked at each tuple ... but
    1072             :      * not always, especially not if there are enough tuples involved that the
    1073             :      * bitmaps become lossy.  For the moment, just assume they will be
    1074             :      * rechecked always.  This means we charge the full freight for all the
    1075             :      * scan clauses.
    1076             :      */
    1077      566564 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1078             : 
    1079      566564 :     startup_cost += qpqual_cost.startup;
    1080      566564 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
    1081      566564 :     cpu_run_cost = cpu_per_tuple * tuples_fetched;
    1082             : 
    1083             :     /* Adjust costing for parallelism, if used. */
    1084      566564 :     if (path->parallel_workers > 0)
    1085             :     {
    1086        4958 :         double      parallel_divisor = get_parallel_divisor(path);
    1087             : 
    1088             :         /* The CPU cost is divided among all the workers. */
    1089        4958 :         cpu_run_cost /= parallel_divisor;
    1090             : 
    1091        4958 :         path->rows = clamp_row_est(path->rows / parallel_divisor);
    1092             :     }
    1093             :     else
    1094      561606 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1095             : 
    1096             : 
    1097      566564 :     run_cost += cpu_run_cost;
    1098             : 
    1099             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1100      566564 :     startup_cost += path->pathtarget->cost.startup;
    1101      566564 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
    1102             : 
    1103      566564 :     path->disabled_nodes =
    1104      566564 :         (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
    1105      566564 :     path->startup_cost = startup_cost;
    1106      566564 :     path->total_cost = startup_cost + run_cost;
    1107      566564 : }
    1108             : 
    1109             : /*
    1110             :  * cost_bitmap_tree_node
    1111             :  *      Extract cost and selectivity from a bitmap tree node (index/and/or)
    1112             :  */
    1113             : void
    1114     1042934 : cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
    1115             : {
    1116     1042934 :     if (IsA(path, IndexPath))
    1117             :     {
    1118      987340 :         *cost = ((IndexPath *) path)->indextotalcost;
    1119      987340 :         *selec = ((IndexPath *) path)->indexselectivity;
    1120             : 
    1121             :         /*
    1122             :          * Charge a small amount per retrieved tuple to reflect the costs of
    1123             :          * manipulating the bitmap.  This is mostly to make sure that a bitmap
    1124             :          * scan doesn't look to be the same cost as an indexscan to retrieve a
    1125             :          * single tuple.
    1126             :          */
    1127      987340 :         *cost += 0.1 * cpu_operator_cost * path->rows;
    1128             :     }
    1129       55594 :     else if (IsA(path, BitmapAndPath))
    1130             :     {
    1131       51922 :         *cost = path->total_cost;
    1132       51922 :         *selec = ((BitmapAndPath *) path)->bitmapselectivity;
    1133             :     }
    1134        3672 :     else if (IsA(path, BitmapOrPath))
    1135             :     {
    1136        3672 :         *cost = path->total_cost;
    1137        3672 :         *selec = ((BitmapOrPath *) path)->bitmapselectivity;
    1138             :     }
    1139             :     else
    1140             :     {
    1141           0 :         elog(ERROR, "unrecognized node type: %d", nodeTag(path));
    1142             :         *cost = *selec = 0;     /* keep compiler quiet */
    1143             :     }
    1144     1042934 : }
    1145             : 
    1146             : /*
    1147             :  * cost_bitmap_and_node
    1148             :  *      Estimate the cost of a BitmapAnd node
    1149             :  *
    1150             :  * Note that this considers only the costs of index scanning and bitmap
    1151             :  * creation, not the eventual heap access.  In that sense the object isn't
    1152             :  * truly a Path, but it has enough path-like properties (costs in particular)
    1153             :  * to warrant treating it as one.  We don't bother to set the path rows field,
    1154             :  * however.
    1155             :  */
    1156             : void
    1157       51704 : cost_bitmap_and_node(BitmapAndPath *path, PlannerInfo *root)
    1158             : {
    1159             :     Cost        totalCost;
    1160             :     Selectivity selec;
    1161             :     ListCell   *l;
    1162             : 
    1163             :     /*
    1164             :      * We estimate AND selectivity on the assumption that the inputs are
    1165             :      * independent.  This is probably often wrong, but we don't have the info
    1166             :      * to do better.
    1167             :      *
    1168             :      * The runtime cost of the BitmapAnd itself is estimated at 100x
    1169             :      * cpu_operator_cost for each tbm_intersect needed.  Probably too small,
    1170             :      * definitely too simplistic?
    1171             :      */
    1172       51704 :     totalCost = 0.0;
    1173       51704 :     selec = 1.0;
    1174      155112 :     foreach(l, path->bitmapquals)
    1175             :     {
    1176      103408 :         Path       *subpath = (Path *) lfirst(l);
    1177             :         Cost        subCost;
    1178             :         Selectivity subselec;
    1179             : 
    1180      103408 :         cost_bitmap_tree_node(subpath, &subCost, &subselec);
    1181             : 
    1182      103408 :         selec *= subselec;
    1183             : 
    1184      103408 :         totalCost += subCost;
    1185      103408 :         if (l != list_head(path->bitmapquals))
    1186       51704 :             totalCost += 100.0 * cpu_operator_cost;
    1187             :     }
    1188       51704 :     path->bitmapselectivity = selec;
    1189       51704 :     path->path.rows = 0;     /* per above, not used */
    1190       51704 :     path->path.disabled_nodes = 0;
    1191       51704 :     path->path.startup_cost = totalCost;
    1192       51704 :     path->path.total_cost = totalCost;
    1193       51704 : }
    1194             : 
    1195             : /*
    1196             :  * cost_bitmap_or_node
    1197             :  *      Estimate the cost of a BitmapOr node
    1198             :  *
    1199             :  * See comments for cost_bitmap_and_node.
    1200             :  */
    1201             : void
    1202        1040 : cost_bitmap_or_node(BitmapOrPath *path, PlannerInfo *root)
    1203             : {
    1204             :     Cost        totalCost;
    1205             :     Selectivity selec;
    1206             :     ListCell   *l;
    1207             : 
    1208             :     /*
    1209             :      * We estimate OR selectivity on the assumption that the inputs are
    1210             :      * non-overlapping, since that's often the case in "x IN (list)" type
    1211             :      * situations.  Of course, we clamp to 1.0 at the end.
    1212             :      *
    1213             :      * The runtime cost of the BitmapOr itself is estimated at 100x
    1214             :      * cpu_operator_cost for each tbm_union needed.  Probably too small,
    1215             :      * definitely too simplistic?  We are aware that the tbm_unions are
    1216             :      * optimized out when the inputs are BitmapIndexScans.
    1217             :      */
    1218        1040 :     totalCost = 0.0;
    1219        1040 :     selec = 0.0;
    1220        2922 :     foreach(l, path->bitmapquals)
    1221             :     {
    1222        1882 :         Path       *subpath = (Path *) lfirst(l);
    1223             :         Cost        subCost;
    1224             :         Selectivity subselec;
    1225             : 
    1226        1882 :         cost_bitmap_tree_node(subpath, &subCost, &subselec);
    1227             : 
    1228        1882 :         selec += subselec;
    1229             : 
    1230        1882 :         totalCost += subCost;
    1231        1882 :         if (l != list_head(path->bitmapquals) &&
    1232         842 :             !IsA(subpath, IndexPath))
    1233           0 :             totalCost += 100.0 * cpu_operator_cost;
    1234             :     }
    1235        1040 :     path->bitmapselectivity = Min(selec, 1.0);
    1236        1040 :     path->path.rows = 0;     /* per above, not used */
    1237        1040 :     path->path.startup_cost = totalCost;
    1238        1040 :     path->path.total_cost = totalCost;
    1239        1040 : }
    1240             : 
    1241             : /*
    1242             :  * cost_tidscan
    1243             :  *    Determines and returns the cost of scanning a relation using TIDs.
    1244             :  *
    1245             :  * 'baserel' is the relation to be scanned
    1246             :  * 'tidquals' is the list of TID-checkable quals
    1247             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
    1248             :  */
    1249             : void
    1250         872 : cost_tidscan(Path *path, PlannerInfo *root,
    1251             :              RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
    1252             : {
    1253         872 :     Cost        startup_cost = 0;
    1254         872 :     Cost        run_cost = 0;
    1255             :     QualCost    qpqual_cost;
    1256             :     Cost        cpu_per_tuple;
    1257             :     QualCost    tid_qual_cost;
    1258             :     double      ntuples;
    1259             :     ListCell   *l;
    1260             :     double      spc_random_page_cost;
    1261         872 :     uint64      enable_mask = 0;
    1262             : 
    1263             :     /* Should only be applied to base relations */
    1264             :     Assert(baserel->relid > 0);
    1265             :     Assert(baserel->rtekind == RTE_RELATION);
    1266             :     Assert(tidquals != NIL);
    1267             : 
    1268             :     /* Mark the path with the correct row estimate */
    1269         872 :     if (param_info)
    1270         144 :         path->rows = param_info->ppi_rows;
    1271             :     else
    1272         728 :         path->rows = baserel->rows;
    1273             : 
    1274             :     /* Count how many tuples we expect to retrieve */
    1275         872 :     ntuples = 0;
    1276        1770 :     foreach(l, tidquals)
    1277             :     {
    1278         898 :         RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    1279         898 :         Expr       *qual = rinfo->clause;
    1280             : 
    1281             :         /*
    1282             :          * We must use a TID scan for CurrentOfExpr; in any other case, we
    1283             :          * should be generating a TID scan only if TID scans are allowed.
    1284             :          * Also, if CurrentOfExpr is the qual, there should be only one.
    1285             :          */
    1286             :         Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0 || IsA(qual, CurrentOfExpr));
    1287             :         Assert(list_length(tidquals) == 1 || !IsA(qual, CurrentOfExpr));
    1288             : 
    1289         898 :         if (IsA(qual, ScalarArrayOpExpr))
    1290             :         {
    1291             :             /* Each element of the array yields 1 tuple */
    1292          50 :             ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
    1293          50 :             Node       *arraynode = (Node *) lsecond(saop->args);
    1294             : 
    1295          50 :             ntuples += estimate_array_length(root, arraynode);
    1296             :         }
    1297         848 :         else if (IsA(qual, CurrentOfExpr))
    1298             :         {
    1299             :             /* CURRENT OF yields 1 tuple */
    1300         404 :             ntuples++;
    1301             :         }
    1302             :         else
    1303             :         {
    1304             :             /* It's just CTID = something, count 1 tuple */
    1305         444 :             ntuples++;
    1306             :         }
    1307             :     }
    1308             : 
    1309             :     /*
    1310             :      * The TID qual expressions will be computed once, any other baserestrict
    1311             :      * quals once per retrieved tuple.
    1312             :      */
    1313         872 :     cost_qual_eval(&tid_qual_cost, tidquals, root);
    1314             : 
    1315             :     /* fetch estimated page cost for tablespace containing table */
    1316         872 :     get_tablespace_page_costs(baserel->reltablespace,
    1317             :                               &spc_random_page_cost,
    1318             :                               NULL);
    1319             : 
    1320             :     /* disk costs --- assume each tuple on a different page */
    1321         872 :     run_cost += spc_random_page_cost * ntuples;
    1322             : 
    1323             :     /* Add scanning CPU costs */
    1324         872 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1325             : 
    1326             :     /* XXX currently we assume TID quals are a subset of qpquals */
    1327         872 :     startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
    1328         872 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
    1329         872 :         tid_qual_cost.per_tuple;
    1330         872 :     run_cost += cpu_per_tuple * ntuples;
    1331             : 
    1332             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1333         872 :     startup_cost += path->pathtarget->cost.startup;
    1334         872 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
    1335             : 
    1336             :     /*
    1337             :      * There are assertions above verifying that we only reach this function
    1338             :      * either when baserel->pgs_mask includes PGS_TIDSCAN or when the TID scan
    1339             :      * is the only legal path, so we only need to consider the effects of
    1340             :      * PGS_CONSIDER_NONPARTIAL here.
    1341             :      */
    1342         872 :     if (path->parallel_workers == 0)
    1343         872 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1344         872 :     path->disabled_nodes =
    1345         872 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1346         872 :     path->startup_cost = startup_cost;
    1347         872 :     path->total_cost = startup_cost + run_cost;
    1348         872 : }
    1349             : 
    1350             : /*
    1351             :  * cost_tidrangescan
    1352             :  *    Determines and sets the costs of scanning a relation using a range of
    1353             :  *    TIDs for 'path'
    1354             :  *
    1355             :  * 'baserel' is the relation to be scanned
    1356             :  * 'tidrangequals' is the list of TID-checkable range quals
    1357             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
    1358             :  */
    1359             : void
    1360        2052 : cost_tidrangescan(Path *path, PlannerInfo *root,
    1361             :                   RelOptInfo *baserel, List *tidrangequals,
    1362             :                   ParamPathInfo *param_info)
    1363             : {
    1364             :     Selectivity selectivity;
    1365             :     double      pages;
    1366             :     Cost        startup_cost;
    1367             :     Cost        cpu_run_cost;
    1368             :     Cost        disk_run_cost;
    1369             :     QualCost    qpqual_cost;
    1370             :     Cost        cpu_per_tuple;
    1371             :     QualCost    tid_qual_cost;
    1372             :     double      ntuples;
    1373             :     double      nseqpages;
    1374             :     double      spc_random_page_cost;
    1375             :     double      spc_seq_page_cost;
    1376        2052 :     uint64      enable_mask = PGS_TIDSCAN;
    1377             : 
    1378             :     /* Should only be applied to base relations */
    1379             :     Assert(baserel->relid > 0);
    1380             :     Assert(baserel->rtekind == RTE_RELATION);
    1381             : 
    1382             :     /* Mark the path with the correct row estimate */
    1383        2052 :     if (param_info)
    1384           0 :         path->rows = param_info->ppi_rows;
    1385             :     else
    1386        2052 :         path->rows = baserel->rows;
    1387             : 
    1388             :     /* Count how many tuples and pages we expect to scan */
    1389        2052 :     selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
    1390             :                                          JOIN_INNER, NULL);
    1391        2052 :     pages = ceil(selectivity * baserel->pages);
    1392             : 
    1393        2052 :     if (pages <= 0.0)
    1394          42 :         pages = 1.0;
    1395             : 
    1396             :     /*
    1397             :      * The first page in a range requires a random seek, but each subsequent
    1398             :      * page is just a normal sequential page read. NOTE: it's desirable for
    1399             :      * TID Range Scans to cost more than the equivalent Sequential Scans,
    1400             :      * because Seq Scans have some performance advantages such as scan
    1401             :      * synchronization, and we'd prefer one of them to be picked unless a TID
    1402             :      * Range Scan really is better.
    1403             :      */
    1404        2052 :     ntuples = selectivity * baserel->tuples;
    1405        2052 :     nseqpages = pages - 1.0;
    1406             : 
    1407             :     /*
    1408             :      * The TID qual expressions will be computed once, any other baserestrict
    1409             :      * quals once per retrieved tuple.
    1410             :      */
    1411        2052 :     cost_qual_eval(&tid_qual_cost, tidrangequals, root);
    1412             : 
    1413             :     /* fetch estimated page cost for tablespace containing table */
    1414        2052 :     get_tablespace_page_costs(baserel->reltablespace,
    1415             :                               &spc_random_page_cost,
    1416             :                               &spc_seq_page_cost);
    1417             : 
    1418             :     /* disk costs; 1 random page and the remainder as seq pages */
    1419        2052 :     disk_run_cost = spc_random_page_cost + spc_seq_page_cost * nseqpages;
    1420             : 
    1421             :     /* Add scanning CPU costs */
    1422        2052 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1423             : 
    1424             :     /*
    1425             :      * XXX currently we assume TID quals are a subset of qpquals at this
    1426             :      * point; they will be removed (if possible) when we create the plan, so
    1427             :      * we subtract their cost from the total qpqual cost.  (If the TID quals
    1428             :      * can't be removed, this is a mistake and we're going to underestimate
    1429             :      * the CPU cost a bit.)
    1430             :      */
    1431        2052 :     startup_cost = qpqual_cost.startup + tid_qual_cost.per_tuple;
    1432        2052 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
    1433        2052 :         tid_qual_cost.per_tuple;
    1434        2052 :     cpu_run_cost = cpu_per_tuple * ntuples;
    1435             : 
    1436             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1437        2052 :     startup_cost += path->pathtarget->cost.startup;
    1438        2052 :     cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
    1439             : 
    1440             :     /* Adjust costing for parallelism, if used. */
    1441        2052 :     if (path->parallel_workers > 0)
    1442             :     {
    1443          48 :         double      parallel_divisor = get_parallel_divisor(path);
    1444             : 
    1445             :         /* The CPU cost is divided among all the workers. */
    1446          48 :         cpu_run_cost /= parallel_divisor;
    1447             : 
    1448             :         /*
    1449             :          * In the case of a parallel plan, the row count needs to represent
    1450             :          * the number of tuples processed per worker.
    1451             :          */
    1452          48 :         path->rows = clamp_row_est(path->rows / parallel_divisor);
    1453             :     }
    1454             : 
    1455             :     /*
    1456             :      * We should not generate this path type when PGS_TIDSCAN is unset, but we
    1457             :      * might need to disable this path due to PGS_CONSIDER_NONPARTIAL.
    1458             :      */
    1459             :     Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0);
    1460        2052 :     if (path->parallel_workers == 0)
    1461        2004 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1462        2052 :     path->disabled_nodes =
    1463        2052 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1464        2052 :     path->startup_cost = startup_cost;
    1465        2052 :     path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
    1466        2052 : }
    1467             : 
    1468             : /*
    1469             :  * cost_subqueryscan
    1470             :  *    Determines and returns the cost of scanning a subquery RTE.
    1471             :  *
    1472             :  * 'baserel' is the relation to be scanned
    1473             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
    1474             :  * 'trivial_pathtarget' is true if the pathtarget is believed to be trivial.
    1475             :  */
    1476             : void
    1477       63190 : cost_subqueryscan(SubqueryScanPath *path, PlannerInfo *root,
    1478             :                   RelOptInfo *baserel, ParamPathInfo *param_info,
    1479             :                   bool trivial_pathtarget)
    1480             : {
    1481             :     Cost        startup_cost;
    1482             :     Cost        run_cost;
    1483             :     List       *qpquals;
    1484             :     QualCost    qpqual_cost;
    1485             :     Cost        cpu_per_tuple;
    1486       63190 :     uint64      enable_mask = 0;
    1487             : 
    1488             :     /* Should only be applied to base relations that are subqueries */
    1489             :     Assert(baserel->relid > 0);
    1490             :     Assert(baserel->rtekind == RTE_SUBQUERY);
    1491             : 
    1492             :     /*
    1493             :      * We compute the rowcount estimate as the subplan's estimate times the
    1494             :      * selectivity of relevant restriction clauses.  In simple cases this will
    1495             :      * come out the same as baserel->rows; but when dealing with parallelized
    1496             :      * paths we must do it like this to get the right answer.
    1497             :      */
    1498       63190 :     if (param_info)
    1499         940 :         qpquals = list_concat_copy(param_info->ppi_clauses,
    1500         940 :                                    baserel->baserestrictinfo);
    1501             :     else
    1502       62250 :         qpquals = baserel->baserestrictinfo;
    1503             : 
    1504       63190 :     path->path.rows = clamp_row_est(path->subpath->rows *
    1505       63190 :                                     clauselist_selectivity(root,
    1506             :                                                            qpquals,
    1507             :                                                            0,
    1508             :                                                            JOIN_INNER,
    1509             :                                                            NULL));
    1510             : 
    1511             :     /*
    1512             :      * Cost of path is cost of evaluating the subplan, plus cost of evaluating
    1513             :      * any restriction clauses and tlist that will be attached to the
    1514             :      * SubqueryScan node, plus cpu_tuple_cost to account for selection and
    1515             :      * projection overhead.
    1516             :      */
    1517       63190 :     if (path->path.parallel_workers == 0)
    1518       63124 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1519       63190 :     path->path.disabled_nodes = path->subpath->disabled_nodes
    1520       63190 :         + (((baserel->pgs_mask & enable_mask) != enable_mask) ? 1 : 0);
    1521       63190 :     path->path.startup_cost = path->subpath->startup_cost;
    1522       63190 :     path->path.total_cost = path->subpath->total_cost;
    1523             : 
    1524             :     /*
    1525             :      * However, if there are no relevant restriction clauses and the
    1526             :      * pathtarget is trivial, then we expect that setrefs.c will optimize away
    1527             :      * the SubqueryScan plan node altogether, so we should just make its cost
    1528             :      * and rowcount equal to the input path's.
    1529             :      *
    1530             :      * Note: there are some edge cases where createplan.c will apply a
    1531             :      * different targetlist to the SubqueryScan node, thus falsifying our
    1532             :      * current estimate of whether the target is trivial, and making the cost
    1533             :      * estimate (though not the rowcount) wrong.  It does not seem worth the
    1534             :      * extra complication to try to account for that exactly, especially since
    1535             :      * that behavior falsifies other cost estimates as well.
    1536             :      */
    1537       63190 :     if (qpquals == NIL && trivial_pathtarget)
    1538       27650 :         return;
    1539             : 
    1540       35540 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1541             : 
    1542       35540 :     startup_cost = qpqual_cost.startup;
    1543       35540 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
    1544       35540 :     run_cost = cpu_per_tuple * path->subpath->rows;
    1545             : 
    1546             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1547       35540 :     startup_cost += path->path.pathtarget->cost.startup;
    1548       35540 :     run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
    1549             : 
    1550       35540 :     path->path.startup_cost += startup_cost;
    1551       35540 :     path->path.total_cost += startup_cost + run_cost;
    1552             : }
    1553             : 
    1554             : /*
    1555             :  * cost_functionscan
    1556             :  *    Determines and returns the cost of scanning a function RTE.
    1557             :  *
    1558             :  * 'baserel' is the relation to be scanned
    1559             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
    1560             :  */
    1561             : void
    1562       53556 : cost_functionscan(Path *path, PlannerInfo *root,
    1563             :                   RelOptInfo *baserel, ParamPathInfo *param_info)
    1564             : {
    1565       53556 :     Cost        startup_cost = 0;
    1566       53556 :     Cost        run_cost = 0;
    1567             :     QualCost    qpqual_cost;
    1568             :     Cost        cpu_per_tuple;
    1569             :     RangeTblEntry *rte;
    1570             :     QualCost    exprcost;
    1571       53556 :     uint64      enable_mask = 0;
    1572             : 
    1573             :     /* Should only be applied to base relations that are functions */
    1574             :     Assert(baserel->relid > 0);
    1575       53556 :     rte = planner_rt_fetch(baserel->relid, root);
    1576             :     Assert(rte->rtekind == RTE_FUNCTION);
    1577             : 
    1578             :     /* Mark the path with the correct row estimate */
    1579       53556 :     if (param_info)
    1580        8590 :         path->rows = param_info->ppi_rows;
    1581             :     else
    1582       44966 :         path->rows = baserel->rows;
    1583             : 
    1584             :     /*
    1585             :      * Estimate costs of executing the function expression(s).
    1586             :      *
    1587             :      * Currently, nodeFunctionscan.c always executes the functions to
    1588             :      * completion before returning any rows, and caches the results in a
    1589             :      * tuplestore.  So the function eval cost is all startup cost, and per-row
    1590             :      * costs are minimal.
    1591             :      *
    1592             :      * XXX in principle we ought to charge tuplestore spill costs if the
    1593             :      * number of rows is large.  However, given how phony our rowcount
    1594             :      * estimates for functions tend to be, there's not a lot of point in that
    1595             :      * refinement right now.
    1596             :      */
    1597       53556 :     cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
    1598             : 
    1599       53556 :     startup_cost += exprcost.startup + exprcost.per_tuple;
    1600             : 
    1601             :     /* Add scanning CPU costs */
    1602       53556 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1603             : 
    1604       53556 :     startup_cost += qpqual_cost.startup;
    1605       53556 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
    1606       53556 :     run_cost += cpu_per_tuple * baserel->tuples;
    1607             : 
    1608             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1609       53556 :     startup_cost += path->pathtarget->cost.startup;
    1610       53556 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
    1611             : 
    1612       53556 :     if (path->parallel_workers == 0)
    1613       53556 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1614       53556 :     path->disabled_nodes =
    1615       53556 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1616       53556 :     path->startup_cost = startup_cost;
    1617       53556 :     path->total_cost = startup_cost + run_cost;
    1618       53556 : }
    1619             : 
    1620             : /*
    1621             :  * cost_tablefuncscan
    1622             :  *    Determines and returns the cost of scanning a table function.
    1623             :  *
    1624             :  * 'baserel' is the relation to be scanned
    1625             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
    1626             :  */
    1627             : void
    1628         626 : cost_tablefuncscan(Path *path, PlannerInfo *root,
    1629             :                    RelOptInfo *baserel, ParamPathInfo *param_info)
    1630             : {
    1631         626 :     Cost        startup_cost = 0;
    1632         626 :     Cost        run_cost = 0;
    1633             :     QualCost    qpqual_cost;
    1634             :     Cost        cpu_per_tuple;
    1635             :     RangeTblEntry *rte;
    1636             :     QualCost    exprcost;
    1637         626 :     uint64      enable_mask = 0;
    1638             : 
    1639             :     /* Should only be applied to base relations that are functions */
    1640             :     Assert(baserel->relid > 0);
    1641         626 :     rte = planner_rt_fetch(baserel->relid, root);
    1642             :     Assert(rte->rtekind == RTE_TABLEFUNC);
    1643             : 
    1644             :     /* Mark the path with the correct row estimate */
    1645         626 :     if (param_info)
    1646         234 :         path->rows = param_info->ppi_rows;
    1647             :     else
    1648         392 :         path->rows = baserel->rows;
    1649             : 
    1650             :     /*
    1651             :      * Estimate costs of executing the table func expression(s).
    1652             :      *
    1653             :      * XXX in principle we ought to charge tuplestore spill costs if the
    1654             :      * number of rows is large.  However, given how phony our rowcount
    1655             :      * estimates for tablefuncs tend to be, there's not a lot of point in that
    1656             :      * refinement right now.
    1657             :      */
    1658         626 :     cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
    1659             : 
    1660         626 :     startup_cost += exprcost.startup + exprcost.per_tuple;
    1661             : 
    1662             :     /* Add scanning CPU costs */
    1663         626 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1664             : 
    1665         626 :     startup_cost += qpqual_cost.startup;
    1666         626 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
    1667         626 :     run_cost += cpu_per_tuple * baserel->tuples;
    1668             : 
    1669             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1670         626 :     startup_cost += path->pathtarget->cost.startup;
    1671         626 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
    1672             : 
    1673         626 :     if (path->parallel_workers == 0)
    1674         626 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1675         626 :     path->disabled_nodes =
    1676         626 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1677         626 :     path->startup_cost = startup_cost;
    1678         626 :     path->total_cost = startup_cost + run_cost;
    1679         626 : }
    1680             : 
    1681             : /*
    1682             :  * cost_valuesscan
    1683             :  *    Determines and returns the cost of scanning a VALUES RTE.
    1684             :  *
    1685             :  * 'baserel' is the relation to be scanned
    1686             :  * 'param_info' is the ParamPathInfo if this is a parameterized path, else NULL
    1687             :  */
    1688             : void
    1689        8520 : cost_valuesscan(Path *path, PlannerInfo *root,
    1690             :                 RelOptInfo *baserel, ParamPathInfo *param_info)
    1691             : {
    1692        8520 :     Cost        startup_cost = 0;
    1693        8520 :     Cost        run_cost = 0;
    1694             :     QualCost    qpqual_cost;
    1695             :     Cost        cpu_per_tuple;
    1696        8520 :     uint64      enable_mask = 0;
    1697             : 
    1698             :     /* Should only be applied to base relations that are values lists */
    1699             :     Assert(baserel->relid > 0);
    1700             :     Assert(baserel->rtekind == RTE_VALUES);
    1701             : 
    1702             :     /* Mark the path with the correct row estimate */
    1703        8520 :     if (param_info)
    1704          66 :         path->rows = param_info->ppi_rows;
    1705             :     else
    1706        8454 :         path->rows = baserel->rows;
    1707             : 
    1708             :     /*
    1709             :      * For now, estimate list evaluation cost at one operator eval per list
    1710             :      * (probably pretty bogus, but is it worth being smarter?)
    1711             :      */
    1712        8520 :     cpu_per_tuple = cpu_operator_cost;
    1713             : 
    1714             :     /* Add scanning CPU costs */
    1715        8520 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1716             : 
    1717        8520 :     startup_cost += qpqual_cost.startup;
    1718        8520 :     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
    1719        8520 :     run_cost += cpu_per_tuple * baserel->tuples;
    1720             : 
    1721             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1722        8520 :     startup_cost += path->pathtarget->cost.startup;
    1723        8520 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
    1724             : 
    1725        8520 :     if (path->parallel_workers == 0)
    1726        8520 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1727        8520 :     path->disabled_nodes =
    1728        8520 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1729        8520 :     path->startup_cost = startup_cost;
    1730        8520 :     path->total_cost = startup_cost + run_cost;
    1731        8520 : }
    1732             : 
    1733             : /*
    1734             :  * cost_ctescan
    1735             :  *    Determines and returns the cost of scanning a CTE RTE.
    1736             :  *
    1737             :  * Note: this is used for both self-reference and regular CTEs; the
    1738             :  * possible cost differences are below the threshold of what we could
    1739             :  * estimate accurately anyway.  Note that the costs of evaluating the
    1740             :  * referenced CTE query are added into the final plan as initplan costs,
    1741             :  * and should NOT be counted here.
    1742             :  */
    1743             : void
    1744        5312 : cost_ctescan(Path *path, PlannerInfo *root,
    1745             :              RelOptInfo *baserel, ParamPathInfo *param_info)
    1746             : {
    1747        5312 :     Cost        startup_cost = 0;
    1748        5312 :     Cost        run_cost = 0;
    1749             :     QualCost    qpqual_cost;
    1750             :     Cost        cpu_per_tuple;
    1751        5312 :     uint64      enable_mask = 0;
    1752             : 
    1753             :     /* Should only be applied to base relations that are CTEs */
    1754             :     Assert(baserel->relid > 0);
    1755             :     Assert(baserel->rtekind == RTE_CTE);
    1756             : 
    1757             :     /* Mark the path with the correct row estimate */
    1758        5312 :     if (param_info)
    1759           0 :         path->rows = param_info->ppi_rows;
    1760             :     else
    1761        5312 :         path->rows = baserel->rows;
    1762             : 
    1763             :     /* Charge one CPU tuple cost per row for tuplestore manipulation */
    1764        5312 :     cpu_per_tuple = cpu_tuple_cost;
    1765             : 
    1766             :     /* Add scanning CPU costs */
    1767        5312 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1768             : 
    1769        5312 :     startup_cost += qpqual_cost.startup;
    1770        5312 :     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
    1771        5312 :     run_cost += cpu_per_tuple * baserel->tuples;
    1772             : 
    1773             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    1774        5312 :     startup_cost += path->pathtarget->cost.startup;
    1775        5312 :     run_cost += path->pathtarget->cost.per_tuple * path->rows;
    1776             : 
    1777        5312 :     if (path->parallel_workers == 0)
    1778        5312 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1779        5312 :     path->disabled_nodes =
    1780        5312 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1781        5312 :     path->startup_cost = startup_cost;
    1782        5312 :     path->total_cost = startup_cost + run_cost;
    1783        5312 : }
    1784             : 
    1785             : /*
    1786             :  * cost_namedtuplestorescan
    1787             :  *    Determines and returns the cost of scanning a named tuplestore.
    1788             :  */
    1789             : void
    1790         474 : cost_namedtuplestorescan(Path *path, PlannerInfo *root,
    1791             :                          RelOptInfo *baserel, ParamPathInfo *param_info)
    1792             : {
    1793         474 :     Cost        startup_cost = 0;
    1794         474 :     Cost        run_cost = 0;
    1795             :     QualCost    qpqual_cost;
    1796             :     Cost        cpu_per_tuple;
    1797         474 :     uint64      enable_mask = 0;
    1798             : 
    1799             :     /* Should only be applied to base relations that are Tuplestores */
    1800             :     Assert(baserel->relid > 0);
    1801             :     Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
    1802             : 
    1803             :     /* Mark the path with the correct row estimate */
    1804         474 :     if (param_info)
    1805           0 :         path->rows = param_info->ppi_rows;
    1806             :     else
    1807         474 :         path->rows = baserel->rows;
    1808             : 
    1809             :     /* Charge one CPU tuple cost per row for tuplestore manipulation */
    1810         474 :     cpu_per_tuple = cpu_tuple_cost;
    1811             : 
    1812             :     /* Add scanning CPU costs */
    1813         474 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1814             : 
    1815         474 :     startup_cost += qpqual_cost.startup;
    1816         474 :     cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
    1817         474 :     run_cost += cpu_per_tuple * baserel->tuples;
    1818             : 
    1819         474 :     if (path->parallel_workers == 0)
    1820         474 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1821         474 :     path->disabled_nodes =
    1822         474 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1823         474 :     path->startup_cost = startup_cost;
    1824         474 :     path->total_cost = startup_cost + run_cost;
    1825         474 : }
    1826             : 
    1827             : /*
    1828             :  * cost_resultscan
    1829             :  *    Determines and returns the cost of scanning an RTE_RESULT relation.
    1830             :  */
    1831             : void
    1832        4352 : cost_resultscan(Path *path, PlannerInfo *root,
    1833             :                 RelOptInfo *baserel, ParamPathInfo *param_info)
    1834             : {
    1835        4352 :     Cost        startup_cost = 0;
    1836        4352 :     Cost        run_cost = 0;
    1837             :     QualCost    qpqual_cost;
    1838             :     Cost        cpu_per_tuple;
    1839        4352 :     uint64      enable_mask = 0;
    1840             : 
    1841             :     /* Should only be applied to RTE_RESULT base relations */
    1842             :     Assert(baserel->relid > 0);
    1843             :     Assert(baserel->rtekind == RTE_RESULT);
    1844             : 
    1845             :     /* Mark the path with the correct row estimate */
    1846        4352 :     if (param_info)
    1847         156 :         path->rows = param_info->ppi_rows;
    1848             :     else
    1849        4196 :         path->rows = baserel->rows;
    1850             : 
    1851             :     /* We charge qual cost plus cpu_tuple_cost */
    1852        4352 :     get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
    1853             : 
    1854        4352 :     startup_cost += qpqual_cost.startup;
    1855        4352 :     cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
    1856        4352 :     run_cost += cpu_per_tuple * baserel->tuples;
    1857             : 
    1858        4352 :     if (path->parallel_workers == 0)
    1859        4352 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1860        4352 :     path->disabled_nodes =
    1861        4352 :         (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1862        4352 :     path->startup_cost = startup_cost;
    1863        4352 :     path->total_cost = startup_cost + run_cost;
    1864        4352 : }
    1865             : 
    1866             : /*
    1867             :  * cost_recursive_union
    1868             :  *    Determines and returns the cost of performing a recursive union,
    1869             :  *    and also the estimated output size.
    1870             :  *
    1871             :  * We are given Paths for the nonrecursive and recursive terms.
    1872             :  */
    1873             : void
    1874         936 : cost_recursive_union(Path *runion, Path *nrterm, Path *rterm)
    1875             : {
    1876             :     Cost        startup_cost;
    1877             :     Cost        total_cost;
    1878             :     double      total_rows;
    1879         936 :     uint64      enable_mask = 0;
    1880             : 
    1881             :     /* We probably have decent estimates for the non-recursive term */
    1882         936 :     startup_cost = nrterm->startup_cost;
    1883         936 :     total_cost = nrterm->total_cost;
    1884         936 :     total_rows = nrterm->rows;
    1885             : 
    1886             :     /*
    1887             :      * We arbitrarily assume that about 10 recursive iterations will be
    1888             :      * needed, and that we've managed to get a good fix on the cost and output
    1889             :      * size of each one of them.  These are mighty shaky assumptions but it's
    1890             :      * hard to see how to do better.
    1891             :      */
    1892         936 :     total_cost += 10 * rterm->total_cost;
    1893         936 :     total_rows += 10 * rterm->rows;
    1894             : 
    1895             :     /*
    1896             :      * Also charge cpu_tuple_cost per row to account for the costs of
    1897             :      * manipulating the tuplestores.  (We don't worry about possible
    1898             :      * spill-to-disk costs.)
    1899             :      */
    1900         936 :     total_cost += cpu_tuple_cost * total_rows;
    1901             : 
    1902         936 :     if (runion->parallel_workers == 0)
    1903         936 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    1904         936 :     runion->disabled_nodes =
    1905         936 :         (runion->parent->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
    1906         936 :     runion->startup_cost = startup_cost;
    1907         936 :     runion->total_cost = total_cost;
    1908         936 :     runion->rows = total_rows;
    1909         936 :     runion->pathtarget->width = Max(nrterm->pathtarget->width,
    1910             :                                     rterm->pathtarget->width);
    1911         936 : }
    1912             : 
    1913             : /*
    1914             :  * cost_tuplesort
    1915             :  *    Determines and returns the cost of sorting a relation using tuplesort,
    1916             :  *    not including the cost of reading the input data.
    1917             :  *
    1918             :  * If the total volume of data to sort is less than sort_mem, we will do
    1919             :  * an in-memory sort, which requires no I/O and about t*log2(t) tuple
    1920             :  * comparisons for t tuples.
    1921             :  *
    1922             :  * If the total volume exceeds sort_mem, we switch to a tape-style merge
    1923             :  * algorithm.  There will still be about t*log2(t) tuple comparisons in
    1924             :  * total, but we will also need to write and read each tuple once per
    1925             :  * merge pass.  We expect about ceil(logM(r)) merge passes where r is the
    1926             :  * number of initial runs formed and M is the merge order used by tuplesort.c.
    1927             :  * Since the average initial run should be about sort_mem, we have
    1928             :  *      disk traffic = 2 * relsize * ceil(logM(p / sort_mem))
    1929             :  *      cpu = comparison_cost * t * log2(t)
    1930             :  *
    1931             :  * If the sort is bounded (i.e., only the first k result tuples are needed)
    1932             :  * and k tuples can fit into sort_mem, we use a heap method that keeps only
    1933             :  * k tuples in the heap; this will require about t*log2(k) tuple comparisons.
    1934             :  *
    1935             :  * The disk traffic is assumed to be 3/4ths sequential and 1/4th random
    1936             :  * accesses (XXX can't we refine that guess?)
    1937             :  *
    1938             :  * By default, we charge two operator evals per tuple comparison, which should
    1939             :  * be in the right ballpark in most cases.  The caller can tweak this by
    1940             :  * specifying nonzero comparison_cost; typically that's used for any extra
    1941             :  * work that has to be done to prepare the inputs to the comparison operators.
    1942             :  *
    1943             :  * 'tuples' is the number of tuples in the relation
    1944             :  * 'width' is the average tuple width in bytes
    1945             :  * 'comparison_cost' is the extra cost per comparison, if any
    1946             :  * 'sort_mem' is the number of kilobytes of work memory allowed for the sort
    1947             :  * 'limit_tuples' is the bound on the number of output tuples; -1 if no bound
    1948             :  */
    1949             : static void
    1950     2147642 : cost_tuplesort(Cost *startup_cost, Cost *run_cost,
    1951             :                double tuples, int width,
    1952             :                Cost comparison_cost, int sort_mem,
    1953             :                double limit_tuples)
    1954             : {
    1955     2147642 :     double      input_bytes = relation_byte_size(tuples, width);
    1956             :     double      output_bytes;
    1957             :     double      output_tuples;
    1958     2147642 :     int64       sort_mem_bytes = sort_mem * (int64) 1024;
    1959             : 
    1960             :     /*
    1961             :      * We want to be sure the cost of a sort is never estimated as zero, even
    1962             :      * if passed-in tuple count is zero.  Besides, mustn't do log(0)...
    1963             :      */
    1964     2147642 :     if (tuples < 2.0)
    1965      581902 :         tuples = 2.0;
    1966             : 
    1967             :     /* Include the default cost-per-comparison */
    1968     2147642 :     comparison_cost += 2.0 * cpu_operator_cost;
    1969             : 
    1970             :     /* Do we have a useful LIMIT? */
    1971     2147642 :     if (limit_tuples > 0 && limit_tuples < tuples)
    1972             :     {
    1973        1826 :         output_tuples = limit_tuples;
    1974        1826 :         output_bytes = relation_byte_size(output_tuples, width);
    1975             :     }
    1976             :     else
    1977             :     {
    1978     2145816 :         output_tuples = tuples;
    1979     2145816 :         output_bytes = input_bytes;
    1980             :     }
    1981             : 
    1982     2147642 :     if (output_bytes > sort_mem_bytes)
    1983             :     {
    1984             :         /*
    1985             :          * We'll have to use a disk-based sort of all the tuples
    1986             :          */
    1987       17658 :         double      npages = ceil(input_bytes / BLCKSZ);
    1988       17658 :         double      nruns = input_bytes / sort_mem_bytes;
    1989       17658 :         double      mergeorder = tuplesort_merge_order(sort_mem_bytes);
    1990             :         double      log_runs;
    1991             :         double      npageaccesses;
    1992             : 
    1993             :         /*
    1994             :          * CPU costs
    1995             :          *
    1996             :          * Assume about N log2 N comparisons
    1997             :          */
    1998       17658 :         *startup_cost = comparison_cost * tuples * LOG2(tuples);
    1999             : 
    2000             :         /* Disk costs */
    2001             : 
    2002             :         /* Compute logM(r) as log(r) / log(M) */
    2003       17658 :         if (nruns > mergeorder)
    2004        5274 :             log_runs = ceil(log(nruns) / log(mergeorder));
    2005             :         else
    2006       12384 :             log_runs = 1.0;
    2007       17658 :         npageaccesses = 2.0 * npages * log_runs;
    2008             :         /* Assume 3/4ths of accesses are sequential, 1/4th are not */
    2009       17658 :         *startup_cost += npageaccesses *
    2010       17658 :             (seq_page_cost * 0.75 + random_page_cost * 0.25);
    2011             :     }
    2012     2129984 :     else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
    2013             :     {
    2014             :         /*
    2015             :          * We'll use a bounded heap-sort keeping just K tuples in memory, for
    2016             :          * a total number of tuple comparisons of N log2 K; but the constant
    2017             :          * factor is a bit higher than for quicksort.  Tweak it so that the
    2018             :          * cost curve is continuous at the crossover point.
    2019             :          */
    2020        1346 :         *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
    2021             :     }
    2022             :     else
    2023             :     {
    2024             :         /* We'll use plain quicksort on all the input tuples */
    2025     2128638 :         *startup_cost = comparison_cost * tuples * LOG2(tuples);
    2026             :     }
    2027             : 
    2028             :     /*
    2029             :      * Also charge a small amount (arbitrarily set equal to operator cost) per
    2030             :      * extracted tuple.  We don't charge cpu_tuple_cost because a Sort node
    2031             :      * doesn't do qual-checking or projection, so it has less overhead than
    2032             :      * most plan nodes.  Note it's correct to use tuples not output_tuples
    2033             :      * here --- the upper LIMIT will pro-rate the run cost so we'd be double
    2034             :      * counting the LIMIT otherwise.
    2035             :      */
    2036     2147642 :     *run_cost = cpu_operator_cost * tuples;
    2037     2147642 : }
    2038             : 
    2039             : /*
    2040             :  * cost_incremental_sort
    2041             :  *  Determines and returns the cost of sorting a relation incrementally, when
    2042             :  *  the input path is presorted by a prefix of the pathkeys.
    2043             :  *
    2044             :  * 'presorted_keys' is the number of leading pathkeys by which the input path
    2045             :  * is sorted.
    2046             :  *
    2047             :  * We estimate the number of groups into which the relation is divided by the
    2048             :  * leading pathkeys, and then calculate the cost of sorting a single group
    2049             :  * with tuplesort using cost_tuplesort().
    2050             :  */
    2051             : void
    2052       12890 : cost_incremental_sort(Path *path,
    2053             :                       PlannerInfo *root, List *pathkeys, int presorted_keys,
    2054             :                       int input_disabled_nodes,
    2055             :                       Cost input_startup_cost, Cost input_total_cost,
    2056             :                       double input_tuples, int width, Cost comparison_cost, int sort_mem,
    2057             :                       double limit_tuples)
    2058             : {
    2059             :     Cost        startup_cost,
    2060             :                 run_cost,
    2061       12890 :                 input_run_cost = input_total_cost - input_startup_cost;
    2062             :     double      group_tuples,
    2063             :                 input_groups;
    2064             :     Cost        group_startup_cost,
    2065             :                 group_run_cost,
    2066             :                 group_input_run_cost;
    2067       12890 :     List       *presortedExprs = NIL;
    2068             :     ListCell   *l;
    2069       12890 :     bool        unknown_varno = false;
    2070             : 
    2071             :     Assert(presorted_keys > 0 && presorted_keys < list_length(pathkeys));
    2072             : 
    2073             :     /*
    2074             :      * We want to be sure the cost of a sort is never estimated as zero, even
    2075             :      * if passed-in tuple count is zero.  Besides, mustn't do log(0)...
    2076             :      */
    2077       12890 :     if (input_tuples < 2.0)
    2078        6792 :         input_tuples = 2.0;
    2079             : 
    2080             :     /* Default estimate of number of groups, capped to one group per row. */
    2081       12890 :     input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
    2082             : 
    2083             :     /*
    2084             :      * Extract presorted keys as list of expressions.
    2085             :      *
    2086             :      * We need to be careful about Vars containing "varno 0" which might have
    2087             :      * been introduced by generate_append_tlist, which would confuse
    2088             :      * estimate_num_groups (in fact it'd fail for such expressions). See
    2089             :      * recurse_set_operations which has to deal with the same issue.
    2090             :      *
    2091             :      * Unlike recurse_set_operations we can't access the original target list
    2092             :      * here, and even if we could it's not very clear how useful would that be
    2093             :      * for a set operation combining multiple tables. So we simply detect if
    2094             :      * there are any expressions with "varno 0" and use the default
    2095             :      * DEFAULT_NUM_DISTINCT in that case.
    2096             :      *
    2097             :      * We might also use either 1.0 (a single group) or input_tuples (each row
    2098             :      * being a separate group), pretty much the worst and best case for
    2099             :      * incremental sort. But those are extreme cases and using something in
    2100             :      * between seems reasonable. Furthermore, generate_append_tlist is used
    2101             :      * for set operations, which are likely to produce mostly unique output
    2102             :      * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
    2103             :      * while maintaining lower startup cost.
    2104             :      */
    2105       12986 :     foreach(l, pathkeys)
    2106             :     {
    2107       12986 :         PathKey    *key = (PathKey *) lfirst(l);
    2108       12986 :         EquivalenceMember *member = (EquivalenceMember *)
    2109       12986 :             linitial(key->pk_eclass->ec_members);
    2110             : 
    2111             :         /*
    2112             :          * Check if the expression contains Var with "varno 0" so that we
    2113             :          * don't call estimate_num_groups in that case.
    2114             :          */
    2115       12986 :         if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
    2116             :         {
    2117          10 :             unknown_varno = true;
    2118          10 :             break;
    2119             :         }
    2120             : 
    2121             :         /* expression not containing any Vars with "varno 0" */
    2122       12976 :         presortedExprs = lappend(presortedExprs, member->em_expr);
    2123             : 
    2124       12976 :         if (foreach_current_index(l) + 1 >= presorted_keys)
    2125       12880 :             break;
    2126             :     }
    2127             : 
    2128             :     /* Estimate the number of groups with equal presorted keys. */
    2129       12890 :     if (!unknown_varno)
    2130       12880 :         input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
    2131             :                                            NULL, NULL);
    2132             : 
    2133       12890 :     group_tuples = input_tuples / input_groups;
    2134       12890 :     group_input_run_cost = input_run_cost / input_groups;
    2135             : 
    2136             :     /*
    2137             :      * Estimate the average cost of sorting of one group where presorted keys
    2138             :      * are equal.
    2139             :      */
    2140       12890 :     cost_tuplesort(&group_startup_cost, &group_run_cost,
    2141             :                    group_tuples, width, comparison_cost, sort_mem,
    2142             :                    limit_tuples);
    2143             : 
    2144             :     /*
    2145             :      * Startup cost of incremental sort is the startup cost of its first group
    2146             :      * plus the cost of its input.
    2147             :      */
    2148       12890 :     startup_cost = group_startup_cost + input_startup_cost +
    2149             :         group_input_run_cost;
    2150             : 
    2151             :     /*
    2152             :      * After we started producing tuples from the first group, the cost of
    2153             :      * producing all the tuples is given by the cost to finish processing this
    2154             :      * group, plus the total cost to process the remaining groups, plus the
    2155             :      * remaining cost of input.
    2156             :      */
    2157       12890 :     run_cost = group_run_cost + (group_run_cost + group_startup_cost) *
    2158       12890 :         (input_groups - 1) + group_input_run_cost * (input_groups - 1);
    2159             : 
    2160             :     /*
    2161             :      * Incremental sort adds some overhead by itself. Firstly, it has to
    2162             :      * detect the sort groups. This is roughly equal to one extra copy and
    2163             :      * comparison per tuple.
    2164             :      */
    2165       12890 :     run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
    2166             : 
    2167             :     /*
    2168             :      * Additionally, we charge double cpu_tuple_cost for each input group to
    2169             :      * account for the tuplesort_reset that's performed after each group.
    2170             :      */
    2171       12890 :     run_cost += 2.0 * cpu_tuple_cost * input_groups;
    2172             : 
    2173       12890 :     path->rows = input_tuples;
    2174             : 
    2175             :     /*
    2176             :      * We should not generate these paths when enable_incremental_sort=false.
    2177             :      * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
    2178             :      * it will have already affected the input path.
    2179             :      */
    2180             :     Assert(enable_incremental_sort);
    2181       12890 :     path->disabled_nodes = input_disabled_nodes;
    2182             : 
    2183       12890 :     path->startup_cost = startup_cost;
    2184       12890 :     path->total_cost = startup_cost + run_cost;
    2185       12890 : }
    2186             : 
    2187             : /*
    2188             :  * cost_sort
    2189             :  *    Determines and returns the cost of sorting a relation, including
    2190             :  *    the cost of reading the input data.
    2191             :  *
    2192             :  * NOTE: some callers currently pass NIL for pathkeys because they
    2193             :  * can't conveniently supply the sort keys.  Since this routine doesn't
    2194             :  * currently do anything with pathkeys anyway, that doesn't matter...
    2195             :  * but if it ever does, it should react gracefully to lack of key data.
    2196             :  * (Actually, the thing we'd most likely be interested in is just the number
    2197             :  * of sort keys, which all callers *could* supply.)
    2198             :  */
    2199             : void
    2200     2134752 : cost_sort(Path *path, PlannerInfo *root,
    2201             :           List *pathkeys, int input_disabled_nodes,
    2202             :           Cost input_cost, double tuples, int width,
    2203             :           Cost comparison_cost, int sort_mem,
    2204             :           double limit_tuples)
    2205             : 
    2206             : {
    2207             :     Cost        startup_cost;
    2208             :     Cost        run_cost;
    2209             : 
    2210     2134752 :     cost_tuplesort(&startup_cost, &run_cost,
    2211             :                    tuples, width,
    2212             :                    comparison_cost, sort_mem,
    2213             :                    limit_tuples);
    2214             : 
    2215     2134752 :     startup_cost += input_cost;
    2216             : 
    2217             :     /*
    2218             :      * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
    2219             :      * it will have already affected the input path.
    2220             :      */
    2221     2134752 :     path->rows = tuples;
    2222     2134752 :     path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
    2223     2134752 :     path->startup_cost = startup_cost;
    2224     2134752 :     path->total_cost = startup_cost + run_cost;
    2225     2134752 : }
    2226             : 
    2227             : /*
    2228             :  * append_nonpartial_cost
    2229             :  *    Estimate the cost of the non-partial paths in a Parallel Append.
    2230             :  *    The non-partial paths are assumed to be the first "numpaths" paths
    2231             :  *    from the subpaths list, and to be in order of decreasing cost.
    2232             :  */
    2233             : static Cost
    2234       26122 : append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
    2235             : {
    2236             :     Cost       *costarr;
    2237             :     int         arrlen;
    2238             :     ListCell   *l;
    2239             :     ListCell   *cell;
    2240             :     int         path_index;
    2241             :     int         min_index;
    2242             :     int         max_index;
    2243             : 
    2244       26122 :     if (numpaths == 0)
    2245       21072 :         return 0;
    2246             : 
    2247             :     /*
    2248             :      * Array length is number of workers or number of relevant paths,
    2249             :      * whichever is less.
    2250             :      */
    2251        5050 :     arrlen = Min(parallel_workers, numpaths);
    2252        5050 :     costarr = palloc_array(Cost, arrlen);
    2253             : 
    2254             :     /* The first few paths will each be claimed by a different worker. */
    2255        5050 :     path_index = 0;
    2256       14676 :     foreach(cell, subpaths)
    2257             :     {
    2258       10928 :         Path       *subpath = (Path *) lfirst(cell);
    2259             : 
    2260       10928 :         if (path_index == arrlen)
    2261        1302 :             break;
    2262        9626 :         costarr[path_index++] = subpath->total_cost;
    2263             :     }
    2264             : 
    2265             :     /*
    2266             :      * Since subpaths are sorted by decreasing cost, the last one will have
    2267             :      * the minimum cost.
    2268             :      */
    2269        5050 :     min_index = arrlen - 1;
    2270             : 
    2271             :     /*
    2272             :      * For each of the remaining subpaths, add its cost to the array element
    2273             :      * with minimum cost.
    2274             :      */
    2275        9802 :     for_each_cell(l, subpaths, cell)
    2276             :     {
    2277        5298 :         Path       *subpath = (Path *) lfirst(l);
    2278             : 
    2279             :         /* Consider only the non-partial paths */
    2280        5298 :         if (path_index++ == numpaths)
    2281         546 :             break;
    2282             : 
    2283        4752 :         costarr[min_index] += subpath->total_cost;
    2284             : 
    2285             :         /* Update the new min cost array index */
    2286        4752 :         min_index = 0;
    2287       14292 :         for (int i = 0; i < arrlen; i++)
    2288             :         {
    2289        9540 :             if (costarr[i] < costarr[min_index])
    2290        1532 :                 min_index = i;
    2291             :         }
    2292             :     }
    2293             : 
    2294             :     /* Return the highest cost from the array */
    2295        5050 :     max_index = 0;
    2296       14676 :     for (int i = 0; i < arrlen; i++)
    2297             :     {
    2298        9626 :         if (costarr[i] > costarr[max_index])
    2299         418 :             max_index = i;
    2300             :     }
    2301             : 
    2302        5050 :     return costarr[max_index];
    2303             : }
    2304             : 
    2305             : /*
    2306             :  * cost_append
    2307             :  *    Determines and returns the cost of an Append node.
    2308             :  */
    2309             : void
    2310       70896 : cost_append(AppendPath *apath, PlannerInfo *root)
    2311             : {
    2312       70896 :     RelOptInfo *rel = apath->path.parent;
    2313             :     ListCell   *l;
    2314       70896 :     uint64      enable_mask = PGS_APPEND;
    2315             : 
    2316       70896 :     if (apath->path.parallel_workers == 0)
    2317       44726 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    2318             : 
    2319       70896 :     apath->path.disabled_nodes =
    2320       70896 :         (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
    2321       70896 :     apath->path.startup_cost = 0;
    2322       70896 :     apath->path.total_cost = 0;
    2323       70896 :     apath->path.rows = 0;
    2324             : 
    2325       70896 :     if (apath->subpaths == NIL)
    2326        2084 :         return;
    2327             : 
    2328       68812 :     if (!apath->path.parallel_aware)
    2329             :     {
    2330       42690 :         List       *pathkeys = apath->path.pathkeys;
    2331             : 
    2332       42690 :         if (pathkeys == NIL)
    2333             :         {
    2334       40546 :             Path       *firstsubpath = (Path *) linitial(apath->subpaths);
    2335             : 
    2336             :             /*
    2337             :              * For an unordered, non-parallel-aware Append we take the startup
    2338             :              * cost as the startup cost of the first subpath.
    2339             :              */
    2340       40546 :             apath->path.startup_cost = firstsubpath->startup_cost;
    2341             : 
    2342             :             /*
    2343             :              * Compute rows, number of disabled nodes, and total cost as sums
    2344             :              * of underlying subplan values.
    2345             :              */
    2346      158666 :             foreach(l, apath->subpaths)
    2347             :             {
    2348      118120 :                 Path       *subpath = (Path *) lfirst(l);
    2349             : 
    2350      118120 :                 apath->path.rows += subpath->rows;
    2351      118120 :                 apath->path.disabled_nodes += subpath->disabled_nodes;
    2352      118120 :                 apath->path.total_cost += subpath->total_cost;
    2353             :             }
    2354             :         }
    2355             :         else
    2356             :         {
    2357             :             /*
    2358             :              * For an ordered, non-parallel-aware Append we take the startup
    2359             :              * cost as the sum of the subpath startup costs.  This ensures
    2360             :              * that we don't underestimate the startup cost when a query's
    2361             :              * LIMIT is such that several of the children have to be run to
    2362             :              * satisfy it.  This might be overkill --- another plausible hack
    2363             :              * would be to take the Append's startup cost as the maximum of
    2364             :              * the child startup costs.  But we don't want to risk believing
    2365             :              * that an ORDER BY LIMIT query can be satisfied at small cost
    2366             :              * when the first child has small startup cost but later ones
    2367             :              * don't.  (If we had the ability to deal with nonlinear cost
    2368             :              * interpolation for partial retrievals, we would not need to be
    2369             :              * so conservative about this.)
    2370             :              *
    2371             :              * This case is also different from the above in that we have to
    2372             :              * account for possibly injecting sorts into subpaths that aren't
    2373             :              * natively ordered.
    2374             :              */
    2375        8340 :             foreach(l, apath->subpaths)
    2376             :             {
    2377        6196 :                 Path       *subpath = (Path *) lfirst(l);
    2378             :                 int         presorted_keys;
    2379             :                 Path        sort_path;  /* dummy for result of
    2380             :                                          * cost_sort/cost_incremental_sort */
    2381             : 
    2382        6196 :                 if (!pathkeys_count_contained_in(pathkeys, subpath->pathkeys,
    2383             :                                                  &presorted_keys))
    2384             :                 {
    2385             :                     /*
    2386             :                      * We'll need to insert a Sort node, so include costs for
    2387             :                      * that.  We choose to use incremental sort if it is
    2388             :                      * enabled and there are presorted keys; otherwise we use
    2389             :                      * full sort.
    2390             :                      *
    2391             :                      * We can use the parent's LIMIT if any, since we
    2392             :                      * certainly won't pull more than that many tuples from
    2393             :                      * any child.
    2394             :                      */
    2395          44 :                     if (enable_incremental_sort && presorted_keys > 0)
    2396             :                     {
    2397          12 :                         cost_incremental_sort(&sort_path,
    2398             :                                               root,
    2399             :                                               pathkeys,
    2400             :                                               presorted_keys,
    2401             :                                               subpath->disabled_nodes,
    2402             :                                               subpath->startup_cost,
    2403             :                                               subpath->total_cost,
    2404             :                                               subpath->rows,
    2405          12 :                                               subpath->pathtarget->width,
    2406             :                                               0.0,
    2407             :                                               work_mem,
    2408             :                                               apath->limit_tuples);
    2409             :                     }
    2410             :                     else
    2411             :                     {
    2412          32 :                         cost_sort(&sort_path,
    2413             :                                   root,
    2414             :                                   pathkeys,
    2415             :                                   subpath->disabled_nodes,
    2416             :                                   subpath->total_cost,
    2417             :                                   subpath->rows,
    2418          32 :                                   subpath->pathtarget->width,
    2419             :                                   0.0,
    2420             :                                   work_mem,
    2421             :                                   apath->limit_tuples);
    2422             :                     }
    2423             : 
    2424          44 :                     subpath = &sort_path;
    2425             :                 }
    2426             : 
    2427        6196 :                 apath->path.rows += subpath->rows;
    2428        6196 :                 apath->path.disabled_nodes += subpath->disabled_nodes;
    2429        6196 :                 apath->path.startup_cost += subpath->startup_cost;
    2430        6196 :                 apath->path.total_cost += subpath->total_cost;
    2431             :             }
    2432             :         }
    2433             :     }
    2434             :     else                        /* parallel-aware */
    2435             :     {
    2436       26122 :         int         i = 0;
    2437       26122 :         double      parallel_divisor = get_parallel_divisor(&apath->path);
    2438             : 
    2439             :         /* Parallel-aware Append never produces ordered output. */
    2440             :         Assert(apath->path.pathkeys == NIL);
    2441             : 
    2442             :         /* Calculate startup cost. */
    2443      103542 :         foreach(l, apath->subpaths)
    2444             :         {
    2445       77420 :             Path       *subpath = (Path *) lfirst(l);
    2446             : 
    2447             :             /*
    2448             :              * Append will start returning tuples when the child node having
    2449             :              * lowest startup cost is done setting up. We consider only the
    2450             :              * first few subplans that immediately get a worker assigned.
    2451             :              */
    2452       77420 :             if (i == 0)
    2453       26122 :                 apath->path.startup_cost = subpath->startup_cost;
    2454       51298 :             else if (i < apath->path.parallel_workers)
    2455       25546 :                 apath->path.startup_cost = Min(apath->path.startup_cost,
    2456             :                                                subpath->startup_cost);
    2457             : 
    2458             :             /*
    2459             :              * Apply parallel divisor to subpaths.  Scale the number of rows
    2460             :              * for each partial subpath based on the ratio of the parallel
    2461             :              * divisor originally used for the subpath to the one we adopted.
    2462             :              * Also add the cost of partial paths to the total cost, but
    2463             :              * ignore non-partial paths for now.
    2464             :              */
    2465       77420 :             if (i < apath->first_partial_path)
    2466       14378 :                 apath->path.rows += subpath->rows / parallel_divisor;
    2467             :             else
    2468             :             {
    2469             :                 double      subpath_parallel_divisor;
    2470             : 
    2471       63042 :                 subpath_parallel_divisor = get_parallel_divisor(subpath);
    2472       63042 :                 apath->path.rows += subpath->rows * (subpath_parallel_divisor /
    2473             :                                                      parallel_divisor);
    2474       63042 :                 apath->path.total_cost += subpath->total_cost;
    2475             :             }
    2476             : 
    2477       77420 :             apath->path.disabled_nodes += subpath->disabled_nodes;
    2478       77420 :             apath->path.rows = clamp_row_est(apath->path.rows);
    2479             : 
    2480       77420 :             i++;
    2481             :         }
    2482             : 
    2483             :         /* Add cost for non-partial subpaths. */
    2484       26122 :         apath->path.total_cost +=
    2485       26122 :             append_nonpartial_cost(apath->subpaths,
    2486             :                                    apath->first_partial_path,
    2487             :                                    apath->path.parallel_workers);
    2488             :     }
    2489             : 
    2490             :     /*
    2491             :      * Although Append does not do any selection or projection, it's not free;
    2492             :      * add a small per-tuple overhead.
    2493             :      */
    2494       68812 :     apath->path.total_cost +=
    2495       68812 :         cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * apath->path.rows;
    2496             : }
    2497             : 
    2498             : /*
    2499             :  * cost_merge_append
    2500             :  *    Determines and returns the cost of a MergeAppend node.
    2501             :  *
    2502             :  * MergeAppend merges several pre-sorted input streams, using a heap that
    2503             :  * at any given instant holds the next tuple from each stream.  If there
    2504             :  * are N streams, we need about N*log2(N) tuple comparisons to construct
    2505             :  * the heap at startup, and then for each output tuple, about log2(N)
    2506             :  * comparisons to replace the top entry.
    2507             :  *
    2508             :  * (The effective value of N will drop once some of the input streams are
    2509             :  * exhausted, but it seems unlikely to be worth trying to account for that.)
    2510             :  *
    2511             :  * The heap is never spilled to disk, since we assume N is not very large.
    2512             :  * So this is much simpler than cost_sort.
    2513             :  *
    2514             :  * As in cost_sort, we charge two operator evals per tuple comparison.
    2515             :  *
    2516             :  * 'pathkeys' is a list of sort keys
    2517             :  * 'n_streams' is the number of input streams
    2518             :  * 'input_disabled_nodes' is the sum of the input streams' disabled node counts
    2519             :  * 'input_startup_cost' is the sum of the input streams' startup costs
    2520             :  * 'input_total_cost' is the sum of the input streams' total costs
    2521             :  * 'tuples' is the number of tuples in all the streams
    2522             :  */
    2523             : void
    2524        9900 : cost_merge_append(Path *path, PlannerInfo *root,
    2525             :                   List *pathkeys, int n_streams,
    2526             :                   int input_disabled_nodes,
    2527             :                   Cost input_startup_cost, Cost input_total_cost,
    2528             :                   double tuples)
    2529             : {
    2530        9900 :     RelOptInfo *rel = path->parent;
    2531        9900 :     Cost        startup_cost = 0;
    2532        9900 :     Cost        run_cost = 0;
    2533             :     Cost        comparison_cost;
    2534             :     double      N;
    2535             :     double      logN;
    2536        9900 :     uint64      enable_mask = PGS_MERGE_APPEND;
    2537             : 
    2538        9900 :     if (path->parallel_workers == 0)
    2539        9900 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    2540             : 
    2541             :     /*
    2542             :      * Avoid log(0)...
    2543             :      */
    2544        9900 :     N = (n_streams < 2) ? 2.0 : (double) n_streams;
    2545        9900 :     logN = LOG2(N);
    2546             : 
    2547             :     /* Assumed cost per tuple comparison */
    2548        9900 :     comparison_cost = 2.0 * cpu_operator_cost;
    2549             : 
    2550             :     /* Heap creation cost */
    2551        9900 :     startup_cost += comparison_cost * N * logN;
    2552             : 
    2553             :     /* Per-tuple heap maintenance cost */
    2554        9900 :     run_cost += tuples * comparison_cost * logN;
    2555             : 
    2556             :     /*
    2557             :      * Although MergeAppend does not do any selection or projection, it's not
    2558             :      * free; add a small per-tuple overhead.
    2559             :      */
    2560        9900 :     run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
    2561             : 
    2562        9900 :     path->disabled_nodes =
    2563        9900 :         (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
    2564        9900 :     path->disabled_nodes += input_disabled_nodes;
    2565        9900 :     path->startup_cost = startup_cost + input_startup_cost;
    2566        9900 :     path->total_cost = startup_cost + run_cost + input_total_cost;
    2567        9900 : }
    2568             : 
    2569             : /*
    2570             :  * cost_material
    2571             :  *    Determines and returns the cost of materializing a relation, including
    2572             :  *    the cost of reading the input data.
    2573             :  *
    2574             :  * If the total volume of data to materialize exceeds work_mem, we will need
    2575             :  * to write it to disk, so the cost is much higher in that case.
    2576             :  *
    2577             :  * Note that here we are estimating the costs for the first scan of the
    2578             :  * relation, so the materialization is all overhead --- any savings will
    2579             :  * occur only on rescan, which is estimated in cost_rescan.
    2580             :  */
    2581             : void
    2582      694176 : cost_material(Path *path,
    2583             :               bool enabled, int input_disabled_nodes,
    2584             :               Cost input_startup_cost, Cost input_total_cost,
    2585             :               double tuples, int width)
    2586             : {
    2587      694176 :     Cost        startup_cost = input_startup_cost;
    2588      694176 :     Cost        run_cost = input_total_cost - input_startup_cost;
    2589      694176 :     double      nbytes = relation_byte_size(tuples, width);
    2590      694176 :     double      work_mem_bytes = work_mem * (Size) 1024;
    2591             : 
    2592      694176 :     if (path->parallel_workers == 0 &&
    2593      694176 :         path->parent != NULL &&
    2594      694102 :         (path->parent->pgs_mask & PGS_CONSIDER_NONPARTIAL) == 0)
    2595           0 :         enabled = false;
    2596             : 
    2597      694176 :     path->rows = tuples;
    2598             : 
    2599             :     /*
    2600             :      * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
    2601             :      * reflect bookkeeping overhead.  (This rate must be more than what
    2602             :      * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
    2603             :      * if it is exactly the same then there will be a cost tie between
    2604             :      * nestloop with A outer, materialized B inner and nestloop with B outer,
    2605             :      * materialized A inner.  The extra cost ensures we'll prefer
    2606             :      * materializing the smaller rel.)  Note that this is normally a good deal
    2607             :      * less than cpu_tuple_cost; which is OK because a Material plan node
    2608             :      * doesn't do qual-checking or projection, so it's got less overhead than
    2609             :      * most plan nodes.
    2610             :      */
    2611      694176 :     run_cost += 2 * cpu_operator_cost * tuples;
    2612             : 
    2613             :     /*
    2614             :      * If we will spill to disk, charge at the rate of seq_page_cost per page.
    2615             :      * This cost is assumed to be evenly spread through the plan run phase,
    2616             :      * which isn't exactly accurate but our cost model doesn't allow for
    2617             :      * nonuniform costs within the run phase.
    2618             :      */
    2619      694176 :     if (nbytes > work_mem_bytes)
    2620             :     {
    2621        5082 :         double      npages = ceil(nbytes / BLCKSZ);
    2622             : 
    2623        5082 :         run_cost += seq_page_cost * npages;
    2624             :     }
    2625             : 
    2626      694176 :     path->disabled_nodes = input_disabled_nodes + (enabled ? 0 : 1);
    2627      694176 :     path->startup_cost = startup_cost;
    2628      694176 :     path->total_cost = startup_cost + run_cost;
    2629      694176 : }
    2630             : 
    2631             : /*
    2632             :  * cost_memoize_rescan
    2633             :  *    Determines the estimated cost of rescanning a Memoize node.
    2634             :  *
    2635             :  * In order to estimate this, we must gain knowledge of how often we expect to
    2636             :  * be called and how many distinct sets of parameters we are likely to be
    2637             :  * called with. If we expect a good cache hit ratio, then we can set our
    2638             :  * costs to account for that hit ratio, plus a little bit of cost for the
    2639             :  * caching itself.  Caching will not work out well if we expect to be called
    2640             :  * with too many distinct parameter values.  The worst-case here is that we
    2641             :  * never see any parameter value twice, in which case we'd never get a cache
    2642             :  * hit and caching would be a complete waste of effort.
    2643             :  */
    2644             : static void
    2645      297590 : cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath,
    2646             :                     Cost *rescan_startup_cost, Cost *rescan_total_cost)
    2647             : {
    2648             :     EstimationInfo estinfo;
    2649             :     ListCell   *lc;
    2650      297590 :     Cost        input_startup_cost = mpath->subpath->startup_cost;
    2651      297590 :     Cost        input_total_cost = mpath->subpath->total_cost;
    2652      297590 :     double      tuples = mpath->subpath->rows;
    2653      297590 :     Cardinality est_calls = mpath->est_calls;
    2654      297590 :     int         width = mpath->subpath->pathtarget->width;
    2655             : 
    2656             :     double      hash_mem_bytes;
    2657             :     double      est_entry_bytes;
    2658             :     Cardinality est_cache_entries;
    2659             :     Cardinality ndistinct;
    2660             :     double      evict_ratio;
    2661             :     double      hit_ratio;
    2662             :     Cost        startup_cost;
    2663             :     Cost        total_cost;
    2664             : 
    2665             :     /* available cache space */
    2666      297590 :     hash_mem_bytes = get_hash_memory_limit();
    2667             : 
    2668             :     /*
    2669             :      * Set the number of bytes each cache entry should consume in the cache.
    2670             :      * To provide us with better estimations on how many cache entries we can
    2671             :      * store at once, we make a call to the executor here to ask it what
    2672             :      * memory overheads there are for a single cache entry.
    2673             :      */
    2674      297590 :     est_entry_bytes = relation_byte_size(tuples, width) +
    2675      297590 :         ExecEstimateCacheEntryOverheadBytes(tuples);
    2676             : 
    2677             :     /* include the estimated width for the cache keys */
    2678      633854 :     foreach(lc, mpath->param_exprs)
    2679      336264 :         est_entry_bytes += get_expr_width(root, (Node *) lfirst(lc));
    2680             : 
    2681             :     /* estimate on the upper limit of cache entries we can hold at once */
    2682      297590 :     est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
    2683             : 
    2684             :     /* estimate on the distinct number of parameter values */
    2685      297590 :     ndistinct = estimate_num_groups(root, mpath->param_exprs, est_calls, NULL,
    2686             :                                     &estinfo);
    2687             : 
    2688             :     /*
    2689             :      * When the estimation fell back on using a default value, it's a bit too
    2690             :      * risky to assume that it's ok to use a Memoize node.  The use of a
    2691             :      * default could cause us to use a Memoize node when it's really
    2692             :      * inappropriate to do so.  If we see that this has been done, then we'll
    2693             :      * assume that every call will have unique parameters, which will almost
    2694             :      * certainly mean a MemoizePath will never survive add_path().
    2695             :      */
    2696      297590 :     if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
    2697       17398 :         ndistinct = est_calls;
    2698             : 
    2699             :     /* Remember the ndistinct estimate for EXPLAIN */
    2700      297590 :     mpath->est_unique_keys = ndistinct;
    2701             : 
    2702             :     /*
    2703             :      * Since we've already estimated the maximum number of entries we can
    2704             :      * store at once and know the estimated number of distinct values we'll be
    2705             :      * called with, we'll take this opportunity to set the path's est_entries.
    2706             :      * This will ultimately determine the hash table size that the executor
    2707             :      * will use.  If we leave this at zero, the executor will just choose the
    2708             :      * size itself.  Really this is not the right place to do this, but it's
    2709             :      * convenient since everything is already calculated.
    2710             :      */
    2711      297590 :     mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
    2712             :                              PG_UINT32_MAX);
    2713             : 
    2714             :     /*
    2715             :      * When the number of distinct parameter values is above the amount we can
    2716             :      * store in the cache, then we'll have to evict some entries from the
    2717             :      * cache.  This is not free. Here we estimate how often we'll incur the
    2718             :      * cost of that eviction.
    2719             :      */
    2720      297590 :     evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
    2721             : 
    2722             :     /*
    2723             :      * In order to estimate how costly a single scan will be, we need to
    2724             :      * attempt to estimate what the cache hit ratio will be.  To do that we
    2725             :      * must look at how many scans are estimated in total for this node and
    2726             :      * how many of those scans we expect to get a cache hit.
    2727             :      */
    2728      595180 :     hit_ratio = ((est_calls - ndistinct) / est_calls) *
    2729      297590 :         (est_cache_entries / Max(ndistinct, est_cache_entries));
    2730             : 
    2731             :     /* Remember the hit ratio estimate for EXPLAIN */
    2732      297590 :     mpath->est_hit_ratio = hit_ratio;
    2733             : 
    2734             :     Assert(hit_ratio >= 0 && hit_ratio <= 1.0);
    2735             : 
    2736             :     /*
    2737             :      * Set the total_cost accounting for the expected cache hit ratio.  We
    2738             :      * also add on a cpu_operator_cost to account for a cache lookup. This
    2739             :      * will happen regardless of whether it's a cache hit or not.
    2740             :      */
    2741      297590 :     total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
    2742             : 
    2743             :     /* Now adjust the total cost to account for cache evictions */
    2744             : 
    2745             :     /* Charge a cpu_tuple_cost for evicting the actual cache entry */
    2746      297590 :     total_cost += cpu_tuple_cost * evict_ratio;
    2747             : 
    2748             :     /*
    2749             :      * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
    2750             :      * The per-tuple eviction is really just a pfree, so charging a whole
    2751             :      * cpu_operator_cost seems a little excessive.
    2752             :      */
    2753      297590 :     total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
    2754             : 
    2755             :     /*
    2756             :      * Now adjust for storing things in the cache, since that's not free
    2757             :      * either.  Everything must go in the cache.  We don't proportion this
    2758             :      * over any ratio, just apply it once for the scan.  We charge a
    2759             :      * cpu_tuple_cost for the creation of the cache entry and also a
    2760             :      * cpu_operator_cost for each tuple we expect to cache.
    2761             :      */
    2762      297590 :     total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
    2763             : 
    2764             :     /*
    2765             :      * Getting the first row must be also be proportioned according to the
    2766             :      * expected cache hit ratio.
    2767             :      */
    2768      297590 :     startup_cost = input_startup_cost * (1.0 - hit_ratio);
    2769             : 
    2770             :     /*
    2771             :      * Additionally we charge a cpu_tuple_cost to account for cache lookups,
    2772             :      * which we'll do regardless of whether it was a cache hit or not.
    2773             :      */
    2774      297590 :     startup_cost += cpu_tuple_cost;
    2775             : 
    2776      297590 :     *rescan_startup_cost = startup_cost;
    2777      297590 :     *rescan_total_cost = total_cost;
    2778      297590 : }
    2779             : 
    2780             : /*
    2781             :  * cost_agg
    2782             :  *      Determines and returns the cost of performing an Agg plan node,
    2783             :  *      including the cost of its input.
    2784             :  *
    2785             :  * aggcosts can be NULL when there are no actual aggregate functions (i.e.,
    2786             :  * we are using a hashed Agg node just to do grouping).
    2787             :  *
    2788             :  * Note: when aggstrategy == AGG_SORTED, caller must ensure that input costs
    2789             :  * are for appropriately-sorted input.
    2790             :  */
    2791             : void
    2792       95282 : cost_agg(Path *path, PlannerInfo *root,
    2793             :          AggStrategy aggstrategy, const AggClauseCosts *aggcosts,
    2794             :          int numGroupCols, double numGroups,
    2795             :          List *quals,
    2796             :          int disabled_nodes,
    2797             :          Cost input_startup_cost, Cost input_total_cost,
    2798             :          double input_tuples, double input_width)
    2799             : {
    2800             :     double      output_tuples;
    2801             :     Cost        startup_cost;
    2802             :     Cost        total_cost;
    2803       95282 :     const AggClauseCosts dummy_aggcosts = {0};
    2804             : 
    2805             :     /* Use all-zero per-aggregate costs if NULL is passed */
    2806       95282 :     if (aggcosts == NULL)
    2807             :     {
    2808             :         Assert(aggstrategy == AGG_HASHED);
    2809       19244 :         aggcosts = &dummy_aggcosts;
    2810             :     }
    2811             : 
    2812             :     /*
    2813             :      * The transCost.per_tuple component of aggcosts should be charged once
    2814             :      * per input tuple, corresponding to the costs of evaluating the aggregate
    2815             :      * transfns and their input expressions. The finalCost.per_tuple component
    2816             :      * is charged once per output tuple, corresponding to the costs of
    2817             :      * evaluating the finalfns.  Startup costs are of course charged but once.
    2818             :      *
    2819             :      * If we are grouping, we charge an additional cpu_operator_cost per
    2820             :      * grouping column per input tuple for grouping comparisons.
    2821             :      *
    2822             :      * We will produce a single output tuple if not grouping, and a tuple per
    2823             :      * group otherwise.  We charge cpu_tuple_cost for each output tuple.
    2824             :      *
    2825             :      * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
    2826             :      * same total CPU cost, but AGG_SORTED has lower startup cost.  If the
    2827             :      * input path is already sorted appropriately, AGG_SORTED should be
    2828             :      * preferred (since it has no risk of memory overflow).  This will happen
    2829             :      * as long as the computed total costs are indeed exactly equal --- but if
    2830             :      * there's roundoff error we might do the wrong thing.  So be sure that
    2831             :      * the computations below form the same intermediate values in the same
    2832             :      * order.
    2833             :      */
    2834       95282 :     if (aggstrategy == AGG_PLAIN)
    2835             :     {
    2836       44980 :         startup_cost = input_total_cost;
    2837       44980 :         startup_cost += aggcosts->transCost.startup;
    2838       44980 :         startup_cost += aggcosts->transCost.per_tuple * input_tuples;
    2839       44980 :         startup_cost += aggcosts->finalCost.startup;
    2840       44980 :         startup_cost += aggcosts->finalCost.per_tuple;
    2841             :         /* we aren't grouping */
    2842       44980 :         total_cost = startup_cost + cpu_tuple_cost;
    2843       44980 :         output_tuples = 1;
    2844             :     }
    2845       50302 :     else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
    2846             :     {
    2847             :         /* Here we are able to deliver output on-the-fly */
    2848       18364 :         startup_cost = input_startup_cost;
    2849       18364 :         total_cost = input_total_cost;
    2850       18364 :         if (aggstrategy == AGG_MIXED && !enable_hashagg)
    2851         540 :             ++disabled_nodes;
    2852             :         /* calcs phrased this way to match HASHED case, see note above */
    2853       18364 :         total_cost += aggcosts->transCost.startup;
    2854       18364 :         total_cost += aggcosts->transCost.per_tuple * input_tuples;
    2855       18364 :         total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
    2856       18364 :         total_cost += aggcosts->finalCost.startup;
    2857       18364 :         total_cost += aggcosts->finalCost.per_tuple * numGroups;
    2858       18364 :         total_cost += cpu_tuple_cost * numGroups;
    2859       18364 :         output_tuples = numGroups;
    2860             :     }
    2861             :     else
    2862             :     {
    2863             :         /* must be AGG_HASHED */
    2864       31938 :         startup_cost = input_total_cost;
    2865       31938 :         if (!enable_hashagg)
    2866        1890 :             ++disabled_nodes;
    2867       31938 :         startup_cost += aggcosts->transCost.startup;
    2868       31938 :         startup_cost += aggcosts->transCost.per_tuple * input_tuples;
    2869             :         /* cost of computing hash value */
    2870       31938 :         startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
    2871       31938 :         startup_cost += aggcosts->finalCost.startup;
    2872             : 
    2873       31938 :         total_cost = startup_cost;
    2874       31938 :         total_cost += aggcosts->finalCost.per_tuple * numGroups;
    2875             :         /* cost of retrieving from hash table */
    2876       31938 :         total_cost += cpu_tuple_cost * numGroups;
    2877       31938 :         output_tuples = numGroups;
    2878             :     }
    2879             : 
    2880             :     /*
    2881             :      * Add the disk costs of hash aggregation that spills to disk.
    2882             :      *
    2883             :      * Groups that go into the hash table stay in memory until finalized, so
    2884             :      * spilling and reprocessing tuples doesn't incur additional invocations
    2885             :      * of transCost or finalCost. Furthermore, the computed hash value is
    2886             :      * stored with the spilled tuples, so we don't incur extra invocations of
    2887             :      * the hash function.
    2888             :      *
    2889             :      * Hash Agg begins returning tuples after the first batch is complete.
    2890             :      * Accrue writes (spilled tuples) to startup_cost and to total_cost;
    2891             :      * accrue reads only to total_cost.
    2892             :      */
    2893       95282 :     if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
    2894             :     {
    2895             :         double      pages;
    2896       32972 :         double      pages_written = 0.0;
    2897       32972 :         double      pages_read = 0.0;
    2898             :         double      spill_cost;
    2899             :         double      hashentrysize;
    2900             :         double      nbatches;
    2901             :         Size        mem_limit;
    2902             :         uint64      ngroups_limit;
    2903             :         int         num_partitions;
    2904             :         int         depth;
    2905             : 
    2906             :         /*
    2907             :          * Estimate number of batches based on the computed limits. If less
    2908             :          * than or equal to one, all groups are expected to fit in memory;
    2909             :          * otherwise we expect to spill.
    2910             :          */
    2911       32972 :         hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
    2912             :                                             input_width,
    2913       32972 :                                             aggcosts->transitionSpace);
    2914       32972 :         hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
    2915             :                             &ngroups_limit, &num_partitions);
    2916             : 
    2917       32972 :         nbatches = Max((numGroups * hashentrysize) / mem_limit,
    2918             :                        numGroups / ngroups_limit);
    2919             : 
    2920       32972 :         nbatches = Max(ceil(nbatches), 1.0);
    2921       32972 :         num_partitions = Max(num_partitions, 2);
    2922             : 
    2923             :         /*
    2924             :          * The number of partitions can change at different levels of
    2925             :          * recursion; but for the purposes of this calculation assume it stays
    2926             :          * constant.
    2927             :          */
    2928       32972 :         depth = ceil(log(nbatches) / log(num_partitions));
    2929             : 
    2930             :         /*
    2931             :          * Estimate number of pages read and written. For each level of
    2932             :          * recursion, a tuple must be written and then later read.
    2933             :          */
    2934       32972 :         pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
    2935       32972 :         pages_written = pages_read = pages * depth;
    2936             : 
    2937             :         /*
    2938             :          * HashAgg has somewhat worse IO behavior than Sort on typical
    2939             :          * hardware/OS combinations. Account for this with a generic penalty.
    2940             :          */
    2941       32972 :         pages_read *= 2.0;
    2942       32972 :         pages_written *= 2.0;
    2943             : 
    2944       32972 :         startup_cost += pages_written * random_page_cost;
    2945       32972 :         total_cost += pages_written * random_page_cost;
    2946       32972 :         total_cost += pages_read * seq_page_cost;
    2947             : 
    2948             :         /* account for CPU cost of spilling a tuple and reading it back */
    2949       32972 :         spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
    2950       32972 :         startup_cost += spill_cost;
    2951       32972 :         total_cost += spill_cost;
    2952             :     }
    2953             : 
    2954             :     /*
    2955             :      * If there are quals (HAVING quals), account for their cost and
    2956             :      * selectivity.
    2957             :      */
    2958       95282 :     if (quals)
    2959             :     {
    2960             :         QualCost    qual_cost;
    2961             : 
    2962        4658 :         cost_qual_eval(&qual_cost, quals, root);
    2963        4658 :         startup_cost += qual_cost.startup;
    2964        4658 :         total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
    2965             : 
    2966        4658 :         output_tuples = clamp_row_est(output_tuples *
    2967        4658 :                                       clauselist_selectivity(root,
    2968             :                                                              quals,
    2969             :                                                              0,
    2970             :                                                              JOIN_INNER,
    2971             :                                                              NULL));
    2972             :     }
    2973             : 
    2974       95282 :     path->rows = output_tuples;
    2975       95282 :     path->disabled_nodes = disabled_nodes;
    2976       95282 :     path->startup_cost = startup_cost;
    2977       95282 :     path->total_cost = total_cost;
    2978       95282 : }
    2979             : 
    2980             : /*
    2981             :  * get_windowclause_startup_tuples
    2982             :  *      Estimate how many tuples we'll need to fetch from a WindowAgg's
    2983             :  *      subnode before we can output the first WindowAgg tuple.
    2984             :  *
    2985             :  * How many tuples need to be read depends on the WindowClause.  For example,
    2986             :  * a WindowClause with no PARTITION BY and no ORDER BY requires that all
    2987             :  * subnode tuples are read and aggregated before the WindowAgg can output
    2988             :  * anything.  If there's a PARTITION BY, then we only need to look at tuples
    2989             :  * in the first partition.  Here we attempt to estimate just how many
    2990             :  * 'input_tuples' the WindowAgg will need to read for the given WindowClause
    2991             :  * before the first tuple can be output.
    2992             :  */
    2993             : static double
    2994        2976 : get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc,
    2995             :                                 double input_tuples)
    2996             : {
    2997        2976 :     int         frameOptions = wc->frameOptions;
    2998             :     double      partition_tuples;
    2999             :     double      return_tuples;
    3000             :     double      peer_tuples;
    3001             : 
    3002             :     /*
    3003             :      * First, figure out how many partitions there are likely to be and set
    3004             :      * partition_tuples according to that estimate.
    3005             :      */
    3006        2976 :     if (wc->partitionClause != NIL)
    3007             :     {
    3008             :         double      num_partitions;
    3009         734 :         List       *partexprs = get_sortgrouplist_exprs(wc->partitionClause,
    3010         734 :                                                         root->parse->targetList);
    3011             : 
    3012         734 :         num_partitions = estimate_num_groups(root, partexprs, input_tuples,
    3013             :                                              NULL, NULL);
    3014         734 :         list_free(partexprs);
    3015             : 
    3016         734 :         partition_tuples = input_tuples / num_partitions;
    3017             :     }
    3018             :     else
    3019             :     {
    3020             :         /* all tuples belong to the same partition */
    3021        2242 :         partition_tuples = input_tuples;
    3022             :     }
    3023             : 
    3024             :     /* estimate the number of tuples in each peer group */
    3025        2976 :     if (wc->orderClause != NIL)
    3026             :     {
    3027             :         double      num_groups;
    3028             :         List       *orderexprs;
    3029             : 
    3030        2370 :         orderexprs = get_sortgrouplist_exprs(wc->orderClause,
    3031        2370 :                                              root->parse->targetList);
    3032             : 
    3033             :         /* estimate out how many peer groups there are in the partition */
    3034        2370 :         num_groups = estimate_num_groups(root, orderexprs,
    3035             :                                          partition_tuples, NULL,
    3036             :                                          NULL);
    3037        2370 :         list_free(orderexprs);
    3038        2370 :         peer_tuples = partition_tuples / num_groups;
    3039             :     }
    3040             :     else
    3041             :     {
    3042             :         /* no ORDER BY so only 1 tuple belongs in each peer group */
    3043         606 :         peer_tuples = 1.0;
    3044             :     }
    3045             : 
    3046        2976 :     if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
    3047             :     {
    3048             :         /* include all partition rows */
    3049         364 :         return_tuples = partition_tuples;
    3050             :     }
    3051        2612 :     else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
    3052             :     {
    3053        1574 :         if (frameOptions & FRAMEOPTION_ROWS)
    3054             :         {
    3055             :             /* just count the current row */
    3056         722 :             return_tuples = 1.0;
    3057             :         }
    3058         852 :         else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
    3059             :         {
    3060             :             /*
    3061             :              * When in RANGE/GROUPS mode, it's more complex.  If there's no
    3062             :              * ORDER BY, then all rows in the partition are peers, otherwise
    3063             :              * we'll need to read the first group of peers.
    3064             :              */
    3065         852 :             if (wc->orderClause == NIL)
    3066         326 :                 return_tuples = partition_tuples;
    3067             :             else
    3068         526 :                 return_tuples = peer_tuples;
    3069             :         }
    3070             :         else
    3071             :         {
    3072             :             /*
    3073             :              * Something new we don't support yet?  This needs attention.
    3074             :              * We'll just return 1.0 in the meantime.
    3075             :              */
    3076             :             Assert(false);
    3077           0 :             return_tuples = 1.0;
    3078             :         }
    3079             :     }
    3080        1038 :     else if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
    3081             :     {
    3082             :         /*
    3083             :          * BETWEEN ... AND N PRECEDING will only need to read the WindowAgg's
    3084             :          * subnode after N ROWS/RANGES/GROUPS.  N can be 0, but not negative,
    3085             :          * so we'll just assume only the current row needs to be read to fetch
    3086             :          * the first WindowAgg row.
    3087             :          */
    3088         108 :         return_tuples = 1.0;
    3089             :     }
    3090         930 :     else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
    3091             :     {
    3092         930 :         Const      *endOffset = (Const *) wc->endOffset;
    3093             :         double      end_offset_value;
    3094             : 
    3095             :         /* try and figure out the value specified in the endOffset. */
    3096         930 :         if (IsA(endOffset, Const))
    3097             :         {
    3098         930 :             if (endOffset->constisnull)
    3099             :             {
    3100             :                 /*
    3101             :                  * NULLs are not allowed, but currently, there's no code to
    3102             :                  * error out if there's a NULL Const.  We'll only discover
    3103             :                  * this during execution.  For now, just pretend everything is
    3104             :                  * fine and assume that just the first row/range/group will be
    3105             :                  * needed.
    3106             :                  */
    3107           0 :                 end_offset_value = 1.0;
    3108             :             }
    3109             :             else
    3110             :             {
    3111         930 :                 switch (endOffset->consttype)
    3112             :                 {
    3113          24 :                     case INT2OID:
    3114          24 :                         end_offset_value =
    3115          24 :                             (double) DatumGetInt16(endOffset->constvalue);
    3116          24 :                         break;
    3117         132 :                     case INT4OID:
    3118         132 :                         end_offset_value =
    3119         132 :                             (double) DatumGetInt32(endOffset->constvalue);
    3120         132 :                         break;
    3121         432 :                     case INT8OID:
    3122         432 :                         end_offset_value =
    3123         432 :                             (double) DatumGetInt64(endOffset->constvalue);
    3124         432 :                         break;
    3125         342 :                     default:
    3126         342 :                         end_offset_value =
    3127         342 :                             partition_tuples / peer_tuples *
    3128             :                             DEFAULT_INEQ_SEL;
    3129         342 :                         break;
    3130             :                 }
    3131             :             }
    3132             :         }
    3133             :         else
    3134             :         {
    3135             :             /*
    3136             :              * When the end bound is not a Const, we'll just need to guess. We
    3137             :              * just make use of DEFAULT_INEQ_SEL.
    3138             :              */
    3139           0 :             end_offset_value =
    3140           0 :                 partition_tuples / peer_tuples * DEFAULT_INEQ_SEL;
    3141             :         }
    3142             : 
    3143         930 :         if (frameOptions & FRAMEOPTION_ROWS)
    3144             :         {
    3145             :             /* include the N FOLLOWING and the current row */
    3146         270 :             return_tuples = end_offset_value + 1.0;
    3147             :         }
    3148         660 :         else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
    3149             :         {
    3150             :             /* include N FOLLOWING ranges/group and the initial range/group */
    3151         660 :             return_tuples = peer_tuples * (end_offset_value + 1.0);
    3152             :         }
    3153             :         else
    3154             :         {
    3155             :             /*
    3156             :              * Something new we don't support yet?  This needs attention.
    3157             :              * We'll just return 1.0 in the meantime.
    3158             :              */
    3159             :             Assert(false);
    3160           0 :             return_tuples = 1.0;
    3161             :         }
    3162             :     }
    3163             :     else
    3164             :     {
    3165             :         /*
    3166             :          * Something new we don't support yet?  This needs attention.  We'll
    3167             :          * just return 1.0 in the meantime.
    3168             :          */
    3169             :         Assert(false);
    3170           0 :         return_tuples = 1.0;
    3171             :     }
    3172             : 
    3173        2976 :     if (wc->partitionClause != NIL || wc->orderClause != NIL)
    3174             :     {
    3175             :         /*
    3176             :          * Cap the return value to the estimated partition tuples and account
    3177             :          * for the extra tuple WindowAgg will need to read to confirm the next
    3178             :          * tuple does not belong to the same partition or peer group.
    3179             :          */
    3180        2582 :         return_tuples = Min(return_tuples + 1.0, partition_tuples);
    3181             :     }
    3182             :     else
    3183             :     {
    3184             :         /*
    3185             :          * Cap the return value so it's never higher than the expected tuples
    3186             :          * in the partition.
    3187             :          */
    3188         394 :         return_tuples = Min(return_tuples, partition_tuples);
    3189             :     }
    3190             : 
    3191             :     /*
    3192             :      * We needn't worry about any EXCLUDE options as those only exclude rows
    3193             :      * from being aggregated, not from being read from the WindowAgg's
    3194             :      * subnode.
    3195             :      */
    3196             : 
    3197        2976 :     return clamp_row_est(return_tuples);
    3198             : }
    3199             : 
    3200             : /*
    3201             :  * cost_windowagg
    3202             :  *      Determines and returns the cost of performing a WindowAgg plan node,
    3203             :  *      including the cost of its input.
    3204             :  *
    3205             :  * Input is assumed already properly sorted.
    3206             :  */
    3207             : void
    3208        2976 : cost_windowagg(Path *path, PlannerInfo *root,
    3209             :                List *windowFuncs, WindowClause *winclause,
    3210             :                int input_disabled_nodes,
    3211             :                Cost input_startup_cost, Cost input_total_cost,
    3212             :                double input_tuples)
    3213             : {
    3214             :     Cost        startup_cost;
    3215             :     Cost        total_cost;
    3216             :     double      startup_tuples;
    3217             :     int         numPartCols;
    3218             :     int         numOrderCols;
    3219             :     ListCell   *lc;
    3220             : 
    3221        2976 :     numPartCols = list_length(winclause->partitionClause);
    3222        2976 :     numOrderCols = list_length(winclause->orderClause);
    3223             : 
    3224        2976 :     startup_cost = input_startup_cost;
    3225        2976 :     total_cost = input_total_cost;
    3226             : 
    3227             :     /*
    3228             :      * Window functions are assumed to cost their stated execution cost, plus
    3229             :      * the cost of evaluating their input expressions, per tuple.  Since they
    3230             :      * may in fact evaluate their inputs at multiple rows during each cycle,
    3231             :      * this could be a drastic underestimate; but without a way to know how
    3232             :      * many rows the window function will fetch, it's hard to do better.  In
    3233             :      * any case, it's a good estimate for all the built-in window functions,
    3234             :      * so we'll just do this for now.
    3235             :      */
    3236        6834 :     foreach(lc, windowFuncs)
    3237             :     {
    3238        3858 :         WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
    3239             :         Cost        wfunccost;
    3240             :         QualCost    argcosts;
    3241             : 
    3242        3858 :         argcosts.startup = argcosts.per_tuple = 0;
    3243        3858 :         add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
    3244             :                           &argcosts);
    3245        3858 :         startup_cost += argcosts.startup;
    3246        3858 :         wfunccost = argcosts.per_tuple;
    3247             : 
    3248             :         /* also add the input expressions' cost to per-input-row costs */
    3249        3858 :         cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
    3250        3858 :         startup_cost += argcosts.startup;
    3251        3858 :         wfunccost += argcosts.per_tuple;
    3252             : 
    3253             :         /*
    3254             :          * Add the filter's cost to per-input-row costs.  XXX We should reduce
    3255             :          * input expression costs according to filter selectivity.
    3256             :          */
    3257        3858 :         cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
    3258        3858 :         startup_cost += argcosts.startup;
    3259        3858 :         wfunccost += argcosts.per_tuple;
    3260             : 
    3261        3858 :         total_cost += wfunccost * input_tuples;
    3262             :     }
    3263             : 
    3264             :     /*
    3265             :      * We also charge cpu_operator_cost per grouping column per tuple for
    3266             :      * grouping comparisons, plus cpu_tuple_cost per tuple for general
    3267             :      * overhead.
    3268             :      *
    3269             :      * XXX this neglects costs of spooling the data to disk when it overflows
    3270             :      * work_mem.  Sooner or later that should get accounted for.
    3271             :      */
    3272        2976 :     total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
    3273        2976 :     total_cost += cpu_tuple_cost * input_tuples;
    3274             : 
    3275        2976 :     path->rows = input_tuples;
    3276        2976 :     path->disabled_nodes = input_disabled_nodes;
    3277        2976 :     path->startup_cost = startup_cost;
    3278        2976 :     path->total_cost = total_cost;
    3279             : 
    3280             :     /*
    3281             :      * Also, take into account how many tuples we need to read from the
    3282             :      * subnode in order to produce the first tuple from the WindowAgg.  To do
    3283             :      * this we proportion the run cost (total cost not including startup cost)
    3284             :      * over the estimated startup tuples.  We already included the startup
    3285             :      * cost of the subnode, so we only need to do this when the estimated
    3286             :      * startup tuples is above 1.0.
    3287             :      */
    3288        2976 :     startup_tuples = get_windowclause_startup_tuples(root, winclause,
    3289             :                                                      input_tuples);
    3290             : 
    3291        2976 :     if (startup_tuples > 1.0)
    3292        2568 :         path->startup_cost += (total_cost - startup_cost) / input_tuples *
    3293        2568 :             (startup_tuples - 1.0);
    3294        2976 : }
    3295             : 
    3296             : /*
    3297             :  * cost_group
    3298             :  *      Determines and returns the cost of performing a Group plan node,
    3299             :  *      including the cost of its input.
    3300             :  *
    3301             :  * Note: caller must ensure that input costs are for appropriately-sorted
    3302             :  * input.
    3303             :  */
    3304             : void
    3305        1226 : cost_group(Path *path, PlannerInfo *root,
    3306             :            int numGroupCols, double numGroups,
    3307             :            List *quals,
    3308             :            int input_disabled_nodes,
    3309             :            Cost input_startup_cost, Cost input_total_cost,
    3310             :            double input_tuples)
    3311             : {
    3312             :     double      output_tuples;
    3313             :     Cost        startup_cost;
    3314             :     Cost        total_cost;
    3315             : 
    3316        1226 :     output_tuples = numGroups;
    3317        1226 :     startup_cost = input_startup_cost;
    3318        1226 :     total_cost = input_total_cost;
    3319             : 
    3320             :     /*
    3321             :      * Charge one cpu_operator_cost per comparison per input tuple. We assume
    3322             :      * all columns get compared at most of the tuples.
    3323             :      */
    3324        1226 :     total_cost += cpu_operator_cost * input_tuples * numGroupCols;
    3325             : 
    3326             :     /*
    3327             :      * If there are quals (HAVING quals), account for their cost and
    3328             :      * selectivity.
    3329             :      */
    3330        1226 :     if (quals)
    3331             :     {
    3332             :         QualCost    qual_cost;
    3333             : 
    3334           0 :         cost_qual_eval(&qual_cost, quals, root);
    3335           0 :         startup_cost += qual_cost.startup;
    3336           0 :         total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
    3337             : 
    3338           0 :         output_tuples = clamp_row_est(output_tuples *
    3339           0 :                                       clauselist_selectivity(root,
    3340             :                                                              quals,
    3341             :                                                              0,
    3342             :                                                              JOIN_INNER,
    3343             :                                                              NULL));
    3344             :     }
    3345             : 
    3346        1226 :     path->rows = output_tuples;
    3347        1226 :     path->disabled_nodes = input_disabled_nodes;
    3348        1226 :     path->startup_cost = startup_cost;
    3349        1226 :     path->total_cost = total_cost;
    3350        1226 : }
    3351             : 
    3352             : /*
    3353             :  * initial_cost_nestloop
    3354             :  *    Preliminary estimate of the cost of a nestloop join path.
    3355             :  *
    3356             :  * This must quickly produce lower-bound estimates of the path's startup and
    3357             :  * total costs.  If we are unable to eliminate the proposed path from
    3358             :  * consideration using the lower bounds, final_cost_nestloop will be called
    3359             :  * to obtain the final estimates.
    3360             :  *
    3361             :  * The exact division of labor between this function and final_cost_nestloop
    3362             :  * is private to them, and represents a tradeoff between speed of the initial
    3363             :  * estimate and getting a tight lower bound.  We choose to not examine the
    3364             :  * join quals here, since that's by far the most expensive part of the
    3365             :  * calculations.  The end result is that CPU-cost considerations must be
    3366             :  * left for the second phase; and for SEMI/ANTI joins, we must also postpone
    3367             :  * incorporation of the inner path's run cost.
    3368             :  *
    3369             :  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
    3370             :  *      other data to be used by final_cost_nestloop
    3371             :  * 'jointype' is the type of join to be performed
    3372             :  * 'outer_path' is the outer input to the join
    3373             :  * 'inner_path' is the inner input to the join
    3374             :  * 'extra' contains miscellaneous information about the join
    3375             :  */
    3376             : void
    3377     3386462 : initial_cost_nestloop(PlannerInfo *root, JoinCostWorkspace *workspace,
    3378             :                       JoinType jointype, uint64 enable_mask,
    3379             :                       Path *outer_path, Path *inner_path,
    3380             :                       JoinPathExtraData *extra)
    3381             : {
    3382             :     int         disabled_nodes;
    3383     3386462 :     Cost        startup_cost = 0;
    3384     3386462 :     Cost        run_cost = 0;
    3385     3386462 :     double      outer_path_rows = outer_path->rows;
    3386             :     Cost        inner_rescan_start_cost;
    3387             :     Cost        inner_rescan_total_cost;
    3388             :     Cost        inner_run_cost;
    3389             :     Cost        inner_rescan_run_cost;
    3390             : 
    3391             :     /* Count up disabled nodes. */
    3392     3386462 :     disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
    3393     3386462 :     disabled_nodes += inner_path->disabled_nodes;
    3394     3386462 :     disabled_nodes += outer_path->disabled_nodes;
    3395             : 
    3396             :     /* estimate costs to rescan the inner relation */
    3397     3386462 :     cost_rescan(root, inner_path,
    3398             :                 &inner_rescan_start_cost,
    3399             :                 &inner_rescan_total_cost);
    3400             : 
    3401             :     /* cost of source data */
    3402             : 
    3403             :     /*
    3404             :      * NOTE: clearly, we must pay both outer and inner paths' startup_cost
    3405             :      * before we can start returning tuples, so the join's startup cost is
    3406             :      * their sum.  We'll also pay the inner path's rescan startup cost
    3407             :      * multiple times.
    3408             :      */
    3409     3386462 :     startup_cost += outer_path->startup_cost + inner_path->startup_cost;
    3410     3386462 :     run_cost += outer_path->total_cost - outer_path->startup_cost;
    3411     3386462 :     if (outer_path_rows > 1)
    3412     2441920 :         run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
    3413             : 
    3414     3386462 :     inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
    3415     3386462 :     inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
    3416             : 
    3417     3386462 :     if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
    3418     3324714 :         extra->inner_unique)
    3419             :     {
    3420             :         /*
    3421             :          * With a SEMI or ANTI join, or if the innerrel is known unique, the
    3422             :          * executor will stop after the first match.
    3423             :          *
    3424             :          * Getting decent estimates requires inspection of the join quals,
    3425             :          * which we choose to postpone to final_cost_nestloop.
    3426             :          */
    3427             : 
    3428             :         /* Save private data for final_cost_nestloop */
    3429     1385690 :         workspace->inner_run_cost = inner_run_cost;
    3430     1385690 :         workspace->inner_rescan_run_cost = inner_rescan_run_cost;
    3431             :     }
    3432             :     else
    3433             :     {
    3434             :         /* Normal case; we'll scan whole input rel for each outer row */
    3435     2000772 :         run_cost += inner_run_cost;
    3436     2000772 :         if (outer_path_rows > 1)
    3437     1534430 :             run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
    3438             :     }
    3439             : 
    3440             :     /* CPU costs left for later */
    3441             : 
    3442             :     /* Public result fields */
    3443     3386462 :     workspace->disabled_nodes = disabled_nodes;
    3444     3386462 :     workspace->startup_cost = startup_cost;
    3445     3386462 :     workspace->total_cost = startup_cost + run_cost;
    3446             :     /* Save private data for final_cost_nestloop */
    3447     3386462 :     workspace->run_cost = run_cost;
    3448     3386462 : }
    3449             : 
    3450             : /*
    3451             :  * final_cost_nestloop
    3452             :  *    Final estimate of the cost and result size of a nestloop join path.
    3453             :  *
    3454             :  * 'path' is already filled in except for the rows and cost fields
    3455             :  * 'workspace' is the result from initial_cost_nestloop
    3456             :  * 'extra' contains miscellaneous information about the join
    3457             :  */
    3458             : void
    3459     1520154 : final_cost_nestloop(PlannerInfo *root, NestPath *path,
    3460             :                     JoinCostWorkspace *workspace,
    3461             :                     JoinPathExtraData *extra)
    3462             : {
    3463     1520154 :     Path       *outer_path = path->jpath.outerjoinpath;
    3464     1520154 :     Path       *inner_path = path->jpath.innerjoinpath;
    3465     1520154 :     double      outer_path_rows = outer_path->rows;
    3466     1520154 :     double      inner_path_rows = inner_path->rows;
    3467     1520154 :     Cost        startup_cost = workspace->startup_cost;
    3468     1520154 :     Cost        run_cost = workspace->run_cost;
    3469             :     Cost        cpu_per_tuple;
    3470             :     QualCost    restrict_qual_cost;
    3471             :     double      ntuples;
    3472             : 
    3473             :     /* Set the number of disabled nodes. */
    3474     1520154 :     path->jpath.path.disabled_nodes = workspace->disabled_nodes;
    3475             : 
    3476             :     /* Protect some assumptions below that rowcounts aren't zero */
    3477     1520154 :     if (outer_path_rows <= 0)
    3478           0 :         outer_path_rows = 1;
    3479     1520154 :     if (inner_path_rows <= 0)
    3480         726 :         inner_path_rows = 1;
    3481             :     /* Mark the path with the correct row estimate */
    3482     1520154 :     if (path->jpath.path.param_info)
    3483       33238 :         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
    3484             :     else
    3485     1486916 :         path->jpath.path.rows = path->jpath.path.parent->rows;
    3486             : 
    3487             :     /* For partial paths, scale row estimate. */
    3488     1520154 :     if (path->jpath.path.parallel_workers > 0)
    3489             :     {
    3490       44012 :         double      parallel_divisor = get_parallel_divisor(&path->jpath.path);
    3491             : 
    3492       44012 :         path->jpath.path.rows =
    3493       44012 :             clamp_row_est(path->jpath.path.rows / parallel_divisor);
    3494             :     }
    3495             : 
    3496             :     /* cost of inner-relation source data (we already dealt with outer rel) */
    3497             : 
    3498     1520154 :     if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
    3499     1476706 :         extra->inner_unique)
    3500      955428 :     {
    3501             :         /*
    3502             :          * With a SEMI or ANTI join, or if the innerrel is known unique, the
    3503             :          * executor will stop after the first match.
    3504             :          */
    3505      955428 :         Cost        inner_run_cost = workspace->inner_run_cost;
    3506      955428 :         Cost        inner_rescan_run_cost = workspace->inner_rescan_run_cost;
    3507             :         double      outer_matched_rows;
    3508             :         double      outer_unmatched_rows;
    3509             :         Selectivity inner_scan_frac;
    3510             : 
    3511             :         /*
    3512             :          * For an outer-rel row that has at least one match, we can expect the
    3513             :          * inner scan to stop after a fraction 1/(match_count+1) of the inner
    3514             :          * rows, if the matches are evenly distributed.  Since they probably
    3515             :          * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
    3516             :          * that fraction.  (If we used a larger fuzz factor, we'd have to
    3517             :          * clamp inner_scan_frac to at most 1.0; but since match_count is at
    3518             :          * least 1, no such clamp is needed now.)
    3519             :          */
    3520      955428 :         outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
    3521      955428 :         outer_unmatched_rows = outer_path_rows - outer_matched_rows;
    3522      955428 :         inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
    3523             : 
    3524             :         /*
    3525             :          * Compute number of tuples processed (not number emitted!).  First,
    3526             :          * account for successfully-matched outer rows.
    3527             :          */
    3528      955428 :         ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
    3529             : 
    3530             :         /*
    3531             :          * Now we need to estimate the actual costs of scanning the inner
    3532             :          * relation, which may be quite a bit less than N times inner_run_cost
    3533             :          * due to early scan stops.  We consider two cases.  If the inner path
    3534             :          * is an indexscan using all the joinquals as indexquals, then an
    3535             :          * unmatched outer row results in an indexscan returning no rows,
    3536             :          * which is probably quite cheap.  Otherwise, the executor will have
    3537             :          * to scan the whole inner rel for an unmatched row; not so cheap.
    3538             :          */
    3539      955428 :         if (has_indexed_join_quals(path))
    3540             :         {
    3541             :             /*
    3542             :              * Successfully-matched outer rows will only require scanning
    3543             :              * inner_scan_frac of the inner relation.  In this case, we don't
    3544             :              * need to charge the full inner_run_cost even when that's more
    3545             :              * than inner_rescan_run_cost, because we can assume that none of
    3546             :              * the inner scans ever scan the whole inner relation.  So it's
    3547             :              * okay to assume that all the inner scan executions can be
    3548             :              * fractions of the full cost, even if materialization is reducing
    3549             :              * the rescan cost.  At this writing, it's impossible to get here
    3550             :              * for a materialized inner scan, so inner_run_cost and
    3551             :              * inner_rescan_run_cost will be the same anyway; but just in
    3552             :              * case, use inner_run_cost for the first matched tuple and
    3553             :              * inner_rescan_run_cost for additional ones.
    3554             :              */
    3555      157300 :             run_cost += inner_run_cost * inner_scan_frac;
    3556      157300 :             if (outer_matched_rows > 1)
    3557       21210 :                 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
    3558             : 
    3559             :             /*
    3560             :              * Add the cost of inner-scan executions for unmatched outer rows.
    3561             :              * We estimate this as the same cost as returning the first tuple
    3562             :              * of a nonempty scan.  We consider that these are all rescans,
    3563             :              * since we used inner_run_cost once already.
    3564             :              */
    3565      157300 :             run_cost += outer_unmatched_rows *
    3566      157300 :                 inner_rescan_run_cost / inner_path_rows;
    3567             : 
    3568             :             /*
    3569             :              * We won't be evaluating any quals at all for unmatched rows, so
    3570             :              * don't add them to ntuples.
    3571             :              */
    3572             :         }
    3573             :         else
    3574             :         {
    3575             :             /*
    3576             :              * Here, a complicating factor is that rescans may be cheaper than
    3577             :              * first scans.  If we never scan all the way to the end of the
    3578             :              * inner rel, it might be (depending on the plan type) that we'd
    3579             :              * never pay the whole inner first-scan run cost.  However it is
    3580             :              * difficult to estimate whether that will happen (and it could
    3581             :              * not happen if there are any unmatched outer rows!), so be
    3582             :              * conservative and always charge the whole first-scan cost once.
    3583             :              * We consider this charge to correspond to the first unmatched
    3584             :              * outer row, unless there isn't one in our estimate, in which
    3585             :              * case blame it on the first matched row.
    3586             :              */
    3587             : 
    3588             :             /* First, count all unmatched join tuples as being processed */
    3589      798128 :             ntuples += outer_unmatched_rows * inner_path_rows;
    3590             : 
    3591             :             /* Now add the forced full scan, and decrement appropriate count */
    3592      798128 :             run_cost += inner_run_cost;
    3593      798128 :             if (outer_unmatched_rows >= 1)
    3594      758170 :                 outer_unmatched_rows -= 1;
    3595             :             else
    3596       39958 :                 outer_matched_rows -= 1;
    3597             : 
    3598             :             /* Add inner run cost for additional outer tuples having matches */
    3599      798128 :             if (outer_matched_rows > 0)
    3600      282160 :                 run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
    3601             : 
    3602             :             /* Add inner run cost for additional unmatched outer tuples */
    3603      798128 :             if (outer_unmatched_rows > 0)
    3604      496018 :                 run_cost += outer_unmatched_rows * inner_rescan_run_cost;
    3605             :         }
    3606             :     }
    3607             :     else
    3608             :     {
    3609             :         /* Normal-case source costs were included in preliminary estimate */
    3610             : 
    3611             :         /* Compute number of tuples processed (not number emitted!) */
    3612      564726 :         ntuples = outer_path_rows * inner_path_rows;
    3613             :     }
    3614             : 
    3615             :     /* CPU costs */
    3616     1520154 :     cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
    3617     1520154 :     startup_cost += restrict_qual_cost.startup;
    3618     1520154 :     cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
    3619     1520154 :     run_cost += cpu_per_tuple * ntuples;
    3620             : 
    3621             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    3622     1520154 :     startup_cost += path->jpath.path.pathtarget->cost.startup;
    3623     1520154 :     run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
    3624             : 
    3625     1520154 :     path->jpath.path.startup_cost = startup_cost;
    3626     1520154 :     path->jpath.path.total_cost = startup_cost + run_cost;
    3627     1520154 : }
    3628             : 
    3629             : /*
    3630             :  * initial_cost_mergejoin
    3631             :  *    Preliminary estimate of the cost of a mergejoin path.
    3632             :  *
    3633             :  * This must quickly produce lower-bound estimates of the path's startup and
    3634             :  * total costs.  If we are unable to eliminate the proposed path from
    3635             :  * consideration using the lower bounds, final_cost_mergejoin will be called
    3636             :  * to obtain the final estimates.
    3637             :  *
    3638             :  * The exact division of labor between this function and final_cost_mergejoin
    3639             :  * is private to them, and represents a tradeoff between speed of the initial
    3640             :  * estimate and getting a tight lower bound.  We choose to not examine the
    3641             :  * join quals here, except for obtaining the scan selectivity estimate which
    3642             :  * is really essential (but fortunately, use of caching keeps the cost of
    3643             :  * getting that down to something reasonable).
    3644             :  * We also assume that cost_sort/cost_incremental_sort is cheap enough to use
    3645             :  * here.
    3646             :  *
    3647             :  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
    3648             :  *      other data to be used by final_cost_mergejoin
    3649             :  * 'jointype' is the type of join to be performed
    3650             :  * 'mergeclauses' is the list of joinclauses to be used as merge clauses
    3651             :  * 'outer_path' is the outer input to the join
    3652             :  * 'inner_path' is the inner input to the join
    3653             :  * 'outersortkeys' is the list of sort keys for the outer path
    3654             :  * 'innersortkeys' is the list of sort keys for the inner path
    3655             :  * 'outer_presorted_keys' is the number of presorted keys of the outer path
    3656             :  * 'extra' contains miscellaneous information about the join
    3657             :  *
    3658             :  * Note: outersortkeys and innersortkeys should be NIL if no explicit
    3659             :  * sort is needed because the respective source path is already ordered.
    3660             :  */
    3661             : void
    3662     1536716 : initial_cost_mergejoin(PlannerInfo *root, JoinCostWorkspace *workspace,
    3663             :                        JoinType jointype,
    3664             :                        List *mergeclauses,
    3665             :                        Path *outer_path, Path *inner_path,
    3666             :                        List *outersortkeys, List *innersortkeys,
    3667             :                        int outer_presorted_keys,
    3668             :                        JoinPathExtraData *extra)
    3669             : {
    3670             :     int         disabled_nodes;
    3671     1536716 :     Cost        startup_cost = 0;
    3672     1536716 :     Cost        run_cost = 0;
    3673     1536716 :     double      outer_path_rows = outer_path->rows;
    3674     1536716 :     double      inner_path_rows = inner_path->rows;
    3675             :     Cost        inner_run_cost;
    3676             :     double      outer_rows,
    3677             :                 inner_rows,
    3678             :                 outer_skip_rows,
    3679             :                 inner_skip_rows;
    3680             :     Selectivity outerstartsel,
    3681             :                 outerendsel,
    3682             :                 innerstartsel,
    3683             :                 innerendsel;
    3684             :     Path        sort_path;      /* dummy for result of
    3685             :                                  * cost_sort/cost_incremental_sort */
    3686             : 
    3687             :     /* Protect some assumptions below that rowcounts aren't zero */
    3688     1536716 :     if (outer_path_rows <= 0)
    3689          96 :         outer_path_rows = 1;
    3690     1536716 :     if (inner_path_rows <= 0)
    3691         126 :         inner_path_rows = 1;
    3692             : 
    3693             :     /*
    3694             :      * A merge join will stop as soon as it exhausts either input stream
    3695             :      * (unless it's an outer join, in which case the outer side has to be
    3696             :      * scanned all the way anyway).  Estimate fraction of the left and right
    3697             :      * inputs that will actually need to be scanned.  Likewise, we can
    3698             :      * estimate the number of rows that will be skipped before the first join
    3699             :      * pair is found, which should be factored into startup cost. We use only
    3700             :      * the first (most significant) merge clause for this purpose. Since
    3701             :      * mergejoinscansel() is a fairly expensive computation, we cache the
    3702             :      * results in the merge clause RestrictInfo.
    3703             :      */
    3704     1536716 :     if (mergeclauses && jointype != JOIN_FULL)
    3705     1530452 :     {
    3706     1530452 :         RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
    3707             :         List       *opathkeys;
    3708             :         List       *ipathkeys;
    3709             :         PathKey    *opathkey;
    3710             :         PathKey    *ipathkey;
    3711             :         MergeScanSelCache *cache;
    3712             : 
    3713             :         /* Get the input pathkeys to determine the sort-order details */
    3714     1530452 :         opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
    3715     1530452 :         ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
    3716             :         Assert(opathkeys);
    3717             :         Assert(ipathkeys);
    3718     1530452 :         opathkey = (PathKey *) linitial(opathkeys);
    3719     1530452 :         ipathkey = (PathKey *) linitial(ipathkeys);
    3720             :         /* debugging check */
    3721     1530452 :         if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
    3722     1530452 :             opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
    3723     1530452 :             opathkey->pk_cmptype != ipathkey->pk_cmptype ||
    3724     1530452 :             opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
    3725           0 :             elog(ERROR, "left and right pathkeys do not match in mergejoin");
    3726             : 
    3727             :         /* Get the selectivity with caching */
    3728     1530452 :         cache = cached_scansel(root, firstclause, opathkey);
    3729             : 
    3730     1530452 :         if (bms_is_subset(firstclause->left_relids,
    3731     1530452 :                           outer_path->parent->relids))
    3732             :         {
    3733             :             /* left side of clause is outer */
    3734      798028 :             outerstartsel = cache->leftstartsel;
    3735      798028 :             outerendsel = cache->leftendsel;
    3736      798028 :             innerstartsel = cache->rightstartsel;
    3737      798028 :             innerendsel = cache->rightendsel;
    3738             :         }
    3739             :         else
    3740             :         {
    3741             :             /* left side of clause is inner */
    3742      732424 :             outerstartsel = cache->rightstartsel;
    3743      732424 :             outerendsel = cache->rightendsel;
    3744      732424 :             innerstartsel = cache->leftstartsel;
    3745      732424 :             innerendsel = cache->leftendsel;
    3746             :         }
    3747     1530452 :         if (jointype == JOIN_LEFT ||
    3748             :             jointype == JOIN_ANTI)
    3749             :         {
    3750      200638 :             outerstartsel = 0.0;
    3751      200638 :             outerendsel = 1.0;
    3752             :         }
    3753     1329814 :         else if (jointype == JOIN_RIGHT ||
    3754             :                  jointype == JOIN_RIGHT_ANTI)
    3755             :         {
    3756      200294 :             innerstartsel = 0.0;
    3757      200294 :             innerendsel = 1.0;
    3758             :         }
    3759             :     }
    3760             :     else
    3761             :     {
    3762             :         /* cope with clauseless or full mergejoin */
    3763        6264 :         outerstartsel = innerstartsel = 0.0;
    3764        6264 :         outerendsel = innerendsel = 1.0;
    3765             :     }
    3766             : 
    3767             :     /*
    3768             :      * Convert selectivities to row counts.  We force outer_rows and
    3769             :      * inner_rows to be at least 1, but the skip_rows estimates can be zero.
    3770             :      */
    3771     1536716 :     outer_skip_rows = rint(outer_path_rows * outerstartsel);
    3772     1536716 :     inner_skip_rows = rint(inner_path_rows * innerstartsel);
    3773     1536716 :     outer_rows = clamp_row_est(outer_path_rows * outerendsel);
    3774     1536716 :     inner_rows = clamp_row_est(inner_path_rows * innerendsel);
    3775             : 
    3776             :     Assert(outer_skip_rows <= outer_rows);
    3777             :     Assert(inner_skip_rows <= inner_rows);
    3778             : 
    3779             :     /*
    3780             :      * Readjust scan selectivities to account for above rounding.  This is
    3781             :      * normally an insignificant effect, but when there are only a few rows in
    3782             :      * the inputs, failing to do this makes for a large percentage error.
    3783             :      */
    3784     1536716 :     outerstartsel = outer_skip_rows / outer_path_rows;
    3785     1536716 :     innerstartsel = inner_skip_rows / inner_path_rows;
    3786     1536716 :     outerendsel = outer_rows / outer_path_rows;
    3787     1536716 :     innerendsel = inner_rows / inner_path_rows;
    3788             : 
    3789             :     Assert(outerstartsel <= outerendsel);
    3790             :     Assert(innerstartsel <= innerendsel);
    3791             : 
    3792             :     /*
    3793             :      * We don't decide whether to materialize the inner path until we get to
    3794             :      * final_cost_mergejoin(), so we don't know whether to check the pgs_mask
    3795             :      * against PGS_MERGEJOIN_PLAIN or PGS_MERGEJOIN_MATERIALIZE. Instead, we
    3796             :      * just account for any child nodes here and assume that this node is not
    3797             :      * itself disabled; we can sort out the details in final_cost_mergejoin().
    3798             :      *
    3799             :      * (We could be more precise here by setting disabled_nodes to 1 at this
    3800             :      * stage if both PGS_MERGEJOIN_PLAIN and PGS_MERGEJOIN_MATERIALIZE are
    3801             :      * disabled, but that seems to against the idea of making this function
    3802             :      * produce a quick, optimistic approximation of the final cost.)
    3803             :      */
    3804     1536716 :     disabled_nodes = 0;
    3805             : 
    3806             :     /* cost of source data */
    3807             : 
    3808     1536716 :     if (outersortkeys)          /* do we need to sort outer? */
    3809             :     {
    3810             :         /*
    3811             :          * We can assert that the outer path is not already ordered
    3812             :          * appropriately for the mergejoin; otherwise, outersortkeys would
    3813             :          * have been set to NIL.
    3814             :          */
    3815             :         Assert(!pathkeys_contained_in(outersortkeys, outer_path->pathkeys));
    3816             : 
    3817             :         /*
    3818             :          * We choose to use incremental sort if it is enabled and there are
    3819             :          * presorted keys; otherwise we use full sort.
    3820             :          */
    3821      776994 :         if (enable_incremental_sort && outer_presorted_keys > 0)
    3822             :         {
    3823        2036 :             cost_incremental_sort(&sort_path,
    3824             :                                   root,
    3825             :                                   outersortkeys,
    3826             :                                   outer_presorted_keys,
    3827             :                                   outer_path->disabled_nodes,
    3828             :                                   outer_path->startup_cost,
    3829             :                                   outer_path->total_cost,
    3830             :                                   outer_path_rows,
    3831        2036 :                                   outer_path->pathtarget->width,
    3832             :                                   0.0,
    3833             :                                   work_mem,
    3834             :                                   -1.0);
    3835             :         }
    3836             :         else
    3837             :         {
    3838      774958 :             cost_sort(&sort_path,
    3839             :                       root,
    3840             :                       outersortkeys,
    3841             :                       outer_path->disabled_nodes,
    3842             :                       outer_path->total_cost,
    3843             :                       outer_path_rows,
    3844      774958 :                       outer_path->pathtarget->width,
    3845             :                       0.0,
    3846             :                       work_mem,
    3847             :                       -1.0);
    3848             :         }
    3849             : 
    3850      776994 :         disabled_nodes += sort_path.disabled_nodes;
    3851      776994 :         startup_cost += sort_path.startup_cost;
    3852      776994 :         startup_cost += (sort_path.total_cost - sort_path.startup_cost)
    3853      776994 :             * outerstartsel;
    3854      776994 :         run_cost += (sort_path.total_cost - sort_path.startup_cost)
    3855      776994 :             * (outerendsel - outerstartsel);
    3856             :     }
    3857             :     else
    3858             :     {
    3859      759722 :         disabled_nodes += outer_path->disabled_nodes;
    3860      759722 :         startup_cost += outer_path->startup_cost;
    3861      759722 :         startup_cost += (outer_path->total_cost - outer_path->startup_cost)
    3862      759722 :             * outerstartsel;
    3863      759722 :         run_cost += (outer_path->total_cost - outer_path->startup_cost)
    3864      759722 :             * (outerendsel - outerstartsel);
    3865             :     }
    3866             : 
    3867     1536716 :     if (innersortkeys)          /* do we need to sort inner? */
    3868             :     {
    3869             :         /*
    3870             :          * We can assert that the inner path is not already ordered
    3871             :          * appropriately for the mergejoin; otherwise, innersortkeys would
    3872             :          * have been set to NIL.
    3873             :          */
    3874             :         Assert(!pathkeys_contained_in(innersortkeys, inner_path->pathkeys));
    3875             : 
    3876             :         /*
    3877             :          * We do not consider incremental sort for inner path, because
    3878             :          * incremental sort does not support mark/restore.
    3879             :          */
    3880             : 
    3881     1229826 :         cost_sort(&sort_path,
    3882             :                   root,
    3883             :                   innersortkeys,
    3884             :                   inner_path->disabled_nodes,
    3885             :                   inner_path->total_cost,
    3886             :                   inner_path_rows,
    3887     1229826 :                   inner_path->pathtarget->width,
    3888             :                   0.0,
    3889             :                   work_mem,
    3890             :                   -1.0);
    3891     1229826 :         disabled_nodes += sort_path.disabled_nodes;
    3892     1229826 :         startup_cost += sort_path.startup_cost;
    3893     1229826 :         startup_cost += (sort_path.total_cost - sort_path.startup_cost)
    3894     1229826 :             * innerstartsel;
    3895     1229826 :         inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
    3896     1229826 :             * (innerendsel - innerstartsel);
    3897             :     }
    3898             :     else
    3899             :     {
    3900      306890 :         disabled_nodes += inner_path->disabled_nodes;
    3901      306890 :         startup_cost += inner_path->startup_cost;
    3902      306890 :         startup_cost += (inner_path->total_cost - inner_path->startup_cost)
    3903      306890 :             * innerstartsel;
    3904      306890 :         inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
    3905      306890 :             * (innerendsel - innerstartsel);
    3906             :     }
    3907             : 
    3908             :     /*
    3909             :      * We can't yet determine whether rescanning occurs, or whether
    3910             :      * materialization of the inner input should be done.  The minimum
    3911             :      * possible inner input cost, regardless of rescan and materialization
    3912             :      * considerations, is inner_run_cost.  We include that in
    3913             :      * workspace->total_cost, but not yet in run_cost.
    3914             :      */
    3915             : 
    3916             :     /* CPU costs left for later */
    3917             : 
    3918             :     /* Public result fields */
    3919     1536716 :     workspace->disabled_nodes = disabled_nodes;
    3920     1536716 :     workspace->startup_cost = startup_cost;
    3921     1536716 :     workspace->total_cost = startup_cost + run_cost + inner_run_cost;
    3922             :     /* Save private data for final_cost_mergejoin */
    3923     1536716 :     workspace->run_cost = run_cost;
    3924     1536716 :     workspace->inner_run_cost = inner_run_cost;
    3925     1536716 :     workspace->outer_rows = outer_rows;
    3926     1536716 :     workspace->inner_rows = inner_rows;
    3927     1536716 :     workspace->outer_skip_rows = outer_skip_rows;
    3928     1536716 :     workspace->inner_skip_rows = inner_skip_rows;
    3929     1536716 : }
    3930             : 
    3931             : /*
    3932             :  * final_cost_mergejoin
    3933             :  *    Final estimate of the cost and result size of a mergejoin path.
    3934             :  *
    3935             :  * Unlike other costsize functions, this routine makes two actual decisions:
    3936             :  * whether the executor will need to do mark/restore, and whether we should
    3937             :  * materialize the inner path.  It would be logically cleaner to build
    3938             :  * separate paths testing these alternatives, but that would require repeating
    3939             :  * most of the cost calculations, which are not all that cheap.  Since the
    3940             :  * choice will not affect output pathkeys or startup cost, only total cost,
    3941             :  * there is no possibility of wanting to keep more than one path.  So it seems
    3942             :  * best to make the decisions here and record them in the path's
    3943             :  * skip_mark_restore and materialize_inner fields.
    3944             :  *
    3945             :  * Mark/restore overhead is usually required, but can be skipped if we know
    3946             :  * that the executor need find only one match per outer tuple, and that the
    3947             :  * mergeclauses are sufficient to identify a match.
    3948             :  *
    3949             :  * We materialize the inner path if we need mark/restore and either the inner
    3950             :  * path can't support mark/restore, or it's cheaper to use an interposed
    3951             :  * Material node to handle mark/restore.
    3952             :  *
    3953             :  * 'path' is already filled in except for the rows and cost fields and
    3954             :  *      skip_mark_restore and materialize_inner
    3955             :  * 'workspace' is the result from initial_cost_mergejoin
    3956             :  * 'extra' contains miscellaneous information about the join
    3957             :  */
    3958             : void
    3959      473372 : final_cost_mergejoin(PlannerInfo *root, MergePath *path,
    3960             :                      JoinCostWorkspace *workspace,
    3961             :                      JoinPathExtraData *extra)
    3962             : {
    3963      473372 :     Path       *outer_path = path->jpath.outerjoinpath;
    3964      473372 :     Path       *inner_path = path->jpath.innerjoinpath;
    3965      473372 :     double      inner_path_rows = inner_path->rows;
    3966      473372 :     List       *mergeclauses = path->path_mergeclauses;
    3967      473372 :     List       *innersortkeys = path->innersortkeys;
    3968      473372 :     Cost        startup_cost = workspace->startup_cost;
    3969      473372 :     Cost        run_cost = workspace->run_cost;
    3970      473372 :     Cost        inner_run_cost = workspace->inner_run_cost;
    3971      473372 :     double      outer_rows = workspace->outer_rows;
    3972      473372 :     double      inner_rows = workspace->inner_rows;
    3973      473372 :     double      outer_skip_rows = workspace->outer_skip_rows;
    3974      473372 :     double      inner_skip_rows = workspace->inner_skip_rows;
    3975             :     Cost        cpu_per_tuple,
    3976             :                 bare_inner_cost,
    3977             :                 mat_inner_cost;
    3978             :     QualCost    merge_qual_cost;
    3979             :     QualCost    qp_qual_cost;
    3980             :     double      mergejointuples,
    3981             :                 rescannedtuples;
    3982             :     double      rescanratio;
    3983      473372 :     uint64      enable_mask = 0;
    3984             : 
    3985             :     /* Protect some assumptions below that rowcounts aren't zero */
    3986      473372 :     if (inner_path_rows <= 0)
    3987          90 :         inner_path_rows = 1;
    3988             : 
    3989             :     /* Mark the path with the correct row estimate */
    3990      473372 :     if (path->jpath.path.param_info)
    3991        1624 :         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
    3992             :     else
    3993      471748 :         path->jpath.path.rows = path->jpath.path.parent->rows;
    3994             : 
    3995             :     /* For partial paths, scale row estimate. */
    3996      473372 :     if (path->jpath.path.parallel_workers > 0)
    3997             :     {
    3998       65872 :         double      parallel_divisor = get_parallel_divisor(&path->jpath.path);
    3999             : 
    4000       65872 :         path->jpath.path.rows =
    4001       65872 :             clamp_row_est(path->jpath.path.rows / parallel_divisor);
    4002             :     }
    4003             : 
    4004             :     /*
    4005             :      * Compute cost of the mergequals and qpquals (other restriction clauses)
    4006             :      * separately.
    4007             :      */
    4008      473372 :     cost_qual_eval(&merge_qual_cost, mergeclauses, root);
    4009      473372 :     cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
    4010      473372 :     qp_qual_cost.startup -= merge_qual_cost.startup;
    4011      473372 :     qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
    4012             : 
    4013             :     /*
    4014             :      * With a SEMI or ANTI join, or if the innerrel is known unique, the
    4015             :      * executor will stop scanning for matches after the first match.  When
    4016             :      * all the joinclauses are merge clauses, this means we don't ever need to
    4017             :      * back up the merge, and so we can skip mark/restore overhead.
    4018             :      */
    4019      473372 :     if ((path->jpath.jointype == JOIN_SEMI ||
    4020      466126 :          path->jpath.jointype == JOIN_ANTI ||
    4021      624292 :          extra->inner_unique) &&
    4022      165260 :         (list_length(path->jpath.joinrestrictinfo) ==
    4023      165260 :          list_length(path->path_mergeclauses)))
    4024      142906 :         path->skip_mark_restore = true;
    4025             :     else
    4026      330466 :         path->skip_mark_restore = false;
    4027             : 
    4028             :     /*
    4029             :      * Get approx # tuples passing the mergequals.  We use approx_tuple_count
    4030             :      * here because we need an estimate done with JOIN_INNER semantics.
    4031             :      */
    4032      473372 :     mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
    4033             : 
    4034             :     /*
    4035             :      * When there are equal merge keys in the outer relation, the mergejoin
    4036             :      * must rescan any matching tuples in the inner relation. This means
    4037             :      * re-fetching inner tuples; we have to estimate how often that happens.
    4038             :      *
    4039             :      * For regular inner and outer joins, the number of re-fetches can be
    4040             :      * estimated approximately as size of merge join output minus size of
    4041             :      * inner relation. Assume that the distinct key values are 1, 2, ..., and
    4042             :      * denote the number of values of each key in the outer relation as m1,
    4043             :      * m2, ...; in the inner relation, n1, n2, ...  Then we have
    4044             :      *
    4045             :      * size of join = m1 * n1 + m2 * n2 + ...
    4046             :      *
    4047             :      * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
    4048             :      * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
    4049             :      * relation
    4050             :      *
    4051             :      * This equation works correctly for outer tuples having no inner match
    4052             :      * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
    4053             :      * are effectively subtracting those from the number of rescanned tuples,
    4054             :      * when we should not.  Can we do better without expensive selectivity
    4055             :      * computations?
    4056             :      *
    4057             :      * The whole issue is moot if we know we don't need to mark/restore at
    4058             :      * all, or if we are working from a unique-ified outer input.
    4059             :      */
    4060      473372 :     if (path->skip_mark_restore ||
    4061      330466 :         RELATION_WAS_MADE_UNIQUE(outer_path->parent, extra->sjinfo,
    4062             :                                  path->jpath.jointype))
    4063      147616 :         rescannedtuples = 0;
    4064             :     else
    4065             :     {
    4066      325756 :         rescannedtuples = mergejointuples - inner_path_rows;
    4067             :         /* Must clamp because of possible underestimate */
    4068      325756 :         if (rescannedtuples < 0)
    4069       80234 :             rescannedtuples = 0;
    4070             :     }
    4071             : 
    4072             :     /*
    4073             :      * We'll inflate various costs this much to account for rescanning.  Note
    4074             :      * that this is to be multiplied by something involving inner_rows, or
    4075             :      * another number related to the portion of the inner rel we'll scan.
    4076             :      */
    4077      473372 :     rescanratio = 1.0 + (rescannedtuples / inner_rows);
    4078             : 
    4079             :     /*
    4080             :      * Decide whether we want to materialize the inner input to shield it from
    4081             :      * mark/restore and performing re-fetches.  Our cost model for regular
    4082             :      * re-fetches is that a re-fetch costs the same as an original fetch,
    4083             :      * which is probably an overestimate; but on the other hand we ignore the
    4084             :      * bookkeeping costs of mark/restore.  Not clear if it's worth developing
    4085             :      * a more refined model.  So we just need to inflate the inner run cost by
    4086             :      * rescanratio.
    4087             :      */
    4088      473372 :     bare_inner_cost = inner_run_cost * rescanratio;
    4089             : 
    4090             :     /*
    4091             :      * When we interpose a Material node the re-fetch cost is assumed to be
    4092             :      * just cpu_operator_cost per tuple, independently of the underlying
    4093             :      * plan's cost; and we charge an extra cpu_operator_cost per original
    4094             :      * fetch as well.  Note that we're assuming the materialize node will
    4095             :      * never spill to disk, since it only has to remember tuples back to the
    4096             :      * last mark.  (If there are a huge number of duplicates, our other cost
    4097             :      * factors will make the path so expensive that it probably won't get
    4098             :      * chosen anyway.)  So we don't use cost_rescan here.
    4099             :      *
    4100             :      * Note: keep this estimate in sync with create_mergejoin_plan's labeling
    4101             :      * of the generated Material node.
    4102             :      */
    4103      473372 :     mat_inner_cost = inner_run_cost +
    4104      473372 :         cpu_operator_cost * inner_rows * rescanratio;
    4105             : 
    4106             :     /*
    4107             :      * If we don't need mark/restore at all, we don't need materialization.
    4108             :      */
    4109      473372 :     if (path->skip_mark_restore)
    4110      142906 :         path->materialize_inner = false;
    4111             : 
    4112             :     /*
    4113             :      * If merge joins with materialization are enabled, then choose
    4114             :      * materialization if either (a) it looks cheaper or (b) merge joins
    4115             :      * without materialization are disabled.
    4116             :      */
    4117      330466 :     else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
    4118      327064 :              (mat_inner_cost < bare_inner_cost ||
    4119      327064 :               (extra->pgs_mask & PGS_MERGEJOIN_PLAIN) == 0))
    4120        3340 :         path->materialize_inner = true;
    4121             : 
    4122             :     /*
    4123             :      * Regardless of what plan shapes are enabled and what the costs seem to
    4124             :      * be, we *must* materialize it if the inner path is to be used directly
    4125             :      * (without sorting) and it doesn't support mark/restore. Planner failure
    4126             :      * is not an option!
    4127             :      *
    4128             :      * Since the inner side must be ordered, and only Sorts and IndexScans can
    4129             :      * create order to begin with, and they both support mark/restore, you
    4130             :      * might think there's no problem --- but you'd be wrong.  Nestloop and
    4131             :      * merge joins can *preserve* the order of their inputs, so they can be
    4132             :      * selected as the input of a mergejoin, and they don't support
    4133             :      * mark/restore at present.
    4134             :      */
    4135      327126 :     else if (innersortkeys == NIL &&
    4136        9084 :              !ExecSupportsMarkRestore(inner_path))
    4137        1918 :         path->materialize_inner = true;
    4138             : 
    4139             :     /*
    4140             :      * Also, force materializing if the inner path is to be sorted and the
    4141             :      * sort is expected to spill to disk.  This is because the final merge
    4142             :      * pass can be done on-the-fly if it doesn't have to support mark/restore.
    4143             :      * We don't try to adjust the cost estimates for this consideration,
    4144             :      * though.
    4145             :      *
    4146             :      * Since materialization is a performance optimization in this case,
    4147             :      * rather than necessary for correctness, we skip it if materialization is
    4148             :      * switched off.
    4149             :      */
    4150      325208 :     else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
    4151      317988 :              innersortkeys != NIL &&
    4152      317988 :              relation_byte_size(inner_path_rows,
    4153      317988 :                                 inner_path->pathtarget->width) >
    4154      317988 :              work_mem * (Size) 1024)
    4155         284 :         path->materialize_inner = true;
    4156             :     else
    4157      324924 :         path->materialize_inner = false;
    4158             : 
    4159             :     /* Get the number of disabled nodes, not yet including this one. */
    4160      473372 :     path->jpath.path.disabled_nodes = workspace->disabled_nodes;
    4161             : 
    4162             :     /*
    4163             :      * Charge the right incremental cost for the chosen case, and update
    4164             :      * enable_mask as appropriate.
    4165             :      */
    4166      473372 :     if (path->materialize_inner)
    4167             :     {
    4168        5542 :         run_cost += mat_inner_cost;
    4169        5542 :         enable_mask |= PGS_MERGEJOIN_MATERIALIZE;
    4170             :     }
    4171             :     else
    4172             :     {
    4173      467830 :         run_cost += bare_inner_cost;
    4174      467830 :         enable_mask |= PGS_MERGEJOIN_PLAIN;
    4175             :     }
    4176             : 
    4177             :     /* Incremental count of disabled nodes if this node is disabled. */
    4178      473372 :     if (path->jpath.path.parallel_workers == 0)
    4179      407500 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    4180      473372 :     if ((extra->pgs_mask & enable_mask) != enable_mask)
    4181          14 :         ++path->jpath.path.disabled_nodes;
    4182             : 
    4183             :     /* CPU costs */
    4184             : 
    4185             :     /*
    4186             :      * The number of tuple comparisons needed is approximately number of outer
    4187             :      * rows plus number of inner rows plus number of rescanned tuples (can we
    4188             :      * refine this?).  At each one, we need to evaluate the mergejoin quals.
    4189             :      */
    4190      473372 :     startup_cost += merge_qual_cost.startup;
    4191      473372 :     startup_cost += merge_qual_cost.per_tuple *
    4192      473372 :         (outer_skip_rows + inner_skip_rows * rescanratio);
    4193      473372 :     run_cost += merge_qual_cost.per_tuple *
    4194      473372 :         ((outer_rows - outer_skip_rows) +
    4195      473372 :          (inner_rows - inner_skip_rows) * rescanratio);
    4196             : 
    4197             :     /*
    4198             :      * For each tuple that gets through the mergejoin proper, we charge
    4199             :      * cpu_tuple_cost plus the cost of evaluating additional restriction
    4200             :      * clauses that are to be applied at the join.  (This is pessimistic since
    4201             :      * not all of the quals may get evaluated at each tuple.)
    4202             :      *
    4203             :      * Note: we could adjust for SEMI/ANTI joins skipping some qual
    4204             :      * evaluations here, but it's probably not worth the trouble.
    4205             :      */
    4206      473372 :     startup_cost += qp_qual_cost.startup;
    4207      473372 :     cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
    4208      473372 :     run_cost += cpu_per_tuple * mergejointuples;
    4209             : 
    4210             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    4211      473372 :     startup_cost += path->jpath.path.pathtarget->cost.startup;
    4212      473372 :     run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
    4213             : 
    4214      473372 :     path->jpath.path.startup_cost = startup_cost;
    4215      473372 :     path->jpath.path.total_cost = startup_cost + run_cost;
    4216      473372 : }
    4217             : 
    4218             : /*
    4219             :  * run mergejoinscansel() with caching
    4220             :  */
    4221             : static MergeScanSelCache *
    4222     1530452 : cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
    4223             : {
    4224             :     MergeScanSelCache *cache;
    4225             :     ListCell   *lc;
    4226             :     Selectivity leftstartsel,
    4227             :                 leftendsel,
    4228             :                 rightstartsel,
    4229             :                 rightendsel;
    4230             :     MemoryContext oldcontext;
    4231             : 
    4232             :     /* Do we have this result already? */
    4233     1530458 :     foreach(lc, rinfo->scansel_cache)
    4234             :     {
    4235     1385704 :         cache = (MergeScanSelCache *) lfirst(lc);
    4236     1385704 :         if (cache->opfamily == pathkey->pk_opfamily &&
    4237     1385704 :             cache->collation == pathkey->pk_eclass->ec_collation &&
    4238     1385704 :             cache->cmptype == pathkey->pk_cmptype &&
    4239     1385698 :             cache->nulls_first == pathkey->pk_nulls_first)
    4240     1385698 :             return cache;
    4241             :     }
    4242             : 
    4243             :     /* Nope, do the computation */
    4244      144754 :     mergejoinscansel(root,
    4245      144754 :                      (Node *) rinfo->clause,
    4246             :                      pathkey->pk_opfamily,
    4247             :                      pathkey->pk_cmptype,
    4248      144754 :                      pathkey->pk_nulls_first,
    4249             :                      &leftstartsel,
    4250             :                      &leftendsel,
    4251             :                      &rightstartsel,
    4252             :                      &rightendsel);
    4253             : 
    4254             :     /* Cache the result in suitably long-lived workspace */
    4255      144754 :     oldcontext = MemoryContextSwitchTo(root->planner_cxt);
    4256             : 
    4257      144754 :     cache = palloc_object(MergeScanSelCache);
    4258      144754 :     cache->opfamily = pathkey->pk_opfamily;
    4259      144754 :     cache->collation = pathkey->pk_eclass->ec_collation;
    4260      144754 :     cache->cmptype = pathkey->pk_cmptype;
    4261      144754 :     cache->nulls_first = pathkey->pk_nulls_first;
    4262      144754 :     cache->leftstartsel = leftstartsel;
    4263      144754 :     cache->leftendsel = leftendsel;
    4264      144754 :     cache->rightstartsel = rightstartsel;
    4265      144754 :     cache->rightendsel = rightendsel;
    4266             : 
    4267      144754 :     rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
    4268             : 
    4269      144754 :     MemoryContextSwitchTo(oldcontext);
    4270             : 
    4271      144754 :     return cache;
    4272             : }
    4273             : 
    4274             : /*
    4275             :  * initial_cost_hashjoin
    4276             :  *    Preliminary estimate of the cost of a hashjoin path.
    4277             :  *
    4278             :  * This must quickly produce lower-bound estimates of the path's startup and
    4279             :  * total costs.  If we are unable to eliminate the proposed path from
    4280             :  * consideration using the lower bounds, final_cost_hashjoin will be called
    4281             :  * to obtain the final estimates.
    4282             :  *
    4283             :  * The exact division of labor between this function and final_cost_hashjoin
    4284             :  * is private to them, and represents a tradeoff between speed of the initial
    4285             :  * estimate and getting a tight lower bound.  We choose to not examine the
    4286             :  * join quals here (other than by counting the number of hash clauses),
    4287             :  * so we can't do much with CPU costs.  We do assume that
    4288             :  * ExecChooseHashTableSize is cheap enough to use here.
    4289             :  *
    4290             :  * 'workspace' is to be filled with startup_cost, total_cost, and perhaps
    4291             :  *      other data to be used by final_cost_hashjoin
    4292             :  * 'jointype' is the type of join to be performed
    4293             :  * 'hashclauses' is the list of joinclauses to be used as hash clauses
    4294             :  * 'outer_path' is the outer input to the join
    4295             :  * 'inner_path' is the inner input to the join
    4296             :  * 'extra' contains miscellaneous information about the join
    4297             :  * 'parallel_hash' indicates that inner_path is partial and that a shared
    4298             :  *      hash table will be built in parallel
    4299             :  */
    4300             : void
    4301      900444 : initial_cost_hashjoin(PlannerInfo *root, JoinCostWorkspace *workspace,
    4302             :                       JoinType jointype,
    4303             :                       List *hashclauses,
    4304             :                       Path *outer_path, Path *inner_path,
    4305             :                       JoinPathExtraData *extra,
    4306             :                       bool parallel_hash)
    4307             : {
    4308             :     int         disabled_nodes;
    4309      900444 :     Cost        startup_cost = 0;
    4310      900444 :     Cost        run_cost = 0;
    4311      900444 :     double      outer_path_rows = outer_path->rows;
    4312      900444 :     double      inner_path_rows = inner_path->rows;
    4313      900444 :     double      inner_path_rows_total = inner_path_rows;
    4314      900444 :     int         num_hashclauses = list_length(hashclauses);
    4315             :     int         numbuckets;
    4316             :     int         numbatches;
    4317             :     int         num_skew_mcvs;
    4318             :     size_t      space_allowed;  /* unused */
    4319      900444 :     uint64      enable_mask = PGS_HASHJOIN;
    4320             : 
    4321      900444 :     if (outer_path->parallel_workers == 0)
    4322      752596 :         enable_mask |= PGS_CONSIDER_NONPARTIAL;
    4323             : 
    4324             :     /* Count up disabled nodes. */
    4325      900444 :     disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
    4326      900444 :     disabled_nodes += inner_path->disabled_nodes;
    4327      900444 :     disabled_nodes += outer_path->disabled_nodes;
    4328             : 
    4329             :     /* cost of source data */
    4330      900444 :     startup_cost += outer_path->startup_cost;
    4331      900444 :     run_cost += outer_path->total_cost - outer_path->startup_cost;
    4332      900444 :     startup_cost += inner_path->total_cost;
    4333             : 
    4334             :     /*
    4335             :      * Cost of computing hash function: must do it once per input tuple. We
    4336             :      * charge one cpu_operator_cost for each column's hash function.  Also,
    4337             :      * tack on one cpu_tuple_cost per inner row, to model the costs of
    4338             :      * inserting the row into the hashtable.
    4339             :      *
    4340             :      * XXX when a hashclause is more complex than a single operator, we really
    4341             :      * should charge the extra eval costs of the left or right side, as
    4342             :      * appropriate, here.  This seems more work than it's worth at the moment.
    4343             :      */
    4344      900444 :     startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
    4345      900444 :         * inner_path_rows;
    4346      900444 :     run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
    4347             : 
    4348             :     /*
    4349             :      * If this is a parallel hash build, then the value we have for
    4350             :      * inner_rows_total currently refers only to the rows returned by each
    4351             :      * participant.  For shared hash table size estimation, we need the total
    4352             :      * number, so we need to undo the division.
    4353             :      */
    4354      900444 :     if (parallel_hash)
    4355       75186 :         inner_path_rows_total *= get_parallel_divisor(inner_path);
    4356             : 
    4357             :     /*
    4358             :      * Get hash table size that executor would use for inner relation.
    4359             :      *
    4360             :      * XXX for the moment, always assume that skew optimization will be
    4361             :      * performed.  As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
    4362             :      * trying to determine that for sure.
    4363             :      *
    4364             :      * XXX at some point it might be interesting to try to account for skew
    4365             :      * optimization in the cost estimate, but for now, we don't.
    4366             :      */
    4367      900444 :     ExecChooseHashTableSize(inner_path_rows_total,
    4368      900444 :                             inner_path->pathtarget->width,
    4369             :                             true,   /* useskew */
    4370             :                             parallel_hash,  /* try_combined_hash_mem */
    4371             :                             outer_path->parallel_workers,
    4372             :                             &space_allowed,
    4373             :                             &numbuckets,
    4374             :                             &numbatches,
    4375             :                             &num_skew_mcvs);
    4376             : 
    4377             :     /*
    4378             :      * If inner relation is too big then we will need to "batch" the join,
    4379             :      * which implies writing and reading most of the tuples to disk an extra
    4380             :      * time.  Charge seq_page_cost per page, since the I/O should be nice and
    4381             :      * sequential.  Writing the inner rel counts as startup cost, all the rest
    4382             :      * as run cost.
    4383             :      */
    4384      900444 :     if (numbatches > 1)
    4385             :     {
    4386        4790 :         double      outerpages = page_size(outer_path_rows,
    4387        4790 :                                            outer_path->pathtarget->width);
    4388        4790 :         double      innerpages = page_size(inner_path_rows,
    4389        4790 :                                            inner_path->pathtarget->width);
    4390             : 
    4391        4790 :         startup_cost += seq_page_cost * innerpages;
    4392        4790 :         run_cost += seq_page_cost * (innerpages + 2 * outerpages);
    4393             :     }
    4394             : 
    4395             :     /* CPU costs left for later */
    4396             : 
    4397             :     /* Public result fields */
    4398      900444 :     workspace->disabled_nodes = disabled_nodes;
    4399      900444 :     workspace->startup_cost = startup_cost;
    4400      900444 :     workspace->total_cost = startup_cost + run_cost;
    4401             :     /* Save private data for final_cost_hashjoin */
    4402      900444 :     workspace->run_cost = run_cost;
    4403      900444 :     workspace->numbuckets = numbuckets;
    4404      900444 :     workspace->numbatches = numbatches;
    4405      900444 :     workspace->inner_rows_total = inner_path_rows_total;
    4406      900444 : }
    4407             : 
    4408             : /*
    4409             :  * final_cost_hashjoin
    4410             :  *    Final estimate of the cost and result size of a hashjoin path.
    4411             :  *
    4412             :  * Note: the numbatches estimate is also saved into 'path' for use later
    4413             :  *
    4414             :  * 'path' is already filled in except for the rows and cost fields and
    4415             :  *      num_batches
    4416             :  * 'workspace' is the result from initial_cost_hashjoin
    4417             :  * 'extra' contains miscellaneous information about the join
    4418             :  */
    4419             : void
    4420      465420 : final_cost_hashjoin(PlannerInfo *root, HashPath *path,
    4421             :                     JoinCostWorkspace *workspace,
    4422             :                     JoinPathExtraData *extra)
    4423             : {
    4424      465420 :     Path       *outer_path = path->jpath.outerjoinpath;
    4425      465420 :     Path       *inner_path = path->jpath.innerjoinpath;
    4426      465420 :     double      outer_path_rows = outer_path->rows;
    4427      465420 :     double      inner_path_rows = inner_path->rows;
    4428      465420 :     double      inner_path_rows_total = workspace->inner_rows_total;
    4429      465420 :     List       *hashclauses = path->path_hashclauses;
    4430      465420 :     Cost        startup_cost = workspace->startup_cost;
    4431      465420 :     Cost        run_cost = workspace->run_cost;
    4432      465420 :     int         numbuckets = workspace->numbuckets;
    4433      465420 :     int         numbatches = workspace->numbatches;
    4434             :     Cost        cpu_per_tuple;
    4435             :     QualCost    hash_qual_cost;
    4436             :     QualCost    qp_qual_cost;
    4437             :     double      hashjointuples;
    4438             :     double      virtualbuckets;
    4439             :     Selectivity innerbucketsize;
    4440             :     Selectivity innermcvfreq;
    4441             :     ListCell   *hcl;
    4442             : 
    4443             :     /* Set the number of disabled nodes. */
    4444      465420 :     path->jpath.path.disabled_nodes = workspace->disabled_nodes;
    4445             : 
    4446             :     /* Mark the path with the correct row estimate */
    4447      465420 :     if (path->jpath.path.param_info)
    4448        3668 :         path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
    4449             :     else
    4450      461752 :         path->jpath.path.rows = path->jpath.path.parent->rows;
    4451             : 
    4452             :     /* For partial paths, scale row estimate. */
    4453      465420 :     if (path->jpath.path.parallel_workers > 0)
    4454             :     {
    4455      107144 :         double      parallel_divisor = get_parallel_divisor(&path->jpath.path);
    4456             : 
    4457      107144 :         path->jpath.path.rows =
    4458      107144 :             clamp_row_est(path->jpath.path.rows / parallel_divisor);
    4459             :     }
    4460             : 
    4461             :     /* mark the path with estimated # of batches */
    4462      465420 :     path->num_batches = numbatches;
    4463             : 
    4464             :     /* store the total number of tuples (sum of partial row estimates) */
    4465      465420 :     path->inner_rows_total = inner_path_rows_total;
    4466             : 
    4467             :     /* and compute the number of "virtual" buckets in the whole join */
    4468      465420 :     virtualbuckets = (double) numbuckets * (double) numbatches;
    4469             : 
    4470             :     /*
    4471             :      * Determine bucketsize fraction and MCV frequency for the inner relation.
    4472             :      * We use the smallest bucketsize or MCV frequency estimated for any
    4473             :      * individual hashclause; this is undoubtedly conservative.
    4474             :      *
    4475             :      * BUT: if inner relation has been unique-ified, we can assume it's good
    4476             :      * for hashing.  This is important both because it's the right answer, and
    4477             :      * because we avoid contaminating the cache with a value that's wrong for
    4478             :      * non-unique-ified paths.
    4479             :      */
    4480      465420 :     if (RELATION_WAS_MADE_UNIQUE(inner_path->parent, extra->sjinfo,
    4481             :                                  path->jpath.jointype))
    4482             :     {
    4483        4476 :         innerbucketsize = 1.0 / virtualbuckets;
    4484        4476 :         innermcvfreq = 1.0 / inner_path_rows_total;
    4485             :     }
    4486             :     else
    4487             :     {
    4488             :         List       *otherclauses;
    4489             : 
    4490      460944 :         innerbucketsize = 1.0;
    4491      460944 :         innermcvfreq = 1.0;
    4492             : 
    4493             :         /* At first, try to estimate bucket size using extended statistics. */
    4494      460944 :         otherclauses = estimate_multivariate_bucketsize(root,
    4495             :                                                         inner_path->parent,
    4496             :                                                         hashclauses,
    4497             :                                                         &innerbucketsize);
    4498             : 
    4499             :         /* Pass through the remaining clauses */
    4500      959226 :         foreach(hcl, otherclauses)
    4501             :         {
    4502      498282 :             RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
    4503             :             Selectivity thisbucketsize;
    4504             :             Selectivity thismcvfreq;
    4505             : 
    4506             :             /*
    4507             :              * First we have to figure out which side of the hashjoin clause
    4508             :              * is the inner side.
    4509             :              *
    4510             :              * Since we tend to visit the same clauses over and over when
    4511             :              * planning a large query, we cache the bucket stats estimates in
    4512             :              * the RestrictInfo node to avoid repeated lookups of statistics.
    4513             :              */
    4514      498282 :             if (bms_is_subset(restrictinfo->right_relids,
    4515      498282 :                               inner_path->parent->relids))
    4516             :             {
    4517             :                 /* righthand side is inner */
    4518      258760 :                 thisbucketsize = restrictinfo->right_bucketsize;
    4519      258760 :                 if (thisbucketsize < 0)
    4520             :                 {
    4521             :                     /* not cached yet */
    4522      111656 :                     estimate_hash_bucket_stats(root,
    4523      111656 :                                                get_rightop(restrictinfo->clause),
    4524             :                                                virtualbuckets,
    4525             :                                                &restrictinfo->right_mcvfreq,
    4526             :                                                &restrictinfo->right_bucketsize);
    4527      111656 :                     thisbucketsize = restrictinfo->right_bucketsize;
    4528             :                 }
    4529      258760 :                 thismcvfreq = restrictinfo->right_mcvfreq;
    4530             :             }
    4531             :             else
    4532             :             {
    4533             :                 Assert(bms_is_subset(restrictinfo->left_relids,
    4534             :                                      inner_path->parent->relids));
    4535             :                 /* lefthand side is inner */
    4536      239522 :                 thisbucketsize = restrictinfo->left_bucketsize;
    4537      239522 :                 if (thisbucketsize < 0)
    4538             :                 {
    4539             :                     /* not cached yet */
    4540       95658 :                     estimate_hash_bucket_stats(root,
    4541       95658 :                                                get_leftop(restrictinfo->clause),
    4542             :                                                virtualbuckets,
    4543             :                                                &restrictinfo->left_mcvfreq,
    4544             :                                                &restrictinfo->left_bucketsize);
    4545       95658 :                     thisbucketsize = restrictinfo->left_bucketsize;
    4546             :                 }
    4547      239522 :                 thismcvfreq = restrictinfo->left_mcvfreq;
    4548             :             }
    4549             : 
    4550      498282 :             if (innerbucketsize > thisbucketsize)
    4551      365546 :                 innerbucketsize = thisbucketsize;
    4552             :             /* Disregard zero for MCV freq, it means we have no data */
    4553      498282 :             if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq)
    4554      369432 :                 innermcvfreq = thismcvfreq;
    4555             :         }
    4556             :     }
    4557             : 
    4558             :     /*
    4559             :      * If the bucket holding the inner MCV would exceed hash_mem, we don't
    4560             :      * want to hash unless there is really no other alternative, so apply
    4561             :      * disable_cost.  (The executor normally copes with excessive memory usage
    4562             :      * by splitting batches, but obviously it cannot separate equal values
    4563             :      * that way, so it will be unable to drive the batch size below hash_mem
    4564             :      * when this is true.)
    4565             :      */
    4566      465420 :     if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
    4567      930840 :                            inner_path->pathtarget->width) > get_hash_memory_limit())
    4568         116 :         startup_cost += disable_cost;
    4569             : 
    4570             :     /*
    4571             :      * Compute cost of the hashquals and qpquals (other restriction clauses)
    4572             :      * separately.
    4573             :      */
    4574      465420 :     cost_qual_eval(&hash_qual_cost, hashclauses, root);
    4575      465420 :     cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
    4576      465420 :     qp_qual_cost.startup -= hash_qual_cost.startup;
    4577      465420 :     qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
    4578             : 
    4579             :     /* CPU costs */
    4580             : 
    4581      465420 :     if (path->jpath.jointype == JOIN_SEMI ||
    4582      459056 :         path->jpath.jointype == JOIN_ANTI ||
    4583      454484 :         extra->inner_unique)
    4584      127718 :     {
    4585             :         double      outer_matched_rows;
    4586             :         Selectivity inner_scan_frac;
    4587             : 
    4588             :         /*
    4589             :          * With a SEMI or ANTI join, or if the innerrel is known unique, the
    4590             :          * executor will stop after the first match.
    4591             :          *
    4592             :          * For an outer-rel row that has at least one match, we can expect the
    4593             :          * bucket scan to stop after a fraction 1/(match_count+1) of the
    4594             :          * bucket's rows, if the matches are evenly distributed.  Since they
    4595             :          * probably aren't quite evenly distributed, we apply a fuzz factor of
    4596             :          * 2.0 to that fraction.  (If we used a larger fuzz factor, we'd have
    4597             :          * to clamp inner_scan_frac to at most 1.0; but since match_count is
    4598             :          * at least 1, no such clamp is needed now.)
    4599             :          */
    4600      127718 :         outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
    4601      127718 :         inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
    4602             : 
    4603      127718 :         startup_cost += hash_qual_cost.startup;
    4604      255436 :         run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
    4605      127718 :             clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
    4606             : 
    4607             :         /*
    4608             :          * For unmatched outer-rel rows, the picture is quite a lot different.
    4609             :          * In the first place, there is no reason to assume that these rows
    4610             :          * preferentially hit heavily-populated buckets; instead assume they
    4611             :          * are uncorrelated with the inner distribution and so they see an
    4612             :          * average bucket size of inner_path_rows / virtualbuckets.  In the
    4613             :          * second place, it seems likely that they will have few if any exact
    4614             :          * hash-code matches and so very few of the tuples in the bucket will
    4615             :          * actually require eval of the hash quals.  We don't have any good
    4616             :          * way to estimate how many will, but for the moment assume that the
    4617             :          * effective cost per bucket entry is one-tenth what it is for
    4618             :          * matchable tuples.
    4619             :          */
    4620      255436 :         run_cost += hash_qual_cost.per_tuple *
    4621      255436 :             (outer_path_rows - outer_matched_rows) *
    4622      127718 :             clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
    4623             : 
    4624             :         /* Get # of tuples that will pass the basic join */
    4625      127718 :         if (path->jpath.jointype == JOIN_ANTI)
    4626        4572 :             hashjointuples = outer_path_rows - outer_matched_rows;
    4627             :         else
    4628      123146 :             hashjointuples = outer_matched_rows;
    4629             :     }
    4630             :     else
    4631             :     {
    4632             :         /*
    4633             :          * The number of tuple comparisons needed is the number of outer
    4634             :          * tuples times the typical number of tuples in a hash bucket, which
    4635             :          * is the inner relation size times its bucketsize fraction.  At each
    4636             :          * one, we need to evaluate the hashjoin quals.  But actually,
    4637             :          * charging the full qual eval cost at each tuple is pessimistic,
    4638             :          * since we don't evaluate the quals unless the hash values match
    4639             :          * exactly.  For lack of a better idea, halve the cost estimate to
    4640             :          * allow for that.
    4641             :          */
    4642      337702 :         startup_cost += hash_qual_cost.startup;
    4643      675404 :         run_cost += hash_qual_cost.per_tuple * outer_path_rows *
    4644      337702 :             clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
    4645             : 
    4646             :         /*
    4647             :          * Get approx # tuples passing the hashquals.  We use
    4648             :          * approx_tuple_count here because we need an estimate done with
    4649             :          * JOIN_INNER semantics.
    4650             :          */
    4651      337702 :         hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
    4652             :     }
    4653             : 
    4654             :     /*
    4655             :      * For each tuple that gets through the hashjoin proper, we charge
    4656             :      * cpu_tuple_cost plus the cost of evaluating additional restriction
    4657             :      * clauses that are to be applied at the join.  (This is pessimistic since
    4658             :      * not all of the quals may get evaluated at each tuple.)
    4659             :      */
    4660      465420 :     startup_cost += qp_qual_cost.startup;
    4661      465420 :     cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
    4662      465420 :     run_cost += cpu_per_tuple * hashjointuples;
    4663             : 
    4664             :     /* tlist eval costs are paid per output row, not per tuple scanned */
    4665      465420 :     startup_cost += path->jpath.path.pathtarget->cost.startup;
    4666      465420 :     run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
    4667             : 
    4668      465420 :     path->jpath.path.startup_cost = startup_cost;
    4669      465420 :     path->jpath.path.total_cost = startup_cost + run_cost;
    4670      465420 : }
    4671             : 
    4672             : 
    4673             : /*
    4674             :  * cost_subplan
    4675             :  *      Figure the costs for a SubPlan (or initplan).
    4676             :  *
    4677             :  * Note: we could dig the subplan's Plan out of the root list, but in practice
    4678             :  * all callers have it handy already, so we make them pass it.
    4679             :  */
    4680             : void
    4681       44336 : cost_subplan(PlannerInfo *root, SubPlan *subplan, Plan *plan)
    4682             : {
    4683             :     QualCost    sp_cost;
    4684             : 
    4685             :     /*
    4686             :      * Figure any cost for evaluating the testexpr.
    4687             :      *
    4688             :      * Usually, SubPlan nodes are built very early, before we have constructed
    4689             :      * any RelOptInfos for the parent query level, which means the parent root
    4690             :      * does not yet contain enough information to safely consult statistics.
    4691             :      * Therefore, we pass root as NULL here.  cost_qual_eval() is already
    4692             :      * well-equipped to handle a NULL root.
    4693             :      *
    4694             :      * One exception is SubPlan nodes built for the initplans of MIN/MAX
    4695             :      * aggregates from indexes (cf. SS_make_initplan_from_plan).  In this
    4696             :      * case, having a NULL root is safe because testexpr will be NULL.
    4697             :      * Besides, an initplan will by definition not consult anything from the
    4698             :      * parent plan.
    4699             :      */
    4700       44336 :     cost_qual_eval(&sp_cost,
    4701       44336 :                    make_ands_implicit((Expr *) subplan->testexpr),
    4702             :                    NULL);
    4703             : 
    4704       44336 :     if (subplan->useHashTable)
    4705             :     {
    4706             :         /*
    4707             :          * If we are using a hash table for the subquery outputs, then the
    4708             :          * cost of evaluating the query is a one-time cost.  We charge one
    4709             :          * cpu_operator_cost per tuple for the work of loading the hashtable,
    4710             :          * too.
    4711             :          */
    4712        2128 :         sp_cost.startup += plan->total_cost +
    4713        2128 :             cpu_operator_cost * plan->plan_rows;
    4714             : 
    4715             :         /*
    4716             :          * The per-tuple costs include the cost of evaluating the lefthand
    4717             :          * expressions, plus the cost of probing the hashtable.  We already
    4718             :          * accounted for the lefthand expressions as part of the testexpr, and
    4719             :          * will also have counted one cpu_operator_cost for each comparison
    4720             :          * operator.  That is probably too low for the probing cost, but it's
    4721             :          * hard to make a better estimate, so live with it for now.
    4722             :          */
    4723             :     }
    4724             :     else
    4725             :     {
    4726             :         /*
    4727             :          * Otherwise we will be rescanning the subplan output on each
    4728             :          * evaluation.  We need to estimate how much of the output we will
    4729             :          * actually need to scan.  NOTE: this logic should agree with the
    4730             :          * tuple_fraction estimates used by make_subplan() in
    4731             :          * plan/subselect.c.
    4732             :          */
    4733       42208 :         Cost        plan_run_cost = plan->total_cost - plan->startup_cost;
    4734             : 
    4735       42208 :         if (subplan->subLinkType == EXISTS_SUBLINK)
    4736             :         {
    4737             :             /* we only need to fetch 1 tuple; clamp to avoid zero divide */
    4738        2576 :             sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
    4739             :         }
    4740       39632 :         else if (subplan->subLinkType == ALL_SUBLINK ||
    4741       39614 :                  subplan->subLinkType == ANY_SUBLINK)
    4742             :         {
    4743             :             /* assume we need 50% of the tuples */
    4744         146 :             sp_cost.per_tuple += 0.50 * plan_run_cost;
    4745             :             /* also charge a cpu_operator_cost per row examined */
    4746         146 :             sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
    4747             :         }
    4748             :         else
    4749             :         {
    4750             :             /* assume we need all tuples */
    4751       39486 :             sp_cost.per_tuple += plan_run_cost;
    4752             :         }
    4753             : 
    4754             :         /*
    4755             :          * Also account for subplan's startup cost. If the subplan is
    4756             :          * uncorrelated or undirect correlated, AND its topmost node is one
    4757             :          * that materializes its output, assume that we'll only need to pay
    4758             :          * its startup cost once; otherwise assume we pay the startup cost
    4759             :          * every time.
    4760             :          */
    4761       55598 :         if (subplan->parParam == NIL &&
    4762       13390 :             ExecMaterializesOutput(nodeTag(plan)))
    4763         774 :             sp_cost.startup += plan->startup_cost;
    4764             :         else
    4765       41434 :             sp_cost.per_tuple += plan->startup_cost;
    4766             :     }
    4767             : 
    4768       44336 :     subplan->startup_cost = sp_cost.startup;
    4769       44336 :     subplan->per_call_cost = sp_cost.per_tuple;
    4770       44336 : }
    4771             : 
    4772             : 
    4773             : /*
    4774             :  * cost_rescan
    4775             :  *      Given a finished Path, estimate the costs of rescanning it after
    4776             :  *      having done so the first time.  For some Path types a rescan is
    4777             :  *      cheaper than an original scan (if no parameters change), and this
    4778             :  *      function embodies knowledge about that.  The default is to return
    4779             :  *      the same costs stored in the Path.  (Note that the cost estimates
    4780             :  *      actually stored in Paths are always for first scans.)
    4781             :  *
    4782             :  * This function is not currently intended to model effects such as rescans
    4783             :  * being cheaper due to disk block caching; what we are concerned with is
    4784             :  * plan types wherein the executor caches results explicitly, or doesn't
    4785             :  * redo startup calculations, etc.
    4786             :  */
    4787             : static void
    4788     3386462 : cost_rescan(PlannerInfo *root, Path *path,
    4789             :             Cost *rescan_startup_cost,  /* output parameters */
    4790             :             Cost *rescan_total_cost)
    4791             : {
    4792     3386462 :     switch (path->pathtype)
    4793             :     {
    4794       53980 :         case T_FunctionScan:
    4795             : 
    4796             :             /*
    4797             :              * Currently, nodeFunctionscan.c always executes the function to
    4798             :              * completion before returning any rows, and caches the results in
    4799             :              * a tuplestore.  So the function eval cost is all startup cost
    4800             :              * and isn't paid over again on rescans. However, all run costs
    4801             :              * will be paid over again.
    4802             :              */
    4803       53980 :             *rescan_startup_cost = 0;
    4804       53980 :             *rescan_total_cost = path->total_cost - path->startup_cost;
    4805       53980 :             break;
    4806      133860 :         case T_HashJoin:
    4807             : 
    4808             :             /*
    4809             :              * If it's a single-batch join, we don't need to rebuild the hash
    4810             :              * table during a rescan.
    4811             :              */
    4812      133860 :             if (((HashPath *) path)->num_batches == 1)
    4813             :             {
    4814             :                 /* Startup cost is exactly the cost of hash table building */
    4815      133860 :                 *rescan_startup_cost = 0;
    4816      133860 :                 *rescan_total_cost = path->total_cost - path->startup_cost;
    4817             :             }
    4818             :             else
    4819             :             {
    4820             :                 /* Otherwise, no special treatment */
    4821           0 :                 *rescan_startup_cost = path->startup_cost;
    4822           0 :                 *rescan_total_cost = path->total_cost;
    4823             :             }
    4824      133860 :             break;
    4825        8142 :         case T_CteScan:
    4826             :         case T_WorkTableScan:
    4827             :             {
    4828             :                 /*
    4829             :                  * These plan types materialize their final result in a
    4830             :                  * tuplestore or tuplesort object.  So the rescan cost is only
    4831             :                  * cpu_tuple_cost per tuple, unless the result is large enough
    4832             :                  * to spill to disk.
    4833             :                  */
    4834        8142 :                 Cost        run_cost = cpu_tuple_cost * path->rows;
    4835        8142 :                 double      nbytes = relation_byte_size(path->rows,
    4836        8142 :                                                         path->pathtarget->width);
    4837        8142 :                 double      work_mem_bytes = work_mem * (Size) 1024;
    4838             : 
    4839        8142 :                 if (nbytes > work_mem_bytes)
    4840             :                 {
    4841             :                     /* It will spill, so account for re-read cost */
    4842         368 :                     double      npages = ceil(nbytes / BLCKSZ);
    4843             : 
    4844         368 :                     run_cost += seq_page_cost * npages;
    4845             :                 }
    4846        8142 :                 *rescan_startup_cost = 0;
    4847        8142 :                 *rescan_total_cost = run_cost;
    4848             :             }
    4849        8142 :             break;
    4850     1222530 :         case T_Material:
    4851             :         case T_Sort:
    4852             :             {
    4853             :                 /*
    4854             :                  * These plan types not only materialize their results, but do
    4855             :                  * not implement qual filtering or projection.  So they are
    4856             :                  * even cheaper to rescan than the ones above.  We charge only
    4857             :                  * cpu_operator_cost per tuple.  (Note: keep that in sync with
    4858             :                  * the run_cost charge in cost_sort, and also see comments in
    4859             :                  * cost_material before you change it.)
    4860             :                  */
    4861     1222530 :                 Cost        run_cost = cpu_operator_cost * path->rows;
    4862     1222530 :                 double      nbytes = relation_byte_size(path->rows,
    4863     1222530 :                                                         path->pathtarget->width);
    4864     1222530 :                 double      work_mem_bytes = work_mem * (Size) 1024;
    4865             : 
    4866     1222530 :                 if (nbytes > work_mem_bytes)
    4867             :                 {
    4868             :                     /* It will spill, so account for re-read cost */
    4869       10150 :                     double      npages = ceil(nbytes / BLCKSZ);
    4870             : 
    4871       10150 :                     run_cost += seq_page_cost * npages;
    4872             :                 }
    4873     1222530 :                 *rescan_startup_cost = 0;
    4874     1222530 :                 *rescan_total_cost = run_cost;
    4875             :             }
    4876     1222530 :             break;
    4877      297590 :         case T_Memoize:
    4878             :             /* All the hard work is done by cost_memoize_rescan */
    4879      297590 :             cost_memoize_rescan(root, (MemoizePath *) path,
    4880             :                                 rescan_startup_cost, rescan_total_cost);
    4881      297590 :             break;
    4882     1670360 :         default:
    4883     1670360 :             *rescan_startup_cost = path->startup_cost;
    4884     1670360 :             *rescan_total_cost = path->total_cost;
    4885     1670360 :             break;
    4886             :     }
    4887     3386462 : }
    4888             : 
    4889             : 
    4890             : /*
    4891             :  * cost_qual_eval
    4892             :  *      Estimate the CPU costs of evaluating a WHERE clause.
    4893             :  *      The input can be either an implicitly-ANDed list of boolean
    4894             :  *      expressions, or a list of RestrictInfo nodes.  (The latter is
    4895             :  *      preferred since it allows caching of the results.)
    4896             :  *      The result includes both a one-time (startup) component,
    4897             :  *      and a per-evaluation component.
    4898             :  *
    4899             :  * Note: in some code paths root can be passed as NULL, resulting in
    4900             :  * slightly worse estimates.
    4901             :  */
    4902             : void
    4903     4801972 : cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
    4904             : {
    4905             :     cost_qual_eval_context context;
    4906             :     ListCell   *l;
    4907             : 
    4908     4801972 :     context.root = root;
    4909     4801972 :     context.total.startup = 0;
    4910     4801972 :     context.total.per_tuple = 0;
    4911             : 
    4912             :     /* We don't charge any cost for the implicit ANDing at top level ... */
    4913             : 
    4914     9144806 :     foreach(l, quals)
    4915             :     {
    4916     4342834 :         Node       *qual = (Node *) lfirst(l);
    4917             : 
    4918     4342834 :         cost_qual_eval_walker(qual, &context);
    4919             :     }
    4920             : 
    4921     4801972 :     *cost = context.total;
    4922     4801972 : }
    4923             : 
    4924             : /*
    4925             :  * cost_qual_eval_node
    4926             :  *      As above, for a single RestrictInfo or expression.
    4927             :  */
    4928             : void
    4929     1897558 : cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
    4930             : {
    4931             :     cost_qual_eval_context context;
    4932             : 
    4933     1897558 :     context.root = root;
    4934     1897558 :     context.total.startup = 0;
    4935     1897558 :     context.total.per_tuple = 0;
    4936             : 
    4937     1897558 :     cost_qual_eval_walker(qual, &context);
    4938             : 
    4939     1897558 :     *cost = context.total;
    4940     1897558 : }
    4941             : 
    4942             : static bool
    4943     9775244 : cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
    4944             : {
    4945     9775244 :     if (node == NULL)
    4946       95670 :         return false;
    4947             : 
    4948             :     /*
    4949             :      * RestrictInfo nodes contain an eval_cost field reserved for this
    4950             :      * routine's use, so that it's not necessary to evaluate the qual clause's
    4951             :      * cost more than once.  If the clause's cost hasn't been computed yet,
    4952             :      * the field's startup value will contain -1.
    4953             :      */
    4954     9679574 :     if (IsA(node, RestrictInfo))
    4955             :     {
    4956     4534470 :         RestrictInfo *rinfo = (RestrictInfo *) node;
    4957             : 
    4958     4534470 :         if (rinfo->eval_cost.startup < 0)
    4959             :         {
    4960             :             cost_qual_eval_context locContext;
    4961             : 
    4962      615812 :             locContext.root = context->root;
    4963      615812 :             locContext.total.startup = 0;
    4964      615812 :             locContext.total.per_tuple = 0;
    4965             : 
    4966             :             /*
    4967             :              * For an OR clause, recurse into the marked-up tree so that we
    4968             :              * set the eval_cost for contained RestrictInfos too.
    4969             :              */
    4970      615812 :             if (rinfo->orclause)
    4971       10056 :                 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
    4972             :             else
    4973      605756 :                 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
    4974             : 
    4975             :             /*
    4976             :              * If the RestrictInfo is marked pseudoconstant, it will be tested
    4977             :              * only once, so treat its cost as all startup cost.
    4978             :              */
    4979      615812 :             if (rinfo->pseudoconstant)
    4980             :             {
    4981             :                 /* count one execution during startup */
    4982       10310 :                 locContext.total.startup += locContext.total.per_tuple;
    4983       10310 :                 locContext.total.per_tuple = 0;
    4984             :             }
    4985      615812 :             rinfo->eval_cost = locContext.total;
    4986             :         }
    4987     4534470 :         context->total.startup += rinfo->eval_cost.startup;
    4988     4534470 :         context->total.per_tuple += rinfo->eval_cost.per_tuple;
    4989             :         /* do NOT recurse into children */
    4990     4534470 :         return false;
    4991             :     }
    4992             : 
    4993             :     /*
    4994             :      * For each operator or function node in the given tree, we charge the
    4995             :      * estimated execution cost given by pg_proc.procost (remember to multiply
    4996             :      * this by cpu_operator_cost).
    4997             :      *
    4998             :      * Vars and Consts are charged zero, and so are boolean operators (AND,
    4999             :      * OR, NOT). Simplistic, but a lot better than no model at all.
    5000             :      *
    5001             :      * Should we try to account for the possibility of short-circuit
    5002             :      * evaluation of AND/OR?  Probably *not*, because that would make the
    5003             :      * results depend on the clause ordering, and we are not in any position
    5004             :      * to expect that the current ordering of the clauses is the one that's
    5005             :      * going to end up being used.  The above per-RestrictInfo caching would
    5006             :      * not mix well with trying to re-order clauses anyway.
    5007             :      *
    5008             :      * Another issue that is entirely ignored here is that if a set-returning
    5009             :      * function is below top level in the tree, the functions/operators above
    5010             :      * it will need to be evaluated multiple times.  In practical use, such
    5011             :      * cases arise so seldom as to not be worth the added complexity needed;
    5012             :      * moreover, since our rowcount estimates for functions tend to be pretty
    5013             :      * phony, the results would also be pretty phony.
    5014             :      */
    5015     5145104 :     if (IsA(node, FuncExpr))
    5016             :     {
    5017      349630 :         add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
    5018             :                           &context->total);
    5019             :     }
    5020     4795474 :     else if (IsA(node, OpExpr) ||
    5021     4124022 :              IsA(node, DistinctExpr) ||
    5022     4122938 :              IsA(node, NullIfExpr))
    5023             :     {
    5024             :         /* rely on struct equivalence to treat these all alike */
    5025      672660 :         set_opfuncid((OpExpr *) node);
    5026      672660 :         add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
    5027             :                           &context->total);
    5028             :     }
    5029     4122814 :     else if (IsA(node, ScalarArrayOpExpr))
    5030             :     {
    5031       45482 :         ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
    5032       45482 :         Node       *arraynode = (Node *) lsecond(saop->args);
    5033             :         QualCost    sacosts;
    5034             :         QualCost    hcosts;
    5035       45482 :         double      estarraylen = estimate_array_length(context->root, arraynode);
    5036             : 
    5037       45482 :         set_sa_opfuncid(saop);
    5038       45482 :         sacosts.startup = sacosts.per_tuple = 0;
    5039       45482 :         add_function_cost(context->root, saop->opfuncid, NULL,
    5040             :                           &sacosts);
    5041             : 
    5042       45482 :         if (OidIsValid(saop->hashfuncid))
    5043             :         {
    5044             :             /* Handle costs for hashed ScalarArrayOpExpr */
    5045         430 :             hcosts.startup = hcosts.per_tuple = 0;
    5046             : 
    5047         430 :             add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
    5048         430 :             context->total.startup += sacosts.startup + hcosts.startup;
    5049             : 
    5050             :             /* Estimate the cost of building the hashtable. */
    5051         430 :             context->total.startup += estarraylen * hcosts.per_tuple;
    5052             : 
    5053             :             /*
    5054             :              * XXX should we charge a little bit for sacosts.per_tuple when
    5055             :              * building the table, or is it ok to assume there will be zero
    5056             :              * hash collision?
    5057             :              */
    5058             : 
    5059             :             /*
    5060             :              * Charge for hashtable lookups.  Charge a single hash and a
    5061             :              * single comparison.
    5062             :              */
    5063         430 :             context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
    5064             :         }
    5065             :         else
    5066             :         {
    5067             :             /*
    5068             :              * Estimate that the operator will be applied to about half of the
    5069             :              * array elements before the answer is determined.
    5070             :              */
    5071       45052 :             context->total.startup += sacosts.startup;
    5072       90104 :             context->total.per_tuple += sacosts.per_tuple *
    5073       45052 :                 estimate_array_length(context->root, arraynode) * 0.5;
    5074             :         }
    5075             :     }
    5076     4077332 :     else if (IsA(node, Aggref) ||
    5077     4004342 :              IsA(node, WindowFunc))
    5078             :     {
    5079             :         /*
    5080             :          * Aggref and WindowFunc nodes are (and should be) treated like Vars,
    5081             :          * ie, zero execution cost in the current model, because they behave
    5082             :          * essentially like Vars at execution.  We disregard the costs of
    5083             :          * their input expressions for the same reason.  The actual execution
    5084             :          * costs of the aggregate/window functions and their arguments have to
    5085             :          * be factored into plan-node-specific costing of the Agg or WindowAgg
    5086             :          * plan node.
    5087             :          */
    5088       76868 :         return false;           /* don't recurse into children */
    5089             :     }
    5090     4000464 :     else if (IsA(node, GroupingFunc))
    5091             :     {
    5092             :         /* Treat this as having cost 1 */
    5093         430 :         context->total.per_tuple += cpu_operator_cost;
    5094         430 :         return false;           /* don't recurse into children */
    5095             :     }
    5096     4000034 :     else if (IsA(node, CoerceViaIO))
    5097             :     {
    5098       22808 :         CoerceViaIO *iocoerce = (CoerceViaIO *) node;
    5099             :         Oid         iofunc;
    5100             :         Oid         typioparam;
    5101             :         bool        typisvarlena;
    5102             : 
    5103             :         /* check the result type's input function */
    5104       22808 :         getTypeInputInfo(iocoerce->resulttype,
    5105             :                          &iofunc, &typioparam);
    5106       22808 :         add_function_cost(context->root, iofunc, NULL,
    5107             :                           &context->total);
    5108             :         /* check the input type's output function */
    5109       22808 :         getTypeOutputInfo(exprType((Node *) iocoerce->arg),
    5110             :                           &iofunc, &typisvarlena);
    5111       22808 :         add_function_cost(context->root, iofunc, NULL,
    5112             :                           &context->total);
    5113             :     }
    5114     3977226 :     else if (IsA(node, ArrayCoerceExpr))
    5115             :     {
    5116        5210 :         ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
    5117             :         QualCost    perelemcost;
    5118             : 
    5119        5210 :         cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
    5120             :                             context->root);
    5121        5210 :         context->total.startup += perelemcost.startup;
    5122        5210 :         if (perelemcost.per_tuple > 0)
    5123          66 :             context->total.per_tuple += perelemcost.per_tuple *
    5124          66 :                 estimate_array_length(context->root, (Node *) acoerce->arg);
    5125             :     }
    5126     3972016 :     else if (IsA(node, RowCompareExpr))
    5127             :     {
    5128             :         /* Conservatively assume we will check all the columns */
    5129         252 :         RowCompareExpr *rcexpr = (RowCompareExpr *) node;
    5130             :         ListCell   *lc;
    5131             : 
    5132         810 :         foreach(lc, rcexpr->opnos)
    5133             :         {
    5134         558 :             Oid         opid = lfirst_oid(lc);
    5135             : 
    5136         558 :             add_function_cost(context->root, get_opcode(opid), NULL,
    5137             :                               &context->total);
    5138             :         }
    5139             :     }
    5140     3971764 :     else if (IsA(node, MinMaxExpr) ||
    5141     3971486 :              IsA(node, SQLValueFunction) ||
    5142     3966692 :              IsA(node, XmlExpr) ||
    5143     3965990 :              IsA(node, CoerceToDomain) ||
    5144     3956132 :              IsA(node, NextValueExpr) ||
    5145     3955736 :              IsA(node, JsonExpr))
    5146             :     {
    5147             :         /* Treat all these as having cost 1 */
    5148       18600 :         context->total.per_tuple += cpu_operator_cost;
    5149             :     }
    5150     3953164 :     else if (IsA(node, SubLink))
    5151             :     {
    5152             :         /* This routine should not be applied to un-planned expressions */
    5153           0 :         elog(ERROR, "cannot handle unplanned sub-select");
    5154             :     }
    5155     3953164 :     else if (IsA(node, SubPlan))
    5156             :     {
    5157             :         /*
    5158             :          * A subplan node in an expression typically indicates that the
    5159             :          * subplan will be executed on each evaluation, so charge accordingly.
    5160             :          * (Sub-selects that can be executed as InitPlans have already been
    5161             :          * removed from the expression.)
    5162             :          */
    5163       43828 :         SubPlan    *subplan = (SubPlan *) node;
    5164             : 
    5165       43828 :         context->total.startup += subplan->startup_cost;
    5166       43828 :         context->total.per_tuple += subplan->per_call_cost;
    5167             : 
    5168             :         /*
    5169             :          * We don't want to recurse into the testexpr, because it was already
    5170             :          * counted in the SubPlan node's costs.  So we're done.
    5171             :          */
    5172       43828 :         return false;
    5173             :     }
    5174     3909336 :     else if (IsA(node, AlternativeSubPlan))
    5175             :     {
    5176             :         /*
    5177             :          * Arbitrarily use the first alternative plan for costing.  (We should
    5178             :          * certainly only include one alternative, and we don't yet have
    5179             :          * enough information to know which one the executor is most likely to
    5180             :          * use.)
    5181             :          */
    5182        1860 :         AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
    5183             : 
    5184        1860 :         return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
    5185             :                                      context);
    5186             :     }
    5187     3907476 :     else if (IsA(node, PlaceHolderVar))
    5188             :     {
    5189             :         /*
    5190             :          * A PlaceHolderVar should be given cost zero when considering general
    5191             :          * expression evaluation costs.  The expense of doing the contained
    5192             :          * expression is charged as part of the tlist eval costs of the scan
    5193             :          * or join where the PHV is first computed (see set_rel_width and
    5194             :          * add_placeholders_to_joinrel).  If we charged it again here, we'd be
    5195             :          * double-counting the cost for each level of plan that the PHV
    5196             :          * bubbles up through.  Hence, return without recursing into the
    5197             :          * phexpr.
    5198             :          */
    5199        5636 :         return false;
    5200             :     }
    5201             : 
    5202             :     /* recurse into children */
    5203     5016482 :     return expression_tree_walker(node, cost_qual_eval_walker, context);
    5204             : }
    5205             : 
    5206             : /*
    5207             :  * get_restriction_qual_cost
    5208             :  *    Compute evaluation costs of a baserel's restriction quals, plus any
    5209             :  *    movable join quals that have been pushed down to the scan.
    5210             :  *    Results are returned into *qpqual_cost.
    5211             :  *
    5212             :  * This is a convenience subroutine that works for seqscans and other cases
    5213             :  * where all the given quals will be evaluated the hard way.  It's not useful
    5214             :  * for cost_index(), for example, where the index machinery takes care of
    5215             :  * some of the quals.  We assume baserestrictcost was previously set by
    5216             :  * set_baserel_size_estimates().
    5217             :  */
    5218             : static void
    5219     1126656 : get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel,
    5220             :                           ParamPathInfo *param_info,
    5221             :                           QualCost *qpqual_cost)
    5222             : {
    5223     1126656 :     if (param_info)
    5224             :     {
    5225             :         /* Include costs of pushed-down clauses */
    5226      251846 :         cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
    5227             : 
    5228      251846 :         qpqual_cost->startup += baserel->baserestrictcost.startup;
    5229      251846 :         qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
    5230             :     }
    5231             :     else
    5232      874810 :         *qpqual_cost = baserel->baserestrictcost;
    5233     1126656 : }
    5234             : 
    5235             : 
    5236             : /*
    5237             :  * compute_semi_anti_join_factors
    5238             :  *    Estimate how much of the inner input a SEMI, ANTI, or inner_unique join
    5239             :  *    can be expected to scan.
    5240             :  *
    5241             :  * In a hash or nestloop SEMI/ANTI join, the executor will stop scanning
    5242             :  * inner rows as soon as it finds a match to the current outer row.
    5243             :  * The same happens if we have detected the inner rel is unique.
    5244             :  * We should therefore adjust some of the cost components for this effect.
    5245             :  * This function computes some estimates needed for these adjustments.
    5246             :  * These estimates will be the same regardless of the particular paths used
    5247             :  * for the outer and inner relation, so we compute these once and then pass
    5248             :  * them to all the join cost estimation functions.
    5249             :  *
    5250             :  * Input parameters:
    5251             :  *  joinrel: join relation under consideration
    5252             :  *  outerrel: outer relation under consideration
    5253             :  *  innerrel: inner relation under consideration
    5254             :  *  jointype: if not JOIN_SEMI or JOIN_ANTI, we assume it's inner_unique
    5255             :  *  sjinfo: SpecialJoinInfo relevant to this join
    5256             :  *  restrictlist: join quals
    5257             :  * Output parameters:
    5258             :  *  *semifactors is filled in (see pathnodes.h for field definitions)
    5259             :  */
    5260             : void
    5261      223802 : compute_semi_anti_join_factors(PlannerInfo *root,
    5262             :                                RelOptInfo *joinrel,
    5263             :                                RelOptInfo *outerrel,
    5264             :                                RelOptInfo *innerrel,
    5265             :                                JoinType jointype,
    5266             :                                SpecialJoinInfo *sjinfo,
    5267             :                                List *restrictlist,
    5268             :                                SemiAntiJoinFactors *semifactors)
    5269             : {
    5270             :     Selectivity jselec;
    5271             :     Selectivity nselec;
    5272             :     Selectivity avgmatch;
    5273             :     SpecialJoinInfo norm_sjinfo;
    5274             :     List       *joinquals;
    5275             :     ListCell   *l;
    5276             : 
    5277             :     /*
    5278             :      * In an ANTI join, we must ignore clauses that are "pushed down", since
    5279             :      * those won't affect the match logic.  In a SEMI join, we do not
    5280             :      * distinguish joinquals from "pushed down" quals, so just use the whole
    5281             :      * restrictinfo list.  For other outer join types, we should consider only
    5282             :      * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
    5283             :      */
    5284      223802 :     if (IS_OUTER_JOIN(jointype))
    5285             :     {
    5286       77484 :         joinquals = NIL;
    5287      169254 :         foreach(l, restrictlist)
    5288             :         {
    5289       91770 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    5290             : 
    5291       91770 :             if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
    5292       86876 :                 joinquals = lappend(joinquals, rinfo);
    5293             :         }
    5294             :     }
    5295             :     else
    5296      146318 :         joinquals = restrictlist;
    5297             : 
    5298             :     /*
    5299             :      * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
    5300             :      */
    5301      223802 :     jselec = clauselist_selectivity(root,
    5302             :                                     joinquals,
    5303             :                                     0,
    5304             :                                     (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
    5305             :                                     sjinfo);
    5306             : 
    5307             :     /*
    5308             :      * Also get the normal inner-join selectivity of the join clauses.
    5309             :      */
    5310      223802 :     init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
    5311             : 
    5312      223802 :     nselec = clauselist_selectivity(root,
    5313             :                                     joinquals,
    5314             :                                     0,
    5315             :                                     JOIN_INNER,
    5316             :                                     &norm_sjinfo);
    5317             : 
    5318             :     /* Avoid leaking a lot of ListCells */
    5319      223802 :     if (IS_OUTER_JOIN(jointype))
    5320       77484 :         list_free(joinquals);
    5321             : 
    5322             :     /*
    5323             :      * jselec can be interpreted as the fraction of outer-rel rows that have
    5324             :      * any matches (this is true for both SEMI and ANTI cases).  And nselec is
    5325             :      * the fraction of the Cartesian product that matches.  So, the average
    5326             :      * number of matches for each outer-rel row that has at least one match is
    5327             :      * nselec * inner_rows / jselec.
    5328             :      *
    5329             :      * Note: it is correct to use the inner rel's "rows" count here, even
    5330             :      * though we might later be considering a parameterized inner path with
    5331             :      * fewer rows.  This is because we have included all the join clauses in
    5332             :      * the selectivity estimate.
    5333             :      */
    5334      223802 :     if (jselec > 0)              /* protect against zero divide */
    5335             :     {
    5336      223434 :         avgmatch = nselec * innerrel->rows / jselec;
    5337             :         /* Clamp to sane range */
    5338      223434 :         avgmatch = Max(1.0, avgmatch);
    5339             :     }
    5340             :     else
    5341         368 :         avgmatch = 1.0;
    5342             : 
    5343      223802 :     semifactors->outer_match_frac = jselec;
    5344      223802 :     semifactors->match_count = avgmatch;
    5345      223802 : }
    5346             : 
    5347             : /*
    5348             :  * has_indexed_join_quals
    5349             :  *    Check whether all the joinquals of a nestloop join are used as
    5350             :  *    inner index quals.
    5351             :  *
    5352             :  * If the inner path of a SEMI/ANTI join is an indexscan (including bitmap
    5353             :  * indexscan) that uses all the joinquals as indexquals, we can assume that an
    5354             :  * unmatched outer tuple is cheap to process, whereas otherwise it's probably
    5355             :  * expensive.
    5356             :  */
    5357             : static bool
    5358      955428 : has_indexed_join_quals(NestPath *path)
    5359             : {
    5360      955428 :     JoinPath   *joinpath = &path->jpath;
    5361      955428 :     Relids      joinrelids = joinpath->path.parent->relids;
    5362      955428 :     Path       *innerpath = joinpath->innerjoinpath;
    5363             :     List       *indexclauses;
    5364             :     bool        found_one;
    5365             :     ListCell   *lc;
    5366             : 
    5367             :     /* If join still has quals to evaluate, it's not fast */
    5368      955428 :     if (joinpath->joinrestrictinfo != NIL)
    5369      680398 :         return false;
    5370             :     /* Nor if the inner path isn't parameterized at all */
    5371      275030 :     if (innerpath->param_info == NULL)
    5372        3300 :         return false;
    5373             : 
    5374             :     /* Find the indexclauses list for the inner scan */
    5375      271730 :     switch (innerpath->pathtype)
    5376             :     {
    5377      166460 :         case T_IndexScan:
    5378             :         case T_IndexOnlyScan:
    5379      166460 :             indexclauses = ((IndexPath *) innerpath)->indexclauses;
    5380      166460 :             break;
    5381         270 :         case T_BitmapHeapScan:
    5382             :             {
    5383             :                 /* Accept only a simple bitmap scan, not AND/OR cases */
    5384         270 :                 Path       *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
    5385             : 
    5386         270 :                 if (IsA(bmqual, IndexPath))
    5387         222 :                     indexclauses = ((IndexPath *) bmqual)->indexclauses;
    5388             :                 else
    5389          48 :                     return false;
    5390         222 :                 break;
    5391             :             }
    5392      105000 :         default:
    5393             : 
    5394             :             /*
    5395             :              * If it's not a simple indexscan, it probably doesn't run quickly
    5396             :              * for zero rows out, even if it's a parameterized path using all
    5397             :              * the joinquals.
    5398             :              */
    5399      105000 :             return false;
    5400             :     }
    5401             : 
    5402             :     /*
    5403             :      * Examine the inner path's param clauses.  Any that are from the outer
    5404             :      * path must be found in the indexclauses list, either exactly or in an
    5405             :      * equivalent form generated by equivclass.c.  Also, we must find at least
    5406             :      * one such clause, else it's a clauseless join which isn't fast.
    5407             :      */
    5408      166682 :     found_one = false;
    5409      329156 :     foreach(lc, innerpath->param_info->ppi_clauses)
    5410             :     {
    5411      171304 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
    5412             : 
    5413      171304 :         if (join_clause_is_movable_into(rinfo,
    5414      171304 :                                         innerpath->parent->relids,
    5415             :                                         joinrelids))
    5416             :         {
    5417      170752 :             if (!is_redundant_with_indexclauses(rinfo, indexclauses))
    5418        8830 :                 return false;
    5419      161922 :             found_one = true;
    5420             :         }
    5421             :     }
    5422      157852 :     return found_one;
    5423             : }
    5424             : 
    5425             : 
    5426             : /*
    5427             :  * approx_tuple_count
    5428             :  *      Quick-and-dirty estimation of the number of join rows passing
    5429             :  *      a set of qual conditions.
    5430             :  *
    5431             :  * The quals can be either an implicitly-ANDed list of boolean expressions,
    5432             :  * or a list of RestrictInfo nodes (typically the latter).
    5433             :  *
    5434             :  * We intentionally compute the selectivity under JOIN_INNER rules, even
    5435             :  * if it's some type of outer join.  This is appropriate because we are
    5436             :  * trying to figure out how many tuples pass the initial merge or hash
    5437             :  * join step.
    5438             :  *
    5439             :  * This is quick-and-dirty because we bypass clauselist_selectivity, and
    5440             :  * simply multiply the independent clause selectivities together.  Now
    5441             :  * clauselist_selectivity often can't do any better than that anyhow, but
    5442             :  * for some situations (such as range constraints) it is smarter.  However,
    5443             :  * we can't effectively cache the results of clauselist_selectivity, whereas
    5444             :  * the individual clause selectivities can be and are cached.
    5445             :  *
    5446             :  * Since we are only using the results to estimate how many potential
    5447             :  * output tuples are generated and passed through qpqual checking, it
    5448             :  * seems OK to live with the approximation.
    5449             :  */
    5450             : static double
    5451      811074 : approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
    5452             : {
    5453             :     double      tuples;
    5454      811074 :     double      outer_tuples = path->outerjoinpath->rows;
    5455      811074 :     double      inner_tuples = path->innerjoinpath->rows;
    5456             :     SpecialJoinInfo sjinfo;
    5457      811074 :     Selectivity selec = 1.0;
    5458             :     ListCell   *l;
    5459             : 
    5460             :     /*
    5461             :      * Make up a SpecialJoinInfo for JOIN_INNER semantics.
    5462             :      */
    5463      811074 :     init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
    5464      811074 :                       path->innerjoinpath->parent->relids);
    5465             : 
    5466             :     /* Get the approximate selectivity */
    5467     1714094 :     foreach(l, quals)
    5468             :     {
    5469      903020 :         Node       *qual = (Node *) lfirst(l);
    5470             : 
    5471             :         /* Note that clause_selectivity will be able to cache its result */
    5472      903020 :         selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
    5473             :     }
    5474             : 
    5475             :     /* Apply it to the input relation sizes */
    5476      811074 :     tuples = selec * outer_tuples * inner_tuples;
    5477             : 
    5478      811074 :     return clamp_row_est(tuples);
    5479             : }
    5480             : 
    5481             : 
    5482             : /*
    5483             :  * set_baserel_size_estimates
    5484             :  *      Set the size estimates for the given base relation.
    5485             :  *
    5486             :  * The rel's targetlist and restrictinfo list must have been constructed
    5487             :  * already, and rel->tuples must be set.
    5488             :  *
    5489             :  * We set the following fields of the rel node:
    5490             :  *  rows: the estimated number of output tuples (after applying
    5491             :  *        restriction clauses).
    5492             :  *  width: the estimated average output tuple width in bytes.
    5493             :  *  baserestrictcost: estimated cost of evaluating baserestrictinfo clauses.
    5494             :  */
    5495             : void
    5496      534534 : set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    5497             : {
    5498             :     double      nrows;
    5499             : 
    5500             :     /* Should only be applied to base relations */
    5501             :     Assert(rel->relid > 0);
    5502             : 
    5503     1069038 :     nrows = rel->tuples *
    5504      534534 :         clauselist_selectivity(root,
    5505             :                                rel->baserestrictinfo,
    5506             :                                0,
    5507             :                                JOIN_INNER,
    5508             :                                NULL);
    5509             : 
    5510      534504 :     rel->rows = clamp_row_est(nrows);
    5511             : 
    5512      534504 :     cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
    5513             : 
    5514      534504 :     set_rel_width(root, rel);
    5515      534504 : }
    5516             : 
    5517             : /*
    5518             :  * get_parameterized_baserel_size
    5519             :  *      Make a size estimate for a parameterized scan of a base relation.
    5520             :  *
    5521             :  * 'param_clauses' lists the additional join clauses to be used.
    5522             :  *
    5523             :  * set_baserel_size_estimates must have been applied already.
    5524             :  */
    5525             : double
    5526      165080 : get_parameterized_baserel_size(PlannerInfo *root, RelOptInfo *rel,
    5527             :                                List *param_clauses)
    5528             : {
    5529             :     List       *allclauses;
    5530             :     double      nrows;
    5531             : 
    5532             :     /*
    5533             :      * Estimate the number of rows returned by the parameterized scan, knowing
    5534             :      * that it will apply all the extra join clauses as well as the rel's own
    5535             :      * restriction clauses.  Note that we force the clauses to be treated as
    5536             :      * non-join clauses during selectivity estimation.
    5537             :      */
    5538      165080 :     allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
    5539      330160 :     nrows = rel->tuples *
    5540      165080 :         clauselist_selectivity(root,
    5541             :                                allclauses,
    5542      165080 :                                rel->relid,   /* do not use 0! */
    5543             :                                JOIN_INNER,
    5544             :                                NULL);
    5545      165080 :     nrows = clamp_row_est(nrows);
    5546             :     /* For safety, make sure result is not more than the base estimate */
    5547      165080 :     if (nrows > rel->rows)
    5548           0 :         nrows = rel->rows;
    5549      165080 :     return nrows;
    5550             : }
    5551             : 
    5552             : /*
    5553             :  * set_joinrel_size_estimates
    5554             :  *      Set the size estimates for the given join relation.
    5555             :  *
    5556             :  * The rel's targetlist must have been constructed already, and a
    5557             :  * restriction clause list that matches the given component rels must
    5558             :  * be provided.
    5559             :  *
    5560             :  * Since there is more than one way to make a joinrel for more than two
    5561             :  * base relations, the results we get here could depend on which component
    5562             :  * rel pair is provided.  In theory we should get the same answers no matter
    5563             :  * which pair is provided; in practice, since the selectivity estimation
    5564             :  * routines don't handle all cases equally well, we might not.  But there's
    5565             :  * not much to be done about it.  (Would it make sense to repeat the
    5566             :  * calculations for each pair of input rels that's encountered, and somehow
    5567             :  * average the results?  Probably way more trouble than it's worth, and
    5568             :  * anyway we must keep the rowcount estimate the same for all paths for the
    5569             :  * joinrel.)
    5570             :  *
    5571             :  * We set only the rows field here.  The reltarget field was already set by
    5572             :  * build_joinrel_tlist, and baserestrictcost is not used for join rels.
    5573             :  */
    5574             : void
    5575      261768 : set_joinrel_size_estimates(PlannerInfo *root, RelOptInfo *rel,
    5576             :                            RelOptInfo *outer_rel,
    5577             :                            RelOptInfo *inner_rel,
    5578             :                            SpecialJoinInfo *sjinfo,
    5579             :                            List *restrictlist)
    5580             : {
    5581      261768 :     rel->rows = calc_joinrel_size_estimate(root,
    5582             :                                            rel,
    5583             :                                            outer_rel,
    5584             :                                            inner_rel,
    5585             :                                            outer_rel->rows,
    5586             :                                            inner_rel->rows,
    5587             :                                            sjinfo,
    5588             :                                            restrictlist);
    5589      261768 : }
    5590             : 
    5591             : /*
    5592             :  * get_parameterized_joinrel_size
    5593             :  *      Make a size estimate for a parameterized scan of a join relation.
    5594             :  *
    5595             :  * 'rel' is the joinrel under consideration.
    5596             :  * 'outer_path', 'inner_path' are (probably also parameterized) Paths that
    5597             :  *      produce the relations being joined.
    5598             :  * 'sjinfo' is any SpecialJoinInfo relevant to this join.
    5599             :  * 'restrict_clauses' lists the join clauses that need to be applied at the
    5600             :  * join node (including any movable clauses that were moved down to this join,
    5601             :  * and not including any movable clauses that were pushed down into the
    5602             :  * child paths).
    5603             :  *
    5604             :  * set_joinrel_size_estimates must have been applied already.
    5605             :  */
    5606             : double
    5607       10238 : get_parameterized_joinrel_size(PlannerInfo *root, RelOptInfo *rel,
    5608             :                                Path *outer_path,
    5609             :                                Path *inner_path,
    5610             :                                SpecialJoinInfo *sjinfo,
    5611             :                                List *restrict_clauses)
    5612             : {
    5613             :     double      nrows;
    5614             : 
    5615             :     /*
    5616             :      * Estimate the number of rows returned by the parameterized join as the
    5617             :      * sizes of the input paths times the selectivity of the clauses that have
    5618             :      * ended up at this join node.
    5619             :      *
    5620             :      * As with set_joinrel_size_estimates, the rowcount estimate could depend
    5621             :      * on the pair of input paths provided, though ideally we'd get the same
    5622             :      * estimate for any pair with the same parameterization.
    5623             :      */
    5624       10238 :     nrows = calc_joinrel_size_estimate(root,
    5625             :                                        rel,
    5626             :                                        outer_path->parent,
    5627             :                                        inner_path->parent,
    5628             :                                        outer_path->rows,
    5629             :                                        inner_path->rows,
    5630             :                                        sjinfo,
    5631             :                                        restrict_clauses);
    5632             :     /* For safety, make sure result is not more than the base estimate */
    5633       10238 :     if (nrows > rel->rows)
    5634          12 :         nrows = rel->rows;
    5635       10238 :     return nrows;
    5636             : }
    5637             : 
    5638             : /*
    5639             :  * calc_joinrel_size_estimate
    5640             :  *      Workhorse for set_joinrel_size_estimates and
    5641             :  *      get_parameterized_joinrel_size.
    5642             :  *
    5643             :  * outer_rel/inner_rel are the relations being joined, but they should be
    5644             :  * assumed to have sizes outer_rows/inner_rows; those numbers might be less
    5645             :  * than what rel->rows says, when we are considering parameterized paths.
    5646             :  */
    5647             : static double
    5648      272006 : calc_joinrel_size_estimate(PlannerInfo *root,
    5649             :                            RelOptInfo *joinrel,
    5650             :                            RelOptInfo *outer_rel,
    5651             :                            RelOptInfo *inner_rel,
    5652             :                            double outer_rows,
    5653             :                            double inner_rows,
    5654             :                            SpecialJoinInfo *sjinfo,
    5655             :                            List *restrictlist)
    5656             : {
    5657      272006 :     JoinType    jointype = sjinfo->jointype;
    5658             :     Selectivity fkselec;
    5659             :     Selectivity jselec;
    5660             :     Selectivity pselec;
    5661             :     double      nrows;
    5662             : 
    5663             :     /*
    5664             :      * Compute joinclause selectivity.  Note that we are only considering
    5665             :      * clauses that become restriction clauses at this join level; we are not
    5666             :      * double-counting them because they were not considered in estimating the
    5667             :      * sizes of the component rels.
    5668             :      *
    5669             :      * First, see whether any of the joinclauses can be matched to known FK
    5670             :      * constraints.  If so, drop those clauses from the restrictlist, and
    5671             :      * instead estimate their selectivity using FK semantics.  (We do this
    5672             :      * without regard to whether said clauses are local or "pushed down".
    5673             :      * Probably, an FK-matching clause could never be seen as pushed down at
    5674             :      * an outer join, since it would be strict and hence would be grounds for
    5675             :      * join strength reduction.)  fkselec gets the net selectivity for
    5676             :      * FK-matching clauses, or 1.0 if there are none.
    5677             :      */
    5678      272006 :     fkselec = get_foreign_key_join_selectivity(root,
    5679             :                                                outer_rel->relids,
    5680             :                                                inner_rel->relids,
    5681             :                                                sjinfo,
    5682             :                                                &restrictlist);
    5683             : 
    5684             :     /*
    5685             :      * For an outer join, we have to distinguish the selectivity of the join's
    5686             :      * own clauses (JOIN/ON conditions) from any clauses that were "pushed
    5687             :      * down".  For inner joins we just count them all as joinclauses.
    5688             :      */
    5689      272006 :     if (IS_OUTER_JOIN(jointype))
    5690             :     {
    5691       82804 :         List       *joinquals = NIL;
    5692       82804 :         List       *pushedquals = NIL;
    5693             :         ListCell   *l;
    5694             : 
    5695             :         /* Grovel through the clauses to separate into two lists */
    5696      186182 :         foreach(l, restrictlist)
    5697             :         {
    5698      103378 :             RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
    5699             : 
    5700      103378 :             if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
    5701        4308 :                 pushedquals = lappend(pushedquals, rinfo);
    5702             :             else
    5703       99070 :                 joinquals = lappend(joinquals, rinfo);
    5704             :         }
    5705             : 
    5706             :         /* Get the separate selectivities */
    5707       82804 :         jselec = clauselist_selectivity(root,
    5708             :                                         joinquals,
    5709             :                                         0,
    5710             :                                         jointype,
    5711             :                                         sjinfo);
    5712       82804 :         pselec = clauselist_selectivity(root,
    5713             :                                         pushedquals,
    5714             :                                         0,
    5715             :                                         jointype,
    5716             :                                         sjinfo);
    5717             : 
    5718             :         /* Avoid leaking a lot of ListCells */
    5719       82804 :         list_free(joinquals);
    5720       82804 :         list_free(pushedquals);
    5721             :     }
    5722             :     else
    5723             :     {
    5724      189202 :         jselec = clauselist_selectivity(root,
    5725             :                                         restrictlist,
    5726             :                                         0,
    5727             :                                         jointype,
    5728             :                                         sjinfo);
    5729      189202 :         pselec = 0.0;           /* not used, keep compiler quiet */
    5730             :     }
    5731             : 
    5732             :     /*
    5733             :      * Basically, we multiply size of Cartesian product by selectivity.
    5734             :      *
    5735             :      * If we are doing an outer join, take that into account: the joinqual
    5736             :      * selectivity has to be clamped using the knowledge that the output must
    5737             :      * be at least as large as the non-nullable input.  However, any
    5738             :      * pushed-down quals are applied after the outer join, so their
    5739             :      * selectivity applies fully.
    5740             :      *
    5741             :      * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
    5742             :      * of LHS rows that have matches, and we apply that straightforwardly.
    5743             :      */
    5744      272006 :     switch (jointype)
    5745             :     {
    5746      180966 :         case JOIN_INNER:
    5747      180966 :             nrows = outer_rows * inner_rows * fkselec * jselec;
    5748             :             /* pselec not used */
    5749      180966 :             break;
    5750       76008 :         case JOIN_LEFT:
    5751       76008 :             nrows = outer_rows * inner_rows * fkselec * jselec;
    5752       76008 :             if (nrows < outer_rows)
    5753       31198 :                 nrows = outer_rows;
    5754       76008 :             nrows *= pselec;
    5755       76008 :             break;
    5756        1720 :         case JOIN_FULL:
    5757        1720 :             nrows = outer_rows * inner_rows * fkselec * jselec;
    5758        1720 :             if (nrows < outer_rows)
    5759        1178 :                 nrows = outer_rows;
    5760        1720 :             if (nrows < inner_rows)
    5761         120 :                 nrows = inner_rows;
    5762        1720 :             nrows *= pselec;
    5763        1720 :             break;
    5764        8236 :         case JOIN_SEMI:
    5765        8236 :             nrows = outer_rows * fkselec * jselec;
    5766             :             /* pselec not used */
    5767        8236 :             break;
    5768        5076 :         case JOIN_ANTI:
    5769        5076 :             nrows = outer_rows * (1.0 - fkselec * jselec);
    5770        5076 :             nrows *= pselec;
    5771        5076 :             break;
    5772           0 :         default:
    5773             :             /* other values not expected here */
    5774           0 :             elog(ERROR, "unrecognized join type: %d", (int) jointype);
    5775             :             nrows = 0;          /* keep compiler quiet */
    5776             :             break;
    5777             :     }
    5778             : 
    5779      272006 :     return clamp_row_est(nrows);
    5780             : }
    5781             : 
    5782             : /*
    5783             :  * get_foreign_key_join_selectivity
    5784             :  *      Estimate join selectivity for foreign-key-related clauses.
    5785             :  *
    5786             :  * Remove any clauses that can be matched to FK constraints from *restrictlist,
    5787             :  * and return a substitute estimate of their selectivity.  1.0 is returned
    5788             :  * when there are no such clauses.
    5789             :  *
    5790             :  * The reason for treating such clauses specially is that we can get better
    5791             :  * estimates this way than by relying on clauselist_selectivity(), especially
    5792             :  * for multi-column FKs where that function's assumption that the clauses are
    5793             :  * independent falls down badly.  But even with single-column FKs, we may be
    5794             :  * able to get a better answer when the pg_statistic stats are missing or out
    5795             :  * of date.
    5796             :  */
    5797             : static Selectivity
    5798      272006 : get_foreign_key_join_selectivity(PlannerInfo *root,
    5799             :                                  Relids outer_relids,
    5800             :                                  Relids inner_relids,
    5801             :                                  SpecialJoinInfo *sjinfo,
    5802             :                                  List **restrictlist)
    5803             : {
    5804      272006 :     Selectivity fkselec = 1.0;
    5805      272006 :     JoinType    jointype = sjinfo->jointype;
    5806      272006 :     List       *worklist = *restrictlist;
    5807             :     ListCell   *lc;
    5808             : 
    5809             :     /* Consider each FK constraint that is known to match the query */
    5810      273972 :     foreach(lc, root->fkey_list)
    5811             :     {
    5812        1966 :         ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
    5813             :         bool        ref_is_outer;
    5814             :         List       *removedlist;
    5815             :         ListCell   *cell;
    5816             : 
    5817             :         /*
    5818             :          * This FK is not relevant unless it connects a baserel on one side of
    5819             :          * this join to a baserel on the other side.
    5820             :          */
    5821        3580 :         if (bms_is_member(fkinfo->con_relid, outer_relids) &&
    5822        1614 :             bms_is_member(fkinfo->ref_relid, inner_relids))
    5823        1440 :             ref_is_outer = false;
    5824         866 :         else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
    5825         340 :                  bms_is_member(fkinfo->con_relid, inner_relids))
    5826         130 :             ref_is_outer = true;
    5827             :         else
    5828         396 :             continue;
    5829             : 
    5830             :         /*
    5831             :          * If we're dealing with a semi/anti join, and the FK's referenced
    5832             :          * relation is on the outside, then knowledge of the FK doesn't help
    5833             :          * us figure out what we need to know (which is the fraction of outer
    5834             :          * rows that have matches).  On the other hand, if the referenced rel
    5835             :          * is on the inside, then all outer rows must have matches in the
    5836             :          * referenced table (ignoring nulls).  But any restriction or join
    5837             :          * clauses that filter that table will reduce the fraction of matches.
    5838             :          * We can account for restriction clauses, but it's too hard to guess
    5839             :          * how many table rows would get through a join that's inside the RHS.
    5840             :          * Hence, if either case applies, punt and ignore the FK.
    5841             :          */
    5842        1570 :         if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
    5843        1048 :             (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
    5844          12 :             continue;
    5845             : 
    5846             :         /*
    5847             :          * Modify the restrictlist by removing clauses that match the FK (and
    5848             :          * putting them into removedlist instead).  It seems unsafe to modify
    5849             :          * the originally-passed List structure, so we make a shallow copy the
    5850             :          * first time through.
    5851             :          */
    5852        1558 :         if (worklist == *restrictlist)
    5853        1334 :             worklist = list_copy(worklist);
    5854             : 
    5855        1558 :         removedlist = NIL;
    5856        3252 :         foreach(cell, worklist)
    5857             :         {
    5858        1694 :             RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
    5859        1694 :             bool        remove_it = false;
    5860             :             int         i;
    5861             : 
    5862             :             /* Drop this clause if it matches any column of the FK */
    5863        2140 :             for (i = 0; i < fkinfo->nkeys; i++)
    5864             :             {
    5865        2110 :                 if (rinfo->parent_ec)
    5866             :                 {
    5867             :                     /*
    5868             :                      * EC-derived clauses can only match by EC.  It is okay to
    5869             :                      * consider any clause derived from the same EC as
    5870             :                      * matching the FK: even if equivclass.c chose to generate
    5871             :                      * a clause equating some other pair of Vars, it could
    5872             :                      * have generated one equating the FK's Vars.  So for
    5873             :                      * purposes of estimation, we can act as though it did so.
    5874             :                      *
    5875             :                      * Note: checking parent_ec is a bit of a cheat because
    5876             :                      * there are EC-derived clauses that don't have parent_ec
    5877             :                      * set; but such clauses must compare expressions that
    5878             :                      * aren't just Vars, so they cannot match the FK anyway.
    5879             :                      */
    5880         304 :                     if (fkinfo->eclass[i] == rinfo->parent_ec)
    5881             :                     {
    5882         298 :                         remove_it = true;
    5883         298 :                         break;
    5884             :                     }
    5885             :                 }
    5886             :                 else
    5887             :                 {
    5888             :                     /*
    5889             :                      * Otherwise, see if rinfo was previously matched to FK as
    5890             :                      * a "loose" clause.
    5891             :                      */
    5892        1806 :                     if (list_member_ptr(fkinfo->rinfos[i], rinfo))
    5893             :                     {
    5894        1366 :                         remove_it = true;
    5895        1366 :                         break;
    5896             :                     }
    5897             :                 }
    5898             :             }
    5899        1694 :             if (remove_it)
    5900             :             {
    5901        1664 :                 worklist = foreach_delete_current(worklist, cell);
    5902        1664 :                 removedlist = lappend(removedlist, rinfo);
    5903             :             }
    5904             :         }
    5905             : 
    5906             :         /*
    5907             :          * If we failed to remove all the matching clauses we expected to
    5908             :          * find, chicken out and ignore this FK; applying its selectivity
    5909             :          * might result in double-counting.  Put any clauses we did manage to
    5910             :          * remove back into the worklist.
    5911             :          *
    5912             :          * Since the matching clauses are known not outerjoin-delayed, they
    5913             :          * would normally have appeared in the initial joinclause list.  If we
    5914             :          * didn't find them, there are two possibilities:
    5915             :          *
    5916             :          * 1. If the FK match is based on an EC that is ec_has_const, it won't
    5917             :          * have generated any join clauses at all.  We discount such ECs while
    5918             :          * checking to see if we have "all" the clauses.  (Below, we'll adjust
    5919             :          * the selectivity estimate for this case.)
    5920             :          *
    5921             :          * 2. The clauses were matched to some other FK in a previous
    5922             :          * iteration of this loop, and thus removed from worklist.  (A likely
    5923             :          * case is that two FKs are matched to the same EC; there will be only
    5924             :          * one EC-derived clause in the initial list, so the first FK will
    5925             :          * consume it.)  Applying both FKs' selectivity independently risks
    5926             :          * underestimating the join size; in particular, this would undo one
    5927             :          * of the main things that ECs were invented for, namely to avoid
    5928             :          * double-counting the selectivity of redundant equality conditions.
    5929             :          * Later we might think of a reasonable way to combine the estimates,
    5930             :          * but for now, just punt, since this is a fairly uncommon situation.
    5931             :          */
    5932        1558 :         if (removedlist == NIL ||
    5933        1272 :             list_length(removedlist) !=
    5934        1272 :             (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
    5935             :         {
    5936         286 :             worklist = list_concat(worklist, removedlist);
    5937         286 :             continue;
    5938             :         }
    5939             : 
    5940             :         /*
    5941             :          * Finally we get to the payoff: estimate selectivity using the
    5942             :          * knowledge that each referencing row will match exactly one row in
    5943             :          * the referenced table.
    5944             :          *
    5945             :          * XXX that's not true in the presence of nulls in the referencing
    5946             :          * column(s), so in principle we should derate the estimate for those.
    5947             :          * However (1) if there are any strict restriction clauses for the
    5948             :          * referencing column(s) elsewhere in the query, derating here would
    5949             :          * be double-counting the null fraction, and (2) it's not very clear
    5950             :          * how to combine null fractions for multiple referencing columns. So
    5951             :          * we do nothing for now about correcting for nulls.
    5952             :          *
    5953             :          * XXX another point here is that if either side of an FK constraint
    5954             :          * is an inheritance parent, we estimate as though the constraint
    5955             :          * covers all its children as well.  This is not an unreasonable
    5956             :          * assumption for a referencing table, ie the user probably applied
    5957             :          * identical constraints to all child tables (though perhaps we ought
    5958             :          * to check that).  But it's not possible to have done that for a
    5959             :          * referenced table.  Fortunately, precisely because that doesn't
    5960             :          * work, it is uncommon in practice to have an FK referencing a parent
    5961             :          * table.  So, at least for now, disregard inheritance here.
    5962             :          */
    5963        1272 :         if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
    5964         824 :         {
    5965             :             /*
    5966             :              * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
    5967             :              * referenced table is exactly the inside of the join.  The join
    5968             :              * selectivity is defined as the fraction of LHS rows that have
    5969             :              * matches.  The FK implies that every LHS row has a match *in the
    5970             :              * referenced table*; but any restriction clauses on it will
    5971             :              * reduce the number of matches.  Hence we take the join
    5972             :              * selectivity as equal to the selectivity of the table's
    5973             :              * restriction clauses, which is rows / tuples; but we must guard
    5974             :              * against tuples == 0.
    5975             :              */
    5976         824 :             RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
    5977         824 :             double      ref_tuples = Max(ref_rel->tuples, 1.0);
    5978             : 
    5979         824 :             fkselec *= ref_rel->rows / ref_tuples;
    5980             :         }
    5981             :         else
    5982             :         {
    5983             :             /*
    5984             :              * Otherwise, selectivity is exactly 1/referenced-table-size; but
    5985             :              * guard against tuples == 0.  Note we should use the raw table
    5986             :              * tuple count, not any estimate of its filtered or joined size.
    5987             :              */
    5988         448 :             RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
    5989         448 :             double      ref_tuples = Max(ref_rel->tuples, 1.0);
    5990             : 
    5991         448 :             fkselec *= 1.0 / ref_tuples;
    5992             :         }
    5993             : 
    5994             :         /*
    5995             :          * If any of the FK columns participated in ec_has_const ECs, then
    5996             :          * equivclass.c will have generated "var = const" restrictions for
    5997             :          * each side of the join, thus reducing the sizes of both input
    5998             :          * relations.  Taking the fkselec at face value would amount to
    5999             :          * double-counting the selectivity of the constant restriction for the
    6000             :          * referencing Var.  Hence, look for the restriction clause(s) that
    6001             :          * were applied to the referencing Var(s), and divide out their
    6002             :          * selectivity to correct for this.
    6003             :          */
    6004        1272 :         if (fkinfo->nconst_ec > 0)
    6005             :         {
    6006          24 :             for (int i = 0; i < fkinfo->nkeys; i++)
    6007             :             {
    6008          18 :                 EquivalenceClass *ec = fkinfo->eclass[i];
    6009             : 
    6010          18 :                 if (ec && ec->ec_has_const)
    6011             :                 {
    6012           6 :                     EquivalenceMember *em = fkinfo->fk_eclass_member[i];
    6013           6 :                     RestrictInfo *rinfo = find_derived_clause_for_ec_member(root,
    6014             :                                                                             ec,
    6015             :                                                                             em);
    6016             : 
    6017           6 :                     if (rinfo)
    6018             :                     {
    6019             :                         Selectivity s0;
    6020             : 
    6021           6 :                         s0 = clause_selectivity(root,
    6022             :                                                 (Node *) rinfo,
    6023             :                                                 0,
    6024             :                                                 jointype,
    6025             :                                                 sjinfo);
    6026           6 :                         if (s0 > 0)
    6027           6 :                             fkselec /= s0;
    6028             :                     }
    6029             :                 }
    6030             :             }
    6031             :         }
    6032             :     }
    6033             : 
    6034      272006 :     *restrictlist = worklist;
    6035      272006 :     CLAMP_PROBABILITY(fkselec);
    6036      272006 :     return fkselec;
    6037             : }
    6038             : 
    6039             : /*
    6040             :  * set_subquery_size_estimates
    6041             :  *      Set the size estimates for a base relation that is a subquery.
    6042             :  *
    6043             :  * The rel's targetlist and restrictinfo list must have been constructed
    6044             :  * already, and the Paths for the subquery must have been completed.
    6045             :  * We look at the subquery's PlannerInfo to extract data.
    6046             :  *
    6047             :  * We set the same fields as set_baserel_size_estimates.
    6048             :  */
    6049             : void
    6050       40298 : set_subquery_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    6051             : {
    6052       40298 :     PlannerInfo *subroot = rel->subroot;
    6053             :     RelOptInfo *sub_final_rel;
    6054             :     ListCell   *lc;
    6055             : 
    6056             :     /* Should only be applied to base relations that are subqueries */
    6057             :     Assert(rel->relid > 0);
    6058             :     Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
    6059             : 
    6060             :     /*
    6061             :      * Copy raw number of output rows from subquery.  All of its paths should
    6062             :      * have the same output rowcount, so just look at cheapest-total.
    6063             :      */
    6064       40298 :     sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
    6065       40298 :     rel->tuples = sub_final_rel->cheapest_total_path->rows;
    6066             : 
    6067             :     /*
    6068             :      * Compute per-output-column width estimates by examining the subquery's
    6069             :      * targetlist.  For any output that is a plain Var, get the width estimate
    6070             :      * that was made while planning the subquery.  Otherwise, we leave it to
    6071             :      * set_rel_width to fill in a datatype-based default estimate.
    6072             :      */
    6073      194592 :     foreach(lc, subroot->parse->targetList)
    6074             :     {
    6075      154294 :         TargetEntry *te = lfirst_node(TargetEntry, lc);
    6076      154294 :         Node       *texpr = (Node *) te->expr;
    6077      154294 :         int32       item_width = 0;
    6078             : 
    6079             :         /* junk columns aren't visible to upper query */
    6080      154294 :         if (te->resjunk)
    6081        6902 :             continue;
    6082             : 
    6083             :         /*
    6084             :          * The subquery could be an expansion of a view that's had columns
    6085             :          * added to it since the current query was parsed, so that there are
    6086             :          * non-junk tlist columns in it that don't correspond to any column
    6087             :          * visible at our query level.  Ignore such columns.
    6088             :          */
    6089      147392 :         if (te->resno < rel->min_attr || te->resno > rel->max_attr)
    6090           0 :             continue;
    6091             : 
    6092             :         /*
    6093             :          * XXX This currently doesn't work for subqueries containing set
    6094             :          * operations, because the Vars in their tlists are bogus references
    6095             :          * to the first leaf subquery, which wouldn't give the right answer
    6096             :          * even if we could still get to its PlannerInfo.
    6097             :          *
    6098             :          * Also, the subquery could be an appendrel for which all branches are
    6099             :          * known empty due to constraint exclusion, in which case
    6100             :          * set_append_rel_pathlist will have left the attr_widths set to zero.
    6101             :          *
    6102             :          * In either case, we just leave the width estimate zero until
    6103             :          * set_rel_width fixes it.
    6104             :          */
    6105      147392 :         if (IsA(texpr, Var) &&
    6106       64784 :             subroot->parse->setOperations == NULL)
    6107             :         {
    6108       62930 :             Var        *var = (Var *) texpr;
    6109       62930 :             RelOptInfo *subrel = find_base_rel(subroot, var->varno);
    6110             : 
    6111       62930 :             item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
    6112             :         }
    6113      147392 :         rel->attr_widths[te->resno - rel->min_attr] = item_width;
    6114             :     }
    6115             : 
    6116             :     /* Now estimate number of output rows, etc */
    6117       40298 :     set_baserel_size_estimates(root, rel);
    6118       40298 : }
    6119             : 
    6120             : /*
    6121             :  * set_function_size_estimates
    6122             :  *      Set the size estimates for a base relation that is a function call.
    6123             :  *
    6124             :  * The rel's targetlist and restrictinfo list must have been constructed
    6125             :  * already.
    6126             :  *
    6127             :  * We set the same fields as set_baserel_size_estimates.
    6128             :  */
    6129             : void
    6130       53556 : set_function_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    6131             : {
    6132             :     RangeTblEntry *rte;
    6133             :     ListCell   *lc;
    6134             : 
    6135             :     /* Should only be applied to base relations that are functions */
    6136             :     Assert(rel->relid > 0);
    6137       53556 :     rte = planner_rt_fetch(rel->relid, root);
    6138             :     Assert(rte->rtekind == RTE_FUNCTION);
    6139             : 
    6140             :     /*
    6141             :      * Estimate number of rows the functions will return. The rowcount of the
    6142             :      * node is that of the largest function result.
    6143             :      */
    6144       53556 :     rel->tuples = 0;
    6145      107616 :     foreach(lc, rte->functions)
    6146             :     {
    6147       54060 :         RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
    6148       54060 :         double      ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
    6149             : 
    6150       54060 :         if (ntup > rel->tuples)
    6151       53580 :             rel->tuples = ntup;
    6152             :     }
    6153             : 
    6154             :     /* Now estimate number of output rows, etc */
    6155       53556 :     set_baserel_size_estimates(root, rel);
    6156       53556 : }
    6157             : 
    6158             : /*
    6159             :  * set_function_size_estimates
    6160             :  *      Set the size estimates for a base relation that is a function call.
    6161             :  *
    6162             :  * The rel's targetlist and restrictinfo list must have been constructed
    6163             :  * already.
    6164             :  *
    6165             :  * We set the same fields as set_tablefunc_size_estimates.
    6166             :  */
    6167             : void
    6168         626 : set_tablefunc_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    6169             : {
    6170             :     /* Should only be applied to base relations that are functions */
    6171             :     Assert(rel->relid > 0);
    6172             :     Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
    6173             : 
    6174         626 :     rel->tuples = 100;
    6175             : 
    6176             :     /* Now estimate number of output rows, etc */
    6177         626 :     set_baserel_size_estimates(root, rel);
    6178         626 : }
    6179             : 
    6180             : /*
    6181             :  * set_values_size_estimates
    6182             :  *      Set the size estimates for a base relation that is a values list.
    6183             :  *
    6184             :  * The rel's targetlist and restrictinfo list must have been constructed
    6185             :  * already.
    6186             :  *
    6187             :  * We set the same fields as set_baserel_size_estimates.
    6188             :  */
    6189             : void
    6190        8520 : set_values_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    6191             : {
    6192             :     RangeTblEntry *rte;
    6193             : 
    6194             :     /* Should only be applied to base relations that are values lists */
    6195             :     Assert(rel->relid > 0);
    6196        8520 :     rte = planner_rt_fetch(rel->relid, root);
    6197             :     Assert(rte->rtekind == RTE_VALUES);
    6198             : 
    6199             :     /*
    6200             :      * Estimate number of rows the values list will return. We know this
    6201             :      * precisely based on the list length (well, barring set-returning
    6202             :      * functions in list items, but that's a refinement not catered for
    6203             :      * anywhere else either).
    6204             :      */
    6205        8520 :     rel->tuples = list_length(rte->values_lists);
    6206             : 
    6207             :     /* Now estimate number of output rows, etc */
    6208        8520 :     set_baserel_size_estimates(root, rel);
    6209        8520 : }
    6210             : 
    6211             : /*
    6212             :  * set_cte_size_estimates
    6213             :  *      Set the size estimates for a base relation that is a CTE reference.
    6214             :  *
    6215             :  * The rel's targetlist and restrictinfo list must have been constructed
    6216             :  * already, and we need an estimate of the number of rows returned by the CTE
    6217             :  * (if a regular CTE) or the non-recursive term (if a self-reference).
    6218             :  *
    6219             :  * We set the same fields as set_baserel_size_estimates.
    6220             :  */
    6221             : void
    6222        5312 : set_cte_size_estimates(PlannerInfo *root, RelOptInfo *rel, double cte_rows)
    6223             : {
    6224             :     RangeTblEntry *rte;
    6225             : 
    6226             :     /* Should only be applied to base relations that are CTE references */
    6227             :     Assert(rel->relid > 0);
    6228        5312 :     rte = planner_rt_fetch(rel->relid, root);
    6229             :     Assert(rte->rtekind == RTE_CTE);
    6230             : 
    6231        5312 :     if (rte->self_reference)
    6232             :     {
    6233             :         /*
    6234             :          * In a self-reference, we assume the average worktable size is a
    6235             :          * multiple of the nonrecursive term's size.  The best multiplier will
    6236             :          * vary depending on query "fan-out", so make its value adjustable.
    6237             :          */
    6238         942 :         rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
    6239             :     }
    6240             :     else
    6241             :     {
    6242             :         /* Otherwise just believe the CTE's rowcount estimate */
    6243        4370 :         rel->tuples = cte_rows;
    6244             :     }
    6245             : 
    6246             :     /* Now estimate number of output rows, etc */
    6247        5312 :     set_baserel_size_estimates(root, rel);
    6248        5312 : }
    6249             : 
    6250             : /*
    6251             :  * set_namedtuplestore_size_estimates
    6252             :  *      Set the size estimates for a base relation that is a tuplestore reference.
    6253             :  *
    6254             :  * The rel's targetlist and restrictinfo list must have been constructed
    6255             :  * already.
    6256             :  *
    6257             :  * We set the same fields as set_baserel_size_estimates.
    6258             :  */
    6259             : void
    6260         474 : set_namedtuplestore_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    6261             : {
    6262             :     RangeTblEntry *rte;
    6263             : 
    6264             :     /* Should only be applied to base relations that are tuplestore references */
    6265             :     Assert(rel->relid > 0);
    6266         474 :     rte = planner_rt_fetch(rel->relid, root);
    6267             :     Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
    6268             : 
    6269             :     /*
    6270             :      * Use the estimate provided by the code which is generating the named
    6271             :      * tuplestore.  In some cases, the actual number might be available; in
    6272             :      * others the same plan will be re-used, so a "typical" value might be
    6273             :      * estimated and used.
    6274             :      */
    6275         474 :     rel->tuples = rte->enrtuples;
    6276         474 :     if (rel->tuples < 0)
    6277           0 :         rel->tuples = 1000;
    6278             : 
    6279             :     /* Now estimate number of output rows, etc */
    6280         474 :     set_baserel_size_estimates(root, rel);
    6281         474 : }
    6282             : 
    6283             : /*
    6284             :  * set_result_size_estimates
    6285             :  *      Set the size estimates for an RTE_RESULT base relation
    6286             :  *
    6287             :  * The rel's targetlist and restrictinfo list must have been constructed
    6288             :  * already.
    6289             :  *
    6290             :  * We set the same fields as set_baserel_size_estimates.
    6291             :  */
    6292             : void
    6293        4292 : set_result_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    6294             : {
    6295             :     /* Should only be applied to RTE_RESULT base relations */
    6296             :     Assert(rel->relid > 0);
    6297             :     Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
    6298             : 
    6299             :     /* RTE_RESULT always generates a single row, natively */
    6300        4292 :     rel->tuples = 1;
    6301             : 
    6302             :     /* Now estimate number of output rows, etc */
    6303        4292 :     set_baserel_size_estimates(root, rel);
    6304        4292 : }
    6305             : 
    6306             : /*
    6307             :  * set_foreign_size_estimates
    6308             :  *      Set the size estimates for a base relation that is a foreign table.
    6309             :  *
    6310             :  * There is not a whole lot that we can do here; the foreign-data wrapper
    6311             :  * is responsible for producing useful estimates.  We can do a decent job
    6312             :  * of estimating baserestrictcost, so we set that, and we also set up width
    6313             :  * using what will be purely datatype-driven estimates from the targetlist.
    6314             :  * There is no way to do anything sane with the rows value, so we just put
    6315             :  * a default estimate and hope that the wrapper can improve on it.  The
    6316             :  * wrapper's GetForeignRelSize function will be called momentarily.
    6317             :  *
    6318             :  * The rel's targetlist and restrictinfo list must have been constructed
    6319             :  * already.
    6320             :  */
    6321             : void
    6322        2468 : set_foreign_size_estimates(PlannerInfo *root, RelOptInfo *rel)
    6323             : {
    6324             :     /* Should only be applied to base relations */
    6325             :     Assert(rel->relid > 0);
    6326             : 
    6327        2468 :     rel->rows = 1000;            /* entirely bogus default estimate */
    6328             : 
    6329        2468 :     cost_qual_eval(&rel->baserestrictcost, rel->baserestrictinfo, root);
    6330             : 
    6331        2468 :     set_rel_width(root, rel);
    6332        2468 : }
    6333             : 
    6334             : 
    6335             : /*
    6336             :  * set_rel_width
    6337             :  *      Set the estimated output width of a base relation.
    6338             :  *
    6339             :  * The estimated output width is the sum of the per-attribute width estimates
    6340             :  * for the actually-referenced columns, plus any PHVs or other expressions
    6341             :  * that have to be calculated at this relation.  This is the amount of data
    6342             :  * we'd need to pass upwards in case of a sort, hash, etc.
    6343             :  *
    6344             :  * This function also sets reltarget->cost, so it's a bit misnamed now.
    6345             :  *
    6346             :  * NB: this works best on plain relations because it prefers to look at
    6347             :  * real Vars.  For subqueries, set_subquery_size_estimates will already have
    6348             :  * copied up whatever per-column estimates were made within the subquery,
    6349             :  * and for other types of rels there isn't much we can do anyway.  We fall
    6350             :  * back on (fairly stupid) datatype-based width estimates if we can't get
    6351             :  * any better number.
    6352             :  *
    6353             :  * The per-attribute width estimates are cached for possible re-use while
    6354             :  * building join relations or post-scan/join pathtargets.
    6355             :  */
    6356             : static void
    6357      536972 : set_rel_width(PlannerInfo *root, RelOptInfo *rel)
    6358             : {
    6359      536972 :     Oid         reloid = planner_rt_fetch(rel->relid, root)->relid;
    6360      536972 :     int64       tuple_width = 0;
    6361      536972 :     bool        have_wholerow_var = false;
    6362             :     ListCell   *lc;
    6363             : 
    6364             :     /* Vars are assumed to have cost zero, but other exprs do not */
    6365      536972 :     rel->reltarget->cost.startup = 0;
    6366      536972 :     rel->reltarget->cost.per_tuple = 0;
    6367             : 
    6368     1913060 :     foreach(lc, rel->reltarget->exprs)
    6369             :     {
    6370     1376088 :         Node       *node = (Node *) lfirst(lc);
    6371             : 
    6372             :         /*
    6373             :          * Ordinarily, a Var in a rel's targetlist must belong to that rel;
    6374             :          * but there are corner cases involving LATERAL references where that
    6375             :          * isn't so.  If the Var has the wrong varno, fall through to the
    6376             :          * generic case (it doesn't seem worth the trouble to be any smarter).
    6377             :          */
    6378     1376088 :         if (IsA(node, Var) &&
    6379     1351610 :             ((Var *) node)->varno == rel->relid)
    6380      369018 :         {
    6381     1351544 :             Var        *var = (Var *) node;
    6382             :             int         ndx;
    6383             :             int32       item_width;
    6384             : 
    6385             :             Assert(var->varattno >= rel->min_attr);
    6386             :             Assert(var->varattno <= rel->max_attr);
    6387             : 
    6388     1351544 :             ndx = var->varattno - rel->min_attr;
    6389             : 
    6390             :             /*
    6391             :              * If it's a whole-row Var, we'll deal with it below after we have
    6392             :              * already cached as many attr widths as possible.
    6393             :              */
    6394     1351544 :             if (var->varattno == 0)
    6395             :             {
    6396        3062 :                 have_wholerow_var = true;
    6397        3062 :                 continue;
    6398             :             }
    6399             : 
    6400             :             /*
    6401             :              * The width may have been cached already (especially if it's a
    6402             :              * subquery), so don't duplicate effort.
    6403             :              */
    6404     1348482 :             if (rel->attr_widths[ndx] > 0)
    6405             :             {
    6406      266026 :                 tuple_width += rel->attr_widths[ndx];
    6407      266026 :                 continue;
    6408             :             }
    6409             : 
    6410             :             /* Try to get column width from statistics */
    6411     1082456 :             if (reloid != InvalidOid && var->varattno > 0)
    6412             :             {
    6413      848266 :                 item_width = get_attavgwidth(reloid, var->varattno);
    6414      848266 :                 if (item_width > 0)
    6415             :                 {
    6416      713438 :                     rel->attr_widths[ndx] = item_width;
    6417      713438 :                     tuple_width += item_width;
    6418      713438 :                     continue;
    6419             :                 }
    6420             :             }
    6421             : 
    6422             :             /*
    6423             :              * Not a plain relation, or can't find statistics for it. Estimate
    6424             :              * using just the type info.
    6425             :              */
    6426      369018 :             item_width = get_typavgwidth(var->vartype, var->vartypmod);
    6427             :             Assert(item_width > 0);
    6428      369018 :             rel->attr_widths[ndx] = item_width;
    6429      369018 :             tuple_width += item_width;
    6430             :         }
    6431       24544 :         else if (IsA(node, PlaceHolderVar))
    6432             :         {
    6433             :             /*
    6434             :              * We will need to evaluate the PHV's contained expression while
    6435             :              * scanning this rel, so be sure to include it in reltarget->cost.
    6436             :              */
    6437        2134 :             PlaceHolderVar *phv = (PlaceHolderVar *) node;
    6438        2134 :             PlaceHolderInfo *phinfo = find_placeholder_info(root, phv);
    6439             :             QualCost    cost;
    6440             : 
    6441        2134 :             tuple_width += phinfo->ph_width;
    6442        2134 :             cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
    6443        2134 :             rel->reltarget->cost.startup += cost.startup;
    6444        2134 :             rel->reltarget->cost.per_tuple += cost.per_tuple;
    6445             :         }
    6446             :         else
    6447             :         {
    6448             :             /*
    6449             :              * We could be looking at an expression pulled up from a subquery,
    6450             :              * or a ROW() representing a whole-row child Var, etc.  Do what we
    6451             :              * can using the expression type information.
    6452             :              */
    6453             :             int32       item_width;
    6454             :             QualCost    cost;
    6455             : 
    6456       22410 :             item_width = get_typavgwidth(exprType(node), exprTypmod(node));
    6457             :             Assert(item_width > 0);
    6458       22410 :             tuple_width += item_width;
    6459             :             /* Not entirely clear if we need to account for cost, but do so */
    6460       22410 :             cost_qual_eval_node(&cost, node, root);
    6461       22410 :             rel->reltarget->cost.startup += cost.startup;
    6462       22410 :             rel->reltarget->cost.per_tuple += cost.per_tuple;
    6463             :         }
    6464             :     }
    6465             : 
    6466             :     /*
    6467             :      * If we have a whole-row reference, estimate its width as the sum of
    6468             :      * per-column widths plus heap tuple header overhead.
    6469             :      */
    6470      536972 :     if (have_wholerow_var)
    6471             :     {
    6472        3062 :         int64       wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
    6473             : 
    6474        3062 :         if (reloid != InvalidOid)
    6475             :         {
    6476             :             /* Real relation, so estimate true tuple width */
    6477        2392 :             wholerow_width += get_relation_data_width(reloid,
    6478        2392 :                                                       rel->attr_widths - rel->min_attr);
    6479             :         }
    6480             :         else
    6481             :         {
    6482             :             /* Do what we can with info for a phony rel */
    6483             :             AttrNumber  i;
    6484             : 
    6485        1820 :             for (i = 1; i <= rel->max_attr; i++)
    6486        1150 :                 wholerow_width += rel->attr_widths[i - rel->min_attr];
    6487             :         }
    6488             : 
    6489        3062 :         rel->attr_widths[0 - rel->min_attr] = clamp_width_est(wholerow_width);
    6490             : 
    6491             :         /*
    6492             :          * Include the whole-row Var as part of the output tuple.  Yes, that
    6493             :          * really is what happens at runtime.
    6494             :          */
    6495        3062 :         tuple_width += wholerow_width;
    6496             :     }
    6497             : 
    6498      536972 :     rel->reltarget->width = clamp_width_est(tuple_width);
    6499      536972 : }
    6500             : 
    6501             : /*
    6502             :  * set_pathtarget_cost_width
    6503             :  *      Set the estimated eval cost and output width of a PathTarget tlist.
    6504             :  *
    6505             :  * As a notational convenience, returns the same PathTarget pointer passed in.
    6506             :  *
    6507             :  * Most, though not quite all, uses of this function occur after we've run
    6508             :  * set_rel_width() for base relations; so we can usually obtain cached width
    6509             :  * estimates for Vars.  If we can't, fall back on datatype-based width
    6510             :  * estimates.  Present early-planning uses of PathTargets don't need accurate
    6511             :  * widths badly enough to justify going to the catalogs for better data.
    6512             :  */
    6513             : PathTarget *
    6514      641208 : set_pathtarget_cost_width(PlannerInfo *root, PathTarget *target)
    6515             : {
    6516      641208 :     int64       tuple_width = 0;
    6517             :     ListCell   *lc;
    6518             : 
    6519             :     /* Vars are assumed to have cost zero, but other exprs do not */
    6520      641208 :     target->cost.startup = 0;
    6521      641208 :     target->cost.per_tuple = 0;
    6522             : 
    6523     2217614 :     foreach(lc, target->exprs)
    6524             :     {
    6525     1576406 :         Node       *node = (Node *) lfirst(lc);
    6526             : 
    6527     1576406 :         tuple_width += get_expr_width(root, node);
    6528             : 
    6529             :         /* For non-Vars, account for evaluation cost */
    6530     1576406 :         if (!IsA(node, Var))
    6531             :         {
    6532             :             QualCost    cost;
    6533             : 
    6534      681540 :             cost_qual_eval_node(&cost, node, root);
    6535      681540 :             target->cost.startup += cost.startup;
    6536      681540 :             target->cost.per_tuple += cost.per_tuple;
    6537             :         }
    6538             :     }
    6539             : 
    6540      641208 :     target->width = clamp_width_est(tuple_width);
    6541             : 
    6542      641208 :     return target;
    6543             : }
    6544             : 
    6545             : /*
    6546             :  * get_expr_width
    6547             :  *      Estimate the width of the given expr attempting to use the width
    6548             :  *      cached in a Var's owning RelOptInfo, else fallback on the type's
    6549             :  *      average width when unable to or when the given Node is not a Var.
    6550             :  */
    6551             : static int32
    6552     1912670 : get_expr_width(PlannerInfo *root, const Node *expr)
    6553             : {
    6554             :     int32       width;
    6555             : 
    6556     1912670 :     if (IsA(expr, Var))
    6557             :     {
    6558     1218420 :         const Var  *var = (const Var *) expr;
    6559             : 
    6560             :         /* We should not see any upper-level Vars here */
    6561             :         Assert(var->varlevelsup == 0);
    6562             : 
    6563             :         /* Try to get data from RelOptInfo cache */
    6564     1218420 :         if (!IS_SPECIAL_VARNO(var->varno) &&
    6565     1212510 :             var->varno < root->simple_rel_array_size)
    6566             :         {
    6567     1212510 :             RelOptInfo *rel = root->simple_rel_array[var->varno];
    6568             : 
    6569     1212510 :             if (rel != NULL &&
    6570     1194486 :                 var->varattno >= rel->min_attr &&
    6571     1194486 :                 var->varattno <= rel->max_attr)
    6572             :             {
    6573     1194486 :                 int         ndx = var->varattno - rel->min_attr;
    6574             : 
    6575     1194486 :                 if (rel->attr_widths[ndx] > 0)
    6576     1161902 :                     return rel->attr_widths[ndx];
    6577             :             }
    6578             :         }
    6579             : 
    6580             :         /*
    6581             :          * No cached data available, so estimate using just the type info.
    6582             :          */
    6583       56518 :         width = get_typavgwidth(var->vartype, var->vartypmod);
    6584             :         Assert(width > 0);
    6585             : 
    6586       56518 :         return width;
    6587             :     }
    6588             : 
    6589      694250 :     width = get_typavgwidth(exprType(expr), exprTypmod(expr));
    6590             :     Assert(width > 0);
    6591      694250 :     return width;
    6592             : }
    6593             : 
    6594             : /*
    6595             :  * relation_byte_size
    6596             :  *    Estimate the storage space in bytes for a given number of tuples
    6597             :  *    of a given width (size in bytes).
    6598             :  */
    6599             : static double
    6600     5197866 : relation_byte_size(double tuples, int width)
    6601             : {
    6602     5197866 :     return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
    6603             : }
    6604             : 
    6605             : /*
    6606             :  * page_size
    6607             :  *    Returns an estimate of the number of pages covered by a given
    6608             :  *    number of tuples of a given width (size in bytes).
    6609             :  */
    6610             : static double
    6611        9580 : page_size(double tuples, int width)
    6612             : {
    6613        9580 :     return ceil(relation_byte_size(tuples, width) / BLCKSZ);
    6614             : }
    6615             : 
    6616             : /*
    6617             :  * Estimate the fraction of the work that each worker will do given the
    6618             :  * number of workers budgeted for the path.
    6619             :  */
    6620             : static double
    6621      471456 : get_parallel_divisor(Path *path)
    6622             : {
    6623      471456 :     double      parallel_divisor = path->parallel_workers;
    6624             : 
    6625             :     /*
    6626             :      * Early experience with parallel query suggests that when there is only
    6627             :      * one worker, the leader often makes a very substantial contribution to
    6628             :      * executing the parallel portion of the plan, but as more workers are
    6629             :      * added, it does less and less, because it's busy reading tuples from the
    6630             :      * workers and doing whatever non-parallel post-processing is needed.  By
    6631             :      * the time we reach 4 workers, the leader no longer makes a meaningful
    6632             :      * contribution.  Thus, for now, estimate that the leader spends 30% of
    6633             :      * its time servicing each worker, and the remainder executing the
    6634             :      * parallel plan.
    6635             :      */
    6636      471456 :     if (parallel_leader_participation)
    6637             :     {
    6638             :         double      leader_contribution;
    6639             : 
    6640      470226 :         leader_contribution = 1.0 - (0.3 * path->parallel_workers);
    6641      470226 :         if (leader_contribution > 0)
    6642      467646 :             parallel_divisor += leader_contribution;
    6643             :     }
    6644             : 
    6645      471456 :     return parallel_divisor;
    6646             : }
    6647             : 
    6648             : /*
    6649             :  * compute_bitmap_pages
    6650             :  *    Estimate number of pages fetched from heap in a bitmap heap scan.
    6651             :  *
    6652             :  * 'baserel' is the relation to be scanned
    6653             :  * 'bitmapqual' is a tree of IndexPaths, BitmapAndPaths, and BitmapOrPaths
    6654             :  * 'loop_count' is the number of repetitions of the indexscan to factor into
    6655             :  *      estimates of caching behavior
    6656             :  *
    6657             :  * If cost_p isn't NULL, the indexTotalCost estimate is returned in *cost_p.
    6658             :  * If tuples_p isn't NULL, the tuples_fetched estimate is returned in *tuples_p.
    6659             :  */
    6660             : double
    6661      713824 : compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel,
    6662             :                      Path *bitmapqual, double loop_count,
    6663             :                      Cost *cost_p, double *tuples_p)
    6664             : {
    6665             :     Cost        indexTotalCost;
    6666             :     Selectivity indexSelectivity;
    6667             :     double      T;
    6668             :     double      pages_fetched;
    6669             :     double      tuples_fetched;
    6670             :     double      heap_pages;
    6671             :     double      maxentries;
    6672             : 
    6673             :     /*
    6674             :      * Fetch total cost of obtaining the bitmap, as well as its total
    6675             :      * selectivity.
    6676             :      */
    6677      713824 :     cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
    6678             : 
    6679             :     /*
    6680             :      * Estimate number of main-table pages fetched.
    6681             :      */
    6682      713824 :     tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
    6683             : 
    6684      713824 :     T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
    6685             : 
    6686             :     /*
    6687             :      * For a single scan, the number of heap pages that need to be fetched is
    6688             :      * the same as the Mackert and Lohman formula for the case T <= b (ie, no
    6689             :      * re-reads needed).
    6690             :      */
    6691      713824 :     pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
    6692             : 
    6693             :     /*
    6694             :      * Calculate the number of pages fetched from the heap.  Then based on
    6695             :      * current work_mem estimate get the estimated maxentries in the bitmap.
    6696             :      * (Note that we always do this calculation based on the number of pages
    6697             :      * that would be fetched in a single iteration, even if loop_count > 1.
    6698             :      * That's correct, because only that number of entries will be stored in
    6699             :      * the bitmap at one time.)
    6700             :      */
    6701      713824 :     heap_pages = Min(pages_fetched, baserel->pages);
    6702      713824 :     maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
    6703             : 
    6704      713824 :     if (loop_count > 1)
    6705             :     {
    6706             :         /*
    6707             :          * For repeated bitmap scans, scale up the number of tuples fetched in
    6708             :          * the Mackert and Lohman formula by the number of scans, so that we
    6709             :          * estimate the number of pages fetched by all the scans. Then
    6710             :          * pro-rate for one scan.
    6711             :          */
    6712      150500 :         pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
    6713             :                                             baserel->pages,
    6714             :                                             get_indexpath_pages(bitmapqual),
    6715             :                                             root);
    6716      150500 :         pages_fetched /= loop_count;
    6717             :     }
    6718             : 
    6719      713824 :     if (pages_fetched >= T)
    6720       72576 :         pages_fetched = T;
    6721             :     else
    6722      641248 :         pages_fetched = ceil(pages_fetched);
    6723             : 
    6724      713824 :     if (maxentries < heap_pages)
    6725             :     {
    6726             :         double      exact_pages;
    6727             :         double      lossy_pages;
    6728             : 
    6729             :         /*
    6730             :          * Crude approximation of the number of lossy pages.  Because of the
    6731             :          * way tbm_lossify() is coded, the number of lossy pages increases
    6732             :          * very sharply as soon as we run short of memory; this formula has
    6733             :          * that property and seems to perform adequately in testing, but it's
    6734             :          * possible we could do better somehow.
    6735             :          */
    6736          18 :         lossy_pages = Max(0, heap_pages - maxentries / 2);
    6737          18 :         exact_pages = heap_pages - lossy_pages;
    6738             : 
    6739             :         /*
    6740             :          * If there are lossy pages then recompute the number of tuples
    6741             :          * processed by the bitmap heap node.  We assume here that the chance
    6742             :          * of a given tuple coming from an exact page is the same as the
    6743             :          * chance that a given page is exact.  This might not be true, but
    6744             :          * it's not clear how we can do any better.
    6745             :          */
    6746          18 :         if (lossy_pages > 0)
    6747             :             tuples_fetched =
    6748          18 :                 clamp_row_est(indexSelectivity *
    6749          18 :                               (exact_pages / heap_pages) * baserel->tuples +
    6750          18 :                               (lossy_pages / heap_pages) * baserel->tuples);
    6751             :     }
    6752             : 
    6753      713824 :     if (cost_p)
    6754      566564 :         *cost_p = indexTotalCost;
    6755      713824 :     if (tuples_p)
    6756      566564 :         *tuples_p = tuples_fetched;
    6757             : 
    6758      713824 :     return pages_fetched;
    6759             : }
    6760             : 
    6761             : /*
    6762             :  * compute_gather_rows
    6763             :  *    Estimate number of rows for gather (merge) nodes.
    6764             :  *
    6765             :  * In a parallel plan, each worker's row estimate is determined by dividing the
    6766             :  * total number of rows by parallel_divisor, which accounts for the leader's
    6767             :  * contribution in addition to the number of workers.  Accordingly, when
    6768             :  * estimating the number of rows for gather (merge) nodes, we multiply the rows
    6769             :  * per worker by the same parallel_divisor to undo the division.
    6770             :  */
    6771             : double
    6772       45740 : compute_gather_rows(Path *path)
    6773             : {
    6774             :     Assert(path->parallel_workers > 0);
    6775             : 
    6776       45740 :     return clamp_row_est(path->rows * get_parallel_divisor(path));
    6777             : }

Generated by: LCOV version 1.16