PostgreSQL Source Code  git master
cost.h File Reference
#include "nodes/pathnodes.h"
#include "nodes/plannodes.h"
Include dependency graph for cost.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define DEFAULT_SEQ_PAGE_COST   1.0
 
#define DEFAULT_RANDOM_PAGE_COST   4.0
 
#define DEFAULT_CPU_TUPLE_COST   0.01
 
#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005
 
#define DEFAULT_CPU_OPERATOR_COST   0.0025
 
#define DEFAULT_PARALLEL_TUPLE_COST   0.1
 
#define DEFAULT_PARALLEL_SETUP_COST   1000.0
 
#define DEFAULT_RECURSIVE_WORKTABLE_FACTOR   10.0
 
#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */
 

Enumerations

enum  ConstraintExclusionType { CONSTRAINT_EXCLUSION_OFF , CONSTRAINT_EXCLUSION_ON , CONSTRAINT_EXCLUSION_PARTITION }
 

Functions

double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
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_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
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_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (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)
 
void cost_sort (Path *path, PlannerInfo *root, List *pathkeys, Cost input_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, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_append (AppendPath *apath)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, WindowClause *winclause, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, 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_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, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
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)
 
double get_parameterized_joinrel_size (PlannerInfo *root, RelOptInfo *rel, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, List *restrict_clauses)
 
void set_joinrel_size_estimates (PlannerInfo *root, RelOptInfo *rel, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *restrictlist)
 
void set_subquery_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
void set_function_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_tablefunc_size_estimates (PlannerInfo *root, RelOptInfo *rel)
 
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

PGDLLIMPORT Cost disable_cost
 
PGDLLIMPORT int max_parallel_workers_per_gather
 
PGDLLIMPORT bool enable_seqscan
 
PGDLLIMPORT bool enable_indexscan
 
PGDLLIMPORT bool enable_indexonlyscan
 
PGDLLIMPORT bool enable_bitmapscan
 
PGDLLIMPORT bool enable_tidscan
 
PGDLLIMPORT bool enable_sort
 
PGDLLIMPORT bool enable_incremental_sort
 
PGDLLIMPORT bool enable_hashagg
 
PGDLLIMPORT bool enable_nestloop
 
PGDLLIMPORT bool enable_material
 
PGDLLIMPORT bool enable_memoize
 
PGDLLIMPORT bool enable_mergejoin
 
PGDLLIMPORT bool enable_hashjoin
 
PGDLLIMPORT bool enable_gathermerge
 
PGDLLIMPORT bool enable_partitionwise_join
 
PGDLLIMPORT bool enable_partitionwise_aggregate
 
PGDLLIMPORT bool enable_parallel_append
 
PGDLLIMPORT bool enable_parallel_hash
 
PGDLLIMPORT bool enable_partition_pruning
 
PGDLLIMPORT bool enable_presorted_aggregate
 
PGDLLIMPORT bool enable_async_append
 
PGDLLIMPORT int constraint_exclusion
 

Macro Definition Documentation

◆ DEFAULT_CPU_INDEX_TUPLE_COST

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

◆ DEFAULT_CPU_OPERATOR_COST

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

◆ DEFAULT_CPU_TUPLE_COST

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

◆ DEFAULT_EFFECTIVE_CACHE_SIZE

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 34 of file cost.h.

◆ DEFAULT_PARALLEL_SETUP_COST

#define DEFAULT_PARALLEL_SETUP_COST   1000.0

Definition at line 30 of file cost.h.

◆ DEFAULT_PARALLEL_TUPLE_COST

#define DEFAULT_PARALLEL_TUPLE_COST   0.1

Definition at line 29 of file cost.h.

◆ DEFAULT_RANDOM_PAGE_COST

#define DEFAULT_RANDOM_PAGE_COST   4.0

Definition at line 25 of file cost.h.

◆ DEFAULT_RECURSIVE_WORKTABLE_FACTOR

#define DEFAULT_RECURSIVE_WORKTABLE_FACTOR   10.0

Definition at line 33 of file cost.h.

◆ DEFAULT_SEQ_PAGE_COST

#define DEFAULT_SEQ_PAGE_COST   1.0

Definition at line 24 of file cost.h.

Enumeration Type Documentation

◆ ConstraintExclusionType

Enumerator
CONSTRAINT_EXCLUSION_OFF 
CONSTRAINT_EXCLUSION_ON 
CONSTRAINT_EXCLUSION_PARTITION 

Definition at line 36 of file cost.h.

37 {
38  CONSTRAINT_EXCLUSION_OFF, /* do not use c_e */
39  CONSTRAINT_EXCLUSION_ON, /* apply c_e to all rels */
40  CONSTRAINT_EXCLUSION_PARTITION, /* apply c_e to otherrels only */
ConstraintExclusionType
Definition: cost.h:37
@ CONSTRAINT_EXCLUSION_OFF
Definition: cost.h:38
@ CONSTRAINT_EXCLUSION_PARTITION
Definition: cost.h:40
@ CONSTRAINT_EXCLUSION_ON
Definition: cost.h:39

Function Documentation

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

6380 {
6381  Cost indexTotalCost;
6382  Selectivity indexSelectivity;
6383  double T;
6384  double pages_fetched;
6385  double tuples_fetched;
6386  double heap_pages;
6387  long maxentries;
6388 
6389  /*
6390  * Fetch total cost of obtaining the bitmap, as well as its total
6391  * selectivity.
6392  */
6393  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6394 
6395  /*
6396  * Estimate number of main-table pages fetched.
6397  */
6398  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6399 
6400  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6401 
6402  /*
6403  * For a single scan, the number of heap pages that need to be fetched is
6404  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6405  * re-reads needed).
6406  */
6407  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6408 
6409  /*
6410  * Calculate the number of pages fetched from the heap. Then based on
6411  * current work_mem estimate get the estimated maxentries in the bitmap.
6412  * (Note that we always do this calculation based on the number of pages
6413  * that would be fetched in a single iteration, even if loop_count > 1.
6414  * That's correct, because only that number of entries will be stored in
6415  * the bitmap at one time.)
6416  */
6417  heap_pages = Min(pages_fetched, baserel->pages);
6418  maxentries = tbm_calculate_entries(work_mem * 1024L);
6419 
6420  if (loop_count > 1)
6421  {
6422  /*
6423  * For repeated bitmap scans, scale up the number of tuples fetched in
6424  * the Mackert and Lohman formula by the number of scans, so that we
6425  * estimate the number of pages fetched by all the scans. Then
6426  * pro-rate for one scan.
6427  */
6428  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6429  baserel->pages,
6430  get_indexpath_pages(bitmapqual),
6431  root);
6432  pages_fetched /= loop_count;
6433  }
6434 
6435  if (pages_fetched >= T)
6436  pages_fetched = T;
6437  else
6438  pages_fetched = ceil(pages_fetched);
6439 
6440  if (maxentries < heap_pages)
6441  {
6442  double exact_pages;
6443  double lossy_pages;
6444 
6445  /*
6446  * Crude approximation of the number of lossy pages. Because of the
6447  * way tbm_lossify() is coded, the number of lossy pages increases
6448  * very sharply as soon as we run short of memory; this formula has
6449  * that property and seems to perform adequately in testing, but it's
6450  * possible we could do better somehow.
6451  */
6452  lossy_pages = Max(0, heap_pages - maxentries / 2);
6453  exact_pages = heap_pages - lossy_pages;
6454 
6455  /*
6456  * If there are lossy pages then recompute the number of tuples
6457  * processed by the bitmap heap node. We assume here that the chance
6458  * of a given tuple coming from an exact page is the same as the
6459  * chance that a given page is exact. This might not be true, but
6460  * it's not clear how we can do any better.
6461  */
6462  if (lossy_pages > 0)
6463  tuples_fetched =
6464  clamp_row_est(indexSelectivity *
6465  (exact_pages / heap_pages) * baserel->tuples +
6466  (lossy_pages / heap_pages) * baserel->tuples);
6467  }
6468 
6469  if (cost_p)
6470  *cost_p = indexTotalCost;
6471  if (tuples_p)
6472  *tuples_p = tuples_fetched;
6473 
6474  return pages_fetched;
6475 }
#define Min(x, y)
Definition: c.h:1004
#define Max(x, y)
Definition: c.h:998
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:898
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:963
double clamp_row_est(double nrows)
Definition: costsize.c:202
int work_mem
Definition: globals.c:129
static const uint32 T[65]
Definition: md5.c:119
double Cost
Definition: nodes.h:251
double Selectivity
Definition: nodes.h:250
tree ctl root
Definition: radixtree.h:1886
Cardinality tuples
Definition: pathnodes.h:943
BlockNumber pages
Definition: pathnodes.h:942
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1542

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

◆ compute_gather_rows()

double compute_gather_rows ( Path path)

Definition at line 6488 of file costsize.c.

6489 {
6490  Assert(path->parallel_workers > 0);
6491 
6492  return clamp_row_est(path->rows * get_parallel_divisor(path));
6493 }
#define Assert(condition)
Definition: c.h:858
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6337
Cardinality rows
Definition: pathnodes.h:1660
int parallel_workers
Definition: pathnodes.h:1657

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

4986 {
4987  Selectivity jselec;
4988  Selectivity nselec;
4989  Selectivity avgmatch;
4990  SpecialJoinInfo norm_sjinfo;
4991  List *joinquals;
4992  ListCell *l;
4993 
4994  /*
4995  * In an ANTI join, we must ignore clauses that are "pushed down", since
4996  * those won't affect the match logic. In a SEMI join, we do not
4997  * distinguish joinquals from "pushed down" quals, so just use the whole
4998  * restrictinfo list. For other outer join types, we should consider only
4999  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5000  */
5001  if (IS_OUTER_JOIN(jointype))
5002  {
5003  joinquals = NIL;
5004  foreach(l, restrictlist)
5005  {
5006  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
5007 
5008  if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5009  joinquals = lappend(joinquals, rinfo);
5010  }
5011  }
5012  else
5013  joinquals = restrictlist;
5014 
5015  /*
5016  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5017  */
5018  jselec = clauselist_selectivity(root,
5019  joinquals,
5020  0,
5021  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5022  sjinfo);
5023 
5024  /*
5025  * Also get the normal inner-join selectivity of the join clauses.
5026  */
5027  init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
5028 
5029  nselec = clauselist_selectivity(root,
5030  joinquals,
5031  0,
5032  JOIN_INNER,
5033  &norm_sjinfo);
5034 
5035  /* Avoid leaking a lot of ListCells */
5036  if (IS_OUTER_JOIN(jointype))
5037  list_free(joinquals);
5038 
5039  /*
5040  * jselec can be interpreted as the fraction of outer-rel rows that have
5041  * any matches (this is true for both SEMI and ANTI cases). And nselec is
5042  * the fraction of the Cartesian product that matches. So, the average
5043  * number of matches for each outer-rel row that has at least one match is
5044  * nselec * inner_rows / jselec.
5045  *
5046  * Note: it is correct to use the inner rel's "rows" count here, even
5047  * though we might later be considering a parameterized inner path with
5048  * fewer rows. This is because we have included all the join clauses in
5049  * the selectivity estimate.
5050  */
5051  if (jselec > 0) /* protect against zero divide */
5052  {
5053  avgmatch = nselec * innerrel->rows / jselec;
5054  /* Clamp to sane range */
5055  avgmatch = Max(1.0, avgmatch);
5056  }
5057  else
5058  avgmatch = 1.0;
5059 
5060  semifactors->outer_match_frac = jselec;
5061  semifactors->match_count = avgmatch;
5062 }
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:100
void init_dummy_sjinfo(SpecialJoinInfo *sjinfo, Relids left_relids, Relids right_relids)
Definition: joinrels.c:669
List * lappend(List *list, void *datum)
Definition: list.c:339
void list_free(List *list)
Definition: list.c:1546
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:338
@ JOIN_SEMI
Definition: nodes.h:307
@ JOIN_INNER
Definition: nodes.h:293
@ JOIN_ANTI
Definition: nodes.h:308
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition: pathnodes.h:2721
#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:865
Cardinality rows
Definition: pathnodes.h:871
Selectivity outer_match_frac
Definition: pathnodes.h:3211
Selectivity match_count
Definition: pathnodes.h:3212

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

Referenced by add_paths_to_joinrel().

◆ cost_agg()

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

Definition at line 2629 of file costsize.c.

2635 {
2636  double output_tuples;
2637  Cost startup_cost;
2638  Cost total_cost;
2639  AggClauseCosts dummy_aggcosts;
2640 
2641  /* Use all-zero per-aggregate costs if NULL is passed */
2642  if (aggcosts == NULL)
2643  {
2644  Assert(aggstrategy == AGG_HASHED);
2645  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2646  aggcosts = &dummy_aggcosts;
2647  }
2648 
2649  /*
2650  * The transCost.per_tuple component of aggcosts should be charged once
2651  * per input tuple, corresponding to the costs of evaluating the aggregate
2652  * transfns and their input expressions. The finalCost.per_tuple component
2653  * is charged once per output tuple, corresponding to the costs of
2654  * evaluating the finalfns. Startup costs are of course charged but once.
2655  *
2656  * If we are grouping, we charge an additional cpu_operator_cost per
2657  * grouping column per input tuple for grouping comparisons.
2658  *
2659  * We will produce a single output tuple if not grouping, and a tuple per
2660  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2661  *
2662  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2663  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2664  * input path is already sorted appropriately, AGG_SORTED should be
2665  * preferred (since it has no risk of memory overflow). This will happen
2666  * as long as the computed total costs are indeed exactly equal --- but if
2667  * there's roundoff error we might do the wrong thing. So be sure that
2668  * the computations below form the same intermediate values in the same
2669  * order.
2670  */
2671  if (aggstrategy == AGG_PLAIN)
2672  {
2673  startup_cost = input_total_cost;
2674  startup_cost += aggcosts->transCost.startup;
2675  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2676  startup_cost += aggcosts->finalCost.startup;
2677  startup_cost += aggcosts->finalCost.per_tuple;
2678  /* we aren't grouping */
2679  total_cost = startup_cost + cpu_tuple_cost;
2680  output_tuples = 1;
2681  }
2682  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2683  {
2684  /* Here we are able to deliver output on-the-fly */
2685  startup_cost = input_startup_cost;
2686  total_cost = input_total_cost;
2687  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2688  {
2689  startup_cost += disable_cost;
2690  total_cost += disable_cost;
2691  }
2692  /* calcs phrased this way to match HASHED case, see note above */
2693  total_cost += aggcosts->transCost.startup;
2694  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2695  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2696  total_cost += aggcosts->finalCost.startup;
2697  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2698  total_cost += cpu_tuple_cost * numGroups;
2699  output_tuples = numGroups;
2700  }
2701  else
2702  {
2703  /* must be AGG_HASHED */
2704  startup_cost = input_total_cost;
2705  if (!enable_hashagg)
2706  startup_cost += disable_cost;
2707  startup_cost += aggcosts->transCost.startup;
2708  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2709  /* cost of computing hash value */
2710  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2711  startup_cost += aggcosts->finalCost.startup;
2712 
2713  total_cost = startup_cost;
2714  total_cost += aggcosts->finalCost.per_tuple * numGroups;
2715  /* cost of retrieving from hash table */
2716  total_cost += cpu_tuple_cost * numGroups;
2717  output_tuples = numGroups;
2718  }
2719 
2720  /*
2721  * Add the disk costs of hash aggregation that spills to disk.
2722  *
2723  * Groups that go into the hash table stay in memory until finalized, so
2724  * spilling and reprocessing tuples doesn't incur additional invocations
2725  * of transCost or finalCost. Furthermore, the computed hash value is
2726  * stored with the spilled tuples, so we don't incur extra invocations of
2727  * the hash function.
2728  *
2729  * Hash Agg begins returning tuples after the first batch is complete.
2730  * Accrue writes (spilled tuples) to startup_cost and to total_cost;
2731  * accrue reads only to total_cost.
2732  */
2733  if (aggstrategy == AGG_HASHED || aggstrategy == AGG_MIXED)
2734  {
2735  double pages;
2736  double pages_written = 0.0;
2737  double pages_read = 0.0;
2738  double spill_cost;
2739  double hashentrysize;
2740  double nbatches;
2741  Size mem_limit;
2742  uint64 ngroups_limit;
2743  int num_partitions;
2744  int depth;
2745 
2746  /*
2747  * Estimate number of batches based on the computed limits. If less
2748  * than or equal to one, all groups are expected to fit in memory;
2749  * otherwise we expect to spill.
2750  */
2751  hashentrysize = hash_agg_entry_size(list_length(root->aggtransinfos),
2752  input_width,
2753  aggcosts->transitionSpace);
2754  hash_agg_set_limits(hashentrysize, numGroups, 0, &mem_limit,
2755  &ngroups_limit, &num_partitions);
2756 
2757  nbatches = Max((numGroups * hashentrysize) / mem_limit,
2758  numGroups / ngroups_limit);
2759 
2760  nbatches = Max(ceil(nbatches), 1.0);
2761  num_partitions = Max(num_partitions, 2);
2762 
2763  /*
2764  * The number of partitions can change at different levels of
2765  * recursion; but for the purposes of this calculation assume it stays
2766  * constant.
2767  */
2768  depth = ceil(log(nbatches) / log(num_partitions));
2769 
2770  /*
2771  * Estimate number of pages read and written. For each level of
2772  * recursion, a tuple must be written and then later read.
2773  */
2774  pages = relation_byte_size(input_tuples, input_width) / BLCKSZ;
2775  pages_written = pages_read = pages * depth;
2776 
2777  /*
2778  * HashAgg has somewhat worse IO behavior than Sort on typical
2779  * hardware/OS combinations. Account for this with a generic penalty.
2780  */
2781  pages_read *= 2.0;
2782  pages_written *= 2.0;
2783 
2784  startup_cost += pages_written * random_page_cost;
2785  total_cost += pages_written * random_page_cost;
2786  total_cost += pages_read * seq_page_cost;
2787 
2788  /* account for CPU cost of spilling a tuple and reading it back */
2789  spill_cost = depth * input_tuples * 2.0 * cpu_tuple_cost;
2790  startup_cost += spill_cost;
2791  total_cost += spill_cost;
2792  }
2793 
2794  /*
2795  * If there are quals (HAVING quals), account for their cost and
2796  * selectivity.
2797  */
2798  if (quals)
2799  {
2800  QualCost qual_cost;
2801 
2802  cost_qual_eval(&qual_cost, quals, root);
2803  startup_cost += qual_cost.startup;
2804  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2805 
2806  output_tuples = clamp_row_est(output_tuples *
2808  quals,
2809  0,
2810  JOIN_INNER,
2811  NULL));
2812  }
2813 
2814  path->rows = output_tuples;
2815  path->startup_cost = startup_cost;
2816  path->total_cost = total_cost;
2817 }
#define MemSet(start, val, len)
Definition: c.h:1020
size_t Size
Definition: c.h:605
double random_page_cost
Definition: costsize.c:120
double cpu_operator_cost
Definition: costsize.c:123
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:6316
double cpu_tuple_cost
Definition: costsize.c:121
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4619
double seq_page_cost
Definition: costsize.c:119
bool enable_hashagg
Definition: costsize.c:141
Cost disable_cost
Definition: costsize.c:130
Size hash_agg_entry_size(int numTrans, Size tupleWidth, Size transitionSpace)
Definition: nodeAgg.c:1694
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:1798
@ AGG_SORTED
Definition: nodes.h:355
@ AGG_HASHED
Definition: nodes.h:356
@ AGG_MIXED
Definition: nodes.h:357
@ AGG_PLAIN
Definition: nodes.h:354
static int list_length(const List *l)
Definition: pg_list.h:152
QualCost finalCost
Definition: pathnodes.h:61
Size transitionSpace
Definition: pathnodes.h:62
QualCost transCost
Definition: pathnodes.h:60
Cost startup_cost
Definition: pathnodes.h:1661
Cost total_cost
Definition: pathnodes.h:1662
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

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

Referenced by choose_hashed_setop(), create_agg_path(), create_groupingsets_path(), and create_unique_path().

◆ cost_append()

void cost_append ( AppendPath apath)

Definition at line 2210 of file costsize.c.

2211 {
2212  ListCell *l;
2213 
2214  apath->path.startup_cost = 0;
2215  apath->path.total_cost = 0;
2216  apath->path.rows = 0;
2217 
2218  if (apath->subpaths == NIL)
2219  return;
2220 
2221  if (!apath->path.parallel_aware)
2222  {
2223  List *pathkeys = apath->path.pathkeys;
2224 
2225  if (pathkeys == NIL)
2226  {
2227  Path *firstsubpath = (Path *) linitial(apath->subpaths);
2228 
2229  /*
2230  * For an unordered, non-parallel-aware Append we take the startup
2231  * cost as the startup cost of the first subpath.
2232  */
2233  apath->path.startup_cost = firstsubpath->startup_cost;
2234 
2235  /* Compute rows and costs as sums of subplan rows and costs. */
2236  foreach(l, apath->subpaths)
2237  {
2238  Path *subpath = (Path *) lfirst(l);
2239 
2240  apath->path.rows += subpath->rows;
2241  apath->path.total_cost += subpath->total_cost;
2242  }
2243  }
2244  else
2245  {
2246  /*
2247  * For an ordered, non-parallel-aware Append we take the startup
2248  * cost as the sum of the subpath startup costs. This ensures
2249  * that we don't underestimate the startup cost when a query's
2250  * LIMIT is such that several of the children have to be run to
2251  * satisfy it. This might be overkill --- another plausible hack
2252  * would be to take the Append's startup cost as the maximum of
2253  * the child startup costs. But we don't want to risk believing
2254  * that an ORDER BY LIMIT query can be satisfied at small cost
2255  * when the first child has small startup cost but later ones
2256  * don't. (If we had the ability to deal with nonlinear cost
2257  * interpolation for partial retrievals, we would not need to be
2258  * so conservative about this.)
2259  *
2260  * This case is also different from the above in that we have to
2261  * account for possibly injecting sorts into subpaths that aren't
2262  * natively ordered.
2263  */
2264  foreach(l, apath->subpaths)
2265  {
2266  Path *subpath = (Path *) lfirst(l);
2267  Path sort_path; /* dummy for result of cost_sort */
2268 
2269  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
2270  {
2271  /*
2272  * We'll need to insert a Sort node, so include costs for
2273  * that. We can use the parent's LIMIT if any, since we
2274  * certainly won't pull more than that many tuples from
2275  * any child.
2276  */
2277  cost_sort(&sort_path,
2278  NULL, /* doesn't currently need root */
2279  pathkeys,
2280  subpath->total_cost,
2281  subpath->rows,
2282  subpath->pathtarget->width,
2283  0.0,
2284  work_mem,
2285  apath->limit_tuples);
2286  subpath = &sort_path;
2287  }
2288 
2289  apath->path.rows += subpath->rows;
2290  apath->path.startup_cost += subpath->startup_cost;
2291  apath->path.total_cost += subpath->total_cost;
2292  }
2293  }
2294  }
2295  else /* parallel-aware */
2296  {
2297  int i = 0;
2298  double parallel_divisor = get_parallel_divisor(&apath->path);
2299 
2300  /* Parallel-aware Append never produces ordered output. */
2301  Assert(apath->path.pathkeys == NIL);
2302 
2303  /* Calculate startup cost. */
2304  foreach(l, apath->subpaths)
2305  {
2306  Path *subpath = (Path *) lfirst(l);
2307 
2308  /*
2309  * Append will start returning tuples when the child node having
2310  * lowest startup cost is done setting up. We consider only the
2311  * first few subplans that immediately get a worker assigned.
2312  */
2313  if (i == 0)
2314  apath->path.startup_cost = subpath->startup_cost;
2315  else if (i < apath->path.parallel_workers)
2316  apath->path.startup_cost = Min(apath->path.startup_cost,
2317  subpath->startup_cost);
2318 
2319  /*
2320  * Apply parallel divisor to subpaths. Scale the number of rows
2321  * for each partial subpath based on the ratio of the parallel
2322  * divisor originally used for the subpath to the one we adopted.
2323  * Also add the cost of partial paths to the total cost, but
2324  * ignore non-partial paths for now.
2325  */
2326  if (i < apath->first_partial_path)
2327  apath->path.rows += subpath->rows / parallel_divisor;
2328  else
2329  {
2330  double subpath_parallel_divisor;
2331 
2332  subpath_parallel_divisor = get_parallel_divisor(subpath);
2333  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
2334  parallel_divisor);
2335  apath->path.total_cost += subpath->total_cost;
2336  }
2337 
2338  apath->path.rows = clamp_row_est(apath->path.rows);
2339 
2340  i++;
2341  }
2342 
2343  /* Add cost for non-partial subpaths. */
2344  apath->path.total_cost +=
2346  apath->first_partial_path,
2347  apath->path.parallel_workers);
2348  }
2349 
2350  /*
2351  * Although Append does not do any selection or projection, it's not free;
2352  * add a small per-tuple overhead.
2353  */
2354  apath->path.total_cost +=
2356 }
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:109
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:2134
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:2103
int i
Definition: isn.c:73
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:310
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:341
#define lfirst(lc)
Definition: pg_list.h:172
#define linitial(l)
Definition: pg_list.h:178
int first_partial_path
Definition: pathnodes.h:1934
Cardinality limit_tuples
Definition: pathnodes.h:1935
List * subpaths
Definition: pathnodes.h:1932
List * pathkeys
Definition: pathnodes.h:1665
bool parallel_aware
Definition: pathnodes.h:1653

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

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1157 of file costsize.c.

1158 {
1159  Cost totalCost;
1160  Selectivity selec;
1161  ListCell *l;
1162 
1163  /*
1164  * We estimate AND selectivity on the assumption that the inputs are
1165  * independent. This is probably often wrong, but we don't have the info
1166  * to do better.
1167  *
1168  * The runtime cost of the BitmapAnd itself is estimated at 100x
1169  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1170  * definitely too simplistic?
1171  */
1172  totalCost = 0.0;
1173  selec = 1.0;
1174  foreach(l, path->bitmapquals)
1175  {
1176  Path *subpath = (Path *) lfirst(l);
1177  Cost subCost;
1178  Selectivity subselec;
1179 
1180  cost_bitmap_tree_node(subpath, &subCost, &subselec);
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.startup_cost = totalCost;
1191  path->path.total_cost = totalCost;
1192 }
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
Selectivity bitmapselectivity
Definition: pathnodes.h:1798
List * bitmapquals
Definition: pathnodes.h:1797

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

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

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1201 of file costsize.c.

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

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

Referenced by create_bitmap_or_path().

◆ cost_bitmap_tree_node()

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

Definition at line 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 ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define nodeTag(nodeptr)
Definition: nodes.h:133

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

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

◆ cost_ctescan()

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

Definition at line 1677 of file costsize.c.

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

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

◆ cost_functionscan()

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

Definition at line 1510 of file costsize.c.

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

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

Referenced by create_functionscan_path().

◆ cost_gather()

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

Definition at line 436 of file costsize.c.

439 {
440  Cost startup_cost = 0;
441  Cost run_cost = 0;
442 
443  /* Mark the path with the correct row estimate */
444  if (rows)
445  path->path.rows = *rows;
446  else if (param_info)
447  path->path.rows = param_info->ppi_rows;
448  else
449  path->path.rows = rel->rows;
450 
451  startup_cost = path->subpath->startup_cost;
452 
453  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
454 
455  /* Parallel setup and communication cost. */
456  startup_cost += parallel_setup_cost;
457  run_cost += parallel_tuple_cost * path->path.rows;
458 
459  path->path.startup_cost = startup_cost;
460  path->path.total_cost = (startup_cost + run_cost);
461 }
double parallel_setup_cost
Definition: costsize.c:125
double parallel_tuple_cost
Definition: costsize.c:124
Path * subpath
Definition: pathnodes.h:2042

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

Referenced by create_gather_path().

◆ cost_gather_merge()

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

Definition at line 474 of file costsize.c.

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

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

Referenced by create_gather_merge_path().

◆ cost_group()

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

Definition at line 3142 of file costsize.c.

3147 {
3148  double output_tuples;
3149  Cost startup_cost;
3150  Cost total_cost;
3151 
3152  output_tuples = numGroups;
3153  startup_cost = input_startup_cost;
3154  total_cost = input_total_cost;
3155 
3156  /*
3157  * Charge one cpu_operator_cost per comparison per input tuple. We assume
3158  * all columns get compared at most of the tuples.
3159  */
3160  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3161 
3162  /*
3163  * If there are quals (HAVING quals), account for their cost and
3164  * selectivity.
3165  */
3166  if (quals)
3167  {
3168  QualCost qual_cost;
3169 
3170  cost_qual_eval(&qual_cost, quals, root);
3171  startup_cost += qual_cost.startup;
3172  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3173 
3174  output_tuples = clamp_row_est(output_tuples *
3176  quals,
3177  0,
3178  JOIN_INNER,
3179  NULL));
3180  }
3181 
3182  path->rows = output_tuples;
3183  path->startup_cost = startup_cost;
3184  path->total_cost = total_cost;
3185 }

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

Referenced by choose_hashed_setop(), and create_group_path().

◆ cost_incremental_sort()

void cost_incremental_sort ( Path path,
PlannerInfo root,
List pathkeys,
int  presorted_keys,
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 1965 of file costsize.c.

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

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

Referenced by create_incremental_sort_path().

◆ cost_index()

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

Definition at line 549 of file costsize.c.

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

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

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2432 of file costsize.c.

2435 {
2436  Cost startup_cost = input_startup_cost;
2437  Cost run_cost = input_total_cost - input_startup_cost;
2438  double nbytes = relation_byte_size(tuples, width);
2439  long work_mem_bytes = work_mem * 1024L;
2440 
2441  path->rows = tuples;
2442 
2443  /*
2444  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2445  * reflect bookkeeping overhead. (This rate must be more than what
2446  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2447  * if it is exactly the same then there will be a cost tie between
2448  * nestloop with A outer, materialized B inner and nestloop with B outer,
2449  * materialized A inner. The extra cost ensures we'll prefer
2450  * materializing the smaller rel.) Note that this is normally a good deal
2451  * less than cpu_tuple_cost; which is OK because a Material plan node
2452  * doesn't do qual-checking or projection, so it's got less overhead than
2453  * most plan nodes.
2454  */
2455  run_cost += 2 * cpu_operator_cost * tuples;
2456 
2457  /*
2458  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2459  * This cost is assumed to be evenly spread through the plan run phase,
2460  * which isn't exactly accurate but our cost model doesn't allow for
2461  * nonuniform costs within the run phase.
2462  */
2463  if (nbytes > work_mem_bytes)
2464  {
2465  double npages = ceil(nbytes / BLCKSZ);
2466 
2467  run_cost += seq_page_cost * npages;
2468  }
2469 
2470  path->startup_cost = startup_cost;
2471  path->total_cost = startup_cost + run_cost;
2472 }

References cpu_operator_cost, 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_merge_append()

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

Definition at line 2383 of file costsize.c.

2387 {
2388  Cost startup_cost = 0;
2389  Cost run_cost = 0;
2390  Cost comparison_cost;
2391  double N;
2392  double logN;
2393 
2394  /*
2395  * Avoid log(0)...
2396  */
2397  N = (n_streams < 2) ? 2.0 : (double) n_streams;
2398  logN = LOG2(N);
2399 
2400  /* Assumed cost per tuple comparison */
2401  comparison_cost = 2.0 * cpu_operator_cost;
2402 
2403  /* Heap creation cost */
2404  startup_cost += comparison_cost * N * logN;
2405 
2406  /* Per-tuple heap maintenance cost */
2407  run_cost += tuples * comparison_cost * logN;
2408 
2409  /*
2410  * Although MergeAppend does not do any selection or projection, it's not
2411  * free; add a small per-tuple overhead.
2412  */
2413  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
2414 
2415  path->startup_cost = startup_cost + input_startup_cost;
2416  path->total_cost = startup_cost + run_cost + input_total_cost;
2417 }

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

Referenced by create_merge_append_path().

◆ cost_namedtuplestorescan()

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

Definition at line 1718 of file costsize.c.

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

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

Referenced by create_namedtuplestorescan_path().

◆ cost_qual_eval()

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

Definition at line 4619 of file costsize.c.

4620 {
4622  ListCell *l;
4623 
4624  context.root = root;
4625  context.total.startup = 0;
4626  context.total.per_tuple = 0;
4627 
4628  /* We don't charge any cost for the implicit ANDing at top level ... */
4629 
4630  foreach(l, quals)
4631  {
4632  Node *qual = (Node *) lfirst(l);
4633 
4635  }
4636 
4637  *cost = context.total;
4638 }
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4659
tree context
Definition: radixtree.h:1835

References context, cost_qual_eval_walker(), lfirst, and root.

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

void cost_qual_eval_node ( QualCost cost,
Node qual,
PlannerInfo root 
)

◆ cost_recursive_union()

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

Definition at line 1792 of file costsize.c.

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

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

Referenced by create_recursiveunion_path().

◆ cost_resultscan()

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

Definition at line 1755 of file costsize.c.

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

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

Referenced by create_resultscan_path().

◆ cost_samplescan()

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

Definition at line 361 of file costsize.c.

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

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

Referenced by create_samplescan_path().

◆ cost_seqscan()

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

Definition at line 284 of file costsize.c.

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

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

Referenced by create_seqscan_path().

◆ cost_sort()

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

Definition at line 2103 of file costsize.c.

2108 {
2109  Cost startup_cost;
2110  Cost run_cost;
2111 
2112  cost_tuplesort(&startup_cost, &run_cost,
2113  tuples, width,
2114  comparison_cost, sort_mem,
2115  limit_tuples);
2116 
2117  if (!enable_sort)
2118  startup_cost += disable_cost;
2119 
2120  startup_cost += input_cost;
2121 
2122  path->rows = tuples;
2123  path->startup_cost = startup_cost;
2124  path->total_cost = startup_cost + run_cost;
2125 }
bool enable_sort
Definition: costsize.c:139

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

Referenced by adjust_foreign_grouping_path_cost(), choose_hashed_setop(), cost_append(), create_groupingsets_path(), create_merge_append_path(), create_sort_path(), create_unique_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 4414 of file costsize.c.

4415 {
4416  QualCost sp_cost;
4417 
4418  /* Figure any cost for evaluating the testexpr */
4419  cost_qual_eval(&sp_cost,
4420  make_ands_implicit((Expr *) subplan->testexpr),
4421  root);
4422 
4423  if (subplan->useHashTable)
4424  {
4425  /*
4426  * If we are using a hash table for the subquery outputs, then the
4427  * cost of evaluating the query is a one-time cost. We charge one
4428  * cpu_operator_cost per tuple for the work of loading the hashtable,
4429  * too.
4430  */
4431  sp_cost.startup += plan->total_cost +
4432  cpu_operator_cost * plan->plan_rows;
4433 
4434  /*
4435  * The per-tuple costs include the cost of evaluating the lefthand
4436  * expressions, plus the cost of probing the hashtable. We already
4437  * accounted for the lefthand expressions as part of the testexpr, and
4438  * will also have counted one cpu_operator_cost for each comparison
4439  * operator. That is probably too low for the probing cost, but it's
4440  * hard to make a better estimate, so live with it for now.
4441  */
4442  }
4443  else
4444  {
4445  /*
4446  * Otherwise we will be rescanning the subplan output on each
4447  * evaluation. We need to estimate how much of the output we will
4448  * actually need to scan. NOTE: this logic should agree with the
4449  * tuple_fraction estimates used by make_subplan() in
4450  * plan/subselect.c.
4451  */
4452  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4453 
4454  if (subplan->subLinkType == EXISTS_SUBLINK)
4455  {
4456  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4457  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4458  }
4459  else if (subplan->subLinkType == ALL_SUBLINK ||
4460  subplan->subLinkType == ANY_SUBLINK)
4461  {
4462  /* assume we need 50% of the tuples */
4463  sp_cost.per_tuple += 0.50 * plan_run_cost;
4464  /* also charge a cpu_operator_cost per row examined */
4465  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4466  }
4467  else
4468  {
4469  /* assume we need all tuples */
4470  sp_cost.per_tuple += plan_run_cost;
4471  }
4472 
4473  /*
4474  * Also account for subplan's startup cost. If the subplan is
4475  * uncorrelated or undirect correlated, AND its topmost node is one
4476  * that materializes its output, assume that we'll only need to pay
4477  * its startup cost once; otherwise assume we pay the startup cost
4478  * every time.
4479  */
4480  if (subplan->parParam == NIL &&
4482  sp_cost.startup += plan->startup_cost;
4483  else
4484  sp_cost.per_tuple += plan->startup_cost;
4485  }
4486 
4487  subplan->startup_cost = sp_cost.startup;
4488  subplan->per_call_cost = sp_cost.per_tuple;
4489 }
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:635
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:737
#define plan(x)
Definition: pg_regress.c:162
@ ANY_SUBLINK
Definition: primnodes.h:999
@ ALL_SUBLINK
Definition: primnodes.h:998
@ EXISTS_SUBLINK
Definition: primnodes.h:997
bool useHashTable
Definition: primnodes.h:1079
Node * testexpr
Definition: primnodes.h:1067
List * parParam
Definition: primnodes.h:1090
Cost startup_cost
Definition: primnodes.h:1093
Cost per_call_cost
Definition: primnodes.h:1094
SubLinkType subLinkType
Definition: primnodes.h:1065

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

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

◆ cost_subqueryscan()

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

Definition at line 1430 of file costsize.c.

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

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

Referenced by create_subqueryscan_path().

◆ cost_tablefuncscan()

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

Definition at line 1571 of file costsize.c.

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

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

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

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

Definition at line 1339 of file costsize.c.

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

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

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1249 of file costsize.c.

1251 {
1252  Cost startup_cost = 0;
1253  Cost run_cost = 0;
1254  QualCost qpqual_cost;
1255  Cost cpu_per_tuple;
1256  QualCost tid_qual_cost;
1257  double ntuples;
1258  ListCell *l;
1259  double spc_random_page_cost;
1260 
1261  /* Should only be applied to base relations */
1262  Assert(baserel->relid > 0);
1263  Assert(baserel->rtekind == RTE_RELATION);
1264 
1265  /* Mark the path with the correct row estimate */
1266  if (param_info)
1267  path->rows = param_info->ppi_rows;
1268  else
1269  path->rows = baserel->rows;
1270 
1271  /* Count how many tuples we expect to retrieve */
1272  ntuples = 0;
1273  foreach(l, tidquals)
1274  {
1275  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
1276  Expr *qual = rinfo->clause;
1277 
1278  if (IsA(qual, ScalarArrayOpExpr))
1279  {
1280  /* Each element of the array yields 1 tuple */
1281  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) qual;
1282  Node *arraynode = (Node *) lsecond(saop->args);
1283 
1284  ntuples += estimate_array_length(root, arraynode);
1285  }
1286  else if (IsA(qual, CurrentOfExpr))
1287  {
1288  /* CURRENT OF yields 1 tuple */
1289  ntuples++;
1290  }
1291  else
1292  {
1293  /* It's just CTID = something, count 1 tuple */
1294  ntuples++;
1295  }
1296  }
1297 
1298  /*
1299  * The TID qual expressions will be computed once, any other baserestrict
1300  * quals once per retrieved tuple.
1301  */
1302  cost_qual_eval(&tid_qual_cost, tidquals, root);
1303 
1304  /* fetch estimated page cost for tablespace containing table */
1306  &spc_random_page_cost,
1307  NULL);
1308 
1309  /* disk costs --- assume each tuple on a different page */
1310  run_cost += spc_random_page_cost * ntuples;
1311 
1312  /* Add scanning CPU costs */
1313  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1314 
1315  /* XXX currently we assume TID quals are a subset of qpquals */
1316  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1317  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1318  tid_qual_cost.per_tuple;
1319  run_cost += cpu_per_tuple * ntuples;
1320 
1321  /* tlist eval costs are paid per output row, not per tuple scanned */
1322  startup_cost += path->pathtarget->cost.startup;
1323  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1324 
1325  path->startup_cost = startup_cost;
1326  path->total_cost = startup_cost + run_cost;
1327 }
#define lsecond(l)
Definition: pg_list.h:183
double estimate_array_length(PlannerInfo *root, Node *arrayexpr)
Definition: selfuncs.c:2136
Expr * clause
Definition: pathnodes.h:2564

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

Referenced by create_tidscan_path().

◆ cost_valuesscan()

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

Definition at line 1627 of file costsize.c.

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

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

Referenced by create_valuesscan_path().

◆ cost_windowagg()

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

Definition at line 3047 of file costsize.c.

3051 {
3052  Cost startup_cost;
3053  Cost total_cost;
3054  double startup_tuples;
3055  int numPartCols;
3056  int numOrderCols;
3057  ListCell *lc;
3058 
3059  numPartCols = list_length(winclause->partitionClause);
3060  numOrderCols = list_length(winclause->orderClause);
3061 
3062  startup_cost = input_startup_cost;
3063  total_cost = input_total_cost;
3064 
3065  /*
3066  * Window functions are assumed to cost their stated execution cost, plus
3067  * the cost of evaluating their input expressions, per tuple. Since they
3068  * may in fact evaluate their inputs at multiple rows during each cycle,
3069  * this could be a drastic underestimate; but without a way to know how
3070  * many rows the window function will fetch, it's hard to do better. In
3071  * any case, it's a good estimate for all the built-in window functions,
3072  * so we'll just do this for now.
3073  */
3074  foreach(lc, windowFuncs)
3075  {
3076  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
3077  Cost wfunccost;
3078  QualCost argcosts;
3079 
3080  argcosts.startup = argcosts.per_tuple = 0;
3081  add_function_cost(root, wfunc->winfnoid, (Node *) wfunc,
3082  &argcosts);
3083  startup_cost += argcosts.startup;
3084  wfunccost = argcosts.per_tuple;
3085 
3086  /* also add the input expressions' cost to per-input-row costs */
3087  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
3088  startup_cost += argcosts.startup;
3089  wfunccost += argcosts.per_tuple;
3090 
3091  /*
3092  * Add the filter's cost to per-input-row costs. XXX We should reduce
3093  * input expression costs according to filter selectivity.
3094  */
3095  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
3096  startup_cost += argcosts.startup;
3097  wfunccost += argcosts.per_tuple;
3098 
3099  total_cost += wfunccost * input_tuples;
3100  }
3101 
3102  /*
3103  * We also charge cpu_operator_cost per grouping column per tuple for
3104  * grouping comparisons, plus cpu_tuple_cost per tuple for general
3105  * overhead.
3106  *
3107  * XXX this neglects costs of spooling the data to disk when it overflows
3108  * work_mem. Sooner or later that should get accounted for.
3109  */
3110  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
3111  total_cost += cpu_tuple_cost * input_tuples;
3112 
3113  path->rows = input_tuples;
3114  path->startup_cost = startup_cost;
3115  path->total_cost = total_cost;
3116 
3117  /*
3118  * Also, take into account how many tuples we need to read from the
3119  * subnode in order to produce the first tuple from the WindowAgg. To do
3120  * this we proportion the run cost (total cost not including startup cost)
3121  * over the estimated startup tuples. We already included the startup
3122  * cost of the subnode, so we only need to do this when the estimated
3123  * startup tuples is above 1.0.
3124  */
3125  startup_tuples = get_windowclause_startup_tuples(root, winclause,
3126  input_tuples);
3127 
3128  if (startup_tuples > 1.0)
3129  path->startup_cost += (total_cost - startup_cost) / input_tuples *
3130  (startup_tuples - 1.0);
3131 }
static double get_windowclause_startup_tuples(PlannerInfo *root, WindowClause *wc, double input_tuples)
Definition: costsize.c:2833
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2077
List * partitionClause
Definition: parsenodes.h:1546
List * orderClause
Definition: parsenodes.h:1548
List * args
Definition: primnodes.h:575
Expr * aggfilter
Definition: primnodes.h:577
Oid winfnoid
Definition: primnodes.h:567

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

Referenced by create_windowagg_path().

◆ final_cost_hashjoin()

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

Definition at line 4160 of file costsize.c.

4163 {
4164  Path *outer_path = path->jpath.outerjoinpath;
4165  Path *inner_path = path->jpath.innerjoinpath;
4166  double outer_path_rows = outer_path->rows;
4167  double inner_path_rows = inner_path->rows;
4168  double inner_path_rows_total = workspace->inner_rows_total;
4169  List *hashclauses = path->path_hashclauses;
4170  Cost startup_cost = workspace->startup_cost;
4171  Cost run_cost = workspace->run_cost;
4172  int numbuckets = workspace->numbuckets;
4173  int numbatches = workspace->numbatches;
4174  Cost cpu_per_tuple;
4175  QualCost hash_qual_cost;
4176  QualCost qp_qual_cost;
4177  double hashjointuples;
4178  double virtualbuckets;
4179  Selectivity innerbucketsize;
4180  Selectivity innermcvfreq;
4181  ListCell *hcl;
4182 
4183  /* Mark the path with the correct row estimate */
4184  if (path->jpath.path.param_info)
4185  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4186  else
4187  path->jpath.path.rows = path->jpath.path.parent->rows;
4188 
4189  /* For partial paths, scale row estimate. */
4190  if (path->jpath.path.parallel_workers > 0)
4191  {
4192  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4193 
4194  path->jpath.path.rows =
4195  clamp_row_est(path->jpath.path.rows / parallel_divisor);
4196  }
4197 
4198  /*
4199  * We could include disable_cost in the preliminary estimate, but that
4200  * would amount to optimizing for the case where the join method is
4201  * disabled, which doesn't seem like the way to bet.
4202  */
4203  if (!enable_hashjoin)
4204  startup_cost += disable_cost;
4205 
4206  /* mark the path with estimated # of batches */
4207  path->num_batches = numbatches;
4208 
4209  /* store the total number of tuples (sum of partial row estimates) */
4210  path->inner_rows_total = inner_path_rows_total;
4211 
4212  /* and compute the number of "virtual" buckets in the whole join */
4213  virtualbuckets = (double) numbuckets * (double) numbatches;
4214 
4215  /*
4216  * Determine bucketsize fraction and MCV frequency for the inner relation.
4217  * We use the smallest bucketsize or MCV frequency estimated for any
4218  * individual hashclause; this is undoubtedly conservative.
4219  *
4220  * BUT: if inner relation has been unique-ified, we can assume it's good
4221  * for hashing. This is important both because it's the right answer, and
4222  * because we avoid contaminating the cache with a value that's wrong for
4223  * non-unique-ified paths.
4224  */
4225  if (IsA(inner_path, UniquePath))
4226  {
4227  innerbucketsize = 1.0 / virtualbuckets;
4228  innermcvfreq = 0.0;
4229  }
4230  else
4231  {
4232  innerbucketsize = 1.0;
4233  innermcvfreq = 1.0;
4234  foreach(hcl, hashclauses)
4235  {
4236  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
4237  Selectivity thisbucketsize;
4238  Selectivity thismcvfreq;
4239 
4240  /*
4241  * First we have to figure out which side of the hashjoin clause
4242  * is the inner side.
4243  *
4244  * Since we tend to visit the same clauses over and over when
4245  * planning a large query, we cache the bucket stats estimates in
4246  * the RestrictInfo node to avoid repeated lookups of statistics.
4247  */
4248  if (bms_is_subset(restrictinfo->right_relids,
4249  inner_path->parent->relids))
4250  {
4251  /* righthand side is inner */
4252  thisbucketsize = restrictinfo->right_bucketsize;
4253  if (thisbucketsize < 0)
4254  {
4255  /* not cached yet */
4257  get_rightop(restrictinfo->clause),
4258  virtualbuckets,
4259  &restrictinfo->right_mcvfreq,
4260  &restrictinfo->right_bucketsize);
4261  thisbucketsize = restrictinfo->right_bucketsize;
4262  }
4263  thismcvfreq = restrictinfo->right_mcvfreq;
4264  }
4265  else
4266  {
4267  Assert(bms_is_subset(restrictinfo->left_relids,
4268  inner_path->parent->relids));
4269  /* lefthand side is inner */
4270  thisbucketsize = restrictinfo->left_bucketsize;
4271  if (thisbucketsize < 0)
4272  {
4273  /* not cached yet */
4275  get_leftop(restrictinfo->clause),
4276  virtualbuckets,
4277  &restrictinfo->left_mcvfreq,
4278  &restrictinfo->left_bucketsize);
4279  thisbucketsize = restrictinfo->left_bucketsize;
4280  }
4281  thismcvfreq = restrictinfo->left_mcvfreq;
4282  }
4283 
4284  if (innerbucketsize > thisbucketsize)
4285  innerbucketsize = thisbucketsize;
4286  if (innermcvfreq > thismcvfreq)
4287  innermcvfreq = thismcvfreq;
4288  }
4289  }
4290 
4291  /*
4292  * If the bucket holding the inner MCV would exceed hash_mem, we don't
4293  * want to hash unless there is really no other alternative, so apply
4294  * disable_cost. (The executor normally copes with excessive memory usage
4295  * by splitting batches, but obviously it cannot separate equal values
4296  * that way, so it will be unable to drive the batch size below hash_mem
4297  * when this is true.)
4298  */
4299  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
4300  inner_path->pathtarget->width) > get_hash_memory_limit())
4301  startup_cost += disable_cost;
4302 
4303  /*
4304  * Compute cost of the hashquals and qpquals (other restriction clauses)
4305  * separately.
4306  */
4307  cost_qual_eval(&hash_qual_cost, hashclauses, root);
4308  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
4309  qp_qual_cost.startup -= hash_qual_cost.startup;
4310  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4311 
4312  /* CPU costs */
4313 
4314  if (path->jpath.jointype == JOIN_SEMI ||
4315  path->jpath.jointype == JOIN_ANTI ||
4316  extra->inner_unique)
4317  {
4318  double outer_matched_rows;
4319  Selectivity inner_scan_frac;
4320 
4321  /*
4322  * With a SEMI or ANTI join, or if the innerrel is known unique, the
4323  * executor will stop after the first match.
4324  *
4325  * For an outer-rel row that has at least one match, we can expect the
4326  * bucket scan to stop after a fraction 1/(match_count+1) of the
4327  * bucket's rows, if the matches are evenly distributed. Since they
4328  * probably aren't quite evenly distributed, we apply a fuzz factor of
4329  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4330  * to clamp inner_scan_frac to at most 1.0; but since match_count is
4331  * at least 1, no such clamp is needed now.)
4332  */
4333  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
4334  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4335 
4336  startup_cost += hash_qual_cost.startup;
4337  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4338  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
4339 
4340  /*
4341  * For unmatched outer-rel rows, the picture is quite a lot different.
4342  * In the first place, there is no reason to assume that these rows
4343  * preferentially hit heavily-populated buckets; instead assume they
4344  * are uncorrelated with the inner distribution and so they see an
4345  * average bucket size of inner_path_rows / virtualbuckets. In the
4346  * second place, it seems likely that they will have few if any exact
4347  * hash-code matches and so very few of the tuples in the bucket will
4348  * actually require eval of the hash quals. We don't have any good
4349  * way to estimate how many will, but for the moment assume that the
4350  * effective cost per bucket entry is one-tenth what it is for
4351  * matchable tuples.
4352  */
4353  run_cost += hash_qual_cost.per_tuple *
4354  (outer_path_rows - outer_matched_rows) *
4355  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
4356 
4357  /* Get # of tuples that will pass the basic join */
4358  if (path->jpath.jointype == JOIN_ANTI)
4359  hashjointuples = outer_path_rows - outer_matched_rows;
4360  else
4361  hashjointuples = outer_matched_rows;
4362  }
4363  else
4364  {
4365  /*
4366  * The number of tuple comparisons needed is the number of outer
4367  * tuples times the typical number of tuples in a hash bucket, which
4368  * is the inner relation size times its bucketsize fraction. At each
4369  * one, we need to evaluate the hashjoin quals. But actually,
4370  * charging the full qual eval cost at each tuple is pessimistic,
4371  * since we don't evaluate the quals unless the hash values match
4372  * exactly. For lack of a better idea, halve the cost estimate to
4373  * allow for that.
4374  */
4375  startup_cost += hash_qual_cost.startup;
4376  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4377  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
4378 
4379  /*
4380  * Get approx # tuples passing the hashquals. We use
4381  * approx_tuple_count here because we need an estimate done with
4382  * JOIN_INNER semantics.
4383  */
4384  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4385  }
4386 
4387  /*
4388  * For each tuple that gets through the hashjoin proper, we charge
4389  * cpu_tuple_cost plus the cost of evaluating additional restriction
4390  * clauses that are to be applied at the join. (This is pessimistic since
4391  * not all of the quals may get evaluated at each tuple.)
4392  */
4393  startup_cost += qp_qual_cost.startup;
4394  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
4395  run_cost += cpu_per_tuple * hashjointuples;
4396 
4397  /* tlist eval costs are paid per output row, not per tuple scanned */
4398  startup_cost += path->jpath.path.pathtarget->cost.startup;
4399  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4400 
4401  path->jpath.path.startup_cost = startup_cost;
4402  path->jpath.path.total_cost = startup_cost + run_cost;
4403 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
bool enable_hashjoin
Definition: costsize.c:146
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:5168
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:93
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:81
size_t get_hash_memory_limit(void)
Definition: nodeHash.c:3595
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3798
List * path_hashclauses
Definition: pathnodes.h:2152
Cardinality inner_rows_total
Definition: pathnodes.h:2154
int num_batches
Definition: pathnodes.h:2153
JoinPath jpath
Definition: pathnodes.h:2151
Cardinality inner_rows_total
Definition: pathnodes.h:3355
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:3234
Path * outerjoinpath
Definition: pathnodes.h:2074
Path * innerjoinpath
Definition: pathnodes.h:2075
JoinType jointype
Definition: pathnodes.h:2069
List * joinrestrictinfo
Definition: pathnodes.h:2077

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

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3724 of file costsize.c.

3727 {
3728  Path *outer_path = path->jpath.outerjoinpath;
3729  Path *inner_path = path->jpath.innerjoinpath;
3730  double inner_path_rows = inner_path->rows;
3731  List *mergeclauses = path->path_mergeclauses;
3732  List *innersortkeys = path->innersortkeys;
3733  Cost startup_cost = workspace->startup_cost;
3734  Cost run_cost = workspace->run_cost;
3735  Cost inner_run_cost = workspace->inner_run_cost;
3736  double outer_rows = workspace->outer_rows;
3737  double inner_rows = workspace->inner_rows;
3738  double outer_skip_rows = workspace->outer_skip_rows;
3739  double inner_skip_rows = workspace->inner_skip_rows;
3740  Cost cpu_per_tuple,
3741  bare_inner_cost,
3742  mat_inner_cost;
3743  QualCost merge_qual_cost;
3744  QualCost qp_qual_cost;
3745  double mergejointuples,
3746  rescannedtuples;
3747  double rescanratio;
3748 
3749  /* Protect some assumptions below that rowcounts aren't zero */
3750  if (inner_path_rows <= 0)
3751  inner_path_rows = 1;
3752 
3753  /* Mark the path with the correct row estimate */
3754  if (path->jpath.path.param_info)
3755  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3756  else
3757  path->jpath.path.rows = path->jpath.path.parent->rows;
3758 
3759  /* For partial paths, scale row estimate. */
3760  if (path->jpath.path.parallel_workers > 0)
3761  {
3762  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3763 
3764  path->jpath.path.rows =
3765  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3766  }
3767 
3768  /*
3769  * We could include disable_cost in the preliminary estimate, but that
3770  * would amount to optimizing for the case where the join method is
3771  * disabled, which doesn't seem like the way to bet.
3772  */
3773  if (!enable_mergejoin)
3774  startup_cost += disable_cost;
3775 
3776  /*
3777  * Compute cost of the mergequals and qpquals (other restriction clauses)
3778  * separately.
3779  */
3780  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
3781  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3782  qp_qual_cost.startup -= merge_qual_cost.startup;
3783  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
3784 
3785  /*
3786  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3787  * executor will stop scanning for matches after the first match. When
3788  * all the joinclauses are merge clauses, this means we don't ever need to
3789  * back up the merge, and so we can skip mark/restore overhead.
3790  */
3791  if ((path->jpath.jointype == JOIN_SEMI ||
3792  path->jpath.jointype == JOIN_ANTI ||
3793  extra->inner_unique) &&
3796  path->skip_mark_restore = true;
3797  else
3798  path->skip_mark_restore = false;
3799 
3800  /*
3801  * Get approx # tuples passing the mergequals. We use approx_tuple_count
3802  * here because we need an estimate done with JOIN_INNER semantics.
3803  */
3804  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
3805 
3806  /*
3807  * When there are equal merge keys in the outer relation, the mergejoin
3808  * must rescan any matching tuples in the inner relation. This means
3809  * re-fetching inner tuples; we have to estimate how often that happens.
3810  *
3811  * For regular inner and outer joins, the number of re-fetches can be
3812  * estimated approximately as size of merge join output minus size of
3813  * inner relation. Assume that the distinct key values are 1, 2, ..., and
3814  * denote the number of values of each key in the outer relation as m1,
3815  * m2, ...; in the inner relation, n1, n2, ... Then we have
3816  *
3817  * size of join = m1 * n1 + m2 * n2 + ...
3818  *
3819  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
3820  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
3821  * relation
3822  *
3823  * This equation works correctly for outer tuples having no inner match
3824  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
3825  * are effectively subtracting those from the number of rescanned tuples,
3826  * when we should not. Can we do better without expensive selectivity
3827  * computations?
3828  *
3829  * The whole issue is moot if we are working from a unique-ified outer
3830  * input, or if we know we don't need to mark/restore at all.
3831  */
3832  if (IsA(outer_path, UniquePath) || path->skip_mark_restore)
3833  rescannedtuples = 0;
3834  else
3835  {
3836  rescannedtuples = mergejointuples - inner_path_rows;
3837  /* Must clamp because of possible underestimate */
3838  if (rescannedtuples < 0)
3839  rescannedtuples = 0;
3840  }
3841 
3842  /*
3843  * We'll inflate various costs this much to account for rescanning. Note
3844  * that this is to be multiplied by something involving inner_rows, or
3845  * another number related to the portion of the inner rel we'll scan.
3846  */
3847  rescanratio = 1.0 + (rescannedtuples / inner_rows);
3848 
3849  /*
3850  * Decide whether we want to materialize the inner input to shield it from
3851  * mark/restore and performing re-fetches. Our cost model for regular
3852  * re-fetches is that a re-fetch costs the same as an original fetch,
3853  * which is probably an overestimate; but on the other hand we ignore the
3854  * bookkeeping costs of mark/restore. Not clear if it's worth developing
3855  * a more refined model. So we just need to inflate the inner run cost by
3856  * rescanratio.
3857  */
3858  bare_inner_cost = inner_run_cost * rescanratio;
3859 
3860  /*
3861  * When we interpose a Material node the re-fetch cost is assumed to be
3862  * just cpu_operator_cost per tuple, independently of the underlying
3863  * plan's cost; and we charge an extra cpu_operator_cost per original
3864  * fetch as well. Note that we're assuming the materialize node will
3865  * never spill to disk, since it only has to remember tuples back to the
3866  * last mark. (If there are a huge number of duplicates, our other cost
3867  * factors will make the path so expensive that it probably won't get
3868  * chosen anyway.) So we don't use cost_rescan here.
3869  *
3870  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
3871  * of the generated Material node.
3872  */
3873  mat_inner_cost = inner_run_cost +
3874  cpu_operator_cost * inner_rows * rescanratio;
3875 
3876  /*
3877  * If we don't need mark/restore at all, we don't need materialization.
3878  */
3879  if (path->skip_mark_restore)
3880  path->materialize_inner = false;
3881 
3882  /*
3883  * Prefer materializing if it looks cheaper, unless the user has asked to
3884  * suppress materialization.
3885  */
3886  else if (enable_material && mat_inner_cost < bare_inner_cost)
3887  path->materialize_inner = true;
3888 
3889  /*
3890  * Even if materializing doesn't look cheaper, we *must* do it if the
3891  * inner path is to be used directly (without sorting) and it doesn't
3892  * support mark/restore.
3893  *
3894  * Since the inner side must be ordered, and only Sorts and IndexScans can
3895  * create order to begin with, and they both support mark/restore, you
3896  * might think there's no problem --- but you'd be wrong. Nestloop and
3897  * merge joins can *preserve* the order of their inputs, so they can be
3898  * selected as the input of a mergejoin, and they don't support
3899  * mark/restore at present.
3900  *
3901  * We don't test the value of enable_material here, because
3902  * materialization is required for correctness in this case, and turning
3903  * it off does not entitle us to deliver an invalid plan.
3904  */
3905  else if (innersortkeys == NIL &&
3906  !ExecSupportsMarkRestore(inner_path))
3907  path->materialize_inner = true;
3908 
3909  /*
3910  * Also, force materializing if the inner path is to be sorted and the
3911  * sort is expected to spill to disk. This is because the final merge
3912  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3913  * We don't try to adjust the cost estimates for this consideration,
3914  * though.
3915  *
3916  * Since materialization is a performance optimization in this case,
3917  * rather than necessary for correctness, we skip it if enable_material is
3918  * off.
3919  */
3920  else if (enable_material && innersortkeys != NIL &&
3921  relation_byte_size(inner_path_rows,
3922  inner_path->pathtarget->width) >
3923  (work_mem * 1024L))
3924  path->materialize_inner = true;
3925  else
3926  path->materialize_inner = false;
3927 
3928  /* Charge the right incremental cost for the chosen case */
3929  if (path->materialize_inner)
3930  run_cost += mat_inner_cost;
3931  else
3932  run_cost += bare_inner_cost;
3933 
3934  /* CPU costs */
3935 
3936  /*
3937  * The number of tuple comparisons needed is approximately number of outer
3938  * rows plus number of inner rows plus number of rescanned tuples (can we
3939  * refine this?). At each one, we need to evaluate the mergejoin quals.
3940  */
3941  startup_cost += merge_qual_cost.startup;
3942  startup_cost += merge_qual_cost.per_tuple *
3943  (outer_skip_rows + inner_skip_rows * rescanratio);
3944  run_cost += merge_qual_cost.per_tuple *
3945  ((outer_rows - outer_skip_rows) +
3946  (inner_rows - inner_skip_rows) * rescanratio);
3947 
3948  /*
3949  * For each tuple that gets through the mergejoin proper, we charge
3950  * cpu_tuple_cost plus the cost of evaluating additional restriction
3951  * clauses that are to be applied at the join. (This is pessimistic since
3952  * not all of the quals may get evaluated at each tuple.)
3953  *
3954  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3955  * evaluations here, but it's probably not worth the trouble.
3956  */
3957  startup_cost += qp_qual_cost.startup;
3958  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3959  run_cost += cpu_per_tuple * mergejointuples;
3960 
3961  /* tlist eval costs are paid per output row, not per tuple scanned */
3962  startup_cost += path->jpath.path.pathtarget->cost.startup;
3963  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3964 
3965  path->jpath.path.startup_cost = startup_cost;
3966  path->jpath.path.total_cost = startup_cost + run_cost;
3967 }
bool enable_material
Definition: costsize.c:143
bool enable_mergejoin
Definition: costsize.c:145
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:417
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
Cardinality inner_rows
Definition: pathnodes.h:3348
Cardinality outer_rows
Definition: pathnodes.h:3347
Cardinality inner_skip_rows
Definition: pathnodes.h:3350
Cardinality outer_skip_rows
Definition: pathnodes.h:3349
bool skip_mark_restore
Definition: pathnodes.h:2136
List * innersortkeys
Definition: pathnodes.h:2135
JoinPath jpath
Definition: pathnodes.h:2132
bool materialize_inner
Definition: pathnodes.h:2137
List * path_mergeclauses
Definition: pathnodes.h:2133

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

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3287 of file costsize.c.

3290 {
3291  Path *outer_path = path->jpath.outerjoinpath;
3292  Path *inner_path = path->jpath.innerjoinpath;
3293  double outer_path_rows = outer_path->rows;
3294  double inner_path_rows = inner_path->rows;
3295  Cost startup_cost = workspace->startup_cost;
3296  Cost run_cost = workspace->run_cost;
3297  Cost cpu_per_tuple;
3298  QualCost restrict_qual_cost;
3299  double ntuples;
3300 
3301  /* Protect some assumptions below that rowcounts aren't zero */
3302  if (outer_path_rows <= 0)
3303  outer_path_rows = 1;
3304  if (inner_path_rows <= 0)
3305  inner_path_rows = 1;
3306  /* Mark the path with the correct row estimate */
3307  if (path->jpath.path.param_info)
3308  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3309  else
3310  path->jpath.path.rows = path->jpath.path.parent->rows;
3311 
3312  /* For partial paths, scale row estimate. */
3313  if (path->jpath.path.parallel_workers > 0)
3314  {
3315  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3316 
3317  path->jpath.path.rows =
3318  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3319  }
3320 
3321  /*
3322  * We could include disable_cost in the preliminary estimate, but that
3323  * would amount to optimizing for the case where the join method is
3324  * disabled, which doesn't seem like the way to bet.
3325  */
3326  if (!enable_nestloop)
3327  startup_cost += disable_cost;
3328 
3329  /* cost of inner-relation source data (we already dealt with outer rel) */
3330 
3331  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI ||
3332  extra->inner_unique)
3333  {
3334  /*
3335  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3336  * executor will stop after the first match.
3337  */
3338  Cost inner_run_cost = workspace->inner_run_cost;
3339  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
3340  double outer_matched_rows;
3341  double outer_unmatched_rows;
3342  Selectivity inner_scan_frac;
3343 
3344  /*
3345  * For an outer-rel row that has at least one match, we can expect the
3346  * inner scan to stop after a fraction 1/(match_count+1) of the inner
3347  * rows, if the matches are evenly distributed. Since they probably
3348  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
3349  * that fraction. (If we used a larger fuzz factor, we'd have to
3350  * clamp inner_scan_frac to at most 1.0; but since match_count is at
3351  * least 1, no such clamp is needed now.)
3352  */
3353  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3354  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
3355  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3356 
3357  /*
3358  * Compute number of tuples processed (not number emitted!). First,
3359  * account for successfully-matched outer rows.
3360  */
3361  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
3362 
3363  /*
3364  * Now we need to estimate the actual costs of scanning the inner
3365  * relation, which may be quite a bit less than N times inner_run_cost
3366  * due to early scan stops. We consider two cases. If the inner path
3367  * is an indexscan using all the joinquals as indexquals, then an
3368  * unmatched outer row results in an indexscan returning no rows,
3369  * which is probably quite cheap. Otherwise, the executor will have
3370  * to scan the whole inner rel for an unmatched row; not so cheap.
3371  */
3372  if (has_indexed_join_quals(path))
3373  {
3374  /*
3375  * Successfully-matched outer rows will only require scanning
3376  * inner_scan_frac of the inner relation. In this case, we don't
3377  * need to charge the full inner_run_cost even when that's more
3378  * than inner_rescan_run_cost, because we can assume that none of
3379  * the inner scans ever scan the whole inner relation. So it's
3380  * okay to assume that all the inner scan executions can be
3381  * fractions of the full cost, even if materialization is reducing
3382  * the rescan cost. At this writing, it's impossible to get here
3383  * for a materialized inner scan, so inner_run_cost and
3384  * inner_rescan_run_cost will be the same anyway; but just in
3385  * case, use inner_run_cost for the first matched tuple and
3386  * inner_rescan_run_cost for additional ones.
3387  */
3388  run_cost += inner_run_cost * inner_scan_frac;
3389  if (outer_matched_rows > 1)
3390  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
3391 
3392  /*
3393  * Add the cost of inner-scan executions for unmatched outer rows.
3394  * We estimate this as the same cost as returning the first tuple
3395  * of a nonempty scan. We consider that these are all rescans,
3396  * since we used inner_run_cost once already.
3397  */
3398  run_cost += outer_unmatched_rows *
3399  inner_rescan_run_cost / inner_path_rows;
3400 
3401  /*
3402  * We won't be evaluating any quals at all for unmatched rows, so
3403  * don't add them to ntuples.
3404  */
3405  }
3406  else
3407  {
3408  /*
3409  * Here, a complicating factor is that rescans may be cheaper than
3410  * first scans. If we never scan all the way to the end of the
3411  * inner rel, it might be (depending on the plan type) that we'd
3412  * never pay the whole inner first-scan run cost. However it is
3413  * difficult to estimate whether that will happen (and it could
3414  * not happen if there are any unmatched outer rows!), so be
3415  * conservative and always charge the whole first-scan cost once.
3416  * We consider this charge to correspond to the first unmatched
3417  * outer row, unless there isn't one in our estimate, in which
3418  * case blame it on the first matched row.
3419  */
3420 
3421  /* First, count all unmatched join tuples as being processed */
3422  ntuples += outer_unmatched_rows * inner_path_rows;
3423 
3424  /* Now add the forced full scan, and decrement appropriate count */
3425  run_cost += inner_run_cost;
3426  if (outer_unmatched_rows >= 1)
3427  outer_unmatched_rows -= 1;
3428  else
3429  outer_matched_rows -= 1;
3430 
3431  /* Add inner run cost for additional outer tuples having matches */
3432  if (outer_matched_rows > 0)
3433  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
3434 
3435  /* Add inner run cost for additional unmatched outer tuples */
3436  if (outer_unmatched_rows > 0)
3437  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
3438  }
3439  }
3440  else
3441  {
3442  /* Normal-case source costs were included in preliminary estimate */
3443 
3444  /* Compute number of tuples processed (not number emitted!) */
3445  ntuples = outer_path_rows * inner_path_rows;
3446  }
3447 
3448  /* CPU costs */
3449  cost_qual_eval(&restrict_qual_cost, path->jpath.joinrestrictinfo, root);
3450  startup_cost += restrict_qual_cost.startup;
3451  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
3452  run_cost += cpu_per_tuple * ntuples;
3453 
3454  /* tlist eval costs are paid per output row, not per tuple scanned */
3455  startup_cost += path->jpath.path.pathtarget->cost.startup;
3456  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3457 
3458  path->jpath.path.startup_cost = startup_cost;
3459  path->jpath.path.total_cost = startup_cost + run_cost;
3460 }
static bool has_indexed_join_quals(NestPath *path)
Definition: costsize.c:5075
bool enable_nestloop
Definition: costsize.c:142
Cost inner_rescan_run_cost
Definition: pathnodes.h:3344
JoinPath jpath
Definition: pathnodes.h:2092

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

Referenced by create_nestloop_path().

◆ get_parameterized_baserel_size()

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

Definition at line 5243 of file costsize.c.

5245 {
5246  List *allclauses;
5247  double nrows;
5248 
5249  /*
5250  * Estimate the number of rows returned by the parameterized scan, knowing
5251  * that it will apply all the extra join clauses as well as the rel's own
5252  * restriction clauses. Note that we force the clauses to be treated as
5253  * non-join clauses during selectivity estimation.
5254  */
5255  allclauses = list_concat_copy(param_clauses, rel->baserestrictinfo);
5256  nrows = rel->tuples *
5258  allclauses,
5259  rel->relid, /* do not use 0! */
5260  JOIN_INNER,
5261  NULL);
5262  nrows = clamp_row_est(nrows);
5263  /* For safety, make sure result is not more than the base estimate */
5264  if (nrows > rel->rows)
5265  nrows = rel->rows;
5266  return nrows;
5267 }

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

Referenced by get_baserel_parampathinfo().

◆ get_parameterized_joinrel_size()

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

Definition at line 5324 of file costsize.c.

5329 {
5330  double nrows;
5331 
5332  /*
5333  * Estimate the number of rows returned by the parameterized join as the
5334  * sizes of the input paths times the selectivity of the clauses that have
5335  * ended up at this join node.
5336  *
5337  * As with set_joinrel_size_estimates, the rowcount estimate could depend
5338  * on the pair of input paths provided, though ideally we'd get the same
5339  * estimate for any pair with the same parameterization.
5340  */
5342  rel,
5343  outer_path->parent,
5344  inner_path->parent,
5345  outer_path->rows,
5346  inner_path->rows,
5347  sjinfo,
5348  restrict_clauses);
5349  /* For safety, make sure result is not more than the base estimate */
5350  if (nrows > rel->rows)
5351  nrows = rel->rows;
5352  return nrows;
5353 }
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:5365

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

Referenced by get_joinrel_parampathinfo().

◆ index_pages_fetched()

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

Definition at line 898 of file costsize.c.

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

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

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

◆ initial_cost_hashjoin()

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

Definition at line 4052 of file costsize.c.

4058 {
4059  Cost startup_cost = 0;
4060  Cost run_cost = 0;
4061  double outer_path_rows = outer_path->rows;
4062  double inner_path_rows = inner_path->rows;
4063  double inner_path_rows_total = inner_path_rows;
4064  int num_hashclauses = list_length(hashclauses);
4065  int numbuckets;
4066  int numbatches;
4067  int num_skew_mcvs;
4068  size_t space_allowed; /* unused */
4069 
4070  /* cost of source data */
4071  startup_cost += outer_path->startup_cost;
4072  run_cost += outer_path->total_cost - outer_path->startup_cost;
4073  startup_cost += inner_path->total_cost;
4074 
4075  /*
4076  * Cost of computing hash function: must do it once per input tuple. We
4077  * charge one cpu_operator_cost for each column's hash function. Also,
4078  * tack on one cpu_tuple_cost per inner row, to model the costs of
4079  * inserting the row into the hashtable.
4080  *
4081  * XXX when a hashclause is more complex than a single operator, we really
4082  * should charge the extra eval costs of the left or right side, as
4083  * appropriate, here. This seems more work than it's worth at the moment.
4084  */
4085  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
4086  * inner_path_rows;
4087  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
4088 
4089  /*
4090  * If this is a parallel hash build, then the value we have for
4091  * inner_rows_total currently refers only to the rows returned by each
4092  * participant. For shared hash table size estimation, we need the total
4093  * number, so we need to undo the division.
4094  */
4095  if (parallel_hash)
4096  inner_path_rows_total *= get_parallel_divisor(inner_path);
4097 
4098  /*
4099  * Get hash table size that executor would use for inner relation.
4100  *
4101  * XXX for the moment, always assume that skew optimization will be
4102  * performed. As long as SKEW_HASH_MEM_PERCENT is small, it's not worth
4103  * trying to determine that for sure.
4104  *
4105  * XXX at some point it might be interesting to try to account for skew
4106  * optimization in the cost estimate, but for now, we don't.
4107  */
4108  ExecChooseHashTableSize(inner_path_rows_total,
4109  inner_path->pathtarget->width,
4110  true, /* useskew */
4111  parallel_hash, /* try_combined_hash_mem */
4112  outer_path->parallel_workers,
4113  &space_allowed,
4114  &numbuckets,
4115  &numbatches,
4116  &num_skew_mcvs);
4117 
4118  /*
4119  * If inner relation is too big then we will need to "batch" the join,
4120  * which implies writing and reading most of the tuples to disk an extra
4121  * time. Charge seq_page_cost per page, since the I/O should be nice and
4122  * sequential. Writing the inner rel counts as startup cost, all the rest
4123  * as run cost.
4124  */
4125  if (numbatches > 1)
4126  {
4127  double outerpages = page_size(outer_path_rows,
4128  outer_path->pathtarget->width);
4129  double innerpages = page_size(inner_path_rows,
4130  inner_path->pathtarget->width);
4131 
4132  startup_cost += seq_page_cost * innerpages;
4133  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
4134  }
4135 
4136  /* CPU costs left for later */
4137 
4138  /* Public result fields */
4139  workspace->startup_cost = startup_cost;
4140  workspace->total_cost = startup_cost + run_cost;
4141  /* Save private data for final_cost_hashjoin */
4142  workspace->run_cost = run_cost;
4143  workspace->numbuckets = numbuckets;
4144  workspace->numbatches = numbatches;
4145  workspace->inner_rows_total = inner_path_rows_total;
4146 }
static double page_size(double tuples, int width)
Definition: costsize.c:6327
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:675

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

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

◆ initial_cost_mergejoin()

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

Definition at line 3493 of file costsize.c.

3499 {
3500  Cost startup_cost = 0;
3501  Cost run_cost = 0;
3502  double outer_path_rows = outer_path->rows;
3503  double inner_path_rows = inner_path->rows;
3504  Cost inner_run_cost;
3505  double outer_rows,
3506  inner_rows,
3507  outer_skip_rows,
3508  inner_skip_rows;
3509  Selectivity outerstartsel,
3510  outerendsel,
3511  innerstartsel,
3512  innerendsel;
3513  Path sort_path; /* dummy for result of cost_sort */
3514 
3515  /* Protect some assumptions below that rowcounts aren't zero */
3516  if (outer_path_rows <= 0)
3517  outer_path_rows = 1;
3518  if (inner_path_rows <= 0)
3519  inner_path_rows = 1;
3520 
3521  /*
3522  * A merge join will stop as soon as it exhausts either input stream
3523  * (unless it's an outer join, in which case the outer side has to be
3524  * scanned all the way anyway). Estimate fraction of the left and right
3525  * inputs that will actually need to be scanned. Likewise, we can
3526  * estimate the number of rows that will be skipped before the first join
3527  * pair is found, which should be factored into startup cost. We use only
3528  * the first (most significant) merge clause for this purpose. Since
3529  * mergejoinscansel() is a fairly expensive computation, we cache the
3530  * results in the merge clause RestrictInfo.
3531  */
3532  if (mergeclauses && jointype != JOIN_FULL)
3533  {
3534  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
3535  List *opathkeys;
3536  List *ipathkeys;
3537  PathKey *opathkey;
3538  PathKey *ipathkey;
3539  MergeScanSelCache *cache;
3540 
3541  /* Get the input pathkeys to determine the sort-order details */
3542  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
3543  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
3544  Assert(opathkeys);
3545  Assert(ipathkeys);
3546  opathkey = (PathKey *) linitial(opathkeys);
3547  ipathkey = (PathKey *) linitial(ipathkeys);
3548  /* debugging check */
3549  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
3550  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
3551  opathkey->pk_strategy != ipathkey->pk_strategy ||
3552  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
3553  elog(ERROR, "left and right pathkeys do not match in mergejoin");
3554 
3555  /* Get the selectivity with caching */
3556  cache = cached_scansel(root, firstclause, opathkey);
3557 
3558  if (bms_is_subset(firstclause->left_relids,
3559  outer_path->parent->relids))
3560  {
3561  /* left side of clause is outer */
3562  outerstartsel = cache->leftstartsel;
3563  outerendsel = cache->leftendsel;
3564  innerstartsel = cache->rightstartsel;
3565  innerendsel = cache->rightendsel;
3566  }
3567  else
3568  {
3569  /* left side of clause is inner */
3570  outerstartsel = cache->rightstartsel;
3571  outerendsel = cache->rightendsel;
3572  innerstartsel = cache->leftstartsel;
3573  innerendsel = cache->leftendsel;
3574  }
3575  if (jointype == JOIN_LEFT ||
3576  jointype == JOIN_ANTI)
3577  {
3578  outerstartsel = 0.0;
3579  outerendsel = 1.0;
3580  }
3581  else if (jointype == JOIN_RIGHT ||
3582  jointype == JOIN_RIGHT_ANTI)
3583  {
3584  innerstartsel = 0.0;
3585  innerendsel = 1.0;
3586  }
3587  }
3588  else
3589  {
3590  /* cope with clauseless or full mergejoin */
3591  outerstartsel = innerstartsel = 0.0;
3592  outerendsel = innerendsel = 1.0;
3593  }
3594 
3595  /*
3596  * Convert selectivities to row counts. We force outer_rows and
3597  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
3598  */
3599  outer_skip_rows = rint(outer_path_rows * outerstartsel);
3600  inner_skip_rows = rint(inner_path_rows * innerstartsel);
3601  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
3602  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
3603 
3604  Assert(outer_skip_rows <= outer_rows);
3605  Assert(inner_skip_rows <= inner_rows);
3606 
3607  /*
3608  * Readjust scan selectivities to account for above rounding. This is
3609  * normally an insignificant effect, but when there are only a few rows in
3610  * the inputs, failing to do this makes for a large percentage error.
3611  */
3612  outerstartsel = outer_skip_rows / outer_path_rows;
3613  innerstartsel = inner_skip_rows / inner_path_rows;
3614  outerendsel = outer_rows / outer_path_rows;
3615  innerendsel = inner_rows / inner_path_rows;
3616 
3617  Assert(outerstartsel <= outerendsel);
3618  Assert(innerstartsel <= innerendsel);
3619 
3620  /* cost of source data */
3621 
3622  if (outersortkeys) /* do we need to sort outer? */
3623  {
3624  cost_sort(&sort_path,
3625  root,
3626  outersortkeys,
3627  outer_path->total_cost,
3628  outer_path_rows,
3629  outer_path->pathtarget->width,
3630  0.0,
3631  work_mem,
3632  -1.0);
3633  startup_cost += sort_path.startup_cost;
3634  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3635  * outerstartsel;
3636  run_cost += (sort_path.total_cost - sort_path.startup_cost)
3637  * (outerendsel - outerstartsel);
3638  }
3639  else
3640  {
3641  startup_cost += outer_path->startup_cost;
3642  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
3643  * outerstartsel;
3644  run_cost += (outer_path->total_cost - outer_path->startup_cost)
3645  * (outerendsel - outerstartsel);
3646  }
3647 
3648  if (innersortkeys) /* do we need to sort inner? */
3649  {
3650  cost_sort(&sort_path,
3651  root,
3652  innersortkeys,
3653  inner_path->total_cost,
3654  inner_path_rows,
3655  inner_path->pathtarget->width,
3656  0.0,
3657  work_mem,
3658  -1.0);
3659  startup_cost += sort_path.startup_cost;
3660  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
3661  * innerstartsel;
3662  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
3663  * (innerendsel - innerstartsel);
3664  }
3665  else
3666  {
3667  startup_cost += inner_path->startup_cost;
3668  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
3669  * innerstartsel;
3670  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
3671  * (innerendsel - innerstartsel);
3672  }
3673 
3674  /*
3675  * We can't yet determine whether rescanning occurs, or whether
3676  * materialization of the inner input should be done. The minimum
3677  * possible inner input cost, regardless of rescan and materialization
3678  * considerations, is inner_run_cost. We include that in
3679  * workspace->total_cost, but not yet in run_cost.
3680  */
3681 
3682  /* CPU costs left for later */
3683 
3684  /* Public result fields */
3685  workspace->startup_cost = startup_cost;
3686  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
3687  /* Save private data for final_cost_mergejoin */
3688  workspace->run_cost = run_cost;
3689  workspace->inner_run_cost = inner_run_cost;
3690  workspace->outer_rows = outer_rows;
3691  workspace->inner_rows = inner_rows;
3692  workspace->outer_skip_rows = outer_skip_rows;
3693  workspace->inner_skip_rows = inner_skip_rows;
3694 }
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:3973
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_RIGHT
Definition: nodes.h:296
@ JOIN_LEFT
Definition: nodes.h:294
@ JOIN_RIGHT_ANTI
Definition: nodes.h:310
Selectivity leftstartsel
Definition: pathnodes.h:2740
Selectivity leftendsel
Definition: pathnodes.h:2741
Selectivity rightendsel
Definition: pathnodes.h:2743
Selectivity rightstartsel
Definition: pathnodes.h:2742
bool pk_nulls_first
Definition: pathnodes.h:1471
int pk_strategy
Definition: pathnodes.h:1470
Oid pk_opfamily
Definition: pathnodes.h:1469

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

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

◆ initial_cost_nestloop()

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

Definition at line 3212 of file costsize.c.

3216 {
3217  Cost startup_cost = 0;
3218  Cost run_cost = 0;
3219  double outer_path_rows = outer_path->rows;
3220  Cost inner_rescan_start_cost;
3221  Cost inner_rescan_total_cost;
3222  Cost inner_run_cost;
3223  Cost inner_rescan_run_cost;
3224 
3225  /* estimate costs to rescan the inner relation */
3226  cost_rescan(root, inner_path,
3227  &inner_rescan_start_cost,
3228  &inner_rescan_total_cost);
3229 
3230  /* cost of source data */
3231 
3232  /*
3233  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
3234  * before we can start returning tuples, so the join's startup cost is
3235  * their sum. We'll also pay the inner path's rescan startup cost
3236  * multiple times.
3237  */
3238  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
3239  run_cost += outer_path->total_cost - outer_path->startup_cost;
3240  if (outer_path_rows > 1)
3241  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
3242 
3243  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
3244  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
3245 
3246  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI ||
3247  extra->inner_unique)
3248  {
3249  /*
3250  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3251  * executor will stop after the first match.
3252  *
3253  * Getting decent estimates requires inspection of the join quals,
3254  * which we choose to postpone to final_cost_nestloop.
3255  */
3256 
3257  /* Save private data for final_cost_nestloop */
3258  workspace->inner_run_cost = inner_run_cost;
3259  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
3260  }
3261  else
3262  {
3263  /* Normal case; we'll scan whole input rel for each outer row */
3264  run_cost += inner_run_cost;
3265  if (outer_path_rows > 1)
3266  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
3267  }
3268 
3269  /* CPU costs left for later */
3270 
3271  /* Public result fields */
3272  workspace->startup_cost = startup_cost;
3273  workspace->total_cost = startup_cost + run_cost;
3274  /* Save private data for final_cost_nestloop */
3275  workspace->run_cost = run_cost;
3276 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:4507

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

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5213 of file costsize.c.

5214 {
5215  double nrows;
5216 
5217  /* Should only be applied to base relations */
5218  Assert(rel->relid > 0);
5219 
5220  nrows = rel->tuples *
5222  rel->baserestrictinfo,
5223  0,
5224  JOIN_INNER,
5225  NULL);
5226 
5227  rel->rows = clamp_row_est(nrows);
5228 
5230 
5231  set_rel_width(root, rel);
5232 }
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:6073
QualCost baserestrictcost
Definition: pathnodes.h:981

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

Referenced by postgresGetForeignRelSize(), set_cte_size_estimates(), set_function_size_estimates(), set_namedtuplestore_size_estimates(), set_plain_rel_size(), set_result_size_estimates(), set_subquery_size_estimates(), set_tablefunc_size_estimates(), set_tablesample_rel_size(), and set_values_size_estimates().

◆ set_cte_size_estimates()

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

Definition at line 5938 of file costsize.c.

5939 {
5940  RangeTblEntry *rte;
5941 
5942  /* Should only be applied to base relations that are CTE references */
5943  Assert(rel->relid > 0);
5944  rte = planner_rt_fetch(rel->relid, root);
5945  Assert(rte->rtekind == RTE_CTE);
5946 
5947  if (rte->self_reference)
5948  {
5949  /*
5950  * In a self-reference, we assume the average worktable size is a
5951  * multiple of the nonrecursive term's size. The best multiplier will
5952  * vary depending on query "fan-out", so make its value adjustable.
5953  */
5954  rel->tuples = clamp_row_est(recursive_worktable_factor * cte_rows);
5955  }
5956  else
5957  {
5958  /* Otherwise just believe the CTE's rowcount estimate */
5959  rel->tuples = cte_rows;
5960  }
5961 
5962  /* Now estimate number of output rows, etc */
5964 }
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5213
double recursive_worktable_factor
Definition: costsize.c:126

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

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

◆ set_foreign_size_estimates()

void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6038 of file costsize.c.

6039 {
6040  /* Should only be applied to base relations */
6041  Assert(rel->relid > 0);
6042 
6043  rel->rows = 1000; /* entirely bogus default estimate */
6044 
6046 
6047  set_rel_width(root, rel);
6048 }

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

5847 {
5848  RangeTblEntry *rte;
5849  ListCell *lc;
5850 
5851  /* Should only be applied to base relations that are functions */
5852  Assert(rel->relid > 0);
5853  rte = planner_rt_fetch(rel->relid, root);
5854  Assert(rte->rtekind == RTE_FUNCTION);
5855 
5856  /*
5857  * Estimate number of rows the functions will return. The rowcount of the
5858  * node is that of the largest function result.
5859  */
5860  rel->tuples = 0;
5861  foreach(lc, rte->functions)
5862  {
5863  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
5864  double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
5865 
5866  if (ntup > rel->tuples)
5867  rel->tuples = ntup;
5868  }
5869 
5870  /* Now estimate number of output rows, etc */
5872 }
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition: clauses.c:289

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

Referenced by set_rel_size().

◆ set_joinrel_size_estimates()

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

Definition at line 5292 of file costsize.c.

5297 {
5299  rel,
5300  outer_rel,
5301  inner_rel,
5302  outer_rel->rows,
5303  inner_rel->rows,
5304  sjinfo,
5305  restrictlist);
5306 }

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

Referenced by build_child_join_rel(), and build_join_rel().

◆ set_namedtuplestore_size_estimates()

void set_namedtuplestore_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5976 of file costsize.c.

5977 {
5978  RangeTblEntry *rte;
5979 
5980  /* Should only be applied to base relations that are tuplestore references */
5981  Assert(rel->relid > 0);
5982  rte = planner_rt_fetch(rel->relid, root);
5984 
5985  /*
5986  * Use the estimate provided by the code which is generating the named
5987  * tuplestore. In some cases, the actual number might be available; in
5988  * others the same plan will be re-used, so a "typical" value might be
5989  * estimated and used.
5990  */
5991  rel->tuples = rte->enrtuples;
5992  if (rel->tuples < 0)
5993  rel->tuples = 1000;
5994 
5995  /* Now estimate number of output rows, etc */
5997 }

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

Referenced by set_namedtuplestore_pathlist().

◆ set_pathtarget_cost_width()

PathTarget* set_pathtarget_cost_width ( PlannerInfo root,
PathTarget target 
)

Definition at line 6230 of file costsize.c.

6231 {
6232  int64 tuple_width = 0;
6233  ListCell *lc;
6234 
6235  /* Vars are assumed to have cost zero, but other exprs do not */
6236  target->cost.startup = 0;
6237  target->cost.per_tuple = 0;
6238 
6239  foreach(lc, target->exprs)
6240  {
6241  Node *node = (Node *) lfirst(lc);
6242 
6243  tuple_width += get_expr_width(root, node);
6244 
6245  /* For non-Vars, account for evaluation cost */
6246  if (!IsA(node, Var))
6247  {
6248  QualCost cost;
6249 
6250  cost_qual_eval_node(&cost, node, root);
6251  target->cost.startup += cost.startup;
6252  target->cost.per_tuple += cost.per_tuple;
6253  }
6254  }
6255 
6256  target->width = clamp_width_est(tuple_width);
6257 
6258  return target;
6259 }
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:231
static int32 get_expr_width(PlannerInfo *root, const Node *expr)
Definition: costsize.c:6268
List * exprs
Definition: pathnodes.h:1533
QualCost cost
Definition: pathnodes.h:1539
Definition: primnodes.h:248

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

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

◆ set_result_size_estimates()

void set_result_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6009 of file costsize.c.

6010 {
6011  /* Should only be applied to RTE_RESULT base relations */
6012  Assert(rel->relid > 0);
6013  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6014 
6015  /* RTE_RESULT always generates a single row, natively */
6016  rel->tuples = 1;
6017 
6018  /* Now estimate number of output rows, etc */
6020 }

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

5767 {
5768  PlannerInfo *subroot = rel->subroot;
5769  RelOptInfo *sub_final_rel;
5770  ListCell *lc;
5771 
5772  /* Should only be applied to base relations that are subqueries */
5773  Assert(rel->relid > 0);
5774  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_SUBQUERY);
5775 
5776  /*
5777  * Copy raw number of output rows from subquery. All of its paths should
5778  * have the same output rowcount, so just look at cheapest-total.
5779  */
5780  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
5781  rel->tuples = sub_final_rel->cheapest_total_path->rows;
5782 
5783  /*
5784  * Compute per-output-column width estimates by examining the subquery's
5785  * targetlist. For any output that is a plain Var, get the width estimate
5786  * that was made while planning the subquery. Otherwise, we leave it to
5787  * set_rel_width to fill in a datatype-based default estimate.
5788  */
5789  foreach(lc, subroot->parse->targetList)
5790  {
5791  TargetEntry *te = lfirst_node(TargetEntry, lc);
5792  Node *texpr = (Node *) te->expr;
5793  int32 item_width = 0;
5794 
5795  /* junk columns aren't visible to upper query */
5796  if (te->resjunk)
5797  continue;
5798 
5799  /*
5800  * The subquery could be an expansion of a view that's had columns
5801  * added to it since the current query was parsed, so that there are
5802  * non-junk tlist columns in it that don't correspond to any column
5803  * visible at our query level. Ignore such columns.
5804  */
5805  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
5806  continue;
5807 
5808  /*
5809  * XXX This currently doesn't work for subqueries containing set
5810  * operations, because the Vars in their tlists are bogus references
5811  * to the first leaf subquery, which wouldn't give the right answer
5812  * even if we could still get to its PlannerInfo.
5813  *
5814  * Also, the subquery could be an appendrel for which all branches are
5815  * known empty due to constraint exclusion, in which case
5816  * set_append_rel_pathlist will have left the attr_widths set to zero.
5817  *
5818  * In either case, we just leave the width estimate zero until
5819  * set_rel_width fixes it.
5820  */
5821  if (IsA(texpr, Var) &&
5822  subroot->parse->setOperations == NULL)
5823  {
5824  Var *var = (Var *) texpr;
5825  RelOptInfo *subrel = find_base_rel(subroot, var->varno);
5826 
5827  item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
5828  }
5829  rel->attr_widths[te->resno - rel->min_attr] = item_width;
5830  }
5831 
5832  /* Now estimate number of output rows, etc */
5834 }
signed int int32
Definition: c.h:494
@ UPPERREL_FINAL
Definition: pathnodes.h:79
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:414
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1470
Query * parse
Definition: pathnodes.h:202
Node * setOperations
Definition: parsenodes.h:219
List * targetList
Definition: parsenodes.h:191
struct Path * cheapest_total_path
Definition: pathnodes.h:896
PlannerInfo * subroot
Definition: pathnodes.h:947
AttrNumber max_attr
Definition: pathnodes.h:920
AttrNumber min_attr
Definition: pathnodes.h:918
Expr * expr
Definition: primnodes.h:2186
AttrNumber resno
Definition: primnodes.h:2188
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255

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

Referenced by build_setop_child_paths(), and set_subquery_pathlist().

◆ set_tablefunc_size_estimates()

void set_tablefunc_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5884 of file costsize.c.

5885 {
5886  /* Should only be applied to base relations that are functions */
5887  Assert(rel->relid > 0);
5888  Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
5889 
5890  rel->tuples = 100;
5891 
5892  /* Now estimate number of output rows, etc */
5894 }

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

5907 {
5908  RangeTblEntry *rte;
5909 
5910  /* Should only be applied to base relations that are values lists */
5911  Assert(rel->relid > 0);
5912  rte = planner_rt_fetch(rel->relid, root);
5913  Assert(rte->rtekind == RTE_VALUES);
5914 
5915  /*
5916  * Estimate number of rows the values list will return. We know this
5917  * precisely based on the list length (well, barring set-returning
5918  * functions in list items, but that's a refinement not catered for
5919  * anywhere else either).
5920  */
5921  rel->tuples = list_length(rte->values_lists);
5922 
5923  /* Now estimate number of output rows, etc */
5925 }
List * values_lists
Definition: parsenodes.h:1200

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

Referenced by set_rel_size().

Variable Documentation

◆ constraint_exclusion

PGDLLIMPORT int constraint_exclusion
extern

Definition at line 56 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ disable_cost

◆ enable_async_append

PGDLLIMPORT bool enable_async_append
extern

Definition at line 154 of file costsize.c.

Referenced by create_append_plan().

◆ enable_bitmapscan

PGDLLIMPORT bool enable_bitmapscan
extern

Definition at line 137 of file costsize.c.

Referenced by cost_bitmap_heap_scan().

◆ enable_gathermerge

PGDLLIMPORT bool enable_gathermerge
extern

Definition at line 147 of file costsize.c.

Referenced by cost_gather_merge().

◆ enable_hashagg

◆ enable_hashjoin

PGDLLIMPORT bool enable_hashjoin
extern

Definition at line 146 of file costsize.c.

Referenced by add_paths_to_joinrel(), and final_cost_hashjoin().

◆ enable_incremental_sort

◆ enable_indexonlyscan

PGDLLIMPORT bool enable_indexonlyscan
extern

Definition at line 136 of file costsize.c.

Referenced by check_index_only().

◆ enable_indexscan

PGDLLIMPORT bool enable_indexscan
extern

Definition at line 135 of file costsize.c.

Referenced by cost_index(), and plan_cluster_use_sort().

◆ enable_material

PGDLLIMPORT bool enable_material
extern

◆ enable_memoize

PGDLLIMPORT bool enable_memoize
extern

Definition at line 144 of file costsize.c.

Referenced by get_memoize_path().

◆ enable_mergejoin

PGDLLIMPORT bool enable_mergejoin
extern

Definition at line 145 of file costsize.c.

Referenced by add_paths_to_joinrel(), and final_cost_mergejoin().

◆ enable_nestloop

PGDLLIMPORT bool enable_nestloop
extern

Definition at line 142 of file costsize.c.

Referenced by final_cost_nestloop().

◆ enable_parallel_append

PGDLLIMPORT bool enable_parallel_append
extern

Definition at line 150 of file costsize.c.

Referenced by add_paths_to_append_rel(), and generate_union_paths().

◆ enable_parallel_hash

PGDLLIMPORT bool enable_parallel_hash
extern

Definition at line 151 of file costsize.c.

Referenced by hash_inner_and_outer().

◆ enable_partition_pruning

PGDLLIMPORT bool enable_partition_pruning
extern

◆ enable_partitionwise_aggregate

PGDLLIMPORT bool enable_partitionwise_aggregate
extern

Definition at line 149 of file costsize.c.

Referenced by create_grouping_paths().

◆ enable_partitionwise_join

PGDLLIMPORT bool enable_partitionwise_join
extern

Definition at line 148 of file costsize.c.

Referenced by build_joinrel_partition_info(), and set_append_rel_size().

◆ enable_presorted_aggregate

PGDLLIMPORT bool enable_presorted_aggregate
extern

Definition at line 153 of file costsize.c.

Referenced by adjust_group_pathkeys_for_groupagg().

◆ enable_seqscan

PGDLLIMPORT bool enable_seqscan
extern

Definition at line 134 of file costsize.c.

Referenced by cost_seqscan().

◆ enable_sort

PGDLLIMPORT bool enable_sort
extern

Definition at line 139 of file costsize.c.

Referenced by cost_sort().

◆ enable_tidscan

PGDLLIMPORT bool enable_tidscan
extern

Definition at line 138 of file costsize.c.

Referenced by create_tidscan_paths().

◆ max_parallel_workers_per_gather