PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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, int input_disabled_nodes, 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, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_append (AppendPath *apath, PlannerInfo *root)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, bool enabled, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, int disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples, double input_width)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, WindowClause *winclause, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, uint64 enable_mask, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, int outer_presorted_keys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, double *rows)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, int input_disabled_nodes, Cost input_startup_cost, Cost input_total_cost, double *rows)
 
void cost_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_groupagg
 
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 
)
extern

Definition at line 6681 of file costsize.c.

6684{
6685 Cost indexTotalCost;
6686 Selectivity indexSelectivity;
6687 double T;
6688 double pages_fetched;
6689 double tuples_fetched;
6690 double heap_pages;
6691 double maxentries;
6692
6693 /*
6694 * Fetch total cost of obtaining the bitmap, as well as its total
6695 * selectivity.
6696 */
6697 cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
6698
6699 /*
6700 * Estimate number of main-table pages fetched.
6701 */
6702 tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
6703
6704 T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
6705
6706 /*
6707 * For a single scan, the number of heap pages that need to be fetched is
6708 * the same as the Mackert and Lohman formula for the case T <= b (ie, no
6709 * re-reads needed).
6710 */
6711 pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
6712
6713 /*
6714 * Calculate the number of pages fetched from the heap. Then based on
6715 * current work_mem estimate get the estimated maxentries in the bitmap.
6716 * (Note that we always do this calculation based on the number of pages
6717 * that would be fetched in a single iteration, even if loop_count > 1.
6718 * That's correct, because only that number of entries will be stored in
6719 * the bitmap at one time.)
6720 */
6722 maxentries = tbm_calculate_entries(work_mem * (Size) 1024);
6723
6724 if (loop_count > 1)
6725 {
6726 /*
6727 * For repeated bitmap scans, scale up the number of tuples fetched in
6728 * the Mackert and Lohman formula by the number of scans, so that we
6729 * estimate the number of pages fetched by all the scans. Then
6730 * pro-rate for one scan.
6731 */
6732 pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
6733 baserel->pages,
6734 get_indexpath_pages(bitmapqual),
6735 root);
6737 }
6738
6739 if (pages_fetched >= T)
6740 pages_fetched = T;
6741 else
6743
6744 if (maxentries < heap_pages)
6745 {
6746 double exact_pages;
6747 double lossy_pages;
6748
6749 /*
6750 * Crude approximation of the number of lossy pages. Because of the
6751 * way tbm_lossify() is coded, the number of lossy pages increases
6752 * very sharply as soon as we run short of memory; this formula has
6753 * that property and seems to perform adequately in testing, but it's
6754 * possible we could do better somehow.
6755 */
6756 lossy_pages = Max(0, heap_pages - maxentries / 2);
6757 exact_pages = heap_pages - lossy_pages;
6758
6759 /*
6760 * If there are lossy pages then recompute the number of tuples
6761 * processed by the bitmap heap node. We assume here that the chance
6762 * of a given tuple coming from an exact page is the same as the
6763 * chance that a given page is exact. This might not be true, but
6764 * it's not clear how we can do any better.
6765 */
6766 if (lossy_pages > 0)
6767 tuples_fetched =
6768 clamp_row_est(indexSelectivity *
6769 (exact_pages / heap_pages) * baserel->tuples +
6770 (lossy_pages / heap_pages) * baserel->tuples);
6771 }
6772
6773 if (cost_p)
6774 *cost_p = indexTotalCost;
6775 if (tuples_p)
6776 *tuples_p = tuples_fetched;
6777
6778 return pages_fetched;
6779}
#define Min(x, y)
Definition c.h:1131
#define Max(x, y)
Definition c.h:1125
size_t Size
Definition c.h:748
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:1116
static double get_indexpath_pages(Path *bitmapqual)
Definition costsize.c:963
double clamp_row_est(double nrows)
Definition costsize.c:215
int work_mem
Definition globals.c:133
static const uint32 T[65]
Definition md5.c:119
double Cost
Definition nodes.h:259
double Selectivity
Definition nodes.h:258
static int fb(int x)
tree ctl root
Definition radixtree.h:1857
int tbm_calculate_entries(Size maxbytes)
Definition tidbitmap.c:1542

References clamp_row_est(), cost_bitmap_tree_node(), fb(), get_indexpath_pages(), index_pages_fetched(), Max, Min, root, T, tbm_calculate_entries(), and work_mem.

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

◆ compute_gather_rows()

double compute_gather_rows ( Path path)
extern

Definition at line 6792 of file costsize.c.

6793{
6794 Assert(path->parallel_workers > 0);
6795
6796 return clamp_row_est(path->rows * get_parallel_divisor(path));
6797}
#define Assert(condition)
Definition c.h:1002
static double get_parallel_divisor(Path *path)
Definition costsize.c:6641
Cardinality rows
Definition pathnodes.h:2005
int parallel_workers
Definition pathnodes.h:2002

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

Definition at line 5281 of file costsize.c.

5289{
5294 List *joinquals;
5295 ListCell *l;
5296
5297 /*
5298 * In an ANTI join, we must ignore clauses that are "pushed down", since
5299 * those won't affect the match logic. In a SEMI join, we do not
5300 * distinguish joinquals from "pushed down" quals, so just use the whole
5301 * restrictinfo list. For other outer join types, we should consider only
5302 * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
5303 */
5304 if (IS_OUTER_JOIN(jointype))
5305 {
5306 joinquals = NIL;
5307 foreach(l, restrictlist)
5308 {
5310
5311 if (!RINFO_IS_PUSHED_DOWN(rinfo, joinrel->relids))
5312 joinquals = lappend(joinquals, rinfo);
5313 }
5314 }
5315 else
5316 joinquals = restrictlist;
5317
5318 /*
5319 * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
5320 */
5322 joinquals,
5323 0,
5324 (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
5325 sjinfo);
5326
5327 /*
5328 * Also get the normal inner-join selectivity of the join clauses.
5329 */
5330 init_dummy_sjinfo(&norm_sjinfo, outerrel->relids, innerrel->relids);
5331
5333 joinquals,
5334 0,
5335 JOIN_INNER,
5336 &norm_sjinfo);
5337
5338 /* Avoid leaking a lot of ListCells */
5339 if (IS_OUTER_JOIN(jointype))
5341
5342 /*
5343 * jselec can be interpreted as the fraction of outer-rel rows that have
5344 * any matches (this is true for both SEMI and ANTI cases). And nselec is
5345 * the fraction of the Cartesian product that matches. So, the average
5346 * number of matches for each outer-rel row that has at least one match is
5347 * nselec * inner_rows / jselec.
5348 *
5349 * Note: it is correct to use the inner rel's "rows" count here, even
5350 * though we might later be considering a parameterized inner path with
5351 * fewer rows. This is because we have included all the join clauses in
5352 * the selectivity estimate.
5353 */
5354 if (jselec > 0) /* protect against zero divide */
5355 {
5356 avgmatch = nselec * innerrel->rows / jselec;
5357 /* Clamp to sane range */
5358 avgmatch = Max(1.0, avgmatch);
5359 }
5360 else
5361 avgmatch = 1.0;
5362
5363 semifactors->outer_match_frac = jselec;
5364 semifactors->match_count = avgmatch;
5365}
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:664
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:346
@ JOIN_SEMI
Definition nodes.h:315
@ JOIN_INNER
Definition nodes.h:301
@ JOIN_ANTI
Definition nodes.h:316
#define RINFO_IS_PUSHED_DOWN(rinfo, joinrelids)
Definition pathnodes.h:3058
#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:1021
Cardinality rows
Definition pathnodes.h:1027
Selectivity outer_match_frac
Definition pathnodes.h:3600
Selectivity match_count
Definition pathnodes.h:3601

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

Referenced by add_paths_to_joinrel().

◆ cost_agg()

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

Definition at line 2789 of file costsize.c.

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

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, Assert, clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, enable_groupagg, enable_hashagg, fb(), hash_agg_entry_size(), hash_agg_set_limits(), JOIN_INNER, list_length(), Max, random_page_cost, relation_byte_size(), root, Path::rows, seq_page_cost, Path::startup_cost, and Path::total_cost.

Referenced by create_agg_path(), and create_groupingsets_path().

◆ cost_append()

void cost_append ( AppendPath apath,
PlannerInfo root 
)
extern

Definition at line 2312 of file costsize.c.

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

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

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)
extern

Definition at line 1159 of file costsize.c.

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

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

Referenced by create_bitmap_and_path().

◆ cost_bitmap_heap_scan()

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

Definition at line 1013 of file costsize.c.

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

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)
extern

Definition at line 1204 of file costsize.c.

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

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

Referenced by create_bitmap_or_path().

◆ cost_bitmap_tree_node()

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

Definition at line 1116 of file costsize.c.

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

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

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

◆ cost_ctescan()

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

Definition at line 1746 of file costsize.c.

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

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

◆ cost_functionscan()

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

Definition at line 1564 of file costsize.c.

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

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

Referenced by create_functionscan_path().

◆ cost_gather()

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

Definition at line 431 of file costsize.c.

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

References Path::disabled_nodes, fb(), parallel_setup_cost, parallel_tuple_cost, GatherPath::path, PGS_GATHER, RelOptInfo::pgs_mask, RelOptInfo::rows, Path::rows, Path::startup_cost, GatherPath::subpath, and Path::total_cost.

Referenced by create_gather_path().

◆ cost_gather_merge()

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

Definition at line 471 of file costsize.c.

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

References Assert, cpu_operator_cost, Path::disabled_nodes, fb(), LOG2, GatherMergePath::num_workers, parallel_setup_cost, parallel_tuple_cost, GatherMergePath::path, PGS_GATHER_MERGE, RelOptInfo::pgs_mask, RelOptInfo::rows, Path::rows, Path::startup_cost, GatherMergePath::subpath, and Path::total_cost.

Referenced by create_gather_merge_path().

◆ cost_group()

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

Definition at line 3324 of file costsize.c.

3330{
3331 double output_tuples;
3332 Cost startup_cost;
3333 Cost total_cost;
3334
3335 output_tuples = numGroups;
3336 startup_cost = input_startup_cost;
3337 total_cost = input_total_cost;
3338
3339 /*
3340 * Charge one cpu_operator_cost per comparison per input tuple. We assume
3341 * all columns get compared at most of the tuples.
3342 */
3343 total_cost += cpu_operator_cost * input_tuples * numGroupCols;
3344
3345 /*
3346 * If there are quals (HAVING quals), account for their cost and
3347 * selectivity.
3348 */
3349 if (quals)
3350 {
3352
3353 cost_qual_eval(&qual_cost, quals, root);
3354 startup_cost += qual_cost.startup;
3355 total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
3356
3359 quals,
3360 0,
3361 JOIN_INNER,
3362 NULL));
3363 }
3364
3365 path->rows = output_tuples;
3367 path->startup_cost = startup_cost;
3368 path->total_cost = total_cost;
3369}

References clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, Path::disabled_nodes, enable_groupagg, fb(), JOIN_INNER, root, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by create_group_path().

◆ cost_incremental_sort()

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

Definition at line 2054 of file costsize.c.

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

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

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

◆ cost_index()

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

Definition at line 546 of file costsize.c.

548{
550 RelOptInfo *baserel = index->rel;
551 bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
552 amcostestimate_function amcostestimate;
553 List *qpquals;
554 Cost startup_cost = 0;
555 Cost run_cost = 0;
556 Cost cpu_run_cost = 0;
557 Cost indexStartupCost;
558 Cost indexTotalCost;
559 Selectivity indexSelectivity;
560 double indexCorrelation,
561 csquared;
562 double spc_seq_page_cost,
563 spc_random_page_cost;
568 double tuples_fetched;
569 double pages_fetched;
570 double rand_heap_pages;
571 double index_pages;
573
574 /* Should only be applied to base relations */
577 Assert(baserel->relid > 0);
578 Assert(baserel->rtekind == RTE_RELATION);
579
580 /*
581 * Mark the path with the correct row estimate, and identify which quals
582 * will need to be enforced as qpquals. We need not check any quals that
583 * are implied by the index's predicate, so we can use indrestrictinfo not
584 * baserestrictinfo as the list of relevant restriction clauses for the
585 * rel.
586 */
587 if (path->path.param_info)
588 {
589 path->path.rows = path->path.param_info->ppi_rows;
590 /* qpquals come from the rel's restriction clauses and ppi_clauses */
592 path->indexclauses),
593 extract_nonindex_conditions(path->path.param_info->ppi_clauses,
594 path->indexclauses));
595 }
596 else
597 {
598 path->path.rows = baserel->rows;
599 /* qpquals come from just the rel's restriction clauses */
601 path->indexclauses);
602 }
603
604 /* is this scan type disabled? */
607 path->path.disabled_nodes =
608 (baserel->pgs_mask & enable_mask) == enable_mask ? 0 : 1;
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 */
639 get_tablespace_page_costs(baserel->reltablespace,
640 &spc_random_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 */
681 baserel->pages,
682 (double) index->pages,
683 root);
684
685 if (indexonly)
686 pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
687
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
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
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)
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 */
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 */
796
797 startup_cost += qpqual_cost.startup;
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 {
810
812
813 /* The CPU cost is divided among all the workers. */
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:4973
void(* amcostestimate_function)(PlannerInfo *root, IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition amapi.h:148
int max_parallel_workers_per_gather
Definition costsize.c:144
static List * extract_nonindex_conditions(List *qual_clauses, List *indexclauses)
Definition costsize.c:840
List * list_concat(List *list1, const List *list2)
Definition list.c:561
#define PGS_INDEXONLYSCAN
Definition pathnodes.h:68
#define PGS_INDEXSCAN
Definition pathnodes.h:67
List * indrestrictinfo
Definition pathnodes.h:1417
List * indexclauses
Definition pathnodes.h:2057
Selectivity indexselectivity
Definition pathnodes.h:2062
Cost indextotalcost
Definition pathnodes.h:2061
IndexOptInfo * indexinfo
Definition pathnodes.h:2056
NodeTag pathtype
Definition pathnodes.h:1971
bool parallel_aware
Definition pathnodes.h:1998
Definition type.h:97

References Assert, clamp_row_est(), compute_parallel_worker(), cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, extract_nonindex_conditions(), fb(), get_parallel_divisor(), get_tablespace_page_costs(), index_pages_fetched(), IndexPath::indexclauses, IndexPath::indexinfo, IndexPath::indexselectivity, IndexPath::indextotalcost, IndexOptInfo::indrestrictinfo, IsA, list_concat(), max_parallel_workers_per_gather, Path::parallel_aware, Path::parallel_workers, IndexPath::path, Path::pathtype, PGS_CONSIDER_NONPARTIAL, PGS_INDEXONLYSCAN, PGS_INDEXSCAN, root, Path::rows, RTE_RELATION, Path::startup_cost, and Path::total_cost.

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2584 of file costsize.c.

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

References cpu_operator_cost, Path::disabled_nodes, fb(), 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,
int  input_disabled_nodes,
Cost  input_startup_cost,
Cost  input_total_cost,
double  tuples 
)
extern

Definition at line 2526 of file costsize.c.

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

References APPEND_CPU_COST_MULTIPLIER, cpu_operator_cost, cpu_tuple_cost, Path::disabled_nodes, fb(), LOG2, Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, RelOptInfo::pgs_mask, PGS_MERGE_APPEND, Path::startup_cost, and Path::total_cost.

Referenced by create_merge_append_path().

◆ cost_namedtuplestorescan()

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

Definition at line 1792 of file costsize.c.

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

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

Referenced by create_namedtuplestorescan_path().

◆ cost_qual_eval()

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

Definition at line 4923 of file costsize.c.

4924{
4925 cost_qual_eval_context context;
4926 ListCell *l;
4927
4928 context.root = root;
4929 context.total.startup = 0;
4930 context.total.per_tuple = 0;
4931
4932 /* We don't charge any cost for the implicit ANDing at top level ... */
4933
4934 foreach(l, quals)
4935 {
4936 Node *qual = (Node *) lfirst(l);
4937
4938 cost_qual_eval_walker(qual, &context);
4939 }
4940
4941 *cost = context.total;
4942}
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition costsize.c:4963
Cost per_tuple
Definition pathnodes.h:121
Cost startup
Definition pathnodes.h:120
PlannerInfo * root
Definition costsize.c:171

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

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

◆ cost_qual_eval_node()

◆ cost_recursive_union()

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

Definition at line 1876 of file costsize.c.

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

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

Referenced by create_recursiveunion_path().

◆ cost_resultscan()

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

Definition at line 1834 of file costsize.c.

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

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

Referenced by create_resultscan_path().

◆ cost_samplescan()

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

Definition at line 350 of file costsize.c.

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

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

Referenced by create_samplescan_path().

◆ cost_seqscan()

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

Definition at line 271 of file costsize.c.

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

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

Referenced by create_seqscan_path().

◆ cost_sort()

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

Definition at line 2202 of file costsize.c.

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

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

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

◆ cost_subplan()

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

Definition at line 4700 of file costsize.c.

4701{
4703
4704 /*
4705 * Figure any cost for evaluating the testexpr.
4706 *
4707 * Usually, SubPlan nodes are built very early, before we have constructed
4708 * any RelOptInfos for the parent query level, which means the parent root
4709 * does not yet contain enough information to safely consult statistics.
4710 * Therefore, we pass root as NULL here. cost_qual_eval() is already
4711 * well-equipped to handle a NULL root.
4712 *
4713 * One exception is SubPlan nodes built for the initplans of MIN/MAX
4714 * aggregates from indexes (cf. SS_make_initplan_from_plan). In this
4715 * case, having a NULL root is safe because testexpr will be NULL.
4716 * Besides, an initplan will by definition not consult anything from the
4717 * parent plan.
4718 */
4720 make_ands_implicit((Expr *) subplan->testexpr),
4721 NULL);
4722
4723 if (subplan->useHashTable)
4724 {
4725 /*
4726 * If we are using a hash table for the subquery outputs, then the
4727 * cost of evaluating the query is a one-time cost. We charge one
4728 * cpu_operator_cost per tuple for the work of loading the hashtable,
4729 * too.
4730 */
4731 sp_cost.startup += plan->total_cost +
4732 cpu_operator_cost * plan->plan_rows;
4733
4734 /*
4735 * The per-tuple costs include the cost of evaluating the lefthand
4736 * expressions, plus the cost of probing the hashtable. We already
4737 * accounted for the lefthand expressions as part of the testexpr, and
4738 * will also have counted one cpu_operator_cost for each comparison
4739 * operator. That is probably too low for the probing cost, but it's
4740 * hard to make a better estimate, so live with it for now.
4741 */
4742 }
4743 else
4744 {
4745 /*
4746 * Otherwise we will be rescanning the subplan output on each
4747 * evaluation. We need to estimate how much of the output we will
4748 * actually need to scan. NOTE: this logic should agree with the
4749 * tuple_fraction estimates used by make_subplan() in
4750 * plan/subselect.c.
4751 */
4752 Cost plan_run_cost = plan->total_cost - plan->startup_cost;
4753
4754 if (subplan->subLinkType == EXISTS_SUBLINK)
4755 {
4756 /* we only need to fetch 1 tuple; clamp to avoid zero divide */
4757 sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
4758 }
4759 else if (subplan->subLinkType == ALL_SUBLINK ||
4760 subplan->subLinkType == ANY_SUBLINK)
4761 {
4762 /* assume we need 50% of the tuples */
4763 sp_cost.per_tuple += 0.50 * plan_run_cost;
4764 /* also charge a cpu_operator_cost per row examined */
4765 sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
4766 }
4767 else
4768 {
4769 /* assume we need all tuples */
4770 sp_cost.per_tuple += plan_run_cost;
4771 }
4772
4773 /*
4774 * Also account for subplan's startup cost. If the subplan is
4775 * uncorrelated or undirect correlated, AND its topmost node is one
4776 * that materializes its output, assume that we'll only need to pay
4777 * its startup cost once; otherwise assume we pay the startup cost
4778 * every time.
4779 */
4780 if (subplan->parParam == NIL &&
4782 sp_cost.startup += plan->startup_cost;
4783 else
4784 sp_cost.per_tuple += plan->startup_cost;
4785 }
4786
4787 subplan->disabled_nodes = plan->disabled_nodes;
4788 subplan->startup_cost = sp_cost.startup;
4789 subplan->per_call_cost = sp_cost.per_tuple;
4790}
bool ExecMaterializesOutput(NodeTag plantype)
Definition execAmi.c:636
List * make_ands_implicit(Expr *clause)
Definition makefuncs.c:810
#define plan(x)
Definition pg_regress.c:164
@ ANY_SUBLINK
Definition primnodes.h:1013
@ ALL_SUBLINK
Definition primnodes.h:1012
@ EXISTS_SUBLINK
Definition primnodes.h:1011
int disabled_nodes
Definition primnodes.h:1108
bool useHashTable
Definition primnodes.h:1094
Node * testexpr
Definition primnodes.h:1081
List * parParam
Definition primnodes.h:1105
Cost startup_cost
Definition primnodes.h:1109
Cost per_call_cost
Definition primnodes.h:1110
SubLinkType subLinkType
Definition primnodes.h:1079

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

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

◆ cost_subqueryscan()

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

Definition at line 1479 of file costsize.c.

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

References Assert, clamp_row_est(), clauselist_selectivity(), cpu_tuple_cost, Path::disabled_nodes, fb(), get_restriction_qual_cost(), JOIN_INNER, list_concat_copy(), NIL, Path::parallel_workers, SubqueryScanPath::path, PGS_CONSIDER_NONPARTIAL, root, Path::rows, RTE_SUBQUERY, Path::startup_cost, SubqueryScanPath::subpath, and Path::total_cost.

Referenced by create_subqueryscan_path().

◆ cost_tablefuncscan()

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

Definition at line 1630 of file costsize.c.

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

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

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

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

Definition at line 1362 of file costsize.c.

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

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

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1252 of file costsize.c.

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

References ScalarArrayOpExpr::args, Assert, RestrictInfo::clause, cost_qual_eval(), cpu_tuple_cost, Path::disabled_nodes, estimate_array_length(), fb(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, lfirst_node, list_length(), lsecond, NIL, Path::parallel_workers, PGS_CONSIDER_NONPARTIAL, PGS_TIDSCAN, root, Path::rows, RTE_RELATION, Path::startup_cost, and Path::total_cost.

Referenced by create_tidscan_path().

◆ cost_valuesscan()

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

Definition at line 1691 of file costsize.c.

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

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

Referenced by create_valuesscan_path().

◆ cost_windowagg()

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

Definition at line 3227 of file costsize.c.

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

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

Referenced by create_windowagg_path().

◆ final_cost_hashjoin()

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

Definition at line 4439 of file costsize.c.

4442{
4446 double inner_path_rows = inner_path->rows;
4447 double inner_path_rows_total = workspace->inner_rows_total;
4448 List *hashclauses = path->path_hashclauses;
4449 Cost startup_cost = workspace->startup_cost;
4450 Cost run_cost = workspace->run_cost;
4451 int numbuckets = workspace->numbuckets;
4452 int numbatches = workspace->numbatches;
4456 double hashjointuples;
4457 double virtualbuckets;
4460 ListCell *hcl;
4461
4462 /* Set the number of disabled nodes. */
4463 path->jpath.path.disabled_nodes = workspace->disabled_nodes;
4464
4465 /* Mark the path with the correct row estimate */
4466 if (path->jpath.path.param_info)
4467 path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
4468 else
4469 path->jpath.path.rows = path->jpath.path.parent->rows;
4470
4471 /* For partial paths, scale row estimate. */
4472 if (path->jpath.path.parallel_workers > 0)
4473 {
4474 double parallel_divisor = get_parallel_divisor(&path->jpath.path);
4475
4476 path->jpath.path.rows =
4477 clamp_row_est(path->jpath.path.rows / parallel_divisor);
4478 }
4479
4480 /* mark the path with estimated # of batches */
4481 path->num_batches = numbatches;
4482
4483 /* store the total number of tuples (sum of partial row estimates) */
4485
4486 /* and compute the number of "virtual" buckets in the whole join */
4487 virtualbuckets = (double) numbuckets * (double) numbatches;
4488
4489 /*
4490 * Determine bucketsize fraction and MCV frequency for the inner relation.
4491 * We use the smallest bucketsize or MCV frequency estimated for any
4492 * individual hashclause; this is undoubtedly conservative.
4493 *
4494 * BUT: if inner relation has been unique-ified, we can assume it's good
4495 * for hashing. This is important both because it's the right answer, and
4496 * because we avoid contaminating the cache with a value that's wrong for
4497 * non-unique-ified paths.
4498 */
4499 if (RELATION_WAS_MADE_UNIQUE(inner_path->parent, extra->sjinfo,
4500 path->jpath.jointype))
4501 {
4504 }
4505 else
4506 {
4508
4509 innerbucketsize = 1.0;
4510 innermcvfreq = 1.0;
4511
4512 /* At first, try to estimate bucket size using extended statistics. */
4514 inner_path->parent,
4515 hashclauses,
4517
4518 /* Pass through the remaining clauses */
4519 foreach(hcl, otherclauses)
4520 {
4524
4525 /*
4526 * First we have to figure out which side of the hashjoin clause
4527 * is the inner side.
4528 *
4529 * Since we tend to visit the same clauses over and over when
4530 * planning a large query, we cache the bucket stats estimates in
4531 * the RestrictInfo node to avoid repeated lookups of statistics.
4532 */
4533 if (bms_is_subset(restrictinfo->right_relids,
4534 inner_path->parent->relids))
4535 {
4536 /* righthand side is inner */
4537 thisbucketsize = restrictinfo->right_bucketsize;
4538 if (thisbucketsize < 0)
4539 {
4540 /* not cached yet */
4542 get_rightop(restrictinfo->clause),
4544 &restrictinfo->right_mcvfreq,
4545 &restrictinfo->right_bucketsize);
4546 thisbucketsize = restrictinfo->right_bucketsize;
4547 }
4548 thismcvfreq = restrictinfo->right_mcvfreq;
4549 }
4550 else
4551 {
4552 Assert(bms_is_subset(restrictinfo->left_relids,
4553 inner_path->parent->relids));
4554 /* lefthand side is inner */
4555 thisbucketsize = restrictinfo->left_bucketsize;
4556 if (thisbucketsize < 0)
4557 {
4558 /* not cached yet */
4560 get_leftop(restrictinfo->clause),
4562 &restrictinfo->left_mcvfreq,
4563 &restrictinfo->left_bucketsize);
4564 thisbucketsize = restrictinfo->left_bucketsize;
4565 }
4566 thismcvfreq = restrictinfo->left_mcvfreq;
4567 }
4568
4571 /* Disregard zero for MCV freq, it means we have no data */
4572 if (thismcvfreq > 0.0 && innermcvfreq > thismcvfreq)
4574 }
4575 }
4576
4577 /*
4578 * If the bucket holding the inner MCV would exceed hash_mem, we don't
4579 * want to hash unless there is really no other alternative, so apply
4580 * disable_cost. (The executor normally copes with excessive memory usage
4581 * by splitting batches, but obviously it cannot separate equal values
4582 * that way, so it will be unable to drive the batch size below hash_mem
4583 * when this is true.)
4584 */
4586 inner_path->pathtarget->width) > get_hash_memory_limit())
4587 startup_cost += disable_cost;
4588
4589 /*
4590 * Compute cost of the hashquals and qpquals (other restriction clauses)
4591 * separately.
4592 */
4593 cost_qual_eval(&hash_qual_cost, hashclauses, root);
4595 qp_qual_cost.startup -= hash_qual_cost.startup;
4596 qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
4597
4598 /* CPU costs */
4599
4600 if (path->jpath.jointype == JOIN_SEMI ||
4601 path->jpath.jointype == JOIN_ANTI ||
4602 extra->inner_unique)
4603 {
4604 double outer_matched_rows;
4606
4607 /*
4608 * With a SEMI or ANTI join, or if the innerrel is known unique, the
4609 * executor will stop after the first match.
4610 *
4611 * For an outer-rel row that has at least one match, we can expect the
4612 * bucket scan to stop after a fraction 1/(match_count+1) of the
4613 * bucket's rows, if the matches are evenly distributed. Since they
4614 * probably aren't quite evenly distributed, we apply a fuzz factor of
4615 * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
4616 * to clamp inner_scan_frac to at most 1.0; but since match_count is
4617 * at least 1, no such clamp is needed now.)
4618 */
4620 inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
4621
4622 startup_cost += hash_qual_cost.startup;
4623 run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
4625
4626 /*
4627 * For unmatched outer-rel rows, the picture is quite a lot different.
4628 * In the first place, there is no reason to assume that these rows
4629 * preferentially hit heavily-populated buckets; instead assume they
4630 * are uncorrelated with the inner distribution and so they see an
4631 * average bucket size of inner_path_rows / virtualbuckets. In the
4632 * second place, it seems likely that they will have few if any exact
4633 * hash-code matches and so very few of the tuples in the bucket will
4634 * actually require eval of the hash quals. We don't have any good
4635 * way to estimate how many will, but for the moment assume that the
4636 * effective cost per bucket entry is one-tenth what it is for
4637 * matchable tuples.
4638 */
4639 run_cost += hash_qual_cost.per_tuple *
4642
4643 /* Get # of tuples that will pass the basic join */
4644 if (path->jpath.jointype == JOIN_ANTI)
4646 else
4648 }
4649 else
4650 {
4651 /*
4652 * The number of tuple comparisons needed is the number of outer
4653 * tuples times the typical number of tuples in a hash bucket, which
4654 * is the inner relation size times its bucketsize fraction. At each
4655 * one, we need to evaluate the hashjoin quals. But actually,
4656 * charging the full qual eval cost at each tuple is pessimistic,
4657 * since we don't evaluate the quals unless the hash values match
4658 * exactly. For lack of a better idea, halve the cost estimate to
4659 * allow for that.
4660 */
4661 startup_cost += hash_qual_cost.startup;
4662 run_cost += hash_qual_cost.per_tuple * outer_path_rows *
4664
4665 /*
4666 * Get approx # tuples passing the hashquals. We use
4667 * approx_tuple_count here because we need an estimate done with
4668 * JOIN_INNER semantics.
4669 */
4670 hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
4671 }
4672
4673 /*
4674 * For each tuple that gets through the hashjoin proper, we charge
4675 * cpu_tuple_cost plus the cost of evaluating additional restriction
4676 * clauses that are to be applied at the join. (This is pessimistic since
4677 * not all of the quals may get evaluated at each tuple.)
4678 */
4679 startup_cost += qp_qual_cost.startup;
4681 run_cost += cpu_per_tuple * hashjointuples;
4682
4683 /* tlist eval costs are paid per output row, not per tuple scanned */
4684 startup_cost += path->jpath.path.pathtarget->cost.startup;
4685 run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
4686
4687 path->jpath.path.startup_cost = startup_cost;
4688 path->jpath.path.total_cost = startup_cost + run_cost;
4689}
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:547
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition costsize.c:5471
Cost disable_cost
Definition costsize.c:142
static Node * get_rightop(const void *clause)
Definition nodeFuncs.h:95
static Node * get_leftop(const void *clause)
Definition nodeFuncs.h:83
size_t get_hash_memory_limit(void)
Definition nodeHash.c:3680
#define RELATION_WAS_MADE_UNIQUE(rel, sjinfo, nominal_jointype)
Definition pathnodes.h:1250
List * estimate_multivariate_bucketsize(PlannerInfo *root, RelOptInfo *inner, List *hashclauses, Selectivity *innerbucketsize)
Definition selfuncs.c:4156
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition selfuncs.c:4424
List * path_hashclauses
Definition pathnodes.h:2490
Cardinality inner_rows_total
Definition pathnodes.h:2492
int num_batches
Definition pathnodes.h:2491
JoinPath jpath
Definition pathnodes.h:2489
Cardinality inner_rows_total
Definition pathnodes.h:3747
SemiAntiJoinFactors semifactors
Definition pathnodes.h:3624
SpecialJoinInfo * sjinfo
Definition pathnodes.h:3623
Path * outerjoinpath
Definition pathnodes.h:2404
Path * innerjoinpath
Definition pathnodes.h:2405
JoinType jointype
Definition pathnodes.h:2399
List * joinrestrictinfo
Definition pathnodes.h:2407

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

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3978 of file costsize.c.

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

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

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3478 of file costsize.c.

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

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

Referenced by create_nestloop_path().

◆ get_parameterized_baserel_size()

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

Definition at line 5546 of file costsize.c.

5548{
5550 double nrows;
5551
5552 /*
5553 * Estimate the number of rows returned by the parameterized scan, knowing
5554 * that it will apply all the extra join clauses as well as the rel's own
5555 * restriction clauses. Note that we force the clauses to be treated as
5556 * non-join clauses during selectivity estimation.
5557 */
5559 nrows = rel->tuples *
5561 allclauses,
5562 rel->relid, /* do not use 0! */
5563 JOIN_INNER,
5564 NULL);
5565 nrows = clamp_row_est(nrows);
5566 /* For safety, make sure result is not more than the base estimate */
5567 if (nrows > rel->rows)
5568 nrows = rel->rows;
5569 return nrows;
5570}
List * baserestrictinfo
Definition pathnodes.h:1142
Index relid
Definition pathnodes.h:1069
Cardinality tuples
Definition pathnodes.h:1096

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

Referenced by get_baserel_parampathinfo().

◆ get_parameterized_joinrel_size()

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

Definition at line 5627 of file costsize.c.

5632{
5633 double nrows;
5634
5635 /*
5636 * Estimate the number of rows returned by the parameterized join as the
5637 * sizes of the input paths times the selectivity of the clauses that have
5638 * ended up at this join node.
5639 *
5640 * As with set_joinrel_size_estimates, the rowcount estimate could depend
5641 * on the pair of input paths provided, though ideally we'd get the same
5642 * estimate for any pair with the same parameterization.
5643 */
5645 rel,
5646 outer_path->parent,
5647 inner_path->parent,
5648 outer_path->rows,
5649 inner_path->rows,
5650 sjinfo,
5652 /* For safety, make sure result is not more than the base estimate */
5653 if (nrows > rel->rows)
5654 nrows = rel->rows;
5655 return nrows;
5656}
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:5668

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

Referenced by get_joinrel_parampathinfo().

◆ index_pages_fetched()

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

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;
912 Assert(T <= total_pages);
913
914 /* b is pro-rated share of effective_cache_size */
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 {
927 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
928 if (pages_fetched >= T)
930 else
932 }
933 else
934 {
935 double lim;
936
937 lim = (2.0 * T * b) / (2.0 * T - b);
938 if (tuples_fetched <= lim)
939 {
941 (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
942 }
943 else
944 {
946 b + (tuples_fetched - lim) * (T - b) / T;
947 }
949 }
950 return pages_fetched;
951}
int effective_cache_size
Definition costsize.c:140
int b
Definition isn.c:74

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

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

◆ initial_cost_hashjoin()

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

Definition at line 4320 of file costsize.c.

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

References cpu_operator_cost, cpu_tuple_cost, JoinCostWorkspace::disabled_nodes, ExecChooseHashTableSize(), fb(), get_parallel_divisor(), JoinCostWorkspace::inner_rows_total, list_length(), JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, page_size(), PGS_CONSIDER_NONPARTIAL, PGS_HASHJOIN, JoinPathExtraData::pgs_mask, JoinCostWorkspace::run_cost, seq_page_cost, JoinCostWorkspace::startup_cost, and JoinCostWorkspace::total_cost.

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

◆ initial_cost_mergejoin()

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

Definition at line 3681 of file costsize.c.

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

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

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

◆ initial_cost_nestloop()

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

Definition at line 3396 of file costsize.c.

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

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

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)
extern

◆ set_cte_size_estimates()

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

Definition at line 6242 of file costsize.c.

6243{
6245
6246 /* Should only be applied to base relations that are CTE references */
6247 Assert(rel->relid > 0);
6248 rte = planner_rt_fetch(rel->relid, root);
6249 Assert(rte->rtekind == RTE_CTE);
6250
6251 if (rte->self_reference)
6252 {
6253 /*
6254 * In a self-reference, we assume the average worktable size is a
6255 * multiple of the nonrecursive term's size. The best multiplier will
6256 * vary depending on query "fan-out", so make its value adjustable.
6257 */
6259 }
6260 else
6261 {
6262 /* Otherwise just believe the CTE's rowcount estimate */
6263 rel->tuples = cte_rows;
6264 }
6265
6266 /* Now estimate number of output rows, etc */
6268}
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition costsize.c:5516
double recursive_worktable_factor
Definition costsize.c:138

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

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

◆ set_foreign_size_estimates()

void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)
extern

Definition at line 6342 of file costsize.c.

6343{
6344 /* Should only be applied to base relations */
6345 Assert(rel->relid > 0);
6346
6347 rel->rows = 1000; /* entirely bogus default estimate */
6348
6350
6351 set_rel_width(root, rel);
6352}

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

Definition at line 6150 of file costsize.c.

6151{
6153 ListCell *lc;
6154
6155 /* Should only be applied to base relations that are functions */
6156 Assert(rel->relid > 0);
6157 rte = planner_rt_fetch(rel->relid, root);
6158 Assert(rte->rtekind == RTE_FUNCTION);
6159
6160 /*
6161 * Estimate number of rows the functions will return. The rowcount of the
6162 * node is that of the largest function result.
6163 */
6164 rel->tuples = 0;
6165 foreach(lc, rte->functions)
6166 {
6168 double ntup = expression_returns_set_rows(root, rtfunc->funcexpr);
6169
6170 if (ntup > rel->tuples)
6171 rel->tuples = ntup;
6172 }
6173
6174 /* Now estimate number of output rows, etc */
6176}
double expression_returns_set_rows(PlannerInfo *root, Node *clause)
Definition clauses.c:318

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

Referenced by set_rel_size().

◆ set_joinrel_size_estimates()

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

Definition at line 5595 of file costsize.c.

5600{
5602 rel,
5603 outer_rel,
5604 inner_rel,
5605 outer_rel->rows,
5606 inner_rel->rows,
5607 sjinfo,
5608 restrictlist);
5609}

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

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

◆ set_namedtuplestore_size_estimates()

void set_namedtuplestore_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)
extern

Definition at line 6280 of file costsize.c.

6281{
6283
6284 /* Should only be applied to base relations that are tuplestore references */
6285 Assert(rel->relid > 0);
6286 rte = planner_rt_fetch(rel->relid, root);
6287 Assert(rte->rtekind == RTE_NAMEDTUPLESTORE);
6288
6289 /*
6290 * Use the estimate provided by the code which is generating the named
6291 * tuplestore. In some cases, the actual number might be available; in
6292 * others the same plan will be re-used, so a "typical" value might be
6293 * estimated and used.
6294 */
6295 rel->tuples = rte->enrtuples;
6296 if (rel->tuples < 0)
6297 rel->tuples = 1000;
6298
6299 /* Now estimate number of output rows, etc */
6301}

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

Referenced by set_namedtuplestore_pathlist().

◆ set_pathtarget_cost_width()

PathTarget * set_pathtarget_cost_width ( PlannerInfo root,
PathTarget target 
)
extern

Definition at line 6534 of file costsize.c.

6535{
6536 int64 tuple_width = 0;
6537 ListCell *lc;
6538
6539 /* Vars are assumed to have cost zero, but other exprs do not */
6540 target->cost.startup = 0;
6541 target->cost.per_tuple = 0;
6542
6543 foreach(lc, target->exprs)
6544 {
6545 Node *node = (Node *) lfirst(lc);
6546
6548
6549 /* For non-Vars, account for evaluation cost */
6550 if (!IsA(node, Var))
6551 {
6552 QualCost cost;
6553
6554 cost_qual_eval_node(&cost, node, root);
6555 target->cost.startup += cost.startup;
6556 target->cost.per_tuple += cost.per_tuple;
6557 }
6558 }
6559
6561
6562 return target;
6563}
int64_t int64
Definition c.h:680
int32 clamp_width_est(int64 tuple_width)
Definition costsize.c:244
static int32 get_expr_width(PlannerInfo *root, const Node *expr)
Definition costsize.c:6572
List * exprs
Definition pathnodes.h:1878
QualCost cost
Definition pathnodes.h:1884

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

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

◆ set_result_size_estimates()

void set_result_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)
extern

Definition at line 6313 of file costsize.c.

6314{
6315 /* Should only be applied to RTE_RESULT base relations */
6316 Assert(rel->relid > 0);
6317 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6318
6319 /* RTE_RESULT always generates a single row, natively */
6320 rel->tuples = 1;
6321
6322 /* Now estimate number of output rows, etc */
6324}

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

Definition at line 6070 of file costsize.c.

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

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

Referenced by build_setop_child_paths(), and set_subquery_pathlist().

◆ set_tablefunc_size_estimates()

void set_tablefunc_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)
extern

Definition at line 6188 of file costsize.c.

6189{
6190 /* Should only be applied to base relations that are functions */
6191 Assert(rel->relid > 0);
6192 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
6193
6194 rel->tuples = 100;
6195
6196 /* Now estimate number of output rows, etc */
6198}

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

Definition at line 6210 of file costsize.c.

6211{
6213
6214 /* Should only be applied to base relations that are values lists */
6215 Assert(rel->relid > 0);
6216 rte = planner_rt_fetch(rel->relid, root);
6217 Assert(rte->rtekind == RTE_VALUES);
6218
6219 /*
6220 * Estimate number of rows the values list will return. We know this
6221 * precisely based on the list length (well, barring set-returning
6222 * functions in list items, but that's a refinement not catered for
6223 * anywhere else either).
6224 */
6225 rel->tuples = list_length(rte->values_lists);
6226
6227 /* Now estimate number of output rows, etc */
6229}

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

Referenced by set_rel_size().

Variable Documentation

◆ constraint_exclusion

PGDLLIMPORT int constraint_exclusion
extern

Definition at line 58 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ disable_cost

PGDLLIMPORT Cost disable_cost
extern

Definition at line 142 of file costsize.c.

Referenced by final_cost_hashjoin().

◆ enable_async_append

PGDLLIMPORT bool enable_async_append
extern

Definition at line 167 of file costsize.c.

Referenced by create_append_plan().

◆ enable_bitmapscan

PGDLLIMPORT bool enable_bitmapscan
extern

Definition at line 149 of file costsize.c.

Referenced by standard_planner().

◆ enable_gathermerge

PGDLLIMPORT bool enable_gathermerge
extern

Definition at line 160 of file costsize.c.

Referenced by standard_planner().

◆ enable_groupagg

PGDLLIMPORT bool enable_groupagg
extern

Definition at line 154 of file costsize.c.

Referenced by cost_agg(), cost_group(), create_setop_path(), and create_unique_path().

◆ enable_hashagg

◆ enable_hashjoin

PGDLLIMPORT bool enable_hashjoin
extern

Definition at line 159 of file costsize.c.

Referenced by standard_planner().

◆ enable_incremental_sort

◆ enable_indexonlyscan

PGDLLIMPORT bool enable_indexonlyscan
extern

Definition at line 148 of file costsize.c.

Referenced by standard_planner().

◆ enable_indexscan

PGDLLIMPORT bool enable_indexscan
extern

Definition at line 147 of file costsize.c.

Referenced by plan_cluster_use_sort(), and standard_planner().

◆ enable_material

PGDLLIMPORT bool enable_material
extern

Definition at line 156 of file costsize.c.

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

◆ enable_memoize

PGDLLIMPORT bool enable_memoize
extern

Definition at line 157 of file costsize.c.

Referenced by standard_planner().

◆ enable_mergejoin

PGDLLIMPORT bool enable_mergejoin
extern

Definition at line 158 of file costsize.c.

Referenced by standard_planner().

◆ enable_nestloop

PGDLLIMPORT bool enable_nestloop
extern

Definition at line 155 of file costsize.c.

Referenced by standard_planner().

◆ enable_parallel_append

PGDLLIMPORT bool enable_parallel_append
extern

Definition at line 163 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 164 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 162 of file costsize.c.

Referenced by create_grouping_paths().

◆ enable_partitionwise_join

PGDLLIMPORT bool enable_partitionwise_join
extern

Definition at line 161 of file costsize.c.

Referenced by set_append_rel_size(), and standard_planner().

◆ enable_presorted_aggregate

PGDLLIMPORT bool enable_presorted_aggregate
extern

Definition at line 166 of file costsize.c.

Referenced by adjust_group_pathkeys_for_groupagg().

◆ enable_seqscan

PGDLLIMPORT bool enable_seqscan
extern

Definition at line 146 of file costsize.c.

Referenced by standard_planner().

◆ enable_sort

PGDLLIMPORT bool enable_sort
extern

Definition at line 151 of file costsize.c.

Referenced by cost_sort(), and make_sort().

◆ enable_tidscan

PGDLLIMPORT bool enable_tidscan
extern

Definition at line 150 of file costsize.c.

Referenced by standard_planner().

◆ max_parallel_workers_per_gather