PostgreSQL Source Code git master
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 2164 of file costsize.c.

2165{
2166 Cost *costarr;
2167 int arrlen;
2168 ListCell *l;
2169 ListCell *cell;
2170 int path_index;
2171 int min_index;
2172 int max_index;
2173
2174 if (numpaths == 0)
2175 return 0;
2176
2177 /*
2178 * Array length is number of workers or number of relevant paths,
2179 * whichever is less.
2180 */
2181 arrlen = Min(parallel_workers, numpaths);
2182 costarr = palloc_array(Cost, arrlen);
2183
2184 /* The first few paths will each be claimed by a different worker. */
2185 path_index = 0;
2186 foreach(cell, subpaths)
2187 {
2188 Path *subpath = (Path *) lfirst(cell);
2189
2190 if (path_index == arrlen)
2191 break;
2192 costarr[path_index++] = subpath->total_cost;
2193 }
2194
2195 /*
2196 * Since subpaths are sorted by decreasing cost, the last one will have
2197 * the minimum cost.
2198 */
2199 min_index = arrlen - 1;
2200
2201 /*
2202 * For each of the remaining subpaths, add its cost to the array element
2203 * with minimum cost.
2204 */
2205 for_each_cell(l, subpaths, cell)
2206 {
2207 Path *subpath = (Path *) lfirst(l);
2208
2209 /* Consider only the non-partial paths */
2210 if (path_index++ == numpaths)
2211 break;
2212
2213 costarr[min_index] += subpath->total_cost;
2214
2215 /* Update the new min cost array index */
2216 min_index = 0;
2217 for (int i = 0; i < arrlen; i++)
2218 {
2219 if (costarr[i] < costarr[min_index])
2220 min_index = i;
2221 }
2222 }
2223
2224 /* Return the highest cost from the array */
2225 max_index = 0;
2226 for (int i = 0; i < arrlen; i++)
2227 {
2228 if (costarr[i] > costarr[max_index])
2229 max_index = i;
2230 }
2231
2232 return costarr[max_index];
2233}
#define Min(x, y)
Definition: c.h:1003
#define palloc_array(type, count)
Definition: fe_memutils.h:76
int i
Definition: isn.c:77
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:311
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_array, and subpath().

Referenced by cost_append().

◆ approx_tuple_count()

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

Definition at line 5330 of file costsize.c.

5331{
5332 double tuples;
5333 double outer_tuples = path->outerjoinpath->rows;
5334 double inner_tuples = path->innerjoinpath->rows;
5335 SpecialJoinInfo sjinfo;
5336 Selectivity selec = 1.0;
5337 ListCell *l;
5338
5339 /*
5340 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5341 */
5342 init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
5343 path->innerjoinpath->parent->relids);
5344
5345 /* Get the approximate selectivity */
5346 foreach(l, quals)
5347 {
5348 Node *qual = (Node *) lfirst(l);
5349
5350 /* Note that clause_selectivity will be able to cache its result */
5351 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5352 }
5353
5354 /* Apply it to the input relation sizes */
5355 tuples = selec * outer_tuples * inner_tuples;
5356
5357 return clamp_row_est(tuples);
5358}
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:2296
Path * innerjoinpath
Definition: pathnodes.h:2297
Definition: nodes.h:135
Cardinality rows
Definition: pathnodes.h:1907

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 4105 of file costsize.c.

4106{
4107 MergeScanSelCache *cache;
4108 ListCell *lc;
4109 Selectivity leftstartsel,
4110 leftendsel,
4111 rightstartsel,
4112 rightendsel;
4113 MemoryContext oldcontext;
4114
4115 /* Do we have this result already? */
4116 foreach(lc, rinfo->scansel_cache)
4117 {
4118 cache = (MergeScanSelCache *) lfirst(lc);
4119 if (cache->opfamily == pathkey->pk_opfamily &&
4120 cache->collation == pathkey->pk_eclass->ec_collation &&
4121 cache->cmptype == pathkey->pk_cmptype &&
4122 cache->nulls_first == pathkey->pk_nulls_first)
4123 return cache;
4124 }
4125
4126 /* Nope, do the computation */
4128 (Node *) rinfo->clause,
4129 pathkey->pk_opfamily,
4130 pathkey->pk_cmptype,
4131 pathkey->pk_nulls_first,
4132 &leftstartsel,
4133 &leftendsel,
4134 &rightstartsel,
4135 &rightendsel);
4136
4137 /* Cache the result in suitably long-lived workspace */
4138 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4139
4141 cache->opfamily = pathkey->pk_opfamily;
4142 cache->collation = pathkey->pk_eclass->ec_collation;
4143 cache->cmptype = pathkey->pk_cmptype;
4144 cache->nulls_first = pathkey->pk_nulls_first;
4145 cache->leftstartsel = leftstartsel;
4146 cache->leftendsel = leftendsel;
4147 cache->rightstartsel = rightstartsel;
4148 cache->rightendsel = rightendsel;
4149
4150 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4151
4152 MemoryContextSwitchTo(oldcontext);
4153
4154 return cache;
4155}
#define palloc_object(type)
Definition: fe_memutils.h:74
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:3285
Selectivity leftstartsel
Definition: pathnodes.h:2968
Selectivity leftendsel
Definition: pathnodes.h:2969
CompareType cmptype
Definition: pathnodes.h:2965
Selectivity rightendsel
Definition: pathnodes.h:2971
Selectivity rightstartsel
Definition: pathnodes.h:2970
CompareType pk_cmptype
Definition: pathnodes.h:1717
bool pk_nulls_first
Definition: pathnodes.h:1718
Oid pk_opfamily
Definition: pathnodes.h:1716
Expr * clause
Definition: pathnodes.h:2792

References RestrictInfo::clause, MergeScanSelCache::cmptype, MergeScanSelCache::collation, lappend(), MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, lfirst, MemoryContextSwitchTo(), mergejoinscansel(), MergeScanSelCache::nulls_first, MergeScanSelCache::opfamily, palloc_object, 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 5527 of file costsize.c.

5535{
5536 JoinType jointype = sjinfo->jointype;
5537 Selectivity fkselec;
5538 Selectivity jselec;
5539 Selectivity pselec;
5540 double nrows;
5541
5542 /*
5543 * Compute joinclause selectivity. Note that we are only considering
5544 * clauses that become restriction clauses at this join level; we are not
5545 * double-counting them because they were not considered in estimating the
5546 * sizes of the component rels.
5547 *
5548 * First, see whether any of the joinclauses can be matched to known FK
5549 * constraints. If so, drop those clauses from the restrictlist, and
5550 * instead estimate their selectivity using FK semantics. (We do this
5551 * without regard to whether said clauses are local or "pushed down".
5552 * Probably, an FK-matching clause could never be seen as pushed down at
5553 * an outer join, since it would be strict and hence would be grounds for
5554 * join strength reduction.) fkselec gets the net selectivity for
5555 * FK-matching clauses, or 1.0 if there are none.
5556 */
5558 outer_rel->relids,
5559 inner_rel->relids,
5560 sjinfo,
5561 &restrictlist);
5562
5563 /*
5564 * For an outer join, we have to distinguish the selectivity of the join's
5565 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5566 * down". For inner joins we just count them all as joinclauses.
5567 */
5568 if (IS_OUTER_JOIN(jointype))
5569 {
5570 List *joinquals = NIL;
5571 List *pushedquals = NIL;
5572 ListCell *l;
5573
5574 /* Grovel through the clauses to separate into two lists */
5575 foreach(l, restrictlist)
5576 {
5578
5579 if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5580 pushedquals = lappend(pushedquals, rinfo);
5581 else
5582 joinquals = lappend(joinquals, rinfo);
5583 }
5584
5585 /* Get the separate selectivities */
5587 joinquals,
5588 0,
5589 jointype,
5590 sjinfo);
5592 pushedquals,
5593 0,
5594 jointype,
5595 sjinfo);
5596
5597 /* Avoid leaking a lot of ListCells */
5598 list_free(joinquals);
5599 list_free(pushedquals);
5600 }
5601 else
5602 {
5604 restrictlist,
5605 0,
5606 jointype,
5607 sjinfo);
5608 pselec = 0.0; /* not used, keep compiler quiet */
5609 }
5610
5611 /*
5612 * Basically, we multiply size of Cartesian product by selectivity.
5613 *
5614 * If we are doing an outer join, take that into account: the joinqual
5615 * selectivity has to be clamped using the knowledge that the output must
5616 * be at least as large as the non-nullable input. However, any
5617 * pushed-down quals are applied after the outer join, so their
5618 * selectivity applies fully.
5619 *
5620 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5621 * of LHS rows that have matches, and we apply that straightforwardly.
5622 */
5623 switch (jointype)
5624 {
5625 case JOIN_INNER:
5626 nrows = outer_rows * inner_rows * fkselec * jselec;
5627 /* pselec not used */
5628 break;
5629 case JOIN_LEFT:
5630 nrows = outer_rows * inner_rows * fkselec * jselec;
5631 if (nrows < outer_rows)
5632 nrows = outer_rows;
5633 nrows *= pselec;
5634 break;
5635 case JOIN_FULL:
5636 nrows = outer_rows * inner_rows * fkselec * jselec;
5637 if (nrows < outer_rows)
5638 nrows = outer_rows;
5639 if (nrows < inner_rows)
5640 nrows = inner_rows;
5641 nrows *= pselec;
5642 break;
5643 case JOIN_SEMI:
5644 nrows = outer_rows * fkselec * jselec;
5645 /* pselec not used */
5646 break;
5647 case JOIN_ANTI:
5648 nrows = outer_rows * (1.0 - fkselec * jselec);
5649 nrows *= pselec;
5650 break;
5651 default:
5652 /* other values not expected here */
5653 elog(ERROR, "unrecognized join type: %d", (int) jointype);
5654 nrows = 0; /* keep compiler quiet */
5655 break;
5656 }
5657
5658 return clamp_row_est(nrows);
5659}
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:5677
#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:2949
#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:3121

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(), cost_tidrangescan(), 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:548
#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 6540 of file costsize.c.

6543{
6544 Cost indexTotalCost;
6545 Selectivity indexSelectivity;
6546 double T;
6547 double pages_fetched;
6548 double tuples_fetched;
6549 double heap_pages;
6550 double maxentries;
6551
6552 /*
6553 * Fetch total cost of obtaining the bitmap, as well as its total
6554 * selectivity.
6555 */
6556 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6557
6558 /*
6559 * Estimate number of main-table pages fetched.
6560 */
6561 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6562
6563 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6564
6565 /*
6566 * For a single scan, the number of heap pages that need to be fetched is
6567 * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6568 * re-reads needed).
6569 */
6570 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6571
6572 /*
6573 * Calculate the number of pages fetched from the heap. Then based on
6574 * current work_mem estimate get the estimated maxentries in the bitmap.
6575 * (Note that we always do this calculation based on the number of pages
6576 * that would be fetched in a single iteration, even if loop_count > 1.
6577 * That's correct, because only that number of entries will be stored in
6578 * the bitmap at one time.)
6579 */
6580 heap_pages = Min(pages_fetched, baserel->pages);
6581 maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
6582
6583 if (loop_count > 1)
6584 {
6585 /*
6586 * For repeated bitmap scans, scale up the number of tuples fetched in
6587 * the Mackert and Lohman formula by the number of scans, so that we
6588 * estimate the number of pages fetched by all the scans. Then
6589 * pro-rate for one scan.
6590 */
6591 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6592 baserel->pages,
6593 get_indexpath_pages(bitmapqual),
6594 root);
6595 pages_fetched /= loop_count;
6596 }
6597
6598 if (pages_fetched >= T)
6599 pages_fetched = T;
6600 else
6601 pages_fetched = ceil(pages_fetched);
6602
6603 if (maxentries < heap_pages)
6604 {
6605 double exact_pages;
6606 double lossy_pages;
6607
6608 /*
6609 * Crude approximation of the number of lossy pages. Because of the
6610 * way tbm_lossify() is coded, the number of lossy pages increases
6611 * very sharply as soon as we run short of memory; this formula has
6612 * that property and seems to perform adequately in testing, but it's
6613 * possible we could do better somehow.
6614 */
6615 lossy_pages = Max(0, heap_pages - maxentries / 2);
6616 exact_pages = heap_pages - lossy_pages;
6617
6618 /*
6619 * If there are lossy pages then recompute the number of tuples
6620 * processed by the bitmap heap node. We assume here that the chance
6621 * of a given tuple coming from an exact page is the same as the
6622 * chance that a given page is exact. This might not be true, but
6623 * it's not clear how we can do any better.
6624 */
6625 if (lossy_pages > 0)
6626 tuples_fetched =
6627 clamp_row_est(indexSelectivity *
6628 (exact_pages / heap_pages) * baserel->tuples +
6629 (lossy_pages / heap_pages) * baserel->tuples);
6630 }
6631
6632 if (cost_p)
6633 *cost_p = indexTotalCost;
6634 if (tuples_p)
6635 *tuples_p = tuples_fetched;
6636
6637 return pages_fetched;
6638}
#define Max(x, y)
Definition: c.h:997
size_t Size
Definition: c.h:625
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:1542

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 6651 of file costsize.c.

6652{
6653 Assert(path->parallel_workers > 0);
6654
6655 return clamp_row_est(path->rows * get_parallel_divisor(path));
6656}
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6500
int parallel_workers
Definition: pathnodes.h:1904

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 5140 of file costsize.c.

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

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 2704 of file costsize.c.

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

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

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:2046
List * bitmapquals
Definition: pathnodes.h:2045

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:5098
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition: costsize.c:6540
bool enable_bitmapscan
Definition: costsize.c:148
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
@ RTE_RELATION
Definition: parsenodes.h:1070
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:1827
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:2059
List * bitmapquals
Definition: pathnodes.h:2058

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 1698 of file costsize.c.

1700{
1701 Cost startup_cost = 0;
1702 Cost run_cost = 0;
1703 QualCost qpqual_cost;
1704 Cost cpu_per_tuple;
1705
1706 /* Should only be applied to base relations that are CTEs */
1707 Assert(baserel->relid > 0);
1708 Assert(baserel->rtekind == RTE_CTE);
1709
1710 /* Mark the path with the correct row estimate */
1711 if (param_info)
1712 path->rows = param_info->ppi_rows;
1713 else
1714 path->rows = baserel->rows;
1715
1716 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1717 cpu_per_tuple = cpu_tuple_cost;
1718
1719 /* Add scanning CPU costs */
1720 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1721
1722 startup_cost += qpqual_cost.startup;
1723 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1724 run_cost += cpu_per_tuple * baserel->tuples;
1725
1726 /* tlist eval costs are paid per output row, not per tuple scanned */
1727 startup_cost += path->pathtarget->cost.startup;
1728 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1729
1730 path->disabled_nodes = 0;
1731 path->startup_cost = startup_cost;
1732 path->total_cost = startup_cost + run_cost;
1733}
@ RTE_CTE
Definition: parsenodes.h:1076

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 1528 of file costsize.c.

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

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:2264

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 3217 of file costsize.c.

3223{
3224 double output_tuples;
3225 Cost startup_cost;
3226 Cost total_cost;
3227
3228 output_tuples = numGroups;
3229 startup_cost = input_startup_cost;
3230 total_cost = input_total_cost;
3231
3232 /*
3233 * Charge one cpu_operator_cost per comparison per input tuple. We assume
3234 * all columns get compared at most of the tuples.
3235 */
3236 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3237
3238 /*
3239 * If there are quals (HAVING quals), account for their cost and
3240 * selectivity.
3241 */
3242 if (quals)
3243 {
3244 QualCost qual_cost;
3245
3246 cost_qual_eval(&qual_cost, quals, root);
3247 startup_cost += qual_cost.startup;
3248 total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3249
3250 output_tuples = clamp_row_est(output_tuples *
3252 quals,
3253 0,
3254 JOIN_INNER,
3255 NULL));
3256 }
3257
3258 path->rows = output_tuples;
3259 path->disabled_nodes = input_disabled_nodes;
3260 path->startup_cost = startup_cost;
3261 path->total_cost = total_cost;
3262}

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 1990 of file costsize.c.

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

2503{
2504 Cost startup_cost = input_startup_cost;
2505 Cost run_cost = input_total_cost - input_startup_cost;
2506 double nbytes = relation_byte_size(tuples, width);
2507 double work_mem_bytes = work_mem * (Size) 1024;
2508
2509 path->rows = tuples;
2510
2511 /*
2512 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2513 * reflect bookkeeping overhead. (This rate must be more than what
2514 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2515 * if it is exactly the same then there will be a cost tie between
2516 * nestloop with A outer, materialized B inner and nestloop with B outer,
2517 * materialized A inner. The extra cost ensures we'll prefer
2518 * materializing the smaller rel.) Note that this is normally a good deal
2519 * less than cpu_tuple_cost; which is OK because a Material plan node
2520 * doesn't do qual-checking or projection, so it's got less overhead than
2521 * most plan nodes.
2522 */
2523 run_cost += 2 * cpu_operator_cost * tuples;
2524
2525 /*
2526 * If we will spill to disk, charge at the rate of seq_page_cost per page.
2527 * This cost is assumed to be evenly spread through the plan run phase,
2528 * which isn't exactly accurate but our cost model doesn't allow for
2529 * nonuniform costs within the run phase.
2530 */
2531 if (nbytes > work_mem_bytes)
2532 {
2533 double npages = ceil(nbytes / BLCKSZ);
2534
2535 run_cost += seq_page_cost * npages;
2536 }
2537
2538 path->disabled_nodes = input_disabled_nodes + (enable_material ? 0 : 1);
2539 path->startup_cost = startup_cost;
2540 path->total_cost = startup_cost + run_cost;
2541}
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 2557 of file costsize.c.

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

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 2448 of file costsize.c.

2453{
2454 Cost startup_cost = 0;
2455 Cost run_cost = 0;
2456 Cost comparison_cost;
2457 double N;
2458 double logN;
2459
2460 /*
2461 * Avoid log(0)...
2462 */
2463 N = (n_streams < 2) ? 2.0 : (double) n_streams;
2464 logN = LOG2(N);
2465
2466 /* Assumed cost per tuple comparison */
2467 comparison_cost = 2.0 * cpu_operator_cost;
2468
2469 /* Heap creation cost */
2470 startup_cost += comparison_cost * N * logN;
2471
2472 /* Per-tuple heap maintenance cost */
2473 run_cost += tuples * comparison_cost * logN;
2474
2475 /*
2476 * Although MergeAppend does not do any selection or projection, it's not
2477 * free; add a small per-tuple overhead.
2478 */
2479 run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2480
2481 path->disabled_nodes = input_disabled_nodes;
2482 path->startup_cost = startup_cost + input_startup_cost;
2483 path->total_cost = startup_cost + run_cost + input_total_cost;
2484}

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 1740 of file costsize.c.

1742{
1743 Cost startup_cost = 0;
1744 Cost run_cost = 0;
1745 QualCost qpqual_cost;
1746 Cost cpu_per_tuple;
1747
1748 /* Should only be applied to base relations that are Tuplestores */
1749 Assert(baserel->relid > 0);
1750 Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1751
1752 /* Mark the path with the correct row estimate */
1753 if (param_info)
1754 path->rows = param_info->ppi_rows;
1755 else
1756 path->rows = baserel->rows;
1757
1758 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1759 cpu_per_tuple = cpu_tuple_cost;
1760
1761 /* Add scanning CPU costs */
1762 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1763
1764 startup_cost += qpqual_cost.startup;
1765 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1766 run_cost += cpu_per_tuple * baserel->tuples;
1767
1768 path->disabled_nodes = 0;
1769 path->startup_cost = startup_cost;
1770 path->total_cost = startup_cost + run_cost;
1771}
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1077

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 4782 of file costsize.c.

4783{
4784 cost_qual_eval_context context;
4785 ListCell *l;
4786
4787 context.root = root;
4788 context.total.startup = 0;
4789 context.total.per_tuple = 0;
4790
4791 /* We don't charge any cost for the implicit ANDing at top level ... */
4792
4793 foreach(l, quals)
4794 {
4795 Node *qual = (Node *) lfirst(l);
4796
4797 cost_qual_eval_walker(qual, &context);
4798 }
4799
4800 *cost = context.total;
4801}
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4822
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 4822 of file costsize.c.

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

1817{
1818 Cost startup_cost;
1819 Cost total_cost;
1820 double total_rows;
1821
1822 /* We probably have decent estimates for the non-recursive term */
1823 startup_cost = nrterm->startup_cost;
1824 total_cost = nrterm->total_cost;
1825 total_rows = nrterm->rows;
1826
1827 /*
1828 * We arbitrarily assume that about 10 recursive iterations will be
1829 * needed, and that we've managed to get a good fix on the cost and output
1830 * size of each one of them. These are mighty shaky assumptions but it's
1831 * hard to see how to do better.
1832 */
1833 total_cost += 10 * rterm->total_cost;
1834 total_rows += 10 * rterm->rows;
1835
1836 /*
1837 * Also charge cpu_tuple_cost per row to account for the costs of
1838 * manipulating the tuplestores. (We don't worry about possible
1839 * spill-to-disk costs.)
1840 */
1841 total_cost += cpu_tuple_cost * total_rows;
1842
1843 runion->disabled_nodes = nrterm->disabled_nodes + rterm->disabled_nodes;
1844 runion->startup_cost = startup_cost;
1845 runion->total_cost = total_cost;
1846 runion->rows = total_rows;
1847 runion->pathtarget->width = Max(nrterm->pathtarget->width,
1848 rterm->pathtarget->width);
1849}

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 4667 of file costsize.c.

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

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 1778 of file costsize.c.

1780{
1781 Cost startup_cost = 0;
1782 Cost run_cost = 0;
1783 QualCost qpqual_cost;
1784 Cost cpu_per_tuple;
1785
1786 /* Should only be applied to RTE_RESULT base relations */
1787 Assert(baserel->relid > 0);
1788 Assert(baserel->rtekind == RTE_RESULT);
1789
1790 /* Mark the path with the correct row estimate */
1791 if (param_info)
1792 path->rows = param_info->ppi_rows;
1793 else
1794 path->rows = baserel->rows;
1795
1796 /* We charge qual cost plus cpu_tuple_cost */
1797 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1798
1799 startup_cost += qpqual_cost.startup;
1800 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1801 run_cost += cpu_per_tuple * baserel->tuples;
1802
1803 path->disabled_nodes = 0;
1804 path->startup_cost = startup_cost;
1805 path->total_cost = startup_cost + run_cost;
1806}
@ RTE_RESULT
Definition: parsenodes.h:1078

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:1156
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 2134 of file costsize.c.

2140{
2141 Cost startup_cost;
2142 Cost run_cost;
2143
2144 cost_tuplesort(&startup_cost, &run_cost,
2145 tuples, width,
2146 comparison_cost, sort_mem,
2147 limit_tuples);
2148
2149 startup_cost += input_cost;
2150
2151 path->rows = tuples;
2152 path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
2153 path->startup_cost = startup_cost;
2154 path->total_cost = startup_cost + run_cost;
2155}
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 4560 of file costsize.c.

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

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

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

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

References Assert(), clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, enable_tidscan, get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), JOIN_INNER, 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_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 1888 of file costsize.c.

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

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 1647 of file costsize.c.

1649{
1650 Cost startup_cost = 0;
1651 Cost run_cost = 0;
1652 QualCost qpqual_cost;
1653 Cost cpu_per_tuple;
1654
1655 /* Should only be applied to base relations that are values lists */
1656 Assert(baserel->relid > 0);
1657 Assert(baserel->rtekind == RTE_VALUES);
1658
1659 /* Mark the path with the correct row estimate */
1660 if (param_info)
1661 path->rows = param_info->ppi_rows;
1662 else
1663 path->rows = baserel->rows;
1664
1665 /*
1666 * For now, estimate list evaluation cost at one operator eval per list
1667 * (probably pretty bogus, but is it worth being smarter?)
1668 */
1669 cpu_per_tuple = cpu_operator_cost;
1670
1671 /* Add scanning CPU costs */
1672 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1673
1674 startup_cost += qpqual_cost.startup;
1675 cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1676 run_cost += cpu_per_tuple * baserel->tuples;
1677
1678 /* tlist eval costs are paid per output row, not per tuple scanned */
1679 startup_cost += path->pathtarget->cost.startup;
1680 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1681
1682 path->disabled_nodes = 0;
1683 path->startup_cost = startup_cost;
1684 path->total_cost = startup_cost + run_cost;
1685}
@ RTE_VALUES
Definition: parsenodes.h:1075

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 3120 of file costsize.c.

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

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

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 3859 of file costsize.c.

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

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 3371 of file costsize.c.

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

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 6431 of file costsize.c.

6432{
6433 int32 width;
6434
6435 if (IsA(expr, Var))
6436 {
6437 const Var *var = (const Var *) expr;
6438
6439 /* We should not see any upper-level Vars here */
6440 Assert(var->varlevelsup == 0);
6441
6442 /* Try to get data from RelOptInfo cache */
6443 if (!IS_SPECIAL_VARNO(var->varno) &&
6444 var->varno < root->simple_rel_array_size)
6445 {
6446 RelOptInfo *rel = root->simple_rel_array[var->varno];
6447
6448 if (rel != NULL &&
6449 var->varattno >= rel->min_attr &&
6450 var->varattno <= rel->max_attr)
6451 {
6452 int ndx = var->varattno - rel->min_attr;
6453
6454 if (rel->attr_widths[ndx] > 0)
6455 return rel->attr_widths[ndx];
6456 }
6457 }
6458
6459 /*
6460 * No cached data available, so estimate using just the type info.
6461 */
6462 width = get_typavgwidth(var->vartype, var->vartypmod);
6463 Assert(width > 0);
6464
6465 return width;
6466 }
6467
6468 width = get_typavgwidth(exprType(expr), exprTypmod(expr));
6469 Assert(width > 0);
6470 return width;
6471}
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2728
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 5677 of file costsize.c.

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

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:1267

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 6500 of file costsize.c.

6501{
6502 double parallel_divisor = path->parallel_workers;
6503
6504 /*
6505 * Early experience with parallel query suggests that when there is only
6506 * one worker, the leader often makes a very substantial contribution to
6507 * executing the parallel portion of the plan, but as more workers are
6508 * added, it does less and less, because it's busy reading tuples from the
6509 * workers and doing whatever non-parallel post-processing is needed. By
6510 * the time we reach 4 workers, the leader no longer makes a meaningful
6511 * contribution. Thus, for now, estimate that the leader spends 30% of
6512 * its time servicing each worker, and the remainder executing the
6513 * parallel plan.
6514 */
6516 {
6517 double leader_contribution;
6518
6519 leader_contribution = 1.0 - (0.3 * path->parallel_workers);
6520 if (leader_contribution > 0)
6521 parallel_divisor += leader_contribution;
6522 }
6523
6524 return parallel_divisor;
6525}
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(), cost_tidrangescan(), 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 5405 of file costsize.c.

5407{
5408 List *allclauses;
5409 double nrows;
5410
5411 /*
5412 * Estimate the number of rows returned by the parameterized scan, knowing
5413 * that it will apply all the extra join clauses as well as the rel's own
5414 * restriction clauses. Note that we force the clauses to be treated as
5415 * non-join clauses during selectivity estimation.
5416 */
5417 allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5418 nrows = rel->tuples *
5420 allclauses,
5421 rel->relid, /* do not use 0! */
5422 JOIN_INNER,
5423 NULL);
5424 nrows = clamp_row_est(nrows);
5425 /* For safety, make sure result is not more than the base estimate */
5426 if (nrows > rel->rows)
5427 nrows = rel->rows;
5428 return nrows;
5429}

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 5486 of file costsize.c.

5491{
5492 double nrows;
5493
5494 /*
5495 * Estimate the number of rows returned by the parameterized join as the
5496 * sizes of the input paths times the selectivity of the clauses that have
5497 * ended up at this join node.
5498 *
5499 * As with set_joinrel_size_estimates, the rowcount estimate could depend
5500 * on the pair of input paths provided, though ideally we'd get the same
5501 * estimate for any pair with the same parameterization.
5502 */
5504 rel,
5505 outer_path->parent,
5506 inner_path->parent,
5507 outer_path->rows,
5508 inner_path->rows,
5509 sjinfo,
5510 restrict_clauses);
5511 /* For safety, make sure result is not more than the base estimate */
5512 if (nrows > rel->rows)
5513 nrows = rel->rows;
5514 return nrows;
5515}
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:5527

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 5098 of file costsize.c.

5101{
5102 if (param_info)
5103 {
5104 /* Include costs of pushed-down clauses */
5105 cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
5106
5107 qpqual_cost->startup += baserel->baserestrictcost.startup;
5108 qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
5109 }
5110 else
5111 *qpqual_cost = baserel->baserestrictcost;
5112}
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 2906 of file costsize.c.

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

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 5237 of file costsize.c.

5238{
5239 JoinPath *joinpath = &path->jpath;
5240 Relids joinrelids = joinpath->path.parent->relids;
5241 Path *innerpath = joinpath->innerjoinpath;
5242 List *indexclauses;
5243 bool found_one;
5244 ListCell *lc;
5245
5246 /* If join still has quals to evaluate, it's not fast */
5247 if (joinpath->joinrestrictinfo != NIL)
5248 return false;
5249 /* Nor if the inner path isn't parameterized at all */
5250 if (innerpath->param_info == NULL)
5251 return false;
5252
5253 /* Find the indexclauses list for the inner scan */
5254 switch (innerpath->pathtype)
5255 {
5256 case T_IndexScan:
5257 case T_IndexOnlyScan:
5258 indexclauses = ((IndexPath *) innerpath)->indexclauses;
5259 break;
5260 case T_BitmapHeapScan:
5261 {
5262 /* Accept only a simple bitmap scan, not AND/OR cases */
5263 Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
5264
5265 if (IsA(bmqual, IndexPath))
5266 indexclauses = ((IndexPath *) bmqual)->indexclauses;
5267 else
5268 return false;
5269 break;
5270 }
5271 default:
5272
5273 /*
5274 * If it's not a simple indexscan, it probably doesn't run quickly
5275 * for zero rows out, even if it's a parameterized path using all
5276 * the joinquals.
5277 */
5278 return false;
5279 }
5280
5281 /*
5282 * Examine the inner path's param clauses. Any that are from the outer
5283 * path must be found in the indexclauses list, either exactly or in an
5284 * equivalent form generated by equivclass.c. Also, we must find at least
5285 * one such clause, else it's a clauseless join which isn't fast.
5286 */
5287 found_one = false;
5288 foreach(lc, innerpath->param_info->ppi_clauses)
5289 {
5290 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
5291
5293 innerpath->parent->relids,
5294 joinrelids))
5295 {
5296 if (!is_redundant_with_indexclauses(rinfo, indexclauses))
5297 return false;
5298 found_one = true;
5299 }
5300 }
5301 return found_one;
5302}
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 4184 of file costsize.c.

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

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

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

6491{
6492 return ceil(relation_byte_size(tuples, width) / BLCKSZ);
6493}

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 6479 of file costsize.c.

6480{
6481 return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
6482}
#define MAXALIGN(LEN)
Definition: c.h:832
#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 6101 of file costsize.c.

6102{
6103 RangeTblEntry *rte;
6104
6105 /* Should only be applied to base relations that are CTE references */
6106 Assert(rel->relid > 0);
6107 rte = planner_rt_fetch(rel->relid, root);
6108 Assert(rte->rtekind == RTE_CTE);
6109
6110 if (rte->self_reference)
6111 {
6112 /*
6113 * In a self-reference, we assume the average worktable size is a
6114 * multiple of the nonrecursive term's size. The best multiplier will
6115 * vary depending on query "fan-out", so make its value adjustable.
6116 */
6118 }
6119 else
6120 {
6121 /* Otherwise just believe the CTE's rowcount estimate */
6122 rel->tuples = cte_rows;
6123 }
6124
6125 /* Now estimate number of output rows, etc */
6127}
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5375
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 6201 of file costsize.c.

6202{
6203 /* Should only be applied to base relations */
6204 Assert(rel->relid > 0);
6205
6206 rel->rows = 1000; /* entirely bogus default estimate */
6207
6209
6210 set_rel_width(root, rel);
6211}

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 6009 of file costsize.c.

6010{
6011 RangeTblEntry *rte;
6012 ListCell *lc;
6013
6014 /* Should only be applied to base relations that are functions */
6015 Assert(rel->relid > 0);
6016 rte = planner_rt_fetch(rel->relid, root);
6017 Assert(rte->rtekind == RTE_FUNCTION);
6018
6019 /*
6020 * Estimate number of rows the functions will return. The rowcount of the
6021 * node is that of the largest function result.
6022 */
6023 rel->tuples = 0;
6024 foreach(lc, rte->functions)
6025 {
6026 RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
6027 double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
6028
6029 if (ntup > rel->tuples)
6030 rel->tuples = ntup;
6031 }
6032
6033 /* Now estimate number of output rows, etc */
6035}
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:301

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 5454 of file costsize.c.

5459{
5461 rel,
5462 outer_rel,
5463 inner_rel,
5464 outer_rel->rows,
5465 inner_rel->rows,
5466 sjinfo,
5467 restrictlist);
5468}

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 6139 of file costsize.c.

6140{
6141 RangeTblEntry *rte;
6142
6143 /* Should only be applied to base relations that are tuplestore references */
6144 Assert(rel->relid > 0);
6145 rte = planner_rt_fetch(rel->relid, root);
6147
6148 /*
6149 * Use the estimate provided by the code which is generating the named
6150 * tuplestore. In some cases, the actual number might be available; in
6151 * others the same plan will be re-used, so a "typical" value might be
6152 * estimated and used.
6153 */
6154 rel->tuples = rte->enrtuples;
6155 if (rel->tuples < 0)
6156 rel->tuples = 1000;
6157
6158 /* Now estimate number of output rows, etc */
6160}

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 6393 of file costsize.c.

6394{
6395 int64 tuple_width = 0;
6396 ListCell *lc;
6397
6398 /* Vars are assumed to have cost zero, but other exprs do not */
6399 target->cost.startup = 0;
6400 target->cost.per_tuple = 0;
6401
6402 foreach(lc, target->exprs)
6403 {
6404 Node *node = (Node *) lfirst(lc);
6405
6406 tuple_width += get_expr_width(root, node);
6407
6408 /* For non-Vars, account for evaluation cost */
6409 if (!IsA(node, Var))
6410 {
6411 QualCost cost;
6412
6413 cost_qual_eval_node(&cost, node, root);
6414 target->cost.startup += cost.startup;
6415 target->cost.per_tuple += cost.per_tuple;
6416 }
6417 }
6418
6419 target->width = clamp_width_est(tuple_width);
6420
6421 return target;
6422}
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:242
List * exprs
Definition: pathnodes.h:1780
QualCost cost
Definition: pathnodes.h:1786

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_extended().

◆ set_rel_width()

static void set_rel_width ( PlannerInfo root,
RelOptInfo rel 
)
static

Definition at line 6236 of file costsize.c.

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

6173{
6174 /* Should only be applied to RTE_RESULT base relations */
6175 Assert(rel->relid > 0);
6176 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6177
6178 /* RTE_RESULT always generates a single row, natively */
6179 rel->tuples = 1;
6180
6181 /* Now estimate number of output rows, etc */
6183}

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 5929 of file costsize.c.

5930{
5931 PlannerInfo *subroot = rel->subroot;
5932 RelOptInfo *sub_final_rel;
5933 ListCell *lc;
5934
5935 /* Should only be applied to base relations that are subqueries */
5936 Assert(rel->relid > 0);
5937 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5938
5939 /*
5940 * Copy raw number of output rows from subquery. All of its paths should
5941 * have the same output rowcount, so just look at cheapest-total.
5942 */
5943 sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5944 rel->tuples = sub_final_rel->cheapest_total_path->rows;
5945
5946 /*
5947 * Compute per-output-column width estimates by examining the subquery's
5948 * targetlist. For any output that is a plain Var, get the width estimate
5949 * that was made while planning the subquery. Otherwise, we leave it to
5950 * set_rel_width to fill in a datatype-based default estimate.
5951 */
5952 foreach(lc, subroot->parse->targetList)
5953 {
5955 Node *texpr = (Node *) te->expr;
5956 int32 item_width = 0;
5957
5958 /* junk columns aren't visible to upper query */
5959 if (te->resjunk)
5960 continue;
5961
5962 /*
5963 * The subquery could be an expansion of a view that's had columns
5964 * added to it since the current query was parsed, so that there are
5965 * non-junk tlist columns in it that don't correspond to any column
5966 * visible at our query level. Ignore such columns.
5967 */
5968 if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5969 continue;
5970
5971 /*
5972 * XXX This currently doesn't work for subqueries containing set
5973 * operations, because the Vars in their tlists are bogus references
5974 * to the first leaf subquery, which wouldn't give the right answer
5975 * even if we could still get to its PlannerInfo.
5976 *
5977 * Also, the subquery could be an appendrel for which all branches are
5978 * known empty due to constraint exclusion, in which case
5979 * set_append_rel_pathlist will have left the attr_widths set to zero.
5980 *
5981 * In either case, we just leave the width estimate zero until
5982 * set_rel_width fixes it.
5983 */
5984 if (IsA(texpr, Var) &&
5985 subroot->parse->setOperations == NULL)
5986 {
5987 Var *var = (Var *) texpr;
5988 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5989
5990 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5991 }
5992 rel->attr_widths[te->resno - rel->min_attr] = item_width;
5993 }
5994
5995 /* Now estimate number of output rows, etc */
5997}
@ 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 6047 of file costsize.c.

6048{
6049 /* Should only be applied to base relations that are functions */
6050 Assert(rel->relid > 0);
6051 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
6052
6053 rel->tuples = 100;
6054
6055 /* Now estimate number of output rows, etc */
6057}

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 6069 of file costsize.c.

6070{
6071 RangeTblEntry *rte;
6072
6073 /* Should only be applied to base relations that are values lists */
6074 Assert(rel->relid > 0);
6075 rte = planner_rt_fetch(rel->relid, root);
6076 Assert(rte->rtekind == RTE_VALUES);
6077
6078 /*
6079 * Estimate number of rows the values list will return. We know this
6080 * precisely based on the list length (well, barring set-returning
6081 * functions in list items, but that's a refinement not catered for
6082 * anywhere else either).
6083 */
6084 rel->tuples = list_length(rte->values_lists);
6085
6086 /* Now estimate number of output rows, etc */
6088}
List * values_lists
Definition: parsenodes.h:1248

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

◆ 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