Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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

Go to the source code of this file.

Macros

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

Enumerations

enum  ConstraintExclusionType { CONSTRAINT_EXCLUSION_OFF , CONSTRAINT_EXCLUSION_ON , CONSTRAINT_EXCLUSION_PARTITION }
 

Functions

double index_pages_fetched (double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
 
void cost_seqscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_samplescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_index (IndexPath *path, PlannerInfo *root, double loop_count, bool partial_path)
 
void cost_bitmap_heap_scan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, Path *bitmapqual, double loop_count)
 
void cost_bitmap_and_node (BitmapAndPath *path, PlannerInfo *root)
 
void cost_bitmap_or_node (BitmapOrPath *path, PlannerInfo *root)
 
void cost_bitmap_tree_node (Path *path, Cost *cost, Selectivity *selec)
 
void cost_tidscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidquals, ParamPathInfo *param_info)
 
void cost_tidrangescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, List *tidrangequals, ParamPathInfo *param_info)
 
void cost_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, bool trivial_pathtarget)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_valuesscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tablefuncscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_ctescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_namedtuplestorescan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_resultscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_recursive_union (Path *runion, Path *nrterm, Path *rterm)
 
void cost_sort (Path *path, PlannerInfo *root, List *pathkeys, 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, 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, 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_nestloop
 
PGDLLIMPORT bool enable_material
 
PGDLLIMPORT bool enable_memoize
 
PGDLLIMPORT bool enable_mergejoin
 
PGDLLIMPORT bool enable_hashjoin
 
PGDLLIMPORT bool enable_gathermerge
 
PGDLLIMPORT bool enable_partitionwise_join
 
PGDLLIMPORT bool enable_partitionwise_aggregate
 
PGDLLIMPORT bool enable_parallel_append
 
PGDLLIMPORT bool enable_parallel_hash
 
PGDLLIMPORT bool enable_partition_pruning
 
PGDLLIMPORT bool enable_presorted_aggregate
 
PGDLLIMPORT bool enable_async_append
 
PGDLLIMPORT int constraint_exclusion
 

Macro Definition Documentation

◆ DEFAULT_CPU_INDEX_TUPLE_COST

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

◆ DEFAULT_CPU_OPERATOR_COST

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

◆ DEFAULT_CPU_TUPLE_COST

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

◆ DEFAULT_EFFECTIVE_CACHE_SIZE

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 34 of file cost.h.

◆ DEFAULT_PARALLEL_SETUP_COST

#define DEFAULT_PARALLEL_SETUP_COST   1000.0

Definition at line 30 of file cost.h.

◆ DEFAULT_PARALLEL_TUPLE_COST

#define DEFAULT_PARALLEL_TUPLE_COST   0.1

Definition at line 29 of file cost.h.

◆ DEFAULT_RANDOM_PAGE_COST

#define DEFAULT_RANDOM_PAGE_COST   4.0

Definition at line 25 of file cost.h.

◆ DEFAULT_RECURSIVE_WORKTABLE_FACTOR

#define DEFAULT_RECURSIVE_WORKTABLE_FACTOR   10.0

Definition at line 33 of file cost.h.

◆ DEFAULT_SEQ_PAGE_COST

#define DEFAULT_SEQ_PAGE_COST   1.0

Definition at line 24 of file cost.h.

Enumeration Type Documentation

◆ ConstraintExclusionType

Enumerator
CONSTRAINT_EXCLUSION_OFF 
CONSTRAINT_EXCLUSION_ON 
CONSTRAINT_EXCLUSION_PARTITION 

Definition at line 36 of file cost.h.

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

Function Documentation

◆ compute_bitmap_pages()

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

Definition at line 6549 of file costsize.c.

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

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

◆ compute_gather_rows()

double compute_gather_rows ( Path path)

Definition at line 6660 of file costsize.c.

6661{
6662 Assert(path->parallel_workers > 0);
6663
6664 return clamp_row_est(path->rows * get_parallel_divisor(path));
6665}
static double get_parallel_divisor(Path *path)
Definition: costsize.c:6509
Assert(PointerIsAligned(start, uint64))
Cardinality rows
Definition: pathnodes.h:1818
int parallel_workers
Definition: pathnodes.h:1815

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

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

◆ compute_semi_anti_join_factors()

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

Definition at line 5149 of file costsize.c.

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

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

Referenced by add_paths_to_joinrel().

◆ cost_agg()

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

Definition at line 2714 of file costsize.c.

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

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

Referenced by create_agg_path(), and create_groupingsets_path().

◆ cost_append()

void cost_append ( AppendPath apath,
PlannerInfo root 
)

Definition at line 2250 of file costsize.c.

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

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

Referenced by create_append_path().

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1165 of file costsize.c.

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

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

Referenced by create_bitmap_and_path().

◆ cost_bitmap_heap_scan()

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

Definition at line 1023 of file costsize.c.

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

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

Referenced by bitmap_scan_cost_est(), and create_bitmap_heap_path().

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1210 of file costsize.c.

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

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

Referenced by create_bitmap_or_path().

◆ cost_bitmap_tree_node()

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

Definition at line 1122 of file costsize.c.

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

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

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

◆ cost_ctescan()

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

Definition at line 1708 of file costsize.c.

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

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

Referenced by create_ctescan_path(), and create_worktablescan_path().

◆ cost_functionscan()

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

Definition at line 1538 of file costsize.c.

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

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

Referenced by create_functionscan_path().

◆ cost_gather()

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

Definition at line 446 of file costsize.c.

449{
450 Cost startup_cost = 0;
451 Cost run_cost = 0;
452
453 /* Mark the path with the correct row estimate */
454 if (rows)
455 path->path.rows = *rows;
456 else if (param_info)
457 path->path.rows = param_info->ppi_rows;
458 else
459 path->path.rows = rel->rows;
460
461 startup_cost = path->subpath->startup_cost;
462
463 run_cost = path->subpath->total_cost - path->subpath->startup_cost;
464
465 /* Parallel setup and communication cost. */
466 startup_cost += parallel_setup_cost;
467 run_cost += parallel_tuple_cost * path->path.rows;
468
470 path->path.startup_cost = startup_cost;
471 path->path.total_cost = (startup_cost + run_cost);
472}
double parallel_setup_cost
Definition: costsize.c:136
double parallel_tuple_cost
Definition: costsize.c:135
Path * subpath
Definition: pathnodes.h:2175

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

Referenced by create_gather_path().

◆ cost_gather_merge()

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

Definition at line 485 of file costsize.c.

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

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

Referenced by create_gather_merge_path().

◆ cost_group()

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

Definition at line 3227 of file costsize.c.

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

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

Referenced by create_group_path().

◆ cost_incremental_sort()

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

Definition at line 2000 of file costsize.c.

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

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

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

◆ cost_index()

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

Definition at line 560 of file costsize.c.

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

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

Referenced by create_index_path(), and reparameterize_path().

◆ cost_material()

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

Definition at line 2509 of file costsize.c.

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

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

Referenced by create_material_path(), and materialize_finished_plan().

◆ cost_merge_append()

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

Definition at line 2458 of file costsize.c.

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

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

Referenced by create_merge_append_path().

◆ cost_namedtuplestorescan()

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

Definition at line 1750 of file costsize.c.

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

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

Referenced by create_namedtuplestorescan_path().

◆ cost_qual_eval()

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

Definition at line 4791 of file costsize.c.

4792{
4793 cost_qual_eval_context context;
4794 ListCell *l;
4795
4796 context.root = root;
4797 context.total.startup = 0;
4798 context.total.per_tuple = 0;
4799
4800 /* We don't charge any cost for the implicit ANDing at top level ... */
4801
4802 foreach(l, quals)
4803 {
4804 Node *qual = (Node *) lfirst(l);
4805
4806 cost_qual_eval_walker(qual, &context);
4807 }
4808
4809 *cost = context.total;
4810}
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:4831
PlannerInfo * root
Definition: costsize.c:169

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

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

◆ cost_qual_eval_node()

◆ cost_recursive_union()

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

Definition at line 1826 of file costsize.c.

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

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

Referenced by create_recursiveunion_path().

◆ cost_resultscan()

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

Definition at line 1788 of file costsize.c.

1790{
1791 Cost startup_cost = 0;
1792 Cost run_cost = 0;
1793 QualCost qpqual_cost;
1794 Cost cpu_per_tuple;
1795
1796 /* Should only be applied to RTE_RESULT base relations */
1797 Assert(baserel->relid > 0);
1798 Assert(baserel->rtekind == RTE_RESULT);
1799
1800 /* Mark the path with the correct row estimate */
1801 if (param_info)
1802 path->rows = param_info->ppi_rows;
1803 else
1804 path->rows = baserel->rows;
1805
1806 /* We charge qual cost plus cpu_tuple_cost */
1807 get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1808
1809 startup_cost += qpqual_cost.startup;
1810 cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1811 run_cost += cpu_per_tuple * baserel->tuples;
1812
1813 path->disabled_nodes = 0;
1814 path->startup_cost = startup_cost;
1815 path->total_cost = startup_cost + run_cost;
1816}
@ RTE_RESULT
Definition: parsenodes.h:1050

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

Referenced by create_resultscan_path().

◆ cost_samplescan()

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

Definition at line 370 of file costsize.c.

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

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

Referenced by create_samplescan_path().

◆ cost_seqscan()

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

Definition at line 295 of file costsize.c.

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

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

Referenced by create_seqscan_path().

◆ cost_sort()

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

Definition at line 2144 of file costsize.c.

2150{
2151 Cost startup_cost;
2152 Cost run_cost;
2153
2154 cost_tuplesort(&startup_cost, &run_cost,
2155 tuples, width,
2156 comparison_cost, sort_mem,
2157 limit_tuples);
2158
2159 startup_cost += input_cost;
2160
2161 path->rows = tuples;
2162 path->disabled_nodes = input_disabled_nodes + (enable_sort ? 0 : 1);
2163 path->startup_cost = startup_cost;
2164 path->total_cost = startup_cost + run_cost;
2165}
bool enable_sort
Definition: costsize.c:150

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

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

◆ cost_subplan()

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

Definition at line 4569 of file costsize.c.

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

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

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

◆ cost_subqueryscan()

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

Definition at line 1457 of file costsize.c.

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

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

Referenced by create_subqueryscan_path().

◆ cost_tablefuncscan()

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

Definition at line 1600 of file costsize.c.

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

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

Referenced by create_tablefuncscan_path().

◆ cost_tidrangescan()

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

Definition at line 1363 of file costsize.c.

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

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

Referenced by create_tidrangescan_path().

◆ cost_tidscan()

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

Definition at line 1258 of file costsize.c.

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

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

Referenced by create_tidscan_path().

◆ cost_valuesscan()

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

Definition at line 1657 of file costsize.c.

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

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

Referenced by create_valuesscan_path().

◆ cost_windowagg()

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

Definition at line 3130 of file costsize.c.

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

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

Referenced by create_windowagg_path().

◆ final_cost_hashjoin()

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

Definition at line 4309 of file costsize.c.

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

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

Referenced by create_hashjoin_path().

◆ final_cost_mergejoin()

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

Definition at line 3869 of file costsize.c.

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

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

Referenced by create_mergejoin_path().

◆ final_cost_nestloop()

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

Definition at line 3381 of file costsize.c.

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

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

Referenced by create_nestloop_path().

◆ get_parameterized_baserel_size()

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

Definition at line 5414 of file costsize.c.

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

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

Referenced by get_baserel_parampathinfo().

◆ get_parameterized_joinrel_size()

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

Definition at line 5495 of file costsize.c.

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

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

Referenced by get_joinrel_parampathinfo().

◆ index_pages_fetched()

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

Definition at line 908 of file costsize.c.

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

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

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

◆ initial_cost_hashjoin()

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

Definition at line 4194 of file costsize.c.

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

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

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

◆ initial_cost_mergejoin()

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

Definition at line 3584 of file costsize.c.

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

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

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

◆ initial_cost_nestloop()

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

Definition at line 3299 of file costsize.c.

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

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

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

◆ set_baserel_size_estimates()

void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

◆ set_cte_size_estimates()

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

Definition at line 6110 of file costsize.c.

6111{
6112 RangeTblEntry *rte;
6113
6114 /* Should only be applied to base relations that are CTE references */
6115 Assert(rel->relid > 0);
6116 rte = planner_rt_fetch(rel->relid, root);
6117 Assert(rte->rtekind == RTE_CTE);
6118
6119 if (rte->self_reference)
6120 {
6121 /*
6122 * In a self-reference, we assume the average worktable size is a
6123 * multiple of the nonrecursive term's size. The best multiplier will
6124 * vary depending on query "fan-out", so make its value adjustable.
6125 */
6127 }
6128 else
6129 {
6130 /* Otherwise just believe the CTE's rowcount estimate */
6131 rel->tuples = cte_rows;
6132 }
6133
6134 /* Now estimate number of output rows, etc */
6136}
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:5384
double recursive_worktable_factor
Definition: costsize.c:137

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

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

◆ set_foreign_size_estimates()

void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6210 of file costsize.c.

6211{
6212 /* Should only be applied to base relations */
6213 Assert(rel->relid > 0);
6214
6215 rel->rows = 1000; /* entirely bogus default estimate */
6216
6218
6219 set_rel_width(root, rel);
6220}

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

Referenced by set_foreign_size().

◆ set_function_size_estimates()

void set_function_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6018 of file costsize.c.

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

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

Referenced by set_rel_size().

◆ set_joinrel_size_estimates()

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

Definition at line 5463 of file costsize.c.

5468{
5470 rel,
5471 outer_rel,
5472 inner_rel,
5473 outer_rel->rows,
5474 inner_rel->rows,
5475 sjinfo,
5476 restrictlist);
5477}

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

Referenced by build_child_join_rel(), and build_join_rel().

◆ set_namedtuplestore_size_estimates()

void set_namedtuplestore_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6148 of file costsize.c.

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

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

Referenced by set_namedtuplestore_pathlist().

◆ set_pathtarget_cost_width()

PathTarget * set_pathtarget_cost_width ( PlannerInfo root,
PathTarget target 
)

Definition at line 6402 of file costsize.c.

6403{
6404 int64 tuple_width = 0;
6405 ListCell *lc;
6406
6407 /* Vars are assumed to have cost zero, but other exprs do not */
6408 target->cost.startup = 0;
6409 target->cost.per_tuple = 0;
6410
6411 foreach(lc, target->exprs)
6412 {
6413 Node *node = (Node *) lfirst(lc);
6414
6415 tuple_width += get_expr_width(root, node);
6416
6417 /* For non-Vars, account for evaluation cost */
6418 if (!IsA(node, Var))
6419 {
6420 QualCost cost;
6421
6422 cost_qual_eval_node(&cost, node, root);
6423 target->cost.startup += cost.startup;
6424 target->cost.per_tuple += cost.per_tuple;
6425 }
6426 }
6427
6428 target->width = clamp_width_est(tuple_width);
6429
6430 return target;
6431}
int64_t int64
Definition: c.h:536
int32 clamp_width_est(int64 tuple_width)
Definition: costsize.c:242
static int32 get_expr_width(PlannerInfo *root, const Node *expr)
Definition: costsize.c:6440
List * exprs
Definition: pathnodes.h:1691
QualCost cost
Definition: pathnodes.h:1697
Definition: primnodes.h:262

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

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

◆ set_result_size_estimates()

void set_result_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6181 of file costsize.c.

6182{
6183 /* Should only be applied to RTE_RESULT base relations */
6184 Assert(rel->relid > 0);
6185 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_RESULT);
6186
6187 /* RTE_RESULT always generates a single row, natively */
6188 rel->tuples = 1;
6189
6190 /* Now estimate number of output rows, etc */
6192}

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

Referenced by set_result_pathlist().

◆ set_subquery_size_estimates()

void set_subquery_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 5938 of file costsize.c.

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

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

Referenced by build_setop_child_paths(), and set_subquery_pathlist().

◆ set_tablefunc_size_estimates()

void set_tablefunc_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6056 of file costsize.c.

6057{
6058 /* Should only be applied to base relations that are functions */
6059 Assert(rel->relid > 0);
6060 Assert(planner_rt_fetch(rel->relid, root)->rtekind == RTE_TABLEFUNC);
6061
6062 rel->tuples = 100;
6063
6064 /* Now estimate number of output rows, etc */
6066}

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

Referenced by set_rel_size().

◆ set_values_size_estimates()

void set_values_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 6078 of file costsize.c.

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

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

Referenced by set_rel_size().

Variable Documentation

◆ constraint_exclusion

PGDLLIMPORT int constraint_exclusion
extern

Definition at line 58 of file plancat.c.

Referenced by relation_excluded_by_constraints().

◆ disable_cost

PGDLLIMPORT Cost disable_cost
extern

Definition at line 141 of file costsize.c.

Referenced by final_cost_hashjoin().

◆ enable_async_append

PGDLLIMPORT bool enable_async_append
extern

Definition at line 165 of file costsize.c.

Referenced by create_append_plan().

◆ enable_bitmapscan

PGDLLIMPORT bool enable_bitmapscan
extern

Definition at line 148 of file costsize.c.

Referenced by cost_bitmap_heap_scan().

◆ enable_gathermerge

PGDLLIMPORT bool enable_gathermerge
extern

Definition at line 158 of file costsize.c.

Referenced by cost_gather_merge().

◆ enable_hashagg

◆ enable_hashjoin

PGDLLIMPORT bool enable_hashjoin
extern

Definition at line 157 of file costsize.c.

Referenced by add_paths_to_joinrel(), and initial_cost_hashjoin().

◆ enable_incremental_sort

◆ enable_indexonlyscan

PGDLLIMPORT bool enable_indexonlyscan
extern

Definition at line 147 of file costsize.c.

Referenced by check_index_only().

◆ enable_indexscan

PGDLLIMPORT bool enable_indexscan
extern

Definition at line 146 of file costsize.c.

Referenced by cost_index(), and plan_cluster_use_sort().

◆ enable_material

PGDLLIMPORT bool enable_material
extern

◆ enable_memoize

PGDLLIMPORT bool enable_memoize
extern

Definition at line 155 of file costsize.c.

Referenced by create_memoize_path(), and get_memoize_path().

◆ enable_mergejoin

PGDLLIMPORT bool enable_mergejoin
extern

Definition at line 156 of file costsize.c.

Referenced by add_paths_to_joinrel(), and initial_cost_mergejoin().

◆ enable_nestloop

PGDLLIMPORT bool enable_nestloop
extern

Definition at line 153 of file costsize.c.

Referenced by initial_cost_nestloop().

◆ enable_parallel_append

PGDLLIMPORT bool enable_parallel_append
extern

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

Referenced by create_grouping_paths().

◆ enable_partitionwise_join

PGDLLIMPORT bool enable_partitionwise_join
extern

Definition at line 159 of file costsize.c.

Referenced by build_joinrel_partition_info(), and set_append_rel_size().

◆ enable_presorted_aggregate

PGDLLIMPORT bool enable_presorted_aggregate
extern

Definition at line 164 of file costsize.c.

Referenced by adjust_group_pathkeys_for_groupagg().

◆ enable_seqscan

PGDLLIMPORT bool enable_seqscan
extern

Definition at line 145 of file costsize.c.

Referenced by cost_seqscan().

◆ enable_sort

PGDLLIMPORT bool enable_sort
extern

Definition at line 150 of file costsize.c.

Referenced by cost_sort(), and make_sort().

◆ enable_tidscan

PGDLLIMPORT bool enable_tidscan
extern

Definition at line 149 of file costsize.c.

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

◆ max_parallel_workers_per_gather