PostgreSQL Source Code git master
β€’All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
costsize.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/amapi.h"
#include "access/htup_details.h"
#include "access/tsmapi.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "executor/nodeHash.h"
#include "executor/nodeMemoize.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/placeholder.h"
#include "optimizer/plancat.h"
#include "optimizer/restrictinfo.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
#include "utils/selfuncs.h"
#include "utils/spccache.h"
#include "utils/tuplesort.h"
Include dependency graph for costsize.c:

Go to the source code of this file.

Data Structures

struct  cost_qual_eval_context
 

Macros

#define LOG2(x)   (log(x) / 0.693147180559945)
 
#define APPEND_CPU_COST_MULTIPLIER   0.5
 
#define MAXIMUM_ROWCOUNT   1e100
 

Functions

static Listextract_nonindex_conditions (List *qual_clauses, List *indexclauses)
 
static MergeScanSelCachecached_scansel (PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
 
static void cost_rescan (PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
static bool cost_qual_eval_walker (Node *node, cost_qual_eval_context *context)
 
static void get_restriction_qual_cost (PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
 
static bool has_indexed_join_quals (NestPath *path)
 
static double approx_tuple_count (PlannerInfo *root, JoinPath *path, List *quals)
 
static double calc_joinrel_size_estimate (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, double outer_rows, double inner_rows, SpecialJoinInfo *sjinfo, List *restrictlist)
 
static Selectivity get_foreign_key_join_selectivity (PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
 
static Cost append_nonpartial_cost (List *subpaths, int numpaths, int parallel_workers)
 
static void set_rel_width (PlannerInfo *root, RelOptInfo *rel)
 
static int32 get_expr_width (PlannerInfo *root, const Node *expr)
 
static double relation_byte_size (double tuples, int width)
 
static double page_size (double tuples, int width)
 
static double get_parallel_divisor (Path *path)
 
double clamp_row_est (double nrows)
 
int32 clamp_width_est (int64 tuple_width)
 
void cost_seqscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_samplescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
static double get_indexpath_pages (Path *bitmapqual)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_tidrangescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, bool trivial_pathtarget)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_ctescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_namedtuplestorescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_resultscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_recursive_union (Path *runion, Path *nrterm, Path *rterm)
 
static void cost_tuplesort (Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_incremental_sort (Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_sort (Path *path, PlannerInfo *root, List *pathkeys, int input_disabled_nodes, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_append (AppendPath *apath, PlannerInfo *root)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
static void cost_memoize_rescan (PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, int disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
static double get_windowclause_startup_tuples (PlannerInfo *root, WindowClause *wc, double input_tuples)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, WindowClause *winclause, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, int outer_presorted_keys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_subplan (PlannerInfo *root, SubPlan *subplan, Plan *plan)
 
void cost_qual_eval (QualCost *cost, List *quals, PlannerInfo *root)
 
void cost_qual_eval_node (QualCost *cost, Node *qual, PlannerInfo *root)
 
void compute_semi_anti_join_factors (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
 
void set_baserel_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
double get_parameterized_baserel_size (PlannerInfo *root, RelOptInfo *rel, List *param_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_values_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_cte_size_estimates (PlannerInfo *root, RelOptInfo *rel, double cte_rows)
 
void set_namedtuplestore_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_result_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_foreign_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
PathTargetset_pathtarget_cost_width (PlannerInfo *root, PathTarget *target)
 
double compute_bitmap_pages (PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
 
double compute_gather_rows (Path *path)
 

Variables

double seq_page_cost = DEFAULT_SEQ_PAGE_COST
 
double random_page_cost = DEFAULT_RANDOM_PAGE_COST
 
double cpu_tuple_cost = DEFAULT_CPU_TUPLE_COST
 
double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST
 
double cpu_operator_cost = DEFAULT_CPU_OPERATOR_COST
 
double parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST
 
double parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST
 
double recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR
 
int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE
 
Cost disable_cost = 1.0e10
 
int max_parallel_workers_per_gather = 2
 
bool enable_seqscan = true
 
bool enable_indexscan = true
 
bool enable_indexonlyscan = true
 
bool enable_bitmapscan = true
 
bool enable_tidscan = true
 
bool enable_sort = true
 
bool enable_incremental_sort = true
 
bool enable_hashagg = true
 
bool enable_nestloop = true
 
bool enable_material = true
 
bool enable_memoize = true
 
bool enable_mergejoin = true
 
bool enable_hashjoin = true
 
bool enable_gathermerge = true
 
bool enable_partitionwise_join = false
 
bool enable_partitionwise_aggregate = false
 
bool enable_parallel_append = true
 
bool enable_parallel_hash = true
 
bool enable_partition_pruning = true
 
bool enable_presorted_aggregate = true
 
bool enable_async_append = true
 

Macro Definition Documentation

β—† APPEND_CPU_COST_MULTIPLIER

#define APPEND_CPU_COST_MULTIPLIER   0.5

Definition at line 120 of file costsize.c.

β—† LOG2

#define LOG2 (   x)    (log(x) / 0.693147180559945)

Definition at line 113 of file costsize.c.

β—† MAXIMUM_ROWCOUNT

#define MAXIMUM_ROWCOUNT   1e100

Definition at line 128 of file costsize.c.

Function Documentation

β—† append_nonpartial_cost()

static Cost append_nonpartial_cost ( List subpaths,
int  numpaths,
int  parallel_workers 
)
static

Definition at line 2148 of file costsize.c.

2149{
2150 Cost *costarr;
2151 int arrlen;
2152 ListCell *l;
2153 ListCell *cell;
2154 int path_index;
2155 int min_index;
2156 int max_index;
2157
2158 if (numpaths == 0)
2159 return 0;
2160
2161 /*
2162 * Array length is number of workers or number of relevant paths,
2163 * whichever is less.
2164 */
2165 arrlen = Min(parallel_workers, numpaths);
2166 costarr = (Cost *) palloc(sizeof(Cost) * arrlen);
2167
2168 /* The first few paths will each be claimed by a different worker. */
2169 path_index = 0;
2170 foreach(cell, subpaths)
2171 {
2172 Path *subpath = (Path *) lfirst(cell);
2173
2174 if (path_index == arrlen)
2175 break;
2176 costarr[path_index++] = subpath->total_cost;
2177 }
2178
2179 /*
2180 * Since subpaths are sorted by decreasing cost, the last one will have
2181 * the minimum cost.
2182 */
2183 min_index = arrlen - 1;
2184
2185 /*
2186 * For each of the remaining subpaths, add its cost to the array element
2187 * with minimum cost.
2188 */
2189 for_each_cell(l, subpaths, cell)
2190 {
2191 Path *subpath = (Path *) lfirst(l);
2192
2193 /* Consider only the non-partial paths */
2194 if (path_index++ == numpaths)
2195 break;
2196
2197 costarr[min_index] += subpath->total_cost;
2198
2199 /* Update the new min cost array index */
2200 min_index = 0;
2201 for (int i = 0; i < arrlen; i++)
2202 {
2203 if (costarr[i] < costarr[min_index])
2204 min_index = i;
2205 }
2206 }
2207
2208 /* Return the highest cost from the array */
2209 max_index = 0;
2210 for (int i = 0; i < arrlen; i++)
2211 {
2212 if (costarr[i] > costarr[max_index])
2213 max_index = i;
2214 }
2215
2216 return costarr[max_index];
2217}
#define Min(x, y)
Definition: c.h:1007
int i
Definition: isn.c:77
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:311
void * palloc(Size size)
Definition: mcxt.c:1365
double Cost
Definition: nodes.h:261
#define lfirst(lc)
Definition: pg_list.h:172
#define for_each_cell(cell, lst, initcell)
Definition: pg_list.h:438

References for_each_cell, i, lfirst, Min, palloc(), and subpath().

Referenced by cost_append().

β—† approx_tuple_count()

static double approx_tuple_count ( PlannerInfo root,
JoinPath path,
List quals 
)
static

Definition at line 5313 of file costsize.c.

5314{
5315 double tuples;
5316 double outer_tuples = path->outerjoinpath->rows;
5317 double inner_tuples = path->innerjoinpath->rows;
5318 SpecialJoinInfo sjinfo;
5319 Selectivity selec = 1.0;
5320 ListCell *l;
5321
5322 /*
5323 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5324 */
5325 init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
5326 path->innerjoinpath->parent->relids);
5327
5328 /* Get the approximate selectivity */
5329 foreach(l, quals)
5330 {
5331 Node *qual = (Node *) lfirst(l);
5332
5333 /* Note that clause_selectivity will be able to cache its result */
5334 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5335 }
5336
5337 /* Apply it to the input relation sizes */
5338 tuples = selec * outer_tuples * inner_tuples;
5339
5340 return clamp_row_est(tuples);
5341}
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:667
double clamp_row_est(double nrows)
Definition: costsize.c:213
void init_dummy_sjinfo(SpecialJoinInfo *sjinfo, Relids left_relids, Relids right_relids)
Definition: joinrels.c:664
double Selectivity
Definition: nodes.h:260
@ JOIN_INNER
Definition: nodes.h:303
tree ctl root
Definition: radixtree.h:1857
Path * outerjoinpath
Definition: pathnodes.h:2295
Path * innerjoinpath
Definition: pathnodes.h:2296
Definition: nodes.h:135
Cardinality rows
Definition: pathnodes.h:1906

References clamp_row_est(), clause_selectivity(), init_dummy_sjinfo(), JoinPath::innerjoinpath, JOIN_INNER, lfirst, JoinPath::outerjoinpath, root, and Path::rows.

Referenced by final_cost_hashjoin(), and final_cost_mergejoin().

β—† cached_scansel()

static MergeScanSelCache * cached_scansel ( PlannerInfo root,
RestrictInfo rinfo,
PathKey pathkey 
)
static

Definition at line 4089 of file costsize.c.

4090{
4091 MergeScanSelCache *cache;
4092 ListCell *lc;
4093 Selectivity leftstartsel,
4094 leftendsel,
4095 rightstartsel,
4096 rightendsel;
4097 MemoryContext oldcontext;
4098
4099 /* Do we have this result already? */
4100 foreach(lc, rinfo->scansel_cache)
4101 {
4102 cache = (MergeScanSelCache *) lfirst(lc);
4103 if (cache->opfamily == pathkey->pk_opfamily &&
4104 cache->collation == pathkey->pk_eclass->ec_collation &&
4105 cache->cmptype == pathkey->pk_cmptype &&
4106 cache->nulls_first == pathkey->pk_nulls_first)
4107 return cache;
4108 }
4109
4110 /* Nope, do the computation */
4112 (Node *) rinfo->clause,
4113 pathkey->pk_opfamily,
4114 pathkey->pk_cmptype,
4115 pathkey->pk_nulls_first,
4116 &leftstartsel,
4117 &leftendsel,
4118 &rightstartsel,
4119 &rightendsel);
4120
4121 /* Cache the result in suitably long-lived workspace */
4122 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4123
4124 cache = (MergeScanSelCache *) palloc(sizeof(MergeScanSelCache));
4125 cache->opfamily = pathkey->pk_opfamily;
4126 cache->collation = pathkey->pk_eclass->ec_collation;
4127 cache->cmptype = pathkey->pk_cmptype;
4128 cache->nulls_first = pathkey->pk_nulls_first;
4129 cache->leftstartsel = leftstartsel;
4130 cache->leftendsel = leftendsel;
4131 cache->rightstartsel = rightstartsel;
4132 cache->rightendsel = rightendsel;
4133
4134 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4135
4136 MemoryContextSwitchTo(oldcontext);
4137
4138 return cache;
4139}
List * lappend(List *list, void *datum)
Definition: list.c:339
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
void mergejoinscansel(PlannerInfo *root, Node *clause, Oid opfamily, CompareType cmptype, bool nulls_first, Selectivity *leftstart, Selectivity *leftend, Selectivity *rightstart, Selectivity *rightend)
Definition: selfuncs.c:2970
Selectivity leftstartsel
Definition: pathnodes.h:2967
Selectivity leftendsel
Definition: pathnodes.h:2968
CompareType cmptype
Definition: pathnodes.h:2964
Selectivity rightendsel
Definition: pathnodes.h:2970
Selectivity rightstartsel
Definition: pathnodes.h:2969
CompareType pk_cmptype
Definition: pathnodes.h:1716
bool pk_nulls_first
Definition: pathnodes.h:1717
Oid pk_opfamily
Definition: pathnodes.h:1715
Expr * clause
Definition: pathnodes.h:2791

References RestrictInfo::clause, MergeScanSelCache::cmptype, MergeScanSelCache::collation, lappend(), MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, lfirst, MemoryContextSwitchTo(), mergejoinscansel(), MergeScanSelCache::nulls_first, MergeScanSelCache::opfamily, palloc(), PathKey::pk_cmptype, PathKey::pk_nulls_first, PathKey::pk_opfamily, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, and root.

Referenced by initial_cost_mergejoin().

β—† calc_joinrel_size_estimate()

static double calc_joinrel_size_estimate ( PlannerInfo root,
RelOptInfo joinrel,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
double  outer_rows,
double  inner_rows,
SpecialJoinInfo sjinfo,
List restrictlist 
)
static

Definition at line 5510 of file costsize.c.

5518{
5519 JoinType jointype = sjinfo->jointype;
5520 Selectivity fkselec;
5521 Selectivity jselec;
5522 Selectivity pselec;
5523 double nrows;
5524
5525 /*
5526 * Compute joinclause selectivity. Note that we are only considering
5527 * clauses that become restriction clauses at this join level; we are not
5528 * double-counting them because they were not considered in estimating the
5529 * sizes of the component rels.
5530 *
5531 * First, see whether any of the joinclauses can be matched to known FK
5532 * constraints. If so, drop those clauses from the restrictlist, and
5533 * instead estimate their selectivity using FK semantics. (We do this
5534 * without regard to whether said clauses are local or "pushed down".
5535 * Probably, an FK-matching clause could never be seen as pushed down at
5536 * an outer join, since it would be strict and hence would be grounds for
5537 * join strength reduction.) fkselec gets the net selectivity for
5538 * FK-matching clauses, or 1.0 if there are none.
5539 */
5541 outer_rel->relids,
5542 inner_rel->relids,
5543 sjinfo,
5544 &restrictlist);
5545
5546 /*
5547 * For an outer join, we have to distinguish the selectivity of the join's
5548 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5549 * down". For inner joins we just count them all as joinclauses.
5550 */
5551 if (IS_OUTER_JOIN(jointype))
5552 {
5553 List *joinquals = NIL;
5554 List *pushedquals = NIL;
5555 ListCell *l;
5556
5557 /* Grovel through the clauses to separate into two lists */
5558 foreach(l, restrictlist)
5559 {
5561
5562 if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5563 pushedquals = lappend(pushedquals, rinfo);
5564 else
5565 joinquals = lappend(joinquals, rinfo);
5566 }
5567
5568 /* Get the separate selectivities */
5570 joinquals,
5571 0,
5572 jointype,
5573 sjinfo);
5575 pushedquals,
5576 0,
5577 jointype,
5578 sjinfo);
5579
5580 /* Avoid leaking a lot of ListCells */
5581 list_free(joinquals);
5582 list_free(pushedquals);
5583 }
5584 else
5585 {
5587 restrictlist,
5588 0,
5589 jointype,
5590 sjinfo);
5591 pselec = 0.0; /* not used, keep compiler quiet */
5592 }
5593
5594 /*
5595 * Basically, we multiply size of Cartesian product by selectivity.
5596 *
5597 * If we are doing an outer join, take that into account: the joinqual
5598 * selectivity has to be clamped using the knowledge that the output must
5599 * be at least as large as the non-nullable input. However, any
5600 * pushed-down quals are applied after the outer join, so their
5601 * selectivity applies fully.
5602 *
5603 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5604 * of LHS rows that have matches, and we apply that straightforwardly.
5605 */
5606 switch (jointype)
5607 {
5608 case JOIN_INNER:
5609 nrows = outer_rows * inner_rows * fkselec * jselec;
5610 /* pselec not used */
5611 break;
5612 case JOIN_LEFT:
5613 nrows = outer_rows * inner_rows * fkselec * jselec;
5614 if (nrows < outer_rows)
5615 nrows = outer_rows;
5616 nrows *= pselec;
5617 break;
5618 case JOIN_FULL:
5619 nrows = outer_rows * inner_rows * fkselec * jselec;
5620 if (nrows < outer_rows)
5621 nrows = outer_rows;
5622 if (nrows < inner_rows)
5623 nrows = inner_rows;
5624 nrows *= pselec;
5625 break;
5626 case JOIN_SEMI:
5627 nrows = outer_rows * fkselec * jselec;
5628 /* pselec not used */
5629 break;
5630 case JOIN_ANTI:
5631 nrows = outer_rows * (1.0 - fkselec * jselec);
5632 nrows *= pselec;
5633 break;
5634 default:
5635 /* other values not expected here */
5636 elog(ERROR, "unrecognized join type: %d", (int) jointype);
5637 nrows = 0; /* keep compiler quiet */
5638 break;
5639 }
5640
5641 return clamp_row_est(nrows);
5642}
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
static Selectivity get_foreign_key_join_selectivity(PlannerInfo *root, Relids outer_relids, Relids inner_relids, SpecialJoinInfo *sjinfo, List **restrictlist)
Definition: costsize.c:5660
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
void list_free(List *list)
Definition: list.c:1546
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:348
JoinType
Definition: nodes.h:298
@ JOIN_SEMI
Definition: nodes.h:317
@ JOIN_FULL
Definition: nodes.h:305
@ JOIN_LEFT
Definition: nodes.h:304
@ JOIN_ANTI
Definition: nodes.h:318
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2948
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
Definition: pg_list.h:54
Relids relids
Definition: pathnodes.h:927
JoinType jointype
Definition: pathnodes.h:3120

References clamp_row_est(), clauselist_selectivity(), elog, ERROR, get_foreign_key_join_selectivity(), IS_OUTER_JOIN, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst_node, list_free(), NIL, RelOptInfo::relids, RINFO_IS_PUSHED_DOWN, and root.

Referenced by get_parameterized_joinrel_size(), and set_joinrel_size_estimates().

β—† clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 213 of file costsize.c.

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 if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
222 nrows = MAXIMUM_ROWCOUNT;
223 else if (nrows <= 1.0)
224 nrows = 1.0;
225 else
226 nrows = rint(nrows);
227
228 return nrows;
229}
#define MAXIMUM_ROWCOUNT
Definition: costsize.c:128

References MAXIMUM_ROWCOUNT.

Referenced by adjust_limit_rows_costs(), approx_tuple_count(), bernoulli_samplescangetsamplesize(), calc_joinrel_size_estimate(), compute_bitmap_pages(), compute_gather_rows(), cost_agg(), cost_append(), cost_bitmap_heap_scan(), cost_group(), cost_index(), cost_seqscan(), cost_subplan(), cost_subqueryscan(), create_bitmap_subplan(), create_memoize_path(), estimate_array_length(), estimate_hash_bucket_stats(), estimate_num_groups(), estimate_path_cost_size(), estimate_size(), expression_returns_set_rows(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_parameterized_baserel_size(), get_variable_numdistinct(), get_windowclause_startup_tuples(), initial_cost_mergejoin(), set_baserel_size_estimates(), set_cte_size_estimates(), set_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), system_time_samplescangetsamplesize(), and table_block_relation_estimate_size().

β—† clamp_width_est()

int32 clamp_width_est ( int64  tuple_width)

Definition at line 242 of file costsize.c.

243{
244 /*
245 * Anything more than MaxAllocSize is clearly bogus, since we could not
246 * create a tuple that large.
247 */
248 if (tuple_width > MaxAllocSize)
249 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 return (int32) tuple_width;
258}
int32_t int32
Definition: c.h:538
#define MaxAllocSize
Definition: fe_memutils.h:22
Assert(PointerIsAligned(start, uint64))

References Assert(), and MaxAllocSize.

Referenced by add_placeholders_to_joinrel(), build_joinrel_tlist(), create_one_window_path(), get_rel_data_width(), set_pathtarget_cost_width(), and set_rel_width().

β—† compute_bitmap_pages()

double compute_bitmap_pages ( PlannerInfo root,
RelOptInfo baserel,
Path bitmapqual,
double  loop_count,
Cost cost_p,
double *  tuples_p 
)

Definition at line 6523 of file costsize.c.

6526{
6527 Cost indexTotalCost;
6528 Selectivity indexSelectivity;
6529 double T;
6530 double pages_fetched;
6531 double tuples_fetched;
6532 double heap_pages;
6533 double maxentries;
6534
6535 /*
6536 * Fetch total cost of obtaining the bitmap, as well as its total
6537 * selectivity.
6538 */
6539 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6540
6541 /*
6542 * Estimate number of main-table pages fetched.
6543 */
6544 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6545
6546 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6547
6548 /*
6549 * For a single scan, the number of heap pages that need to be fetched is
6550 * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6551 * re-reads needed).
6552 */
6553 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6554
6555 /*
6556 * Calculate the number of pages fetched from the heap. Then based on
6557 * current work_mem estimate get the estimated maxentries in the bitmap.
6558 * (Note that we always do this calculation based on the number of pages
6559 * that would be fetched in a single iteration, even if loop_count > 1.
6560 * That's correct, because only that number of entries will be stored in
6561 * the bitmap at one time.)
6562 */
6563 heap_pages = Min(pages_fetched, baserel->pages);
6564 maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
6565
6566 if (loop_count > 1)
6567 {
6568 /*
6569 * For repeated bitmap scans, scale up the number of tuples fetched in
6570 * the Mackert and Lohman formula by the number of scans, so that we
6571 * estimate the number of pages fetched by all the scans. Then
6572 * pro-rate for one scan.
6573 */
6574 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6575 baserel->pages,
6576 get_indexpath_pages(bitmapqual),
6577 root);
6578 pages_fetched /= loop_count;
6579 }
6580
6581 if (pages_fetched >= T)
6582 pages_fetched = T;
6583 else
6584 pages_fetched = ceil(pages_fetched);
6585
6586 if (maxentries < heap_pages)
6587 {
6588 double exact_pages;
6589 double lossy_pages;
6590
6591 /*
6592 * Crude approximation of the number of lossy pages. Because of the
6593 * way tbm_lossify() is coded, the number of lossy pages increases
6594 * very sharply as soon as we run short of memory; this formula has
6595 * that property and seems to perform adequately in testing, but it's
6596 * possible we could do better somehow.
6597 */
6598 lossy_pages = Max(0, heap_pages - maxentries / 2);
6599 exact_pages = heap_pages - lossy_pages;
6600
6601 /*
6602 * If there are lossy pages then recompute the number of tuples
6603 * processed by the bitmap heap node. We assume here that the chance
6604 * of a given tuple coming from an exact page is the same as the
6605 * chance that a given page is exact. This might not be true, but
6606 * it's not clear how we can do any better.
6607 */
6608 if (lossy_pages > 0)
6609 tuples_fetched =
6610 clamp_row_est(indexSelectivity *
6611 (exact_pages / heap_pages) * baserel->tuples +
6612 (lossy_pages / heap_pages) * baserel->tuples);
6613 }
6614
6615 if (cost_p)
6616 *cost_p = indexTotalCost;
6617 if (tuples_p)
6618 *tuples_p = tuples_fetched;
6619
6620 return pages_fetched;
6621}
#define Max(x, y)
Definition: c.h:1001
size_t Size
Definition: c.h:614
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:882
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1096
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:947
int work_mem
Definition: globals.c:131
static const uint32 T[65]
Definition: md5.c:119
Cardinality tuples
Definition: pathnodes.h:1000
BlockNumber pages
Definition: pathnodes.h:999
int tbm_calculate_entries(Size maxbytes)
Definition: tidbitmap.c:1546

References clamp_row_est(), cost_bitmap_tree_node(), get_indexpath_pages(), index_pages_fetched(), Max, Min, RelOptInfo::pages, root, T, tbm_calculate_entries(), RelOptInfo::tuples, and work_mem.

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

β—† compute_gather_rows()

double compute_gather_rows ( Path path)

Definition at line 6634 of file costsize.c.

6635{
6636 Assert(path->parallel_workers > 0);
6637
6638 return clamp_row_est(path->rows * get_parallel_divisor(path));
6639}
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6483
int parallel_workers
Definition: pathnodes.h:1903

References Assert(), clamp_row_est(), get_parallel_divisor(), Path::parallel_workers, and Path::rows.

Referenced by create_ordered_paths(), gather_grouping_paths(), generate_gather_paths(), and generate_useful_gather_paths().

β—† compute_semi_anti_join_factors()

void compute_semi_anti_join_factors ( PlannerInfo root,
RelOptInfo joinrel,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
SpecialJoinInfo sjinfo,
List restrictlist,
SemiAntiJoinFactors semifactors 
)

Definition at line 5123 of file costsize.c.

5131{
5132 Selectivity jselec;
5133 Selectivity nselec;
5134 Selectivity avgmatch;
5135 SpecialJoinInfo norm_sjinfo;
5136 List *joinquals;
5137 ListCell *l;
5138
5139 /*
5140 * In an ANTI join, we must ignore clauses that are "pushed down", since
5141 * those won't affect the match logic. In a SEMI join, we do not
5142 * distinguish joinquals from "pushed down" quals, so just use the whole
5143 * restrictinfo list. For other outer join types, we should consider only
5144 * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5145 */
5146 if (IS_OUTER_JOIN(jointype))
5147 {
5148 joinquals = NIL;
5149 foreach(l, restrictlist)
5150 {
5152
5153 if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5154 joinquals = lappend(joinquals, rinfo);
5155 }
5156 }
5157 else
5158 joinquals = restrictlist;
5159
5160 /*
5161 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5162 */
5164 joinquals,
5165 0,
5166 (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5167 sjinfo);
5168
5169 /*
5170 * Also get the normal inner-join selectivity of the join clauses.
5171 */
5172 init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
5173
5175 joinquals,
5176 0,
5177 JOIN_INNER,
5178 &norm_sjinfo);
5179
5180 /* Avoid leaking a lot of ListCells */
5181 if (IS_OUTER_JOIN(jointype))
5182 list_free(joinquals);
5183
5184 /*
5185 * jselec can be interpreted as the fraction of outer-rel rows that have
5186 * any matches (this is true for both SEMI and ANTI cases). And nselec is
5187 * the fraction of the Cartesian product that matches. So, the average
5188 * number of matches for each outer-rel row that has at least one match is
5189 * nselec * inner_rows / jselec.
5190 *
5191 * Note: it is correct to use the inner rel's "rows" count here, even
5192 * though we might later be considering a parameterized inner path with
5193 * fewer rows. This is because we have included all the join clauses in
5194 * the selectivity estimate.
5195 */
5196 if (jselec > 0) /* protect against zero divide */
5197 {
5198 avgmatch = nselec * innerrel->rows / jselec;
5199 /* Clamp to sane range */
5200 avgmatch = Max(1.0, avgmatch);
5201 }
5202 else
5203 avgmatch = 1.0;
5204
5205 semifactors->outer_match_frac = jselec;
5206 semifactors->match_count = avgmatch;
5207}
Cardinality rows
Definition: pathnodes.h:933
Selectivity outer_match_frac
Definition: pathnodes.h:3476
Selectivity match_count
Definition: pathnodes.h:3477

References clauselist_selectivity(), init_dummy_sjinfo(), IS_OUTER_JOIN, JOIN_ANTI, JOIN_INNER, JOIN_SEMI, lappend(), lfirst_node, list_free(), SemiAntiJoinFactors::match_count, Max, NIL, SemiAntiJoinFactors::outer_match_frac, RelOptInfo::relids, RINFO_IS_PUSHED_DOWN, root, and RelOptInfo::rows.

Referenced by add_paths_to_joinrel().

β—† cost_agg()

void cost_agg ( Path path,
PlannerInfo root,
AggStrategy  aggstrategy,
const AggClauseCosts aggcosts,
int  numGroupCols,
double  numGroups,
List quals,
int  disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples,
double  input_width 
)

Definition at line 2688 of file costsize.c.

2695{
2696 double output_tuples;
2697 Cost startup_cost;
2698 Cost total_cost;
2699 const AggClauseCosts dummy_aggcosts = {0};
2700
2701 /* Use all-zero per-aggregate costs if NULL is passed */
2702 if (aggcosts == NULL)
2703 {
2704 Assert(aggstrategy == AGG_HASHED);
2705 aggcosts = &dummy_aggcosts;
2706 }
2707
2708 /*
2709 * The transCost.per_tuple component of aggcosts should be charged once
2710 * per input tuple, corresponding to the costs of evaluating the aggregate
2711 * transfns and their input expressions. The finalCost.per_tuple component
2712 * is charged once per output tuple, corresponding to the costs of
2713 * evaluating the finalfns. Startup costs are of course charged but once.
2714 *
2715 * If we are grouping, we charge an additional cpu_operator_cost per
2716 * grouping column per input tuple for grouping comparisons.
2717 *
2718 * We will produce a single output tuple if not grouping, and a tuple per
2719 * group otherwise. We charge cpu_tuple_cost for each output tuple.
2720 *
2721 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2722 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2723 * input path is already sorted appropriately, AGG_SORTED should be
2724 * preferred (since it has no risk of memory overflow). This will happen
2725 * as long as the computed total costs are indeed exactly equal --- but if
2726 * there's roundoff error we might do the wrong thing. So be sure that
2727 * the computations below form the same intermediate values in the same
2728 * order.
2729 */
2730 if (aggstrategy == AGG_PLAIN)
2731 {
2732 startup_cost = input_total_cost;
2733 startup_cost += aggcosts->transCost.startup;
2734 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2735 startup_cost += aggcosts->finalCost.startup;
2736 startup_cost += aggcosts->finalCost.per_tuple;
2737 /* we aren't grouping */
2738 total_cost = startup_cost + cpu_tuple_cost;
2739 output_tuples = 1;
2740 }
2741 else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2742 {
2743 /* Here we are able to deliver output on-the-fly */
2744 startup_cost = input_startup_cost;
2745 total_cost = input_total_cost;
2746 if (aggstrategy == AGG_MIXED && !enable_hashagg)
2747 ++disabled_nodes;
2748 /* calcs phrased this way to match HASHED case, see note above */
2749 total_cost += aggcosts->transCost.startup;
2750 total_cost += aggcosts->transCost.per_tuple * input_tuples;
2751 total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2752 total_cost += aggcosts->finalCost.startup;
2753 total_cost += aggcosts->finalCost.per_tuple * numGroups;
2754 total_cost += cpu_tuple_cost * numGroups;
2755 output_tuples = numGroups;
2756 }
2757 else
2758 {
2759 /* must be AGG_HASHED */
2760 startup_cost = input_total_cost;
2761 if (!enable_hashagg)
2762 ++disabled_nodes;
2763 startup_cost += aggcosts->transCost.startup;
2764 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2765 /* cost of computing hash value */
2766 startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2767 startup_cost += aggcosts->finalCost.startup;
2768
2769 total_cost = startup_cost;
2770 total_cost += aggcosts->finalCost.per_tuple * numGroups;
2771 /* cost of retrieving from hash table */
2772 total_cost += cpu_tuple_cost * numGroups;
2773 output_tuples = numGroups;
2774 }
2775
2776 /*
2777 * Add the disk costs of hash aggregation that spills to disk.
2778 *
2779 * Groups that go into the hash table stay in memory until finalized, so
2780 * spilling and reprocessing tuples doesn't incur additional invocations
2781 * of transCost or finalCost. Furthermore, the computed hash value is
2782 * stored with the spilled tuples, so we don't incur extra invocations of
2783 * the hash function.
2784 *
2785 * Hash Agg begins returning tuples after the first batch is complete.
2786 * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2787 * accrue reads only to total_cost.
2788 */
2789 if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2790 {
2791 double pages;
2792 double pages_written = 0.0;
2793 double pages_read = 0.0;
2794 double spill_cost;
2795 double hashentrysize;
2796 double nbatches;
2797 Size mem_limit;
2798 uint64 ngroups_limit;
2799 int num_partitions;
2800 int depth;
2801
2802 /*
2803 * Estimate number of batches based on the computed limits. If less
2804 * than or equal to one, all groups are expected to fit in memory;
2805 * otherwise we expect to spill.
2806 */
2807 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2808 input_width,
2809 aggcosts->transitionSpace);
2810 hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2811 &ngroups_limit, &num_partitions);
2812
2813 nbatches = Max((numGroups * hashentrysize) / mem_limit,
2814 numGroups / ngroups_limit);
2815
2816 nbatches = Max(ceil(nbatches), 1.0);
2817 num_partitions = Max(num_partitions, 2);
2818
2819 /*
2820 * The number of partitions can change at different levels of
2821 * recursion; but for the purposes of this calculation assume it stays
2822 * constant.
2823 */
2824 depth = ceil(log(nbatches) / log(num_partitions));
2825
2826 /*
2827 * Estimate number of pages read and written. For each level of
2828 * recursion, a tuple must be written and then later read.
2829 */
2830 pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2831 pages_written = pages_read = pages * depth;
2832
2833 /*
2834 * HashAgg has somewhat worse IO behavior than Sort on typical
2835 * hardware/OS combinations. Account for this with a generic penalty.
2836 */
2837 pages_read *= 2.0;
2838 pages_written *= 2.0;
2839
2840 startup_cost += pages_written * random_page_cost;
2841 total_cost += pages_written * random_page_cost;
2842 total_cost += pages_read * seq_page_cost;
2843
2844 /* account for CPU cost of spilling a tuple and reading it back */
2845 spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2846 startup_cost += spill_cost;
2847 total_cost += spill_cost;
2848 }
2849
2850 /*
2851 * If there are quals (HAVING quals), account for their cost and
2852 * selectivity.
2853 */
2854 if (quals)
2855 {
2856 QualCost qual_cost;
2857
2858 cost_qual_eval(&qual_cost, quals, root);
2859 startup_cost += qual_cost.startup;
2860 total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2861
2862 output_tuples = clamp_row_est(output_tuples *
2864 quals,
2865 0,
2866 JOIN_INNER,
2867 NULL));
2868 }
2869
2870 path->rows = output_tuples;
2871 path->disabled_nodes = disabled_nodes;
2872 path->startup_cost = startup_cost;
2873 path->total_cost = total_cost;
2874}
uint64_t uint64
Definition: c.h:543
double random_page_cost
Definition: costsize.c:131
double cpu_operator_cost
Definition: costsize.c:134
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6462
double cpu_tuple_cost
Definition: costsize.c:132
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4765
double seq_page_cost
Definition: costsize.c:130
bool enable_hashagg
Definition: costsize.c:152
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1698
void hash_agg_set_limits(double hashentrysize, double input_groups, int used_bits, Size *mem_limit, uint64 *ngroups_limit, int *num_partitions)
Definition: nodeAgg.c:1806
@ AGG_SORTED
Definition: nodes.h:365
@ AGG_HASHED
Definition: nodes.h:366
@ AGG_MIXED
Definition: nodes.h:367
@ AGG_PLAIN
Definition: nodes.h:364
static int list_length(const List *l)
Definition: pg_list.h:152
QualCost finalCost
Definition: pathnodes.h:61
Size transitionSpace
Definition: pathnodes.h:62
QualCost transCost
Definition: pathnodes.h:60
Cost startup_cost
Definition: pathnodes.h:1908
int disabled_nodes
Definition: pathnodes.h:1907
Cost total_cost
Definition: pathnodes.h:1909
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, Assert(), clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, enable_hashagg, AggClauseCosts::finalCost, hash_agg_entry_size(), hash_agg_set_limits(), JOIN_INNER, list_length(), Max, QualCost::per_tuple, random_page_cost, relation_byte_size(), root, Path::rows, seq_page_cost, QualCost::startup, Path::startup_cost, Path::total_cost, AggClauseCosts::transCost, and AggClauseCosts::transitionSpace.

Referenced by create_agg_path(), and create_groupingsets_path().

β—† cost_append()

void cost_append ( AppendPath apath,
PlannerInfo root 
)

Definition at line 2224 of file costsize.c.

2225{
2226 ListCell *l;
2227
2228 apath->path.disabled_nodes = 0;
2229 apath->path.startup_cost = 0;
2230 apath->path.total_cost = 0;
2231 apath->path.rows = 0;
2232
2233 if (apath->subpaths == NIL)
2234 return;
2235
2236 if (!apath->path.parallel_aware)
2237 {
2238 List *pathkeys = apath->path.pathkeys;
2239
2240 if (pathkeys == NIL)
2241 {
2242 Path *firstsubpath = (Path *) linitial(apath->subpaths);
2243
2244 /*
2245 * For an unordered, non-parallel-aware Append we take the startup
2246 * cost as the startup cost of the first subpath.
2247 */
2248 apath->path.startup_cost = firstsubpath->startup_cost;
2249
2250 /*
2251 * Compute rows, number of disabled nodes, and total cost as sums
2252 * of underlying subplan values.
2253 */
2254 foreach(l, apath->subpaths)
2255 {
2256 Path *subpath = (Path *) lfirst(l);
2257
2258 apath->path.rows += subpath->rows;
2259 apath->path.disabled_nodes += subpath->disabled_nodes;
2260 apath->path.total_cost += subpath->total_cost;
2261 }
2262 }
2263 else
2264 {
2265 /*
2266 * For an ordered, non-parallel-aware Append we take the startup
2267 * cost as the sum of the subpath startup costs. This ensures
2268 * that we don't underestimate the startup cost when a query's
2269 * LIMIT is such that several of the children have to be run to
2270 * satisfy it. This might be overkill --- another plausible hack
2271 * would be to take the Append's startup cost as the maximum of
2272 * the child startup costs. But we don't want to risk believing
2273 * that an ORDER BY LIMIT query can be satisfied at small cost
2274 * when the first child has small startup cost but later ones
2275 * don't. (If we had the ability to deal with nonlinear cost
2276 * interpolation for partial retrievals, we would not need to be
2277 * so conservative about this.)
2278 *
2279 * This case is also different from the above in that we have to
2280 * account for possibly injecting sorts into subpaths that aren't
2281 * natively ordered.
2282 */
2283 foreach(l, apath->subpaths)
2284 {
2285 Path *subpath = (Path *) lfirst(l);
2286 int presorted_keys;
2287 Path sort_path; /* dummy for result of
2288 * cost_sort/cost_incremental_sort */
2289
2290 if (!pathkeys_count_contained_in(pathkeys, subpath->pathkeys,
2291 &presorted_keys))
2292 {
2293 /*
2294 * We'll need to insert a Sort node, so include costs for
2295 * that. We choose to use incremental sort if it is
2296 * enabled and there are presorted keys; otherwise we use
2297 * full sort.
2298 *
2299 * We can use the parent's LIMIT if any, since we
2300 * certainly won't pull more than that many tuples from
2301 * any child.
2302 */
2303 if (enable_incremental_sort && presorted_keys > 0)
2304 {
2305 cost_incremental_sort(&sort_path,
2306 root,
2307 pathkeys,
2308 presorted_keys,
2309 subpath->disabled_nodes,
2310 subpath->startup_cost,
2311 subpath->total_cost,
2312 subpath->rows,
2313 subpath->pathtarget->width,
2314 0.0,
2315 work_mem,
2316 apath->limit_tuples);
2317 }
2318 else
2319 {
2320 cost_sort(&sort_path,
2321 root,
2322 pathkeys,
2323 subpath->disabled_nodes,
2324 subpath->total_cost,
2325 subpath->rows,
2326 subpath->pathtarget->width,
2327 0.0,
2328 work_mem,
2329 apath->limit_tuples);
2330 }
2331
2332 subpath = &sort_path;
2333 }
2334
2335 apath->path.rows += subpath->rows;
2336 apath->path.disabled_nodes += subpath->disabled_nodes;
2337 apath->path.startup_cost += subpath->startup_cost;
2338 apath->path.total_cost += subpath->total_cost;
2339 }
2340 }
2341 }
2342 else /* parallel-aware */
2343 {
2344 int i = 0;
2345 double parallel_divisor = get_parallel_divisor(&apath->path);
2346
2347 /* Parallel-aware Append never produces ordered output. */
2348 Assert(apath->path.pathkeys == NIL);
2349
2350 /* Calculate startup cost. */
2351 foreach(l, apath->subpaths)
2352 {
2353 Path *subpath = (Path *) lfirst(l);
2354
2355 /*
2356 * Append will start returning tuples when the child node having
2357 * lowest startup cost is done setting up. We consider only the
2358 * first few subplans that immediately get a worker assigned.
2359 */
2360 if (i == 0)
2361 apath->path.startup_cost = subpath->startup_cost;
2362 else if (i < apath->path.parallel_workers)
2363 apath->path.startup_cost = Min(apath->path.startup_cost,
2364 subpath->startup_cost);
2365
2366 /*
2367 * Apply parallel divisor to subpaths. Scale the number of rows
2368 * for each partial subpath based on the ratio of the parallel
2369 * divisor originally used for the subpath to the one we adopted.
2370 * Also add the cost of partial paths to the total cost, but
2371 * ignore non-partial paths for now.
2372 */
2373 if (i < apath->first_partial_path)
2374 apath->path.rows += subpath->rows / parallel_divisor;
2375 else
2376 {
2377 double subpath_parallel_divisor;
2378
2379 subpath_parallel_divisor = get_parallel_divisor(subpath);
2380 apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2381 parallel_divisor);
2382 apath->path.total_cost += subpath->total_cost;
2383 }
2384
2385 apath->path.disabled_nodes += subpath->disabled_nodes;
2386 apath->path.rows = clamp_row_est(apath->path.rows);
2387
2388 i++;
2389 }
2390
2391 /* Add cost for non-partial subpaths. */
2392 apath->path.total_cost +=
2394 apath->first_partial_path,
2395 apath->path.parallel_workers);
2396 }
2397
2398 /*
2399 * Although Append does not do any selection or projection, it's not free;
2400 * add a small per-tuple overhead.
2401 */
2402 apath->path.total_cost +=
2404}
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:120
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, int input_disabled_nodes, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:2118
void cost_incremental_sort(Path *path, PlannerInfo *root, List *pathkeys, int presorted_keys, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1974
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:2148
bool enable_incremental_sort
Definition: costsize.c:151
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:558
#define linitial(l)
Definition: pg_list.h:178
int first_partial_path
Definition: pathnodes.h:2181
Cardinality limit_tuples
Definition: pathnodes.h:2182
List * subpaths
Definition: pathnodes.h:2179
List * pathkeys
Definition: pathnodes.h:1912
bool parallel_aware
Definition: pathnodes.h:1899

References APPEND_CPU_COST_MULTIPLIER, append_nonpartial_cost(), Assert(), clamp_row_est(), cost_incremental_sort(), cost_sort(), cpu_tuple_cost, Path::disabled_nodes, enable_incremental_sort, AppendPath::first_partial_path, get_parallel_divisor(), i, lfirst, AppendPath::limit_tuples, linitial, Min, NIL, Path::parallel_aware, Path::parallel_workers, AppendPath::path, Path::pathkeys, pathkeys_count_contained_in(), root, Path::rows, Path::startup_cost, subpath(), AppendPath::subpaths, Path::total_cost, and work_mem.

Referenced by create_append_path().

β—† cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1139 of file costsize.c.

1140{
1141 Cost totalCost;
1142 Selectivity selec;
1143 ListCell *l;
1144
1145 /*
1146 * We estimate AND selectivity on the assumption that the inputs are
1147 * independent. This is probably often wrong, but we don't have the info
1148 * to do better.
1149 *
1150 * The runtime cost of the BitmapAnd itself is estimated at 100x
1151 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1152 * definitely too simplistic?
1153 */
1154 totalCost = 0.0;
1155 selec = 1.0;
1156 foreach(l, path->bitmapquals)
1157 {
1158 Path *subpath = (Path *) lfirst(l);
1159 Cost subCost;
1160 Selectivity subselec;
1161
1162 cost_bitmap_tree_node(subpath, &subCost, &subselec);
1163
1164 selec *= subselec;
1165
1166 totalCost += subCost;
1167 if (l != list_head(path->bitmapquals))
1168 totalCost += 100.0 * cpu_operator_cost;
1169 }
1170 path->bitmapselectivity = selec;
1171 path->path.rows = 0; /* per above, not used */
1172 path->path.disabled_nodes = 0;
1173 path->path.startup_cost = totalCost;
1174 path->path.total_cost = totalCost;
1175}
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
Selectivity bitmapselectivity
Definition: pathnodes.h:2045
List * bitmapquals
Definition: pathnodes.h:2044

References BitmapAndPath::bitmapquals, BitmapAndPath::bitmapselectivity, cost_bitmap_tree_node(), cpu_operator_cost, Path::disabled_nodes, lfirst, list_head(), BitmapAndPath::path, Path::rows, Path::startup_cost, subpath(), and Path::total_cost.

Referenced by create_bitmap_and_path().

β—† cost_bitmap_heap_scan()

void cost_bitmap_heap_scan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
Path bitmapqual,
double  loop_count 
)

Definition at line 997 of file costsize.c.

1000{
1001 Cost startup_cost = 0;
1002 Cost run_cost = 0;
1003 Cost indexTotalCost;
1004 QualCost qpqual_cost;
1005 Cost cpu_per_tuple;
1006 Cost cost_per_page;
1007 Cost cpu_run_cost;
1008 double tuples_fetched;
1009 double pages_fetched;
1010 double spc_seq_page_cost,
1011 spc_random_page_cost;
1012 double T;
1013
1014 /* Should only be applied to base relations */
1015 Assert(IsA(baserel, RelOptInfo));
1016 Assert(baserel->relid > 0);
1017 Assert(baserel->rtekind == RTE_RELATION);
1018
1019 /* Mark the path with the correct row estimate */
1020 if (param_info)
1021 path->rows = param_info->ppi_rows;
1022 else
1023 path->rows = baserel->rows;
1024
1025 pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
1026 loop_count, &indexTotalCost,
1027 &tuples_fetched);
1028
1029 startup_cost += indexTotalCost;
1030 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1031
1032 /* Fetch estimated page costs for tablespace containing table. */
1034 &spc_random_page_cost,
1035 &spc_seq_page_cost);
1036
1037 /*
1038 * For small numbers of pages we should charge spc_random_page_cost
1039 * apiece, while if nearly all the table's pages are being read, it's more
1040 * appropriate to charge spc_seq_page_cost apiece. The effect is
1041 * nonlinear, too. For lack of a better idea, interpolate like this to
1042 * determine the cost per page.
1043 */
1044 if (pages_fetched >= 2.0)
1045 cost_per_page = spc_random_page_cost -
1046 (spc_random_page_cost - spc_seq_page_cost)
1047 * sqrt(pages_fetched / T);
1048 else
1049 cost_per_page = spc_random_page_cost;
1050
1051 run_cost += pages_fetched * cost_per_page;
1052
1053 /*
1054 * Estimate CPU costs per tuple.
1055 *
1056 * Often the indexquals don't need to be rechecked at each tuple ... but
1057 * not always, especially not if there are enough tuples involved that the
1058 * bitmaps become lossy. For the moment, just assume they will be
1059 * rechecked always. This means we charge the full freight for all the
1060 * scan clauses.
1061 */
1062 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1063
1064 startup_cost += qpqual_cost.startup;
1065 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1066 cpu_run_cost = cpu_per_tuple * tuples_fetched;
1067
1068 /* Adjust costing for parallelism, if used. */
1069 if (path->parallel_workers > 0)
1070 {
1071 double parallel_divisor = get_parallel_divisor(path);
1072
1073 /* The CPU cost is divided among all the workers. */
1074 cpu_run_cost /= parallel_divisor;
1075
1076 path->rows = clamp_row_est(path->rows / parallel_divisor);
1077 }
1078
1079
1080 run_cost += cpu_run_cost;
1081
1082 /* tlist eval costs are paid per output row, not per tuple scanned */
1083 startup_cost += path->pathtarget->cost.startup;
1084 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1085
1086 path->disabled_nodes = enable_bitmapscan ? 0 : 1;
1087 path->startup_cost = startup_cost;
1088 path->total_cost = startup_cost + run_cost;
1089}
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:5081
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition: costsize.c:6523
bool enable_bitmapscan
Definition: costsize.c:148
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
@ RTE_RELATION
Definition: parsenodes.h:1043
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Cardinality ppi_rows
Definition: pathnodes.h:1826
Index relid
Definition: pathnodes.h:973
Oid reltablespace
Definition: pathnodes.h:975
RTEKind rtekind
Definition: pathnodes.h:977

References Assert(), clamp_row_est(), compute_bitmap_pages(), cpu_tuple_cost, Path::disabled_nodes, enable_bitmapscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, RelOptInfo::pages, Path::parallel_workers, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, T, and Path::total_cost.

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

β—† cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1184 of file costsize.c.

1185{
1186 Cost totalCost;
1187 Selectivity selec;
1188 ListCell *l;
1189
1190 /*
1191 * We estimate OR selectivity on the assumption that the inputs are
1192 * non-overlapping, since that's often the case in "x IN (list)" type
1193 * situations. Of course, we clamp to 1.0 at the end.
1194 *
1195 * The runtime cost of the BitmapOr itself is estimated at 100x
1196 * cpu_operator_cost for each tbm_union needed. Probably too small,
1197 * definitely too simplistic? We are aware that the tbm_unions are
1198 * optimized out when the inputs are BitmapIndexScans.
1199 */
1200 totalCost = 0.0;
1201 selec = 0.0;
1202 foreach(l, path->bitmapquals)
1203 {
1204 Path *subpath = (Path *) lfirst(l);
1205 Cost subCost;
1206 Selectivity subselec;
1207
1208 cost_bitmap_tree_node(subpath, &subCost, &subselec);
1209
1210 selec += subselec;
1211
1212 totalCost += subCost;
1213 if (l != list_head(path->bitmapquals) &&
1215 totalCost += 100.0 * cpu_operator_cost;
1216 }
1217 path->bitmapselectivity = Min(selec, 1.0);
1218 path->path.rows = 0; /* per above, not used */
1219 path->path.startup_cost = totalCost;
1220 path->path.total_cost = totalCost;
1221}
Selectivity bitmapselectivity
Definition: pathnodes.h:2058
List * bitmapquals
Definition: pathnodes.h:2057

References BitmapOrPath::bitmapquals, BitmapOrPath::bitmapselectivity, cost_bitmap_tree_node(), cpu_operator_cost, IsA, lfirst, list_head(), Min, BitmapOrPath::path, Path::rows, Path::startup_cost, subpath(), and Path::total_cost.

Referenced by create_bitmap_or_path().

β—† cost_bitmap_tree_node()

void cost_bitmap_tree_node ( Path path,
Cost cost,
Selectivity selec 
)

Definition at line 1096 of file costsize.c.

1097{
1098 if (IsA(path, IndexPath))
1099 {
1100 *cost = ((IndexPath *) path)->indextotalcost;
1101 *selec = ((IndexPath *) path)->indexselectivity;
1102
1103 /*
1104 * Charge a small amount per retrieved tuple to reflect the costs of
1105 * manipulating the bitmap. This is mostly to make sure that a bitmap
1106 * scan doesn't look to be the same cost as an indexscan to retrieve a
1107 * single tuple.
1108 */
1109 *cost += 0.1 * cpu_operator_cost * path->rows;
1110 }
1111 else if (IsA(path, BitmapAndPath))
1112 {
1113 *cost = path->total_cost;
1114 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1115 }
1116 else if (IsA(path, BitmapOrPath))
1117 {
1118 *cost = path->total_cost;
1119 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1120 }
1121 else
1122 {
1123 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1124 *cost = *selec = 0; /* keep compiler quiet */
1125 }
1126}
#define nodeTag(nodeptr)
Definition: nodes.h:139

References cpu_operator_cost, elog, ERROR, IsA, nodeTag, Path::rows, and Path::total_cost.

Referenced by choose_bitmap_and(), compute_bitmap_pages(), cost_bitmap_and_node(), cost_bitmap_or_node(), and path_usage_comparator().

β—† cost_ctescan()

void cost_ctescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1682 of file costsize.c.

1684{
1685 Cost startup_cost = 0;
1686 Cost run_cost = 0;
1687 QualCost qpqual_cost;
1688 Cost cpu_per_tuple;
1689
1690 /* Should only be applied to base relations that are CTEs */
1691 Assert(baserel->relid > 0);
1692 Assert(baserel->rtekind == RTE_CTE);
1693
1694 /* Mark the path with the correct row estimate */
1695 if (param_info)
1696 path->rows = param_info->ppi_rows;
1697 else
1698 path->rows = baserel->rows;
1699
1700 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1701 cpu_per_tuple = cpu_tuple_cost;
1702
1703 /* Add scanning CPU costs */
1704 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1705
1706 startup_cost += qpqual_cost.startup;
1707 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1708 run_cost += cpu_per_tuple * baserel->tuples;
1709
1710 /* tlist eval costs are paid per output row, not per tuple scanned */
1711 startup_cost += path->pathtarget->cost.startup;
1712 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1713
1714 path->disabled_nodes = 0;
1715 path->startup_cost = startup_cost;
1716 path->total_cost = startup_cost + run_cost;
1717}
@ RTE_CTE
Definition: parsenodes.h:1049

References Assert(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, RelOptInfo::rows, Path::rows, RTE_CTE, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_ctescan_path(), and create_worktablescan_path().

β—† cost_functionscan()

void cost_functionscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1512 of file costsize.c.

1514{
1515 Cost startup_cost = 0;
1516 Cost run_cost = 0;
1517 QualCost qpqual_cost;
1518 Cost cpu_per_tuple;
1519 RangeTblEntry *rte;
1520 QualCost exprcost;
1521
1522 /* Should only be applied to base relations that are functions */
1523 Assert(baserel->relid > 0);
1524 rte = planner_rt_fetch(baserel->relid, root);
1525 Assert(rte->rtekind == RTE_FUNCTION);
1526
1527 /* Mark the path with the correct row estimate */
1528 if (param_info)
1529 path->rows = param_info->ppi_rows;
1530 else
1531 path->rows = baserel->rows;
1532
1533 /*
1534 * Estimate costs of executing the function expression(s).
1535 *
1536 * Currently, nodeFunctionscan.c always executes the functions to
1537 * completion before returning any rows, and caches the results in a
1538 * tuplestore. So the function eval cost is all startup cost, and per-row
1539 * costs are minimal.
1540 *
1541 * XXX in principle we ought to charge tuplestore spill costs if the
1542 * number of rows is large. However, given how phony our rowcount
1543 * estimates for functions tend to be, there's not a lot of point in that
1544 * refinement right now.
1545 */
1546 cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1547
1548 startup_cost += exprcost.startup + exprcost.per_tuple;
1549
1550 /* Add scanning CPU costs */
1551 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1552
1553 startup_cost += qpqual_cost.startup;
1554 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1555 run_cost += cpu_per_tuple * baserel->tuples;
1556
1557 /* tlist eval costs are paid per output row, not per tuple scanned */
1558 startup_cost += path->pathtarget->cost.startup;
1559 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1560
1561 path->disabled_nodes = 0;
1562 path->startup_cost = startup_cost;
1563 path->total_cost = startup_cost + run_cost;
1564}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4791
@ RTE_FUNCTION
Definition: parsenodes.h:1046
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:610
List * functions
Definition: parsenodes.h:1208
RTEKind rtekind
Definition: parsenodes.h:1078

References Assert(), cost_qual_eval_node(), cpu_tuple_cost, Path::disabled_nodes, RangeTblEntry::functions, get_restriction_qual_cost(), QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, RelOptInfo::rows, Path::rows, RTE_FUNCTION, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_functionscan_path().

β—† cost_gather()

void cost_gather ( GatherPath path,
PlannerInfo root,
RelOptInfo rel,
ParamPathInfo param_info,
double *  rows 
)

Definition at line 420 of file costsize.c.

423{
424 Cost startup_cost = 0;
425 Cost run_cost = 0;
426
427 /* Mark the path with the correct row estimate */
428 if (rows)
429 path->path.rows = *rows;
430 else if (param_info)
431 path->path.rows = param_info->ppi_rows;
432 else
433 path->path.rows = rel->rows;
434
435 startup_cost = path->subpath->startup_cost;
436
437 run_cost = path->subpath->total_cost - path->subpath->startup_cost;
438
439 /* Parallel setup and communication cost. */
440 startup_cost += parallel_setup_cost;
441 run_cost += parallel_tuple_cost * path->path.rows;
442
444 path->path.startup_cost = startup_cost;
445 path->path.total_cost = (startup_cost + run_cost);
446}
double parallel_setup_cost
Definition: costsize.c:136
double parallel_tuple_cost
Definition: costsize.c:135
Path * subpath
Definition: pathnodes.h:2263

References Path::disabled_nodes, parallel_setup_cost, parallel_tuple_cost, GatherPath::path, ParamPathInfo::ppi_rows, RelOptInfo::rows, Path::rows, Path::startup_cost, GatherPath::subpath, and Path::total_cost.

Referenced by create_gather_path().

β—† cost_gather_merge()

void cost_gather_merge ( GatherMergePath path,
PlannerInfo root,
RelOptInfo rel,
ParamPathInfo param_info,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double *  rows 
)

Definition at line 459 of file costsize.c.

464{
465 Cost startup_cost = 0;
466 Cost run_cost = 0;
467 Cost comparison_cost;
468 double N;
469 double logN;
470
471 /* Mark the path with the correct row estimate */
472 if (rows)
473 path->path.rows = *rows;
474 else if (param_info)
475 path->path.rows = param_info->ppi_rows;
476 else
477 path->path.rows = rel->rows;
478
479 /*
480 * Add one to the number of workers to account for the leader. This might
481 * be overgenerous since the leader will do less work than other workers
482 * in typical cases, but we'll go with it for now.
483 */
484 Assert(path->num_workers > 0);
485 N = (double) path->num_workers + 1;
486 logN = LOG2(N);
487
488 /* Assumed cost per tuple comparison */
489 comparison_cost = 2.0 * cpu_operator_cost;
490
491 /* Heap creation cost */
492 startup_cost += comparison_cost * N * logN;
493
494 /* Per-tuple heap maintenance cost */
495 run_cost += path->path.rows * comparison_cost * logN;
496
497 /* small cost for heap management, like cost_merge_append */
498 run_cost += cpu_operator_cost * path->path.rows;
499
500 /*
501 * Parallel setup and communication cost. Since Gather Merge, unlike
502 * Gather, requires us to block until a tuple is available from every
503 * worker, we bump the IPC cost up a little bit as compared with Gather.
504 * For lack of a better idea, charge an extra 5%.
505 */
506 startup_cost += parallel_setup_cost;
507 run_cost += parallel_tuple_cost * path->path.rows * 1.05;
508
509 path->path.disabled_nodes = input_disabled_nodes
510 + (enable_gathermerge ? 0 : 1);
511 path->path.startup_cost = startup_cost + input_startup_cost;
512 path->path.total_cost = (startup_cost + run_cost + input_total_cost);
513}
#define LOG2(x)
Definition: costsize.c:113
bool enable_gathermerge
Definition: costsize.c:158

References Assert(), cpu_operator_cost, Path::disabled_nodes, enable_gathermerge, LOG2, GatherMergePath::num_workers, parallel_setup_cost, parallel_tuple_cost, GatherMergePath::path, ParamPathInfo::ppi_rows, RelOptInfo::rows, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_gather_merge_path().

β—† cost_group()

void cost_group ( Path path,
PlannerInfo root,
int  numGroupCols,
double  numGroups,
List quals,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 3201 of file costsize.c.

3207{
3208 double output_tuples;
3209 Cost startup_cost;
3210 Cost total_cost;
3211
3212 output_tuples = numGroups;
3213 startup_cost = input_startup_cost;
3214 total_cost = input_total_cost;
3215
3216 /*
3217 * Charge one cpu_operator_cost per comparison per input tuple. We assume
3218 * all columns get compared at most of the tuples.
3219 */
3220 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3221
3222 /*
3223 * If there are quals (HAVING quals), account for their cost and
3224 * selectivity.
3225 */
3226 if (quals)
3227 {
3228 QualCost qual_cost;
3229
3230 cost_qual_eval(&qual_cost, quals, root);
3231 startup_cost += qual_cost.startup;
3232 total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3233
3234 output_tuples = clamp_row_est(output_tuples *
3236 quals,
3237 0,
3238 JOIN_INNER,
3239 NULL));
3240 }
3241
3242 path->rows = output_tuples;
3243 path->disabled_nodes = input_disabled_nodes;
3244 path->startup_cost = startup_cost;
3245 path->total_cost = total_cost;
3246}

References clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, Path::disabled_nodes, JOIN_INNER, QualCost::per_tuple, root, Path::rows, QualCost::startup, Path::startup_cost, and Path::total_cost.

Referenced by create_group_path().

β—† cost_incremental_sort()

void cost_incremental_sort ( Path path,
PlannerInfo root,
List pathkeys,
int  presorted_keys,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)

Definition at line 1974 of file costsize.c.

1980{
1981 Cost startup_cost,
1982 run_cost,
1983 input_run_cost = input_total_cost - input_startup_cost;
1984 double group_tuples,
1985 input_groups;
1986 Cost group_startup_cost,
1987 group_run_cost,
1988 group_input_run_cost;
1989 List *presortedExprs = NIL;
1990 ListCell *l;
1991 bool unknown_varno = false;
1992
1993 Assert(presorted_keys > 0 && presorted_keys < list_length(pathkeys));
1994
1995 /*
1996 * We want to be sure the cost of a sort is never estimated as zero, even
1997 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1998 */
1999 if (input_tuples < 2.0)
2000 input_tuples = 2.0;
2001
2002 /* Default estimate of number of groups, capped to one group per row. */
2003 input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
2004
2005 /*
2006 * Extract presorted keys as list of expressions.
2007 *
2008 * We need to be careful about Vars containing "varno 0" which might have
2009 * been introduced by generate_append_tlist, which would confuse
2010 * estimate_num_groups (in fact it'd fail for such expressions). See
2011 * recurse_set_operations which has to deal with the same issue.
2012 *
2013 * Unlike recurse_set_operations we can't access the original target list
2014 * here, and even if we could it's not very clear how useful would that be
2015 * for a set operation combining multiple tables. So we simply detect if
2016 * there are any expressions with "varno 0" and use the default
2017 * DEFAULT_NUM_DISTINCT in that case.
2018 *
2019 * We might also use either 1.0 (a single group) or input_tuples (each row
2020 * being a separate group), pretty much the worst and best case for
2021 * incremental sort. But those are extreme cases and using something in
2022 * between seems reasonable. Furthermore, generate_append_tlist is used
2023 * for set operations, which are likely to produce mostly unique output
2024 * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2025 * while maintaining lower startup cost.
2026 */
2027 foreach(l, pathkeys)
2028 {
2029 PathKey *key = (PathKey *) lfirst(l);
2031 linitial(key->pk_eclass->ec_members);
2032
2033 /*
2034 * Check if the expression contains Var with "varno 0" so that we
2035 * don't call estimate_num_groups in that case.
2036 */
2037 if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2038 {
2039 unknown_varno = true;
2040 break;
2041 }
2042
2043 /* expression not containing any Vars with "varno 0" */
2044 presortedExprs = lappend(presortedExprs, member->em_expr);
2045
2046 if (foreach_current_index(l) + 1 >= presorted_keys)
2047 break;
2048 }
2049
2050 /* Estimate the number of groups with equal presorted keys. */
2051 if (!unknown_varno)
2052 input_groups = estimate_num_groups(root, presortedExprs, input_tuples,
2053 NULL, NULL);
2054
2055 group_tuples = input_tuples / input_groups;
2056 group_input_run_cost = input_run_cost / input_groups;
2057
2058 /*
2059 * Estimate the average cost of sorting of one group where presorted keys
2060 * are equal.
2061 */
2062 cost_tuplesort(&group_startup_cost, &group_run_cost,
2063 group_tuples, width, comparison_cost, sort_mem,
2064 limit_tuples);
2065
2066 /*
2067 * Startup cost of incremental sort is the startup cost of its first group
2068 * plus the cost of its input.
2069 */
2070 startup_cost = group_startup_cost + input_startup_cost +
2071 group_input_run_cost;
2072
2073 /*
2074 * After we started producing tuples from the first group, the cost of
2075 * producing all the tuples is given by the cost to finish processing this
2076 * group, plus the total cost to process the remaining groups, plus the
2077 * remaining cost of input.
2078 */
2079 run_cost = group_run_cost + (group_run_cost + group_startup_cost) *
2080 (input_groups - 1) + group_input_run_cost * (input_groups - 1);
2081
2082 /*
2083 * Incremental sort adds some overhead by itself. Firstly, it has to
2084 * detect the sort groups. This is roughly equal to one extra copy and
2085 * comparison per tuple.
2086 */
2087 run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2088
2089 /*
2090 * Additionally, we charge double cpu_tuple_cost for each input group to
2091 * account for the tuplesort_reset that's performed after each group.
2092 */
2093 run_cost += 2.0 * cpu_tuple_cost * input_groups;
2094
2095 path->rows = input_tuples;
2096
2097 /* should not generate these paths when enable_incremental_sort=false */
2099 path->disabled_nodes = input_disabled_nodes;
2100
2101 path->startup_cost = startup_cost;
2102 path->total_cost = startup_cost + run_cost;
2103}
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
static void cost_tuplesort(Cost *startup_cost, Cost *run_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1872
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
double estimate_num_groups(PlannerInfo *root, List *groupExprs, double input_rows, List **pgset, EstimationInfo *estinfo)
Definition: selfuncs.c:3456
#define DEFAULT_NUM_DISTINCT
Definition: selfuncs.h:52
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:114

References Assert(), bms_is_member(), cost_tuplesort(), cpu_tuple_cost, DEFAULT_NUM_DISTINCT, Path::disabled_nodes, EquivalenceMember::em_expr, enable_incremental_sort, estimate_num_groups(), foreach_current_index, sort-test::key, lappend(), lfirst, linitial, list_length(), Min, NIL, pull_varnos(), root, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by cost_append(), create_incremental_sort_path(), create_merge_append_path(), initial_cost_mergejoin(), and label_incrementalsort_with_costsize().

β—† cost_index()

void cost_index ( IndexPath path,
PlannerInfo root,
double  loop_count,
bool  partial_path 
)

Definition at line 534 of file costsize.c.

536{
538 RelOptInfo *baserel = index->rel;
539 bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
540 amcostestimate_function amcostestimate;
541 List *qpquals;
542 Cost startup_cost = 0;
543 Cost run_cost = 0;
544 Cost cpu_run_cost = 0;
545 Cost indexStartupCost;
546 Cost indexTotalCost;
547 Selectivity indexSelectivity;
548 double indexCorrelation,
549 csquared;
550 double spc_seq_page_cost,
551 spc_random_page_cost;
552 Cost min_IO_cost,
553 max_IO_cost;
554 QualCost qpqual_cost;
555 Cost cpu_per_tuple;
556 double tuples_fetched;
557 double pages_fetched;
558 double rand_heap_pages;
559 double index_pages;
560
561 /* Should only be applied to base relations */
562 Assert(IsA(baserel, RelOptInfo) &&
564 Assert(baserel->relid > 0);
565 Assert(baserel->rtekind == RTE_RELATION);
566
567 /*
568 * Mark the path with the correct row estimate, and identify which quals
569 * will need to be enforced as qpquals. We need not check any quals that
570 * are implied by the index's predicate, so we can use indrestrictinfo not
571 * baserestrictinfo as the list of relevant restriction clauses for the
572 * rel.
573 */
574 if (path->path.param_info)
575 {
576 path->path.rows = path->path.param_info->ppi_rows;
577 /* qpquals come from the rel's restriction clauses and ppi_clauses */
579 path->indexclauses),
580 extract_nonindex_conditions(path->path.param_info->ppi_clauses,
581 path->indexclauses));
582 }
583 else
584 {
585 path->path.rows = baserel->rows;
586 /* qpquals come from just the rel's restriction clauses */
588 path->indexclauses);
589 }
590
591 /* we don't need to check enable_indexonlyscan; indxpath.c does that */
592 path->path.disabled_nodes = enable_indexscan ? 0 : 1;
593
594 /*
595 * Call index-access-method-specific code to estimate the processing cost
596 * for scanning the index, as well as the selectivity of the index (ie,
597 * the fraction of main-table tuples we will have to retrieve) and its
598 * correlation to the main-table tuple order. We need a cast here because
599 * pathnodes.h uses a weak function type to avoid including amapi.h.
600 */
601 amcostestimate = (amcostestimate_function) index->amcostestimate;
602 amcostestimate(root, path, loop_count,
603 &indexStartupCost, &indexTotalCost,
604 &indexSelectivity, &indexCorrelation,
605 &index_pages);
606
607 /*
608 * Save amcostestimate's results for possible use in bitmap scan planning.
609 * We don't bother to save indexStartupCost or indexCorrelation, because a
610 * bitmap scan doesn't care about either.
611 */
612 path->indextotalcost = indexTotalCost;
613 path->indexselectivity = indexSelectivity;
614
615 /* all costs for touching index itself included here */
616 startup_cost += indexStartupCost;
617 run_cost += indexTotalCost - indexStartupCost;
618
619 /* estimate number of main-table tuples fetched */
620 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
621
622 /* fetch estimated page costs for tablespace containing table */
624 &spc_random_page_cost,
625 &spc_seq_page_cost);
626
627 /*----------
628 * Estimate number of main-table pages fetched, and compute I/O cost.
629 *
630 * When the index ordering is uncorrelated with the table ordering,
631 * we use an approximation proposed by Mackert and Lohman (see
632 * index_pages_fetched() for details) to compute the number of pages
633 * fetched, and then charge spc_random_page_cost per page fetched.
634 *
635 * When the index ordering is exactly correlated with the table ordering
636 * (just after a CLUSTER, for example), the number of pages fetched should
637 * be exactly selectivity * table_size. What's more, all but the first
638 * will be sequential fetches, not the random fetches that occur in the
639 * uncorrelated case. So if the number of pages is more than 1, we
640 * ought to charge
641 * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
642 * For partially-correlated indexes, we ought to charge somewhere between
643 * these two estimates. We currently interpolate linearly between the
644 * estimates based on the correlation squared (XXX is that appropriate?).
645 *
646 * If it's an index-only scan, then we will not need to fetch any heap
647 * pages for which the visibility map shows all tuples are visible.
648 * Hence, reduce the estimated number of heap fetches accordingly.
649 * We use the measured fraction of the entire heap that is all-visible,
650 * which might not be particularly relevant to the subset of the heap
651 * that this query will fetch; but it's not clear how to do better.
652 *----------
653 */
654 if (loop_count > 1)
655 {
656 /*
657 * For repeated indexscans, the appropriate estimate for the
658 * uncorrelated case is to scale up the number of tuples fetched in
659 * the Mackert and Lohman formula by the number of scans, so that we
660 * estimate the number of pages fetched by all the scans; then
661 * pro-rate the costs for one scan. In this case we assume all the
662 * fetches are random accesses.
663 */
664 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
665 baserel->pages,
666 (double) index->pages,
667 root);
668
669 if (indexonly)
670 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
671
672 rand_heap_pages = pages_fetched;
673
674 max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
675
676 /*
677 * In the perfectly correlated case, the number of pages touched by
678 * each scan is selectivity * table_size, and we can use the Mackert
679 * and Lohman formula at the page level to estimate how much work is
680 * saved by caching across scans. We still assume all the fetches are
681 * random, though, which is an overestimate that's hard to correct for
682 * without double-counting the cache effects. (But in most cases
683 * where such a plan is actually interesting, only one page would get
684 * fetched per scan anyway, so it shouldn't matter much.)
685 */
686 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
687
688 pages_fetched = index_pages_fetched(pages_fetched * loop_count,
689 baserel->pages,
690 (double) index->pages,
691 root);
692
693 if (indexonly)
694 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
695
696 min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
697 }
698 else
699 {
700 /*
701 * Normal case: apply the Mackert and Lohman formula, and then
702 * interpolate between that and the correlation-derived result.
703 */
704 pages_fetched = index_pages_fetched(tuples_fetched,
705 baserel->pages,
706 (double) index->pages,
707 root);
708
709 if (indexonly)
710 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
711
712 rand_heap_pages = pages_fetched;
713
714 /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
715 max_IO_cost = pages_fetched * spc_random_page_cost;
716
717 /* min_IO_cost is for the perfectly correlated case (csquared=1) */
718 pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
719
720 if (indexonly)
721 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
722
723 if (pages_fetched > 0)
724 {
725 min_IO_cost = spc_random_page_cost;
726 if (pages_fetched > 1)
727 min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
728 }
729 else
730 min_IO_cost = 0;
731 }
732
733 if (partial_path)
734 {
735 /*
736 * For index only scans compute workers based on number of index pages
737 * fetched; the number of heap pages we fetch might be so small as to
738 * effectively rule out parallelism, which we don't want to do.
739 */
740 if (indexonly)
741 rand_heap_pages = -1;
742
743 /*
744 * Estimate the number of parallel workers required to scan index. Use
745 * the number of heap pages computed considering heap fetches won't be
746 * sequential as for parallel scans the pages are accessed in random
747 * order.
748 */
750 rand_heap_pages,
751 index_pages,
753
754 /*
755 * Fall out if workers can't be assigned for parallel scan, because in
756 * such a case this path will be rejected. So there is no benefit in
757 * doing extra computation.
758 */
759 if (path->path.parallel_workers <= 0)
760 return;
761
762 path->path.parallel_aware = true;
763 }
764
765 /*
766 * Now interpolate based on estimated index order correlation to get total
767 * disk I/O cost for main table accesses.
768 */
769 csquared = indexCorrelation * indexCorrelation;
770
771 run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
772
773 /*
774 * Estimate CPU costs per tuple.
775 *
776 * What we want here is cpu_tuple_cost plus the evaluation costs of any
777 * qual clauses that we have to evaluate as qpquals.
778 */
779 cost_qual_eval(&qpqual_cost, qpquals, root);
780
781 startup_cost += qpqual_cost.startup;
782 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
783
784 cpu_run_cost += cpu_per_tuple * tuples_fetched;
785
786 /* tlist eval costs are paid per output row, not per tuple scanned */
787 startup_cost += path->path.pathtarget->cost.startup;
788 cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
789
790 /* Adjust costing for parallelism, if used. */
791 if (path->path.parallel_workers > 0)
792 {
793 double parallel_divisor = get_parallel_divisor(&path->path);
794
795 path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
796
797 /* The CPU cost is divided among all the workers. */
798 cpu_run_cost /= parallel_divisor;
799 }
800
801 run_cost += cpu_run_cost;
802
803 path->path.startup_cost = startup_cost;
804 path->path.total_cost = startup_cost + run_cost;
805}
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4702
void(* amcostestimate_function)(PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: amapi.h:148
int max_parallel_workers_per_gather
Definition: costsize.c:143
static List * extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
Definition: costsize.c:824
bool enable_indexscan
Definition: costsize.c:146
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
List * indrestrictinfo
Definition: pathnodes.h:1320
List * indexclauses
Definition: pathnodes.h:1958
Path path
Definition: pathnodes.h:1956
Selectivity indexselectivity
Definition: pathnodes.h:1963
Cost indextotalcost
Definition: pathnodes.h:1962
IndexOptInfo * indexinfo
Definition: pathnodes.h:1957
NodeTag pathtype
Definition: pathnodes.h:1872
double allvisfrac
Definition: pathnodes.h:1001
Definition: type.h:96

References RelOptInfo::allvisfrac, Assert(), clamp_row_est(), compute_parallel_worker(), cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, enable_indexscan, extract_nonindex_conditions(), get_parallel_divisor(), get_tablespace_page_costs(), index_pages_fetched(), IndexPath::indexclauses, IndexPath::indexinfo, IndexPath::indexselectivity, IndexPath::indextotalcost, IndexOptInfo::indrestrictinfo, IsA, list_concat(), max_parallel_workers_per_gather, RelOptInfo::pages, Path::parallel_aware, Path::parallel_workers, IndexPath::path, Path::pathtype, QualCost::per_tuple, RelOptInfo::relid, RelOptInfo::reltablespace, root, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_index_path(), and reparameterize_path().

β—† cost_material()

void cost_material ( Path path,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  tuples,
int  width 
)

Definition at line 2483 of file costsize.c.

2487{
2488 Cost startup_cost = input_startup_cost;
2489 Cost run_cost = input_total_cost - input_startup_cost;
2490 double nbytes = relation_byte_size(tuples, width);
2491 double work_mem_bytes = work_mem * (Size) 1024;
2492
2493 path->rows = tuples;
2494
2495 /*
2496 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2497 * reflect bookkeeping overhead. (This rate must be more than what
2498 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2499 * if it is exactly the same then there will be a cost tie between
2500 * nestloop with A outer, materialized B inner and nestloop with B outer,
2501 * materialized A inner. The extra cost ensures we'll prefer
2502 * materializing the smaller rel.) Note that this is normally a good deal
2503 * less than cpu_tuple_cost; which is OK because a Material plan node
2504 * doesn't do qual-checking or projection, so it's got less overhead than
2505 * most plan nodes.
2506 */
2507 run_cost += 2 * cpu_operator_cost * tuples;
2508
2509 /*
2510 * If we will spill to disk, charge at the rate of seq_page_cost per page.
2511 * This cost is assumed to be evenly spread through the plan run phase,
2512 * which isn't exactly accurate but our cost model doesn't allow for
2513 * nonuniform costs within the run phase.
2514 */
2515 if (nbytes > work_mem_bytes)
2516 {
2517 double npages = ceil(nbytes / BLCKSZ);
2518
2519 run_cost += seq_page_cost * npages;
2520 }
2521
2522 path->disabled_nodes = input_disabled_nodes + (enable_material ? 0 : 1);
2523 path->startup_cost = startup_cost;
2524 path->total_cost = startup_cost + run_cost;
2525}
bool enable_material
Definition: costsize.c:154

References cpu_operator_cost, Path::disabled_nodes, enable_material, relation_byte_size(), Path::rows, seq_page_cost, Path::startup_cost, Path::total_cost, and work_mem.

Referenced by create_material_path(), and materialize_finished_plan().

β—† cost_memoize_rescan()

static void cost_memoize_rescan ( PlannerInfo root,
MemoizePath mpath,
Cost rescan_startup_cost,
Cost rescan_total_cost 
)
static

Definition at line 2541 of file costsize.c.

2543{
2544 EstimationInfo estinfo;
2545 ListCell *lc;
2546 Cost input_startup_cost = mpath->subpath->startup_cost;
2547 Cost input_total_cost = mpath->subpath->total_cost;
2548 double tuples = mpath->subpath->rows;
2549 Cardinality est_calls = mpath->est_calls;
2550 int width = mpath->subpath->pathtarget->width;
2551
2552 double hash_mem_bytes;
2553 double est_entry_bytes;
2554 Cardinality est_cache_entries;
2555 Cardinality ndistinct;
2556 double evict_ratio;
2557 double hit_ratio;
2558 Cost startup_cost;
2559 Cost total_cost;
2560
2561 /* available cache space */
2562 hash_mem_bytes = get_hash_memory_limit();
2563
2564 /*
2565 * Set the number of bytes each cache entry should consume in the cache.
2566 * To provide us with better estimations on how many cache entries we can
2567 * store at once, we make a call to the executor here to ask it what
2568 * memory overheads there are for a single cache entry.
2569 */
2570 est_entry_bytes = relation_byte_size(tuples, width) +
2572
2573 /* include the estimated width for the cache keys */
2574 foreach(lc, mpath->param_exprs)
2575 est_entry_bytes += get_expr_width(root, (Node *) lfirst(lc));
2576
2577 /* estimate on the upper limit of cache entries we can hold at once */
2578 est_cache_entries = floor(hash_mem_bytes / est_entry_bytes);
2579
2580 /* estimate on the distinct number of parameter values */
2581 ndistinct = estimate_num_groups(root, mpath->param_exprs, est_calls, NULL,
2582 &estinfo);
2583
2584 /*
2585 * When the estimation fell back on using a default value, it's a bit too
2586 * risky to assume that it's ok to use a Memoize node. The use of a
2587 * default could cause us to use a Memoize node when it's really
2588 * inappropriate to do so. If we see that this has been done, then we'll
2589 * assume that every call will have unique parameters, which will almost
2590 * certainly mean a MemoizePath will never survive add_path().
2591 */
2592 if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2593 ndistinct = est_calls;
2594
2595 /* Remember the ndistinct estimate for EXPLAIN */
2596 mpath->est_unique_keys = ndistinct;
2597
2598 /*
2599 * Since we've already estimated the maximum number of entries we can
2600 * store at once and know the estimated number of distinct values we'll be
2601 * called with, we'll take this opportunity to set the path's est_entries.
2602 * This will ultimately determine the hash table size that the executor
2603 * will use. If we leave this at zero, the executor will just choose the
2604 * size itself. Really this is not the right place to do this, but it's
2605 * convenient since everything is already calculated.
2606 */
2607 mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2609
2610 /*
2611 * When the number of distinct parameter values is above the amount we can
2612 * store in the cache, then we'll have to evict some entries from the
2613 * cache. This is not free. Here we estimate how often we'll incur the
2614 * cost of that eviction.
2615 */
2616 evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2617
2618 /*
2619 * In order to estimate how costly a single scan will be, we need to
2620 * attempt to estimate what the cache hit ratio will be. To do that we
2621 * must look at how many scans are estimated in total for this node and
2622 * how many of those scans we expect to get a cache hit.
2623 */
2624 hit_ratio = ((est_calls - ndistinct) / est_calls) *
2625 (est_cache_entries / Max(ndistinct, est_cache_entries));
2626
2627 /* Remember the hit ratio estimate for EXPLAIN */
2628 mpath->est_hit_ratio = hit_ratio;
2629
2630 Assert(hit_ratio >= 0 && hit_ratio <= 1.0);
2631
2632 /*
2633 * Set the total_cost accounting for the expected cache hit ratio. We
2634 * also add on a cpu_operator_cost to account for a cache lookup. This
2635 * will happen regardless of whether it's a cache hit or not.
2636 */
2637 total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2638
2639 /* Now adjust the total cost to account for cache evictions */
2640
2641 /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2642 total_cost += cpu_tuple_cost * evict_ratio;
2643
2644 /*
2645 * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2646 * The per-tuple eviction is really just a pfree, so charging a whole
2647 * cpu_operator_cost seems a little excessive.
2648 */
2649 total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2650
2651 /*
2652 * Now adjust for storing things in the cache, since that's not free
2653 * either. Everything must go in the cache. We don't proportion this
2654 * over any ratio, just apply it once for the scan. We charge a
2655 * cpu_tuple_cost for the creation of the cache entry and also a
2656 * cpu_operator_cost for each tuple we expect to cache.
2657 */
2658 total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2659
2660 /*
2661 * Getting the first row must be also be proportioned according to the
2662 * expected cache hit ratio.
2663 */
2664 startup_cost = input_startup_cost * (1.0 - hit_ratio);
2665
2666 /*
2667 * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2668 * which we'll do regardless of whether it was a cache hit or not.
2669 */
2670 startup_cost += cpu_tuple_cost;
2671
2672 *rescan_startup_cost = startup_cost;
2673 *rescan_total_cost = total_cost;
2674}
#define PG_UINT32_MAX
Definition: c.h:599
static int32 get_expr_width(PlannerInfo *root, const Node *expr)
Definition: costsize.c:6414
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3621
double ExecEstimateCacheEntryOverheadBytes(double ntuples)
Definition: nodeMemoize.c:1172
double Cardinality
Definition: nodes.h:262
#define SELFLAG_USED_DEFAULT
Definition: selfuncs.h:76
uint32 flags
Definition: selfuncs.h:80
Cardinality est_calls
Definition: pathnodes.h:2250
uint32 est_entries
Definition: pathnodes.h:2247
double est_hit_ratio
Definition: pathnodes.h:2252
Cardinality est_unique_keys
Definition: pathnodes.h:2251
Path * subpath
Definition: pathnodes.h:2240
List * param_exprs
Definition: pathnodes.h:2242

References Assert(), cpu_operator_cost, cpu_tuple_cost, MemoizePath::est_calls, MemoizePath::est_entries, MemoizePath::est_hit_ratio, MemoizePath::est_unique_keys, estimate_num_groups(), ExecEstimateCacheEntryOverheadBytes(), EstimationInfo::flags, get_expr_width(), get_hash_memory_limit(), lfirst, Max, Min, MemoizePath::param_exprs, PG_UINT32_MAX, relation_byte_size(), root, Path::rows, SELFLAG_USED_DEFAULT, Path::startup_cost, MemoizePath::subpath, and Path::total_cost.

Referenced by cost_rescan().

β—† cost_merge_append()

void cost_merge_append ( Path path,
PlannerInfo root,
List pathkeys,
int  n_streams,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  tuples 
)

Definition at line 2432 of file costsize.c.

2437{
2438 Cost startup_cost = 0;
2439 Cost run_cost = 0;
2440 Cost comparison_cost;
2441 double N;
2442 double logN;
2443
2444 /*
2445 * Avoid log(0)...
2446 */
2447 N = (n_streams < 2) ? 2.0 : (double) n_streams;
2448 logN = LOG2(N);
2449
2450 /* Assumed cost per tuple comparison */
2451 comparison_cost = 2.0 * cpu_operator_cost;
2452
2453 /* Heap creation cost */
2454 startup_cost += comparison_cost * N * logN;
2455
2456 /* Per-tuple heap maintenance cost */
2457 run_cost += tuples * comparison_cost * logN;
2458
2459 /*
2460 * Although MergeAppend does not do any selection or projection, it's not
2461 * free; add a small per-tuple overhead.
2462 */
2463 run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2464
2465 path->disabled_nodes = input_disabled_nodes;
2466 path->startup_cost = startup_cost + input_startup_cost;
2467 path->total_cost = startup_cost + run_cost + input_total_cost;
2468}

References APPEND_CPU_COST_MULTIPLIER, cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, LOG2, Path::startup_cost, and Path::total_cost.

Referenced by create_merge_append_path().

β—† cost_namedtuplestorescan()

void cost_namedtuplestorescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1724 of file costsize.c.

1726{
1727 Cost startup_cost = 0;
1728 Cost run_cost = 0;
1729 QualCost qpqual_cost;
1730 Cost cpu_per_tuple;
1731
1732 /* Should only be applied to base relations that are Tuplestores */
1733 Assert(baserel->relid > 0);
1734 Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1735
1736 /* Mark the path with the correct row estimate */
1737 if (param_info)
1738 path->rows = param_info->ppi_rows;
1739 else
1740 path->rows = baserel->rows;
1741
1742 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1743 cpu_per_tuple = cpu_tuple_cost;
1744
1745 /* Add scanning CPU costs */
1746 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1747
1748 startup_cost += qpqual_cost.startup;
1749 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1750 run_cost += cpu_per_tuple * baserel->tuples;
1751
1752 path->disabled_nodes = 0;
1753 path->startup_cost = startup_cost;
1754 path->total_cost = startup_cost + run_cost;
1755}
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1050

References Assert(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, RelOptInfo::rows, Path::rows, RTE_NAMEDTUPLESTORE, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_namedtuplestorescan_path().

β—† cost_qual_eval()

void cost_qual_eval ( QualCost cost,
List quals,
PlannerInfo root 
)

Definition at line 4765 of file costsize.c.

4766{
4767 cost_qual_eval_context context;
4768 ListCell *l;
4769
4770 context.root = root;
4771 context.total.startup = 0;
4772 context.total.per_tuple = 0;
4773
4774 /* We don't charge any cost for the implicit ANDing at top level ... */
4775
4776 foreach(l, quals)
4777 {
4778 Node *qual = (Node *) lfirst(l);
4779
4780 cost_qual_eval_walker(qual, &context);
4781 }
4782
4783 *cost = context.total;
4784}
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4805
PlannerInfo * root
Definition: costsize.c:169

References cost_qual_eval_walker(), lfirst, QualCost::per_tuple, cost_qual_eval_context::root, root, QualCost::startup, and cost_qual_eval_context::total.

Referenced by add_foreign_grouping_paths(), cost_agg(), cost_group(), cost_index(), cost_subplan(), cost_tidrangescan(), cost_tidscan(), create_group_result_path(), create_minmaxagg_path(), estimate_path_cost_size(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_restriction_qual_cost(), inline_function(), plan_cluster_use_sort(), postgresGetForeignJoinPaths(), postgresGetForeignRelSize(), set_baserel_size_estimates(), and set_foreign_size_estimates().

β—† cost_qual_eval_node()

β—† cost_qual_eval_walker()

static bool cost_qual_eval_walker ( Node node,
cost_qual_eval_context context 
)
static

Definition at line 4805 of file costsize.c.

4806{
4807 if (node == NULL)
4808 return false;
4809
4810 /*
4811 * RestrictInfo nodes contain an eval_cost field reserved for this
4812 * routine's use, so that it's not necessary to evaluate the qual clause's
4813 * cost more than once. If the clause's cost hasn't been computed yet,
4814 * the field's startup value will contain -1.
4815 */
4816 if (IsA(node, RestrictInfo))
4817 {
4818 RestrictInfo *rinfo = (RestrictInfo *) node;
4819
4820 if (rinfo->eval_cost.startup < 0)
4821 {
4822 cost_qual_eval_context locContext;
4823
4824 locContext.root = context->root;
4825 locContext.total.startup = 0;
4826 locContext.total.per_tuple = 0;
4827
4828 /*
4829 * For an OR clause, recurse into the marked-up tree so that we
4830 * set the eval_cost for contained RestrictInfos too.
4831 */
4832 if (rinfo->orclause)
4833 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4834 else
4835 cost_qual_eval_walker((Node *) rinfo->clause, &locContext);
4836
4837 /*
4838 * If the RestrictInfo is marked pseudoconstant, it will be tested
4839 * only once, so treat its cost as all startup cost.
4840 */
4841 if (rinfo->pseudoconstant)
4842 {
4843 /* count one execution during startup */
4844 locContext.total.startup += locContext.total.per_tuple;
4845 locContext.total.per_tuple = 0;
4846 }
4847 rinfo->eval_cost = locContext.total;
4848 }
4849 context->total.startup += rinfo->eval_cost.startup;
4850 context->total.per_tuple += rinfo->eval_cost.per_tuple;
4851 /* do NOT recurse into children */
4852 return false;
4853 }
4854
4855 /*
4856 * For each operator or function node in the given tree, we charge the
4857 * estimated execution cost given by pg_proc.procost (remember to multiply
4858 * this by cpu_operator_cost).
4859 *
4860 * Vars and Consts are charged zero, and so are boolean operators (AND,
4861 * OR, NOT). Simplistic, but a lot better than no model at all.
4862 *
4863 * Should we try to account for the possibility of short-circuit
4864 * evaluation of AND/OR? Probably *not*, because that would make the
4865 * results depend on the clause ordering, and we are not in any position
4866 * to expect that the current ordering of the clauses is the one that's
4867 * going to end up being used. The above per-RestrictInfo caching would
4868 * not mix well with trying to re-order clauses anyway.
4869 *
4870 * Another issue that is entirely ignored here is that if a set-returning
4871 * function is below top level in the tree, the functions/operators above
4872 * it will need to be evaluated multiple times. In practical use, such
4873 * cases arise so seldom as to not be worth the added complexity needed;
4874 * moreover, since our rowcount estimates for functions tend to be pretty
4875 * phony, the results would also be pretty phony.
4876 */
4877 if (IsA(node, FuncExpr))
4878 {
4879 add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
4880 &context->total);
4881 }
4882 else if (IsA(node, OpExpr) ||
4883 IsA(node, DistinctExpr) ||
4884 IsA(node, NullIfExpr))
4885 {
4886 /* rely on struct equivalence to treat these all alike */
4887 set_opfuncid((OpExpr *) node);
4888 add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
4889 &context->total);
4890 }
4891 else if (IsA(node, ScalarArrayOpExpr))
4892 {
4893 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
4894 Node *arraynode = (Node *) lsecond(saop->args);
4895 QualCost sacosts;
4896 QualCost hcosts;
4897 double estarraylen = estimate_array_length(context->root, arraynode);
4898
4899 set_sa_opfuncid(saop);
4900 sacosts.startup = sacosts.per_tuple = 0;
4901 add_function_cost(context->root, saop->opfuncid, NULL,
4902 &sacosts);
4903
4904 if (OidIsValid(saop->hashfuncid))
4905 {
4906 /* Handle costs for hashed ScalarArrayOpExpr */
4907 hcosts.startup = hcosts.per_tuple = 0;
4908
4909 add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
4910 context->total.startup += sacosts.startup + hcosts.startup;
4911
4912 /* Estimate the cost of building the hashtable. */
4913 context->total.startup += estarraylen * hcosts.per_tuple;
4914
4915 /*
4916 * XXX should we charge a little bit for sacosts.per_tuple when
4917 * building the table, or is it ok to assume there will be zero
4918 * hash collision?
4919 */
4920
4921 /*
4922 * Charge for hashtable lookups. Charge a single hash and a
4923 * single comparison.
4924 */
4925 context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
4926 }
4927 else
4928 {
4929 /*
4930 * Estimate that the operator will be applied to about half of the
4931 * array elements before the answer is determined.
4932 */
4933 context->total.startup += sacosts.startup;
4934 context->total.per_tuple += sacosts.per_tuple *
4935 estimate_array_length(context->root, arraynode) * 0.5;
4936 }
4937 }
4938 else if (IsA(node, Aggref) ||
4939 IsA(node, WindowFunc))
4940 {
4941 /*
4942 * Aggref and WindowFunc nodes are (and should be) treated like Vars,
4943 * ie, zero execution cost in the current model, because they behave
4944 * essentially like Vars at execution. We disregard the costs of
4945 * their input expressions for the same reason. The actual execution
4946 * costs of the aggregate/window functions and their arguments have to
4947 * be factored into plan-node-specific costing of the Agg or WindowAgg
4948 * plan node.
4949 */
4950 return false; /* don't recurse into children */
4951 }
4952 else if (IsA(node, GroupingFunc))
4953 {
4954 /* Treat this as having cost 1 */
4955 context->total.per_tuple += cpu_operator_cost;
4956 return false; /* don't recurse into children */
4957 }
4958 else if (IsA(node, CoerceViaIO))
4959 {
4960 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
4961 Oid iofunc;
4962 Oid typioparam;
4963 bool typisvarlena;
4964
4965 /* check the result type's input function */
4966 getTypeInputInfo(iocoerce->resulttype,
4967 &iofunc, &typioparam);
4968 add_function_cost(context->root, iofunc, NULL,
4969 &context->total);
4970 /* check the input type's output function */
4971 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
4972 &iofunc, &typisvarlena);
4973 add_function_cost(context->root, iofunc, NULL,
4974 &context->total);
4975 }
4976 else if (IsA(node, ArrayCoerceExpr))
4977 {
4978 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
4979 QualCost perelemcost;
4980
4981 cost_qual_eval_node(&perelemcost, (Node *) acoerce->elemexpr,
4982 context->root);
4983 context->total.startup += perelemcost.startup;
4984 if (perelemcost.per_tuple > 0)
4985 context->total.per_tuple += perelemcost.per_tuple *
4986 estimate_array_length(context->root, (Node *) acoerce->arg);
4987 }
4988 else if (IsA(node, RowCompareExpr))
4989 {
4990 /* Conservatively assume we will check all the columns */
4991 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
4992 ListCell *lc;
4993
4994 foreach(lc, rcexpr->opnos)
4995 {
4996 Oid opid = lfirst_oid(lc);
4997
4998 add_function_cost(context->root, get_opcode(opid), NULL,
4999 &context->total);
5000 }
5001 }
5002 else if (IsA(node, MinMaxExpr) ||
5003 IsA(node, SQLValueFunction) ||
5004 IsA(node, XmlExpr) ||
5005 IsA(node, CoerceToDomain) ||
5006 IsA(node, NextValueExpr) ||
5007 IsA(node, JsonExpr))
5008 {
5009 /* Treat all these as having cost 1 */
5010 context->total.per_tuple += cpu_operator_cost;
5011 }
5012 else if (IsA(node, SubLink))
5013 {
5014 /* This routine should not be applied to un-planned expressions */
5015 elog(ERROR, "cannot handle unplanned sub-select");
5016 }
5017 else if (IsA(node, SubPlan))
5018 {
5019 /*
5020 * A subplan node in an expression typically indicates that the
5021 * subplan will be executed on each evaluation, so charge accordingly.
5022 * (Sub-selects that can be executed as InitPlans have already been
5023 * removed from the expression.)
5024 */
5025 SubPlan *subplan = (SubPlan *) node;
5026
5027 context->total.startup += subplan->startup_cost;
5028 context->total.per_tuple += subplan->per_call_cost;
5029
5030 /*
5031 * We don't want to recurse into the testexpr, because it was already
5032 * counted in the SubPlan node's costs. So we're done.
5033 */
5034 return false;
5035 }
5036 else if (IsA(node, AlternativeSubPlan))
5037 {
5038 /*
5039 * Arbitrarily use the first alternative plan for costing. (We should
5040 * certainly only include one alternative, and we don't yet have
5041 * enough information to know which one the executor is most likely to
5042 * use.)
5043 */
5044 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
5045
5046 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
5047 context);
5048 }
5049 else if (IsA(node, PlaceHolderVar))
5050 {
5051 /*
5052 * A PlaceHolderVar should be given cost zero when considering general
5053 * expression evaluation costs. The expense of doing the contained
5054 * expression is charged as part of the tlist eval costs of the scan
5055 * or join where the PHV is first computed (see set_rel_width and
5056 * add_placeholders_to_joinrel). If we charged it again here, we'd be
5057 * double-counting the cost for each level of plan that the PHV
5058 * bubbles up through. Hence, return without recursing into the
5059 * phexpr.
5060 */
5061 return false;
5062 }
5063
5064 /* recurse into children */
5065 return expression_tree_walker(node, cost_qual_eval_walker, context);
5066}
#define OidIsValid(objectId)
Definition: c.h:778
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:3074
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1452
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:3041
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1879
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1868
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define lsecond(l)
Definition: pg_list.h:183
#define lfirst_oid(lc)
Definition: pg_list.h:174
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2211
unsigned int Oid
Definition: postgres_ext.h:32
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2154
Expr * arg
Definition: primnodes.h:1240
Oid resulttype
Definition: primnodes.h:1241
Cost startup_cost
Definition: primnodes.h:1126
Cost per_call_cost
Definition: primnodes.h:1127

References add_function_cost(), CoerceViaIO::arg, ArrayCoerceExpr::arg, ScalarArrayOpExpr::args, RestrictInfo::clause, cost_qual_eval_node(), cost_qual_eval_walker(), cpu_operator_cost, ArrayCoerceExpr::elemexpr, elog, ERROR, estimate_array_length(), expression_tree_walker, exprType(), get_opcode(), getTypeInputInfo(), getTypeOutputInfo(), IsA, lfirst_oid, linitial, lsecond, OidIsValid, SubPlan::per_call_cost, QualCost::per_tuple, CoerceViaIO::resulttype, cost_qual_eval_context::root, set_opfuncid(), set_sa_opfuncid(), QualCost::startup, SubPlan::startup_cost, AlternativeSubPlan::subplans, and cost_qual_eval_context::total.

Referenced by cost_qual_eval(), cost_qual_eval_node(), and cost_qual_eval_walker().

β—† cost_recursive_union()

void cost_recursive_union ( Path runion,
Path nrterm,
Path rterm 
)

Definition at line 1800 of file costsize.c.

1801{
1802 Cost startup_cost;
1803 Cost total_cost;
1804 double total_rows;
1805
1806 /* We probably have decent estimates for the non-recursive term */
1807 startup_cost = nrterm->startup_cost;
1808 total_cost = nrterm->total_cost;
1809 total_rows = nrterm->rows;
1810
1811 /*
1812 * We arbitrarily assume that about 10 recursive iterations will be
1813 * needed, and that we've managed to get a good fix on the cost and output
1814 * size of each one of them. These are mighty shaky assumptions but it's
1815 * hard to see how to do better.
1816 */
1817 total_cost += 10 * rterm->total_cost;
1818 total_rows += 10 * rterm->rows;
1819
1820 /*
1821 * Also charge cpu_tuple_cost per row to account for the costs of
1822 * manipulating the tuplestores. (We don't worry about possible
1823 * spill-to-disk costs.)
1824 */
1825 total_cost += cpu_tuple_cost * total_rows;
1826
1827 runion->disabled_nodes = nrterm->disabled_nodes + rterm->disabled_nodes;
1828 runion->startup_cost = startup_cost;
1829 runion->total_cost = total_cost;
1830 runion->rows = total_rows;
1831 runion->pathtarget->width = Max(nrterm->pathtarget->width,
1832 rterm->pathtarget->width);
1833}

References cpu_tuple_cost, Path::disabled_nodes, Max, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_recursiveunion_path().

β—† cost_rescan()

static void cost_rescan ( PlannerInfo root,
Path path,
Cost rescan_startup_cost,
Cost rescan_total_cost 
)
static

Definition at line 4650 of file costsize.c.

4653{
4654 switch (path->pathtype)
4655 {
4656 case T_FunctionScan:
4657
4658 /*
4659 * Currently, nodeFunctionscan.c always executes the function to
4660 * completion before returning any rows, and caches the results in
4661 * a tuplestore. So the function eval cost is all startup cost
4662 * and isn't paid over again on rescans. However, all run costs
4663 * will be paid over again.
4664 */
4665 *rescan_startup_cost = 0;
4666 *rescan_total_cost = path->total_cost - path->startup_cost;
4667 break;
4668 case T_HashJoin:
4669
4670 /*
4671 * If it's a single-batch join, we don't need to rebuild the hash
4672 * table during a rescan.
4673 */
4674 if (((HashPath *) path)->num_batches == 1)
4675 {
4676 /* Startup cost is exactly the cost of hash table building */
4677 *rescan_startup_cost = 0;
4678 *rescan_total_cost = path->total_cost - path->startup_cost;
4679 }
4680 else
4681 {
4682 /* Otherwise, no special treatment */
4683 *rescan_startup_cost = path->startup_cost;
4684 *rescan_total_cost = path->total_cost;
4685 }
4686 break;
4687 case T_CteScan:
4688 case T_WorkTableScan:
4689 {
4690 /*
4691 * These plan types materialize their final result in a
4692 * tuplestore or tuplesort object. So the rescan cost is only
4693 * cpu_tuple_cost per tuple, unless the result is large enough
4694 * to spill to disk.
4695 */
4696 Cost run_cost = cpu_tuple_cost * path->rows;
4697 double nbytes = relation_byte_size(path->rows,
4698 path->pathtarget->width);
4699 double work_mem_bytes = work_mem * (Size) 1024;
4700
4701 if (nbytes > work_mem_bytes)
4702 {
4703 /* It will spill, so account for re-read cost */
4704 double npages = ceil(nbytes / BLCKSZ);
4705
4706 run_cost += seq_page_cost * npages;
4707 }
4708 *rescan_startup_cost = 0;
4709 *rescan_total_cost = run_cost;
4710 }
4711 break;
4712 case T_Material:
4713 case T_Sort:
4714 {
4715 /*
4716 * These plan types not only materialize their results, but do
4717 * not implement qual filtering or projection. So they are
4718 * even cheaper to rescan than the ones above. We charge only
4719 * cpu_operator_cost per tuple. (Note: keep that in sync with
4720 * the run_cost charge in cost_sort, and also see comments in
4721 * cost_material before you change it.)
4722 */
4723 Cost run_cost = cpu_operator_cost * path->rows;
4724 double nbytes = relation_byte_size(path->rows,
4725 path->pathtarget->width);
4726 double work_mem_bytes = work_mem * (Size) 1024;
4727
4728 if (nbytes > work_mem_bytes)
4729 {
4730 /* It will spill, so account for re-read cost */
4731 double npages = ceil(nbytes / BLCKSZ);
4732
4733 run_cost += seq_page_cost * npages;
4734 }
4735 *rescan_startup_cost = 0;
4736 *rescan_total_cost = run_cost;
4737 }
4738 break;
4739 case T_Memoize:
4740 /* All the hard work is done by cost_memoize_rescan */
4742 rescan_startup_cost, rescan_total_cost);
4743 break;
4744 default:
4745 *rescan_startup_cost = path->startup_cost;
4746 *rescan_total_cost = path->total_cost;
4747 break;
4748 }
4749}
static void cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:2541

References cost_memoize_rescan(), cpu_operator_cost, cpu_tuple_cost, Path::pathtype, relation_byte_size(), root, seq_page_cost, Path::startup_cost, Path::total_cost, and work_mem.

Referenced by initial_cost_nestloop().

β—† cost_resultscan()

void cost_resultscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1762 of file costsize.c.

1764{
1765 Cost startup_cost = 0;
1766 Cost run_cost = 0;
1767 QualCost qpqual_cost;
1768 Cost cpu_per_tuple;
1769
1770 /* Should only be applied to RTE_RESULT base relations */
1771 Assert(baserel->relid > 0);
1772 Assert(baserel->rtekind == RTE_RESULT);
1773
1774 /* Mark the path with the correct row estimate */
1775 if (param_info)
1776 path->rows = param_info->ppi_rows;
1777 else
1778 path->rows = baserel->rows;
1779
1780 /* We charge qual cost plus cpu_tuple_cost */
1781 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1782
1783 startup_cost += qpqual_cost.startup;
1784 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1785 run_cost += cpu_per_tuple * baserel->tuples;
1786
1787 path->disabled_nodes = 0;
1788 path->startup_cost = startup_cost;
1789 path->total_cost = startup_cost + run_cost;
1790}
@ RTE_RESULT
Definition: parsenodes.h:1051

References Assert(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, RelOptInfo::rows, Path::rows, RTE_RESULT, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_resultscan_path().

β—† cost_samplescan()

void cost_samplescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 344 of file costsize.c.

346{
347 Cost startup_cost = 0;
348 Cost run_cost = 0;
349 RangeTblEntry *rte;
351 TsmRoutine *tsm;
352 double spc_seq_page_cost,
353 spc_random_page_cost,
354 spc_page_cost;
355 QualCost qpqual_cost;
356 Cost cpu_per_tuple;
357
358 /* Should only be applied to base relations with tablesample clauses */
359 Assert(baserel->relid > 0);
360 rte = planner_rt_fetch(baserel->relid, root);
361 Assert(rte->rtekind == RTE_RELATION);
362 tsc = rte->tablesample;
363 Assert(tsc != NULL);
364 tsm = GetTsmRoutine(tsc->tsmhandler);
365
366 /* Mark the path with the correct row estimate */
367 if (param_info)
368 path->rows = param_info->ppi_rows;
369 else
370 path->rows = baserel->rows;
371
372 /* fetch estimated page cost for tablespace containing table */
374 &spc_random_page_cost,
375 &spc_seq_page_cost);
376
377 /* if NextSampleBlock is used, assume random access, else sequential */
378 spc_page_cost = (tsm->NextSampleBlock != NULL) ?
379 spc_random_page_cost : spc_seq_page_cost;
380
381 /*
382 * disk costs (recall that baserel->pages has already been set to the
383 * number of pages the sampling method will visit)
384 */
385 run_cost += spc_page_cost * baserel->pages;
386
387 /*
388 * CPU costs (recall that baserel->tuples has already been set to the
389 * number of tuples the sampling method will select). Note that we ignore
390 * execution cost of the TABLESAMPLE parameter expressions; they will be
391 * evaluated only once per scan, and in most usages they'll likely be
392 * simple constants anyway. We also don't charge anything for the
393 * calculations the sampling method might do internally.
394 */
395 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
396
397 startup_cost += qpqual_cost.startup;
398 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
399 run_cost += cpu_per_tuple * baserel->tuples;
400 /* tlist eval costs are paid per output row, not per tuple scanned */
401 startup_cost += path->pathtarget->cost.startup;
402 run_cost += path->pathtarget->cost.per_tuple * path->rows;
403
404 path->disabled_nodes = 0;
405 path->startup_cost = startup_cost;
406 path->total_cost = startup_cost + run_cost;
407}
struct TableSampleClause * tablesample
Definition: parsenodes.h:1129
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:73
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27

References Assert(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, RelOptInfo::pages, QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, RelOptInfo::rows, Path::rows, RTE_RELATION, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, RangeTblEntry::tablesample, Path::total_cost, TableSampleClause::tsmhandler, and RelOptInfo::tuples.

Referenced by create_samplescan_path().

β—† cost_seqscan()

void cost_seqscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 269 of file costsize.c.

271{
272 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
279 /* Should only be applied to base relations */
280 Assert(baserel->relid > 0);
281 Assert(baserel->rtekind == RTE_RELATION);
282
283 /* Mark the path with the correct row estimate */
284 if (param_info)
285 path->rows = param_info->ppi_rows;
286 else
287 path->rows = baserel->rows;
288
289 /* fetch estimated page cost for tablespace containing table */
291 NULL,
292 &spc_seq_page_cost);
293
294 /*
295 * disk costs
296 */
297 disk_run_cost = spc_seq_page_cost * baserel->pages;
298
299 /* CPU costs */
300 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
301
302 startup_cost += qpqual_cost.startup;
303 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
304 cpu_run_cost = cpu_per_tuple * baserel->tuples;
305 /* tlist eval costs are paid per output row, not per tuple scanned */
306 startup_cost += path->pathtarget->cost.startup;
307 cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
308
309 /* Adjust costing for parallelism, if used. */
310 if (path->parallel_workers > 0)
311 {
312 double parallel_divisor = get_parallel_divisor(path);
313
314 /* The CPU cost is divided among all the workers. */
315 cpu_run_cost /= parallel_divisor;
316
317 /*
318 * It may be possible to amortize some of the I/O cost, but probably
319 * not very much, because most operating systems already do aggressive
320 * prefetching. For now, we assume that the disk run cost can't be
321 * amortized at all.
322 */
323
324 /*
325 * In the case of a parallel plan, the row count needs to represent
326 * the number of tuples processed per worker.
327 */
328 path->rows = clamp_row_est(path->rows / parallel_divisor);
329 }
330
331 path->disabled_nodes = enable_seqscan ? 0 : 1;
332 path->startup_cost = startup_cost;
333 path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
334}
bool enable_seqscan
Definition: costsize.c:145

References Assert(), clamp_row_est(), cpu_tuple_cost, Path::disabled_nodes, enable_seqscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), RelOptInfo::pages, Path::parallel_workers, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_seqscan_path().

β—† cost_sort()

void cost_sort ( Path path,
PlannerInfo root,
List pathkeys,
int  input_disabled_nodes,
Cost  input_cost,
double  tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)

Definition at line 2118 of file costsize.c.

2124{
2125 Cost startup_cost;
2126 Cost run_cost;
2127
2128 cost_tuplesort(&startup_cost, &run_cost,
2129 tuples, width,
2130 comparison_cost, sort_mem,
2131 limit_tuples);
2132
2133 startup_cost += input_cost;
2134
2135 path->rows = tuples;
2136 path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
2137 path->startup_cost = startup_cost;
2138 path->total_cost = startup_cost + run_cost;
2139}
bool enable_sort
Definition: costsize.c:150

References cost_tuplesort(), Path::disabled_nodes, enable_sort, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by adjust_foreign_grouping_path_cost(), cost_append(), create_groupingsets_path(), create_merge_append_path(), create_sort_path(), initial_cost_mergejoin(), label_sort_with_costsize(), and plan_cluster_use_sort().

β—† cost_subplan()

void cost_subplan ( PlannerInfo root,
SubPlan subplan,
Plan plan 
)

Definition at line 4543 of file costsize.c.

4544{
4545 QualCost sp_cost;
4546
4547 /*
4548 * Figure any cost for evaluating the testexpr.
4549 *
4550 * Usually, SubPlan nodes are built very early, before we have constructed
4551 * any RelOptInfos for the parent query level, which means the parent root
4552 * does not yet contain enough information to safely consult statistics.
4553 * Therefore, we pass root as NULL here. cost_qual_eval() is already
4554 * well-equipped to handle a NULL root.
4555 *
4556 * One exception is SubPlan nodes built for the initplans of MIN/MAX
4557 * aggregates from indexes (cf. SS_make_initplan_from_plan). In this
4558 * case, having a NULL root is safe because testexpr will be NULL.
4559 * Besides, an initplan will by definition not consult anything from the
4560 * parent plan.
4561 */
4562 cost_qual_eval(&sp_cost,
4563 make_ands_implicit((Expr *) subplan->testexpr),
4564 NULL);
4565
4566 if (subplan->useHashTable)
4567 {
4568 /*
4569 * If we are using a hash table for the subquery outputs, then the
4570 * cost of evaluating the query is a one-time cost. We charge one
4571 * cpu_operator_cost per tuple for the work of loading the hashtable,
4572 * too.
4573 */
4574 sp_cost.startup += plan->total_cost +
4575 cpu_operator_cost * plan->plan_rows;
4576
4577 /*
4578 * The per-tuple costs include the cost of evaluating the lefthand
4579 * expressions, plus the cost of probing the hashtable. We already
4580 * accounted for the lefthand expressions as part of the testexpr, and
4581 * will also have counted one cpu_operator_cost for each comparison
4582 * operator. That is probably too low for the probing cost, but it's
4583 * hard to make a better estimate, so live with it for now.
4584 */
4585 }
4586 else
4587 {
4588 /*
4589 * Otherwise we will be rescanning the subplan output on each
4590 * evaluation. We need to estimate how much of the output we will
4591 * actually need to scan. NOTE: this logic should agree with the
4592 * tuple_fraction estimates used by make_subplan() in
4593 * plan/subselect.c.
4594 */
4595 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4596
4597 if (subplan->subLinkType == EXISTS_SUBLINK)
4598 {
4599 /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4600 sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4601 }
4602 else if (subplan->subLinkType == ALL_SUBLINK ||
4603 subplan->subLinkType == ANY_SUBLINK)
4604 {
4605 /* assume we need 50% of the tuples */
4606 sp_cost.per_tuple += 0.50 * plan_run_cost;
4607 /* also charge a cpu_operator_cost per row examined */
4608 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4609 }
4610 else
4611 {
4612 /* assume we need all tuples */
4613 sp_cost.per_tuple += plan_run_cost;
4614 }
4615
4616 /*
4617 * Also account for subplan's startup cost. If the subplan is
4618 * uncorrelated or undirect correlated, AND its topmost node is one
4619 * that materializes its output, assume that we'll only need to pay
4620 * its startup cost once; otherwise assume we pay the startup cost
4621 * every time.
4622 */
4623 if (subplan->parParam == NIL &&
4625 sp_cost.startup += plan->startup_cost;
4626 else
4627 sp_cost.per_tuple += plan->startup_cost;
4628 }
4629
4630 subplan->startup_cost = sp_cost.startup;
4631 subplan->per_call_cost = sp_cost.per_tuple;
4632}
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:636
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:810
#define plan(x)
Definition: pg_regress.c:161
@ ANY_SUBLINK
Definition: primnodes.h:1031
@ ALL_SUBLINK
Definition: primnodes.h:1030
@ EXISTS_SUBLINK
Definition: primnodes.h:1029
bool useHashTable
Definition: primnodes.h:1112
Node * testexpr
Definition: primnodes.h:1099
List * parParam
Definition: primnodes.h:1123
SubLinkType subLinkType
Definition: primnodes.h:1097

References ALL_SUBLINK, ANY_SUBLINK, clamp_row_est(), cost_qual_eval(), cpu_operator_cost, ExecMaterializesOutput(), EXISTS_SUBLINK, make_ands_implicit(), NIL, nodeTag, SubPlan::parParam, SubPlan::per_call_cost, QualCost::per_tuple, plan, QualCost::startup, SubPlan::startup_cost, SubPlan::subLinkType, SubPlan::testexpr, and SubPlan::useHashTable.

Referenced by build_subplan(), SS_make_initplan_from_plan(), and SS_process_ctes().

β—† cost_subqueryscan()

void cost_subqueryscan ( SubqueryScanPath path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
bool  trivial_pathtarget 
)

Definition at line 1431 of file costsize.c.

1434{
1435 Cost startup_cost;
1436 Cost run_cost;
1437 List *qpquals;
1438 QualCost qpqual_cost;
1439 Cost cpu_per_tuple;
1440
1441 /* Should only be applied to base relations that are subqueries */
1442 Assert(baserel->relid > 0);
1443 Assert(baserel->rtekind == RTE_SUBQUERY);
1444
1445 /*
1446 * We compute the rowcount estimate as the subplan's estimate times the
1447 * selectivity of relevant restriction clauses. In simple cases this will
1448 * come out the same as baserel->rows; but when dealing with parallelized
1449 * paths we must do it like this to get the right answer.
1450 */
1451 if (param_info)
1452 qpquals = list_concat_copy(param_info->ppi_clauses,
1453 baserel->baserestrictinfo);
1454 else
1455 qpquals = baserel->baserestrictinfo;
1456
1457 path->path.rows = clamp_row_est(path->subpath->rows *
1459 qpquals,
1460 0,
1461 JOIN_INNER,
1462 NULL));
1463
1464 /*
1465 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1466 * any restriction clauses and tlist that will be attached to the
1467 * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1468 * projection overhead.
1469 */
1471 path->path.startup_cost = path->subpath->startup_cost;
1472 path->path.total_cost = path->subpath->total_cost;
1473
1474 /*
1475 * However, if there are no relevant restriction clauses and the
1476 * pathtarget is trivial, then we expect that setrefs.c will optimize away
1477 * the SubqueryScan plan node altogether, so we should just make its cost
1478 * and rowcount equal to the input path's.
1479 *
1480 * Note: there are some edge cases where createplan.c will apply a
1481 * different targetlist to the SubqueryScan node, thus falsifying our
1482 * current estimate of whether the target is trivial, and making the cost
1483 * estimate (though not the rowcount) wrong. It does not seem worth the
1484 * extra complication to try to account for that exactly, especially since
1485 * that behavior falsifies other cost estimates as well.
1486 */
1487 if (qpquals == NIL && trivial_pathtarget)
1488 return;
1489
1490 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1491
1492 startup_cost = qpqual_cost.startup;
1493 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1494 run_cost = cpu_per_tuple * path->subpath->rows;
1495
1496 /* tlist eval costs are paid per output row, not per tuple scanned */
1497 startup_cost += path->path.pathtarget->cost.startup;
1498 run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1499
1500 path->path.startup_cost += startup_cost;
1501 path->path.total_cost += startup_cost + run_cost;
1502}
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:598
@ RTE_SUBQUERY
Definition: parsenodes.h:1044
List * ppi_clauses
Definition: pathnodes.h:1827
List * baserestrictinfo
Definition: pathnodes.h:1046

References Assert(), RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), JOIN_INNER, list_concat_copy(), NIL, SubqueryScanPath::path, QualCost::per_tuple, ParamPathInfo::ppi_clauses, RelOptInfo::relid, root, Path::rows, RTE_SUBQUERY, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, SubqueryScanPath::subpath, and Path::total_cost.

Referenced by create_subqueryscan_path().

β—† cost_tablefuncscan()

void cost_tablefuncscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1574 of file costsize.c.

1576{
1577 Cost startup_cost = 0;
1578 Cost run_cost = 0;
1579 QualCost qpqual_cost;
1580 Cost cpu_per_tuple;
1581 RangeTblEntry *rte;
1582 QualCost exprcost;
1583
1584 /* Should only be applied to base relations that are functions */
1585 Assert(baserel->relid > 0);
1586 rte = planner_rt_fetch(baserel->relid, root);
1587 Assert(rte->rtekind == RTE_TABLEFUNC);
1588
1589 /* Mark the path with the correct row estimate */
1590 if (param_info)
1591 path->rows = param_info->ppi_rows;
1592 else
1593 path->rows = baserel->rows;
1594
1595 /*
1596 * Estimate costs of executing the table func expression(s).
1597 *
1598 * XXX in principle we ought to charge tuplestore spill costs if the
1599 * number of rows is large. However, given how phony our rowcount
1600 * estimates for tablefuncs tend to be, there's not a lot of point in that
1601 * refinement right now.
1602 */
1603 cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1604
1605 startup_cost += exprcost.startup + exprcost.per_tuple;
1606
1607 /* Add scanning CPU costs */
1608 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1609
1610 startup_cost += qpqual_cost.startup;
1611 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1612 run_cost += cpu_per_tuple * baserel->tuples;
1613
1614 /* tlist eval costs are paid per output row, not per tuple scanned */
1615 startup_cost += path->pathtarget->cost.startup;
1616 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1617
1618 path->disabled_nodes = 0;
1619 path->startup_cost = startup_cost;
1620 path->total_cost = startup_cost + run_cost;
1621}
@ RTE_TABLEFUNC
Definition: parsenodes.h:1047
TableFunc * tablefunc
Definition: parsenodes.h:1215

References Assert(), cost_qual_eval_node(), cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, RelOptInfo::rows, Path::rows, RTE_TABLEFUNC, RangeTblEntry::rtekind, QualCost::startup, Path::startup_cost, RangeTblEntry::tablefunc, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_tablefuncscan_path().

β—† cost_tidrangescan()

void cost_tidrangescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
List tidrangequals,
ParamPathInfo param_info 
)

Definition at line 1337 of file costsize.c.

1340{
1341 Selectivity selectivity;
1342 double pages;
1343 Cost startup_cost = 0;
1344 Cost run_cost = 0;
1345 QualCost qpqual_cost;
1346 Cost cpu_per_tuple;
1347 QualCost tid_qual_cost;
1348 double ntuples;
1349 double nseqpages;
1350 double spc_random_page_cost;
1351 double spc_seq_page_cost;
1352
1353 /* Should only be applied to base relations */
1354 Assert(baserel->relid > 0);
1355 Assert(baserel->rtekind == RTE_RELATION);
1356
1357 /* Mark the path with the correct row estimate */
1358 if (param_info)
1359 path->rows = param_info->ppi_rows;
1360 else
1361 path->rows = baserel->rows;
1362
1363 /* Count how many tuples and pages we expect to scan */
1364 selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1365 JOIN_INNER, NULL);
1366 pages = ceil(selectivity * baserel->pages);
1367
1368 if (pages <= 0.0)
1369 pages = 1.0;
1370
1371 /*
1372 * The first page in a range requires a random seek, but each subsequent
1373 * page is just a normal sequential page read. NOTE: it's desirable for
1374 * TID Range Scans to cost more than the equivalent Sequential Scans,
1375 * because Seq Scans have some performance advantages such as scan
1376 * synchronization and parallelizability, and we'd prefer one of them to
1377 * be picked unless a TID Range Scan really is better.
1378 */
1379 ntuples = selectivity * baserel->tuples;
1380 nseqpages = pages - 1.0;
1381
1382 /*
1383 * The TID qual expressions will be computed once, any other baserestrict
1384 * quals once per retrieved tuple.
1385 */
1386 cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1387
1388 /* fetch estimated page cost for tablespace containing table */
1390 &spc_random_page_cost,
1391 &spc_seq_page_cost);
1392
1393 /* disk costs; 1 random page and the remainder as seq pages */
1394 run_cost += spc_random_page_cost + spc_seq_page_cost * nseqpages;
1395
1396 /* Add scanning CPU costs */
1397 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1398
1399 /*
1400 * XXX currently we assume TID quals are a subset of qpquals at this
1401 * point; they will be removed (if possible) when we create the plan, so
1402 * we subtract their cost from the total qpqual cost. (If the TID quals
1403 * can't be removed, this is a mistake and we're going to underestimate
1404 * the CPU cost a bit.)
1405 */
1406 startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1407 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1408 tid_qual_cost.per_tuple;
1409 run_cost += cpu_per_tuple * ntuples;
1410
1411 /* tlist eval costs are paid per output row, not per tuple scanned */
1412 startup_cost += path->pathtarget->cost.startup;
1413 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1414
1415 /* we should not generate this path type when enable_tidscan=false */
1417 path->disabled_nodes = 0;
1418 path->startup_cost = startup_cost;
1419 path->total_cost = startup_cost + run_cost;
1420}
bool enable_tidscan
Definition: costsize.c:149

References Assert(), clauselist_selectivity(), cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, enable_tidscan, get_restriction_qual_cost(), get_tablespace_page_costs(), JOIN_INNER, RelOptInfo::pages, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_tidrangescan_path().

β—† cost_tidscan()

void cost_tidscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
List tidquals,
ParamPathInfo param_info 
)

Definition at line 1232 of file costsize.c.

1234{
1235 Cost startup_cost = 0;
1236 Cost run_cost = 0;
1237 QualCost qpqual_cost;
1238 Cost cpu_per_tuple;
1239 QualCost tid_qual_cost;
1240 double ntuples;
1241 ListCell *l;
1242 double spc_random_page_cost;
1243
1244 /* Should only be applied to base relations */
1245 Assert(baserel->relid > 0);
1246 Assert(baserel->rtekind == RTE_RELATION);
1247 Assert(tidquals != NIL);
1248
1249 /* Mark the path with the correct row estimate */
1250 if (param_info)
1251 path->rows = param_info->ppi_rows;
1252 else
1253 path->rows = baserel->rows;
1254
1255 /* Count how many tuples we expect to retrieve */
1256 ntuples = 0;
1257 foreach(l, tidquals)
1258 {
1260 Expr *qual = rinfo->clause;
1261
1262 /*
1263 * We must use a TID scan for CurrentOfExpr; in any other case, we
1264 * should be generating a TID scan only if enable_tidscan=true. Also,
1265 * if CurrentOfExpr is the qual, there should be only one.
1266 */
1268 Assert(list_length(tidquals) == 1 || !IsA(qual, CurrentOfExpr));
1269
1270 if (IsA(qual, ScalarArrayOpExpr))
1271 {
1272 /* Each element of the array yields 1 tuple */
1273 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1274 Node *arraynode = (Node *) lsecond(saop->args);
1275
1276 ntuples += estimate_array_length(root, arraynode);
1277 }
1278 else if (IsA(qual, CurrentOfExpr))
1279 {
1280 /* CURRENT OF yields 1 tuple */
1281 ntuples++;
1282 }
1283 else
1284 {
1285 /* It's just CTID = something, count 1 tuple */
1286 ntuples++;
1287 }
1288 }
1289
1290 /*
1291 * The TID qual expressions will be computed once, any other baserestrict
1292 * quals once per retrieved tuple.
1293 */
1294 cost_qual_eval(&tid_qual_cost, tidquals, root);
1295
1296 /* fetch estimated page cost for tablespace containing table */
1298 &spc_random_page_cost,
1299 NULL);
1300
1301 /* disk costs --- assume each tuple on a different page */
1302 run_cost += spc_random_page_cost * ntuples;
1303
1304 /* Add scanning CPU costs */
1305 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1306
1307 /* XXX currently we assume TID quals are a subset of qpquals */
1308 startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1309 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1310 tid_qual_cost.per_tuple;
1311 run_cost += cpu_per_tuple * ntuples;
1312
1313 /* tlist eval costs are paid per output row, not per tuple scanned */
1314 startup_cost += path->pathtarget->cost.startup;
1315 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1316
1317 /*
1318 * There are assertions above verifying that we only reach this function
1319 * either when enable_tidscan=true or when the TID scan is the only legal
1320 * path, so it's safe to set disabled_nodes to zero here.
1321 */
1322 path->disabled_nodes = 0;
1323 path->startup_cost = startup_cost;
1324 path->total_cost = startup_cost + run_cost;
1325}

References ScalarArrayOpExpr::args, Assert(), RestrictInfo::clause, cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, enable_tidscan, estimate_array_length(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, lfirst_node, list_length(), lsecond, NIL, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, root, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, and Path::total_cost.

Referenced by create_tidscan_path().

β—† cost_tuplesort()

static void cost_tuplesort ( Cost startup_cost,
Cost run_cost,
double  tuples,
int  width,
Cost  comparison_cost,
int  sort_mem,
double  limit_tuples 
)
static

Definition at line 1872 of file costsize.c.

1876{
1877 double input_bytes = relation_byte_size(tuples, width);
1878 double output_bytes;
1879 double output_tuples;
1880 int64 sort_mem_bytes = sort_mem * (int64) 1024;
1881
1882 /*
1883 * We want to be sure the cost of a sort is never estimated as zero, even
1884 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1885 */
1886 if (tuples < 2.0)
1887 tuples = 2.0;
1888
1889 /* Include the default cost-per-comparison */
1890 comparison_cost += 2.0 * cpu_operator_cost;
1891
1892 /* Do we have a useful LIMIT? */
1893 if (limit_tuples > 0 && limit_tuples < tuples)
1894 {
1895 output_tuples = limit_tuples;
1896 output_bytes = relation_byte_size(output_tuples, width);
1897 }
1898 else
1899 {
1900 output_tuples = tuples;
1901 output_bytes = input_bytes;
1902 }
1903
1904 if (output_bytes > sort_mem_bytes)
1905 {
1906 /*
1907 * We'll have to use a disk-based sort of all the tuples
1908 */
1909 double npages = ceil(input_bytes / BLCKSZ);
1910 double nruns = input_bytes / sort_mem_bytes;
1911 double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1912 double log_runs;
1913 double npageaccesses;
1914
1915 /*
1916 * CPU costs
1917 *
1918 * Assume about N log2 N comparisons
1919 */
1920 *startup_cost = comparison_cost * tuples * LOG2(tuples);
1921
1922 /* Disk costs */
1923
1924 /* Compute logM(r) as log(r) / log(M) */
1925 if (nruns > mergeorder)
1926 log_runs = ceil(log(nruns) / log(mergeorder));
1927 else
1928 log_runs = 1.0;
1929 npageaccesses = 2.0 * npages * log_runs;
1930 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1931 *startup_cost += npageaccesses *
1932 (seq_page_cost * 0.75 + random_page_cost * 0.25);
1933 }
1934 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1935 {
1936 /*
1937 * We'll use a bounded heap-sort keeping just K tuples in memory, for
1938 * a total number of tuple comparisons of N log2 K; but the constant
1939 * factor is a bit higher than for quicksort. Tweak it so that the
1940 * cost curve is continuous at the crossover point.
1941 */
1942 *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
1943 }
1944 else
1945 {
1946 /* We'll use plain quicksort on all the input tuples */
1947 *startup_cost = comparison_cost * tuples * LOG2(tuples);
1948 }
1949
1950 /*
1951 * Also charge a small amount (arbitrarily set equal to operator cost) per
1952 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1953 * doesn't do qual-checking or projection, so it has less overhead than
1954 * most plan nodes. Note it's correct to use tuples not output_tuples
1955 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1956 * counting the LIMIT otherwise.
1957 */
1958 *run_cost = cpu_operator_cost * tuples;
1959}
int64_t int64
Definition: c.h:539
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:1774

References cpu_operator_cost, LOG2, random_page_cost, relation_byte_size(), seq_page_cost, and tuplesort_merge_order().

Referenced by cost_incremental_sort(), and cost_sort().

β—† cost_valuesscan()

void cost_valuesscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1631 of file costsize.c.

1633{
1634 Cost startup_cost = 0;
1635 Cost run_cost = 0;
1636 QualCost qpqual_cost;
1637 Cost cpu_per_tuple;
1638
1639 /* Should only be applied to base relations that are values lists */
1640 Assert(baserel->relid > 0);
1641 Assert(baserel->rtekind == RTE_VALUES);
1642
1643 /* Mark the path with the correct row estimate */
1644 if (param_info)
1645 path->rows = param_info->ppi_rows;
1646 else
1647 path->rows = baserel->rows;
1648
1649 /*
1650 * For now, estimate list evaluation cost at one operator eval per list
1651 * (probably pretty bogus, but is it worth being smarter?)
1652 */
1653 cpu_per_tuple = cpu_operator_cost;
1654
1655 /* Add scanning CPU costs */
1656 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1657
1658 startup_cost += qpqual_cost.startup;
1659 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1660 run_cost += cpu_per_tuple * baserel->tuples;
1661
1662 /* tlist eval costs are paid per output row, not per tuple scanned */
1663 startup_cost += path->pathtarget->cost.startup;
1664 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1665
1666 path->disabled_nodes = 0;
1667 path->startup_cost = startup_cost;
1668 path->total_cost = startup_cost + run_cost;
1669}
@ RTE_VALUES
Definition: parsenodes.h:1048

References Assert(), cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, get_restriction_qual_cost(), QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, root, RelOptInfo::rows, Path::rows, RTE_VALUES, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_valuesscan_path().

β—† cost_windowagg()

void cost_windowagg ( Path path,
PlannerInfo root,
List windowFuncs,
WindowClause winclause,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 3104 of file costsize.c.

3109{
3110 Cost startup_cost;
3111 Cost total_cost;
3112 double startup_tuples;
3113 int numPartCols;
3114 int numOrderCols;
3115 ListCell *lc;
3116
3117 numPartCols = list_length(winclause->partitionClause);
3118 numOrderCols = list_length(winclause->orderClause);
3119
3120 startup_cost = input_startup_cost;
3121 total_cost = input_total_cost;
3122
3123 /*
3124 * Window functions are assumed to cost their stated execution cost, plus
3125 * the cost of evaluating their input expressions, per tuple. Since they
3126 * may in fact evaluate their inputs at multiple rows during each cycle,
3127 * this could be a drastic underestimate; but without a way to know how
3128 * many rows the window function will fetch, it's hard to do better. In
3129 * any case, it's a good estimate for all the built-in window functions,
3130 * so we'll just do this for now.
3131 */
3132 foreach(lc, windowFuncs)
3133 {
3134 WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3135 Cost wfunccost;
3136 QualCost argcosts;
3137
3138 argcosts.startup = argcosts.per_tuple = 0;
3139 add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3140 &argcosts);
3141 startup_cost += argcosts.startup;
3142 wfunccost = argcosts.per_tuple;
3143
3144 /* also add the input expressions' cost to per-input-row costs */
3145 cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3146 startup_cost += argcosts.startup;
3147 wfunccost += argcosts.per_tuple;
3148
3149 /*
3150 * Add the filter's cost to per-input-row costs. XXX We should reduce
3151 * input expression costs according to filter selectivity.
3152 */
3153 cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3154 startup_cost += argcosts.startup;
3155 wfunccost += argcosts.per_tuple;
3156
3157 total_cost += wfunccost * input_tuples;
3158 }
3159
3160 /*
3161 * We also charge cpu_operator_cost per grouping column per tuple for
3162 * grouping comparisons, plus cpu_tuple_cost per tuple for general
3163 * overhead.
3164 *
3165 * XXX this neglects costs of spooling the data to disk when it overflows
3166 * work_mem. Sooner or later that should get accounted for.
3167 */
3168 total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3169 total_cost += cpu_tuple_cost * input_tuples;
3170
3171 path->rows = input_tuples;
3172 path->disabled_nodes = input_disabled_nodes;
3173 path->startup_cost = startup_cost;
3174 path->total_cost = total_cost;
3175
3176 /*
3177 * Also, take into account how many tuples we need to read from the
3178 * subnode in order to produce the first tuple from the WindowAgg. To do
3179 * this we proportion the run cost (total cost not including startup cost)
3180 * over the estimated startup tuples. We already included the startup
3181 * cost of the subnode, so we only need to do this when the estimated
3182 * startup tuples is above 1.0.
3183 */
3184 startup_tuples = get_windowclause_startup_tuples(root, winclause,
3185 input_tuples);
3186
3187 if (startup_tuples > 1.0)
3188 path->startup_cost += (total_cost - startup_cost) / input_tuples *
3189 (startup_tuples - 1.0);
3190}
static double get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc, double input_tuples)
Definition: costsize.c:2890
List * partitionClause
Definition: parsenodes.h:1574
List * orderClause
Definition: parsenodes.h:1576
List * args
Definition: primnodes.h:605
Expr * aggfilter
Definition: primnodes.h:607
Oid winfnoid
Definition: primnodes.h:597

References add_function_cost(), WindowFunc::aggfilter, WindowFunc::args, cost_qual_eval_node(), cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, get_windowclause_startup_tuples(), lfirst_node, list_length(), WindowClause::orderClause, WindowClause::partitionClause, QualCost::per_tuple, root, Path::rows, QualCost::startup, Path::startup_cost, Path::total_cost, and WindowFunc::winfnoid.

Referenced by create_windowagg_path().

β—† extract_nonindex_conditions()

static List * extract_nonindex_conditions ( List qual_clauses,
List indexclauses 
)
static

Definition at line 824 of file costsize.c.

825{
826 List *result = NIL;
827 ListCell *lc;
828
829 foreach(lc, qual_clauses)
830 {
832
833 if (rinfo->pseudoconstant)
834 continue; /* we may drop pseudoconstants here */
835 if (is_redundant_with_indexclauses(rinfo, indexclauses))
836 continue; /* dup or derived from same EquivalenceClass */
837 /* ... skip the predicate proof attempt createplan.c will try ... */
838 result = lappend(result, rinfo);
839 }
840 return result;
841}
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:3577

References is_redundant_with_indexclauses(), lappend(), lfirst_node, and NIL.

Referenced by cost_index().

β—† final_cost_hashjoin()

void final_cost_hashjoin ( PlannerInfo root,
HashPath path,
JoinCostWorkspace workspace,
JoinPathExtraData extra 
)

Definition at line 4283 of file costsize.c.

4286{
4287 Path *outer_path = path->jpath.outerjoinpath;
4288 Path *inner_path = path->jpath.innerjoinpath;
4289 double outer_path_rows = outer_path->rows;
4290 double inner_path_rows = inner_path->rows;
4291 double inner_path_rows_total = workspace->inner_rows_total;
4292 List *hashclauses = path->path_hashclauses;
4293 Cost startup_cost = workspace->startup_cost;
4294 Cost run_cost = workspace->run_cost;
4295 int numbuckets = workspace->numbuckets;
4296 int numbatches = workspace->numbatches;
4297 Cost cpu_per_tuple;
4298 QualCost hash_qual_cost;
4299 QualCost qp_qual_cost;
4300 double hashjointuples;
4301 double virtualbuckets;
4302 Selectivity innerbucketsize;
4303 Selectivity innermcvfreq;
4304 ListCell *hcl;
4305
4306 /* Set the number of disabled nodes. */
4307 path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4308
4309 /* Mark the path with the correct row estimate */
4310 if (path->jpath.path.param_info)
4311 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4312 else
4313 path->jpath.path.rows = path->jpath.path.parent->rows;
4314
4315 /* For partial paths, scale row estimate. */
4316 if (path->jpath.path.parallel_workers > 0)
4317 {
4318 double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4319
4320 path->jpath.path.rows =
4321 clamp_row_est(path->jpath.path.rows / parallel_divisor);
4322 }
4323
4324 /* mark the path with estimated # of batches */
4325 path->num_batches = numbatches;
4326
4327 /* store the total number of tuples (sum of partial row estimates) */
4328 path->inner_rows_total = inner_path_rows_total;
4329
4330 /* and compute the number of "virtual" buckets in the whole join */
4331 virtualbuckets = (double) numbuckets * (double) numbatches;
4332
4333 /*
4334 * Determine bucketsize fraction and MCV frequency for the inner relation.
4335 * We use the smallest bucketsize or MCV frequency estimated for any
4336 * individual hashclause; this is undoubtedly conservative.
4337 *
4338 * BUT: if inner relation has been unique-ified, we can assume it's good
4339 * for hashing. This is important both because it's the right answer, and
4340 * because we avoid contaminating the cache with a value that's wrong for
4341 * non-unique-ified paths.
4342 */
4343 if (RELATION_WAS_MADE_UNIQUE(inner_path->parent, extra->sjinfo,
4344 path->jpath.jointype))
4345 {
4346 innerbucketsize = 1.0 / virtualbuckets;
4347 innermcvfreq = 0.0;
4348 }
4349 else
4350 {
4351 List *otherclauses;
4352
4353 innerbucketsize = 1.0;
4354 innermcvfreq = 1.0;
4355
4356 /* At first, try to estimate bucket size using extended statistics. */
4358 inner_path->parent,
4359 hashclauses,
4360 &innerbucketsize);
4361
4362 /* Pass through the remaining clauses */
4363 foreach(hcl, otherclauses)
4364 {
4365 RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
4366 Selectivity thisbucketsize;
4367 Selectivity thismcvfreq;
4368
4369 /*
4370 * First we have to figure out which side of the hashjoin clause
4371 * is the inner side.
4372 *
4373 * Since we tend to visit the same clauses over and over when
4374 * planning a large query, we cache the bucket stats estimates in
4375 * the RestrictInfo node to avoid repeated lookups of statistics.
4376 */
4377 if (bms_is_subset(restrictinfo->right_relids,
4378 inner_path->parent->relids))
4379 {
4380 /* righthand side is inner */
4381 thisbucketsize = restrictinfo->right_bucketsize;
4382 if (thisbucketsize < 0)
4383 {
4384 /* not cached yet */
4386 get_rightop(restrictinfo->clause),
4387 virtualbuckets,
4388 &restrictinfo->right_mcvfreq,
4389 &restrictinfo->right_bucketsize);
4390 thisbucketsize = restrictinfo->right_bucketsize;
4391 }
4392 thismcvfreq = restrictinfo->right_mcvfreq;
4393 }
4394 else
4395 {
4396 Assert(bms_is_subset(restrictinfo->left_relids,
4397 inner_path->parent->relids));
4398 /* lefthand side is inner */
4399 thisbucketsize = restrictinfo->left_bucketsize;
4400 if (thisbucketsize < 0)
4401 {
4402 /* not cached yet */
4404 get_leftop(restrictinfo->clause),
4405 virtualbuckets,
4406 &restrictinfo->left_mcvfreq,
4407 &restrictinfo->left_bucketsize);
4408 thisbucketsize = restrictinfo->left_bucketsize;
4409 }
4410 thismcvfreq = restrictinfo->left_mcvfreq;
4411 }
4412
4413 if (innerbucketsize > thisbucketsize)
4414 innerbucketsize = thisbucketsize;
4415 if (innermcvfreq > thismcvfreq)
4416 innermcvfreq = thismcvfreq;
4417 }
4418 }
4419
4420 /*
4421 * If the bucket holding the inner MCV would exceed hash_mem, we don't
4422 * want to hash unless there is really no other alternative, so apply
4423 * disable_cost. (The executor normally copes with excessive memory usage
4424 * by splitting batches, but obviously it cannot separate equal values
4425 * that way, so it will be unable to drive the batch size below hash_mem
4426 * when this is true.)
4427 */
4428 if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4429 inner_path->pathtarget->width) > get_hash_memory_limit())
4430 startup_cost += disable_cost;
4431
4432 /*
4433 * Compute cost of the hashquals and qpquals (other restriction clauses)
4434 * separately.
4435 */
4436 cost_qual_eval(&hash_qual_cost, hashclauses, root);
4437 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4438 qp_qual_cost.startup -= hash_qual_cost.startup;
4439 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4440
4441 /* CPU costs */
4442
4443 if (path->jpath.jointype == JOIN_SEMI ||
4444 path->jpath.jointype == JOIN_ANTI ||
4445 extra->inner_unique)
4446 {
4447 double outer_matched_rows;
4448 Selectivity inner_scan_frac;
4449
4450 /*
4451 * With a SEMI or ANTI join, or if the innerrel is known unique, the
4452 * executor will stop after the first match.
4453 *
4454 * For an outer-rel row that has at least one match, we can expect the
4455 * bucket scan to stop after a fraction 1/(match_count+1) of the
4456 * bucket's rows, if the matches are evenly distributed. Since they
4457 * probably aren't quite evenly distributed, we apply a fuzz factor of
4458 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4459 * to clamp inner_scan_frac to at most 1.0; but since match_count is
4460 * at least 1, no such clamp is needed now.)
4461 */
4462 outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4463 inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4464
4465 startup_cost += hash_qual_cost.startup;
4466 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4467 clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4468
4469 /*
4470 * For unmatched outer-rel rows, the picture is quite a lot different.
4471 * In the first place, there is no reason to assume that these rows
4472 * preferentially hit heavily-populated buckets; instead assume they
4473 * are uncorrelated with the inner distribution and so they see an
4474 * average bucket size of inner_path_rows / virtualbuckets. In the
4475 * second place, it seems likely that they will have few if any exact
4476 * hash-code matches and so very few of the tuples in the bucket will
4477 * actually require eval of the hash quals. We don't have any good
4478 * way to estimate how many will, but for the moment assume that the
4479 * effective cost per bucket entry is one-tenth what it is for
4480 * matchable tuples.
4481 */
4482 run_cost += hash_qual_cost.per_tuple *
4483 (outer_path_rows - outer_matched_rows) *
4484 clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4485
4486 /* Get # of tuples that will pass the basic join */
4487 if (path->jpath.jointype == JOIN_ANTI)
4488 hashjointuples = outer_path_rows - outer_matched_rows;
4489 else
4490 hashjointuples = outer_matched_rows;
4491 }
4492 else
4493 {
4494 /*
4495 * The number of tuple comparisons needed is the number of outer
4496 * tuples times the typical number of tuples in a hash bucket, which
4497 * is the inner relation size times its bucketsize fraction. At each
4498 * one, we need to evaluate the hashjoin quals. But actually,
4499 * charging the full qual eval cost at each tuple is pessimistic,
4500 * since we don't evaluate the quals unless the hash values match
4501 * exactly. For lack of a better idea, halve the cost estimate to
4502 * allow for that.
4503 */
4504 startup_cost += hash_qual_cost.startup;
4505 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4506 clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4507
4508 /*
4509 * Get approx # tuples passing the hashquals. We use
4510 * approx_tuple_count here because we need an estimate done with
4511 * JOIN_INNER semantics.
4512 */
4513 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4514 }
4515
4516 /*
4517 * For each tuple that gets through the hashjoin proper, we charge
4518 * cpu_tuple_cost plus the cost of evaluating additional restriction
4519 * clauses that are to be applied at the join. (This is pessimistic since
4520 * not all of the quals may get evaluated at each tuple.)
4521 */
4522 startup_cost += qp_qual_cost.startup;
4523 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4524 run_cost += cpu_per_tuple * hashjointuples;
4525
4526 /* tlist eval costs are paid per output row, not per tuple scanned */
4527 startup_cost += path->jpath.path.pathtarget->cost.startup;
4528 run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4529
4530 path->jpath.path.startup_cost = startup_cost;
4531 path->jpath.path.total_cost = startup_cost + run_cost;
4532}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:5313
Cost disable_cost
Definition: costsize.c:141
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:95
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:83
#define RELATION_WAS_MADE_UNIQUE(rel, sjinfo, nominal_jointype)
Definition: pathnodes.h:1154
List * estimate_multivariate_bucketsize(PlannerInfo *root, RelOptInfo *inner, List *hashclauses, Selectivity *innerbucketsize)
Definition: selfuncs.c:3808
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:4075
List * path_hashclauses
Definition: pathnodes.h:2381
Cardinality inner_rows_total
Definition: pathnodes.h:2383
int num_batches
Definition: pathnodes.h:2382
JoinPath jpath
Definition: pathnodes.h:2380
Cardinality inner_rows_total
Definition: pathnodes.h:3621
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:3499
SpecialJoinInfo * sjinfo
Definition: pathnodes.h:3498
JoinType jointype
Definition: pathnodes.h:2290
List * joinrestrictinfo
Definition: pathnodes.h:2298

References approx_tuple_count(), Assert(), bms_is_subset(), clamp_row_est(), RestrictInfo::clause, cost_qual_eval(), cpu_tuple_cost, disable_cost, JoinCostWorkspace::disabled_nodes, estimate_hash_bucket_stats(), estimate_multivariate_bucketsize(), get_hash_memory_limit(), get_leftop(), get_parallel_divisor(), get_rightop(), HashPath::inner_rows_total, JoinCostWorkspace::inner_rows_total, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, lfirst_node, SemiAntiJoinFactors::match_count, HashPath::num_batches, JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, HashPath::path_hashclauses, QualCost::per_tuple, relation_byte_size(), RELATION_WAS_MADE_UNIQUE, root, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, JoinPathExtraData::sjinfo, QualCost::startup, and JoinCostWorkspace::startup_cost.

Referenced by create_hashjoin_path().

β—† final_cost_mergejoin()

void final_cost_mergejoin ( PlannerInfo root,
MergePath path,
JoinCostWorkspace workspace,
JoinPathExtraData extra 
)

Definition at line 3843 of file costsize.c.

3846{
3847 Path *outer_path = path->jpath.outerjoinpath;
3848 Path *inner_path = path->jpath.innerjoinpath;
3849 double inner_path_rows = inner_path->rows;
3850 List *mergeclauses = path->path_mergeclauses;
3851 List *innersortkeys = path->innersortkeys;
3852 Cost startup_cost = workspace->startup_cost;
3853 Cost run_cost = workspace->run_cost;
3854 Cost inner_run_cost = workspace->inner_run_cost;
3855 double outer_rows = workspace->outer_rows;
3856 double inner_rows = workspace->inner_rows;
3857 double outer_skip_rows = workspace->outer_skip_rows;
3858 double inner_skip_rows = workspace->inner_skip_rows;
3859 Cost cpu_per_tuple,
3860 bare_inner_cost,
3861 mat_inner_cost;
3862 QualCost merge_qual_cost;
3863 QualCost qp_qual_cost;
3864 double mergejointuples,
3865 rescannedtuples;
3866 double rescanratio;
3867
3868 /* Set the number of disabled nodes. */
3869 path->jpath.path.disabled_nodes = workspace->disabled_nodes;
3870
3871 /* Protect some assumptions below that rowcounts aren't zero */
3872 if (inner_path_rows <= 0)
3873 inner_path_rows = 1;
3874
3875 /* Mark the path with the correct row estimate */
3876 if (path->jpath.path.param_info)
3877 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3878 else
3879 path->jpath.path.rows = path->jpath.path.parent->rows;
3880
3881 /* For partial paths, scale row estimate. */
3882 if (path->jpath.path.parallel_workers > 0)
3883 {
3884 double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3885
3886 path->jpath.path.rows =
3887 clamp_row_est(path->jpath.path.rows / parallel_divisor);
3888 }
3889
3890 /*
3891 * Compute cost of the mergequals and qpquals (other restriction clauses)
3892 * separately.
3893 */
3894 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3895 cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3896 qp_qual_cost.startup -= merge_qual_cost.startup;
3897 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3898
3899 /*
3900 * With a SEMI or ANTI join, or if the innerrel is known unique, the
3901 * executor will stop scanning for matches after the first match. When
3902 * all the joinclauses are merge clauses, this means we don't ever need to
3903 * back up the merge, and so we can skip mark/restore overhead.
3904 */
3905 if ((path->jpath.jointype == JOIN_SEMI ||
3906 path->jpath.jointype == JOIN_ANTI ||
3907 extra->inner_unique) &&
3910 path->skip_mark_restore = true;
3911 else
3912 path->skip_mark_restore = false;
3913
3914 /*
3915 * Get approx # tuples passing the mergequals. We use approx_tuple_count
3916 * here because we need an estimate done with JOIN_INNER semantics.
3917 */
3918 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3919
3920 /*
3921 * When there are equal merge keys in the outer relation, the mergejoin
3922 * must rescan any matching tuples in the inner relation. This means
3923 * re-fetching inner tuples; we have to estimate how often that happens.
3924 *
3925 * For regular inner and outer joins, the number of re-fetches can be
3926 * estimated approximately as size of merge join output minus size of
3927 * inner relation. Assume that the distinct key values are 1, 2, ..., and
3928 * denote the number of values of each key in the outer relation as m1,
3929 * m2, ...; in the inner relation, n1, n2, ... Then we have
3930 *
3931 * size of join = m1 * n1 + m2 * n2 + ...
3932 *
3933 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3934 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3935 * relation
3936 *
3937 * This equation works correctly for outer tuples having no inner match
3938 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3939 * are effectively subtracting those from the number of rescanned tuples,
3940 * when we should not. Can we do better without expensive selectivity
3941 * computations?
3942 *
3943 * The whole issue is moot if we know we don't need to mark/restore at
3944 * all, or if we are working from a unique-ified outer input.
3945 */
3946 if (path->skip_mark_restore ||
3947 RELATION_WAS_MADE_UNIQUE(outer_path->parent, extra->sjinfo,
3948 path->jpath.jointype))
3949 rescannedtuples = 0;
3950 else
3951 {
3952 rescannedtuples = mergejointuples - inner_path_rows;
3953 /* Must clamp because of possible underestimate */
3954 if (rescannedtuples < 0)
3955 rescannedtuples = 0;
3956 }
3957
3958 /*
3959 * We'll inflate various costs this much to account for rescanning. Note
3960 * that this is to be multiplied by something involving inner_rows, or
3961 * another number related to the portion of the inner rel we'll scan.
3962 */
3963 rescanratio = 1.0 + (rescannedtuples / inner_rows);
3964
3965 /*
3966 * Decide whether we want to materialize the inner input to shield it from
3967 * mark/restore and performing re-fetches. Our cost model for regular
3968 * re-fetches is that a re-fetch costs the same as an original fetch,
3969 * which is probably an overestimate; but on the other hand we ignore the
3970 * bookkeeping costs of mark/restore. Not clear if it's worth developing
3971 * a more refined model. So we just need to inflate the inner run cost by
3972 * rescanratio.
3973 */
3974 bare_inner_cost = inner_run_cost * rescanratio;
3975
3976 /*
3977 * When we interpose a Material node the re-fetch cost is assumed to be
3978 * just cpu_operator_cost per tuple, independently of the underlying
3979 * plan's cost; and we charge an extra cpu_operator_cost per original
3980 * fetch as well. Note that we're assuming the materialize node will
3981 * never spill to disk, since it only has to remember tuples back to the
3982 * last mark. (If there are a huge number of duplicates, our other cost
3983 * factors will make the path so expensive that it probably won't get
3984 * chosen anyway.) So we don't use cost_rescan here.
3985 *
3986 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3987 * of the generated Material node.
3988 */
3989 mat_inner_cost = inner_run_cost +
3990 cpu_operator_cost * inner_rows * rescanratio;
3991
3992 /*
3993 * If we don't need mark/restore at all, we don't need materialization.
3994 */
3995 if (path->skip_mark_restore)
3996 path->materialize_inner = false;
3997
3998 /*
3999 * Prefer materializing if it looks cheaper, unless the user has asked to
4000 * suppress materialization.
4001 */
4002 else if (enable_material && mat_inner_cost < bare_inner_cost)
4003 path->materialize_inner = true;
4004
4005 /*
4006 * Even if materializing doesn't look cheaper, we *must* do it if the
4007 * inner path is to be used directly (without sorting) and it doesn't
4008 * support mark/restore.
4009 *
4010 * Since the inner side must be ordered, and only Sorts and IndexScans can
4011 * create order to begin with, and they both support mark/restore, you
4012 * might think there's no problem --- but you'd be wrong. Nestloop and
4013 * merge joins can *preserve* the order of their inputs, so they can be
4014 * selected as the input of a mergejoin, and they don't support
4015 * mark/restore at present.
4016 *
4017 * We don't test the value of enable_material here, because
4018 * materialization is required for correctness in this case, and turning
4019 * it off does not entitle us to deliver an invalid plan.
4020 */
4021 else if (innersortkeys == NIL &&
4022 !ExecSupportsMarkRestore(inner_path))
4023 path->materialize_inner = true;
4024
4025 /*
4026 * Also, force materializing if the inner path is to be sorted and the
4027 * sort is expected to spill to disk. This is because the final merge
4028 * pass can be done on-the-fly if it doesn't have to support mark/restore.
4029 * We don't try to adjust the cost estimates for this consideration,
4030 * though.
4031 *
4032 * Since materialization is a performance optimization in this case,
4033 * rather than necessary for correctness, we skip it if enable_material is
4034 * off.
4035 */
4036 else if (enable_material && innersortkeys != NIL &&
4037 relation_byte_size(inner_path_rows,
4038 inner_path->pathtarget->width) >
4039 work_mem * (Size) 1024)
4040 path->materialize_inner = true;
4041 else
4042 path->materialize_inner = false;
4043
4044 /* Charge the right incremental cost for the chosen case */
4045 if (path->materialize_inner)
4046 run_cost += mat_inner_cost;
4047 else
4048 run_cost += bare_inner_cost;
4049
4050 /* CPU costs */
4051
4052 /*
4053 * The number of tuple comparisons needed is approximately number of outer
4054 * rows plus number of inner rows plus number of rescanned tuples (can we
4055 * refine this?). At each one, we need to evaluate the mergejoin quals.
4056 */
4057 startup_cost += merge_qual_cost.startup;
4058 startup_cost += merge_qual_cost.per_tuple *
4059 (outer_skip_rows + inner_skip_rows * rescanratio);
4060 run_cost += merge_qual_cost.per_tuple *
4061 ((outer_rows - outer_skip_rows) +
4062 (inner_rows - inner_skip_rows) * rescanratio);
4063
4064 /*
4065 * For each tuple that gets through the mergejoin proper, we charge
4066 * cpu_tuple_cost plus the cost of evaluating additional restriction
4067 * clauses that are to be applied at the join. (This is pessimistic since
4068 * not all of the quals may get evaluated at each tuple.)
4069 *
4070 * Note: we could adjust for SEMI/ANTI joins skipping some qual
4071 * evaluations here, but it's probably not worth the trouble.
4072 */
4073 startup_cost += qp_qual_cost.startup;
4074 cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4075 run_cost += cpu_per_tuple * mergejointuples;
4076
4077 /* tlist eval costs are paid per output row, not per tuple scanned */
4078 startup_cost += path->jpath.path.pathtarget->cost.startup;
4079 run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4080
4081 path->jpath.path.startup_cost = startup_cost;
4082 path->jpath.path.total_cost = startup_cost + run_cost;
4083}
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:418
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
Cardinality inner_rows
Definition: pathnodes.h:3614
Cardinality outer_rows
Definition: pathnodes.h:3613
Cardinality inner_skip_rows
Definition: pathnodes.h:3616
Cardinality outer_skip_rows
Definition: pathnodes.h:3615
bool skip_mark_restore
Definition: pathnodes.h:2365
List * innersortkeys
Definition: pathnodes.h:2362
JoinPath jpath
Definition: pathnodes.h:2359
bool materialize_inner
Definition: pathnodes.h:2366
List * path_mergeclauses
Definition: pathnodes.h:2360

References approx_tuple_count(), clamp_row_est(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, JoinCostWorkspace::disabled_nodes, enable_material, ExecSupportsMarkRestore(), get_parallel_divisor(), if(), JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, MergePath::innersortkeys, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, MergePath::jpath, list_length(), MergePath::materialize_inner, NIL, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, JoinPath::outerjoinpath, MergePath::path_mergeclauses, QualCost::per_tuple, relation_byte_size(), RELATION_WAS_MADE_UNIQUE, root, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::sjinfo, MergePath::skip_mark_restore, QualCost::startup, JoinCostWorkspace::startup_cost, and work_mem.

Referenced by create_mergejoin_path().

β—† final_cost_nestloop()

void final_cost_nestloop ( PlannerInfo root,
NestPath path,
JoinCostWorkspace workspace,
JoinPathExtraData extra 
)

Definition at line 3355 of file costsize.c.

3358{
3359 Path *outer_path = path->jpath.outerjoinpath;
3360 Path *inner_path = path->jpath.innerjoinpath;
3361 double outer_path_rows = outer_path->rows;
3362 double inner_path_rows = inner_path->rows;
3363 Cost startup_cost = workspace->startup_cost;
3364 Cost run_cost = workspace->run_cost;
3365 Cost cpu_per_tuple;
3366 QualCost restrict_qual_cost;
3367 double ntuples;
3368
3369 /* Set the number of disabled nodes. */
3370 path->jpath.path.disabled_nodes = workspace->disabled_nodes;
3371
3372 /* Protect some assumptions below that rowcounts aren't zero */
3373 if (outer_path_rows <= 0)
3374 outer_path_rows = 1;
3375 if (inner_path_rows <= 0)
3376 inner_path_rows = 1;
3377 /* Mark the path with the correct row estimate */
3378 if (path->jpath.path.param_info)
3379 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3380 else
3381 path->jpath.path.rows = path->jpath.path.parent->rows;
3382
3383 /* For partial paths, scale row estimate. */
3384 if (path->jpath.path.parallel_workers > 0)
3385 {
3386 double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3387
3388 path->jpath.path.rows =
3389 clamp_row_est(path->jpath.path.rows / parallel_divisor);
3390 }
3391
3392 /* cost of inner-relation source data (we already dealt with outer rel) */
3393
3394 if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3395 extra->inner_unique)
3396 {
3397 /*
3398 * With a SEMI or ANTI join, or if the innerrel is known unique, the
3399 * executor will stop after the first match.
3400 */
3401 Cost inner_run_cost = workspace->inner_run_cost;
3402 Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3403 double outer_matched_rows;
3404 double outer_unmatched_rows;
3405 Selectivity inner_scan_frac;
3406
3407 /*
3408 * For an outer-rel row that has at least one match, we can expect the
3409 * inner scan to stop after a fraction 1/(match_count+1) of the inner
3410 * rows, if the matches are evenly distributed. Since they probably
3411 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3412 * that fraction. (If we used a larger fuzz factor, we'd have to
3413 * clamp inner_scan_frac to at most 1.0; but since match_count is at
3414 * least 1, no such clamp is needed now.)
3415 */
3416 outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3417 outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3418 inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3419
3420 /*
3421 * Compute number of tuples processed (not number emitted!). First,
3422 * account for successfully-matched outer rows.
3423 */
3424 ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3425
3426 /*
3427 * Now we need to estimate the actual costs of scanning the inner
3428 * relation, which may be quite a bit less than N times inner_run_cost
3429 * due to early scan stops. We consider two cases. If the inner path
3430 * is an indexscan using all the joinquals as indexquals, then an
3431 * unmatched outer row results in an indexscan returning no rows,
3432 * which is probably quite cheap. Otherwise, the executor will have
3433 * to scan the whole inner rel for an unmatched row; not so cheap.
3434 */
3435 if (has_indexed_join_quals(path))
3436 {
3437 /*
3438 * Successfully-matched outer rows will only require scanning
3439 * inner_scan_frac of the inner relation. In this case, we don't
3440 * need to charge the full inner_run_cost even when that's more
3441 * than inner_rescan_run_cost, because we can assume that none of
3442 * the inner scans ever scan the whole inner relation. So it's
3443 * okay to assume that all the inner scan executions can be
3444 * fractions of the full cost, even if materialization is reducing
3445 * the rescan cost. At this writing, it's impossible to get here
3446 * for a materialized inner scan, so inner_run_cost and
3447 * inner_rescan_run_cost will be the same anyway; but just in
3448 * case, use inner_run_cost for the first matched tuple and
3449 * inner_rescan_run_cost for additional ones.
3450 */
3451 run_cost += inner_run_cost * inner_scan_frac;
3452 if (outer_matched_rows > 1)
3453 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3454
3455 /*
3456 * Add the cost of inner-scan executions for unmatched outer rows.
3457 * We estimate this as the same cost as returning the first tuple
3458 * of a nonempty scan. We consider that these are all rescans,
3459 * since we used inner_run_cost once already.
3460 */
3461 run_cost += outer_unmatched_rows *
3462 inner_rescan_run_cost / inner_path_rows;
3463
3464 /*
3465 * We won't be evaluating any quals at all for unmatched rows, so
3466 * don't add them to ntuples.
3467 */
3468 }
3469 else
3470 {
3471 /*
3472 * Here, a complicating factor is that rescans may be cheaper than
3473 * first scans. If we never scan all the way to the end of the
3474 * inner rel, it might be (depending on the plan type) that we'd
3475 * never pay the whole inner first-scan run cost. However it is
3476 * difficult to estimate whether that will happen (and it could
3477 * not happen if there are any unmatched outer rows!), so be
3478 * conservative and always charge the whole first-scan cost once.
3479 * We consider this charge to correspond to the first unmatched
3480 * outer row, unless there isn't one in our estimate, in which
3481 * case blame it on the first matched row.
3482 */
3483
3484 /* First, count all unmatched join tuples as being processed */
3485 ntuples += outer_unmatched_rows * inner_path_rows;
3486
3487 /* Now add the forced full scan, and decrement appropriate count */
3488 run_cost += inner_run_cost;
3489 if (outer_unmatched_rows >= 1)
3490 outer_unmatched_rows -= 1;
3491 else
3492 outer_matched_rows -= 1;
3493
3494 /* Add inner run cost for additional outer tuples having matches */
3495 if (outer_matched_rows > 0)
3496 run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3497
3498 /* Add inner run cost for additional unmatched outer tuples */
3499 if (outer_unmatched_rows > 0)
3500 run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3501 }
3502 }
3503 else
3504 {
3505 /* Normal-case source costs were included in preliminary estimate */
3506
3507 /* Compute number of tuples processed (not number emitted!) */
3508 ntuples = outer_path_rows * inner_path_rows;
3509 }
3510
3511 /* CPU costs */
3512 cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3513 startup_cost += restrict_qual_cost.startup;
3514 cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3515 run_cost += cpu_per_tuple * ntuples;
3516
3517 /* tlist eval costs are paid per output row, not per tuple scanned */
3518 startup_cost += path->jpath.path.pathtarget->cost.startup;
3519 run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3520
3521 path->jpath.path.startup_cost = startup_cost;
3522 path->jpath.path.total_cost = startup_cost + run_cost;
3523}
static bool has_indexed_join_quals(NestPath *path)
Definition: costsize.c:5220
Cost inner_rescan_run_cost
Definition: pathnodes.h:3610
JoinPath jpath
Definition: pathnodes.h:2313

References clamp_row_est(), cost_qual_eval(), cpu_tuple_cost, JoinCostWorkspace::disabled_nodes, get_parallel_divisor(), has_indexed_join_quals(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, NestPath::jpath, SemiAntiJoinFactors::match_count, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, QualCost::per_tuple, root, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, and JoinCostWorkspace::startup_cost.

Referenced by create_nestloop_path().

β—† get_expr_width()

static int32 get_expr_width ( PlannerInfo root,
const Node expr 
)
static

Definition at line 6414 of file costsize.c.

6415{
6416 int32 width;
6417
6418 if (IsA(expr, Var))
6419 {
6420 const Var *var = (const Var *) expr;
6421
6422 /* We should not see any upper-level Vars here */
6423 Assert(var->varlevelsup == 0);
6424
6425 /* Try to get data from RelOptInfo cache */
6426 if (!IS_SPECIAL_VARNO(var->varno) &&
6427 var->varno < root->simple_rel_array_size)
6428 {
6429 RelOptInfo *rel = root->simple_rel_array[var->varno];
6430
6431 if (rel != NULL &&
6432 var->varattno >= rel->min_attr &&
6433 var->varattno <= rel->max_attr)
6434 {
6435 int ndx = var->varattno - rel->min_attr;
6436
6437 if (rel->attr_widths[ndx] > 0)
6438 return rel->attr_widths[ndx];
6439 }
6440 }
6441
6442 /*
6443 * No cached data available, so estimate using just the type info.
6444 */
6445 width = get_typavgwidth(var->vartype, var->vartypmod);
6446 Assert(width > 0);
6447
6448 return width;
6449 }
6450
6451 width = get_typavgwidth(exprType(expr), exprTypmod(expr));
6452 Assert(width > 0);
6453 return width;
6454}
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2745
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:247
AttrNumber max_attr
Definition: pathnodes.h:981
AttrNumber min_attr
Definition: pathnodes.h:979
Definition: primnodes.h:262
AttrNumber varattno
Definition: primnodes.h:274
int varno
Definition: primnodes.h:269
Index varlevelsup
Definition: primnodes.h:294

References Assert(), exprType(), exprTypmod(), get_typavgwidth(), IS_SPECIAL_VARNO, IsA, RelOptInfo::max_attr, RelOptInfo::min_attr, root, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by cost_memoize_rescan(), and set_pathtarget_cost_width().

β—† get_foreign_key_join_selectivity()

static Selectivity get_foreign_key_join_selectivity ( PlannerInfo root,
Relids  outer_relids,
Relids  inner_relids,
SpecialJoinInfo sjinfo,
List **  restrictlist 
)
static

Definition at line 5660 of file costsize.c.

5665{
5666 Selectivity fkselec = 1.0;
5667 JoinType jointype = sjinfo->jointype;
5668 List *worklist = *restrictlist;
5669 ListCell *lc;
5670
5671 /* Consider each FK constraint that is known to match the query */
5672 foreach(lc, root->fkey_list)
5673 {
5674 ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
5675 bool ref_is_outer;
5676 List *removedlist;
5677 ListCell *cell;
5678
5679 /*
5680 * This FK is not relevant unless it connects a baserel on one side of
5681 * this join to a baserel on the other side.
5682 */
5683 if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5684 bms_is_member(fkinfo->ref_relid, inner_relids))
5685 ref_is_outer = false;
5686 else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5687 bms_is_member(fkinfo->con_relid, inner_relids))
5688 ref_is_outer = true;
5689 else
5690 continue;
5691
5692 /*
5693 * If we're dealing with a semi/anti join, and the FK's referenced
5694 * relation is on the outside, then knowledge of the FK doesn't help
5695 * us figure out what we need to know (which is the fraction of outer
5696 * rows that have matches). On the other hand, if the referenced rel
5697 * is on the inside, then all outer rows must have matches in the
5698 * referenced table (ignoring nulls). But any restriction or join
5699 * clauses that filter that table will reduce the fraction of matches.
5700 * We can account for restriction clauses, but it's too hard to guess
5701 * how many table rows would get through a join that's inside the RHS.
5702 * Hence, if either case applies, punt and ignore the FK.
5703 */
5704 if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
5705 (ref_is_outer || bms_membership(inner_relids) != BMS_SINGLETON))
5706 continue;
5707
5708 /*
5709 * Modify the restrictlist by removing clauses that match the FK (and
5710 * putting them into removedlist instead). It seems unsafe to modify
5711 * the originally-passed List structure, so we make a shallow copy the
5712 * first time through.
5713 */
5714 if (worklist == *restrictlist)
5715 worklist = list_copy(worklist);
5716
5717 removedlist = NIL;
5718 foreach(cell, worklist)
5719 {
5720 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5721 bool remove_it = false;
5722 int i;
5723
5724 /* Drop this clause if it matches any column of the FK */
5725 for (i = 0; i < fkinfo->nkeys; i++)
5726 {
5727 if (rinfo->parent_ec)
5728 {
5729 /*
5730 * EC-derived clauses can only match by EC. It is okay to
5731 * consider any clause derived from the same EC as
5732 * matching the FK: even if equivclass.c chose to generate
5733 * a clause equating some other pair of Vars, it could
5734 * have generated one equating the FK's Vars. So for
5735 * purposes of estimation, we can act as though it did so.
5736 *
5737 * Note: checking parent_ec is a bit of a cheat because
5738 * there are EC-derived clauses that don't have parent_ec
5739 * set; but such clauses must compare expressions that
5740 * aren't just Vars, so they cannot match the FK anyway.
5741 */
5742 if (fkinfo->eclass[i] == rinfo->parent_ec)
5743 {
5744 remove_it = true;
5745 break;
5746 }
5747 }
5748 else
5749 {
5750 /*
5751 * Otherwise, see if rinfo was previously matched to FK as
5752 * a "loose" clause.
5753 */
5754 if (list_member_ptr(fkinfo->rinfos[i], rinfo))
5755 {
5756 remove_it = true;
5757 break;
5758 }
5759 }
5760 }
5761 if (remove_it)
5762 {
5763 worklist = foreach_delete_current(worklist, cell);
5764 removedlist = lappend(removedlist, rinfo);
5765 }
5766 }
5767
5768 /*
5769 * If we failed to remove all the matching clauses we expected to
5770 * find, chicken out and ignore this FK; applying its selectivity
5771 * might result in double-counting. Put any clauses we did manage to
5772 * remove back into the worklist.
5773 *
5774 * Since the matching clauses are known not outerjoin-delayed, they
5775 * would normally have appeared in the initial joinclause list. If we
5776 * didn't find them, there are two possibilities:
5777 *
5778 * 1. If the FK match is based on an EC that is ec_has_const, it won't
5779 * have generated any join clauses at all. We discount such ECs while
5780 * checking to see if we have "all" the clauses. (Below, we'll adjust
5781 * the selectivity estimate for this case.)
5782 *
5783 * 2. The clauses were matched to some other FK in a previous
5784 * iteration of this loop, and thus removed from worklist. (A likely
5785 * case is that two FKs are matched to the same EC; there will be only
5786 * one EC-derived clause in the initial list, so the first FK will
5787 * consume it.) Applying both FKs' selectivity independently risks
5788 * underestimating the join size; in particular, this would undo one
5789 * of the main things that ECs were invented for, namely to avoid
5790 * double-counting the selectivity of redundant equality conditions.
5791 * Later we might think of a reasonable way to combine the estimates,
5792 * but for now, just punt, since this is a fairly uncommon situation.
5793 */
5794 if (removedlist == NIL ||
5795 list_length(removedlist) !=
5796 (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
5797 {
5798 worklist = list_concat(worklist, removedlist);
5799 continue;
5800 }
5801
5802 /*
5803 * Finally we get to the payoff: estimate selectivity using the
5804 * knowledge that each referencing row will match exactly one row in
5805 * the referenced table.
5806 *
5807 * XXX that's not true in the presence of nulls in the referencing
5808 * column(s), so in principle we should derate the estimate for those.
5809 * However (1) if there are any strict restriction clauses for the
5810 * referencing column(s) elsewhere in the query, derating here would
5811 * be double-counting the null fraction, and (2) it's not very clear
5812 * how to combine null fractions for multiple referencing columns. So
5813 * we do nothing for now about correcting for nulls.
5814 *
5815 * XXX another point here is that if either side of an FK constraint
5816 * is an inheritance parent, we estimate as though the constraint
5817 * covers all its children as well. This is not an unreasonable
5818 * assumption for a referencing table, ie the user probably applied
5819 * identical constraints to all child tables (though perhaps we ought
5820 * to check that). But it's not possible to have done that for a
5821 * referenced table. Fortunately, precisely because that doesn't
5822 * work, it is uncommon in practice to have an FK referencing a parent
5823 * table. So, at least for now, disregard inheritance here.
5824 */
5825 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
5826 {
5827 /*
5828 * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
5829 * referenced table is exactly the inside of the join. The join
5830 * selectivity is defined as the fraction of LHS rows that have
5831 * matches. The FK implies that every LHS row has a match *in the
5832 * referenced table*; but any restriction clauses on it will
5833 * reduce the number of matches. Hence we take the join
5834 * selectivity as equal to the selectivity of the table's
5835 * restriction clauses, which is rows / tuples; but we must guard
5836 * against tuples == 0.
5837 */
5838 RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5839 double ref_tuples = Max(ref_rel->tuples, 1.0);
5840
5841 fkselec *= ref_rel->rows / ref_tuples;
5842 }
5843 else
5844 {
5845 /*
5846 * Otherwise, selectivity is exactly 1/referenced-table-size; but
5847 * guard against tuples == 0. Note we should use the raw table
5848 * tuple count, not any estimate of its filtered or joined size.
5849 */
5850 RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5851 double ref_tuples = Max(ref_rel->tuples, 1.0);
5852
5853 fkselec *= 1.0 / ref_tuples;
5854 }
5855
5856 /*
5857 * If any of the FK columns participated in ec_has_const ECs, then
5858 * equivclass.c will have generated "var = const" restrictions for
5859 * each side of the join, thus reducing the sizes of both input
5860 * relations. Taking the fkselec at face value would amount to
5861 * double-counting the selectivity of the constant restriction for the
5862 * referencing Var. Hence, look for the restriction clause(s) that
5863 * were applied to the referencing Var(s), and divide out their
5864 * selectivity to correct for this.
5865 */
5866 if (fkinfo->nconst_ec > 0)
5867 {
5868 for (int i = 0; i < fkinfo->nkeys; i++)
5869 {
5870 EquivalenceClass *ec = fkinfo->eclass[i];
5871
5872 if (ec && ec->ec_has_const)
5873 {
5874 EquivalenceMember *em = fkinfo->fk_eclass_member[i];
5876 ec,
5877 em);
5878
5879 if (rinfo)
5880 {
5881 Selectivity s0;
5882
5884 (Node *) rinfo,
5885 0,
5886 jointype,
5887 sjinfo);
5888 if (s0 > 0)
5889 fkselec /= s0;
5890 }
5891 }
5892 }
5893 }
5894 }
5895
5896 *restrictlist = worklist;
5897 CLAMP_PROBABILITY(fkselec);
5898 return fkselec;
5899}
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:781
@ BMS_SINGLETON
Definition: bitmapset.h:72
RestrictInfo * find_derived_clause_for_ec_member(PlannerInfo *root, EquivalenceClass *ec, EquivalenceMember *em)
Definition: equivclass.c:2804
List * list_copy(const List *oldlist)
Definition: list.c:1573
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:682
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:529
#define CLAMP_PROBABILITY(p)
Definition: selfuncs.h:63
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:1397
List * rinfos[INDEX_MAX_KEYS]
Definition: pathnodes.h:1401
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:1399

References bms_is_member(), bms_membership(), BMS_SINGLETON, CLAMP_PROBABILITY, clause_selectivity(), ForeignKeyOptInfo::con_relid, EquivalenceClass::ec_has_const, ForeignKeyOptInfo::eclass, find_base_rel(), find_derived_clause_for_ec_member(), ForeignKeyOptInfo::fk_eclass_member, foreach_delete_current, i, JOIN_ANTI, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst, list_concat(), list_copy(), list_length(), list_member_ptr(), Max, ForeignKeyOptInfo::nconst_ec, NIL, ForeignKeyOptInfo::nkeys, ForeignKeyOptInfo::nmatched_ec, ForeignKeyOptInfo::nmatched_ri, ForeignKeyOptInfo::ref_relid, ForeignKeyOptInfo::rinfos, root, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by calc_joinrel_size_estimate().

β—† get_indexpath_pages()

static double get_indexpath_pages ( Path bitmapqual)
static

Definition at line 947 of file costsize.c.

948{
949 double result = 0;
950 ListCell *l;
951
952 if (IsA(bitmapqual, BitmapAndPath))
953 {
954 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
955
956 foreach(l, apath->bitmapquals)
957 {
958 result += get_indexpath_pages((Path *) lfirst(l));
959 }
960 }
961 else if (IsA(bitmapqual, BitmapOrPath))
962 {
963 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
964
965 foreach(l, opath->bitmapquals)
966 {
967 result += get_indexpath_pages((Path *) lfirst(l));
968 }
969 }
970 else if (IsA(bitmapqual, IndexPath))
971 {
972 IndexPath *ipath = (IndexPath *) bitmapqual;
973
974 result = (double) ipath->indexinfo->pages;
975 }
976 else
977 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
978
979 return result;
980}
BlockNumber pages
Definition: pathnodes.h:1266

References BitmapAndPath::bitmapquals, BitmapOrPath::bitmapquals, elog, ERROR, get_indexpath_pages(), IndexPath::indexinfo, IsA, lfirst, nodeTag, and IndexOptInfo::pages.

Referenced by compute_bitmap_pages(), and get_indexpath_pages().

β—† get_parallel_divisor()

static double get_parallel_divisor ( Path path)
static

Definition at line 6483 of file costsize.c.

6484{
6485 double parallel_divisor = path->parallel_workers;
6486
6487 /*
6488 * Early experience with parallel query suggests that when there is only
6489 * one worker, the leader often makes a very substantial contribution to
6490 * executing the parallel portion of the plan, but as more workers are
6491 * added, it does less and less, because it's busy reading tuples from the
6492 * workers and doing whatever non-parallel post-processing is needed. By
6493 * the time we reach 4 workers, the leader no longer makes a meaningful
6494 * contribution. Thus, for now, estimate that the leader spends 30% of
6495 * its time servicing each worker, and the remainder executing the
6496 * parallel plan.
6497 */
6499 {
6500 double leader_contribution;
6501
6502 leader_contribution = 1.0 - (0.3 * path->parallel_workers);
6503 if (leader_contribution > 0)
6504 parallel_divisor += leader_contribution;
6505 }
6506
6507 return parallel_divisor;
6508}
bool parallel_leader_participation
Definition: planner.c:70

References parallel_leader_participation, and Path::parallel_workers.

Referenced by compute_gather_rows(), cost_append(), cost_bitmap_heap_scan(), cost_index(), cost_seqscan(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), and initial_cost_hashjoin().

β—† get_parameterized_baserel_size()

double get_parameterized_baserel_size ( PlannerInfo root,
RelOptInfo rel,
List param_clauses 
)

Definition at line 5388 of file costsize.c.

5390{
5391 List *allclauses;
5392 double nrows;
5393
5394 /*
5395 * Estimate the number of rows returned by the parameterized scan, knowing
5396 * that it will apply all the extra join clauses as well as the rel's own
5397 * restriction clauses. Note that we force the clauses to be treated as
5398 * non-join clauses during selectivity estimation.
5399 */
5400 allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5401 nrows = rel->tuples *
5403 allclauses,
5404 rel->relid, /* do not use 0! */
5405 JOIN_INNER,
5406 NULL);
5407 nrows = clamp_row_est(nrows);
5408 /* For safety, make sure result is not more than the base estimate */
5409 if (nrows > rel->rows)
5410 nrows = rel->rows;
5411 return nrows;
5412}

References RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), JOIN_INNER, list_concat_copy(), RelOptInfo::relid, root, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by get_baserel_parampathinfo().

β—† get_parameterized_joinrel_size()

double get_parameterized_joinrel_size ( PlannerInfo root,
RelOptInfo rel,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
List restrict_clauses 
)

Definition at line 5469 of file costsize.c.

5474{
5475 double nrows;
5476
5477 /*
5478 * Estimate the number of rows returned by the parameterized join as the
5479 * sizes of the input paths times the selectivity of the clauses that have
5480 * ended up at this join node.
5481 *
5482 * As with set_joinrel_size_estimates, the rowcount estimate could depend
5483 * on the pair of input paths provided, though ideally we'd get the same
5484 * estimate for any pair with the same parameterization.
5485 */
5487 rel,
5488 outer_path->parent,
5489 inner_path->parent,
5490 outer_path->rows,
5491 inner_path->rows,
5492 sjinfo,
5493 restrict_clauses);
5494 /* For safety, make sure result is not more than the base estimate */
5495 if (nrows > rel->rows)
5496 nrows = rel->rows;
5497 return nrows;
5498}
static double calc_joinrel_size_estimate(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, double outer_rows, double inner_rows, SpecialJoinInfo *sjinfo, List *restrictlist)
Definition: costsize.c:5510

References calc_joinrel_size_estimate(), root, RelOptInfo::rows, and Path::rows.

Referenced by get_joinrel_parampathinfo().

β—† get_restriction_qual_cost()

static void get_restriction_qual_cost ( PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
QualCost qpqual_cost 
)
static

Definition at line 5081 of file costsize.c.

5084{
5085 if (param_info)
5086 {
5087 /* Include costs of pushed-down clauses */
5088 cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
5089
5090 qpqual_cost->startup += baserel->baserestrictcost.startup;
5091 qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
5092 }
5093 else
5094 *qpqual_cost = baserel->baserestrictcost;
5095}
QualCost baserestrictcost
Definition: pathnodes.h:1048

References RelOptInfo::baserestrictcost, cost_qual_eval(), QualCost::per_tuple, ParamPathInfo::ppi_clauses, root, and QualCost::startup.

Referenced by cost_bitmap_heap_scan(), cost_ctescan(), cost_functionscan(), cost_namedtuplestorescan(), cost_resultscan(), cost_samplescan(), cost_seqscan(), cost_subqueryscan(), cost_tablefuncscan(), cost_tidrangescan(), cost_tidscan(), and cost_valuesscan().

β—† get_windowclause_startup_tuples()

static double get_windowclause_startup_tuples ( PlannerInfo root,
WindowClause wc,
double  input_tuples 
)
static

Definition at line 2890 of file costsize.c.

2892{
2893 int frameOptions = wc->frameOptions;
2894 double partition_tuples;
2895 double return_tuples;
2896 double peer_tuples;
2897
2898 /*
2899 * First, figure out how many partitions there are likely to be and set
2900 * partition_tuples according to that estimate.
2901 */
2902 if (wc->partitionClause != NIL)
2903 {
2904 double num_partitions;
2906 root->parse->targetList);
2907
2908 num_partitions = estimate_num_groups(root, partexprs, input_tuples,
2909 NULL, NULL);
2910 list_free(partexprs);
2911
2912 partition_tuples = input_tuples / num_partitions;
2913 }
2914 else
2915 {
2916 /* all tuples belong to the same partition */
2917 partition_tuples = input_tuples;
2918 }
2919
2920 /* estimate the number of tuples in each peer group */
2921 if (wc->orderClause != NIL)
2922 {
2923 double num_groups;
2924 List *orderexprs;
2925
2926 orderexprs = get_sortgrouplist_exprs(wc->orderClause,
2927 root->parse->targetList);
2928
2929 /* estimate out how many peer groups there are in the partition */
2930 num_groups = estimate_num_groups(root, orderexprs,
2931 partition_tuples, NULL,
2932 NULL);
2933 list_free(orderexprs);
2934 peer_tuples = partition_tuples / num_groups;
2935 }
2936 else
2937 {
2938 /* no ORDER BY so only 1 tuple belongs in each peer group */
2939 peer_tuples = 1.0;
2940 }
2941
2942 if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
2943 {
2944 /* include all partition rows */
2945 return_tuples = partition_tuples;
2946 }
2947 else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
2948 {
2949 if (frameOptions & FRAMEOPTION_ROWS)
2950 {
2951 /* just count the current row */
2952 return_tuples = 1.0;
2953 }
2954 else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
2955 {
2956 /*
2957 * When in RANGE/GROUPS mode, it's more complex. If there's no
2958 * ORDER BY, then all rows in the partition are peers, otherwise
2959 * we'll need to read the first group of peers.
2960 */
2961 if (wc->orderClause == NIL)
2962 return_tuples = partition_tuples;
2963 else
2964 return_tuples = peer_tuples;
2965 }
2966 else
2967 {
2968 /*
2969 * Something new we don't support yet? This needs attention.
2970 * We'll just return 1.0 in the meantime.
2971 */
2972 Assert(false);
2973 return_tuples = 1.0;
2974 }
2975 }
2976 else if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
2977 {
2978 /*
2979 * BETWEEN ... AND N PRECEDING will only need to read the WindowAgg's
2980 * subnode after N ROWS/RANGES/GROUPS. N can be 0, but not negative,
2981 * so we'll just assume only the current row needs to be read to fetch
2982 * the first WindowAgg row.
2983 */
2984 return_tuples = 1.0;
2985 }
2986 else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
2987 {
2988 Const *endOffset = (Const *) wc->endOffset;
2989 double end_offset_value;
2990
2991 /* try and figure out the value specified in the endOffset. */
2992 if (IsA(endOffset, Const))
2993 {
2994 if (endOffset->constisnull)
2995 {
2996 /*
2997 * NULLs are not allowed, but currently, there's no code to
2998 * error out if there's a NULL Const. We'll only discover
2999 * this during execution. For now, just pretend everything is
3000 * fine and assume that just the first row/range/group will be
3001 * needed.
3002 */
3003 end_offset_value = 1.0;
3004 }
3005 else
3006 {
3007 switch (endOffset->consttype)
3008 {
3009 case INT2OID:
3010 end_offset_value =
3011 (double) DatumGetInt16(endOffset->constvalue);
3012 break;
3013 case INT4OID:
3014 end_offset_value =
3015 (double) DatumGetInt32(endOffset->constvalue);
3016 break;
3017 case INT8OID:
3018 end_offset_value =
3019 (double) DatumGetInt64(endOffset->constvalue);
3020 break;
3021 default:
3022 end_offset_value =
3023 partition_tuples / peer_tuples *
3025 break;
3026 }
3027 }
3028 }
3029 else
3030 {
3031 /*
3032 * When the end bound is not a Const, we'll just need to guess. We
3033 * just make use of DEFAULT_INEQ_SEL.
3034 */
3035 end_offset_value =
3036 partition_tuples / peer_tuples * DEFAULT_INEQ_SEL;
3037 }
3038
3039 if (frameOptions & FRAMEOPTION_ROWS)
3040 {
3041 /* include the N FOLLOWING and the current row */
3042 return_tuples = end_offset_value + 1.0;
3043 }
3044 else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
3045 {
3046 /* include N FOLLOWING ranges/group and the initial range/group */
3047 return_tuples = peer_tuples * (end_offset_value + 1.0);
3048 }
3049 else
3050 {
3051 /*
3052 * Something new we don't support yet? This needs attention.
3053 * We'll just return 1.0 in the meantime.
3054 */
3055 Assert(false);
3056 return_tuples = 1.0;
3057 }
3058 }
3059 else
3060 {
3061 /*
3062 * Something new we don't support yet? This needs attention. We'll
3063 * just return 1.0 in the meantime.
3064 */
3065 Assert(false);
3066 return_tuples = 1.0;
3067 }
3068
3069 if (wc->partitionClause != NIL || wc->orderClause != NIL)
3070 {
3071 /*
3072 * Cap the return value to the estimated partition tuples and account
3073 * for the extra tuple WindowAgg will need to read to confirm the next
3074 * tuple does not belong to the same partition or peer group.
3075 */
3076 return_tuples = Min(return_tuples + 1.0, partition_tuples);
3077 }
3078 else
3079 {
3080 /*
3081 * Cap the return value so it's never higher than the expected tuples
3082 * in the partition.
3083 */
3084 return_tuples = Min(return_tuples, partition_tuples);
3085 }
3086
3087 /*
3088 * We needn't worry about any EXCLUDE options as those only exclude rows
3089 * from being aggregated, not from being read from the WindowAgg's
3090 * subnode.
3091 */
3092
3093 return clamp_row_est(return_tuples);
3094}
#define FRAMEOPTION_END_CURRENT_ROW
Definition: parsenodes.h:619
#define FRAMEOPTION_END_OFFSET_PRECEDING
Definition: parsenodes.h:621
#define FRAMEOPTION_END_OFFSET_FOLLOWING
Definition: parsenodes.h:623
#define FRAMEOPTION_RANGE
Definition: parsenodes.h:610
#define FRAMEOPTION_GROUPS
Definition: parsenodes.h:612
#define FRAMEOPTION_END_UNBOUNDED_FOLLOWING
Definition: parsenodes.h:617
#define FRAMEOPTION_ROWS
Definition: parsenodes.h:611
static int64 DatumGetInt64(Datum X)
Definition: postgres.h:393
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:172
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:212
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Oid consttype
Definition: primnodes.h:329
Node * endOffset
Definition: parsenodes.h:1579
List * get_sortgrouplist_exprs(List *sgClauses, List *targetList)
Definition: tlist.c:392

References Assert(), clamp_row_est(), Const::consttype, DatumGetInt16(), DatumGetInt32(), DatumGetInt64(), DEFAULT_INEQ_SEL, WindowClause::endOffset, estimate_num_groups(), FRAMEOPTION_END_CURRENT_ROW, FRAMEOPTION_END_OFFSET_FOLLOWING, FRAMEOPTION_END_OFFSET_PRECEDING, FRAMEOPTION_END_UNBOUNDED_FOLLOWING, FRAMEOPTION_GROUPS, FRAMEOPTION_RANGE, FRAMEOPTION_ROWS, WindowClause::frameOptions, get_sortgrouplist_exprs(), if(), IsA, list_free(), Min, NIL, WindowClause::orderClause, WindowClause::partitionClause, and root.

Referenced by cost_windowagg().

β—† has_indexed_join_quals()

static bool has_indexed_join_quals ( NestPath path)
static

Definition at line 5220 of file costsize.c.

5221{
5222 JoinPath *joinpath = &path->jpath;
5223 Relids joinrelids = joinpath->path.parent->relids;
5224 Path *innerpath = joinpath->innerjoinpath;
5225 List *indexclauses;
5226 bool found_one;
5227 ListCell *lc;
5228
5229 /* If join still has quals to evaluate, it's not fast */
5230 if (joinpath->joinrestrictinfo != NIL)
5231 return false;
5232 /* Nor if the inner path isn't parameterized at all */
5233 if (innerpath->param_info == NULL)
5234 return false;
5235
5236 /* Find the indexclauses list for the inner scan */
5237 switch (innerpath->pathtype)
5238 {
5239 case T_IndexScan:
5240 case T_IndexOnlyScan:
5241 indexclauses = ((IndexPath *) innerpath)->indexclauses;
5242 break;
5243 case T_BitmapHeapScan:
5244 {
5245 /* Accept only a simple bitmap scan, not AND/OR cases */
5246 Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
5247
5248 if (IsA(bmqual, IndexPath))
5249 indexclauses = ((IndexPath *) bmqual)->indexclauses;
5250 else
5251 return false;
5252 break;
5253 }
5254 default:
5255
5256 /*
5257 * If it's not a simple indexscan, it probably doesn't run quickly
5258 * for zero rows out, even if it's a parameterized path using all
5259 * the joinquals.
5260 */
5261 return false;
5262 }
5263
5264 /*
5265 * Examine the inner path's param clauses. Any that are from the outer
5266 * path must be found in the indexclauses list, either exactly or in an
5267 * equivalent form generated by equivclass.c. Also, we must find at least
5268 * one such clause, else it's a clauseless join which isn't fast.
5269 */
5270 found_one = false;
5271 foreach(lc, innerpath->param_info->ppi_clauses)
5272 {
5273 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
5274
5276 innerpath->parent->relids,
5277 joinrelids))
5278 {
5279 if (!is_redundant_with_indexclauses(rinfo, indexclauses))
5280 return false;
5281 found_one = true;
5282 }
5283 }
5284 return found_one;
5285}
bool join_clause_is_movable_into(RestrictInfo *rinfo, Relids currentrelids, Relids current_and_outer)
Definition: restrictinfo.c:661

References JoinPath::innerjoinpath, is_redundant_with_indexclauses(), IsA, join_clause_is_movable_into(), JoinPath::joinrestrictinfo, NestPath::jpath, lfirst, NIL, and Path::pathtype.

Referenced by final_cost_nestloop().

β—† index_pages_fetched()

double index_pages_fetched ( double  tuples_fetched,
BlockNumber  pages,
double  index_pages,
PlannerInfo root 
)

Definition at line 882 of file costsize.c.

884{
885 double pages_fetched;
886 double total_pages;
887 double T,
888 b;
889
890 /* T is # pages in table, but don't allow it to be zero */
891 T = (pages > 1) ? (double) pages : 1.0;
892
893 /* Compute number of pages assumed to be competing for cache space */
894 total_pages = root->total_table_pages + index_pages;
895 total_pages = Max(total_pages, 1.0);
896 Assert(T <= total_pages);
897
898 /* b is pro-rated share of effective_cache_size */
899 b = (double) effective_cache_size * T / total_pages;
900
901 /* force it positive and integral */
902 if (b <= 1.0)
903 b = 1.0;
904 else
905 b = ceil(b);
906
907 /* This part is the Mackert and Lohman formula */
908 if (T <= b)
909 {
910 pages_fetched =
911 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
912 if (pages_fetched >= T)
913 pages_fetched = T;
914 else
915 pages_fetched = ceil(pages_fetched);
916 }
917 else
918 {
919 double lim;
920
921 lim = (2.0 * T * b) / (2.0 * T - b);
922 if (tuples_fetched <= lim)
923 {
924 pages_fetched =
925 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
926 }
927 else
928 {
929 pages_fetched =
930 b + (tuples_fetched - lim) * (T - b) / T;
931 }
932 pages_fetched = ceil(pages_fetched);
933 }
934 return pages_fetched;
935}
int effective_cache_size
Definition: costsize.c:139
int b
Definition: isn.c:74

References Assert(), b, effective_cache_size, Max, root, and T.

Referenced by compute_bitmap_pages(), cost_index(), genericcostestimate(), and gincostestimate().

β—† initial_cost_hashjoin()

void initial_cost_hashjoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List hashclauses,
Path outer_path,
Path inner_path,
JoinPathExtraData extra,
bool  parallel_hash 
)

Definition at line 4168 of file costsize.c.

4174{
4175 int disabled_nodes;
4176 Cost startup_cost = 0;
4177 Cost run_cost = 0;
4178 double outer_path_rows = outer_path->rows;
4179 double inner_path_rows = inner_path->rows;
4180 double inner_path_rows_total = inner_path_rows;
4181 int num_hashclauses = list_length(hashclauses);
4182 int numbuckets;
4183 int numbatches;
4184 int num_skew_mcvs;
4185 size_t space_allowed; /* unused */
4186
4187 /* Count up disabled nodes. */
4188 disabled_nodes = enable_hashjoin ? 0 : 1;
4189 disabled_nodes += inner_path->disabled_nodes;
4190 disabled_nodes += outer_path->disabled_nodes;
4191
4192 /* cost of source data */
4193 startup_cost += outer_path->startup_cost;
4194 run_cost += outer_path->total_cost - outer_path->startup_cost;
4195 startup_cost += inner_path->total_cost;
4196
4197 /*
4198 * Cost of computing hash function: must do it once per input tuple. We
4199 * charge one cpu_operator_cost for each column's hash function. Also,
4200 * tack on one cpu_tuple_cost per inner row, to model the costs of
4201 * inserting the row into the hashtable.
4202 *
4203 * XXX when a hashclause is more complex than a single operator, we really
4204 * should charge the extra eval costs of the left or right side, as
4205 * appropriate, here. This seems more work than it's worth at the moment.
4206 */
4207 startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
4208 * inner_path_rows;
4209 run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
4210
4211 /*
4212 * If this is a parallel hash build, then the value we have for
4213 * inner_rows_total currently refers only to the rows returned by each
4214 * participant. For shared hash table size estimation, we need the total
4215 * number, so we need to undo the division.
4216 */
4217 if (parallel_hash)
4218 inner_path_rows_total *= get_parallel_divisor(inner_path);
4219
4220 /*
4221 * Get hash table size that executor would use for inner relation.
4222 *
4223 * XXX for the moment, always assume that skew optimization will be
4224 * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
4225 * trying to determine that for sure.
4226 *
4227 * XXX at some point it might be interesting to try to account for skew
4228 * optimization in the cost estimate, but for now, we don't.
4229 */
4230 ExecChooseHashTableSize(inner_path_rows_total,
4231 inner_path->pathtarget->width,
4232 true, /* useskew */
4233 parallel_hash, /* try_combined_hash_mem */
4234 outer_path->parallel_workers,
4235 &space_allowed,
4236 &numbuckets,
4237 &numbatches,
4238 &num_skew_mcvs);
4239
4240 /*
4241 * If inner relation is too big then we will need to "batch" the join,
4242 * which implies writing and reading most of the tuples to disk an extra
4243 * time. Charge seq_page_cost per page, since the I/O should be nice and
4244 * sequential. Writing the inner rel counts as startup cost, all the rest
4245 * as run cost.
4246 */
4247 if (numbatches > 1)
4248 {
4249 double outerpages = page_size(outer_path_rows,
4250 outer_path->pathtarget->width);
4251 double innerpages = page_size(inner_path_rows,
4252 inner_path->pathtarget->width);
4253
4254 startup_cost += seq_page_cost * innerpages;
4255 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4256 }
4257
4258 /* CPU costs left for later */
4259
4260 /* Public result fields */
4261 workspace->disabled_nodes = disabled_nodes;
4262 workspace->startup_cost = startup_cost;
4263 workspace->total_cost = startup_cost + run_cost;
4264 /* Save private data for final_cost_hashjoin */
4265 workspace->run_cost = run_cost;
4266 workspace->numbuckets = numbuckets;
4267 workspace->numbatches = numbatches;
4268 workspace->inner_rows_total = inner_path_rows_total;
4269}
static double page_size(double tuples, int width)
Definition: costsize.c:6473
bool enable_hashjoin
Definition: costsize.c:157
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, bool try_combined_hash_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:657

References cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, JoinCostWorkspace::disabled_nodes, enable_hashjoin, ExecChooseHashTableSize(), get_parallel_divisor(), JoinCostWorkspace::inner_rows_total, list_length(), JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, page_size(), Path::parallel_workers, Path::rows, JoinCostWorkspace::run_cost, seq_page_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, and JoinCostWorkspace::total_cost.

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

β—† initial_cost_mergejoin()

void initial_cost_mergejoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List mergeclauses,
Path outer_path,
Path inner_path,
List outersortkeys,
List innersortkeys,
int  outer_presorted_keys,
JoinPathExtraData extra 
)

Definition at line 3558 of file costsize.c.

3565{
3566 int disabled_nodes;
3567 Cost startup_cost = 0;
3568 Cost run_cost = 0;
3569 double outer_path_rows = outer_path->rows;
3570 double inner_path_rows = inner_path->rows;
3571 Cost inner_run_cost;
3572 double outer_rows,
3573 inner_rows,
3574 outer_skip_rows,
3575 inner_skip_rows;
3576 Selectivity outerstartsel,
3577 outerendsel,
3578 innerstartsel,
3579 innerendsel;
3580 Path sort_path; /* dummy for result of
3581 * cost_sort/cost_incremental_sort */
3582
3583 /* Protect some assumptions below that rowcounts aren't zero */
3584 if (outer_path_rows <= 0)
3585 outer_path_rows = 1;
3586 if (inner_path_rows <= 0)
3587 inner_path_rows = 1;
3588
3589 /*
3590 * A merge join will stop as soon as it exhausts either input stream
3591 * (unless it's an outer join, in which case the outer side has to be
3592 * scanned all the way anyway). Estimate fraction of the left and right
3593 * inputs that will actually need to be scanned. Likewise, we can
3594 * estimate the number of rows that will be skipped before the first join
3595 * pair is found, which should be factored into startup cost. We use only
3596 * the first (most significant) merge clause for this purpose. Since
3597 * mergejoinscansel() is a fairly expensive computation, we cache the
3598 * results in the merge clause RestrictInfo.
3599 */
3600 if (mergeclauses && jointype != JOIN_FULL)
3601 {
3602 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3603 List *opathkeys;
3604 List *ipathkeys;
3605 PathKey *opathkey;
3606 PathKey *ipathkey;
3607 MergeScanSelCache *cache;
3608
3609 /* Get the input pathkeys to determine the sort-order details */
3610 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3611 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3612 Assert(opathkeys);
3613 Assert(ipathkeys);
3614 opathkey = (PathKey *) linitial(opathkeys);
3615 ipathkey = (PathKey *) linitial(ipathkeys);
3616 /* debugging check */
3617 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3618 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3619 opathkey->pk_cmptype != ipathkey->pk_cmptype ||
3620 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3621 elog(ERROR, "left and right pathkeys do not match in mergejoin");
3622
3623 /* Get the selectivity with caching */
3624 cache = cached_scansel(root, firstclause, opathkey);
3625
3626 if (bms_is_subset(firstclause->left_relids,
3627 outer_path->parent->relids))
3628 {
3629 /* left side of clause is outer */
3630 outerstartsel = cache->leftstartsel;
3631 outerendsel = cache->leftendsel;
3632 innerstartsel = cache->rightstartsel;
3633 innerendsel = cache->rightendsel;
3634 }
3635 else
3636 {
3637 /* left side of clause is inner */
3638 outerstartsel = cache->rightstartsel;
3639 outerendsel = cache->rightendsel;
3640 innerstartsel = cache->leftstartsel;
3641 innerendsel = cache->leftendsel;
3642 }
3643 if (jointype == JOIN_LEFT ||
3644 jointype == JOIN_ANTI)
3645 {
3646 outerstartsel = 0.0;
3647 outerendsel = 1.0;
3648 }
3649 else if (jointype == JOIN_RIGHT ||
3650 jointype == JOIN_RIGHT_ANTI)
3651 {
3652 innerstartsel = 0.0;
3653 innerendsel = 1.0;
3654 }
3655 }
3656 else
3657 {
3658 /* cope with clauseless or full mergejoin */
3659 outerstartsel = innerstartsel = 0.0;
3660 outerendsel = innerendsel = 1.0;
3661 }
3662
3663 /*
3664 * Convert selectivities to row counts. We force outer_rows and
3665 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3666 */
3667 outer_skip_rows = rint(outer_path_rows * outerstartsel);
3668 inner_skip_rows = rint(inner_path_rows * innerstartsel);
3669 outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3670 inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3671
3672 Assert(outer_skip_rows <= outer_rows);
3673 Assert(inner_skip_rows <= inner_rows);
3674
3675 /*
3676 * Readjust scan selectivities to account for above rounding. This is
3677 * normally an insignificant effect, but when there are only a few rows in
3678 * the inputs, failing to do this makes for a large percentage error.
3679 */
3680 outerstartsel = outer_skip_rows / outer_path_rows;
3681 innerstartsel = inner_skip_rows / inner_path_rows;
3682 outerendsel = outer_rows / outer_path_rows;
3683 innerendsel = inner_rows / inner_path_rows;
3684
3685 Assert(outerstartsel <= outerendsel);
3686 Assert(innerstartsel <= innerendsel);
3687
3688 disabled_nodes = enable_mergejoin ? 0 : 1;
3689
3690 /* cost of source data */
3691
3692 if (outersortkeys) /* do we need to sort outer? */
3693 {
3694 /*
3695 * We can assert that the outer path is not already ordered
3696 * appropriately for the mergejoin; otherwise, outersortkeys would
3697 * have been set to NIL.
3698 */
3699 Assert(!pathkeys_contained_in(outersortkeys, outer_path->pathkeys));
3700
3701 /*
3702 * We choose to use incremental sort if it is enabled and there are
3703 * presorted keys; otherwise we use full sort.
3704 */
3705 if (enable_incremental_sort && outer_presorted_keys > 0)
3706 {
3707 cost_incremental_sort(&sort_path,
3708 root,
3709 outersortkeys,
3710 outer_presorted_keys,
3711 outer_path->disabled_nodes,
3712 outer_path->startup_cost,
3713 outer_path->total_cost,
3714 outer_path_rows,
3715 outer_path->pathtarget->width,
3716 0.0,
3717 work_mem,
3718 -1.0);
3719 }
3720 else
3721 {
3722 cost_sort(&sort_path,
3723 root,
3724 outersortkeys,
3725 outer_path->disabled_nodes,
3726 outer_path->total_cost,
3727 outer_path_rows,
3728 outer_path->pathtarget->width,
3729 0.0,
3730 work_mem,
3731 -1.0);
3732 }
3733
3734 disabled_nodes += sort_path.disabled_nodes;
3735 startup_cost += sort_path.startup_cost;
3736 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3737 * outerstartsel;
3738 run_cost += (sort_path.total_cost - sort_path.startup_cost)
3739 * (outerendsel - outerstartsel);
3740 }
3741 else
3742 {
3743 disabled_nodes += outer_path->disabled_nodes;
3744 startup_cost += outer_path->startup_cost;
3745 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3746 * outerstartsel;
3747 run_cost += (outer_path->total_cost - outer_path->startup_cost)
3748 * (outerendsel - outerstartsel);
3749 }
3750
3751 if (innersortkeys) /* do we need to sort inner? */
3752 {
3753 /*
3754 * We can assert that the inner path is not already ordered
3755 * appropriately for the mergejoin; otherwise, innersortkeys would
3756 * have been set to NIL.
3757 */
3758 Assert(!pathkeys_contained_in(innersortkeys, inner_path->pathkeys));
3759
3760 /*
3761 * We do not consider incremental sort for inner path, because
3762 * incremental sort does not support mark/restore.
3763 */
3764
3765 cost_sort(&sort_path,
3766 root,
3767 innersortkeys,
3768 inner_path->disabled_nodes,
3769 inner_path->total_cost,
3770 inner_path_rows,
3771 inner_path->pathtarget->width,
3772 0.0,
3773 work_mem,
3774 -1.0);
3775 disabled_nodes += sort_path.disabled_nodes;
3776 startup_cost += sort_path.startup_cost;
3777 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3778 * innerstartsel;
3779 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3780 * (innerendsel - innerstartsel);
3781 }
3782 else
3783 {
3784 disabled_nodes += inner_path->disabled_nodes;
3785 startup_cost += inner_path->startup_cost;
3786 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3787 * innerstartsel;
3788 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3789 * (innerendsel - innerstartsel);
3790 }
3791
3792 /*
3793 * We can't yet determine whether rescanning occurs, or whether
3794 * materialization of the inner input should be done. The minimum
3795 * possible inner input cost, regardless of rescan and materialization
3796 * considerations, is inner_run_cost. We include that in
3797 * workspace->total_cost, but not yet in run_cost.
3798 */
3799
3800 /* CPU costs left for later */
3801
3802 /* Public result fields */
3803 workspace->disabled_nodes = disabled_nodes;
3804 workspace->startup_cost = startup_cost;
3805 workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3806 /* Save private data for final_cost_mergejoin */
3807 workspace->run_cost = run_cost;
3808 workspace->inner_run_cost = inner_run_cost;
3809 workspace->outer_rows = outer_rows;
3810 workspace->inner_rows = inner_rows;
3811 workspace->outer_skip_rows = outer_skip_rows;
3812 workspace->inner_skip_rows = inner_skip_rows;
3813}
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:4089
bool enable_mergejoin
Definition: costsize.c:156
@ JOIN_RIGHT
Definition: nodes.h:306
@ JOIN_RIGHT_ANTI
Definition: nodes.h:320
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:343

References Assert(), bms_is_subset(), cached_scansel(), clamp_row_est(), cost_incremental_sort(), cost_sort(), Path::disabled_nodes, JoinCostWorkspace::disabled_nodes, elog, enable_incremental_sort, enable_mergejoin, ERROR, JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JOIN_ANTI, JOIN_FULL, JOIN_LEFT, JOIN_RIGHT, JOIN_RIGHT_ANTI, MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, linitial, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, Path::pathkeys, pathkeys_contained_in(), PathKey::pk_cmptype, PathKey::pk_nulls_first, PathKey::pk_opfamily, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, root, Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, and work_mem.

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

β—† initial_cost_nestloop()

void initial_cost_nestloop ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
Path outer_path,
Path inner_path,
JoinPathExtraData extra 
)

Definition at line 3273 of file costsize.c.

3277{
3278 int disabled_nodes;
3279 Cost startup_cost = 0;
3280 Cost run_cost = 0;
3281 double outer_path_rows = outer_path->rows;
3282 Cost inner_rescan_start_cost;
3283 Cost inner_rescan_total_cost;
3284 Cost inner_run_cost;
3285 Cost inner_rescan_run_cost;
3286
3287 /* Count up disabled nodes. */
3288 disabled_nodes = enable_nestloop ? 0 : 1;
3289 disabled_nodes += inner_path->disabled_nodes;
3290 disabled_nodes += outer_path->disabled_nodes;
3291
3292 /* estimate costs to rescan the inner relation */
3293 cost_rescan(root, inner_path,
3294 &inner_rescan_start_cost,
3295 &inner_rescan_total_cost);
3296
3297 /* cost of source data */
3298
3299 /*
3300 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3301 * before we can start returning tuples, so the join's startup cost is
3302 * their sum. We'll also pay the inner path's rescan startup cost
3303 * multiple times.
3304 */
3305 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3306 run_cost += outer_path->total_cost - outer_path->startup_cost;
3307 if (outer_path_rows > 1)
3308 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3309
3310 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3311 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3312
3313 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3314 extra->inner_unique)
3315 {
3316 /*
3317 * With a SEMI or ANTI join, or if the innerrel is known unique, the
3318 * executor will stop after the first match.
3319 *
3320 * Getting decent estimates requires inspection of the join quals,
3321 * which we choose to postpone to final_cost_nestloop.
3322 */
3323
3324 /* Save private data for final_cost_nestloop */
3325 workspace->inner_run_cost = inner_run_cost;
3326 workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3327 }
3328 else
3329 {
3330 /* Normal case; we'll scan whole input rel for each outer row */
3331 run_cost += inner_run_cost;
3332 if (outer_path_rows > 1)
3333 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3334 }
3335
3336 /* CPU costs left for later */
3337
3338 /* Public result fields */
3339 workspace->disabled_nodes = disabled_nodes;
3340 workspace->startup_cost = startup_cost;
3341 workspace->total_cost = startup_cost + run_cost;
3342 /* Save private data for final_cost_nestloop */
3343 workspace->run_cost = run_cost;
3344}
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:4650
bool enable_nestloop
Definition: costsize.c:153

References cost_rescan(), Path::disabled_nodes, JoinCostWorkspace::disabled_nodes, enable_nestloop, JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JOIN_ANTI, JOIN_SEMI, root, Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, and JoinCostWorkspace::total_cost.

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

β—† page_size()

static double page_size ( double  tuples,
int  width 
)
static

Definition at line 6473 of file costsize.c.

6474{
6475 return ceil(relation_byte_size(tuples, width) / BLCKSZ);
6476}

References relation_byte_size().

Referenced by initial_cost_hashjoin().

β—† relation_byte_size()

static double relation_byte_size ( double  tuples,
int  width 
)
static

Definition at line 6462 of file costsize.c.

6463{
6464 return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
6465}
#define MAXALIGN(LEN)
Definition: c.h:814
#define SizeofHeapTupleHeader
Definition: htup_details.h:185

References MAXALIGN, and SizeofHeapTupleHeader.

Referenced by cost_agg(), cost_material(), cost_memoize_rescan(), cost_rescan(), cost_tuplesort(), final_cost_hashjoin(), final_cost_mergejoin(), and page_size().

β—† set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

β—† set_cte_size_estimates()

void set_cte_size_estimates ( PlannerInfo root,
RelOptInfo rel,
double  cte_rows 
)

Definition at line 6084 of file costsize.c.

6085{
6086 RangeTblEntry *rte;
6087
6088 /* Should only be applied to base relations that are CTE references */
6089 Assert(rel->relid > 0);
6090 rte = planner_rt_fetch(rel->relid, root);
6091 Assert(rte->rtekind == RTE_CTE);
6092
6093 if (rte->self_reference)
6094 {
6095 /*
6096 * In a self-reference, we assume the average worktable size is a
6097 * multiple of the nonrecursive term's size. The best multiplier will
6098 * vary depending on query "fan-out", so make its value adjustable.
6099 */
6101 }
6102 else
6103 {
6104 /* Otherwise just believe the CTE's rowcount estimate */
6105 rel->tuples = cte_rows;
6106 }
6107
6108 /* Now estimate number of output rows, etc */
6110}
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5358
double recursive_worktable_factor
Definition: costsize.c:137

References Assert(), clamp_row_est(), planner_rt_fetch, recursive_worktable_factor, RelOptInfo::relid, root, RTE_CTE, RangeTblEntry::rtekind, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

β—† set_foreign_size_estimates()

void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6184 of file costsize.c.

6185{
6186 /* Should only be applied to base relations */
6187 Assert(rel->relid > 0);
6188
6189 rel->rows = 1000; /* entirely bogus default estimate */
6190
6192
6193 set_rel_width(root, rel);
6194}

References Assert(), RelOptInfo::baserestrictcost, RelOptInfo::baserestrictinfo, cost_qual_eval(), RelOptInfo::relid, root, RelOptInfo::rows, and set_rel_width().

Referenced by set_foreign_size().

β—† set_function_size_estimates()

void set_function_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5992 of file costsize.c.

5993{
5994 RangeTblEntry *rte;
5995 ListCell *lc;
5996
5997 /* Should only be applied to base relations that are functions */
5998 Assert(rel->relid > 0);
5999 rte = planner_rt_fetch(rel->relid, root);
6000 Assert(rte->rtekind == RTE_FUNCTION);
6001
6002 /*
6003 * Estimate number of rows the functions will return. The rowcount of the
6004 * node is that of the largest function result.
6005 */
6006 rel->tuples = 0;
6007 foreach(lc, rte->functions)
6008 {
6009 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
6010 double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
6011
6012 if (ntup > rel->tuples)
6013 rel->tuples = ntup;
6014 }
6015
6016 /* Now estimate number of output rows, etc */
6018}
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:293

References Assert(), expression_returns_set_rows(), RangeTblFunction::funcexpr, RangeTblEntry::functions, lfirst, planner_rt_fetch, RelOptInfo::relid, root, RTE_FUNCTION, RangeTblEntry::rtekind, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_rel_size().

β—† set_joinrel_size_estimates()

void set_joinrel_size_estimates ( PlannerInfo root,
RelOptInfo rel,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
SpecialJoinInfo sjinfo,
List restrictlist 
)

Definition at line 5437 of file costsize.c.

5442{
5444 rel,
5445 outer_rel,
5446 inner_rel,
5447 outer_rel->rows,
5448 inner_rel->rows,
5449 sjinfo,
5450 restrictlist);
5451}

References calc_joinrel_size_estimate(), root, and RelOptInfo::rows.

Referenced by build_child_join_rel(), build_join_rel(), and make_grouped_join_rel().

β—† set_namedtuplestore_size_estimates()

void set_namedtuplestore_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6122 of file costsize.c.

6123{
6124 RangeTblEntry *rte;
6125
6126 /* Should only be applied to base relations that are tuplestore references */
6127 Assert(rel->relid > 0);
6128 rte = planner_rt_fetch(rel->relid, root);
6130
6131 /*
6132 * Use the estimate provided by the code which is generating the named
6133 * tuplestore. In some cases, the actual number might be available; in
6134 * others the same plan will be re-used, so a "typical" value might be
6135 * estimated and used.
6136 */
6137 rel->tuples = rte->enrtuples;
6138 if (rel->tuples < 0)
6139 rel->tuples = 1000;
6140
6141 /* Now estimate number of output rows, etc */
6143}

References Assert(), planner_rt_fetch, RelOptInfo::relid, root, RTE_NAMEDTUPLESTORE, RangeTblEntry::rtekind, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_namedtuplestore_pathlist().

β—† set_pathtarget_cost_width()

PathTarget * set_pathtarget_cost_width ( PlannerInfo root,
PathTarget target 
)

Definition at line 6376 of file costsize.c.

6377{
6378 int64 tuple_width = 0;
6379 ListCell *lc;
6380
6381 /* Vars are assumed to have cost zero, but other exprs do not */
6382 target->cost.startup = 0;
6383 target->cost.per_tuple = 0;
6384
6385 foreach(lc, target->exprs)
6386 {
6387 Node *node = (Node *) lfirst(lc);
6388
6389 tuple_width += get_expr_width(root, node);
6390
6391 /* For non-Vars, account for evaluation cost */
6392 if (!IsA(node, Var))
6393 {
6394 QualCost cost;
6395
6396 cost_qual_eval_node(&cost, node, root);
6397 target->cost.startup += cost.startup;
6398 target->cost.per_tuple += cost.per_tuple;
6399 }
6400 }
6401
6402 target->width = clamp_width_est(tuple_width);
6403
6404 return target;
6405}
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:242
List * exprs
Definition: pathnodes.h:1779
QualCost cost
Definition: pathnodes.h:1785

References clamp_width_est(), PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, get_expr_width(), IsA, lfirst, QualCost::per_tuple, root, QualCost::startup, and PathTarget::width.

Referenced by create_rel_agg_info(), make_group_input_target(), make_partial_grouping_target(), make_sort_input_target(), make_window_input_target(), and split_pathtarget_at_srfs().

β—† set_rel_width()

static void set_rel_width ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 6219 of file costsize.c.

6220{
6221 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
6222 int64 tuple_width = 0;
6223 bool have_wholerow_var = false;
6224 ListCell *lc;
6225
6226 /* Vars are assumed to have cost zero, but other exprs do not */
6227 rel->reltarget->cost.startup = 0;
6228 rel->reltarget->cost.per_tuple = 0;
6229
6230 foreach(lc, rel->reltarget->exprs)
6231 {
6232 Node *node = (Node *) lfirst(lc);
6233
6234 /*
6235 * Ordinarily, a Var in a rel's targetlist must belong to that rel;
6236 * but there are corner cases involving LATERAL references where that
6237 * isn't so. If the Var has the wrong varno, fall through to the
6238 * generic case (it doesn't seem worth the trouble to be any smarter).
6239 */
6240 if (IsA(node, Var) &&
6241 ((Var *) node)->varno == rel->relid)
6242 {
6243 Var *var = (Var *) node;
6244 int ndx;
6245 int32 item_width;
6246
6247 Assert(var->varattno >= rel->min_attr);
6248 Assert(var->varattno <= rel->max_attr);
6249
6250 ndx = var->varattno - rel->min_attr;
6251
6252 /*
6253 * If it's a whole-row Var, we'll deal with it below after we have
6254 * already cached as many attr widths as possible.
6255 */
6256 if (var->varattno == 0)
6257 {
6258 have_wholerow_var = true;
6259 continue;
6260 }
6261
6262 /*
6263 * The width may have been cached already (especially if it's a
6264 * subquery), so don't duplicate effort.
6265 */
6266 if (rel->attr_widths[ndx] > 0)
6267 {
6268 tuple_width += rel->attr_widths[ndx];
6269 continue;
6270 }
6271
6272 /* Try to get column width from statistics */
6273 if (reloid != InvalidOid && var->varattno > 0)
6274 {
6275 item_width = get_attavgwidth(reloid, var->varattno);
6276 if (item_width > 0)
6277 {
6278 rel->attr_widths[ndx] = item_width;
6279 tuple_width += item_width;
6280 continue;
6281 }
6282 }
6283
6284 /*
6285 * Not a plain relation, or can't find statistics for it. Estimate
6286 * using just the type info.
6287 */
6288 item_width = get_typavgwidth(var->vartype, var->vartypmod);
6289 Assert(item_width > 0);
6290 rel->attr_widths[ndx] = item_width;
6291 tuple_width += item_width;
6292 }
6293 else if (IsA(node, PlaceHolderVar))
6294 {
6295 /*
6296 * We will need to evaluate the PHV's contained expression while
6297 * scanning this rel, so be sure to include it in reltarget->cost.
6298 */
6299 PlaceHolderVar *phv = (PlaceHolderVar *) node;
6301 QualCost cost;
6302
6303 tuple_width += phinfo->ph_width;
6304 cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
6305 rel->reltarget->cost.startup += cost.startup;
6306 rel->reltarget->cost.per_tuple += cost.per_tuple;
6307 }
6308 else
6309 {
6310 /*
6311 * We could be looking at an expression pulled up from a subquery,
6312 * or a ROW() representing a whole-row child Var, etc. Do what we
6313 * can using the expression type information.
6314 */
6315 int32 item_width;
6316 QualCost cost;
6317
6318 item_width = get_typavgwidth(exprType(node), exprTypmod(node));
6319 Assert(item_width > 0);
6320 tuple_width += item_width;
6321 /* Not entirely clear if we need to account for cost, but do so */
6322 cost_qual_eval_node(&cost, node, root);
6323 rel->reltarget->cost.startup += cost.startup;
6324 rel->reltarget->cost.per_tuple += cost.per_tuple;
6325 }
6326 }
6327
6328 /*
6329 * If we have a whole-row reference, estimate its width as the sum of
6330 * per-column widths plus heap tuple header overhead.
6331 */
6332 if (have_wholerow_var)
6333 {
6334 int64 wholerow_width = MAXALIGN(SizeofHeapTupleHeader);
6335
6336 if (reloid != InvalidOid)
6337 {
6338 /* Real relation, so estimate true tuple width */
6339 wholerow_width += get_relation_data_width(reloid,
6340 rel->attr_widths - rel->min_attr);
6341 }
6342 else
6343 {
6344 /* Do what we can with info for a phony rel */
6345 AttrNumber i;
6346
6347 for (i = 1; i <= rel->max_attr; i++)
6348 wholerow_width += rel->attr_widths[i - rel->min_attr];
6349 }
6350
6351 rel->attr_widths[0 - rel->min_attr] = clamp_width_est(wholerow_width);
6352
6353 /*
6354 * Include the whole-row Var as part of the output tuple. Yes, that
6355 * really is what happens at runtime.
6356 */
6357 tuple_width += wholerow_width;
6358 }
6359
6360 rel->reltarget->width = clamp_width_est(tuple_width);
6361}
int16 AttrNumber
Definition: attnum.h:21
int32 get_attavgwidth(Oid relid, AttrNumber attnum)
Definition: lsyscache.c:3325
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv)
Definition: placeholder.c:83
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1328
#define InvalidOid
Definition: postgres_ext.h:37
struct PathTarget * reltarget
Definition: pathnodes.h:949

References Assert(), clamp_width_est(), PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, exprType(), exprTypmod(), find_placeholder_info(), get_attavgwidth(), get_relation_data_width(), get_typavgwidth(), i, InvalidOid, IsA, lfirst, RelOptInfo::max_attr, MAXALIGN, RelOptInfo::min_attr, QualCost::per_tuple, PlaceHolderInfo::ph_width, planner_rt_fetch, RelOptInfo::relid, RelOptInfo::reltarget, root, SizeofHeapTupleHeader, QualCost::startup, Var::varattno, and PathTarget::width.

Referenced by set_baserel_size_estimates(), and set_foreign_size_estimates().

β—† set_result_size_estimates()

void set_result_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6155 of file costsize.c.

6156{
6157 /* Should only be applied to RTE_RESULT base relations */
6158 Assert(rel->relid > 0);
6159 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6160
6161 /* RTE_RESULT always generates a single row, natively */
6162 rel->tuples = 1;
6163
6164 /* Now estimate number of output rows, etc */
6166}

References Assert(), planner_rt_fetch, RelOptInfo::relid, root, RTE_RESULT, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_result_pathlist().

β—† set_subquery_size_estimates()

void set_subquery_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5912 of file costsize.c.

5913{
5914 PlannerInfo *subroot = rel->subroot;
5915 RelOptInfo *sub_final_rel;
5916 ListCell *lc;
5917
5918 /* Should only be applied to base relations that are subqueries */
5919 Assert(rel->relid > 0);
5920 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5921
5922 /*
5923 * Copy raw number of output rows from subquery. All of its paths should
5924 * have the same output rowcount, so just look at cheapest-total.
5925 */
5926 sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5927 rel->tuples = sub_final_rel->cheapest_total_path->rows;
5928
5929 /*
5930 * Compute per-output-column width estimates by examining the subquery's
5931 * targetlist. For any output that is a plain Var, get the width estimate
5932 * that was made while planning the subquery. Otherwise, we leave it to
5933 * set_rel_width to fill in a datatype-based default estimate.
5934 */
5935 foreach(lc, subroot->parse->targetList)
5936 {
5938 Node *texpr = (Node *) te->expr;
5939 int32 item_width = 0;
5940
5941 /* junk columns aren't visible to upper query */
5942 if (te->resjunk)
5943 continue;
5944
5945 /*
5946 * The subquery could be an expansion of a view that's had columns
5947 * added to it since the current query was parsed, so that there are
5948 * non-junk tlist columns in it that don't correspond to any column
5949 * visible at our query level. Ignore such columns.
5950 */
5951 if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5952 continue;
5953
5954 /*
5955 * XXX This currently doesn't work for subqueries containing set
5956 * operations, because the Vars in their tlists are bogus references
5957 * to the first leaf subquery, which wouldn't give the right answer
5958 * even if we could still get to its PlannerInfo.
5959 *
5960 * Also, the subquery could be an appendrel for which all branches are
5961 * known empty due to constraint exclusion, in which case
5962 * set_append_rel_pathlist will have left the attr_widths set to zero.
5963 *
5964 * In either case, we just leave the width estimate zero until
5965 * set_rel_width fixes it.
5966 */
5967 if (IsA(texpr, Var) &&
5968 subroot->parse->setOperations == NULL)
5969 {
5970 Var *var = (Var *) texpr;
5971 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5972
5973 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5974 }
5975 rel->attr_widths[te->resno - rel->min_attr] = item_width;
5976 }
5977
5978 /* Now estimate number of output rows, etc */
5980}
@ UPPERREL_FINAL
Definition: pathnodes.h:79
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1581
Query * parse
Definition: pathnodes.h:227
Node * setOperations
Definition: parsenodes.h:236
List * targetList
Definition: parsenodes.h:198
struct Path * cheapest_total_path
Definition: pathnodes.h:958
PlannerInfo * subroot
Definition: pathnodes.h:1004
Expr * expr
Definition: primnodes.h:2239
AttrNumber resno
Definition: primnodes.h:2241

References Assert(), RelOptInfo::cheapest_total_path, TargetEntry::expr, fetch_upper_rel(), find_base_rel(), if(), IsA, lfirst_node, RelOptInfo::max_attr, RelOptInfo::min_attr, PlannerInfo::parse, planner_rt_fetch, RelOptInfo::relid, TargetEntry::resno, root, Path::rows, RTE_SUBQUERY, set_baserel_size_estimates(), Query::setOperations, RelOptInfo::subroot, Query::targetList, RelOptInfo::tuples, UPPERREL_FINAL, Var::varattno, and Var::varno.

Referenced by build_setop_child_paths(), and set_subquery_pathlist().

β—† set_tablefunc_size_estimates()

void set_tablefunc_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6030 of file costsize.c.

6031{
6032 /* Should only be applied to base relations that are functions */
6033 Assert(rel->relid > 0);
6034 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
6035
6036 rel->tuples = 100;
6037
6038 /* Now estimate number of output rows, etc */
6040}

References Assert(), planner_rt_fetch, RelOptInfo::relid, root, RTE_TABLEFUNC, set_baserel_size_estimates(), and RelOptInfo::tuples.

Referenced by set_rel_size().

β—† set_values_size_estimates()

void set_values_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6052 of file costsize.c.

6053{
6054 RangeTblEntry *rte;
6055
6056 /* Should only be applied to base relations that are values lists */
6057 Assert(rel->relid > 0);
6058 rte = planner_rt_fetch(rel->relid, root);
6059 Assert(rte->rtekind == RTE_VALUES);
6060
6061 /*
6062 * Estimate number of rows the values list will return. We know this
6063 * precisely based on the list length (well, barring set-returning
6064 * functions in list items, but that's a refinement not catered for
6065 * anywhere else either).
6066 */
6067 rel->tuples = list_length(rte->values_lists);
6068
6069 /* Now estimate number of output rows, etc */
6071}
List * values_lists
Definition: parsenodes.h:1221

References Assert(), list_length(), planner_rt_fetch, RelOptInfo::relid, root, RTE_VALUES, RangeTblEntry::rtekind, set_baserel_size_estimates(), RelOptInfo::tuples, and RangeTblEntry::values_lists.

Referenced by set_rel_size().

Variable Documentation

β—† cpu_index_tuple_cost

double cpu_index_tuple_cost = DEFAULT_CPU_INDEX_TUPLE_COST

Definition at line 133 of file costsize.c.

Referenced by genericcostestimate(), and gincostestimate().

β—† cpu_operator_cost

β—† cpu_tuple_cost

β—† disable_cost

Cost disable_cost = 1.0e10

Definition at line 141 of file costsize.c.

Referenced by final_cost_hashjoin().

β—† effective_cache_size

int effective_cache_size = DEFAULT_EFFECTIVE_CACHE_SIZE

Definition at line 139 of file costsize.c.

Referenced by gistBuildCallback(), gistInitBuffering(), and index_pages_fetched().

β—† enable_async_append

bool enable_async_append = true

Definition at line 165 of file costsize.c.

Referenced by create_append_plan().

β—† enable_bitmapscan

bool enable_bitmapscan = true

Definition at line 148 of file costsize.c.

Referenced by cost_bitmap_heap_scan().

β—† enable_gathermerge

bool enable_gathermerge = true

Definition at line 158 of file costsize.c.

Referenced by cost_gather_merge().

β—† enable_hashagg

β—† enable_hashjoin

bool enable_hashjoin = true

Definition at line 157 of file costsize.c.

Referenced by add_paths_to_joinrel(), and initial_cost_hashjoin().

β—† enable_incremental_sort

β—† enable_indexonlyscan

bool enable_indexonlyscan = true

Definition at line 147 of file costsize.c.

Referenced by check_index_only().

β—† enable_indexscan

bool enable_indexscan = true

Definition at line 146 of file costsize.c.

Referenced by cost_index(), and plan_cluster_use_sort().

β—† enable_material

bool enable_material = true

β—† enable_memoize

bool enable_memoize = true

Definition at line 155 of file costsize.c.

Referenced by create_memoize_path(), and get_memoize_path().

β—† enable_mergejoin

bool enable_mergejoin = true

Definition at line 156 of file costsize.c.

Referenced by add_paths_to_joinrel(), and initial_cost_mergejoin().

β—† enable_nestloop

bool enable_nestloop = true

Definition at line 153 of file costsize.c.

Referenced by initial_cost_nestloop().

β—† enable_parallel_append

bool enable_parallel_append = true

Definition at line 161 of file costsize.c.

Referenced by add_paths_to_append_rel(), and generate_union_paths().

β—† enable_parallel_hash

bool enable_parallel_hash = true

Definition at line 162 of file costsize.c.

Referenced by hash_inner_and_outer().

β—† enable_partition_pruning

bool enable_partition_pruning = true

β—† enable_partitionwise_aggregate

bool enable_partitionwise_aggregate = false

Definition at line 160 of file costsize.c.

Referenced by create_grouping_paths().

β—† enable_partitionwise_join

bool enable_partitionwise_join = false

Definition at line 159 of file costsize.c.

Referenced by build_joinrel_partition_info(), and set_append_rel_size().

β—† enable_presorted_aggregate

bool enable_presorted_aggregate = true

Definition at line 164 of file costsize.c.

Referenced by adjust_group_pathkeys_for_groupagg().

β—† enable_seqscan

bool enable_seqscan = true

Definition at line 145 of file costsize.c.

Referenced by cost_seqscan().

β—† enable_sort

bool enable_sort = true

Definition at line 150 of file costsize.c.

Referenced by cost_sort(), and make_sort().

β—† enable_tidscan

bool enable_tidscan = true

Definition at line 149 of file costsize.c.

Referenced by cost_tidrangescan(), cost_tidscan(), and create_tidscan_paths().

β—† max_parallel_workers_per_gather

int max_parallel_workers_per_gather = 2

β—† parallel_setup_cost

double parallel_setup_cost = DEFAULT_PARALLEL_SETUP_COST

Definition at line 136 of file costsize.c.

Referenced by cost_gather(), cost_gather_merge(), and standard_planner().

β—† parallel_tuple_cost

double parallel_tuple_cost = DEFAULT_PARALLEL_TUPLE_COST

Definition at line 135 of file costsize.c.

Referenced by cost_gather(), cost_gather_merge(), and standard_planner().

β—† random_page_cost

double random_page_cost = DEFAULT_RANDOM_PAGE_COST

β—† recursive_worktable_factor

double recursive_worktable_factor = DEFAULT_RECURSIVE_WORKTABLE_FACTOR

Definition at line 137 of file costsize.c.

Referenced by set_cte_size_estimates().

β—† seq_page_cost