PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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, bool enabled, 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, uint64 enable_mask, 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 2234 of file costsize.c.

2235{
2236 Cost *costarr;
2237 int arrlen;
2238 ListCell *l;
2239 ListCell *cell;
2240 int path_index;
2241 int min_index;
2242 int max_index;
2243
2244 if (numpaths == 0)
2245 return 0;
2246
2247 /*
2248 * Array length is number of workers or number of relevant paths,
2249 * whichever is less.
2250 */
2251 arrlen = Min(parallel_workers, numpaths);
2253
2254 /* The first few paths will each be claimed by a different worker. */
2255 path_index = 0;
2256 foreach(cell, subpaths)
2257 {
2258 Path *subpath = (Path *) lfirst(cell);
2259
2260 if (path_index == arrlen)
2261 break;
2263 }
2264
2265 /*
2266 * Since subpaths are sorted by decreasing cost, the last one will have
2267 * the minimum cost.
2268 */
2269 min_index = arrlen - 1;
2270
2271 /*
2272 * For each of the remaining subpaths, add its cost to the array element
2273 * with minimum cost.
2274 */
2275 for_each_cell(l, subpaths, cell)
2276 {
2277 Path *subpath = (Path *) lfirst(l);
2278
2279 /* Consider only the non-partial paths */
2280 if (path_index++ == numpaths)
2281 break;
2282
2284
2285 /* Update the new min cost array index */
2286 min_index = 0;
2287 for (int i = 0; i < arrlen; i++)
2288 {
2289 if (costarr[i] < costarr[min_index])
2290 min_index = i;
2291 }
2292 }
2293
2294 /* Return the highest cost from the array */
2295 max_index = 0;
2296 for (int i = 0; i < arrlen; i++)
2297 {
2298 if (costarr[i] > costarr[max_index])
2299 max_index = i;
2300 }
2301
2302 return costarr[max_index];
2303}
#define Min(x, y)
Definition c.h:997
#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
static int fb(int x)
Cost total_cost
Definition pathnodes.h:1988

References fb(), for_each_cell, i, lfirst, Min, palloc_array, subpath(), and Path::total_cost.

Referenced by cost_append().

◆ approx_tuple_count()

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

Definition at line 5451 of file costsize.c.

5452{
5453 double tuples;
5454 double outer_tuples = path->outerjoinpath->rows;
5455 double inner_tuples = path->innerjoinpath->rows;
5456 SpecialJoinInfo sjinfo;
5457 Selectivity selec = 1.0;
5458 ListCell *l;
5459
5460 /*
5461 * Make up a SpecialJoinInfo for JOIN_INNER semantics.
5462 */
5463 init_dummy_sjinfo(&sjinfo, path->outerjoinpath->parent->relids,
5464 path->innerjoinpath->parent->relids);
5465
5466 /* Get the approximate selectivity */
5467 foreach(l, quals)
5468 {
5469 Node *qual = (Node *) lfirst(l);
5470
5471 /* Note that clause_selectivity will be able to cache its result */
5472 selec *= clause_selectivity(root, qual, 0, JOIN_INNER, &sjinfo);
5473 }
5474
5475 /* Apply it to the input relation sizes */
5476 tuples = selec * outer_tuples * inner_tuples;
5477
5478 return clamp_row_est(tuples);
5479}
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:2374
Path * innerjoinpath
Definition pathnodes.h:2375
Definition nodes.h:135
Cardinality rows
Definition pathnodes.h:1985

References clamp_row_est(), clause_selectivity(), fb(), 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 4222 of file costsize.c.

4223{
4224 MergeScanSelCache *cache;
4225 ListCell *lc;
4226 Selectivity leftstartsel,
4227 leftendsel,
4228 rightstartsel,
4229 rightendsel;
4230 MemoryContext oldcontext;
4231
4232 /* Do we have this result already? */
4233 foreach(lc, rinfo->scansel_cache)
4234 {
4235 cache = (MergeScanSelCache *) lfirst(lc);
4236 if (cache->opfamily == pathkey->pk_opfamily &&
4237 cache->collation == pathkey->pk_eclass->ec_collation &&
4238 cache->cmptype == pathkey->pk_cmptype &&
4239 cache->nulls_first == pathkey->pk_nulls_first)
4240 return cache;
4241 }
4242
4243 /* Nope, do the computation */
4245 (Node *) rinfo->clause,
4246 pathkey->pk_opfamily,
4247 pathkey->pk_cmptype,
4248 pathkey->pk_nulls_first,
4249 &leftstartsel,
4250 &leftendsel,
4251 &rightstartsel,
4252 &rightendsel);
4253
4254 /* Cache the result in suitably long-lived workspace */
4255 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
4256
4258 cache->opfamily = pathkey->pk_opfamily;
4259 cache->collation = pathkey->pk_eclass->ec_collation;
4260 cache->cmptype = pathkey->pk_cmptype;
4261 cache->nulls_first = pathkey->pk_nulls_first;
4262 cache->leftstartsel = leftstartsel;
4263 cache->leftendsel = leftendsel;
4264 cache->rightstartsel = rightstartsel;
4265 cache->rightendsel = rightendsel;
4266
4267 rinfo->scansel_cache = lappend(rinfo->scansel_cache, cache);
4268
4269 MemoryContextSwitchTo(oldcontext);
4270
4271 return cache;
4272}
#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:3046
Selectivity leftendsel
Definition pathnodes.h:3047
CompareType cmptype
Definition pathnodes.h:3043
Selectivity rightendsel
Definition pathnodes.h:3049
Selectivity rightstartsel
Definition pathnodes.h:3048
Expr * clause
Definition pathnodes.h:2870

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

5656{
5657 JoinType jointype = sjinfo->jointype;
5661 double nrows;
5662
5663 /*
5664 * Compute joinclause selectivity. Note that we are only considering
5665 * clauses that become restriction clauses at this join level; we are not
5666 * double-counting them because they were not considered in estimating the
5667 * sizes of the component rels.
5668 *
5669 * First, see whether any of the joinclauses can be matched to known FK
5670 * constraints. If so, drop those clauses from the restrictlist, and
5671 * instead estimate their selectivity using FK semantics. (We do this
5672 * without regard to whether said clauses are local or "pushed down".
5673 * Probably, an FK-matching clause could never be seen as pushed down at
5674 * an outer join, since it would be strict and hence would be grounds for
5675 * join strength reduction.) fkselec gets the net selectivity for
5676 * FK-matching clauses, or 1.0 if there are none.
5677 */
5679 outer_rel->relids,
5680 inner_rel->relids,
5681 sjinfo,
5682 &restrictlist);
5683
5684 /*
5685 * For an outer join, we have to distinguish the selectivity of the join's
5686 * own clauses (JOIN/ON conditions) from any clauses that were "pushed
5687 * down". For inner joins we just count them all as joinclauses.
5688 */
5689 if (IS_OUTER_JOIN(jointype))
5690 {
5691 List *joinquals = NIL;
5692 List *pushedquals = NIL;
5693 ListCell *l;
5694
5695 /* Grovel through the clauses to separate into two lists */
5696 foreach(l, restrictlist)
5697 {
5699
5700 if (RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5702 else
5703 joinquals = lappend(joinquals, rinfo);
5704 }
5705
5706 /* Get the separate selectivities */
5708 joinquals,
5709 0,
5710 jointype,
5711 sjinfo);
5714 0,
5715 jointype,
5716 sjinfo);
5717
5718 /* Avoid leaking a lot of ListCells */
5721 }
5722 else
5723 {
5725 restrictlist,
5726 0,
5727 jointype,
5728 sjinfo);
5729 pselec = 0.0; /* not used, keep compiler quiet */
5730 }
5731
5732 /*
5733 * Basically, we multiply size of Cartesian product by selectivity.
5734 *
5735 * If we are doing an outer join, take that into account: the joinqual
5736 * selectivity has to be clamped using the knowledge that the output must
5737 * be at least as large as the non-nullable input. However, any
5738 * pushed-down quals are applied after the outer join, so their
5739 * selectivity applies fully.
5740 *
5741 * For JOIN_SEMI and JOIN_ANTI, the selectivity is defined as the fraction
5742 * of LHS rows that have matches, and we apply that straightforwardly.
5743 */
5744 switch (jointype)
5745 {
5746 case JOIN_INNER:
5747 nrows = outer_rows * inner_rows * fkselec * jselec;
5748 /* pselec not used */
5749 break;
5750 case JOIN_LEFT:
5751 nrows = outer_rows * inner_rows * fkselec * jselec;
5752 if (nrows < outer_rows)
5753 nrows = outer_rows;
5754 nrows *= pselec;
5755 break;
5756 case JOIN_FULL:
5757 nrows = outer_rows * inner_rows * fkselec * jselec;
5758 if (nrows < outer_rows)
5759 nrows = outer_rows;
5760 if (nrows < inner_rows)
5761 nrows = inner_rows;
5762 nrows *= pselec;
5763 break;
5764 case JOIN_SEMI:
5765 nrows = outer_rows * fkselec * jselec;
5766 /* pselec not used */
5767 break;
5768 case JOIN_ANTI:
5769 nrows = outer_rows * (1.0 - fkselec * jselec);
5770 nrows *= pselec;
5771 break;
5772 default:
5773 /* other values not expected here */
5774 elog(ERROR, "unrecognized join type: %d", (int) jointype);
5775 nrows = 0; /* keep compiler quiet */
5776 break;
5777 }
5778
5779 return clamp_row_est(nrows);
5780}
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:5798
#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:3027
#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:1003
JoinType jointype
Definition pathnodes.h:3199

References clamp_row_est(), clauselist_selectivity(), elog, ERROR, fb(), 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 fb(), and 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 */
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}
#define Assert(condition)
Definition c.h:873
int32_t int32
Definition c.h:542
#define MaxAllocSize
Definition fe_memutils.h:22

References Assert, fb(), 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 6661 of file costsize.c.

6664{
6665 Cost indexTotalCost;
6666 Selectivity indexSelectivity;
6667 double T;
6668 double pages_fetched;
6669 double tuples_fetched;
6670 double heap_pages;
6671 double maxentries;
6672
6673 /*
6674 * Fetch total cost of obtaining the bitmap, as well as its total
6675 * selectivity.
6676 */
6677 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6678
6679 /*
6680 * Estimate number of main-table pages fetched.
6681 */
6682 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6683
6684 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6685
6686 /*
6687 * For a single scan, the number of heap pages that need to be fetched is
6688 * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6689 * re-reads needed).
6690 */
6691 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6692
6693 /*
6694 * Calculate the number of pages fetched from the heap. Then based on
6695 * current work_mem estimate get the estimated maxentries in the bitmap.
6696 * (Note that we always do this calculation based on the number of pages
6697 * that would be fetched in a single iteration, even if loop_count > 1.
6698 * That's correct, because only that number of entries will be stored in
6699 * the bitmap at one time.)
6700 */
6702 maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
6703
6704 if (loop_count > 1)
6705 {
6706 /*
6707 * For repeated bitmap scans, scale up the number of tuples fetched in
6708 * the Mackert and Lohman formula by the number of scans, so that we
6709 * estimate the number of pages fetched by all the scans. Then
6710 * pro-rate for one scan.
6711 */
6712 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6713 baserel->pages,
6714 get_indexpath_pages(bitmapqual),
6715 root);
6717 }
6718
6719 if (pages_fetched >= T)
6720 pages_fetched = T;
6721 else
6723
6724 if (maxentries < heap_pages)
6725 {
6726 double exact_pages;
6727 double lossy_pages;
6728
6729 /*
6730 * Crude approximation of the number of lossy pages. Because of the
6731 * way tbm_lossify() is coded, the number of lossy pages increases
6732 * very sharply as soon as we run short of memory; this formula has
6733 * that property and seems to perform adequately in testing, but it's
6734 * possible we could do better somehow.
6735 */
6736 lossy_pages = Max(0, heap_pages - maxentries / 2);
6737 exact_pages = heap_pages - lossy_pages;
6738
6739 /*
6740 * If there are lossy pages then recompute the number of tuples
6741 * processed by the bitmap heap node. We assume here that the chance
6742 * of a given tuple coming from an exact page is the same as the
6743 * chance that a given page is exact. This might not be true, but
6744 * it's not clear how we can do any better.
6745 */
6746 if (lossy_pages > 0)
6747 tuples_fetched =
6748 clamp_row_est(indexSelectivity *
6749 (exact_pages / heap_pages) * baserel->tuples +
6750 (lossy_pages / heap_pages) * baserel->tuples);
6751 }
6752
6753 if (cost_p)
6754 *cost_p = indexTotalCost;
6755 if (tuples_p)
6756 *tuples_p = tuples_fetched;
6757
6758 return pages_fetched;
6759}
#define Max(x, y)
Definition c.h:991
size_t Size
Definition c.h:619
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition costsize.c:896
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition costsize.c:1114
static double get_indexpath_pages(Path *bitmapqual)
Definition costsize.c:961
int work_mem
Definition globals.c:131
static const uint32 T[65]
Definition md5.c:119
int tbm_calculate_entries(Size maxbytes)
Definition tidbitmap.c:1542

References clamp_row_est(), cost_bitmap_tree_node(), fb(), get_indexpath_pages(), index_pages_fetched(), Max, Min, root, T, tbm_calculate_entries(), 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 6772 of file costsize.c.

6773{
6774 Assert(path->parallel_workers > 0);
6775
6776 return clamp_row_est(path->rows * get_parallel_divisor(path));
6777}
static double get_parallel_divisor(Path *path)
Definition costsize.c:6621
int parallel_workers
Definition pathnodes.h:1982

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

5269{
5274 List *joinquals;
5275 ListCell *l;
5276
5277 /*
5278 * In an ANTI join, we must ignore clauses that are "pushed down", since
5279 * those won't affect the match logic. In a SEMI join, we do not
5280 * distinguish joinquals from "pushed down" quals, so just use the whole
5281 * restrictinfo list. For other outer join types, we should consider only
5282 * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5283 */
5284 if (IS_OUTER_JOIN(jointype))
5285 {
5286 joinquals = NIL;
5287 foreach(l, restrictlist)
5288 {
5290
5291 if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5292 joinquals = lappend(joinquals, rinfo);
5293 }
5294 }
5295 else
5296 joinquals = restrictlist;
5297
5298 /*
5299 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5300 */
5302 joinquals,
5303 0,
5304 (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5305 sjinfo);
5306
5307 /*
5308 * Also get the normal inner-join selectivity of the join clauses.
5309 */
5310 init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
5311
5313 joinquals,
5314 0,
5315 JOIN_INNER,
5316 &norm_sjinfo);
5317
5318 /* Avoid leaking a lot of ListCells */
5319 if (IS_OUTER_JOIN(jointype))
5321
5322 /*
5323 * jselec can be interpreted as the fraction of outer-rel rows that have
5324 * any matches (this is true for both SEMI and ANTI cases). And nselec is
5325 * the fraction of the Cartesian product that matches. So, the average
5326 * number of matches for each outer-rel row that has at least one match is
5327 * nselec * inner_rows / jselec.
5328 *
5329 * Note: it is correct to use the inner rel's "rows" count here, even
5330 * though we might later be considering a parameterized inner path with
5331 * fewer rows. This is because we have included all the join clauses in
5332 * the selectivity estimate.
5333 */
5334 if (jselec > 0) /* protect against zero divide */
5335 {
5336 avgmatch = nselec * innerrel->rows / jselec;
5337 /* Clamp to sane range */
5338 avgmatch = Max(1.0, avgmatch);
5339 }
5340 else
5341 avgmatch = 1.0;
5342
5343 semifactors->outer_match_frac = jselec;
5344 semifactors->match_count = avgmatch;
5345}
Cardinality rows
Definition pathnodes.h:1009
Selectivity outer_match_frac
Definition pathnodes.h:3555
Selectivity match_count
Definition pathnodes.h:3556

References clauselist_selectivity(), fb(), 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 2792 of file costsize.c.

2799{
2800 double output_tuples;
2801 Cost startup_cost;
2802 Cost total_cost;
2803 const AggClauseCosts dummy_aggcosts = {0};
2804
2805 /* Use all-zero per-aggregate costs if NULL is passed */
2806 if (aggcosts == NULL)
2807 {
2808 Assert(aggstrategy == AGG_HASHED);
2810 }
2811
2812 /*
2813 * The transCost.per_tuple component of aggcosts should be charged once
2814 * per input tuple, corresponding to the costs of evaluating the aggregate
2815 * transfns and their input expressions. The finalCost.per_tuple component
2816 * is charged once per output tuple, corresponding to the costs of
2817 * evaluating the finalfns. Startup costs are of course charged but once.
2818 *
2819 * If we are grouping, we charge an additional cpu_operator_cost per
2820 * grouping column per input tuple for grouping comparisons.
2821 *
2822 * We will produce a single output tuple if not grouping, and a tuple per
2823 * group otherwise. We charge cpu_tuple_cost for each output tuple.
2824 *
2825 * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2826 * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2827 * input path is already sorted appropriately, AGG_SORTED should be
2828 * preferred (since it has no risk of memory overflow). This will happen
2829 * as long as the computed total costs are indeed exactly equal --- but if
2830 * there's roundoff error we might do the wrong thing. So be sure that
2831 * the computations below form the same intermediate values in the same
2832 * order.
2833 */
2834 if (aggstrategy == AGG_PLAIN)
2835 {
2836 startup_cost = input_total_cost;
2837 startup_cost += aggcosts->transCost.startup;
2838 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2839 startup_cost += aggcosts->finalCost.startup;
2840 startup_cost += aggcosts->finalCost.per_tuple;
2841 /* we aren't grouping */
2842 total_cost = startup_cost + cpu_tuple_cost;
2843 output_tuples = 1;
2844 }
2845 else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2846 {
2847 /* Here we are able to deliver output on-the-fly */
2848 startup_cost = input_startup_cost;
2849 total_cost = input_total_cost;
2850 if (aggstrategy == AGG_MIXED && !enable_hashagg)
2851 ++disabled_nodes;
2852 /* calcs phrased this way to match HASHED case, see note above */
2853 total_cost += aggcosts->transCost.startup;
2854 total_cost += aggcosts->transCost.per_tuple * input_tuples;
2855 total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2856 total_cost += aggcosts->finalCost.startup;
2857 total_cost += aggcosts->finalCost.per_tuple * numGroups;
2858 total_cost += cpu_tuple_cost * numGroups;
2859 output_tuples = numGroups;
2860 }
2861 else
2862 {
2863 /* must be AGG_HASHED */
2864 startup_cost = input_total_cost;
2865 if (!enable_hashagg)
2866 ++disabled_nodes;
2867 startup_cost += aggcosts->transCost.startup;
2868 startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2869 /* cost of computing hash value */
2870 startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2871 startup_cost += aggcosts->finalCost.startup;
2872
2873 total_cost = startup_cost;
2874 total_cost += aggcosts->finalCost.per_tuple * numGroups;
2875 /* cost of retrieving from hash table */
2876 total_cost += cpu_tuple_cost * numGroups;
2877 output_tuples = numGroups;
2878 }
2879
2880 /*
2881 * Add the disk costs of hash aggregation that spills to disk.
2882 *
2883 * Groups that go into the hash table stay in memory until finalized, so
2884 * spilling and reprocessing tuples doesn't incur additional invocations
2885 * of transCost or finalCost. Furthermore, the computed hash value is
2886 * stored with the spilled tuples, so we don't incur extra invocations of
2887 * the hash function.
2888 *
2889 * Hash Agg begins returning tuples after the first batch is complete.
2890 * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2891 * accrue reads only to total_cost.
2892 */
2893 if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2894 {
2895 double pages;
2896 double pages_written = 0.0;
2897 double pages_read = 0.0;
2898 double spill_cost;
2899 double hashentrysize;
2900 double nbatches;
2901 Size mem_limit;
2903 int num_partitions;
2904 int depth;
2905
2906 /*
2907 * Estimate number of batches based on the computed limits. If less
2908 * than or equal to one, all groups are expected to fit in memory;
2909 * otherwise we expect to spill.
2910 */
2911 hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2913 aggcosts->transitionSpace);
2914 hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2915 &ngroups_limit, &num_partitions);
2916
2917 nbatches = Max((numGroups * hashentrysize) / mem_limit,
2918 numGroups / ngroups_limit);
2919
2920 nbatches = Max(ceil(nbatches), 1.0);
2921 num_partitions = Max(num_partitions, 2);
2922
2923 /*
2924 * The number of partitions can change at different levels of
2925 * recursion; but for the purposes of this calculation assume it stays
2926 * constant.
2927 */
2928 depth = ceil(log(nbatches) / log(num_partitions));
2929
2930 /*
2931 * Estimate number of pages read and written. For each level of
2932 * recursion, a tuple must be written and then later read.
2933 */
2934 pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2935 pages_written = pages_read = pages * depth;
2936
2937 /*
2938 * HashAgg has somewhat worse IO behavior than Sort on typical
2939 * hardware/OS combinations. Account for this with a generic penalty.
2940 */
2941 pages_read *= 2.0;
2942 pages_written *= 2.0;
2943
2944 startup_cost += pages_written * random_page_cost;
2945 total_cost += pages_written * random_page_cost;
2946 total_cost += pages_read * seq_page_cost;
2947
2948 /* account for CPU cost of spilling a tuple and reading it back */
2949 spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2950 startup_cost += spill_cost;
2951 total_cost += spill_cost;
2952 }
2953
2954 /*
2955 * If there are quals (HAVING quals), account for their cost and
2956 * selectivity.
2957 */
2958 if (quals)
2959 {
2961
2962 cost_qual_eval(&qual_cost, quals, root);
2963 startup_cost += qual_cost.startup;
2964 total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2965
2968 quals,
2969 0,
2970 JOIN_INNER,
2971 NULL));
2972 }
2973
2974 path->rows = output_tuples;
2975 path->disabled_nodes = disabled_nodes;
2976 path->startup_cost = startup_cost;
2977 path->total_cost = total_cost;
2978}
uint64_t uint64
Definition c.h:547
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:6600
double cpu_tuple_cost
Definition costsize.c:132
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition costsize.c:4903
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
Cost startup_cost
Definition pathnodes.h:1987
int disabled_nodes
Definition pathnodes.h:1986

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, fb(), hash_agg_entry_size(), hash_agg_set_limits(), JOIN_INNER, list_length(), Max, random_page_cost, relation_byte_size(), root, Path::rows, seq_page_cost, Path::startup_cost, and Path::total_cost.

Referenced by create_agg_path(), and create_groupingsets_path().

◆ cost_append()

void cost_append ( AppendPath apath,
PlannerInfo root 
)

Definition at line 2310 of file costsize.c.

2311{
2312 RelOptInfo *rel = apath->path.parent;
2313 ListCell *l;
2315
2316 if (apath->path.parallel_workers == 0)
2318
2319 apath->path.disabled_nodes =
2320 (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
2321 apath->path.startup_cost = 0;
2322 apath->path.total_cost = 0;
2323 apath->path.rows = 0;
2324
2325 if (apath->subpaths == NIL)
2326 return;
2327
2328 if (!apath->path.parallel_aware)
2329 {
2330 List *pathkeys = apath->path.pathkeys;
2331
2332 if (pathkeys == NIL)
2333 {
2334 Path *firstsubpath = (Path *) linitial(apath->subpaths);
2335
2336 /*
2337 * For an unordered, non-parallel-aware Append we take the startup
2338 * cost as the startup cost of the first subpath.
2339 */
2340 apath->path.startup_cost = firstsubpath->startup_cost;
2341
2342 /*
2343 * Compute rows, number of disabled nodes, and total cost as sums
2344 * of underlying subplan values.
2345 */
2346 foreach(l, apath->subpaths)
2347 {
2348 Path *subpath = (Path *) lfirst(l);
2349
2350 apath->path.rows += subpath->rows;
2351 apath->path.disabled_nodes += subpath->disabled_nodes;
2352 apath->path.total_cost += subpath->total_cost;
2353 }
2354 }
2355 else
2356 {
2357 /*
2358 * For an ordered, non-parallel-aware Append we take the startup
2359 * cost as the sum of the subpath startup costs. This ensures
2360 * that we don't underestimate the startup cost when a query's
2361 * LIMIT is such that several of the children have to be run to
2362 * satisfy it. This might be overkill --- another plausible hack
2363 * would be to take the Append's startup cost as the maximum of
2364 * the child startup costs. But we don't want to risk believing
2365 * that an ORDER BY LIMIT query can be satisfied at small cost
2366 * when the first child has small startup cost but later ones
2367 * don't. (If we had the ability to deal with nonlinear cost
2368 * interpolation for partial retrievals, we would not need to be
2369 * so conservative about this.)
2370 *
2371 * This case is also different from the above in that we have to
2372 * account for possibly injecting sorts into subpaths that aren't
2373 * natively ordered.
2374 */
2375 foreach(l, apath->subpaths)
2376 {
2377 Path *subpath = (Path *) lfirst(l);
2378 int presorted_keys;
2379 Path sort_path; /* dummy for result of
2380 * cost_sort/cost_incremental_sort */
2381
2382 if (!pathkeys_count_contained_in(pathkeys, subpath->pathkeys,
2383 &presorted_keys))
2384 {
2385 /*
2386 * We'll need to insert a Sort node, so include costs for
2387 * that. We choose to use incremental sort if it is
2388 * enabled and there are presorted keys; otherwise we use
2389 * full sort.
2390 *
2391 * We can use the parent's LIMIT if any, since we
2392 * certainly won't pull more than that many tuples from
2393 * any child.
2394 */
2395 if (enable_incremental_sort && presorted_keys > 0)
2396 {
2398 root,
2399 pathkeys,
2400 presorted_keys,
2401 subpath->disabled_nodes,
2402 subpath->startup_cost,
2403 subpath->total_cost,
2404 subpath->rows,
2405 subpath->pathtarget->width,
2406 0.0,
2407 work_mem,
2408 apath->limit_tuples);
2409 }
2410 else
2411 {
2413 root,
2414 pathkeys,
2415 subpath->disabled_nodes,
2416 subpath->total_cost,
2417 subpath->rows,
2418 subpath->pathtarget->width,
2419 0.0,
2420 work_mem,
2421 apath->limit_tuples);
2422 }
2423
2424 subpath = &sort_path;
2425 }
2426
2427 apath->path.rows += subpath->rows;
2428 apath->path.disabled_nodes += subpath->disabled_nodes;
2429 apath->path.startup_cost += subpath->startup_cost;
2430 apath->path.total_cost += subpath->total_cost;
2431 }
2432 }
2433 }
2434 else /* parallel-aware */
2435 {
2436 int i = 0;
2438
2439 /* Parallel-aware Append never produces ordered output. */
2440 Assert(apath->path.pathkeys == NIL);
2441
2442 /* Calculate startup cost. */
2443 foreach(l, apath->subpaths)
2444 {
2445 Path *subpath = (Path *) lfirst(l);
2446
2447 /*
2448 * Append will start returning tuples when the child node having
2449 * lowest startup cost is done setting up. We consider only the
2450 * first few subplans that immediately get a worker assigned.
2451 */
2452 if (i == 0)
2453 apath->path.startup_cost = subpath->startup_cost;
2454 else if (i < apath->path.parallel_workers)
2455 apath->path.startup_cost = Min(apath->path.startup_cost,
2456 subpath->startup_cost);
2457
2458 /*
2459 * Apply parallel divisor to subpaths. Scale the number of rows
2460 * for each partial subpath based on the ratio of the parallel
2461 * divisor originally used for the subpath to the one we adopted.
2462 * Also add the cost of partial paths to the total cost, but
2463 * ignore non-partial paths for now.
2464 */
2465 if (i < apath->first_partial_path)
2466 apath->path.rows += subpath->rows / parallel_divisor;
2467 else
2468 {
2470
2472 apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2474 apath->path.total_cost += subpath->total_cost;
2475 }
2476
2477 apath->path.disabled_nodes += subpath->disabled_nodes;
2478 apath->path.rows = clamp_row_est(apath->path.rows);
2479
2480 i++;
2481 }
2482
2483 /* Add cost for non-partial subpaths. */
2484 apath->path.total_cost +=
2485 append_nonpartial_cost(apath->subpaths,
2486 apath->first_partial_path,
2487 apath->path.parallel_workers);
2488 }
2489
2490 /*
2491 * Although Append does not do any selection or projection, it's not free;
2492 * add a small per-tuple overhead.
2493 */
2494 apath->path.total_cost +=
2496}
#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:2200
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:2052
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition costsize.c:2234
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 PGS_APPEND
Definition pathnodes.h:78
#define PGS_CONSIDER_NONPARTIAL
Definition pathnodes.h:84
#define linitial(l)
Definition pg_list.h:178
uint64 pgs_mask
Definition pathnodes.h:1021

References APPEND_CPU_COST_MULTIPLIER, append_nonpartial_cost(), Assert, clamp_row_est(), cost_incremental_sort(), cost_sort(), cpu_tuple_cost, enable_incremental_sort, fb(), get_parallel_divisor(), i, lfirst, linitial, Min, NIL, pathkeys_count_contained_in(), PGS_APPEND, PGS_CONSIDER_NONPARTIAL, RelOptInfo::pgs_mask, root, Path::rows, Path::startup_cost, subpath(), and work_mem.

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1157 of file costsize.c.

1158{
1161 ListCell *l;
1162
1163 /*
1164 * We estimate AND selectivity on the assumption that the inputs are
1165 * independent. This is probably often wrong, but we don't have the info
1166 * to do better.
1167 *
1168 * The runtime cost of the BitmapAnd itself is estimated at 100x
1169 * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1170 * definitely too simplistic?
1171 */
1172 totalCost = 0.0;
1173 selec = 1.0;
1174 foreach(l, path->bitmapquals)
1175 {
1176 Path *subpath = (Path *) lfirst(l);
1177 Cost subCost;
1179
1181
1182 selec *= subselec;
1183
1184 totalCost += subCost;
1185 if (l != list_head(path->bitmapquals))
1186 totalCost += 100.0 * cpu_operator_cost;
1187 }
1188 path->bitmapselectivity = selec;
1189 path->path.rows = 0; /* per above, not used */
1190 path->path.disabled_nodes = 0;
1191 path->path.startup_cost = totalCost;
1192 path->path.total_cost = totalCost;
1193}
static ListCell * list_head(const List *l)
Definition pg_list.h:128
Selectivity bitmapselectivity
Definition pathnodes.h:2124
List * bitmapquals
Definition pathnodes.h:2123

References BitmapAndPath::bitmapquals, BitmapAndPath::bitmapselectivity, cost_bitmap_tree_node(), cpu_operator_cost, Path::disabled_nodes, fb(), 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 1011 of file costsize.c.

1014{
1015 Cost startup_cost = 0;
1016 Cost run_cost = 0;
1017 Cost indexTotalCost;
1022 double tuples_fetched;
1023 double pages_fetched;
1024 double spc_seq_page_cost,
1025 spc_random_page_cost;
1026 double T;
1028
1029 /* Should only be applied to base relations */
1031 Assert(baserel->relid > 0);
1032 Assert(baserel->rtekind == RTE_RELATION);
1033
1034 /* Mark the path with the correct row estimate */
1035 if (param_info)
1036 path->rows = param_info->ppi_rows;
1037 else
1038 path->rows = baserel->rows;
1039
1041 loop_count, &indexTotalCost,
1042 &tuples_fetched);
1043
1044 startup_cost += indexTotalCost;
1045 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
1046
1047 /* Fetch estimated page costs for tablespace containing table. */
1048 get_tablespace_page_costs(baserel->reltablespace,
1049 &spc_random_page_cost,
1051
1052 /*
1053 * For small numbers of pages we should charge spc_random_page_cost
1054 * apiece, while if nearly all the table's pages are being read, it's more
1055 * appropriate to charge spc_seq_page_cost apiece. The effect is
1056 * nonlinear, too. For lack of a better idea, interpolate like this to
1057 * determine the cost per page.
1058 */
1059 if (pages_fetched >= 2.0)
1060 cost_per_page = spc_random_page_cost -
1061 (spc_random_page_cost - spc_seq_page_cost)
1062 * sqrt(pages_fetched / T);
1063 else
1064 cost_per_page = spc_random_page_cost;
1065
1066 run_cost += pages_fetched * cost_per_page;
1067
1068 /*
1069 * Estimate CPU costs per tuple.
1070 *
1071 * Often the indexquals don't need to be rechecked at each tuple ... but
1072 * not always, especially not if there are enough tuples involved that the
1073 * bitmaps become lossy. For the moment, just assume they will be
1074 * rechecked always. This means we charge the full freight for all the
1075 * scan clauses.
1076 */
1078
1079 startup_cost += qpqual_cost.startup;
1081 cpu_run_cost = cpu_per_tuple * tuples_fetched;
1082
1083 /* Adjust costing for parallelism, if used. */
1084 if (path->parallel_workers > 0)
1085 {
1087
1088 /* The CPU cost is divided among all the workers. */
1090
1091 path->rows = clamp_row_est(path->rows / parallel_divisor);
1092 }
1093 else
1095
1096
1097 run_cost += cpu_run_cost;
1098
1099 /* tlist eval costs are paid per output row, not per tuple scanned */
1100 startup_cost += path->pathtarget->cost.startup;
1101 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1102
1103 path->disabled_nodes =
1104 (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
1105 path->startup_cost = startup_cost;
1106 path->total_cost = startup_cost + run_cost;
1107}
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition costsize.c:5219
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition costsize.c:6661
#define IsA(nodeptr, _type_)
Definition nodes.h:164
@ RTE_RELATION
#define PGS_BITMAPSCAN
Definition pathnodes.h:69
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition spccache.c:182

References Assert, clamp_row_est(), compute_bitmap_pages(), cpu_tuple_cost, Path::disabled_nodes, fb(), get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, Path::parallel_workers, PGS_BITMAPSCAN, PGS_CONSIDER_NONPARTIAL, root, Path::rows, RTE_RELATION, 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 1202 of file costsize.c.

1203{
1206 ListCell *l;
1207
1208 /*
1209 * We estimate OR selectivity on the assumption that the inputs are
1210 * non-overlapping, since that's often the case in "x IN (list)" type
1211 * situations. Of course, we clamp to 1.0 at the end.
1212 *
1213 * The runtime cost of the BitmapOr itself is estimated at 100x
1214 * cpu_operator_cost for each tbm_union needed. Probably too small,
1215 * definitely too simplistic? We are aware that the tbm_unions are
1216 * optimized out when the inputs are BitmapIndexScans.
1217 */
1218 totalCost = 0.0;
1219 selec = 0.0;
1220 foreach(l, path->bitmapquals)
1221 {
1222 Path *subpath = (Path *) lfirst(l);
1223 Cost subCost;
1225
1227
1228 selec += subselec;
1229
1230 totalCost += subCost;
1231 if (l != list_head(path->bitmapquals) &&
1233 totalCost += 100.0 * cpu_operator_cost;
1234 }
1235 path->bitmapselectivity = Min(selec, 1.0);
1236 path->path.rows = 0; /* per above, not used */
1237 path->path.startup_cost = totalCost;
1238 path->path.total_cost = totalCost;
1239}
Selectivity bitmapselectivity
Definition pathnodes.h:2137
List * bitmapquals
Definition pathnodes.h:2136

References BitmapOrPath::bitmapquals, BitmapOrPath::bitmapselectivity, cost_bitmap_tree_node(), cpu_operator_cost, fb(), 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 1114 of file costsize.c.

1115{
1116 if (IsA(path, IndexPath))
1117 {
1118 *cost = ((IndexPath *) path)->indextotalcost;
1119 *selec = ((IndexPath *) path)->indexselectivity;
1120
1121 /*
1122 * Charge a small amount per retrieved tuple to reflect the costs of
1123 * manipulating the bitmap. This is mostly to make sure that a bitmap
1124 * scan doesn't look to be the same cost as an indexscan to retrieve a
1125 * single tuple.
1126 */
1127 *cost += 0.1 * cpu_operator_cost * path->rows;
1128 }
1129 else if (IsA(path, BitmapAndPath))
1130 {
1131 *cost = path->total_cost;
1132 *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1133 }
1134 else if (IsA(path, BitmapOrPath))
1135 {
1136 *cost = path->total_cost;
1137 *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1138 }
1139 else
1140 {
1141 elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1142 *cost = *selec = 0; /* keep compiler quiet */
1143 }
1144}
#define nodeTag(nodeptr)
Definition nodes.h:139

References cpu_operator_cost, elog, ERROR, fb(), 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 1744 of file costsize.c.

1746{
1747 Cost startup_cost = 0;
1748 Cost run_cost = 0;
1751 uint64 enable_mask = 0;
1752
1753 /* Should only be applied to base relations that are CTEs */
1754 Assert(baserel->relid > 0);
1755 Assert(baserel->rtekind == RTE_CTE);
1756
1757 /* Mark the path with the correct row estimate */
1758 if (param_info)
1759 path->rows = param_info->ppi_rows;
1760 else
1761 path->rows = baserel->rows;
1762
1763 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1765
1766 /* Add scanning CPU costs */
1768
1769 startup_cost += qpqual_cost.startup;
1771 run_cost += cpu_per_tuple * baserel->tuples;
1772
1773 /* tlist eval costs are paid per output row, not per tuple scanned */
1774 startup_cost += path->pathtarget->cost.startup;
1775 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1776
1777 if (path->parallel_workers == 0)
1779 path->disabled_nodes =
1780 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1781 path->startup_cost = startup_cost;
1782 path->total_cost = startup_cost + run_cost;
1783}
@ RTE_CTE

References Assert, cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, root, Path::rows, RTE_CTE, Path::startup_cost, and Path::total_cost.

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

1564{
1565 Cost startup_cost = 0;
1566 Cost run_cost = 0;
1571 uint64 enable_mask = 0;
1572
1573 /* Should only be applied to base relations that are functions */
1574 Assert(baserel->relid > 0);
1575 rte = planner_rt_fetch(baserel->relid, root);
1576 Assert(rte->rtekind == RTE_FUNCTION);
1577
1578 /* Mark the path with the correct row estimate */
1579 if (param_info)
1580 path->rows = param_info->ppi_rows;
1581 else
1582 path->rows = baserel->rows;
1583
1584 /*
1585 * Estimate costs of executing the function expression(s).
1586 *
1587 * Currently, nodeFunctionscan.c always executes the functions to
1588 * completion before returning any rows, and caches the results in a
1589 * tuplestore. So the function eval cost is all startup cost, and per-row
1590 * costs are minimal.
1591 *
1592 * XXX in principle we ought to charge tuplestore spill costs if the
1593 * number of rows is large. However, given how phony our rowcount
1594 * estimates for functions tend to be, there's not a lot of point in that
1595 * refinement right now.
1596 */
1597 cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1598
1599 startup_cost += exprcost.startup + exprcost.per_tuple;
1600
1601 /* Add scanning CPU costs */
1603
1604 startup_cost += qpqual_cost.startup;
1606 run_cost += cpu_per_tuple * baserel->tuples;
1607
1608 /* tlist eval costs are paid per output row, not per tuple scanned */
1609 startup_cost += path->pathtarget->cost.startup;
1610 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1611
1612 if (path->parallel_workers == 0)
1614 path->disabled_nodes =
1615 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1616 path->startup_cost = startup_cost;
1617 path->total_cost = startup_cost + run_cost;
1618}
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition costsize.c:4929
@ RTE_FUNCTION
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:686

References Assert, cost_qual_eval_node(), cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, planner_rt_fetch, root, Path::rows, RTE_FUNCTION, Path::startup_cost, and Path::total_cost.

Referenced by create_functionscan_path().

◆ cost_gather()

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

Definition at line 429 of file costsize.c.

432{
433 Cost startup_cost = 0;
434 Cost run_cost = 0;
435
436 /* Mark the path with the correct row estimate */
437 if (rows)
438 path->path.rows = *rows;
439 else if (param_info)
440 path->path.rows = param_info->ppi_rows;
441 else
442 path->path.rows = rel->rows;
443
444 startup_cost = path->subpath->startup_cost;
445
446 run_cost = path->subpath->total_cost - path->subpath->startup_cost;
447
448 /* Parallel setup and communication cost. */
449 startup_cost += parallel_setup_cost;
450 run_cost += parallel_tuple_cost * path->path.rows;
451
453 + ((rel->pgs_mask & PGS_GATHER) != 0 ? 0 : 1);
454 path->path.startup_cost = startup_cost;
455 path->path.total_cost = (startup_cost + run_cost);
456}
double parallel_setup_cost
Definition costsize.c:136
double parallel_tuple_cost
Definition costsize.c:135
#define PGS_GATHER
Definition pathnodes.h:80
Path * subpath
Definition pathnodes.h:2342

References Path::disabled_nodes, fb(), parallel_setup_cost, parallel_tuple_cost, GatherPath::path, PGS_GATHER, RelOptInfo::pgs_mask, 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 469 of file costsize.c.

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

References Assert, cpu_operator_cost, Path::disabled_nodes, fb(), LOG2, GatherMergePath::num_workers, parallel_setup_cost, parallel_tuple_cost, GatherMergePath::path, PGS_GATHER_MERGE, RelOptInfo::pgs_mask, RelOptInfo::rows, Path::rows, Path::startup_cost, GatherMergePath::subpath, 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 3305 of file costsize.c.

3311{
3312 double output_tuples;
3313 Cost startup_cost;
3314 Cost total_cost;
3315
3316 output_tuples = numGroups;
3317 startup_cost = input_startup_cost;
3318 total_cost = input_total_cost;
3319
3320 /*
3321 * Charge one cpu_operator_cost per comparison per input tuple. We assume
3322 * all columns get compared at most of the tuples.
3323 */
3324 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3325
3326 /*
3327 * If there are quals (HAVING quals), account for their cost and
3328 * selectivity.
3329 */
3330 if (quals)
3331 {
3333
3334 cost_qual_eval(&qual_cost, quals, root);
3335 startup_cost += qual_cost.startup;
3336 total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3337
3340 quals,
3341 0,
3342 JOIN_INNER,
3343 NULL));
3344 }
3345
3346 path->rows = output_tuples;
3348 path->startup_cost = startup_cost;
3349 path->total_cost = total_cost;
3350}

References clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, Path::disabled_nodes, fb(), JOIN_INNER, root, Path::rows, 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 2052 of file costsize.c.

2058{
2059 Cost startup_cost,
2060 run_cost,
2062 double group_tuples,
2068 ListCell *l;
2069 bool unknown_varno = false;
2070
2071 Assert(presorted_keys > 0 && presorted_keys < list_length(pathkeys));
2072
2073 /*
2074 * We want to be sure the cost of a sort is never estimated as zero, even
2075 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
2076 */
2077 if (input_tuples < 2.0)
2078 input_tuples = 2.0;
2079
2080 /* Default estimate of number of groups, capped to one group per row. */
2081 input_groups = Min(input_tuples, DEFAULT_NUM_DISTINCT);
2082
2083 /*
2084 * Extract presorted keys as list of expressions.
2085 *
2086 * We need to be careful about Vars containing "varno 0" which might have
2087 * been introduced by generate_append_tlist, which would confuse
2088 * estimate_num_groups (in fact it'd fail for such expressions). See
2089 * recurse_set_operations which has to deal with the same issue.
2090 *
2091 * Unlike recurse_set_operations we can't access the original target list
2092 * here, and even if we could it's not very clear how useful would that be
2093 * for a set operation combining multiple tables. So we simply detect if
2094 * there are any expressions with "varno 0" and use the default
2095 * DEFAULT_NUM_DISTINCT in that case.
2096 *
2097 * We might also use either 1.0 (a single group) or input_tuples (each row
2098 * being a separate group), pretty much the worst and best case for
2099 * incremental sort. But those are extreme cases and using something in
2100 * between seems reasonable. Furthermore, generate_append_tlist is used
2101 * for set operations, which are likely to produce mostly unique output
2102 * anyway - from that standpoint the DEFAULT_NUM_DISTINCT is defensive
2103 * while maintaining lower startup cost.
2104 */
2105 foreach(l, pathkeys)
2106 {
2107 PathKey *key = (PathKey *) lfirst(l);
2109 linitial(key->pk_eclass->ec_members);
2110
2111 /*
2112 * Check if the expression contains Var with "varno 0" so that we
2113 * don't call estimate_num_groups in that case.
2114 */
2115 if (bms_is_member(0, pull_varnos(root, (Node *) member->em_expr)))
2116 {
2117 unknown_varno = true;
2118 break;
2119 }
2120
2121 /* expression not containing any Vars with "varno 0" */
2123
2124 if (foreach_current_index(l) + 1 >= presorted_keys)
2125 break;
2126 }
2127
2128 /* Estimate the number of groups with equal presorted keys. */
2129 if (!unknown_varno)
2131 NULL, NULL);
2132
2133 group_tuples = input_tuples / input_groups;
2135
2136 /*
2137 * Estimate the average cost of sorting of one group where presorted keys
2138 * are equal.
2139 */
2142 limit_tuples);
2143
2144 /*
2145 * Startup cost of incremental sort is the startup cost of its first group
2146 * plus the cost of its input.
2147 */
2148 startup_cost = group_startup_cost + input_startup_cost +
2150
2151 /*
2152 * After we started producing tuples from the first group, the cost of
2153 * producing all the tuples is given by the cost to finish processing this
2154 * group, plus the total cost to process the remaining groups, plus the
2155 * remaining cost of input.
2156 */
2159
2160 /*
2161 * Incremental sort adds some overhead by itself. Firstly, it has to
2162 * detect the sort groups. This is roughly equal to one extra copy and
2163 * comparison per tuple.
2164 */
2165 run_cost += (cpu_tuple_cost + comparison_cost) * input_tuples;
2166
2167 /*
2168 * Additionally, we charge double cpu_tuple_cost for each input group to
2169 * account for the tuplesort_reset that's performed after each group.
2170 */
2171 run_cost += 2.0 * cpu_tuple_cost * input_groups;
2172
2173 path->rows = input_tuples;
2174
2175 /*
2176 * We should not generate these paths when enable_incremental_sort=false.
2177 * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
2178 * it will have already affected the input path.
2179 */
2182
2183 path->startup_cost = startup_cost;
2184 path->total_cost = startup_cost + run_cost;
2185}
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:1950
#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(), fb(), foreach_current_index, 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 544 of file costsize.c.

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

References Assert, clamp_row_est(), compute_parallel_worker(), cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, extract_nonindex_conditions(), fb(), 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, Path::parallel_aware, Path::parallel_workers, IndexPath::path, Path::pathtype, PGS_CONSIDER_NONPARTIAL, PGS_INDEXONLYSCAN, PGS_INDEXSCAN, root, Path::rows, RTE_RELATION, Path::startup_cost, and Path::total_cost.

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2582 of file costsize.c.

2586{
2587 Cost startup_cost = input_startup_cost;
2589 double nbytes = relation_byte_size(tuples, width);
2590 double work_mem_bytes = work_mem * (Size) 1024;
2591
2592 if (path->parallel_workers == 0 &&
2593 path->parent != NULL &&
2594 (path->parent->pgs_mask & PGS_CONSIDER_NONPARTIAL) == 0)
2595 enabled = false;
2596
2597 path->rows = tuples;
2598
2599 /*
2600 * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2601 * reflect bookkeeping overhead. (This rate must be more than what
2602 * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2603 * if it is exactly the same then there will be a cost tie between
2604 * nestloop with A outer, materialized B inner and nestloop with B outer,
2605 * materialized A inner. The extra cost ensures we'll prefer
2606 * materializing the smaller rel.) Note that this is normally a good deal
2607 * less than cpu_tuple_cost; which is OK because a Material plan node
2608 * doesn't do qual-checking or projection, so it's got less overhead than
2609 * most plan nodes.
2610 */
2611 run_cost += 2 * cpu_operator_cost * tuples;
2612
2613 /*
2614 * If we will spill to disk, charge at the rate of seq_page_cost per page.
2615 * This cost is assumed to be evenly spread through the plan run phase,
2616 * which isn't exactly accurate but our cost model doesn't allow for
2617 * nonuniform costs within the run phase.
2618 */
2619 if (nbytes > work_mem_bytes)
2620 {
2621 double npages = ceil(nbytes / BLCKSZ);
2622
2623 run_cost += seq_page_cost * npages;
2624 }
2625
2626 path->disabled_nodes = input_disabled_nodes + (enabled ? 0 : 1);
2627 path->startup_cost = startup_cost;
2628 path->total_cost = startup_cost + run_cost;
2629}

References cpu_operator_cost, Path::disabled_nodes, fb(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, 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 2645 of file costsize.c.

2647{
2649 ListCell *lc;
2650 Cost input_startup_cost = mpath->subpath->startup_cost;
2651 Cost input_total_cost = mpath->subpath->total_cost;
2652 double tuples = mpath->subpath->rows;
2653 Cardinality est_calls = mpath->est_calls;
2654 int width = mpath->subpath->pathtarget->width;
2655
2656 double hash_mem_bytes;
2657 double est_entry_bytes;
2659 Cardinality ndistinct;
2660 double evict_ratio;
2661 double hit_ratio;
2662 Cost startup_cost;
2663 Cost total_cost;
2664
2665 /* available cache space */
2667
2668 /*
2669 * Set the number of bytes each cache entry should consume in the cache.
2670 * To provide us with better estimations on how many cache entries we can
2671 * store at once, we make a call to the executor here to ask it what
2672 * memory overheads there are for a single cache entry.
2673 */
2674 est_entry_bytes = relation_byte_size(tuples, width) +
2676
2677 /* include the estimated width for the cache keys */
2678 foreach(lc, mpath->param_exprs)
2680
2681 /* estimate on the upper limit of cache entries we can hold at once */
2683
2684 /* estimate on the distinct number of parameter values */
2685 ndistinct = estimate_num_groups(root, mpath->param_exprs, est_calls, NULL,
2686 &estinfo);
2687
2688 /*
2689 * When the estimation fell back on using a default value, it's a bit too
2690 * risky to assume that it's ok to use a Memoize node. The use of a
2691 * default could cause us to use a Memoize node when it's really
2692 * inappropriate to do so. If we see that this has been done, then we'll
2693 * assume that every call will have unique parameters, which will almost
2694 * certainly mean a MemoizePath will never survive add_path().
2695 */
2696 if ((estinfo.flags & SELFLAG_USED_DEFAULT) != 0)
2697 ndistinct = est_calls;
2698
2699 /* Remember the ndistinct estimate for EXPLAIN */
2700 mpath->est_unique_keys = ndistinct;
2701
2702 /*
2703 * Since we've already estimated the maximum number of entries we can
2704 * store at once and know the estimated number of distinct values we'll be
2705 * called with, we'll take this opportunity to set the path's est_entries.
2706 * This will ultimately determine the hash table size that the executor
2707 * will use. If we leave this at zero, the executor will just choose the
2708 * size itself. Really this is not the right place to do this, but it's
2709 * convenient since everything is already calculated.
2710 */
2711 mpath->est_entries = Min(Min(ndistinct, est_cache_entries),
2713
2714 /*
2715 * When the number of distinct parameter values is above the amount we can
2716 * store in the cache, then we'll have to evict some entries from the
2717 * cache. This is not free. Here we estimate how often we'll incur the
2718 * cost of that eviction.
2719 */
2720 evict_ratio = 1.0 - Min(est_cache_entries, ndistinct) / ndistinct;
2721
2722 /*
2723 * In order to estimate how costly a single scan will be, we need to
2724 * attempt to estimate what the cache hit ratio will be. To do that we
2725 * must look at how many scans are estimated in total for this node and
2726 * how many of those scans we expect to get a cache hit.
2727 */
2728 hit_ratio = ((est_calls - ndistinct) / est_calls) *
2729 (est_cache_entries / Max(ndistinct, est_cache_entries));
2730
2731 /* Remember the hit ratio estimate for EXPLAIN */
2732 mpath->est_hit_ratio = hit_ratio;
2733
2734 Assert(hit_ratio >= 0 && hit_ratio <= 1.0);
2735
2736 /*
2737 * Set the total_cost accounting for the expected cache hit ratio. We
2738 * also add on a cpu_operator_cost to account for a cache lookup. This
2739 * will happen regardless of whether it's a cache hit or not.
2740 */
2741 total_cost = input_total_cost * (1.0 - hit_ratio) + cpu_operator_cost;
2742
2743 /* Now adjust the total cost to account for cache evictions */
2744
2745 /* Charge a cpu_tuple_cost for evicting the actual cache entry */
2746 total_cost += cpu_tuple_cost * evict_ratio;
2747
2748 /*
2749 * Charge a 10th of cpu_operator_cost to evict every tuple in that entry.
2750 * The per-tuple eviction is really just a pfree, so charging a whole
2751 * cpu_operator_cost seems a little excessive.
2752 */
2753 total_cost += cpu_operator_cost / 10.0 * evict_ratio * tuples;
2754
2755 /*
2756 * Now adjust for storing things in the cache, since that's not free
2757 * either. Everything must go in the cache. We don't proportion this
2758 * over any ratio, just apply it once for the scan. We charge a
2759 * cpu_tuple_cost for the creation of the cache entry and also a
2760 * cpu_operator_cost for each tuple we expect to cache.
2761 */
2762 total_cost += cpu_tuple_cost + cpu_operator_cost * tuples;
2763
2764 /*
2765 * Getting the first row must be also be proportioned according to the
2766 * expected cache hit ratio.
2767 */
2768 startup_cost = input_startup_cost * (1.0 - hit_ratio);
2769
2770 /*
2771 * Additionally we charge a cpu_tuple_cost to account for cache lookups,
2772 * which we'll do regardless of whether it was a cache hit or not.
2773 */
2774 startup_cost += cpu_tuple_cost;
2775
2776 *rescan_startup_cost = startup_cost;
2777 *rescan_total_cost = total_cost;
2778}
#define PG_UINT32_MAX
Definition c.h:604
static int32 get_expr_width(PlannerInfo *root, const Node *expr)
Definition costsize.c:6552
size_t get_hash_memory_limit(void)
Definition nodeHash.c:3621
double ExecEstimateCacheEntryOverheadBytes(double ntuples)
double Cardinality
Definition nodes.h:262
#define SELFLAG_USED_DEFAULT
Definition selfuncs.h:76

References Assert, cpu_operator_cost, cpu_tuple_cost, estimate_num_groups(), ExecEstimateCacheEntryOverheadBytes(), fb(), get_expr_width(), get_hash_memory_limit(), lfirst, Max, Min, PG_UINT32_MAX, relation_byte_size(), root, and SELFLAG_USED_DEFAULT.

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

2529{
2530 RelOptInfo *rel = path->parent;
2531 Cost startup_cost = 0;
2532 Cost run_cost = 0;
2534 double N;
2535 double logN;
2537
2538 if (path->parallel_workers == 0)
2540
2541 /*
2542 * Avoid log(0)...
2543 */
2544 N = (n_streams < 2) ? 2.0 : (double) n_streams;
2545 logN = LOG2(N);
2546
2547 /* Assumed cost per tuple comparison */
2549
2550 /* Heap creation cost */
2551 startup_cost += comparison_cost * N * logN;
2552
2553 /* Per-tuple heap maintenance cost */
2554 run_cost += tuples * comparison_cost * logN;
2555
2556 /*
2557 * Although MergeAppend does not do any selection or projection, it's not
2558 * free; add a small per-tuple overhead.
2559 */
2560 run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2561
2562 path->disabled_nodes =
2563 (rel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
2565 path->startup_cost = startup_cost + input_startup_cost;
2566 path->total_cost = startup_cost + run_cost + input_total_cost;
2567}
#define PGS_MERGE_APPEND
Definition pathnodes.h:79

References APPEND_CPU_COST_MULTIPLIER, cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, fb(), LOG2, Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, RelOptInfo::pgs_mask, PGS_MERGE_APPEND, 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 1790 of file costsize.c.

1792{
1793 Cost startup_cost = 0;
1794 Cost run_cost = 0;
1797 uint64 enable_mask = 0;
1798
1799 /* Should only be applied to base relations that are Tuplestores */
1800 Assert(baserel->relid > 0);
1801 Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1802
1803 /* Mark the path with the correct row estimate */
1804 if (param_info)
1805 path->rows = param_info->ppi_rows;
1806 else
1807 path->rows = baserel->rows;
1808
1809 /* Charge one CPU tuple cost per row for tuplestore manipulation */
1811
1812 /* Add scanning CPU costs */
1814
1815 startup_cost += qpqual_cost.startup;
1817 run_cost += cpu_per_tuple * baserel->tuples;
1818
1819 if (path->parallel_workers == 0)
1821 path->disabled_nodes =
1822 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1823 path->startup_cost = startup_cost;
1824 path->total_cost = startup_cost + run_cost;
1825}
@ RTE_NAMEDTUPLESTORE

References Assert, cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, root, Path::rows, RTE_NAMEDTUPLESTORE, Path::startup_cost, and Path::total_cost.

Referenced by create_namedtuplestorescan_path().

◆ cost_qual_eval()

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

Definition at line 4903 of file costsize.c.

4904{
4905 cost_qual_eval_context context;
4906 ListCell *l;
4907
4908 context.root = root;
4909 context.total.startup = 0;
4910 context.total.per_tuple = 0;
4911
4912 /* We don't charge any cost for the implicit ANDing at top level ... */
4913
4914 foreach(l, quals)
4915 {
4916 Node *qual = (Node *) lfirst(l);
4917
4918 cost_qual_eval_walker(qual, &context);
4919 }
4920
4921 *cost = context.total;
4922}
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition costsize.c:4943
Cost per_tuple
Definition pathnodes.h:121
Cost startup
Definition pathnodes.h:120
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 4943 of file costsize.c.

4944{
4945 if (node == NULL)
4946 return false;
4947
4948 /*
4949 * RestrictInfo nodes contain an eval_cost field reserved for this
4950 * routine's use, so that it's not necessary to evaluate the qual clause's
4951 * cost more than once. If the clause's cost hasn't been computed yet,
4952 * the field's startup value will contain -1.
4953 */
4954 if (IsA(node, RestrictInfo))
4955 {
4956 RestrictInfo *rinfo = (RestrictInfo *) node;
4957
4958 if (rinfo->eval_cost.startup < 0)
4959 {
4961
4962 locContext.root = context->root;
4963 locContext.total.startup = 0;
4964 locContext.total.per_tuple = 0;
4965
4966 /*
4967 * For an OR clause, recurse into the marked-up tree so that we
4968 * set the eval_cost for contained RestrictInfos too.
4969 */
4970 if (rinfo->orclause)
4971 cost_qual_eval_walker((Node *) rinfo->orclause, &locContext);
4972 else
4974
4975 /*
4976 * If the RestrictInfo is marked pseudoconstant, it will be tested
4977 * only once, so treat its cost as all startup cost.
4978 */
4979 if (rinfo->pseudoconstant)
4980 {
4981 /* count one execution during startup */
4982 locContext.total.startup += locContext.total.per_tuple;
4983 locContext.total.per_tuple = 0;
4984 }
4985 rinfo->eval_cost = locContext.total;
4986 }
4987 context->total.startup += rinfo->eval_cost.startup;
4988 context->total.per_tuple += rinfo->eval_cost.per_tuple;
4989 /* do NOT recurse into children */
4990 return false;
4991 }
4992
4993 /*
4994 * For each operator or function node in the given tree, we charge the
4995 * estimated execution cost given by pg_proc.procost (remember to multiply
4996 * this by cpu_operator_cost).
4997 *
4998 * Vars and Consts are charged zero, and so are boolean operators (AND,
4999 * OR, NOT). Simplistic, but a lot better than no model at all.
5000 *
5001 * Should we try to account for the possibility of short-circuit
5002 * evaluation of AND/OR? Probably *not*, because that would make the
5003 * results depend on the clause ordering, and we are not in any position
5004 * to expect that the current ordering of the clauses is the one that's
5005 * going to end up being used. The above per-RestrictInfo caching would
5006 * not mix well with trying to re-order clauses anyway.
5007 *
5008 * Another issue that is entirely ignored here is that if a set-returning
5009 * function is below top level in the tree, the functions/operators above
5010 * it will need to be evaluated multiple times. In practical use, such
5011 * cases arise so seldom as to not be worth the added complexity needed;
5012 * moreover, since our rowcount estimates for functions tend to be pretty
5013 * phony, the results would also be pretty phony.
5014 */
5015 if (IsA(node, FuncExpr))
5016 {
5017 add_function_cost(context->root, ((FuncExpr *) node)->funcid, node,
5018 &context->total);
5019 }
5020 else if (IsA(node, OpExpr) ||
5021 IsA(node, DistinctExpr) ||
5022 IsA(node, NullIfExpr))
5023 {
5024 /* rely on struct equivalence to treat these all alike */
5025 set_opfuncid((OpExpr *) node);
5026 add_function_cost(context->root, ((OpExpr *) node)->opfuncid, node,
5027 &context->total);
5028 }
5029 else if (IsA(node, ScalarArrayOpExpr))
5030 {
5031 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
5032 Node *arraynode = (Node *) lsecond(saop->args);
5035 double estarraylen = estimate_array_length(context->root, arraynode);
5036
5037 set_sa_opfuncid(saop);
5038 sacosts.startup = sacosts.per_tuple = 0;
5039 add_function_cost(context->root, saop->opfuncid, NULL,
5040 &sacosts);
5041
5042 if (OidIsValid(saop->hashfuncid))
5043 {
5044 /* Handle costs for hashed ScalarArrayOpExpr */
5045 hcosts.startup = hcosts.per_tuple = 0;
5046
5047 add_function_cost(context->root, saop->hashfuncid, NULL, &hcosts);
5048 context->total.startup += sacosts.startup + hcosts.startup;
5049
5050 /* Estimate the cost of building the hashtable. */
5051 context->total.startup += estarraylen * hcosts.per_tuple;
5052
5053 /*
5054 * XXX should we charge a little bit for sacosts.per_tuple when
5055 * building the table, or is it ok to assume there will be zero
5056 * hash collision?
5057 */
5058
5059 /*
5060 * Charge for hashtable lookups. Charge a single hash and a
5061 * single comparison.
5062 */
5063 context->total.per_tuple += hcosts.per_tuple + sacosts.per_tuple;
5064 }
5065 else
5066 {
5067 /*
5068 * Estimate that the operator will be applied to about half of the
5069 * array elements before the answer is determined.
5070 */
5071 context->total.startup += sacosts.startup;
5072 context->total.per_tuple += sacosts.per_tuple *
5073 estimate_array_length(context->root, arraynode) * 0.5;
5074 }
5075 }
5076 else if (IsA(node, Aggref) ||
5077 IsA(node, WindowFunc))
5078 {
5079 /*
5080 * Aggref and WindowFunc nodes are (and should be) treated like Vars,
5081 * ie, zero execution cost in the current model, because they behave
5082 * essentially like Vars at execution. We disregard the costs of
5083 * their input expressions for the same reason. The actual execution
5084 * costs of the aggregate/window functions and their arguments have to
5085 * be factored into plan-node-specific costing of the Agg or WindowAgg
5086 * plan node.
5087 */
5088 return false; /* don't recurse into children */
5089 }
5090 else if (IsA(node, GroupingFunc))
5091 {
5092 /* Treat this as having cost 1 */
5093 context->total.per_tuple += cpu_operator_cost;
5094 return false; /* don't recurse into children */
5095 }
5096 else if (IsA(node, CoerceViaIO))
5097 {
5098 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
5099 Oid iofunc;
5100 Oid typioparam;
5101 bool typisvarlena;
5102
5103 /* check the result type's input function */
5104 getTypeInputInfo(iocoerce->resulttype,
5105 &iofunc, &typioparam);
5106 add_function_cost(context->root, iofunc, NULL,
5107 &context->total);
5108 /* check the input type's output function */
5109 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
5110 &iofunc, &typisvarlena);
5111 add_function_cost(context->root, iofunc, NULL,
5112 &context->total);
5113 }
5114 else if (IsA(node, ArrayCoerceExpr))
5115 {
5118
5120 context->root);
5121 context->total.startup += perelemcost.startup;
5122 if (perelemcost.per_tuple > 0)
5123 context->total.per_tuple += perelemcost.per_tuple *
5124 estimate_array_length(context->root, (Node *) acoerce->arg);
5125 }
5126 else if (IsA(node, RowCompareExpr))
5127 {
5128 /* Conservatively assume we will check all the columns */
5130 ListCell *lc;
5131
5132 foreach(lc, rcexpr->opnos)
5133 {
5134 Oid opid = lfirst_oid(lc);
5135
5137 &context->total);
5138 }
5139 }
5140 else if (IsA(node, MinMaxExpr) ||
5141 IsA(node, SQLValueFunction) ||
5142 IsA(node, XmlExpr) ||
5143 IsA(node, CoerceToDomain) ||
5144 IsA(node, NextValueExpr) ||
5145 IsA(node, JsonExpr))
5146 {
5147 /* Treat all these as having cost 1 */
5148 context->total.per_tuple += cpu_operator_cost;
5149 }
5150 else if (IsA(node, SubLink))
5151 {
5152 /* This routine should not be applied to un-planned expressions */
5153 elog(ERROR, "cannot handle unplanned sub-select");
5154 }
5155 else if (IsA(node, SubPlan))
5156 {
5157 /*
5158 * A subplan node in an expression typically indicates that the
5159 * subplan will be executed on each evaluation, so charge accordingly.
5160 * (Sub-selects that can be executed as InitPlans have already been
5161 * removed from the expression.)
5162 */
5163 SubPlan *subplan = (SubPlan *) node;
5164
5165 context->total.startup += subplan->startup_cost;
5166 context->total.per_tuple += subplan->per_call_cost;
5167
5168 /*
5169 * We don't want to recurse into the testexpr, because it was already
5170 * counted in the SubPlan node's costs. So we're done.
5171 */
5172 return false;
5173 }
5174 else if (IsA(node, AlternativeSubPlan))
5175 {
5176 /*
5177 * Arbitrarily use the first alternative plan for costing. (We should
5178 * certainly only include one alternative, and we don't yet have
5179 * enough information to know which one the executor is most likely to
5180 * use.)
5181 */
5183
5184 return cost_qual_eval_walker((Node *) linitial(asplan->subplans),
5185 context);
5186 }
5187 else if (IsA(node, PlaceHolderVar))
5188 {
5189 /*
5190 * A PlaceHolderVar should be given cost zero when considering general
5191 * expression evaluation costs. The expense of doing the contained
5192 * expression is charged as part of the tlist eval costs of the scan
5193 * or join where the PHV is first computed (see set_rel_width and
5194 * add_placeholders_to_joinrel). If we charged it again here, we'd be
5195 * double-counting the cost for each level of plan that the PHV
5196 * bubbles up through. Hence, return without recursing into the
5197 * phexpr.
5198 */
5199 return false;
5200 }
5201
5202 /* recurse into children */
5203 return expression_tree_walker(node, cost_qual_eval_walker, context);
5204}
#define OidIsValid(objectId)
Definition c.h:788
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:2360
unsigned int Oid
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition selfuncs.c:2223
Cost startup_cost
Definition primnodes.h:1126
Cost per_call_cost
Definition primnodes.h:1127

References add_function_cost(), CoerceViaIO::arg, ScalarArrayOpExpr::args, RestrictInfo::clause, cost_qual_eval_node(), cost_qual_eval_walker(), cpu_operator_cost, elog, ERROR, estimate_array_length(), expression_tree_walker, exprType(), fb(), 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, 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 1874 of file costsize.c.

1875{
1876 Cost startup_cost;
1877 Cost total_cost;
1878 double total_rows;
1879 uint64 enable_mask = 0;
1880
1881 /* We probably have decent estimates for the non-recursive term */
1882 startup_cost = nrterm->startup_cost;
1883 total_cost = nrterm->total_cost;
1884 total_rows = nrterm->rows;
1885
1886 /*
1887 * We arbitrarily assume that about 10 recursive iterations will be
1888 * needed, and that we've managed to get a good fix on the cost and output
1889 * size of each one of them. These are mighty shaky assumptions but it's
1890 * hard to see how to do better.
1891 */
1892 total_cost += 10 * rterm->total_cost;
1893 total_rows += 10 * rterm->rows;
1894
1895 /*
1896 * Also charge cpu_tuple_cost per row to account for the costs of
1897 * manipulating the tuplestores. (We don't worry about possible
1898 * spill-to-disk costs.)
1899 */
1900 total_cost += cpu_tuple_cost * total_rows;
1901
1902 if (runion->parallel_workers == 0)
1904 runion->disabled_nodes =
1905 (runion->parent->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1906 runion->startup_cost = startup_cost;
1907 runion->total_cost = total_cost;
1908 runion->rows = total_rows;
1909 runion->pathtarget->width = Max(nrterm->pathtarget->width,
1910 rterm->pathtarget->width);
1911}

References cpu_tuple_cost, fb(), Max, and PGS_CONSIDER_NONPARTIAL.

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

4791{
4792 switch (path->pathtype)
4793 {
4794 case T_FunctionScan:
4795
4796 /*
4797 * Currently, nodeFunctionscan.c always executes the function to
4798 * completion before returning any rows, and caches the results in
4799 * a tuplestore. So the function eval cost is all startup cost
4800 * and isn't paid over again on rescans. However, all run costs
4801 * will be paid over again.
4802 */
4804 *rescan_total_cost = path->total_cost - path->startup_cost;
4805 break;
4806 case T_HashJoin:
4807
4808 /*
4809 * If it's a single-batch join, we don't need to rebuild the hash
4810 * table during a rescan.
4811 */
4812 if (((HashPath *) path)->num_batches == 1)
4813 {
4814 /* Startup cost is exactly the cost of hash table building */
4816 *rescan_total_cost = path->total_cost - path->startup_cost;
4817 }
4818 else
4819 {
4820 /* Otherwise, no special treatment */
4821 *rescan_startup_cost = path->startup_cost;
4822 *rescan_total_cost = path->total_cost;
4823 }
4824 break;
4825 case T_CteScan:
4826 case T_WorkTableScan:
4827 {
4828 /*
4829 * These plan types materialize their final result in a
4830 * tuplestore or tuplesort object. So the rescan cost is only
4831 * cpu_tuple_cost per tuple, unless the result is large enough
4832 * to spill to disk.
4833 */
4834 Cost run_cost = cpu_tuple_cost * path->rows;
4835 double nbytes = relation_byte_size(path->rows,
4836 path->pathtarget->width);
4837 double work_mem_bytes = work_mem * (Size) 1024;
4838
4839 if (nbytes > work_mem_bytes)
4840 {
4841 /* It will spill, so account for re-read cost */
4842 double npages = ceil(nbytes / BLCKSZ);
4843
4844 run_cost += seq_page_cost * npages;
4845 }
4847 *rescan_total_cost = run_cost;
4848 }
4849 break;
4850 case T_Material:
4851 case T_Sort:
4852 {
4853 /*
4854 * These plan types not only materialize their results, but do
4855 * not implement qual filtering or projection. So they are
4856 * even cheaper to rescan than the ones above. We charge only
4857 * cpu_operator_cost per tuple. (Note: keep that in sync with
4858 * the run_cost charge in cost_sort, and also see comments in
4859 * cost_material before you change it.)
4860 */
4861 Cost run_cost = cpu_operator_cost * path->rows;
4862 double nbytes = relation_byte_size(path->rows,
4863 path->pathtarget->width);
4864 double work_mem_bytes = work_mem * (Size) 1024;
4865
4866 if (nbytes > work_mem_bytes)
4867 {
4868 /* It will spill, so account for re-read cost */
4869 double npages = ceil(nbytes / BLCKSZ);
4870
4871 run_cost += seq_page_cost * npages;
4872 }
4874 *rescan_total_cost = run_cost;
4875 }
4876 break;
4877 case T_Memoize:
4878 /* All the hard work is done by cost_memoize_rescan */
4881 break;
4882 default:
4883 *rescan_startup_cost = path->startup_cost;
4884 *rescan_total_cost = path->total_cost;
4885 break;
4886 }
4887}
static void cost_memoize_rescan(PlannerInfo *root, MemoizePath *mpath, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition costsize.c:2645

References cost_memoize_rescan(), cpu_operator_cost, cpu_tuple_cost, fb(), 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 1832 of file costsize.c.

1834{
1835 Cost startup_cost = 0;
1836 Cost run_cost = 0;
1839 uint64 enable_mask = 0;
1840
1841 /* Should only be applied to RTE_RESULT base relations */
1842 Assert(baserel->relid > 0);
1843 Assert(baserel->rtekind == RTE_RESULT);
1844
1845 /* Mark the path with the correct row estimate */
1846 if (param_info)
1847 path->rows = param_info->ppi_rows;
1848 else
1849 path->rows = baserel->rows;
1850
1851 /* We charge qual cost plus cpu_tuple_cost */
1853
1854 startup_cost += qpqual_cost.startup;
1856 run_cost += cpu_per_tuple * baserel->tuples;
1857
1858 if (path->parallel_workers == 0)
1860 path->disabled_nodes =
1861 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1862 path->startup_cost = startup_cost;
1863 path->total_cost = startup_cost + run_cost;
1864}
@ RTE_RESULT

References Assert, cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, root, Path::rows, RTE_RESULT, Path::startup_cost, and Path::total_cost.

Referenced by create_resultscan_path().

◆ cost_samplescan()

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

Definition at line 348 of file costsize.c.

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

References Assert, cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, planner_rt_fetch, root, Path::rows, RTE_RELATION, Path::startup_cost, and Path::total_cost.

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

References Assert, clamp_row_est(), cpu_tuple_cost, Path::disabled_nodes, fb(), get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, PGS_SEQSCAN, root, Path::rows, RTE_RELATION, Path::startup_cost, and Path::total_cost.

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

2206{
2207 Cost startup_cost;
2208 Cost run_cost;
2209
2210 cost_tuplesort(&startup_cost, &run_cost,
2211 tuples, width,
2213 limit_tuples);
2214
2215 startup_cost += input_cost;
2216
2217 /*
2218 * We can ignore PGS_CONSIDER_NONPARTIAL here, because if it's relevant,
2219 * it will have already affected the input path.
2220 */
2221 path->rows = tuples;
2223 path->startup_cost = startup_cost;
2224 path->total_cost = startup_cost + run_cost;
2225}
bool enable_sort
Definition costsize.c:150

References cost_tuplesort(), Path::disabled_nodes, enable_sort, fb(), 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 4681 of file costsize.c.

4682{
4684
4685 /*
4686 * Figure any cost for evaluating the testexpr.
4687 *
4688 * Usually, SubPlan nodes are built very early, before we have constructed
4689 * any RelOptInfos for the parent query level, which means the parent root
4690 * does not yet contain enough information to safely consult statistics.
4691 * Therefore, we pass root as NULL here. cost_qual_eval() is already
4692 * well-equipped to handle a NULL root.
4693 *
4694 * One exception is SubPlan nodes built for the initplans of MIN/MAX
4695 * aggregates from indexes (cf. SS_make_initplan_from_plan). In this
4696 * case, having a NULL root is safe because testexpr will be NULL.
4697 * Besides, an initplan will by definition not consult anything from the
4698 * parent plan.
4699 */
4701 make_ands_implicit((Expr *) subplan->testexpr),
4702 NULL);
4703
4704 if (subplan->useHashTable)
4705 {
4706 /*
4707 * If we are using a hash table for the subquery outputs, then the
4708 * cost of evaluating the query is a one-time cost. We charge one
4709 * cpu_operator_cost per tuple for the work of loading the hashtable,
4710 * too.
4711 */
4712 sp_cost.startup += plan->total_cost +
4713 cpu_operator_cost * plan->plan_rows;
4714
4715 /*
4716 * The per-tuple costs include the cost of evaluating the lefthand
4717 * expressions, plus the cost of probing the hashtable. We already
4718 * accounted for the lefthand expressions as part of the testexpr, and
4719 * will also have counted one cpu_operator_cost for each comparison
4720 * operator. That is probably too low for the probing cost, but it's
4721 * hard to make a better estimate, so live with it for now.
4722 */
4723 }
4724 else
4725 {
4726 /*
4727 * Otherwise we will be rescanning the subplan output on each
4728 * evaluation. We need to estimate how much of the output we will
4729 * actually need to scan. NOTE: this logic should agree with the
4730 * tuple_fraction estimates used by make_subplan() in
4731 * plan/subselect.c.
4732 */
4733 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4734
4735 if (subplan->subLinkType == EXISTS_SUBLINK)
4736 {
4737 /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4738 sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4739 }
4740 else if (subplan->subLinkType == ALL_SUBLINK ||
4741 subplan->subLinkType == ANY_SUBLINK)
4742 {
4743 /* assume we need 50% of the tuples */
4744 sp_cost.per_tuple += 0.50 * plan_run_cost;
4745 /* also charge a cpu_operator_cost per row examined */
4746 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4747 }
4748 else
4749 {
4750 /* assume we need all tuples */
4751 sp_cost.per_tuple += plan_run_cost;
4752 }
4753
4754 /*
4755 * Also account for subplan's startup cost. If the subplan is
4756 * uncorrelated or undirect correlated, AND its topmost node is one
4757 * that materializes its output, assume that we'll only need to pay
4758 * its startup cost once; otherwise assume we pay the startup cost
4759 * every time.
4760 */
4761 if (subplan->parParam == NIL &&
4763 sp_cost.startup += plan->startup_cost;
4764 else
4765 sp_cost.per_tuple += plan->startup_cost;
4766 }
4767
4768 subplan->startup_cost = sp_cost.startup;
4769 subplan->per_call_cost = sp_cost.per_tuple;
4770}
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, fb(), make_ands_implicit(), NIL, nodeTag, SubPlan::parParam, SubPlan::per_call_cost, plan, 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 1477 of file costsize.c.

1480{
1481 Cost startup_cost;
1482 Cost run_cost;
1483 List *qpquals;
1486 uint64 enable_mask = 0;
1487
1488 /* Should only be applied to base relations that are subqueries */
1489 Assert(baserel->relid > 0);
1490 Assert(baserel->rtekind == RTE_SUBQUERY);
1491
1492 /*
1493 * We compute the rowcount estimate as the subplan's estimate times the
1494 * selectivity of relevant restriction clauses. In simple cases this will
1495 * come out the same as baserel->rows; but when dealing with parallelized
1496 * paths we must do it like this to get the right answer.
1497 */
1498 if (param_info)
1499 qpquals = list_concat_copy(param_info->ppi_clauses,
1500 baserel->baserestrictinfo);
1501 else
1502 qpquals = baserel->baserestrictinfo;
1503
1504 path->path.rows = clamp_row_est(path->subpath->rows *
1506 qpquals,
1507 0,
1508 JOIN_INNER,
1509 NULL));
1510
1511 /*
1512 * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1513 * any restriction clauses and tlist that will be attached to the
1514 * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1515 * projection overhead.
1516 */
1517 if (path->path.parallel_workers == 0)
1520 + (((baserel->pgs_mask & enable_mask) != enable_mask) ? 1 : 0);
1521 path->path.startup_cost = path->subpath->startup_cost;
1522 path->path.total_cost = path->subpath->total_cost;
1523
1524 /*
1525 * However, if there are no relevant restriction clauses and the
1526 * pathtarget is trivial, then we expect that setrefs.c will optimize away
1527 * the SubqueryScan plan node altogether, so we should just make its cost
1528 * and rowcount equal to the input path's.
1529 *
1530 * Note: there are some edge cases where createplan.c will apply a
1531 * different targetlist to the SubqueryScan node, thus falsifying our
1532 * current estimate of whether the target is trivial, and making the cost
1533 * estimate (though not the rowcount) wrong. It does not seem worth the
1534 * extra complication to try to account for that exactly, especially since
1535 * that behavior falsifies other cost estimates as well.
1536 */
1537 if (qpquals == NIL && trivial_pathtarget)
1538 return;
1539
1541
1542 startup_cost = qpqual_cost.startup;
1544 run_cost = cpu_per_tuple * path->subpath->rows;
1545
1546 /* tlist eval costs are paid per output row, not per tuple scanned */
1547 startup_cost += path->path.pathtarget->cost.startup;
1548 run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1549
1550 path->path.startup_cost += startup_cost;
1551 path->path.total_cost += startup_cost + run_cost;
1552}
List * list_concat_copy(const List *list1, const List *list2)
Definition list.c:598
@ RTE_SUBQUERY

References Assert, clamp_row_est(), clauselist_selectivity(), cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), JOIN_INNER, list_concat_copy(), NIL, Path::parallel_workers, SubqueryScanPath::path, PGS_CONSIDER_NONPARTIAL, root, Path::rows, RTE_SUBQUERY, 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 1628 of file costsize.c.

1630{
1631 Cost startup_cost = 0;
1632 Cost run_cost = 0;
1637 uint64 enable_mask = 0;
1638
1639 /* Should only be applied to base relations that are functions */
1640 Assert(baserel->relid > 0);
1641 rte = planner_rt_fetch(baserel->relid, root);
1642 Assert(rte->rtekind == RTE_TABLEFUNC);
1643
1644 /* Mark the path with the correct row estimate */
1645 if (param_info)
1646 path->rows = param_info->ppi_rows;
1647 else
1648 path->rows = baserel->rows;
1649
1650 /*
1651 * Estimate costs of executing the table func expression(s).
1652 *
1653 * XXX in principle we ought to charge tuplestore spill costs if the
1654 * number of rows is large. However, given how phony our rowcount
1655 * estimates for tablefuncs tend to be, there's not a lot of point in that
1656 * refinement right now.
1657 */
1658 cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1659
1660 startup_cost += exprcost.startup + exprcost.per_tuple;
1661
1662 /* Add scanning CPU costs */
1664
1665 startup_cost += qpqual_cost.startup;
1667 run_cost += cpu_per_tuple * baserel->tuples;
1668
1669 /* tlist eval costs are paid per output row, not per tuple scanned */
1670 startup_cost += path->pathtarget->cost.startup;
1671 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1672
1673 if (path->parallel_workers == 0)
1675 path->disabled_nodes =
1676 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1677 path->startup_cost = startup_cost;
1678 path->total_cost = startup_cost + run_cost;
1679}
@ RTE_TABLEFUNC

References Assert, cost_qual_eval_node(), cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, planner_rt_fetch, root, Path::rows, RTE_TABLEFUNC, Path::startup_cost, and Path::total_cost.

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

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

Definition at line 1360 of file costsize.c.

1363{
1364 Selectivity selectivity;
1365 double pages;
1366 Cost startup_cost;
1372 double ntuples;
1373 double nseqpages;
1374 double spc_random_page_cost;
1375 double spc_seq_page_cost;
1377
1378 /* Should only be applied to base relations */
1379 Assert(baserel->relid > 0);
1380 Assert(baserel->rtekind == RTE_RELATION);
1381
1382 /* Mark the path with the correct row estimate */
1383 if (param_info)
1384 path->rows = param_info->ppi_rows;
1385 else
1386 path->rows = baserel->rows;
1387
1388 /* Count how many tuples and pages we expect to scan */
1389 selectivity = clauselist_selectivity(root, tidrangequals, baserel->relid,
1390 JOIN_INNER, NULL);
1391 pages = ceil(selectivity * baserel->pages);
1392
1393 if (pages <= 0.0)
1394 pages = 1.0;
1395
1396 /*
1397 * The first page in a range requires a random seek, but each subsequent
1398 * page is just a normal sequential page read. NOTE: it's desirable for
1399 * TID Range Scans to cost more than the equivalent Sequential Scans,
1400 * because Seq Scans have some performance advantages such as scan
1401 * synchronization, and we'd prefer one of them to be picked unless a TID
1402 * Range Scan really is better.
1403 */
1404 ntuples = selectivity * baserel->tuples;
1405 nseqpages = pages - 1.0;
1406
1407 /*
1408 * The TID qual expressions will be computed once, any other baserestrict
1409 * quals once per retrieved tuple.
1410 */
1411 cost_qual_eval(&tid_qual_cost, tidrangequals, root);
1412
1413 /* fetch estimated page cost for tablespace containing table */
1414 get_tablespace_page_costs(baserel->reltablespace,
1415 &spc_random_page_cost,
1417
1418 /* disk costs; 1 random page and the remainder as seq pages */
1419 disk_run_cost = spc_random_page_cost + spc_seq_page_cost * nseqpages;
1420
1421 /* Add scanning CPU costs */
1423
1424 /*
1425 * XXX currently we assume TID quals are a subset of qpquals at this
1426 * point; they will be removed (if possible) when we create the plan, so
1427 * we subtract their cost from the total qpqual cost. (If the TID quals
1428 * can't be removed, this is a mistake and we're going to underestimate
1429 * the CPU cost a bit.)
1430 */
1431 startup_cost = qpqual_cost.startup + tid_qual_cost.per_tuple;
1433 tid_qual_cost.per_tuple;
1434 cpu_run_cost = cpu_per_tuple * ntuples;
1435
1436 /* tlist eval costs are paid per output row, not per tuple scanned */
1437 startup_cost += path->pathtarget->cost.startup;
1438 cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
1439
1440 /* Adjust costing for parallelism, if used. */
1441 if (path->parallel_workers > 0)
1442 {
1444
1445 /* The CPU cost is divided among all the workers. */
1447
1448 /*
1449 * In the case of a parallel plan, the row count needs to represent
1450 * the number of tuples processed per worker.
1451 */
1452 path->rows = clamp_row_est(path->rows / parallel_divisor);
1453 }
1454
1455 /*
1456 * We should not generate this path type when PGS_TIDSCAN is unset, but we
1457 * might need to disable this path due to PGS_CONSIDER_NONPARTIAL.
1458 */
1459 Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0);
1460 if (path->parallel_workers == 0)
1462 path->disabled_nodes =
1463 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1464 path->startup_cost = startup_cost;
1465 path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
1466}
#define PGS_TIDSCAN
Definition pathnodes.h:70

References Assert, clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, fb(), get_parallel_divisor(), get_restriction_qual_cost(), get_tablespace_page_costs(), JOIN_INNER, Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, PGS_TIDSCAN, root, Path::rows, RTE_RELATION, Path::startup_cost, and Path::total_cost.

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1250 of file costsize.c.

1252{
1253 Cost startup_cost = 0;
1254 Cost run_cost = 0;
1258 double ntuples;
1259 ListCell *l;
1260 double spc_random_page_cost;
1261 uint64 enable_mask = 0;
1262
1263 /* Should only be applied to base relations */
1264 Assert(baserel->relid > 0);
1265 Assert(baserel->rtekind == RTE_RELATION);
1266 Assert(tidquals != NIL);
1267
1268 /* Mark the path with the correct row estimate */
1269 if (param_info)
1270 path->rows = param_info->ppi_rows;
1271 else
1272 path->rows = baserel->rows;
1273
1274 /* Count how many tuples we expect to retrieve */
1275 ntuples = 0;
1276 foreach(l, tidquals)
1277 {
1279 Expr *qual = rinfo->clause;
1280
1281 /*
1282 * We must use a TID scan for CurrentOfExpr; in any other case, we
1283 * should be generating a TID scan only if TID scans are allowed.
1284 * Also, if CurrentOfExpr is the qual, there should be only one.
1285 */
1286 Assert((baserel->pgs_mask & PGS_TIDSCAN) != 0 || IsA(qual, CurrentOfExpr));
1287 Assert(list_length(tidquals) == 1 || !IsA(qual, CurrentOfExpr));
1288
1289 if (IsA(qual, ScalarArrayOpExpr))
1290 {
1291 /* Each element of the array yields 1 tuple */
1292 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1293 Node *arraynode = (Node *) lsecond(saop->args);
1294
1296 }
1297 else if (IsA(qual, CurrentOfExpr))
1298 {
1299 /* CURRENT OF yields 1 tuple */
1300 ntuples++;
1301 }
1302 else
1303 {
1304 /* It's just CTID = something, count 1 tuple */
1305 ntuples++;
1306 }
1307 }
1308
1309 /*
1310 * The TID qual expressions will be computed once, any other baserestrict
1311 * quals once per retrieved tuple.
1312 */
1313 cost_qual_eval(&tid_qual_cost, tidquals, root);
1314
1315 /* fetch estimated page cost for tablespace containing table */
1316 get_tablespace_page_costs(baserel->reltablespace,
1317 &spc_random_page_cost,
1318 NULL);
1319
1320 /* disk costs --- assume each tuple on a different page */
1321 run_cost += spc_random_page_cost * ntuples;
1322
1323 /* Add scanning CPU costs */
1325
1326 /* XXX currently we assume TID quals are a subset of qpquals */
1327 startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1329 tid_qual_cost.per_tuple;
1330 run_cost += cpu_per_tuple * ntuples;
1331
1332 /* tlist eval costs are paid per output row, not per tuple scanned */
1333 startup_cost += path->pathtarget->cost.startup;
1334 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1335
1336 /*
1337 * There are assertions above verifying that we only reach this function
1338 * either when baserel->pgs_mask includes PGS_TIDSCAN or when the TID scan
1339 * is the only legal path, so we only need to consider the effects of
1340 * PGS_CONSIDER_NONPARTIAL here.
1341 */
1342 if (path->parallel_workers == 0)
1344 path->disabled_nodes =
1345 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1346 path->startup_cost = startup_cost;
1347 path->total_cost = startup_cost + run_cost;
1348}

References ScalarArrayOpExpr::args, Assert, RestrictInfo::clause, cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, estimate_array_length(), fb(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, lfirst_node, list_length(), lsecond, NIL, Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, PGS_TIDSCAN, root, Path::rows, RTE_RELATION, 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 1950 of file costsize.c.

1954{
1955 double input_bytes = relation_byte_size(tuples, width);
1956 double output_bytes;
1957 double output_tuples;
1959
1960 /*
1961 * We want to be sure the cost of a sort is never estimated as zero, even
1962 * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1963 */
1964 if (tuples < 2.0)
1965 tuples = 2.0;
1966
1967 /* Include the default cost-per-comparison */
1969
1970 /* Do we have a useful LIMIT? */
1971 if (limit_tuples > 0 && limit_tuples < tuples)
1972 {
1973 output_tuples = limit_tuples;
1975 }
1976 else
1977 {
1978 output_tuples = tuples;
1980 }
1981
1983 {
1984 /*
1985 * We'll have to use a disk-based sort of all the tuples
1986 */
1987 double npages = ceil(input_bytes / BLCKSZ);
1988 double nruns = input_bytes / sort_mem_bytes;
1990 double log_runs;
1991 double npageaccesses;
1992
1993 /*
1994 * CPU costs
1995 *
1996 * Assume about N log2 N comparisons
1997 */
1998 *startup_cost = comparison_cost * tuples * LOG2(tuples);
1999
2000 /* Disk costs */
2001
2002 /* Compute logM(r) as log(r) / log(M) */
2003 if (nruns > mergeorder)
2005 else
2006 log_runs = 1.0;
2007 npageaccesses = 2.0 * npages * log_runs;
2008 /* Assume 3/4ths of accesses are sequential, 1/4th are not */
2009 *startup_cost += npageaccesses *
2010 (seq_page_cost * 0.75 + random_page_cost * 0.25);
2011 }
2012 else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
2013 {
2014 /*
2015 * We'll use a bounded heap-sort keeping just K tuples in memory, for
2016 * a total number of tuple comparisons of N log2 K; but the constant
2017 * factor is a bit higher than for quicksort. Tweak it so that the
2018 * cost curve is continuous at the crossover point.
2019 */
2020 *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples);
2021 }
2022 else
2023 {
2024 /* We'll use plain quicksort on all the input tuples */
2025 *startup_cost = comparison_cost * tuples * LOG2(tuples);
2026 }
2027
2028 /*
2029 * Also charge a small amount (arbitrarily set equal to operator cost) per
2030 * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
2031 * doesn't do qual-checking or projection, so it has less overhead than
2032 * most plan nodes. Note it's correct to use tuples not output_tuples
2033 * here --- the upper LIMIT will pro-rate the run cost so we'd be double
2034 * counting the LIMIT otherwise.
2035 */
2036 *run_cost = cpu_operator_cost * tuples;
2037}
int64_t int64
Definition c.h:543
int tuplesort_merge_order(int64 allowedMem)
Definition tuplesort.c:1763

References cpu_operator_cost, fb(), 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 1689 of file costsize.c.

1691{
1692 Cost startup_cost = 0;
1693 Cost run_cost = 0;
1696 uint64 enable_mask = 0;
1697
1698 /* Should only be applied to base relations that are values lists */
1699 Assert(baserel->relid > 0);
1700 Assert(baserel->rtekind == RTE_VALUES);
1701
1702 /* Mark the path with the correct row estimate */
1703 if (param_info)
1704 path->rows = param_info->ppi_rows;
1705 else
1706 path->rows = baserel->rows;
1707
1708 /*
1709 * For now, estimate list evaluation cost at one operator eval per list
1710 * (probably pretty bogus, but is it worth being smarter?)
1711 */
1713
1714 /* Add scanning CPU costs */
1716
1717 startup_cost += qpqual_cost.startup;
1719 run_cost += cpu_per_tuple * baserel->tuples;
1720
1721 /* tlist eval costs are paid per output row, not per tuple scanned */
1722 startup_cost += path->pathtarget->cost.startup;
1723 run_cost += path->pathtarget->cost.per_tuple * path->rows;
1724
1725 if (path->parallel_workers == 0)
1727 path->disabled_nodes =
1728 (baserel->pgs_mask & enable_mask) != enable_mask ? 1 : 0;
1729 path->startup_cost = startup_cost;
1730 path->total_cost = startup_cost + run_cost;
1731}
@ RTE_VALUES

References Assert, cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, root, Path::rows, RTE_VALUES, Path::startup_cost, and Path::total_cost.

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

3213{
3214 Cost startup_cost;
3215 Cost total_cost;
3216 double startup_tuples;
3217 int numPartCols;
3218 int numOrderCols;
3219 ListCell *lc;
3220
3222 numOrderCols = list_length(winclause->orderClause);
3223
3224 startup_cost = input_startup_cost;
3225 total_cost = input_total_cost;
3226
3227 /*
3228 * Window functions are assumed to cost their stated execution cost, plus
3229 * the cost of evaluating their input expressions, per tuple. Since they
3230 * may in fact evaluate their inputs at multiple rows during each cycle,
3231 * this could be a drastic underestimate; but without a way to know how
3232 * many rows the window function will fetch, it's hard to do better. In
3233 * any case, it's a good estimate for all the built-in window functions,
3234 * so we'll just do this for now.
3235 */
3236 foreach(lc, windowFuncs)
3237 {
3241
3242 argcosts.startup = argcosts.per_tuple = 0;
3243 add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3244 &argcosts);
3245 startup_cost += argcosts.startup;
3246 wfunccost = argcosts.per_tuple;
3247
3248 /* also add the input expressions' cost to per-input-row costs */
3249 cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3250 startup_cost += argcosts.startup;
3251 wfunccost += argcosts.per_tuple;
3252
3253 /*
3254 * Add the filter's cost to per-input-row costs. XXX We should reduce
3255 * input expression costs according to filter selectivity.
3256 */
3258 startup_cost += argcosts.startup;
3259 wfunccost += argcosts.per_tuple;
3260
3261 total_cost += wfunccost * input_tuples;
3262 }
3263
3264 /*
3265 * We also charge cpu_operator_cost per grouping column per tuple for
3266 * grouping comparisons, plus cpu_tuple_cost per tuple for general
3267 * overhead.
3268 *
3269 * XXX this neglects costs of spooling the data to disk when it overflows
3270 * work_mem. Sooner or later that should get accounted for.
3271 */
3272 total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3273 total_cost += cpu_tuple_cost * input_tuples;
3274
3275 path->rows = input_tuples;
3277 path->startup_cost = startup_cost;
3278 path->total_cost = total_cost;
3279
3280 /*
3281 * Also, take into account how many tuples we need to read from the
3282 * subnode in order to produce the first tuple from the WindowAgg. To do
3283 * this we proportion the run cost (total cost not including startup cost)
3284 * over the estimated startup tuples. We already included the startup
3285 * cost of the subnode, so we only need to do this when the estimated
3286 * startup tuples is above 1.0.
3287 */
3289 input_tuples);
3290
3291 if (startup_tuples > 1.0)
3292 path->startup_cost += (total_cost - startup_cost) / input_tuples *
3293 (startup_tuples - 1.0);
3294}
static double get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc, double input_tuples)
Definition costsize.c:2994
List * partitionClause
List * orderClause
List * args
Definition primnodes.h:605
Expr * aggfilter
Definition primnodes.h:607

References add_function_cost(), WindowFunc::aggfilter, WindowFunc::args, cost_qual_eval_node(), cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, fb(), get_windowclause_startup_tuples(), lfirst_node, list_length(), WindowClause::orderClause, WindowClause::partitionClause, 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 838 of file costsize.c.

839{
840 List *result = NIL;
841 ListCell *lc;
842
843 foreach(lc, qual_clauses)
844 {
846
847 if (rinfo->pseudoconstant)
848 continue; /* we may drop pseudoconstants here */
849 if (is_redundant_with_indexclauses(rinfo, indexclauses))
850 continue; /* dup or derived from same EquivalenceClass */
851 /* ... skip the predicate proof attempt createplan.c will try ... */
852 result = lappend(result, rinfo);
853 }
854 return result;
855}
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)

References fb(), 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 4420 of file costsize.c.

4423{
4427 double inner_path_rows = inner_path->rows;
4428 double inner_path_rows_total = workspace->inner_rows_total;
4429 List *hashclauses = path->path_hashclauses;
4430 Cost startup_cost = workspace->startup_cost;
4431 Cost run_cost = workspace->run_cost;
4432 int numbuckets = workspace->numbuckets;
4433 int numbatches = workspace->numbatches;
4437 double hashjointuples;
4438 double virtualbuckets;
4441 ListCell *hcl;
4442
4443 /* Set the number of disabled nodes. */
4444 path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4445
4446 /* Mark the path with the correct row estimate */
4447 if (path->jpath.path.param_info)
4448 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4449 else
4450 path->jpath.path.rows = path->jpath.path.parent->rows;
4451
4452 /* For partial paths, scale row estimate. */
4453 if (path->jpath.path.parallel_workers > 0)
4454 {
4455 double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4456
4457 path->jpath.path.rows =
4458 clamp_row_est(path->jpath.path.rows / parallel_divisor);
4459 }
4460
4461 /* mark the path with estimated # of batches */
4462 path->num_batches = numbatches;
4463
4464 /* store the total number of tuples (sum of partial row estimates) */
4466
4467 /* and compute the number of "virtual" buckets in the whole join */
4468 virtualbuckets = (double) numbuckets * (double) numbatches;
4469
4470 /*
4471 * Determine bucketsize fraction and MCV frequency for the inner relation.
4472 * We use the smallest bucketsize or MCV frequency estimated for any
4473 * individual hashclause; this is undoubtedly conservative.
4474 *
4475 * BUT: if inner relation has been unique-ified, we can assume it's good
4476 * for hashing. This is important both because it's the right answer, and
4477 * because we avoid contaminating the cache with a value that's wrong for
4478 * non-unique-ified paths.
4479 */
4480 if (RELATION_WAS_MADE_UNIQUE(inner_path->parent, extra->sjinfo,
4481 path->jpath.jointype))
4482 {
4485 }
4486 else
4487 {
4489
4490 innerbucketsize = 1.0;
4491 innermcvfreq = 1.0;
4492
4493 /* At first, try to estimate bucket size using extended statistics. */
4495 inner_path->parent,
4496 hashclauses,
4498
4499 /* Pass through the remaining clauses */
4500 foreach(hcl, otherclauses)
4501 {
4505
4506 /*
4507 * First we have to figure out which side of the hashjoin clause
4508 * is the inner side.
4509 *
4510 * Since we tend to visit the same clauses over and over when
4511 * planning a large query, we cache the bucket stats estimates in
4512 * the RestrictInfo node to avoid repeated lookups of statistics.
4513 */
4514 if (bms_is_subset(restrictinfo->right_relids,
4515 inner_path->parent->relids))
4516 {
4517 /* righthand side is inner */
4518 thisbucketsize = restrictinfo->right_bucketsize;
4519 if (thisbucketsize < 0)
4520 {
4521 /* not cached yet */
4523 get_rightop(restrictinfo->clause),
4525 &restrictinfo->right_mcvfreq,
4526 &restrictinfo->right_bucketsize);
4527 thisbucketsize = restrictinfo->right_bucketsize;
4528 }
4529 thismcvfreq = restrictinfo->right_mcvfreq;
4530 }
4531 else
4532 {
4533 Assert(bms_is_subset(restrictinfo->left_relids,
4534 inner_path->parent->relids));
4535 /* lefthand side is inner */
4536 thisbucketsize = restrictinfo->left_bucketsize;
4537 if (thisbucketsize < 0)
4538 {
4539 /* not cached yet */
4541 get_leftop(restrictinfo->clause),
4543 &restrictinfo->left_mcvfreq,
4544 &restrictinfo->left_bucketsize);
4545 thisbucketsize = restrictinfo->left_bucketsize;
4546 }
4547 thismcvfreq = restrictinfo->left_mcvfreq;
4548 }
4549
4552 /* Disregard zero for MCV freq, it means we have no data */
4553 if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq)
4555 }
4556 }
4557
4558 /*
4559 * If the bucket holding the inner MCV would exceed hash_mem, we don't
4560 * want to hash unless there is really no other alternative, so apply
4561 * disable_cost. (The executor normally copes with excessive memory usage
4562 * by splitting batches, but obviously it cannot separate equal values
4563 * that way, so it will be unable to drive the batch size below hash_mem
4564 * when this is true.)
4565 */
4567 inner_path->pathtarget->width) > get_hash_memory_limit())
4568 startup_cost += disable_cost;
4569
4570 /*
4571 * Compute cost of the hashquals and qpquals (other restriction clauses)
4572 * separately.
4573 */
4574 cost_qual_eval(&hash_qual_cost, hashclauses, root);
4576 qp_qual_cost.startup -= hash_qual_cost.startup;
4577 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4578
4579 /* CPU costs */
4580
4581 if (path->jpath.jointype == JOIN_SEMI ||
4582 path->jpath.jointype == JOIN_ANTI ||
4583 extra->inner_unique)
4584 {
4585 double outer_matched_rows;
4587
4588 /*
4589 * With a SEMI or ANTI join, or if the innerrel is known unique, the
4590 * executor will stop after the first match.
4591 *
4592 * For an outer-rel row that has at least one match, we can expect the
4593 * bucket scan to stop after a fraction 1/(match_count+1) of the
4594 * bucket's rows, if the matches are evenly distributed. Since they
4595 * probably aren't quite evenly distributed, we apply a fuzz factor of
4596 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4597 * to clamp inner_scan_frac to at most 1.0; but since match_count is
4598 * at least 1, no such clamp is needed now.)
4599 */
4601 inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4602
4603 startup_cost += hash_qual_cost.startup;
4604 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4606
4607 /*
4608 * For unmatched outer-rel rows, the picture is quite a lot different.
4609 * In the first place, there is no reason to assume that these rows
4610 * preferentially hit heavily-populated buckets; instead assume they
4611 * are uncorrelated with the inner distribution and so they see an
4612 * average bucket size of inner_path_rows / virtualbuckets. In the
4613 * second place, it seems likely that they will have few if any exact
4614 * hash-code matches and so very few of the tuples in the bucket will
4615 * actually require eval of the hash quals. We don't have any good
4616 * way to estimate how many will, but for the moment assume that the
4617 * effective cost per bucket entry is one-tenth what it is for
4618 * matchable tuples.
4619 */
4620 run_cost += hash_qual_cost.per_tuple *
4623
4624 /* Get # of tuples that will pass the basic join */
4625 if (path->jpath.jointype == JOIN_ANTI)
4627 else
4629 }
4630 else
4631 {
4632 /*
4633 * The number of tuple comparisons needed is the number of outer
4634 * tuples times the typical number of tuples in a hash bucket, which
4635 * is the inner relation size times its bucketsize fraction. At each
4636 * one, we need to evaluate the hashjoin quals. But actually,
4637 * charging the full qual eval cost at each tuple is pessimistic,
4638 * since we don't evaluate the quals unless the hash values match
4639 * exactly. For lack of a better idea, halve the cost estimate to
4640 * allow for that.
4641 */
4642 startup_cost += hash_qual_cost.startup;
4643 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4645
4646 /*
4647 * Get approx # tuples passing the hashquals. We use
4648 * approx_tuple_count here because we need an estimate done with
4649 * JOIN_INNER semantics.
4650 */
4651 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4652 }
4653
4654 /*
4655 * For each tuple that gets through the hashjoin proper, we charge
4656 * cpu_tuple_cost plus the cost of evaluating additional restriction
4657 * clauses that are to be applied at the join. (This is pessimistic since
4658 * not all of the quals may get evaluated at each tuple.)
4659 */
4660 startup_cost += qp_qual_cost.startup;
4662 run_cost += cpu_per_tuple * hashjointuples;
4663
4664 /* tlist eval costs are paid per output row, not per tuple scanned */
4665 startup_cost += path->jpath.path.pathtarget->cost.startup;
4666 run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4667
4668 path->jpath.path.startup_cost = startup_cost;
4669 path->jpath.path.total_cost = startup_cost + run_cost;
4670}
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:5451
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:1232
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:2460
Cardinality inner_rows_total
Definition pathnodes.h:2462
int num_batches
Definition pathnodes.h:2461
JoinPath jpath
Definition pathnodes.h:2459
Cardinality inner_rows_total
Definition pathnodes.h:3702
SemiAntiJoinFactors semifactors
Definition pathnodes.h:3579
SpecialJoinInfo * sjinfo
Definition pathnodes.h:3578
JoinType jointype
Definition pathnodes.h:2369
List * joinrestrictinfo
Definition pathnodes.h:2377

References approx_tuple_count(), Assert, bms_is_subset(), clamp_row_est(), cost_qual_eval(), cpu_tuple_cost, disable_cost, JoinCostWorkspace::disabled_nodes, estimate_hash_bucket_stats(), estimate_multivariate_bucketsize(), fb(), 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, relation_byte_size(), RELATION_WAS_MADE_UNIQUE, root, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, JoinPathExtraData::sjinfo, 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 3959 of file costsize.c.

3962{
3966 List *mergeclauses = path->path_mergeclauses;
3967 List *innersortkeys = path->innersortkeys;
3968 Cost startup_cost = workspace->startup_cost;
3969 Cost run_cost = workspace->run_cost;
3970 Cost inner_run_cost = workspace->inner_run_cost;
3971 double outer_rows = workspace->outer_rows;
3972 double inner_rows = workspace->inner_rows;
3973 double outer_skip_rows = workspace->outer_skip_rows;
3974 double inner_skip_rows = workspace->inner_skip_rows;
3980 double mergejointuples,
3982 double rescanratio;
3983 uint64 enable_mask = 0;
3984
3985 /* Protect some assumptions below that rowcounts aren't zero */
3986 if (inner_path_rows <= 0)
3987 inner_path_rows = 1;
3988
3989 /* Mark the path with the correct row estimate */
3990 if (path->jpath.path.param_info)
3991 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3992 else
3993 path->jpath.path.rows = path->jpath.path.parent->rows;
3994
3995 /* For partial paths, scale row estimate. */
3996 if (path->jpath.path.parallel_workers > 0)
3997 {
3998 double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3999
4000 path->jpath.path.rows =
4001 clamp_row_est(path->jpath.path.rows / parallel_divisor);
4002 }
4003
4004 /*
4005 * Compute cost of the mergequals and qpquals (other restriction clauses)
4006 * separately.
4007 */
4008 cost_qual_eval(&merge_qual_cost, mergeclauses, root);
4010 qp_qual_cost.startup -= merge_qual_cost.startup;
4011 qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
4012
4013 /*
4014 * With a SEMI or ANTI join, or if the innerrel is known unique, the
4015 * executor will stop scanning for matches after the first match. When
4016 * all the joinclauses are merge clauses, this means we don't ever need to
4017 * back up the merge, and so we can skip mark/restore overhead.
4018 */
4019 if ((path->jpath.jointype == JOIN_SEMI ||
4020 path->jpath.jointype == JOIN_ANTI ||
4021 extra->inner_unique) &&
4024 path->skip_mark_restore = true;
4025 else
4026 path->skip_mark_restore = false;
4027
4028 /*
4029 * Get approx # tuples passing the mergequals. We use approx_tuple_count
4030 * here because we need an estimate done with JOIN_INNER semantics.
4031 */
4032 mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
4033
4034 /*
4035 * When there are equal merge keys in the outer relation, the mergejoin
4036 * must rescan any matching tuples in the inner relation. This means
4037 * re-fetching inner tuples; we have to estimate how often that happens.
4038 *
4039 * For regular inner and outer joins, the number of re-fetches can be
4040 * estimated approximately as size of merge join output minus size of
4041 * inner relation. Assume that the distinct key values are 1, 2, ..., and
4042 * denote the number of values of each key in the outer relation as m1,
4043 * m2, ...; in the inner relation, n1, n2, ... Then we have
4044 *
4045 * size of join = m1 * n1 + m2 * n2 + ...
4046 *
4047 * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
4048 * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
4049 * relation
4050 *
4051 * This equation works correctly for outer tuples having no inner match
4052 * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
4053 * are effectively subtracting those from the number of rescanned tuples,
4054 * when we should not. Can we do better without expensive selectivity
4055 * computations?
4056 *
4057 * The whole issue is moot if we know we don't need to mark/restore at
4058 * all, or if we are working from a unique-ified outer input.
4059 */
4060 if (path->skip_mark_restore ||
4062 path->jpath.jointype))
4063 rescannedtuples = 0;
4064 else
4065 {
4067 /* Must clamp because of possible underestimate */
4068 if (rescannedtuples < 0)
4069 rescannedtuples = 0;
4070 }
4071
4072 /*
4073 * We'll inflate various costs this much to account for rescanning. Note
4074 * that this is to be multiplied by something involving inner_rows, or
4075 * another number related to the portion of the inner rel we'll scan.
4076 */
4077 rescanratio = 1.0 + (rescannedtuples / inner_rows);
4078
4079 /*
4080 * Decide whether we want to materialize the inner input to shield it from
4081 * mark/restore and performing re-fetches. Our cost model for regular
4082 * re-fetches is that a re-fetch costs the same as an original fetch,
4083 * which is probably an overestimate; but on the other hand we ignore the
4084 * bookkeeping costs of mark/restore. Not clear if it's worth developing
4085 * a more refined model. So we just need to inflate the inner run cost by
4086 * rescanratio.
4087 */
4088 bare_inner_cost = inner_run_cost * rescanratio;
4089
4090 /*
4091 * When we interpose a Material node the re-fetch cost is assumed to be
4092 * just cpu_operator_cost per tuple, independently of the underlying
4093 * plan's cost; and we charge an extra cpu_operator_cost per original
4094 * fetch as well. Note that we're assuming the materialize node will
4095 * never spill to disk, since it only has to remember tuples back to the
4096 * last mark. (If there are a huge number of duplicates, our other cost
4097 * factors will make the path so expensive that it probably won't get
4098 * chosen anyway.) So we don't use cost_rescan here.
4099 *
4100 * Note: keep this estimate in sync with create_mergejoin_plan's labeling
4101 * of the generated Material node.
4102 */
4103 mat_inner_cost = inner_run_cost +
4104 cpu_operator_cost * inner_rows * rescanratio;
4105
4106 /*
4107 * If we don't need mark/restore at all, we don't need materialization.
4108 */
4109 if (path->skip_mark_restore)
4110 path->materialize_inner = false;
4111
4112 /*
4113 * If merge joins with materialization are enabled, then choose
4114 * materialization if either (a) it looks cheaper or (b) merge joins
4115 * without materialization are disabled.
4116 */
4117 else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
4119 (extra->pgs_mask & PGS_MERGEJOIN_PLAIN) == 0))
4120 path->materialize_inner = true;
4121
4122 /*
4123 * Regardless of what plan shapes are enabled and what the costs seem to
4124 * be, we *must* materialize it if the inner path is to be used directly
4125 * (without sorting) and it doesn't support mark/restore. Planner failure
4126 * is not an option!
4127 *
4128 * Since the inner side must be ordered, and only Sorts and IndexScans can
4129 * create order to begin with, and they both support mark/restore, you
4130 * might think there's no problem --- but you'd be wrong. Nestloop and
4131 * merge joins can *preserve* the order of their inputs, so they can be
4132 * selected as the input of a mergejoin, and they don't support
4133 * mark/restore at present.
4134 */
4135 else if (innersortkeys == NIL &&
4137 path->materialize_inner = true;
4138
4139 /*
4140 * Also, force materializing if the inner path is to be sorted and the
4141 * sort is expected to spill to disk. This is because the final merge
4142 * pass can be done on-the-fly if it doesn't have to support mark/restore.
4143 * We don't try to adjust the cost estimates for this consideration,
4144 * though.
4145 *
4146 * Since materialization is a performance optimization in this case,
4147 * rather than necessary for correctness, we skip it if materialization is
4148 * switched off.
4149 */
4150 else if ((extra->pgs_mask & PGS_MERGEJOIN_MATERIALIZE) != 0 &&
4151 innersortkeys != NIL &&
4153 inner_path->pathtarget->width) >
4154 work_mem * (Size) 1024)
4155 path->materialize_inner = true;
4156 else
4157 path->materialize_inner = false;
4158
4159 /* Get the number of disabled nodes, not yet including this one. */
4160 path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4161
4162 /*
4163 * Charge the right incremental cost for the chosen case, and update
4164 * enable_mask as appropriate.
4165 */
4166 if (path->materialize_inner)
4167 {
4168 run_cost += mat_inner_cost;
4170 }
4171 else
4172 {
4173 run_cost += bare_inner_cost;
4175 }
4176
4177 /* Incremental count of disabled nodes if this node is disabled. */
4178 if (path->jpath.path.parallel_workers == 0)
4180 if ((extra->pgs_mask & enable_mask) != enable_mask)
4181 ++path->jpath.path.disabled_nodes;
4182
4183 /* CPU costs */
4184
4185 /*
4186 * The number of tuple comparisons needed is approximately number of outer
4187 * rows plus number of inner rows plus number of rescanned tuples (can we
4188 * refine this?). At each one, we need to evaluate the mergejoin quals.
4189 */
4190 startup_cost += merge_qual_cost.startup;
4191 startup_cost += merge_qual_cost.per_tuple *
4192 (outer_skip_rows + inner_skip_rows * rescanratio);
4193 run_cost += merge_qual_cost.per_tuple *
4194 ((outer_rows - outer_skip_rows) +
4195 (inner_rows - inner_skip_rows) * rescanratio);
4196
4197 /*
4198 * For each tuple that gets through the mergejoin proper, we charge
4199 * cpu_tuple_cost plus the cost of evaluating additional restriction
4200 * clauses that are to be applied at the join. (This is pessimistic since
4201 * not all of the quals may get evaluated at each tuple.)
4202 *
4203 * Note: we could adjust for SEMI/ANTI joins skipping some qual
4204 * evaluations here, but it's probably not worth the trouble.
4205 */
4206 startup_cost += qp_qual_cost.startup;
4208 run_cost += cpu_per_tuple * mergejointuples;
4209
4210 /* tlist eval costs are paid per output row, not per tuple scanned */
4211 startup_cost += path->jpath.path.pathtarget->cost.startup;
4212 run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4213
4214 path->jpath.path.startup_cost = startup_cost;
4215 path->jpath.path.total_cost = startup_cost + run_cost;
4216}
bool ExecSupportsMarkRestore(Path *pathnode)
Definition execAmi.c:418
#define PGS_MERGEJOIN_PLAIN
Definition pathnodes.h:72
#define PGS_MERGEJOIN_MATERIALIZE
Definition pathnodes.h:73
Cardinality inner_rows
Definition pathnodes.h:3695
Cardinality outer_rows
Definition pathnodes.h:3694
Cardinality inner_skip_rows
Definition pathnodes.h:3697
Cardinality outer_skip_rows
Definition pathnodes.h:3696
bool skip_mark_restore
Definition pathnodes.h:2444
List * innersortkeys
Definition pathnodes.h:2441
JoinPath jpath
Definition pathnodes.h:2438
bool materialize_inner
Definition pathnodes.h:2445
List * path_mergeclauses
Definition pathnodes.h:2439

References approx_tuple_count(), clamp_row_est(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, JoinCostWorkspace::disabled_nodes, ExecSupportsMarkRestore(), fb(), get_parallel_divisor(), 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, PGS_CONSIDER_NONPARTIAL, JoinPathExtraData::pgs_mask, PGS_MERGEJOIN_MATERIALIZE, PGS_MERGEJOIN_PLAIN, relation_byte_size(), RELATION_WAS_MADE_UNIQUE, root, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::sjinfo, MergePath::skip_mark_restore, 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 3459 of file costsize.c.

3462{
3466 double inner_path_rows = inner_path->rows;
3467 Cost startup_cost = workspace->startup_cost;
3468 Cost run_cost = workspace->run_cost;
3471 double ntuples;
3472
3473 /* Set the number of disabled nodes. */
3474 path->jpath.path.disabled_nodes = workspace->disabled_nodes;
3475
3476 /* Protect some assumptions below that rowcounts aren't zero */
3477 if (outer_path_rows <= 0)
3478 outer_path_rows = 1;
3479 if (inner_path_rows <= 0)
3480 inner_path_rows = 1;
3481 /* Mark the path with the correct row estimate */
3482 if (path->jpath.path.param_info)
3483 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3484 else
3485 path->jpath.path.rows = path->jpath.path.parent->rows;
3486
3487 /* For partial paths, scale row estimate. */
3488 if (path->jpath.path.parallel_workers > 0)
3489 {
3490 double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3491
3492 path->jpath.path.rows =
3493 clamp_row_est(path->jpath.path.rows / parallel_divisor);
3494 }
3495
3496 /* cost of inner-relation source data (we already dealt with outer rel) */
3497
3498 if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3499 extra->inner_unique)
3500 {
3501 /*
3502 * With a SEMI or ANTI join, or if the innerrel is known unique, the
3503 * executor will stop after the first match.
3504 */
3505 Cost inner_run_cost = workspace->inner_run_cost;
3506 Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3507 double outer_matched_rows;
3508 double outer_unmatched_rows;
3510
3511 /*
3512 * For an outer-rel row that has at least one match, we can expect the
3513 * inner scan to stop after a fraction 1/(match_count+1) of the inner
3514 * rows, if the matches are evenly distributed. Since they probably
3515 * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3516 * that fraction. (If we used a larger fuzz factor, we'd have to
3517 * clamp inner_scan_frac to at most 1.0; but since match_count is at
3518 * least 1, no such clamp is needed now.)
3519 */
3522 inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3523
3524 /*
3525 * Compute number of tuples processed (not number emitted!). First,
3526 * account for successfully-matched outer rows.
3527 */
3529
3530 /*
3531 * Now we need to estimate the actual costs of scanning the inner
3532 * relation, which may be quite a bit less than N times inner_run_cost
3533 * due to early scan stops. We consider two cases. If the inner path
3534 * is an indexscan using all the joinquals as indexquals, then an
3535 * unmatched outer row results in an indexscan returning no rows,
3536 * which is probably quite cheap. Otherwise, the executor will have
3537 * to scan the whole inner rel for an unmatched row; not so cheap.
3538 */
3539 if (has_indexed_join_quals(path))
3540 {
3541 /*
3542 * Successfully-matched outer rows will only require scanning
3543 * inner_scan_frac of the inner relation. In this case, we don't
3544 * need to charge the full inner_run_cost even when that's more
3545 * than inner_rescan_run_cost, because we can assume that none of
3546 * the inner scans ever scan the whole inner relation. So it's
3547 * okay to assume that all the inner scan executions can be
3548 * fractions of the full cost, even if materialization is reducing
3549 * the rescan cost. At this writing, it's impossible to get here
3550 * for a materialized inner scan, so inner_run_cost and
3551 * inner_rescan_run_cost will be the same anyway; but just in
3552 * case, use inner_run_cost for the first matched tuple and
3553 * inner_rescan_run_cost for additional ones.
3554 */
3555 run_cost += inner_run_cost * inner_scan_frac;
3556 if (outer_matched_rows > 1)
3557 run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3558
3559 /*
3560 * Add the cost of inner-scan executions for unmatched outer rows.
3561 * We estimate this as the same cost as returning the first tuple
3562 * of a nonempty scan. We consider that these are all rescans,
3563 * since we used inner_run_cost once already.
3564 */
3565 run_cost += outer_unmatched_rows *
3566 inner_rescan_run_cost / inner_path_rows;
3567
3568 /*
3569 * We won't be evaluating any quals at all for unmatched rows, so
3570 * don't add them to ntuples.
3571 */
3572 }
3573 else
3574 {
3575 /*
3576 * Here, a complicating factor is that rescans may be cheaper than
3577 * first scans. If we never scan all the way to the end of the
3578 * inner rel, it might be (depending on the plan type) that we'd
3579 * never pay the whole inner first-scan run cost. However it is
3580 * difficult to estimate whether that will happen (and it could
3581 * not happen if there are any unmatched outer rows!), so be
3582 * conservative and always charge the whole first-scan cost once.
3583 * We consider this charge to correspond to the first unmatched
3584 * outer row, unless there isn't one in our estimate, in which
3585 * case blame it on the first matched row.
3586 */
3587
3588 /* First, count all unmatched join tuples as being processed */
3590
3591 /* Now add the forced full scan, and decrement appropriate count */
3592 run_cost += inner_run_cost;
3593 if (outer_unmatched_rows >= 1)
3595 else
3596 outer_matched_rows -= 1;
3597
3598 /* Add inner run cost for additional outer tuples having matches */
3599 if (outer_matched_rows > 0)
3600 run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3601
3602 /* Add inner run cost for additional unmatched outer tuples */
3603 if (outer_unmatched_rows > 0)
3604 run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3605 }
3606 }
3607 else
3608 {
3609 /* Normal-case source costs were included in preliminary estimate */
3610
3611 /* Compute number of tuples processed (not number emitted!) */
3612 ntuples = outer_path_rows * inner_path_rows;
3613 }
3614
3615 /* CPU costs */
3617 startup_cost += restrict_qual_cost.startup;
3619 run_cost += cpu_per_tuple * ntuples;
3620
3621 /* tlist eval costs are paid per output row, not per tuple scanned */
3622 startup_cost += path->jpath.path.pathtarget->cost.startup;
3623 run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3624
3625 path->jpath.path.startup_cost = startup_cost;
3626 path->jpath.path.total_cost = startup_cost + run_cost;
3627}
static bool has_indexed_join_quals(NestPath *path)
Definition costsize.c:5358
JoinPath jpath
Definition pathnodes.h:2392

References clamp_row_est(), cost_qual_eval(), cpu_tuple_cost, JoinCostWorkspace::disabled_nodes, fb(), 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, root, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, 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 6552 of file costsize.c.

6553{
6554 int32 width;
6555
6556 if (IsA(expr, Var))
6557 {
6558 const Var *var = (const Var *) expr;
6559
6560 /* We should not see any upper-level Vars here */
6561 Assert(var->varlevelsup == 0);
6562
6563 /* Try to get data from RelOptInfo cache */
6564 if (!IS_SPECIAL_VARNO(var->varno) &&
6565 var->varno < root->simple_rel_array_size)
6566 {
6567 RelOptInfo *rel = root->simple_rel_array[var->varno];
6568
6569 if (rel != NULL &&
6570 var->varattno >= rel->min_attr &&
6571 var->varattno <= rel->max_attr)
6572 {
6573 int ndx = var->varattno - rel->min_attr;
6574
6575 if (rel->attr_widths[ndx] > 0)
6576 return rel->attr_widths[ndx];
6577 }
6578 }
6579
6580 /*
6581 * No cached data available, so estimate using just the type info.
6582 */
6583 width = get_typavgwidth(var->vartype, var->vartypmod);
6584 Assert(width > 0);
6585
6586 return width;
6587 }
6588
6589 width = get_typavgwidth(exprType(expr), exprTypmod(expr));
6590 Assert(width > 0);
6591 return width;
6592}
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:1059
AttrNumber min_attr
Definition pathnodes.h:1057
AttrNumber varattno
Definition primnodes.h:274
int varno
Definition primnodes.h:269
Index varlevelsup
Definition primnodes.h:294

References Assert, exprType(), exprTypmod(), fb(), 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 5798 of file costsize.c.

5803{
5804 Selectivity fkselec = 1.0;
5805 JoinType jointype = sjinfo->jointype;
5806 List *worklist = *restrictlist;
5807 ListCell *lc;
5808
5809 /* Consider each FK constraint that is known to match the query */
5810 foreach(lc, root->fkey_list)
5811 {
5813 bool ref_is_outer;
5815 ListCell *cell;
5816
5817 /*
5818 * This FK is not relevant unless it connects a baserel on one side of
5819 * this join to a baserel on the other side.
5820 */
5821 if (bms_is_member(fkinfo->con_relid, outer_relids) &&
5822 bms_is_member(fkinfo->ref_relid, inner_relids))
5823 ref_is_outer = false;
5824 else if (bms_is_member(fkinfo->ref_relid, outer_relids) &&
5825 bms_is_member(fkinfo->con_relid, inner_relids))
5826 ref_is_outer = true;
5827 else
5828 continue;
5829
5830 /*
5831 * If we're dealing with a semi/anti join, and the FK's referenced
5832 * relation is on the outside, then knowledge of the FK doesn't help
5833 * us figure out what we need to know (which is the fraction of outer
5834 * rows that have matches). On the other hand, if the referenced rel
5835 * is on the inside, then all outer rows must have matches in the
5836 * referenced table (ignoring nulls). But any restriction or join
5837 * clauses that filter that table will reduce the fraction of matches.
5838 * We can account for restriction clauses, but it's too hard to guess
5839 * how many table rows would get through a join that's inside the RHS.
5840 * Hence, if either case applies, punt and ignore the FK.
5841 */
5842 if ((jointype == JOIN_SEMI || jointype == JOIN_ANTI) &&
5844 continue;
5845
5846 /*
5847 * Modify the restrictlist by removing clauses that match the FK (and
5848 * putting them into removedlist instead). It seems unsafe to modify
5849 * the originally-passed List structure, so we make a shallow copy the
5850 * first time through.
5851 */
5852 if (worklist == *restrictlist)
5854
5855 removedlist = NIL;
5856 foreach(cell, worklist)
5857 {
5858 RestrictInfo *rinfo = (RestrictInfo *) lfirst(cell);
5859 bool remove_it = false;
5860 int i;
5861
5862 /* Drop this clause if it matches any column of the FK */
5863 for (i = 0; i < fkinfo->nkeys; i++)
5864 {
5865 if (rinfo->parent_ec)
5866 {
5867 /*
5868 * EC-derived clauses can only match by EC. It is okay to
5869 * consider any clause derived from the same EC as
5870 * matching the FK: even if equivclass.c chose to generate
5871 * a clause equating some other pair of Vars, it could
5872 * have generated one equating the FK's Vars. So for
5873 * purposes of estimation, we can act as though it did so.
5874 *
5875 * Note: checking parent_ec is a bit of a cheat because
5876 * there are EC-derived clauses that don't have parent_ec
5877 * set; but such clauses must compare expressions that
5878 * aren't just Vars, so they cannot match the FK anyway.
5879 */
5880 if (fkinfo->eclass[i] == rinfo->parent_ec)
5881 {
5882 remove_it = true;
5883 break;
5884 }
5885 }
5886 else
5887 {
5888 /*
5889 * Otherwise, see if rinfo was previously matched to FK as
5890 * a "loose" clause.
5891 */
5892 if (list_member_ptr(fkinfo->rinfos[i], rinfo))
5893 {
5894 remove_it = true;
5895 break;
5896 }
5897 }
5898 }
5899 if (remove_it)
5900 {
5903 }
5904 }
5905
5906 /*
5907 * If we failed to remove all the matching clauses we expected to
5908 * find, chicken out and ignore this FK; applying its selectivity
5909 * might result in double-counting. Put any clauses we did manage to
5910 * remove back into the worklist.
5911 *
5912 * Since the matching clauses are known not outerjoin-delayed, they
5913 * would normally have appeared in the initial joinclause list. If we
5914 * didn't find them, there are two possibilities:
5915 *
5916 * 1. If the FK match is based on an EC that is ec_has_const, it won't
5917 * have generated any join clauses at all. We discount such ECs while
5918 * checking to see if we have "all" the clauses. (Below, we'll adjust
5919 * the selectivity estimate for this case.)
5920 *
5921 * 2. The clauses were matched to some other FK in a previous
5922 * iteration of this loop, and thus removed from worklist. (A likely
5923 * case is that two FKs are matched to the same EC; there will be only
5924 * one EC-derived clause in the initial list, so the first FK will
5925 * consume it.) Applying both FKs' selectivity independently risks
5926 * underestimating the join size; in particular, this would undo one
5927 * of the main things that ECs were invented for, namely to avoid
5928 * double-counting the selectivity of redundant equality conditions.
5929 * Later we might think of a reasonable way to combine the estimates,
5930 * but for now, just punt, since this is a fairly uncommon situation.
5931 */
5932 if (removedlist == NIL ||
5934 (fkinfo->nmatched_ec - fkinfo->nconst_ec + fkinfo->nmatched_ri))
5935 {
5937 continue;
5938 }
5939
5940 /*
5941 * Finally we get to the payoff: estimate selectivity using the
5942 * knowledge that each referencing row will match exactly one row in
5943 * the referenced table.
5944 *
5945 * XXX that's not true in the presence of nulls in the referencing
5946 * column(s), so in principle we should derate the estimate for those.
5947 * However (1) if there are any strict restriction clauses for the
5948 * referencing column(s) elsewhere in the query, derating here would
5949 * be double-counting the null fraction, and (2) it's not very clear
5950 * how to combine null fractions for multiple referencing columns. So
5951 * we do nothing for now about correcting for nulls.
5952 *
5953 * XXX another point here is that if either side of an FK constraint
5954 * is an inheritance parent, we estimate as though the constraint
5955 * covers all its children as well. This is not an unreasonable
5956 * assumption for a referencing table, ie the user probably applied
5957 * identical constraints to all child tables (though perhaps we ought
5958 * to check that). But it's not possible to have done that for a
5959 * referenced table. Fortunately, precisely because that doesn't
5960 * work, it is uncommon in practice to have an FK referencing a parent
5961 * table. So, at least for now, disregard inheritance here.
5962 */
5963 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
5964 {
5965 /*
5966 * For JOIN_SEMI and JOIN_ANTI, we only get here when the FK's
5967 * referenced table is exactly the inside of the join. The join
5968 * selectivity is defined as the fraction of LHS rows that have
5969 * matches. The FK implies that every LHS row has a match *in the
5970 * referenced table*; but any restriction clauses on it will
5971 * reduce the number of matches. Hence we take the join
5972 * selectivity as equal to the selectivity of the table's
5973 * restriction clauses, which is rows / tuples; but we must guard
5974 * against tuples == 0.
5975 */
5976 RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5977 double ref_tuples = Max(ref_rel->tuples, 1.0);
5978
5979 fkselec *= ref_rel->rows / ref_tuples;
5980 }
5981 else
5982 {
5983 /*
5984 * Otherwise, selectivity is exactly 1/referenced-table-size; but
5985 * guard against tuples == 0. Note we should use the raw table
5986 * tuple count, not any estimate of its filtered or joined size.
5987 */
5988 RelOptInfo *ref_rel = find_base_rel(root, fkinfo->ref_relid);
5989 double ref_tuples = Max(ref_rel->tuples, 1.0);
5990
5991 fkselec *= 1.0 / ref_tuples;
5992 }
5993
5994 /*
5995 * If any of the FK columns participated in ec_has_const ECs, then
5996 * equivclass.c will have generated "var = const" restrictions for
5997 * each side of the join, thus reducing the sizes of both input
5998 * relations. Taking the fkselec at face value would amount to
5999 * double-counting the selectivity of the constant restriction for the
6000 * referencing Var. Hence, look for the restriction clause(s) that
6001 * were applied to the referencing Var(s), and divide out their
6002 * selectivity to correct for this.
6003 */
6004 if (fkinfo->nconst_ec > 0)
6005 {
6006 for (int i = 0; i < fkinfo->nkeys; i++)
6007 {
6008 EquivalenceClass *ec = fkinfo->eclass[i];
6009
6010 if (ec && ec->ec_has_const)
6011 {
6012 EquivalenceMember *em = fkinfo->fk_eclass_member[i];
6014 ec,
6015 em);
6016
6017 if (rinfo)
6018 {
6019 Selectivity s0;
6020
6022 (Node *) rinfo,
6023 0,
6024 jointype,
6025 sjinfo);
6026 if (s0 > 0)
6027 fkselec /= s0;
6028 }
6029 }
6030 }
6031 }
6032 }
6033
6034 *restrictlist = worklist;
6036 return fkselec;
6037}
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)
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:533
#define CLAMP_PROBABILITY(p)
Definition selfuncs.h:63

References bms_is_member(), bms_membership(), BMS_SINGLETON, CLAMP_PROBABILITY, clause_selectivity(), EquivalenceClass::ec_has_const, fb(), find_base_rel(), find_derived_clause_for_ec_member(), foreach_delete_current, i, JOIN_ANTI, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst, list_concat(), list_copy(), list_length(), list_member_ptr(), Max, NIL, and root.

Referenced by calc_joinrel_size_estimate().

◆ get_indexpath_pages()

static double get_indexpath_pages ( Path bitmapqual)
static

Definition at line 961 of file costsize.c.

962{
963 double result = 0;
964 ListCell *l;
965
966 if (IsA(bitmapqual, BitmapAndPath))
967 {
968 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
969
970 foreach(l, apath->bitmapquals)
971 {
972 result += get_indexpath_pages((Path *) lfirst(l));
973 }
974 }
975 else if (IsA(bitmapqual, BitmapOrPath))
976 {
977 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
978
979 foreach(l, opath->bitmapquals)
980 {
981 result += get_indexpath_pages((Path *) lfirst(l));
982 }
983 }
984 else if (IsA(bitmapqual, IndexPath))
985 {
986 IndexPath *ipath = (IndexPath *) bitmapqual;
987
988 result = (double) ipath->indexinfo->pages;
989 }
990 else
991 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
992
993 return result;
994}
BlockNumber pages
Definition pathnodes.h:1345

References elog, ERROR, fb(), get_indexpath_pages(), IsA, lfirst, and nodeTag.

Referenced by compute_bitmap_pages(), and get_indexpath_pages().

◆ get_parallel_divisor()

static double get_parallel_divisor ( Path path)
static

Definition at line 6621 of file costsize.c.

6622{
6623 double parallel_divisor = path->parallel_workers;
6624
6625 /*
6626 * Early experience with parallel query suggests that when there is only
6627 * one worker, the leader often makes a very substantial contribution to
6628 * executing the parallel portion of the plan, but as more workers are
6629 * added, it does less and less, because it's busy reading tuples from the
6630 * workers and doing whatever non-parallel post-processing is needed. By
6631 * the time we reach 4 workers, the leader no longer makes a meaningful
6632 * contribution. Thus, for now, estimate that the leader spends 30% of
6633 * its time servicing each worker, and the remainder executing the
6634 * parallel plan.
6635 */
6637 {
6638 double leader_contribution;
6639
6640 leader_contribution = 1.0 - (0.3 * path->parallel_workers);
6641 if (leader_contribution > 0)
6643 }
6644
6645 return parallel_divisor;
6646}
bool parallel_leader_participation
Definition planner.c:70

References fb(), 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 5526 of file costsize.c.

5528{
5530 double nrows;
5531
5532 /*
5533 * Estimate the number of rows returned by the parameterized scan, knowing
5534 * that it will apply all the extra join clauses as well as the rel's own
5535 * restriction clauses. Note that we force the clauses to be treated as
5536 * non-join clauses during selectivity estimation.
5537 */
5539 nrows = rel->tuples *
5541 allclauses,
5542 rel->relid, /* do not use 0! */
5543 JOIN_INNER,
5544 NULL);
5545 nrows = clamp_row_est(nrows);
5546 /* For safety, make sure result is not more than the base estimate */
5547 if (nrows > rel->rows)
5548 nrows = rel->rows;
5549 return nrows;
5550}
List * baserestrictinfo
Definition pathnodes.h:1124
Index relid
Definition pathnodes.h:1051
Cardinality tuples
Definition pathnodes.h:1078

References RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), fb(), 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 5607 of file costsize.c.

5612{
5613 double nrows;
5614
5615 /*
5616 * Estimate the number of rows returned by the parameterized join as the
5617 * sizes of the input paths times the selectivity of the clauses that have
5618 * ended up at this join node.
5619 *
5620 * As with set_joinrel_size_estimates, the rowcount estimate could depend
5621 * on the pair of input paths provided, though ideally we'd get the same
5622 * estimate for any pair with the same parameterization.
5623 */
5625 rel,
5626 outer_path->parent,
5627 inner_path->parent,
5628 outer_path->rows,
5629 inner_path->rows,
5630 sjinfo,
5632 /* For safety, make sure result is not more than the base estimate */
5633 if (nrows > rel->rows)
5634 nrows = rel->rows;
5635 return nrows;
5636}
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:5648

References calc_joinrel_size_estimate(), fb(), root, and RelOptInfo::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 5219 of file costsize.c.

5222{
5223 if (param_info)
5224 {
5225 /* Include costs of pushed-down clauses */
5226 cost_qual_eval(qpqual_cost, param_info->ppi_clauses, root);
5227
5228 qpqual_cost->startup += baserel->baserestrictcost.startup;
5229 qpqual_cost->per_tuple += baserel->baserestrictcost.per_tuple;
5230 }
5231 else
5232 *qpqual_cost = baserel->baserestrictcost;
5233}

References cost_qual_eval(), fb(), and root.

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

2996{
2997 int frameOptions = wc->frameOptions;
2998 double partition_tuples;
2999 double return_tuples;
3000 double peer_tuples;
3001
3002 /*
3003 * First, figure out how many partitions there are likely to be and set
3004 * partition_tuples according to that estimate.
3005 */
3006 if (wc->partitionClause != NIL)
3007 {
3008 double num_partitions;
3010 root->parse->targetList);
3011
3012 num_partitions = estimate_num_groups(root, partexprs, input_tuples,
3013 NULL, NULL);
3014 list_free(partexprs);
3015
3016 partition_tuples = input_tuples / num_partitions;
3017 }
3018 else
3019 {
3020 /* all tuples belong to the same partition */
3021 partition_tuples = input_tuples;
3022 }
3023
3024 /* estimate the number of tuples in each peer group */
3025 if (wc->orderClause != NIL)
3026 {
3027 double num_groups;
3029
3031 root->parse->targetList);
3032
3033 /* estimate out how many peer groups there are in the partition */
3036 NULL);
3039 }
3040 else
3041 {
3042 /* no ORDER BY so only 1 tuple belongs in each peer group */
3043 peer_tuples = 1.0;
3044 }
3045
3046 if (frameOptions & FRAMEOPTION_END_UNBOUNDED_FOLLOWING)
3047 {
3048 /* include all partition rows */
3050 }
3051 else if (frameOptions & FRAMEOPTION_END_CURRENT_ROW)
3052 {
3053 if (frameOptions & FRAMEOPTION_ROWS)
3054 {
3055 /* just count the current row */
3056 return_tuples = 1.0;
3057 }
3058 else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
3059 {
3060 /*
3061 * When in RANGE/GROUPS mode, it's more complex. If there's no
3062 * ORDER BY, then all rows in the partition are peers, otherwise
3063 * we'll need to read the first group of peers.
3064 */
3065 if (wc->orderClause == NIL)
3067 else
3069 }
3070 else
3071 {
3072 /*
3073 * Something new we don't support yet? This needs attention.
3074 * We'll just return 1.0 in the meantime.
3075 */
3076 Assert(false);
3077 return_tuples = 1.0;
3078 }
3079 }
3080 else if (frameOptions & FRAMEOPTION_END_OFFSET_PRECEDING)
3081 {
3082 /*
3083 * BETWEEN ... AND N PRECEDING will only need to read the WindowAgg's
3084 * subnode after N ROWS/RANGES/GROUPS. N can be 0, but not negative,
3085 * so we'll just assume only the current row needs to be read to fetch
3086 * the first WindowAgg row.
3087 */
3088 return_tuples = 1.0;
3089 }
3090 else if (frameOptions & FRAMEOPTION_END_OFFSET_FOLLOWING)
3091 {
3092 Const *endOffset = (Const *) wc->endOffset;
3093 double end_offset_value;
3094
3095 /* try and figure out the value specified in the endOffset. */
3096 if (IsA(endOffset, Const))
3097 {
3098 if (endOffset->constisnull)
3099 {
3100 /*
3101 * NULLs are not allowed, but currently, there's no code to
3102 * error out if there's a NULL Const. We'll only discover
3103 * this during execution. For now, just pretend everything is
3104 * fine and assume that just the first row/range/group will be
3105 * needed.
3106 */
3107 end_offset_value = 1.0;
3108 }
3109 else
3110 {
3111 switch (endOffset->consttype)
3112 {
3113 case INT2OID:
3115 (double) DatumGetInt16(endOffset->constvalue);
3116 break;
3117 case INT4OID:
3119 (double) DatumGetInt32(endOffset->constvalue);
3120 break;
3121 case INT8OID:
3123 (double) DatumGetInt64(endOffset->constvalue);
3124 break;
3125 default:
3129 break;
3130 }
3131 }
3132 }
3133 else
3134 {
3135 /*
3136 * When the end bound is not a Const, we'll just need to guess. We
3137 * just make use of DEFAULT_INEQ_SEL.
3138 */
3141 }
3142
3143 if (frameOptions & FRAMEOPTION_ROWS)
3144 {
3145 /* include the N FOLLOWING and the current row */
3147 }
3148 else if (frameOptions & (FRAMEOPTION_RANGE | FRAMEOPTION_GROUPS))
3149 {
3150 /* include N FOLLOWING ranges/group and the initial range/group */
3152 }
3153 else
3154 {
3155 /*
3156 * Something new we don't support yet? This needs attention.
3157 * We'll just return 1.0 in the meantime.
3158 */
3159 Assert(false);
3160 return_tuples = 1.0;
3161 }
3162 }
3163 else
3164 {
3165 /*
3166 * Something new we don't support yet? This needs attention. We'll
3167 * just return 1.0 in the meantime.
3168 */
3169 Assert(false);
3170 return_tuples = 1.0;
3171 }
3172
3173 if (wc->partitionClause != NIL || wc->orderClause != NIL)
3174 {
3175 /*
3176 * Cap the return value to the estimated partition tuples and account
3177 * for the extra tuple WindowAgg will need to read to confirm the next
3178 * tuple does not belong to the same partition or peer group.
3179 */
3181 }
3182 else
3183 {
3184 /*
3185 * Cap the return value so it's never higher than the expected tuples
3186 * in the partition.
3187 */
3189 }
3190
3191 /*
3192 * We needn't worry about any EXCLUDE options as those only exclude rows
3193 * from being aggregated, not from being read from the WindowAgg's
3194 * subnode.
3195 */
3196
3198}
#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
Node * endOffset
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(), fb(), 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(), 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 5358 of file costsize.c.

5359{
5360 JoinPath *joinpath = &path->jpath;
5361 Relids joinrelids = joinpath->path.parent->relids;
5362 Path *innerpath = joinpath->innerjoinpath;
5363 List *indexclauses;
5364 bool found_one;
5365 ListCell *lc;
5366
5367 /* If join still has quals to evaluate, it's not fast */
5368 if (joinpath->joinrestrictinfo != NIL)
5369 return false;
5370 /* Nor if the inner path isn't parameterized at all */
5371 if (innerpath->param_info == NULL)
5372 return false;
5373
5374 /* Find the indexclauses list for the inner scan */
5375 switch (innerpath->pathtype)
5376 {
5377 case T_IndexScan:
5378 case T_IndexOnlyScan:
5379 indexclauses = ((IndexPath *) innerpath)->indexclauses;
5380 break;
5381 case T_BitmapHeapScan:
5382 {
5383 /* Accept only a simple bitmap scan, not AND/OR cases */
5384 Path *bmqual = ((BitmapHeapPath *) innerpath)->bitmapqual;
5385
5386 if (IsA(bmqual, IndexPath))
5387 indexclauses = ((IndexPath *) bmqual)->indexclauses;
5388 else
5389 return false;
5390 break;
5391 }
5392 default:
5393
5394 /*
5395 * If it's not a simple indexscan, it probably doesn't run quickly
5396 * for zero rows out, even if it's a parameterized path using all
5397 * the joinquals.
5398 */
5399 return false;
5400 }
5401
5402 /*
5403 * Examine the inner path's param clauses. Any that are from the outer
5404 * path must be found in the indexclauses list, either exactly or in an
5405 * equivalent form generated by equivclass.c. Also, we must find at least
5406 * one such clause, else it's a clauseless join which isn't fast.
5407 */
5408 found_one = false;
5409 foreach(lc, innerpath->param_info->ppi_clauses)
5410 {
5411 RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
5412
5414 innerpath->parent->relids,
5415 joinrelids))
5416 {
5417 if (!is_redundant_with_indexclauses(rinfo, indexclauses))
5418 return false;
5419 found_one = true;
5420 }
5421 }
5422 return found_one;
5423}
bool join_clause_is_movable_into(RestrictInfo *rinfo, Relids currentrelids, Relids current_and_outer)

References fb(), is_redundant_with_indexclauses(), IsA, join_clause_is_movable_into(), NestPath::jpath, lfirst, and NIL.

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

898{
899 double pages_fetched;
900 double total_pages;
901 double T,
902 b;
903
904 /* T is # pages in table, but don't allow it to be zero */
905 T = (pages > 1) ? (double) pages : 1.0;
906
907 /* Compute number of pages assumed to be competing for cache space */
908 total_pages = root->total_table_pages + index_pages;
910 Assert(T <= total_pages);
911
912 /* b is pro-rated share of effective_cache_size */
914
915 /* force it positive and integral */
916 if (b <= 1.0)
917 b = 1.0;
918 else
919 b = ceil(b);
920
921 /* This part is the Mackert and Lohman formula */
922 if (T <= b)
923 {
925 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
926 if (pages_fetched >= T)
928 else
930 }
931 else
932 {
933 double lim;
934
935 lim = (2.0 * T * b) / (2.0 * T - b);
936 if (tuples_fetched <= lim)
937 {
939 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
940 }
941 else
942 {
944 b + (tuples_fetched - lim) * (T - b) / T;
945 }
947 }
948 return pages_fetched;
949}
int effective_cache_size
Definition costsize.c:139
int b
Definition isn.c:74

References Assert, b, effective_cache_size, fb(), 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 4301 of file costsize.c.

4307{
4308 int disabled_nodes;
4309 Cost startup_cost = 0;
4310 Cost run_cost = 0;
4311 double outer_path_rows = outer_path->rows;
4312 double inner_path_rows = inner_path->rows;
4314 int num_hashclauses = list_length(hashclauses);
4315 int numbuckets;
4316 int numbatches;
4317 int num_skew_mcvs;
4318 size_t space_allowed; /* unused */
4320
4321 if (outer_path->parallel_workers == 0)
4323
4324 /* Count up disabled nodes. */
4325 disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
4326 disabled_nodes += inner_path->disabled_nodes;
4327 disabled_nodes += outer_path->disabled_nodes;
4328
4329 /* cost of source data */
4330 startup_cost += outer_path->startup_cost;
4331 run_cost += outer_path->total_cost - outer_path->startup_cost;
4332 startup_cost += inner_path->total_cost;
4333
4334 /*
4335 * Cost of computing hash function: must do it once per input tuple. We
4336 * charge one cpu_operator_cost for each column's hash function. Also,
4337 * tack on one cpu_tuple_cost per inner row, to model the costs of
4338 * inserting the row into the hashtable.
4339 *
4340 * XXX when a hashclause is more complex than a single operator, we really
4341 * should charge the extra eval costs of the left or right side, as
4342 * appropriate, here. This seems more work than it's worth at the moment.
4343 */
4347
4348 /*
4349 * If this is a parallel hash build, then the value we have for
4350 * inner_rows_total currently refers only to the rows returned by each
4351 * participant. For shared hash table size estimation, we need the total
4352 * number, so we need to undo the division.
4353 */
4354 if (parallel_hash)
4356
4357 /*
4358 * Get hash table size that executor would use for inner relation.
4359 *
4360 * XXX for the moment, always assume that skew optimization will be
4361 * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
4362 * trying to determine that for sure.
4363 *
4364 * XXX at some point it might be interesting to try to account for skew
4365 * optimization in the cost estimate, but for now, we don't.
4366 */
4368 inner_path->pathtarget->width,
4369 true, /* useskew */
4370 parallel_hash, /* try_combined_hash_mem */
4371 outer_path->parallel_workers,
4372 &space_allowed,
4373 &numbuckets,
4374 &numbatches,
4375 &num_skew_mcvs);
4376
4377 /*
4378 * If inner relation is too big then we will need to "batch" the join,
4379 * which implies writing and reading most of the tuples to disk an extra
4380 * time. Charge seq_page_cost per page, since the I/O should be nice and
4381 * sequential. Writing the inner rel counts as startup cost, all the rest
4382 * as run cost.
4383 */
4384 if (numbatches > 1)
4385 {
4387 outer_path->pathtarget->width);
4389 inner_path->pathtarget->width);
4390
4391 startup_cost += seq_page_cost * innerpages;
4392 run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4393 }
4394
4395 /* CPU costs left for later */
4396
4397 /* Public result fields */
4398 workspace->disabled_nodes = disabled_nodes;
4399 workspace->startup_cost = startup_cost;
4400 workspace->total_cost = startup_cost + run_cost;
4401 /* Save private data for final_cost_hashjoin */
4402 workspace->run_cost = run_cost;
4403 workspace->numbuckets = numbuckets;
4404 workspace->numbatches = numbatches;
4406}
static double page_size(double tuples, int width)
Definition costsize.c:6611
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
#define PGS_HASHJOIN
Definition pathnodes.h:77

References cpu_operator_cost, cpu_tuple_cost, JoinCostWorkspace::disabled_nodes, ExecChooseHashTableSize(), fb(), get_parallel_divisor(), JoinCostWorkspace::inner_rows_total, list_length(), JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, page_size(), PGS_CONSIDER_NONPARTIAL, PGS_HASHJOIN, JoinPathExtraData::pgs_mask, JoinCostWorkspace::run_cost, seq_page_cost, JoinCostWorkspace::startup_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 3662 of file costsize.c.

3669{
3670 int disabled_nodes;
3671 Cost startup_cost = 0;
3672 Cost run_cost = 0;
3673 double outer_path_rows = outer_path->rows;
3674 double inner_path_rows = inner_path->rows;
3675 Cost inner_run_cost;
3676 double outer_rows,
3677 inner_rows,
3678 outer_skip_rows,
3679 inner_skip_rows;
3684 Path sort_path; /* dummy for result of
3685 * cost_sort/cost_incremental_sort */
3686
3687 /* Protect some assumptions below that rowcounts aren't zero */
3688 if (outer_path_rows <= 0)
3689 outer_path_rows = 1;
3690 if (inner_path_rows <= 0)
3691 inner_path_rows = 1;
3692
3693 /*
3694 * A merge join will stop as soon as it exhausts either input stream
3695 * (unless it's an outer join, in which case the outer side has to be
3696 * scanned all the way anyway). Estimate fraction of the left and right
3697 * inputs that will actually need to be scanned. Likewise, we can
3698 * estimate the number of rows that will be skipped before the first join
3699 * pair is found, which should be factored into startup cost. We use only
3700 * the first (most significant) merge clause for this purpose. Since
3701 * mergejoinscansel() is a fairly expensive computation, we cache the
3702 * results in the merge clause RestrictInfo.
3703 */
3704 if (mergeclauses && jointype != JOIN_FULL)
3705 {
3706 RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3707 List *opathkeys;
3708 List *ipathkeys;
3711 MergeScanSelCache *cache;
3712
3713 /* Get the input pathkeys to determine the sort-order details */
3714 opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3715 ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3720 /* debugging check */
3721 if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3722 opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3723 opathkey->pk_cmptype != ipathkey->pk_cmptype ||
3724 opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3725 elog(ERROR, "left and right pathkeys do not match in mergejoin");
3726
3727 /* Get the selectivity with caching */
3729
3730 if (bms_is_subset(firstclause->left_relids,
3731 outer_path->parent->relids))
3732 {
3733 /* left side of clause is outer */
3734 outerstartsel = cache->leftstartsel;
3735 outerendsel = cache->leftendsel;
3737 innerendsel = cache->rightendsel;
3738 }
3739 else
3740 {
3741 /* left side of clause is inner */
3743 outerendsel = cache->rightendsel;
3744 innerstartsel = cache->leftstartsel;
3745 innerendsel = cache->leftendsel;
3746 }
3747 if (jointype == JOIN_LEFT ||
3748 jointype == JOIN_ANTI)
3749 {
3750 outerstartsel = 0.0;
3751 outerendsel = 1.0;
3752 }
3753 else if (jointype == JOIN_RIGHT ||
3754 jointype == JOIN_RIGHT_ANTI)
3755 {
3756 innerstartsel = 0.0;
3757 innerendsel = 1.0;
3758 }
3759 }
3760 else
3761 {
3762 /* cope with clauseless or full mergejoin */
3764 outerendsel = innerendsel = 1.0;
3765 }
3766
3767 /*
3768 * Convert selectivities to row counts. We force outer_rows and
3769 * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3770 */
3771 outer_skip_rows = rint(outer_path_rows * outerstartsel);
3772 inner_skip_rows = rint(inner_path_rows * innerstartsel);
3775
3776 Assert(outer_skip_rows <= outer_rows);
3777 Assert(inner_skip_rows <= inner_rows);
3778
3779 /*
3780 * Readjust scan selectivities to account for above rounding. This is
3781 * normally an insignificant effect, but when there are only a few rows in
3782 * the inputs, failing to do this makes for a large percentage error.
3783 */
3784 outerstartsel = outer_skip_rows / outer_path_rows;
3785 innerstartsel = inner_skip_rows / inner_path_rows;
3786 outerendsel = outer_rows / outer_path_rows;
3787 innerendsel = inner_rows / inner_path_rows;
3788
3791
3792 /*
3793 * We don't decide whether to materialize the inner path until we get to
3794 * final_cost_mergejoin(), so we don't know whether to check the pgs_mask
3795 * against PGS_MERGEJOIN_PLAIN or PGS_MERGEJOIN_MATERIALIZE. Instead, we
3796 * just account for any child nodes here and assume that this node is not
3797 * itself disabled; we can sort out the details in final_cost_mergejoin().
3798 *
3799 * (We could be more precise here by setting disabled_nodes to 1 at this
3800 * stage if both PGS_MERGEJOIN_PLAIN and PGS_MERGEJOIN_MATERIALIZE are
3801 * disabled, but that seems to against the idea of making this function
3802 * produce a quick, optimistic approximation of the final cost.)
3803 */
3804 disabled_nodes = 0;
3805
3806 /* cost of source data */
3807
3808 if (outersortkeys) /* do we need to sort outer? */
3809 {
3810 /*
3811 * We can assert that the outer path is not already ordered
3812 * appropriately for the mergejoin; otherwise, outersortkeys would
3813 * have been set to NIL.
3814 */
3815 Assert(!pathkeys_contained_in(outersortkeys, outer_path->pathkeys));
3816
3817 /*
3818 * We choose to use incremental sort if it is enabled and there are
3819 * presorted keys; otherwise we use full sort.
3820 */
3821 if (enable_incremental_sort && outer_presorted_keys > 0)
3822 {
3824 root,
3825 outersortkeys,
3826 outer_presorted_keys,
3827 outer_path->disabled_nodes,
3828 outer_path->startup_cost,
3829 outer_path->total_cost,
3831 outer_path->pathtarget->width,
3832 0.0,
3833 work_mem,
3834 -1.0);
3835 }
3836 else
3837 {
3839 root,
3840 outersortkeys,
3841 outer_path->disabled_nodes,
3842 outer_path->total_cost,
3844 outer_path->pathtarget->width,
3845 0.0,
3846 work_mem,
3847 -1.0);
3848 }
3849
3850 disabled_nodes += sort_path.disabled_nodes;
3851 startup_cost += sort_path.startup_cost;
3852 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3853 * outerstartsel;
3854 run_cost += (sort_path.total_cost - sort_path.startup_cost)
3856 }
3857 else
3858 {
3859 disabled_nodes += outer_path->disabled_nodes;
3860 startup_cost += outer_path->startup_cost;
3861 startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3862 * outerstartsel;
3863 run_cost += (outer_path->total_cost - outer_path->startup_cost)
3865 }
3866
3867 if (innersortkeys) /* do we need to sort inner? */
3868 {
3869 /*
3870 * We can assert that the inner path is not already ordered
3871 * appropriately for the mergejoin; otherwise, innersortkeys would
3872 * have been set to NIL.
3873 */
3874 Assert(!pathkeys_contained_in(innersortkeys, inner_path->pathkeys));
3875
3876 /*
3877 * We do not consider incremental sort for inner path, because
3878 * incremental sort does not support mark/restore.
3879 */
3880
3882 root,
3883 innersortkeys,
3884 inner_path->disabled_nodes,
3885 inner_path->total_cost,
3887 inner_path->pathtarget->width,
3888 0.0,
3889 work_mem,
3890 -1.0);
3891 disabled_nodes += sort_path.disabled_nodes;
3892 startup_cost += sort_path.startup_cost;
3893 startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3894 * innerstartsel;
3895 inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3897 }
3898 else
3899 {
3900 disabled_nodes += inner_path->disabled_nodes;
3901 startup_cost += inner_path->startup_cost;
3902 startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3903 * innerstartsel;
3904 inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3906 }
3907
3908 /*
3909 * We can't yet determine whether rescanning occurs, or whether
3910 * materialization of the inner input should be done. The minimum
3911 * possible inner input cost, regardless of rescan and materialization
3912 * considerations, is inner_run_cost. We include that in
3913 * workspace->total_cost, but not yet in run_cost.
3914 */
3915
3916 /* CPU costs left for later */
3917
3918 /* Public result fields */
3919 workspace->disabled_nodes = disabled_nodes;
3920 workspace->startup_cost = startup_cost;
3921 workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3922 /* Save private data for final_cost_mergejoin */
3923 workspace->run_cost = run_cost;
3924 workspace->inner_run_cost = inner_run_cost;
3925 workspace->outer_rows = outer_rows;
3926 workspace->inner_rows = inner_rows;
3927 workspace->outer_skip_rows = outer_skip_rows;
3928 workspace->inner_skip_rows = inner_skip_rows;
3929}
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition costsize.c:4222
@ 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(), JoinCostWorkspace::disabled_nodes, elog, enable_incremental_sort, ERROR, fb(), 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, pathkeys_contained_in(), MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, root, JoinCostWorkspace::run_cost, JoinCostWorkspace::startup_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,
uint64  enable_mask,
Path outer_path,
Path inner_path,
JoinPathExtraData extra 
)

Definition at line 3377 of file costsize.c.

3381{
3382 int disabled_nodes;
3383 Cost startup_cost = 0;
3384 Cost run_cost = 0;
3385 double outer_path_rows = outer_path->rows;
3388 Cost inner_run_cost;
3389 Cost inner_rescan_run_cost;
3390
3391 /* Count up disabled nodes. */
3392 disabled_nodes = (extra->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
3393 disabled_nodes += inner_path->disabled_nodes;
3394 disabled_nodes += outer_path->disabled_nodes;
3395
3396 /* estimate costs to rescan the inner relation */
3400
3401 /* cost of source data */
3402
3403 /*
3404 * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3405 * before we can start returning tuples, so the join's startup cost is
3406 * their sum. We'll also pay the inner path's rescan startup cost
3407 * multiple times.
3408 */
3409 startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3410 run_cost += outer_path->total_cost - outer_path->startup_cost;
3411 if (outer_path_rows > 1)
3412 run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3413
3414 inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3415 inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3416
3417 if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3418 extra->inner_unique)
3419 {
3420 /*
3421 * With a SEMI or ANTI join, or if the innerrel is known unique, the
3422 * executor will stop after the first match.
3423 *
3424 * Getting decent estimates requires inspection of the join quals,
3425 * which we choose to postpone to final_cost_nestloop.
3426 */
3427
3428 /* Save private data for final_cost_nestloop */
3429 workspace->inner_run_cost = inner_run_cost;
3430 workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3431 }
3432 else
3433 {
3434 /* Normal case; we'll scan whole input rel for each outer row */
3435 run_cost += inner_run_cost;
3436 if (outer_path_rows > 1)
3437 run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3438 }
3439
3440 /* CPU costs left for later */
3441
3442 /* Public result fields */
3443 workspace->disabled_nodes = disabled_nodes;
3444 workspace->startup_cost = startup_cost;
3445 workspace->total_cost = startup_cost + run_cost;
3446 /* Save private data for final_cost_nestloop */
3447 workspace->run_cost = run_cost;
3448}
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition costsize.c:4788

References cost_rescan(), JoinCostWorkspace::disabled_nodes, fb(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JOIN_ANTI, JOIN_SEMI, JoinPathExtraData::pgs_mask, root, JoinCostWorkspace::run_cost, JoinCostWorkspace::startup_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 6611 of file costsize.c.

6612{
6613 return ceil(relation_byte_size(tuples, width) / BLCKSZ);
6614}

References fb(), and relation_byte_size().

Referenced by initial_cost_hashjoin().

◆ relation_byte_size()

static double relation_byte_size ( double  tuples,
int  width 
)
static

Definition at line 6600 of file costsize.c.

6601{
6602 return tuples * (MAXALIGN(width) + MAXALIGN(SizeofHeapTupleHeader));
6603}
#define MAXALIGN(LEN)
Definition c.h:826
#define SizeofHeapTupleHeader

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

6223{
6225
6226 /* Should only be applied to base relations that are CTE references */
6227 Assert(rel->relid > 0);
6228 rte = planner_rt_fetch(rel->relid, root);
6229 Assert(rte->rtekind == RTE_CTE);
6230
6231 if (rte->self_reference)
6232 {
6233 /*
6234 * In a self-reference, we assume the average worktable size is a
6235 * multiple of the nonrecursive term's size. The best multiplier will
6236 * vary depending on query "fan-out", so make its value adjustable.
6237 */
6239 }
6240 else
6241 {
6242 /* Otherwise just believe the CTE's rowcount estimate */
6243 rel->tuples = cte_rows;
6244 }
6245
6246 /* Now estimate number of output rows, etc */
6248}
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:5496
double recursive_worktable_factor
Definition costsize.c:137

References Assert, clamp_row_est(), fb(), planner_rt_fetch, recursive_worktable_factor, RelOptInfo::relid, root, RTE_CTE, 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 6322 of file costsize.c.

6323{
6324 /* Should only be applied to base relations */
6325 Assert(rel->relid > 0);
6326
6327 rel->rows = 1000; /* entirely bogus default estimate */
6328
6330
6331 set_rel_width(root, rel);
6332}

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

6131{
6133 ListCell *lc;
6134
6135 /* Should only be applied to base relations that are functions */
6136 Assert(rel->relid > 0);
6137 rte = planner_rt_fetch(rel->relid, root);
6138 Assert(rte->rtekind == RTE_FUNCTION);
6139
6140 /*
6141 * Estimate number of rows the functions will return. The rowcount of the
6142 * node is that of the largest function result.
6143 */
6144 rel->tuples = 0;
6145 foreach(lc, rte->functions)
6146 {
6148 double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
6149
6150 if (ntup > rel->tuples)
6151 rel->tuples = ntup;
6152 }
6153
6154 /* Now estimate number of output rows, etc */
6156}
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition clauses.c:298

References Assert, expression_returns_set_rows(), fb(), RangeTblFunction::funcexpr, lfirst, planner_rt_fetch, RelOptInfo::relid, root, RTE_FUNCTION, 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 5575 of file costsize.c.

5580{
5582 rel,
5583 outer_rel,
5584 inner_rel,
5585 outer_rel->rows,
5586 inner_rel->rows,
5587 sjinfo,
5588 restrictlist);
5589}

References calc_joinrel_size_estimate(), fb(), 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 6260 of file costsize.c.

6261{
6263
6264 /* Should only be applied to base relations that are tuplestore references */
6265 Assert(rel->relid > 0);
6266 rte = planner_rt_fetch(rel->relid, root);
6267 Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
6268
6269 /*
6270 * Use the estimate provided by the code which is generating the named
6271 * tuplestore. In some cases, the actual number might be available; in
6272 * others the same plan will be re-used, so a "typical" value might be
6273 * estimated and used.
6274 */
6275 rel->tuples = rte->enrtuples;
6276 if (rel->tuples < 0)
6277 rel->tuples = 1000;
6278
6279 /* Now estimate number of output rows, etc */
6281}

References Assert, fb(), planner_rt_fetch, RelOptInfo::relid, root, RTE_NAMEDTUPLESTORE, 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 6514 of file costsize.c.

6515{
6516 int64 tuple_width = 0;
6517 ListCell *lc;
6518
6519 /* Vars are assumed to have cost zero, but other exprs do not */
6520 target->cost.startup = 0;
6521 target->cost.per_tuple = 0;
6522
6523 foreach(lc, target->exprs)
6524 {
6525 Node *node = (Node *) lfirst(lc);
6526
6528
6529 /* For non-Vars, account for evaluation cost */
6530 if (!IsA(node, Var))
6531 {
6532 QualCost cost;
6533
6534 cost_qual_eval_node(&cost, node, root);
6535 target->cost.startup += cost.startup;
6536 target->cost.per_tuple += cost.per_tuple;
6537 }
6538 }
6539
6541
6542 return target;
6543}
int32 clamp_width_est(int64 tuple_width)
Definition costsize.c:242
List * exprs
Definition pathnodes.h:1858
QualCost cost
Definition pathnodes.h:1864

References clamp_width_est(), PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, fb(), 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 6357 of file costsize.c.

6358{
6359 Oid reloid = planner_rt_fetch(rel->relid, root)->relid;
6360 int64 tuple_width = 0;
6361 bool have_wholerow_var = false;
6362 ListCell *lc;
6363
6364 /* Vars are assumed to have cost zero, but other exprs do not */
6365 rel->reltarget->cost.startup = 0;
6366 rel->reltarget->cost.per_tuple = 0;
6367
6368 foreach(lc, rel->reltarget->exprs)
6369 {
6370 Node *node = (Node *) lfirst(lc);
6371
6372 /*
6373 * Ordinarily, a Var in a rel's targetlist must belong to that rel;
6374 * but there are corner cases involving LATERAL references where that
6375 * isn't so. If the Var has the wrong varno, fall through to the
6376 * generic case (it doesn't seem worth the trouble to be any smarter).
6377 */
6378 if (IsA(node, Var) &&
6379 ((Var *) node)->varno == rel->relid)
6380 {
6381 Var *var = (Var *) node;
6382 int ndx;
6384
6385 Assert(var->varattno >= rel->min_attr);
6386 Assert(var->varattno <= rel->max_attr);
6387
6388 ndx = var->varattno - rel->min_attr;
6389
6390 /*
6391 * If it's a whole-row Var, we'll deal with it below after we have
6392 * already cached as many attr widths as possible.
6393 */
6394 if (var->varattno == 0)
6395 {
6396 have_wholerow_var = true;
6397 continue;
6398 }
6399
6400 /*
6401 * The width may have been cached already (especially if it's a
6402 * subquery), so don't duplicate effort.
6403 */
6404 if (rel->attr_widths[ndx] > 0)
6405 {
6406 tuple_width += rel->attr_widths[ndx];
6407 continue;
6408 }
6409
6410 /* Try to get column width from statistics */
6411 if (reloid != InvalidOid && var->varattno > 0)
6412 {
6413 item_width = get_attavgwidth(reloid, var->varattno);
6414 if (item_width > 0)
6415 {
6416 rel->attr_widths[ndx] = item_width;
6418 continue;
6419 }
6420 }
6421
6422 /*
6423 * Not a plain relation, or can't find statistics for it. Estimate
6424 * using just the type info.
6425 */
6426 item_width = get_typavgwidth(var->vartype, var->vartypmod);
6427 Assert(item_width > 0);
6428 rel->attr_widths[ndx] = item_width;
6430 }
6431 else if (IsA(node, PlaceHolderVar))
6432 {
6433 /*
6434 * We will need to evaluate the PHV's contained expression while
6435 * scanning this rel, so be sure to include it in reltarget->cost.
6436 */
6437 PlaceHolderVar *phv = (PlaceHolderVar *) node;
6439 QualCost cost;
6440
6441 tuple_width += phinfo->ph_width;
6442 cost_qual_eval_node(&cost, (Node *) phv->phexpr, root);
6443 rel->reltarget->cost.startup += cost.startup;
6444 rel->reltarget->cost.per_tuple += cost.per_tuple;
6445 }
6446 else
6447 {
6448 /*
6449 * We could be looking at an expression pulled up from a subquery,
6450 * or a ROW() representing a whole-row child Var, etc. Do what we
6451 * can using the expression type information.
6452 */
6454 QualCost cost;
6455
6457 Assert(item_width > 0);
6459 /* Not entirely clear if we need to account for cost, but do so */
6460 cost_qual_eval_node(&cost, node, root);
6461 rel->reltarget->cost.startup += cost.startup;
6462 rel->reltarget->cost.per_tuple += cost.per_tuple;
6463 }
6464 }
6465
6466 /*
6467 * If we have a whole-row reference, estimate its width as the sum of
6468 * per-column widths plus heap tuple header overhead.
6469 */
6471 {
6473
6474 if (reloid != InvalidOid)
6475 {
6476 /* Real relation, so estimate true tuple width */
6478 rel->attr_widths - rel->min_attr);
6479 }
6480 else
6481 {
6482 /* Do what we can with info for a phony rel */
6483 AttrNumber i;
6484
6485 for (i = 1; i <= rel->max_attr; i++)
6486 wholerow_width += rel->attr_widths[i - rel->min_attr];
6487 }
6488
6489 rel->attr_widths[0 - rel->min_attr] = clamp_width_est(wholerow_width);
6490
6491 /*
6492 * Include the whole-row Var as part of the output tuple. Yes, that
6493 * really is what happens at runtime.
6494 */
6496 }
6497
6499}
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:1477
#define InvalidOid
struct PathTarget * reltarget
Definition pathnodes.h:1027

References Assert, clamp_width_est(), PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, exprType(), exprTypmod(), fb(), 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, 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 6293 of file costsize.c.

6294{
6295 /* Should only be applied to RTE_RESULT base relations */
6296 Assert(rel->relid > 0);
6297 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6298
6299 /* RTE_RESULT always generates a single row, natively */
6300 rel->tuples = 1;
6301
6302 /* Now estimate number of output rows, etc */
6304}

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

6051{
6052 PlannerInfo *subroot = rel->subroot;
6054 ListCell *lc;
6055
6056 /* Should only be applied to base relations that are subqueries */
6057 Assert(rel->relid > 0);
6058 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
6059
6060 /*
6061 * Copy raw number of output rows from subquery. All of its paths should
6062 * have the same output rowcount, so just look at cheapest-total.
6063 */
6065 rel->tuples = sub_final_rel->cheapest_total_path->rows;
6066
6067 /*
6068 * Compute per-output-column width estimates by examining the subquery's
6069 * targetlist. For any output that is a plain Var, get the width estimate
6070 * that was made while planning the subquery. Otherwise, we leave it to
6071 * set_rel_width to fill in a datatype-based default estimate.
6072 */
6073 foreach(lc, subroot->parse->targetList)
6074 {
6076 Node *texpr = (Node *) te->expr;
6077 int32 item_width = 0;
6078
6079 /* junk columns aren't visible to upper query */
6080 if (te->resjunk)
6081 continue;
6082
6083 /*
6084 * The subquery could be an expansion of a view that's had columns
6085 * added to it since the current query was parsed, so that there are
6086 * non-junk tlist columns in it that don't correspond to any column
6087 * visible at our query level. Ignore such columns.
6088 */
6089 if (te->resno < rel->min_attr || te->resno > rel->max_attr)
6090 continue;
6091
6092 /*
6093 * XXX This currently doesn't work for subqueries containing set
6094 * operations, because the Vars in their tlists are bogus references
6095 * to the first leaf subquery, which wouldn't give the right answer
6096 * even if we could still get to its PlannerInfo.
6097 *
6098 * Also, the subquery could be an appendrel for which all branches are
6099 * known empty due to constraint exclusion, in which case
6100 * set_append_rel_pathlist will have left the attr_widths set to zero.
6101 *
6102 * In either case, we just leave the width estimate zero until
6103 * set_rel_width fixes it.
6104 */
6105 if (IsA(texpr, Var) &&
6106 subroot->parse->setOperations == NULL)
6107 {
6108 Var *var = (Var *) texpr;
6109 RelOptInfo *subrel = find_base_rel(subroot, var->varno);
6110
6111 item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
6112 }
6113 rel->attr_widths[te->resno - rel->min_attr] = item_width;
6114 }
6115
6116 /* Now estimate number of output rows, etc */
6118}
@ UPPERREL_FINAL
Definition pathnodes.h:152
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition relnode.c:1606
Query * parse
Definition pathnodes.h:303
Node * setOperations
Definition parsenodes.h:236
List * targetList
Definition parsenodes.h:198
PlannerInfo * subroot
Definition pathnodes.h:1082
Expr * expr
Definition primnodes.h:2239

References Assert, TargetEntry::expr, fb(), fetch_upper_rel(), find_base_rel(), IsA, lfirst_node, RelOptInfo::max_attr, RelOptInfo::min_attr, PlannerInfo::parse, planner_rt_fetch, RelOptInfo::relid, TargetEntry::resno, root, 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 6168 of file costsize.c.

6169{
6170 /* Should only be applied to base relations that are functions */
6171 Assert(rel->relid > 0);
6172 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
6173
6174 rel->tuples = 100;
6175
6176 /* Now estimate number of output rows, etc */
6178}

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

6191{
6193
6194 /* Should only be applied to base relations that are values lists */
6195 Assert(rel->relid > 0);
6196 rte = planner_rt_fetch(rel->relid, root);
6197 Assert(rte->rtekind == RTE_VALUES);
6198
6199 /*
6200 * Estimate number of rows the values list will return. We know this
6201 * precisely based on the list length (well, barring set-returning
6202 * functions in list items, but that's a refinement not catered for
6203 * anywhere else either).
6204 */
6205 rel->tuples = list_length(rte->values_lists);
6206
6207 /* Now estimate number of output rows, etc */
6209}

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

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

◆ enable_gathermerge

bool enable_gathermerge = true

Definition at line 158 of file costsize.c.

Referenced by standard_planner().

◆ enable_hashagg

◆ enable_hashjoin

bool enable_hashjoin = true

Definition at line 157 of file costsize.c.

Referenced by standard_planner().

◆ enable_incremental_sort

◆ enable_indexonlyscan

bool enable_indexonlyscan = true

Definition at line 147 of file costsize.c.

Referenced by standard_planner().

◆ enable_indexscan

bool enable_indexscan = true

Definition at line 146 of file costsize.c.

Referenced by plan_cluster_use_sort(), and standard_planner().

◆ enable_material

bool enable_material = true

Definition at line 154 of file costsize.c.

Referenced by build_subplan(), materialize_finished_plan(), and standard_planner().

◆ enable_memoize

bool enable_memoize = true

Definition at line 155 of file costsize.c.

Referenced by standard_planner().

◆ enable_mergejoin

bool enable_mergejoin = true

Definition at line 156 of file costsize.c.

Referenced by standard_planner().

◆ enable_nestloop

bool enable_nestloop = true

Definition at line 153 of file costsize.c.

Referenced by standard_planner().

◆ 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 set_append_rel_size(), and standard_planner().

◆ 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 standard_planner().

◆ 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 standard_planner().

◆ 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

◆ 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