PostgreSQL Source Code  git master
cost.h File Reference
#include "nodes/plannodes.h"
#include "nodes/relation.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_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */
 

Enumerations

enum  ConstraintExclusionType { CONSTRAINT_EXCLUSION_OFF, CONSTRAINT_EXCLUSION_ON, CONSTRAINT_EXCLUSION_PARTITION }
 

Functions

double clamp_row_est (double nrows)
 
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_subqueryscan (SubqueryScanPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_functionscan (Path *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info)
 
void cost_tableexprscan (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_recursive_union (Path *runion, Path *nrterm, Path *rterm)
 
void cost_sort (Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
 
void cost_append (AppendPath *path)
 
void cost_merge_append (Path *path, PlannerInfo *root, List *pathkeys, int n_streams, Cost input_startup_cost, Cost input_total_cost, double tuples)
 
void cost_material (Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
 
void cost_agg (Path *path, PlannerInfo *root, AggStrategy aggstrategy, const AggClauseCosts *aggcosts, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_windowagg (Path *path, PlannerInfo *root, List *windowFuncs, int numPartCols, int numOrderCols, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void cost_group (Path *path, PlannerInfo *root, int numGroupCols, double numGroups, List *quals, Cost input_startup_cost, Cost input_total_cost, double input_tuples)
 
void initial_cost_nestloop (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, Path *outer_path, Path *inner_path, JoinPathExtraData *extra)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, JoinPathExtraData *extra)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, JoinPathExtraData *extra, bool parallel_hash)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, JoinPathExtraData *extra)
 
void cost_gather (GatherPath *path, PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, 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 *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_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, int loop_count, Cost *cost, double *tuple)
 
Selectivity clauselist_selectivity (PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity clause_selectivity (PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
void cost_gather_merge (GatherMergePath *path, PlannerInfo *root, RelOptInfo *rel, ParamPathInfo *param_info, Cost input_startup_cost, Cost input_total_cost, double *rows)
 

Variables

PGDLLIMPORT double seq_page_cost
 
PGDLLIMPORT double random_page_cost
 
PGDLLIMPORT double cpu_tuple_cost
 
PGDLLIMPORT double cpu_index_tuple_cost
 
PGDLLIMPORT double cpu_operator_cost
 
PGDLLIMPORT double parallel_tuple_cost
 
PGDLLIMPORT double parallel_setup_cost
 
PGDLLIMPORT int effective_cache_size
 
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_hashagg
 
PGDLLIMPORT bool enable_nestloop
 
PGDLLIMPORT bool enable_material
 
PGDLLIMPORT bool enable_mergejoin
 
PGDLLIMPORT bool enable_hashjoin
 
PGDLLIMPORT bool enable_gathermerge
 
PGDLLIMPORT bool enable_partitionwise_join
 
PGDLLIMPORT bool enable_parallel_append
 
PGDLLIMPORT bool enable_parallel_hash
 
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 32 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_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 34 of file cost.h.

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

Function Documentation

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 185 of file costsize.c.

References rint().

Referenced by approx_tuple_count(), bernoulli_samplescangetsamplesize(), calc_joinrel_size_estimate(), compute_bitmap_pages(), cost_agg(), cost_append(), cost_bitmap_heap_scan(), cost_group(), cost_index(), cost_seqscan(), cost_subplan(), create_bitmap_subplan(), create_limit_path(), estimate_hash_bucket_stats(), estimate_num_groups(), estimate_path_cost_size(), estimate_size(), expression_returns_set_rows(), final_cost_hashjoin(), final_cost_mergejoin(), final_cost_nestloop(), get_parameterized_baserel_size(), get_variable_numdistinct(), initial_cost_mergejoin(), set_baserel_size_estimates(), set_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

186 {
187  /*
188  * Force estimate to be at least one row, to make explain output look
189  * better and to avoid possible divide-by-zero when interpolating costs.
190  * Make it an integer, too.
191  */
192  if (nrows <= 1.0)
193  nrows = 1.0;
194  else
195  nrows = rint(nrows);
196 
197  return nrows;
198 }
double rint(double x)
Definition: rint.c:22

◆ clause_selectivity()

Selectivity clause_selectivity ( PlannerInfo root,
Node clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 574 of file clausesel.c.

References and_clause(), arg, generate_unaccent_rules::args, OpExpr::args, bms_is_subset_singleton(), booltestsel(), boolvarsel(), RestrictInfo::clause, RestrictInfo::clause_relids, clause_selectivity(), clauselist_selectivity(), Const::constisnull, Const::constvalue, CurrentOfExpr::cvarno, DatumGetBool, DEBUG4, elog, estimate_expression_value(), find_base_rel(), get_notclausearg(), OpExpr::inputcollid, is_opclause, IsA, JOIN_INNER, join_selectivity(), lfirst, RestrictInfo::norm_selec, not_clause(), nulltestsel(), OpExpr::opno, or_clause(), RestrictInfo::orclause, RestrictInfo::outer_selec, RestrictInfo::pseudoconstant, restriction_selectivity(), rowcomparesel(), s1, s2, scalararraysel(), treat_as_join_clause(), RelOptInfo::tuples, RangeQueryClause::var, Var::varlevelsup, and Var::varno.

Referenced by approx_tuple_count(), booltestsel(), clause_selectivity(), clauselist_selectivity(), consider_new_or_clause(), and dependencies_clauselist_selectivity().

579 {
580  Selectivity s1 = 0.5; /* default for any unhandled clause type */
581  RestrictInfo *rinfo = NULL;
582  bool cacheable = false;
583 
584  if (clause == NULL) /* can this still happen? */
585  return s1;
586 
587  if (IsA(clause, RestrictInfo))
588  {
589  rinfo = (RestrictInfo *) clause;
590 
591  /*
592  * If the clause is marked pseudoconstant, then it will be used as a
593  * gating qual and should not affect selectivity estimates; hence
594  * return 1.0. The only exception is that a constant FALSE may be
595  * taken as having selectivity 0.0, since it will surely mean no rows
596  * out of the plan. This case is simple enough that we need not
597  * bother caching the result.
598  */
599  if (rinfo->pseudoconstant)
600  {
601  if (!IsA(rinfo->clause, Const))
602  return (Selectivity) 1.0;
603  }
604 
605  /*
606  * If the clause is marked redundant, always return 1.0.
607  */
608  if (rinfo->norm_selec > 1)
609  return (Selectivity) 1.0;
610 
611  /*
612  * If possible, cache the result of the selectivity calculation for
613  * the clause. We can cache if varRelid is zero or the clause
614  * contains only vars of that relid --- otherwise varRelid will affect
615  * the result, so mustn't cache. Outer join quals might be examined
616  * with either their join's actual jointype or JOIN_INNER, so we need
617  * two cache variables to remember both cases. Note: we assume the
618  * result won't change if we are switching the input relations or
619  * considering a unique-ified case, so we only need one cache variable
620  * for all non-JOIN_INNER cases.
621  */
622  if (varRelid == 0 ||
623  bms_is_subset_singleton(rinfo->clause_relids, varRelid))
624  {
625  /* Cacheable --- do we already have the result? */
626  if (jointype == JOIN_INNER)
627  {
628  if (rinfo->norm_selec >= 0)
629  return rinfo->norm_selec;
630  }
631  else
632  {
633  if (rinfo->outer_selec >= 0)
634  return rinfo->outer_selec;
635  }
636  cacheable = true;
637  }
638 
639  /*
640  * Proceed with examination of contained clause. If the clause is an
641  * OR-clause, we want to look at the variant with sub-RestrictInfos,
642  * so that per-subclause selectivities can be cached.
643  */
644  if (rinfo->orclause)
645  clause = (Node *) rinfo->orclause;
646  else
647  clause = (Node *) rinfo->clause;
648  }
649 
650  if (IsA(clause, Var))
651  {
652  Var *var = (Var *) clause;
653 
654  /*
655  * We probably shouldn't ever see an uplevel Var here, but if we do,
656  * return the default selectivity...
657  */
658  if (var->varlevelsup == 0 &&
659  (varRelid == 0 || varRelid == (int) var->varno))
660  {
661  /* Use the restriction selectivity function for a bool Var */
662  s1 = boolvarsel(root, (Node *) var, varRelid);
663  }
664  }
665  else if (IsA(clause, Const))
666  {
667  /* bool constant is pretty easy... */
668  Const *con = (Const *) clause;
669 
670  s1 = con->constisnull ? 0.0 :
671  DatumGetBool(con->constvalue) ? 1.0 : 0.0;
672  }
673  else if (IsA(clause, Param))
674  {
675  /* see if we can replace the Param */
676  Node *subst = estimate_expression_value(root, clause);
677 
678  if (IsA(subst, Const))
679  {
680  /* bool constant is pretty easy... */
681  Const *con = (Const *) subst;
682 
683  s1 = con->constisnull ? 0.0 :
684  DatumGetBool(con->constvalue) ? 1.0 : 0.0;
685  }
686  else
687  {
688  /* XXX any way to do better than default? */
689  }
690  }
691  else if (not_clause(clause))
692  {
693  /* inverse of the selectivity of the underlying clause */
694  s1 = 1.0 - clause_selectivity(root,
695  (Node *) get_notclausearg((Expr *) clause),
696  varRelid,
697  jointype,
698  sjinfo);
699  }
700  else if (and_clause(clause))
701  {
702  /* share code with clauselist_selectivity() */
703  s1 = clauselist_selectivity(root,
704  ((BoolExpr *) clause)->args,
705  varRelid,
706  jointype,
707  sjinfo);
708  }
709  else if (or_clause(clause))
710  {
711  /*
712  * Selectivities for an OR clause are computed as s1+s2 - s1*s2 to
713  * account for the probable overlap of selected tuple sets.
714  *
715  * XXX is this too conservative?
716  */
717  ListCell *arg;
718 
719  s1 = 0.0;
720  foreach(arg, ((BoolExpr *) clause)->args)
721  {
723  (Node *) lfirst(arg),
724  varRelid,
725  jointype,
726  sjinfo);
727 
728  s1 = s1 + s2 - s1 * s2;
729  }
730  }
731  else if (is_opclause(clause) || IsA(clause, DistinctExpr))
732  {
733  OpExpr *opclause = (OpExpr *) clause;
734  Oid opno = opclause->opno;
735 
736  if (treat_as_join_clause(clause, rinfo, varRelid, sjinfo))
737  {
738  /* Estimate selectivity for a join clause. */
739  s1 = join_selectivity(root, opno,
740  opclause->args,
741  opclause->inputcollid,
742  jointype,
743  sjinfo);
744  }
745  else
746  {
747  /* Estimate selectivity for a restriction clause. */
748  s1 = restriction_selectivity(root, opno,
749  opclause->args,
750  opclause->inputcollid,
751  varRelid);
752  }
753 
754  /*
755  * DistinctExpr has the same representation as OpExpr, but the
756  * contained operator is "=" not "<>", so we must negate the result.
757  * This estimation method doesn't give the right behavior for nulls,
758  * but it's better than doing nothing.
759  */
760  if (IsA(clause, DistinctExpr))
761  s1 = 1.0 - s1;
762  }
763  else if (IsA(clause, ScalarArrayOpExpr))
764  {
765  /* Use node specific selectivity calculation function */
766  s1 = scalararraysel(root,
767  (ScalarArrayOpExpr *) clause,
768  treat_as_join_clause(clause, rinfo,
769  varRelid, sjinfo),
770  varRelid,
771  jointype,
772  sjinfo);
773  }
774  else if (IsA(clause, RowCompareExpr))
775  {
776  /* Use node specific selectivity calculation function */
777  s1 = rowcomparesel(root,
778  (RowCompareExpr *) clause,
779  varRelid,
780  jointype,
781  sjinfo);
782  }
783  else if (IsA(clause, NullTest))
784  {
785  /* Use node specific selectivity calculation function */
786  s1 = nulltestsel(root,
787  ((NullTest *) clause)->nulltesttype,
788  (Node *) ((NullTest *) clause)->arg,
789  varRelid,
790  jointype,
791  sjinfo);
792  }
793  else if (IsA(clause, BooleanTest))
794  {
795  /* Use node specific selectivity calculation function */
796  s1 = booltestsel(root,
797  ((BooleanTest *) clause)->booltesttype,
798  (Node *) ((BooleanTest *) clause)->arg,
799  varRelid,
800  jointype,
801  sjinfo);
802  }
803  else if (IsA(clause, CurrentOfExpr))
804  {
805  /* CURRENT OF selects at most one row of its table */
806  CurrentOfExpr *cexpr = (CurrentOfExpr *) clause;
807  RelOptInfo *crel = find_base_rel(root, cexpr->cvarno);
808 
809  if (crel->tuples > 0)
810  s1 = 1.0 / crel->tuples;
811  }
812  else if (IsA(clause, RelabelType))
813  {
814  /* Not sure this case is needed, but it can't hurt */
815  s1 = clause_selectivity(root,
816  (Node *) ((RelabelType *) clause)->arg,
817  varRelid,
818  jointype,
819  sjinfo);
820  }
821  else if (IsA(clause, CoerceToDomain))
822  {
823  /* Not sure this case is needed, but it can't hurt */
824  s1 = clause_selectivity(root,
825  (Node *) ((CoerceToDomain *) clause)->arg,
826  varRelid,
827  jointype,
828  sjinfo);
829  }
830  else
831  {
832  /*
833  * For anything else, see if we can consider it as a boolean variable.
834  * This only works if it's an immutable expression in Vars of a single
835  * relation; but there's no point in us checking that here because
836  * boolvarsel() will do it internally, and return a suitable default
837  * selectivity if not.
838  */
839  s1 = boolvarsel(root, clause, varRelid);
840  }
841 
842  /* Cache the result if possible */
843  if (cacheable)
844  {
845  if (jointype == JOIN_INNER)
846  rinfo->norm_selec = s1;
847  else
848  rinfo->outer_selec = s1;
849  }
850 
851 #ifdef SELECTIVITY_DEBUG
852  elog(DEBUG4, "clause_selectivity: s1 %f", s1);
853 #endif /* SELECTIVITY_DEBUG */
854 
855  return s1;
856 }
Datum constvalue
Definition: primnodes.h:196
Expr * get_notclausearg(Expr *notclause)
Definition: clauses.c:268
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
Index varlevelsup
Definition: primnodes.h:173
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2495
Expr * orclause
Definition: relation.h:1878
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1685
double tuples
Definition: relation.h:625
Selectivity rowcomparesel(PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:2205
Relids clause_relids
Definition: relation.h:1862
bool pseudoconstant
Definition: relation.h:1855
Definition: nodes.h:513
double Selectivity
Definition: nodes.h:643
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
#define DEBUG4
Definition: elog.h:22
Selectivity scalararraysel(PlannerInfo *root, ScalarArrayOpExpr *clause, bool is_join_clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1848
Selectivity norm_selec
Definition: relation.h:1885
static bool treat_as_join_clause(Node *clause, RestrictInfo *rinfo, int varRelid, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:496
static bool bms_is_subset_singleton(const Bitmapset *s, int x)
Definition: clausesel.c:475
char * s1
#define is_opclause(clause)
Definition: clauses.h:20
Selectivity nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1739
bool and_clause(Node *clause)
Definition: clauses.c:317
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:574
#define DatumGetBool(X)
Definition: postgres.h:376
Selectivity outer_selec
Definition: relation.h:1888
bool not_clause(Node *clause)
Definition: clauses.c:239
Expr * clause
Definition: relation.h:1847
Index varno
Definition: primnodes.h:166
char * s2
bool or_clause(Node *clause)
Definition: clauses.c:283
#define lfirst(lc)
Definition: pg_list.h:106
Oid inputcollid
Definition: primnodes.h:501
void * arg
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1722
Oid opno
Definition: primnodes.h:496
#define elog
Definition: elog.h:219
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:277
List * args
Definition: primnodes.h:502
Selectivity booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1581
Selectivity boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
Definition: selfuncs.c:1542
bool constisnull
Definition: primnodes.h:197

◆ clauselist_selectivity()

Selectivity clauselist_selectivity ( PlannerInfo root,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 99 of file clausesel.c.

References addRangeClause(), generate_unaccent_rules::args, OpExpr::args, bms_is_member(), bms_membership(), BMS_SINGLETON, RestrictInfo::clause, RestrictInfo::clause_relids, clause_selectivity(), DEFAULT_INEQ_SEL, DEFAULT_RANGE_INEQ_SEL, dependencies_clauselist_selectivity(), find_single_rel_for_clauses(), get_oprrest(), RangeQueryClause::have_hibound, RangeQueryClause::have_lobound, RangeQueryClause::hibound, IS_NULL, is_opclause, is_pseudo_constant_clause(), is_pseudo_constant_clause_relids(), IsA, RestrictInfo::left_relids, lfirst, linitial, list_length(), RangeQueryClause::lobound, lsecond, RangeQueryClause::next, NIL, nulltestsel(), NumRelids(), OpExpr::opno, pfree(), RestrictInfo::pseudoconstant, RestrictInfo::right_relids, RTE_RELATION, RelOptInfo::rtekind, s1, s2, RelOptInfo::statlist, and RangeQueryClause::var.

Referenced by brincostestimate(), btcostestimate(), calc_joinrel_size_estimate(), clause_selectivity(), compute_semi_anti_join_factors(), cost_agg(), cost_group(), estimate_path_cost_size(), estimate_size(), genericcostestimate(), get_parameterized_baserel_size(), gincostestimate(), postgresGetForeignJoinPaths(), postgresGetForeignRelSize(), and set_baserel_size_estimates().

104 {
105  Selectivity s1 = 1.0;
106  RelOptInfo *rel;
107  Bitmapset *estimatedclauses = NULL;
108  RangeQueryClause *rqlist = NULL;
109  ListCell *l;
110  int listidx;
111 
112  /*
113  * If there's exactly one clause, just go directly to
114  * clause_selectivity(). None of what we might do below is relevant.
115  */
116  if (list_length(clauses) == 1)
117  return clause_selectivity(root, (Node *) linitial(clauses),
118  varRelid, jointype, sjinfo);
119 
120  /*
121  * Determine if these clauses reference a single relation. If so, and if
122  * it has extended statistics, try to apply those.
123  */
124  rel = find_single_rel_for_clauses(root, clauses);
125  if (rel && rel->rtekind == RTE_RELATION && rel->statlist != NIL)
126  {
127  /*
128  * Perform selectivity estimations on any clauses found applicable by
129  * dependencies_clauselist_selectivity. 'estimatedclauses' will be
130  * filled with the 0-based list positions of clauses used that way, so
131  * that we can ignore them below.
132  */
133  s1 *= dependencies_clauselist_selectivity(root, clauses, varRelid,
134  jointype, sjinfo, rel,
135  &estimatedclauses);
136 
137  /*
138  * This would be the place to apply any other types of extended
139  * statistics selectivity estimations for remaining clauses.
140  */
141  }
142 
143  /*
144  * Apply normal selectivity estimates for remaining clauses. We'll be
145  * careful to skip any clauses which were already estimated above.
146  *
147  * Anything that doesn't look like a potential rangequery clause gets
148  * multiplied into s1 and forgotten. Anything that does gets inserted into
149  * an rqlist entry.
150  */
151  listidx = -1;
152  foreach(l, clauses)
153  {
154  Node *clause = (Node *) lfirst(l);
155  RestrictInfo *rinfo;
156  Selectivity s2;
157 
158  listidx++;
159 
160  /*
161  * Skip this clause if it's already been estimated by some other
162  * statistics above.
163  */
164  if (bms_is_member(listidx, estimatedclauses))
165  continue;
166 
167  /* Always compute the selectivity using clause_selectivity */
168  s2 = clause_selectivity(root, clause, varRelid, jointype, sjinfo);
169 
170  /*
171  * Check for being passed a RestrictInfo.
172  *
173  * If it's a pseudoconstant RestrictInfo, then s2 is either 1.0 or
174  * 0.0; just use that rather than looking for range pairs.
175  */
176  if (IsA(clause, RestrictInfo))
177  {
178  rinfo = (RestrictInfo *) clause;
179  if (rinfo->pseudoconstant)
180  {
181  s1 = s1 * s2;
182  continue;
183  }
184  clause = (Node *) rinfo->clause;
185  }
186  else
187  rinfo = NULL;
188 
189  /*
190  * See if it looks like a restriction clause with a pseudoconstant on
191  * one side. (Anything more complicated than that might not behave in
192  * the simple way we are expecting.) Most of the tests here can be
193  * done more efficiently with rinfo than without.
194  */
195  if (is_opclause(clause) && list_length(((OpExpr *) clause)->args) == 2)
196  {
197  OpExpr *expr = (OpExpr *) clause;
198  bool varonleft = true;
199  bool ok;
200 
201  if (rinfo)
202  {
203  ok = (bms_membership(rinfo->clause_relids) == BMS_SINGLETON) &&
205  rinfo->right_relids) ||
206  (varonleft = false,
208  rinfo->left_relids)));
209  }
210  else
211  {
212  ok = (NumRelids(clause) == 1) &&
214  (varonleft = false,
216  }
217 
218  if (ok)
219  {
220  /*
221  * If it's not a "<"/"<="/">"/">=" operator, just merge the
222  * selectivity in generically. But if it's the right oprrest,
223  * add the clause to rqlist for later processing.
224  */
225  switch (get_oprrest(expr->opno))
226  {
227  case F_SCALARLTSEL:
228  case F_SCALARLESEL:
229  addRangeClause(&rqlist, clause,
230  varonleft, true, s2);
231  break;
232  case F_SCALARGTSEL:
233  case F_SCALARGESEL:
234  addRangeClause(&rqlist, clause,
235  varonleft, false, s2);
236  break;
237  default:
238  /* Just merge the selectivity in generically */
239  s1 = s1 * s2;
240  break;
241  }
242  continue; /* drop to loop bottom */
243  }
244  }
245 
246  /* Not the right form, so treat it generically. */
247  s1 = s1 * s2;
248  }
249 
250  /*
251  * Now scan the rangequery pair list.
252  */
253  while (rqlist != NULL)
254  {
255  RangeQueryClause *rqnext;
256 
257  if (rqlist->have_lobound && rqlist->have_hibound)
258  {
259  /* Successfully matched a pair of range clauses */
260  Selectivity s2;
261 
262  /*
263  * Exact equality to the default value probably means the
264  * selectivity function punted. This is not airtight but should
265  * be good enough.
266  */
267  if (rqlist->hibound == DEFAULT_INEQ_SEL ||
268  rqlist->lobound == DEFAULT_INEQ_SEL)
269  {
271  }
272  else
273  {
274  s2 = rqlist->hibound + rqlist->lobound - 1.0;
275 
276  /* Adjust for double-exclusion of NULLs */
277  s2 += nulltestsel(root, IS_NULL, rqlist->var,
278  varRelid, jointype, sjinfo);
279 
280  /*
281  * A zero or slightly negative s2 should be converted into a
282  * small positive value; we probably are dealing with a very
283  * tight range and got a bogus result due to roundoff errors.
284  * However, if s2 is very negative, then we probably have
285  * default selectivity estimates on one or both sides of the
286  * range that we failed to recognize above for some reason.
287  */
288  if (s2 <= 0.0)
289  {
290  if (s2 < -0.01)
291  {
292  /*
293  * No data available --- use a default estimate that
294  * is small, but not real small.
295  */
297  }
298  else
299  {
300  /*
301  * It's just roundoff error; use a small positive
302  * value
303  */
304  s2 = 1.0e-10;
305  }
306  }
307  }
308  /* Merge in the selectivity of the pair of clauses */
309  s1 *= s2;
310  }
311  else
312  {
313  /* Only found one of a pair, merge it in generically */
314  if (rqlist->have_lobound)
315  s1 *= rqlist->lobound;
316  else
317  s1 *= rqlist->hibound;
318  }
319  /* release storage and advance */
320  rqnext = rqlist->next;
321  pfree(rqlist);
322  rqlist = rqnext;
323  }
324 
325  return s1;
326 }
#define NIL
Definition: pg_list.h:69
Selectivity dependencies_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses)
Definition: dependencies.c:932
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
List * statlist
Definition: relation.h:623
bool is_pseudo_constant_clause_relids(Node *clause, Relids relids)
Definition: clauses.c:2253
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Relids clause_relids
Definition: relation.h:1862
bool pseudoconstant
Definition: relation.h:1855
Definition: nodes.h:513
Relids left_relids
Definition: relation.h:1874
double Selectivity
Definition: nodes.h:643
#define lsecond(l)
Definition: pg_list.h:116
void pfree(void *pointer)
Definition: mcxt.c:936
#define linitial(l)
Definition: pg_list.h:111
char * s1
#define is_opclause(clause)
Definition: clauses.h:20
Selectivity nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1739
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:574
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:2233
struct RangeQueryClause * next
Definition: clausesel.c:34
static void addRangeClause(RangeQueryClause **rqlist, Node *clause, bool varonleft, bool isLTsel, Selectivity s2)
Definition: clausesel.c:334
Selectivity hibound
Definition: clausesel.c:39
Expr * clause
Definition: relation.h:1847
Selectivity lobound
Definition: clausesel.c:38
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1346
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:678
char * s2
RTEKind rtekind
Definition: relation.h:615
static RelOptInfo * find_single_rel_for_clauses(PlannerInfo *root, List *clauses)
Definition: clausesel.c:430
Relids right_relids
Definition: relation.h:1875
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
#define DEFAULT_RANGE_INEQ_SEL
Definition: selfuncs.h:40
Oid opno
Definition: primnodes.h:496
List * args
Definition: primnodes.h:502
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464
int NumRelids(Node *clause)
Definition: clauses.c:2275

◆ compute_bitmap_pages()

double compute_bitmap_pages ( PlannerInfo root,
RelOptInfo baserel,
Path bitmapqual,
int  loop_count,
Cost cost,
double *  tuple 
)

Definition at line 5373 of file costsize.c.

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

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

5375 {
5376  Cost indexTotalCost;
5377  Selectivity indexSelectivity;
5378  double T;
5379  double pages_fetched;
5380  double tuples_fetched;
5381  double heap_pages;
5382  long maxentries;
5383 
5384  /*
5385  * Fetch total cost of obtaining the bitmap, as well as its total
5386  * selectivity.
5387  */
5388  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
5389 
5390  /*
5391  * Estimate number of main-table pages fetched.
5392  */
5393  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
5394 
5395  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
5396 
5397  /*
5398  * For a single scan, the number of heap pages that need to be fetched is
5399  * the same as the Mackert and Lohman formula for the case T <= b (ie, no
5400  * re-reads needed).
5401  */
5402  pages_fetched = (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
5403 
5404  /*
5405  * Calculate the number of pages fetched from the heap. Then based on
5406  * current work_mem estimate get the estimated maxentries in the bitmap.
5407  * (Note that we always do this calculation based on the number of pages
5408  * that would be fetched in a single iteration, even if loop_count > 1.
5409  * That's correct, because only that number of entries will be stored in
5410  * the bitmap at one time.)
5411  */
5412  heap_pages = Min(pages_fetched, baserel->pages);
5413  maxentries = tbm_calculate_entries(work_mem * 1024L);
5414 
5415  if (loop_count > 1)
5416  {
5417  /*
5418  * For repeated bitmap scans, scale up the number of tuples fetched in
5419  * the Mackert and Lohman formula by the number of scans, so that we
5420  * estimate the number of pages fetched by all the scans. Then
5421  * pro-rate for one scan.
5422  */
5423  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
5424  baserel->pages,
5425  get_indexpath_pages(bitmapqual),
5426  root);
5427  pages_fetched /= loop_count;
5428  }
5429 
5430  if (pages_fetched >= T)
5431  pages_fetched = T;
5432  else
5433  pages_fetched = ceil(pages_fetched);
5434 
5435  if (maxentries < heap_pages)
5436  {
5437  double exact_pages;
5438  double lossy_pages;
5439 
5440  /*
5441  * Crude approximation of the number of lossy pages. Because of the
5442  * way tbm_lossify() is coded, the number of lossy pages increases
5443  * very sharply as soon as we run short of memory; this formula has
5444  * that property and seems to perform adequately in testing, but it's
5445  * possible we could do better somehow.
5446  */
5447  lossy_pages = Max(0, heap_pages - maxentries / 2);
5448  exact_pages = heap_pages - lossy_pages;
5449 
5450  /*
5451  * If there are lossy pages then recompute the number of tuples
5452  * processed by the bitmap heap node. We assume here that the chance
5453  * of a given tuple coming from an exact page is the same as the
5454  * chance that a given page is exact. This might not be true, but
5455  * it's not clear how we can do any better.
5456  */
5457  if (lossy_pages > 0)
5458  tuples_fetched =
5459  clamp_row_est(indexSelectivity *
5460  (exact_pages / heap_pages) * baserel->tuples +
5461  (lossy_pages / heap_pages) * baserel->tuples);
5462  }
5463 
5464  if (cost)
5465  *cost = indexTotalCost;
5466  if (tuple)
5467  *tuple = tuples_fetched;
5468 
5469  return pages_fetched;
5470 }
double tuples
Definition: relation.h:625
#define Min(x, y)
Definition: c.h:846
double Selectivity
Definition: nodes.h:643
static const uint32 T[65]
Definition: md5.c:101
int work_mem
Definition: globals.c:113
#define Max(x, y)
Definition: c.h:840
BlockNumber pages
Definition: relation.h:624
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:892
long tbm_calculate_entries(double maxbytes)
Definition: tidbitmap.c:1545
double clamp_row_est(double nrows)
Definition: costsize.c:185
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:827
double Cost
Definition: nodes.h:644
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1043

◆ compute_semi_anti_join_factors()

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

Definition at line 4031 of file costsize.c.

References clauselist_selectivity(), SpecialJoinInfo::delay_upper_joins, IS_OUTER_JOIN, RestrictInfo::is_pushed_down, JOIN_ANTI, JOIN_INNER, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst_node, SpecialJoinInfo::lhs_strict, list_free(), SemiAntiJoinFactors::match_count, Max, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, SemiAntiJoinFactors::outer_match_frac, RelOptInfo::relids, RelOptInfo::rows, SpecialJoinInfo::semi_can_btree, SpecialJoinInfo::semi_can_hash, SpecialJoinInfo::semi_operators, SpecialJoinInfo::semi_rhs_exprs, SpecialJoinInfo::syn_lefthand, SpecialJoinInfo::syn_righthand, T_SpecialJoinInfo, and SpecialJoinInfo::type.

Referenced by add_paths_to_joinrel().

4038 {
4039  Selectivity jselec;
4040  Selectivity nselec;
4041  Selectivity avgmatch;
4042  SpecialJoinInfo norm_sjinfo;
4043  List *joinquals;
4044  ListCell *l;
4045 
4046  /*
4047  * In an ANTI join, we must ignore clauses that are "pushed down", since
4048  * those won't affect the match logic. In a SEMI join, we do not
4049  * distinguish joinquals from "pushed down" quals, so just use the whole
4050  * restrictinfo list. For other outer join types, we should consider only
4051  * non-pushed-down quals, so that this devolves to an IS_OUTER_JOIN check.
4052  */
4053  if (IS_OUTER_JOIN(jointype))
4054  {
4055  joinquals = NIL;
4056  foreach(l, restrictlist)
4057  {
4058  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
4059 
4060  if (!rinfo->is_pushed_down)
4061  joinquals = lappend(joinquals, rinfo);
4062  }
4063  }
4064  else
4065  joinquals = restrictlist;
4066 
4067  /*
4068  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
4069  */
4070  jselec = clauselist_selectivity(root,
4071  joinquals,
4072  0,
4073  (jointype == JOIN_ANTI) ? JOIN_ANTI : JOIN_SEMI,
4074  sjinfo);
4075 
4076  /*
4077  * Also get the normal inner-join selectivity of the join clauses.
4078  */
4079  norm_sjinfo.type = T_SpecialJoinInfo;
4080  norm_sjinfo.min_lefthand = outerrel->relids;
4081  norm_sjinfo.min_righthand = innerrel->relids;
4082  norm_sjinfo.syn_lefthand = outerrel->relids;
4083  norm_sjinfo.syn_righthand = innerrel->relids;
4084  norm_sjinfo.jointype = JOIN_INNER;
4085  /* we don't bother trying to make the remaining fields valid */
4086  norm_sjinfo.lhs_strict = false;
4087  norm_sjinfo.delay_upper_joins = false;
4088  norm_sjinfo.semi_can_btree = false;
4089  norm_sjinfo.semi_can_hash = false;
4090  norm_sjinfo.semi_operators = NIL;
4091  norm_sjinfo.semi_rhs_exprs = NIL;
4092 
4093  nselec = clauselist_selectivity(root,
4094  joinquals,
4095  0,
4096  JOIN_INNER,
4097  &norm_sjinfo);
4098 
4099  /* Avoid leaking a lot of ListCells */
4100  if (IS_OUTER_JOIN(jointype))
4101  list_free(joinquals);
4102 
4103  /*
4104  * jselec can be interpreted as the fraction of outer-rel rows that have
4105  * any matches (this is true for both SEMI and ANTI cases). And nselec is
4106  * the fraction of the Cartesian product that matches. So, the average
4107  * number of matches for each outer-rel row that has at least one match is
4108  * nselec * inner_rows / jselec.
4109  *
4110  * Note: it is correct to use the inner rel's "rows" count here, even
4111  * though we might later be considering a parameterized inner path with
4112  * fewer rows. This is because we have included all the join clauses in
4113  * the selectivity estimate.
4114  */
4115  if (jselec > 0) /* protect against zero divide */
4116  {
4117  avgmatch = nselec * innerrel->rows / jselec;
4118  /* Clamp to sane range */
4119  avgmatch = Max(1.0, avgmatch);
4120  }
4121  else
4122  avgmatch = 1.0;
4123 
4124  semifactors->outer_match_frac = jselec;
4125  semifactors->match_count = avgmatch;
4126 }
#define NIL
Definition: pg_list.h:69
bool semi_can_btree
Definition: relation.h:2027
Relids min_righthand
Definition: relation.h:2020
Selectivity outer_match_frac
Definition: relation.h:2265
NodeTag type
Definition: relation.h:2018
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:726
double Selectivity
Definition: nodes.h:643
Relids syn_lefthand
Definition: relation.h:2021
Relids syn_righthand
Definition: relation.h:2022
List * semi_rhs_exprs
Definition: relation.h:2030
bool semi_can_hash
Definition: relation.h:2028
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Relids relids
Definition: relation.h:585
List * lappend(List *list, void *datum)
Definition: list.c:128
bool delay_upper_joins
Definition: relation.h:2025
double rows
Definition: relation.h:588
bool is_pushed_down
Definition: relation.h:1849
#define Max(x, y)
Definition: c.h:840
JoinType jointype
Definition: relation.h:2023
Selectivity match_count
Definition: relation.h:2266
List * semi_operators
Definition: relation.h:2029
void list_free(List *list)
Definition: list.c:1133
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
Definition: pg_list.h:45
Relids min_lefthand
Definition: relation.h:2019

◆ cost_agg()

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

Definition at line 2057 of file costsize.c.

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, Assert, clamp_row_est(), clauselist_selectivity(), cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_hashagg, AggClauseCosts::finalCost, JOIN_INNER, MemSet, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, Path::total_cost, and AggClauseCosts::transCost.

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

2063 {
2064  double output_tuples;
2065  Cost startup_cost;
2066  Cost total_cost;
2067  AggClauseCosts dummy_aggcosts;
2068 
2069  /* Use all-zero per-aggregate costs if NULL is passed */
2070  if (aggcosts == NULL)
2071  {
2072  Assert(aggstrategy == AGG_HASHED);
2073  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
2074  aggcosts = &dummy_aggcosts;
2075  }
2076 
2077  /*
2078  * The transCost.per_tuple component of aggcosts should be charged once
2079  * per input tuple, corresponding to the costs of evaluating the aggregate
2080  * transfns and their input expressions (with any startup cost of course
2081  * charged but once). The finalCost component is charged once per output
2082  * tuple, corresponding to the costs of evaluating the finalfns.
2083  *
2084  * If we are grouping, we charge an additional cpu_operator_cost per
2085  * grouping column per input tuple for grouping comparisons.
2086  *
2087  * We will produce a single output tuple if not grouping, and a tuple per
2088  * group otherwise. We charge cpu_tuple_cost for each output tuple.
2089  *
2090  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
2091  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
2092  * input path is already sorted appropriately, AGG_SORTED should be
2093  * preferred (since it has no risk of memory overflow). This will happen
2094  * as long as the computed total costs are indeed exactly equal --- but if
2095  * there's roundoff error we might do the wrong thing. So be sure that
2096  * the computations below form the same intermediate values in the same
2097  * order.
2098  */
2099  if (aggstrategy == AGG_PLAIN)
2100  {
2101  startup_cost = input_total_cost;
2102  startup_cost += aggcosts->transCost.startup;
2103  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2104  startup_cost += aggcosts->finalCost;
2105  /* we aren't grouping */
2106  total_cost = startup_cost + cpu_tuple_cost;
2107  output_tuples = 1;
2108  }
2109  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
2110  {
2111  /* Here we are able to deliver output on-the-fly */
2112  startup_cost = input_startup_cost;
2113  total_cost = input_total_cost;
2114  if (aggstrategy == AGG_MIXED && !enable_hashagg)
2115  {
2116  startup_cost += disable_cost;
2117  total_cost += disable_cost;
2118  }
2119  /* calcs phrased this way to match HASHED case, see note above */
2120  total_cost += aggcosts->transCost.startup;
2121  total_cost += aggcosts->transCost.per_tuple * input_tuples;
2122  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2123  total_cost += aggcosts->finalCost * numGroups;
2124  total_cost += cpu_tuple_cost * numGroups;
2125  output_tuples = numGroups;
2126  }
2127  else
2128  {
2129  /* must be AGG_HASHED */
2130  startup_cost = input_total_cost;
2131  if (!enable_hashagg)
2132  startup_cost += disable_cost;
2133  startup_cost += aggcosts->transCost.startup;
2134  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
2135  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
2136  total_cost = startup_cost;
2137  total_cost += aggcosts->finalCost * numGroups;
2138  total_cost += cpu_tuple_cost * numGroups;
2139  output_tuples = numGroups;
2140  }
2141 
2142  /*
2143  * If there are quals (HAVING quals), account for their cost and
2144  * selectivity.
2145  */
2146  if (quals)
2147  {
2148  QualCost qual_cost;
2149 
2150  cost_qual_eval(&qual_cost, quals, root);
2151  startup_cost += qual_cost.startup;
2152  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2153 
2154  output_tuples = clamp_row_est(output_tuples *
2156  quals,
2157  0,
2158  JOIN_INNER,
2159  NULL));
2160  }
2161 
2162  path->rows = output_tuples;
2163  path->startup_cost = startup_cost;
2164  path->total_cost = total_cost;
2165 }
#define MemSet(start, val, len)
Definition: c.h:897
QualCost transCost
Definition: relation.h:62
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
double cpu_operator_cost
Definition: costsize.c:115
Cost finalCost
Definition: relation.h:63
Cost total_cost
Definition: relation.h:1058
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
double cpu_tuple_cost
Definition: costsize.c:113
bool enable_hashagg
Definition: costsize.c:131
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
double clamp_row_est(double nrows)
Definition: costsize.c:185
double Cost
Definition: nodes.h:644

◆ cost_append()

void cost_append ( AppendPath path)

Definition at line 1840 of file costsize.c.

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

Referenced by create_append_path().

1841 {
1842  ListCell *l;
1843 
1844  apath->path.startup_cost = 0;
1845  apath->path.total_cost = 0;
1846 
1847  if (apath->subpaths == NIL)
1848  return;
1849 
1850  if (!apath->path.parallel_aware)
1851  {
1852  Path *subpath = (Path *) linitial(apath->subpaths);
1853 
1854  /*
1855  * Startup cost of non-parallel-aware Append is the startup cost of
1856  * first subpath.
1857  */
1858  apath->path.startup_cost = subpath->startup_cost;
1859 
1860  /* Compute rows and costs as sums of subplan rows and costs. */
1861  foreach(l, apath->subpaths)
1862  {
1863  Path *subpath = (Path *) lfirst(l);
1864 
1865  apath->path.rows += subpath->rows;
1866  apath->path.total_cost += subpath->total_cost;
1867  }
1868  }
1869  else /* parallel-aware */
1870  {
1871  int i = 0;
1872  double parallel_divisor = get_parallel_divisor(&apath->path);
1873 
1874  /* Calculate startup cost. */
1875  foreach(l, apath->subpaths)
1876  {
1877  Path *subpath = (Path *) lfirst(l);
1878 
1879  /*
1880  * Append will start returning tuples when the child node having
1881  * lowest startup cost is done setting up. We consider only the
1882  * first few subplans that immediately get a worker assigned.
1883  */
1884  if (i == 0)
1885  apath->path.startup_cost = subpath->startup_cost;
1886  else if (i < apath->path.parallel_workers)
1887  apath->path.startup_cost = Min(apath->path.startup_cost,
1888  subpath->startup_cost);
1889 
1890  /*
1891  * Apply parallel divisor to subpaths. Scale the number of rows
1892  * for each partial subpath based on the ratio of the parallel
1893  * divisor originally used for the subpath to the one we adopted.
1894  * Also add the cost of partial paths to the total cost, but
1895  * ignore non-partial paths for now.
1896  */
1897  if (i < apath->first_partial_path)
1898  apath->path.rows += subpath->rows / parallel_divisor;
1899  else
1900  {
1901  double subpath_parallel_divisor;
1902 
1903  subpath_parallel_divisor = get_parallel_divisor(subpath);
1904  apath->path.rows += subpath->rows * (subpath_parallel_divisor /
1905  parallel_divisor);
1906  apath->path.total_cost += subpath->total_cost;
1907  }
1908 
1909  apath->path.rows = clamp_row_est(apath->path.rows);
1910 
1911  i++;
1912  }
1913 
1914  /* Add cost for non-partial subpaths. */
1915  apath->path.total_cost +=
1916  append_nonpartial_cost(apath->subpaths,
1917  apath->first_partial_path,
1918  apath->path.parallel_workers);
1919  }
1920 
1921  /*
1922  * Although Append does not do any selection or projection, it's not free;
1923  * add a small per-tuple overhead.
1924  */
1925  apath->path.total_cost +=
1926  cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * apath->path.rows;
1927 }
#define NIL
Definition: pg_list.h:69
#define Min(x, y)
Definition: c.h:846
static Cost append_nonpartial_cost(List *subpaths, int numpaths, int parallel_workers)
Definition: costsize.c:1764
#define linitial(l)
Definition: pg_list.h:111
Cost startup_cost
Definition: relation.h:1057
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:1058
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
double cpu_tuple_cost
Definition: costsize.c:113
int i
double clamp_row_est(double nrows)
Definition: costsize.c:185
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234

◆ cost_bitmap_and_node()

void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1086 of file costsize.c.

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

Referenced by bitmap_and_cost_est(), and create_bitmap_and_path().

1087 {
1088  Cost totalCost;
1089  Selectivity selec;
1090  ListCell *l;
1091 
1092  /*
1093  * We estimate AND selectivity on the assumption that the inputs are
1094  * independent. This is probably often wrong, but we don't have the info
1095  * to do better.
1096  *
1097  * The runtime cost of the BitmapAnd itself is estimated at 100x
1098  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1099  * definitely too simplistic?
1100  */
1101  totalCost = 0.0;
1102  selec = 1.0;
1103  foreach(l, path->bitmapquals)
1104  {
1105  Path *subpath = (Path *) lfirst(l);
1106  Cost subCost;
1107  Selectivity subselec;
1108 
1109  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1110 
1111  selec *= subselec;
1112 
1113  totalCost += subCost;
1114  if (l != list_head(path->bitmapquals))
1115  totalCost += 100.0 * cpu_operator_cost;
1116  }
1117  path->bitmapselectivity = selec;
1118  path->path.rows = 0; /* per above, not used */
1119  path->path.startup_cost = totalCost;
1120  path->path.total_cost = totalCost;
1121 }
double Selectivity
Definition: nodes.h:643
Selectivity bitmapselectivity
Definition: relation.h:1167
List * bitmapquals
Definition: relation.h:1166
Cost startup_cost
Definition: relation.h:1057
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:115
Cost total_cost
Definition: relation.h:1058
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
double Cost
Definition: nodes.h:644
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1043

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

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

Referenced by bitmap_and_cost_est(), bitmap_scan_cost_est(), and create_bitmap_heap_path().

945 {
946  Cost startup_cost = 0;
947  Cost run_cost = 0;
948  Cost indexTotalCost;
949  QualCost qpqual_cost;
950  Cost cpu_per_tuple;
951  Cost cost_per_page;
952  Cost cpu_run_cost;
953  double tuples_fetched;
954  double pages_fetched;
955  double spc_seq_page_cost,
956  spc_random_page_cost;
957  double T;
958 
959  /* Should only be applied to base relations */
960  Assert(IsA(baserel, RelOptInfo));
961  Assert(baserel->relid > 0);
962  Assert(baserel->rtekind == RTE_RELATION);
963 
964  /* Mark the path with the correct row estimate */
965  if (param_info)
966  path->rows = param_info->ppi_rows;
967  else
968  path->rows = baserel->rows;
969 
970  if (!enable_bitmapscan)
971  startup_cost += disable_cost;
972 
973  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
974  loop_count, &indexTotalCost,
975  &tuples_fetched);
976 
977  startup_cost += indexTotalCost;
978  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
979 
980  /* Fetch estimated page costs for tablespace containing table. */
982  &spc_random_page_cost,
983  &spc_seq_page_cost);
984 
985  /*
986  * For small numbers of pages we should charge spc_random_page_cost
987  * apiece, while if nearly all the table's pages are being read, it's more
988  * appropriate to charge spc_seq_page_cost apiece. The effect is
989  * nonlinear, too. For lack of a better idea, interpolate like this to
990  * determine the cost per page.
991  */
992  if (pages_fetched >= 2.0)
993  cost_per_page = spc_random_page_cost -
994  (spc_random_page_cost - spc_seq_page_cost)
995  * sqrt(pages_fetched / T);
996  else
997  cost_per_page = spc_random_page_cost;
998 
999  run_cost += pages_fetched * cost_per_page;
1000 
1001  /*
1002  * Estimate CPU costs per tuple.
1003  *
1004  * Often the indexquals don't need to be rechecked at each tuple ... but
1005  * not always, especially not if there are enough tuples involved that the
1006  * bitmaps become lossy. For the moment, just assume they will be
1007  * rechecked always. This means we charge the full freight for all the
1008  * scan clauses.
1009  */
1010  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1011 
1012  startup_cost += qpqual_cost.startup;
1013  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1014  cpu_run_cost = cpu_per_tuple * tuples_fetched;
1015 
1016  /* Adjust costing for parallelism, if used. */
1017  if (path->parallel_workers > 0)
1018  {
1019  double parallel_divisor = get_parallel_divisor(path);
1020 
1021  /* The CPU cost is divided among all the workers. */
1022  cpu_run_cost /= parallel_divisor;
1023 
1024  path->rows = clamp_row_est(path->rows / parallel_divisor);
1025  }
1026 
1027 
1028  run_cost += cpu_run_cost;
1029 
1030  /* tlist eval costs are paid per output row, not per tuple scanned */
1031  startup_cost += path->pathtarget->cost.startup;
1032  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1033 
1034  path->startup_cost = startup_cost;
1035  path->total_cost = startup_cost + run_cost;
1036 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
PathTarget * pathtarget
Definition: relation.h:1047
Oid reltablespace
Definition: relation.h:614
int parallel_workers
Definition: relation.h:1053
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
static const uint32 T[65]
Definition: md5.c:101
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:613
bool enable_bitmapscan
Definition: costsize.c:128
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
BlockNumber pages
Definition: relation.h:624
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
double clamp_row_est(double nrows)
Definition: costsize.c:185
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:5373
double Cost
Definition: nodes.h:644

◆ cost_bitmap_or_node()

void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1130 of file costsize.c.

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

1131 {
1132  Cost totalCost;
1133  Selectivity selec;
1134  ListCell *l;
1135 
1136  /*
1137  * We estimate OR selectivity on the assumption that the inputs are
1138  * non-overlapping, since that's often the case in "x IN (list)" type
1139  * situations. Of course, we clamp to 1.0 at the end.
1140  *
1141  * The runtime cost of the BitmapOr itself is estimated at 100x
1142  * cpu_operator_cost for each tbm_union needed. Probably too small,
1143  * definitely too simplistic? We are aware that the tbm_unions are
1144  * optimized out when the inputs are BitmapIndexScans.
1145  */
1146  totalCost = 0.0;
1147  selec = 0.0;
1148  foreach(l, path->bitmapquals)
1149  {
1150  Path *subpath = (Path *) lfirst(l);
1151  Cost subCost;
1152  Selectivity subselec;
1153 
1154  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1155 
1156  selec += subselec;
1157 
1158  totalCost += subCost;
1159  if (l != list_head(path->bitmapquals) &&
1160  !IsA(subpath, IndexPath))
1161  totalCost += 100.0 * cpu_operator_cost;
1162  }
1163  path->bitmapselectivity = Min(selec, 1.0);
1164  path->path.rows = 0; /* per above, not used */
1165  path->path.startup_cost = totalCost;
1166  path->path.total_cost = totalCost;
1167 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
#define Min(x, y)
Definition: c.h:846
double Selectivity
Definition: nodes.h:643
List * bitmapquals
Definition: relation.h:1179
Cost startup_cost
Definition: relation.h:1057
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:115
Selectivity bitmapselectivity
Definition: relation.h:1180
Cost total_cost
Definition: relation.h:1058
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
double Cost
Definition: nodes.h:644
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1043

◆ cost_bitmap_tree_node()

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

Definition at line 1043 of file costsize.c.

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

1044 {
1045  if (IsA(path, IndexPath))
1046  {
1047  *cost = ((IndexPath *) path)->indextotalcost;
1048  *selec = ((IndexPath *) path)->indexselectivity;
1049 
1050  /*
1051  * Charge a small amount per retrieved tuple to reflect the costs of
1052  * manipulating the bitmap. This is mostly to make sure that a bitmap
1053  * scan doesn't look to be the same cost as an indexscan to retrieve a
1054  * single tuple.
1055  */
1056  *cost += 0.1 * cpu_operator_cost * path->rows;
1057  }
1058  else if (IsA(path, BitmapAndPath))
1059  {
1060  *cost = path->total_cost;
1061  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1062  }
1063  else if (IsA(path, BitmapOrPath))
1064  {
1065  *cost = path->total_cost;
1066  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1067  }
1068  else
1069  {
1070  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1071  *cost = *selec = 0; /* keep compiler quiet */
1072  }
1073 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
#define ERROR
Definition: elog.h:43
double cpu_operator_cost
Definition: costsize.c:115
Cost total_cost
Definition: relation.h:1058
double rows
Definition: relation.h:1056
#define nodeTag(nodeptr)
Definition: nodes.h:518
#define elog
Definition: elog.h:219

◆ cost_ctescan()

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

Definition at line 1497 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, 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().

1499 {
1500  Cost startup_cost = 0;
1501  Cost run_cost = 0;
1502  QualCost qpqual_cost;
1503  Cost cpu_per_tuple;
1504 
1505  /* Should only be applied to base relations that are CTEs */
1506  Assert(baserel->relid > 0);
1507  Assert(baserel->rtekind == RTE_CTE);
1508 
1509  /* Mark the path with the correct row estimate */
1510  if (param_info)
1511  path->rows = param_info->ppi_rows;
1512  else
1513  path->rows = baserel->rows;
1514 
1515  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1516  cpu_per_tuple = cpu_tuple_cost;
1517 
1518  /* Add scanning CPU costs */
1519  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1520 
1521  startup_cost += qpqual_cost.startup;
1522  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1523  run_cost += cpu_per_tuple * baserel->tuples;
1524 
1525  /* tlist eval costs are paid per output row, not per tuple scanned */
1526  startup_cost += path->pathtarget->cost.startup;
1527  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1528 
1529  path->startup_cost = startup_cost;
1530  path->total_cost = startup_cost + run_cost;
1531 }
PathTarget * pathtarget
Definition: relation.h:1047
double tuples
Definition: relation.h:625
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:1057
Index relid
Definition: relation.h:613
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
double Cost
Definition: nodes.h:644

◆ cost_functionscan()

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

Definition at line 1330 of file costsize.c.

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

Referenced by create_functionscan_path().

1332 {
1333  Cost startup_cost = 0;
1334  Cost run_cost = 0;
1335  QualCost qpqual_cost;
1336  Cost cpu_per_tuple;
1337  RangeTblEntry *rte;
1338  QualCost exprcost;
1339 
1340  /* Should only be applied to base relations that are functions */
1341  Assert(baserel->relid > 0);
1342  rte = planner_rt_fetch(baserel->relid, root);
1343  Assert(rte->rtekind == RTE_FUNCTION);
1344 
1345  /* Mark the path with the correct row estimate */
1346  if (param_info)
1347  path->rows = param_info->ppi_rows;
1348  else
1349  path->rows = baserel->rows;
1350 
1351  /*
1352  * Estimate costs of executing the function expression(s).
1353  *
1354  * Currently, nodeFunctionscan.c always executes the functions to
1355  * completion before returning any rows, and caches the results in a
1356  * tuplestore. So the function eval cost is all startup cost, and per-row
1357  * costs are minimal.
1358  *
1359  * XXX in principle we ought to charge tuplestore spill costs if the
1360  * number of rows is large. However, given how phony our rowcount
1361  * estimates for functions tend to be, there's not a lot of point in that
1362  * refinement right now.
1363  */
1364  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1365 
1366  startup_cost += exprcost.startup + exprcost.per_tuple;
1367 
1368  /* Add scanning CPU costs */
1369  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1370 
1371  startup_cost += qpqual_cost.startup;
1372  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1373  run_cost += cpu_per_tuple * baserel->tuples;
1374 
1375  /* tlist eval costs are paid per output row, not per tuple scanned */
1376  startup_cost += path->pathtarget->cost.startup;
1377  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1378 
1379  path->startup_cost = startup_cost;
1380  path->total_cost = startup_cost + run_cost;
1381 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3737
PathTarget * pathtarget
Definition: relation.h:1047
double tuples
Definition: relation.h:625
Definition: nodes.h:513
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
Cost startup_cost
Definition: relation.h:1057
Index relid
Definition: relation.h:613
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
#define Assert(condition)
Definition: c.h:688
List * functions
Definition: parsenodes.h:1013
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
RTEKind rtekind
Definition: parsenodes.h:959
double Cost
Definition: nodes.h:644

◆ cost_gather()

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

Definition at line 361 of file costsize.c.

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

Referenced by create_gather_path().

364 {
365  Cost startup_cost = 0;
366  Cost run_cost = 0;
367 
368  /* Mark the path with the correct row estimate */
369  if (rows)
370  path->path.rows = *rows;
371  else if (param_info)
372  path->path.rows = param_info->ppi_rows;
373  else
374  path->path.rows = rel->rows;
375 
376  startup_cost = path->subpath->startup_cost;
377 
378  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
379 
380  /* Parallel setup and communication cost. */
381  startup_cost += parallel_setup_cost;
382  run_cost += parallel_tuple_cost * path->path.rows;
383 
384  path->path.startup_cost = startup_cost;
385  path->path.total_cost = (startup_cost + run_cost);
386 }
double parallel_setup_cost
Definition: costsize.c:117
Cost startup_cost
Definition: relation.h:1057
Path * subpath
Definition: relation.h:1363
Cost total_cost
Definition: relation.h:1058
double rows
Definition: relation.h:1056
double ppi_rows
Definition: relation.h:1006
Path path
Definition: relation.h:1362
double Cost
Definition: nodes.h:644
double parallel_tuple_cost
Definition: costsize.c:116

◆ cost_gather_merge()

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

Definition at line 399 of file costsize.c.

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

Referenced by create_gather_merge_path().

403 {
404  Cost startup_cost = 0;
405  Cost run_cost = 0;
406  Cost comparison_cost;
407  double N;
408  double logN;
409 
410  /* Mark the path with the correct row estimate */
411  if (rows)
412  path->path.rows = *rows;
413  else if (param_info)
414  path->path.rows = param_info->ppi_rows;
415  else
416  path->path.rows = rel->rows;
417 
418  if (!enable_gathermerge)
419  startup_cost += disable_cost;
420 
421  /*
422  * Add one to the number of workers to account for the leader. This might
423  * be overgenerous since the leader will do less work than other workers
424  * in typical cases, but we'll go with it for now.
425  */
426  Assert(path->num_workers > 0);
427  N = (double) path->num_workers + 1;
428  logN = LOG2(N);
429 
430  /* Assumed cost per tuple comparison */
431  comparison_cost = 2.0 * cpu_operator_cost;
432 
433  /* Heap creation cost */
434  startup_cost += comparison_cost * N * logN;
435 
436  /* Per-tuple heap maintenance cost */
437  run_cost += path->path.rows * comparison_cost * logN;
438 
439  /* small cost for heap management, like cost_merge_append */
440  run_cost += cpu_operator_cost * path->path.rows;
441 
442  /*
443  * Parallel setup and communication cost. Since Gather Merge, unlike
444  * Gather, requires us to block until a tuple is available from every
445  * worker, we bump the IPC cost up a little bit as compared with Gather.
446  * For lack of a better idea, charge an extra 5%.
447  */
448  startup_cost += parallel_setup_cost;
449  run_cost += parallel_tuple_cost * path->path.rows * 1.05;
450 
451  path->path.startup_cost = startup_cost + input_startup_cost;
452  path->path.total_cost = (startup_cost + run_cost + input_total_cost);
453 }
double parallel_setup_cost
Definition: costsize.c:117
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
double cpu_operator_cost
Definition: costsize.c:115
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
#define LOG2(x)
Definition: costsize.c:101
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
double ppi_rows
Definition: relation.h:1006
bool enable_gathermerge
Definition: costsize.c:136
double Cost
Definition: nodes.h:644
double parallel_tuple_cost
Definition: costsize.c:116

◆ cost_group()

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

Definition at line 2245 of file costsize.c.

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

Referenced by choose_hashed_setop(), and create_group_path().

2250 {
2251  double output_tuples;
2252  Cost startup_cost;
2253  Cost total_cost;
2254 
2255  output_tuples = numGroups;
2256  startup_cost = input_startup_cost;
2257  total_cost = input_total_cost;
2258 
2259  /*
2260  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2261  * all columns get compared at most of the tuples.
2262  */
2263  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2264 
2265  /*
2266  * If there are quals (HAVING quals), account for their cost and
2267  * selectivity.
2268  */
2269  if (quals)
2270  {
2271  QualCost qual_cost;
2272 
2273  cost_qual_eval(&qual_cost, quals, root);
2274  startup_cost += qual_cost.startup;
2275  total_cost += qual_cost.startup + output_tuples * qual_cost.per_tuple;
2276 
2277  output_tuples = clamp_row_est(output_tuples *
2279  quals,
2280  0,
2281  JOIN_INNER,
2282  NULL));
2283  }
2284 
2285  path->rows = output_tuples;
2286  path->startup_cost = startup_cost;
2287  path->total_cost = total_cost;
2288 }
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Cost startup_cost
Definition: relation.h:1057
double cpu_operator_cost
Definition: costsize.c:115
Cost total_cost
Definition: relation.h:1058
double rows
Definition: relation.h:1056
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
double clamp_row_est(double nrows)
Definition: costsize.c:185
double Cost
Definition: nodes.h:644

◆ cost_index()

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

Definition at line 474 of file costsize.c.

References RelOptInfo::allvisfrac, IndexOptInfo::amcostestimate, Assert, clamp_row_est(), compute_parallel_worker(), PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_indexscan, extract_nonindex_conditions(), get_parallel_divisor(), get_tablespace_page_costs(), index_pages_fetched(), IndexPath::indexinfo, IndexPath::indexquals, IndexPath::indexselectivity, IndexPath::indextotalcost, IndexOptInfo::indrestrictinfo, IsA, list_concat(), max_parallel_workers_per_gather, RelOptInfo::pages, IndexOptInfo::pages, Path::parallel_aware, Path::parallel_workers, Path::param_info, IndexPath::path, Path::pathtarget, Path::pathtype, QualCost::per_tuple, ParamPathInfo::ppi_clauses, ParamPathInfo::ppi_rows, IndexOptInfo::rel, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, T_IndexOnlyScan, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_index_path(), and reparameterize_path().

476 {
477  IndexOptInfo *index = path->indexinfo;
478  RelOptInfo *baserel = index->rel;
479  bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
480  amcostestimate_function amcostestimate;
481  List *qpquals;
482  Cost startup_cost = 0;
483  Cost run_cost = 0;
484  Cost cpu_run_cost = 0;
485  Cost indexStartupCost;
486  Cost indexTotalCost;
487  Selectivity indexSelectivity;
488  double indexCorrelation,
489  csquared;
490  double spc_seq_page_cost,
491  spc_random_page_cost;
492  Cost min_IO_cost,
493  max_IO_cost;
494  QualCost qpqual_cost;
495  Cost cpu_per_tuple;
496  double tuples_fetched;
497  double pages_fetched;
498  double rand_heap_pages;
499  double index_pages;
500 
501  /* Should only be applied to base relations */
502  Assert(IsA(baserel, RelOptInfo) &&
503  IsA(index, IndexOptInfo));
504  Assert(baserel->relid > 0);
505  Assert(baserel->rtekind == RTE_RELATION);
506 
507  /*
508  * Mark the path with the correct row estimate, and identify which quals
509  * will need to be enforced as qpquals. We need not check any quals that
510  * are implied by the index's predicate, so we can use indrestrictinfo not
511  * baserestrictinfo as the list of relevant restriction clauses for the
512  * rel.
513  */
514  if (path->path.param_info)
515  {
516  path->path.rows = path->path.param_info->ppi_rows;
517  /* qpquals come from the rel's restriction clauses and ppi_clauses */
518  qpquals = list_concat(
520  path->indexquals),
522  path->indexquals));
523  }
524  else
525  {
526  path->path.rows = baserel->rows;
527  /* qpquals come from just the rel's restriction clauses */
529  path->indexquals);
530  }
531 
532  if (!enable_indexscan)
533  startup_cost += disable_cost;
534  /* we don't need to check enable_indexonlyscan; indxpath.c does that */
535 
536  /*
537  * Call index-access-method-specific code to estimate the processing cost
538  * for scanning the index, as well as the selectivity of the index (ie,
539  * the fraction of main-table tuples we will have to retrieve) and its
540  * correlation to the main-table tuple order. We need a cast here because
541  * relation.h uses a weak function type to avoid including amapi.h.
542  */
543  amcostestimate = (amcostestimate_function) index->amcostestimate;
544  amcostestimate(root, path, loop_count,
545  &indexStartupCost, &indexTotalCost,
546  &indexSelectivity, &indexCorrelation,
547  &index_pages);
548 
549  /*
550  * Save amcostestimate's results for possible use in bitmap scan planning.
551  * We don't bother to save indexStartupCost or indexCorrelation, because a
552  * bitmap scan doesn't care about either.
553  */
554  path->indextotalcost = indexTotalCost;
555  path->indexselectivity = indexSelectivity;
556 
557  /* all costs for touching index itself included here */
558  startup_cost += indexStartupCost;
559  run_cost += indexTotalCost - indexStartupCost;
560 
561  /* estimate number of main-table tuples fetched */
562  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
563 
564  /* fetch estimated page costs for tablespace containing table */
566  &spc_random_page_cost,
567  &spc_seq_page_cost);
568 
569  /*----------
570  * Estimate number of main-table pages fetched, and compute I/O cost.
571  *
572  * When the index ordering is uncorrelated with the table ordering,
573  * we use an approximation proposed by Mackert and Lohman (see
574  * index_pages_fetched() for details) to compute the number of pages
575  * fetched, and then charge spc_random_page_cost per page fetched.
576  *
577  * When the index ordering is exactly correlated with the table ordering
578  * (just after a CLUSTER, for example), the number of pages fetched should
579  * be exactly selectivity * table_size. What's more, all but the first
580  * will be sequential fetches, not the random fetches that occur in the
581  * uncorrelated case. So if the number of pages is more than 1, we
582  * ought to charge
583  * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
584  * For partially-correlated indexes, we ought to charge somewhere between
585  * these two estimates. We currently interpolate linearly between the
586  * estimates based on the correlation squared (XXX is that appropriate?).
587  *
588  * If it's an index-only scan, then we will not need to fetch any heap
589  * pages for which the visibility map shows all tuples are visible.
590  * Hence, reduce the estimated number of heap fetches accordingly.
591  * We use the measured fraction of the entire heap that is all-visible,
592  * which might not be particularly relevant to the subset of the heap
593  * that this query will fetch; but it's not clear how to do better.
594  *----------
595  */
596  if (loop_count > 1)
597  {
598  /*
599  * For repeated indexscans, the appropriate estimate for the
600  * uncorrelated case is to scale up the number of tuples fetched in
601  * the Mackert and Lohman formula by the number of scans, so that we
602  * estimate the number of pages fetched by all the scans; then
603  * pro-rate the costs for one scan. In this case we assume all the
604  * fetches are random accesses.
605  */
606  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
607  baserel->pages,
608  (double) index->pages,
609  root);
610 
611  if (indexonly)
612  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
613 
614  rand_heap_pages = pages_fetched;
615 
616  max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
617 
618  /*
619  * In the perfectly correlated case, the number of pages touched by
620  * each scan is selectivity * table_size, and we can use the Mackert
621  * and Lohman formula at the page level to estimate how much work is
622  * saved by caching across scans. We still assume all the fetches are
623  * random, though, which is an overestimate that's hard to correct for
624  * without double-counting the cache effects. (But in most cases
625  * where such a plan is actually interesting, only one page would get
626  * fetched per scan anyway, so it shouldn't matter much.)
627  */
628  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
629 
630  pages_fetched = index_pages_fetched(pages_fetched * loop_count,
631  baserel->pages,
632  (double) index->pages,
633  root);
634 
635  if (indexonly)
636  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
637 
638  min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
639  }
640  else
641  {
642  /*
643  * Normal case: apply the Mackert and Lohman formula, and then
644  * interpolate between that and the correlation-derived result.
645  */
646  pages_fetched = index_pages_fetched(tuples_fetched,
647  baserel->pages,
648  (double) index->pages,
649  root);
650 
651  if (indexonly)
652  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
653 
654  rand_heap_pages = pages_fetched;
655 
656  /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
657  max_IO_cost = pages_fetched * spc_random_page_cost;
658 
659  /* min_IO_cost is for the perfectly correlated case (csquared=1) */
660  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
661 
662  if (indexonly)
663  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
664 
665  if (pages_fetched > 0)
666  {
667  min_IO_cost = spc_random_page_cost;
668  if (pages_fetched > 1)
669  min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
670  }
671  else
672  min_IO_cost = 0;
673  }
674 
675  if (partial_path)
676  {
677  /*
678  * For index only scans compute workers based on number of index pages
679  * fetched; the number of heap pages we fetch might be so small as to
680  * effectively rule out parallelism, which we don't want to do.
681  */
682  if (indexonly)
683  rand_heap_pages = -1;
684 
685  /*
686  * Estimate the number of parallel workers required to scan index. Use
687  * the number of heap pages computed considering heap fetches won't be
688  * sequential as for parallel scans the pages are accessed in random
689  * order.
690  */
692  rand_heap_pages,
693  index_pages,
695 
696  /*
697  * Fall out if workers can't be assigned for parallel scan, because in
698  * such a case this path will be rejected. So there is no benefit in
699  * doing extra computation.
700  */
701  if (path->path.parallel_workers <= 0)
702  return;
703 
704  path->path.parallel_aware = true;
705  }
706 
707  /*
708  * Now interpolate based on estimated index order correlation to get total
709  * disk I/O cost for main table accesses.
710  */
711  csquared = indexCorrelation * indexCorrelation;
712 
713  run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
714 
715  /*
716  * Estimate CPU costs per tuple.
717  *
718  * What we want here is cpu_tuple_cost plus the evaluation costs of any
719  * qual clauses that we have to evaluate as qpquals.
720  */
721  cost_qual_eval(&qpqual_cost, qpquals, root);
722 
723  startup_cost += qpqual_cost.startup;
724  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
725 
726  cpu_run_cost += cpu_per_tuple * tuples_fetched;
727 
728  /* tlist eval costs are paid per output row, not per tuple scanned */
729  startup_cost += path->path.pathtarget->cost.startup;
730  cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
731 
732  /* Adjust costing for parallelism, if used. */
733  if (path->path.parallel_workers > 0)
734  {
735  double parallel_divisor = get_parallel_divisor(&path->path);
736 
737  path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
738 
739  /* The CPU cost is divided among all the workers. */
740  cpu_run_cost /= parallel_divisor;
741  }
742 
743  run_cost += cpu_run_cost;
744 
745  path->path.startup_cost = startup_cost;
746  path->path.total_cost = startup_cost + run_cost;
747 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
PathTarget * pathtarget
Definition: relation.h:1047
Path path
Definition: relation.h:1122
IndexOptInfo * indexinfo
Definition: relation.h:1123
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:3329
double tuples
Definition: relation.h:625
Oid reltablespace
Definition: relation.h:614
int parallel_workers
Definition: relation.h:1053
ParamPathInfo * param_info
Definition: relation.h:1049
List * list_concat(List *list1, List *list2)
Definition: list.c:321
static List * extract_nonindex_conditions(List *qual_clauses, List *indexquals)
Definition: costsize.c:767
double Selectivity
Definition: nodes.h:643
Cost startup
Definition: relation.h:45
double allvisfrac
Definition: relation.h:626
Definition: type.h:89
BlockNumber pages
Definition: relation.h:728
NodeTag pathtype
Definition: relation.h:1044
Cost per_tuple
Definition: relation.h:46
List * indexquals
Definition: relation.h:1125
RelOptInfo * rel
Definition: relation.h:725
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Cost startup_cost
Definition: relation.h:1057
Cost indextotalcost
Definition: relation.h:1130
Cost disable_cost
Definition: costsize.c:121
Selectivity indexselectivity
Definition: relation.h:1131
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
void(* amcostestimate)()
Definition: relation.h:770
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:613
List * indrestrictinfo
Definition: relation.h:750
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
BlockNumber pages
Definition: relation.h:624
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
List * ppi_clauses
Definition: relation.h:1007
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
void(* amcostestimate_function)(struct PlannerInfo *root, struct IndexPath *path, double loop_count, Cost *indexStartupCost, Cost *indexTotalCost, Selectivity *indexSelectivity, double *indexCorrelation, double *indexPages)
Definition: amapi.h:92
bool parallel_aware
Definition: relation.h:1051
double clamp_row_est(double nrows)
Definition: costsize.c:185
int max_parallel_workers_per_gather
Definition: costsize.c:123
Definition: pg_list.h:45
bool enable_indexscan
Definition: costsize.c:126
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:827
double Cost
Definition: nodes.h:644

◆ cost_material()

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

Definition at line 2003 of file costsize.c.

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

Referenced by create_material_path(), and materialize_finished_plan().

2006 {
2007  Cost startup_cost = input_startup_cost;
2008  Cost run_cost = input_total_cost - input_startup_cost;
2009  double nbytes = relation_byte_size(tuples, width);
2010  long work_mem_bytes = work_mem * 1024L;
2011 
2012  path->rows = tuples;
2013 
2014  /*
2015  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
2016  * reflect bookkeeping overhead. (This rate must be more than what
2017  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
2018  * if it is exactly the same then there will be a cost tie between
2019  * nestloop with A outer, materialized B inner and nestloop with B outer,
2020  * materialized A inner. The extra cost ensures we'll prefer
2021  * materializing the smaller rel.) Note that this is normally a good deal
2022  * less than cpu_tuple_cost; which is OK because a Material plan node
2023  * doesn't do qual-checking or projection, so it's got less overhead than
2024  * most plan nodes.
2025  */
2026  run_cost += 2 * cpu_operator_cost * tuples;
2027 
2028  /*
2029  * If we will spill to disk, charge at the rate of seq_page_cost per page.
2030  * This cost is assumed to be evenly spread through the plan run phase,
2031  * which isn't exactly accurate but our cost model doesn't allow for
2032  * nonuniform costs within the run phase.
2033  */
2034  if (nbytes > work_mem_bytes)
2035  {
2036  double npages = ceil(nbytes / BLCKSZ);
2037 
2038  run_cost += seq_page_cost * npages;
2039  }
2040 
2041  path->startup_cost = startup_cost;
2042  path->total_cost = startup_cost + run_cost;
2043 }
Cost startup_cost
Definition: relation.h:1057
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5319
int work_mem
Definition: globals.c:113
Cost total_cost
Definition: relation.h:1058
double rows
Definition: relation.h:1056
double seq_page_cost
Definition: costsize.c:111
double Cost
Definition: nodes.h:644

◆ cost_merge_append()

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

Definition at line 1954 of file costsize.c.

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

Referenced by create_merge_append_path().

1958 {
1959  Cost startup_cost = 0;
1960  Cost run_cost = 0;
1961  Cost comparison_cost;
1962  double N;
1963  double logN;
1964 
1965  /*
1966  * Avoid log(0)...
1967  */
1968  N = (n_streams < 2) ? 2.0 : (double) n_streams;
1969  logN = LOG2(N);
1970 
1971  /* Assumed cost per tuple comparison */
1972  comparison_cost = 2.0 * cpu_operator_cost;
1973 
1974  /* Heap creation cost */
1975  startup_cost += comparison_cost * N * logN;
1976 
1977  /* Per-tuple heap maintenance cost */
1978  run_cost += tuples * comparison_cost * logN;
1979 
1980  /*
1981  * Although MergeAppend does not do any selection or projection, it's not
1982  * free; add a small per-tuple overhead.
1983  */
1984  run_cost += cpu_tuple_cost * APPEND_CPU_COST_MULTIPLIER * tuples;
1985 
1986  path->startup_cost = startup_cost + input_startup_cost;
1987  path->total_cost = startup_cost + run_cost + input_total_cost;
1988 }
Cost startup_cost
Definition: relation.h:1057
double cpu_operator_cost
Definition: costsize.c:115
#define APPEND_CPU_COST_MULTIPLIER
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:1058
#define LOG2(x)
Definition: costsize.c:101
double cpu_tuple_cost
Definition: costsize.c:113
double Cost
Definition: nodes.h:644

◆ cost_namedtuplestorescan()

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

Definition at line 1538 of file costsize.c.

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

Referenced by create_namedtuplestorescan_path().

1540 {
1541  Cost startup_cost = 0;
1542  Cost run_cost = 0;
1543  QualCost qpqual_cost;
1544  Cost cpu_per_tuple;
1545 
1546  /* Should only be applied to base relations that are Tuplestores */
1547  Assert(baserel->relid > 0);
1548  Assert(baserel->rtekind == RTE_NAMEDTUPLESTORE);
1549 
1550  /* Mark the path with the correct row estimate */
1551  if (param_info)
1552  path->rows = param_info->ppi_rows;
1553  else
1554  path->rows = baserel->rows;
1555 
1556  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1557  cpu_per_tuple = cpu_tuple_cost;
1558 
1559  /* Add scanning CPU costs */
1560  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1561 
1562  startup_cost += qpqual_cost.startup;
1563  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1564  run_cost += cpu_per_tuple * baserel->tuples;
1565 
1566  path->startup_cost = startup_cost;
1567  path->total_cost = startup_cost + run_cost;
1568 }
double tuples
Definition: relation.h:625
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:1057
Index relid
Definition: relation.h:613
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
double Cost
Definition: nodes.h:644

◆ cost_qual_eval()

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

Definition at line 3711 of file costsize.c.

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

Referenced by cost_agg(), cost_group(), cost_index(), cost_subplan(), cost_tidscan(), create_minmaxagg_path(), create_result_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().

3712 {
3713  cost_qual_eval_context context;
3714  ListCell *l;
3715 
3716  context.root = root;
3717  context.total.startup = 0;
3718  context.total.per_tuple = 0;
3719 
3720  /* We don't charge any cost for the implicit ANDing at top level ... */
3721 
3722  foreach(l, quals)
3723  {
3724  Node *qual = (Node *) lfirst(l);
3725 
3726  cost_qual_eval_walker(qual, &context);
3727  }
3728 
3729  *cost = context.total;
3730 }
PlannerInfo * root
Definition: costsize.c:143
Definition: nodes.h:513
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3751
#define lfirst(lc)
Definition: pg_list.h:106

◆ cost_qual_eval_node()

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

Definition at line 3737 of file costsize.c.

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

Referenced by add_placeholders_to_joinrel(), cost_functionscan(), cost_qual_eval_walker(), cost_tablefuncscan(), cost_windowagg(), get_agg_clause_costs_walker(), make_sort_input_target(), order_qual_clauses(), orderby_operands_eval_cost(), other_operands_eval_cost(), set_pathtarget_cost_width(), and set_rel_width().

3738 {
3739  cost_qual_eval_context context;
3740 
3741  context.root = root;
3742  context.total.startup = 0;
3743  context.total.per_tuple = 0;
3744 
3745  cost_qual_eval_walker(qual, &context);
3746 
3747  *cost = context.total;
3748 }
PlannerInfo * root
Definition: costsize.c:143
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
static bool cost_qual_eval_walker(Node *node, cost_qual_eval_context *context)
Definition: costsize.c:3751

◆ cost_recursive_union()

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

Definition at line 1578 of file costsize.c.

References cpu_tuple_cost, Max, Path::pathtarget, Path::rows, Path::startup_cost, Path::total_cost, and PathTarget::width.

Referenced by create_recursiveunion_path().

1579 {
1580  Cost startup_cost;
1581  Cost total_cost;
1582  double total_rows;
1583 
1584  /* We probably have decent estimates for the non-recursive term */
1585  startup_cost = nrterm->startup_cost;
1586  total_cost = nrterm->total_cost;
1587  total_rows = nrterm->rows;
1588 
1589  /*
1590  * We arbitrarily assume that about 10 recursive iterations will be
1591  * needed, and that we've managed to get a good fix on the cost and output
1592  * size of each one of them. These are mighty shaky assumptions but it's
1593  * hard to see how to do better.
1594  */
1595  total_cost += 10 * rterm->total_cost;
1596  total_rows += 10 * rterm->rows;
1597 
1598  /*
1599  * Also charge cpu_tuple_cost per row to account for the costs of
1600  * manipulating the tuplestores. (We don't worry about possible
1601  * spill-to-disk costs.)
1602  */
1603  total_cost += cpu_tuple_cost * total_rows;
1604 
1605  runion->startup_cost = startup_cost;
1606  runion->total_cost = total_cost;
1607  runion->rows = total_rows;
1608  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1609  rterm->pathtarget->width);
1610 }
PathTarget * pathtarget
Definition: relation.h:1047
Cost startup_cost
Definition: relation.h:1057
Cost total_cost
Definition: relation.h:1058
#define Max(x, y)
Definition: c.h:840
double rows
Definition: relation.h:1056
double cpu_tuple_cost
Definition: costsize.c:113
int width
Definition: relation.h:979
double Cost
Definition: nodes.h:644

◆ cost_samplescan()

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

Definition at line 286 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, RelOptInfo::pages, Path::pathtarget, QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, 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().

288 {
289  Cost startup_cost = 0;
290  Cost run_cost = 0;
291  RangeTblEntry *rte;
292  TableSampleClause *tsc;
293  TsmRoutine *tsm;
294  double spc_seq_page_cost,
295  spc_random_page_cost,
296  spc_page_cost;
297  QualCost qpqual_cost;
298  Cost cpu_per_tuple;
299 
300  /* Should only be applied to base relations with tablesample clauses */
301  Assert(baserel->relid > 0);
302  rte = planner_rt_fetch(baserel->relid, root);
303  Assert(rte->rtekind == RTE_RELATION);
304  tsc = rte->tablesample;
305  Assert(tsc != NULL);
306  tsm = GetTsmRoutine(tsc->tsmhandler);
307 
308  /* Mark the path with the correct row estimate */
309  if (param_info)
310  path->rows = param_info->ppi_rows;
311  else
312  path->rows = baserel->rows;
313 
314  /* fetch estimated page cost for tablespace containing table */
316  &spc_random_page_cost,
317  &spc_seq_page_cost);
318 
319  /* if NextSampleBlock is used, assume random access, else sequential */
320  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
321  spc_random_page_cost : spc_seq_page_cost;
322 
323  /*
324  * disk costs (recall that baserel->pages has already been set to the
325  * number of pages the sampling method will visit)
326  */
327  run_cost += spc_page_cost * baserel->pages;
328 
329  /*
330  * CPU costs (recall that baserel->tuples has already been set to the
331  * number of tuples the sampling method will select). Note that we ignore
332  * execution cost of the TABLESAMPLE parameter expressions; they will be
333  * evaluated only once per scan, and in most usages they'll likely be
334  * simple constants anyway. We also don't charge anything for the
335  * calculations the sampling method might do internally.
336  */
337  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
338 
339  startup_cost += qpqual_cost.startup;
340  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
341  run_cost += cpu_per_tuple * baserel->tuples;
342  /* tlist eval costs are paid per output row, not per tuple scanned */
343  startup_cost += path->pathtarget->cost.startup;
344  run_cost += path->pathtarget->cost.per_tuple * path->rows;
345 
346  path->startup_cost = startup_cost;
347  path->total_cost = startup_cost + run_cost;
348 }
PathTarget * pathtarget
Definition: relation.h:1047
double tuples
Definition: relation.h:625
Oid reltablespace
Definition: relation.h:614
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
Cost startup_cost
Definition: relation.h:1057
NextSampleBlock_function NextSampleBlock
Definition: tsmapi.h:72
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:613
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: relation.h:624
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
RTEKind rtekind
Definition: parsenodes.h:959
struct TableSampleClause * tablesample
Definition: parsenodes.h:977
double Cost
Definition: nodes.h:644

◆ cost_seqscan()

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

Definition at line 209 of file costsize.c.

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

Referenced by create_seqscan_path().

211 {
212  Cost startup_cost = 0;
213  Cost cpu_run_cost;
214  Cost disk_run_cost;
215  double spc_seq_page_cost;
216  QualCost qpqual_cost;
217  Cost cpu_per_tuple;
218 
219  /* Should only be applied to base relations */
220  Assert(baserel->relid > 0);
221  Assert(baserel->rtekind == RTE_RELATION);
222 
223  /* Mark the path with the correct row estimate */
224  if (param_info)
225  path->rows = param_info->ppi_rows;
226  else
227  path->rows = baserel->rows;
228 
229  if (!enable_seqscan)
230  startup_cost += disable_cost;
231 
232  /* fetch estimated page cost for tablespace containing table */
234  NULL,
235  &spc_seq_page_cost);
236 
237  /*
238  * disk costs
239  */
240  disk_run_cost = spc_seq_page_cost * baserel->pages;
241 
242  /* CPU costs */
243  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
244 
245  startup_cost += qpqual_cost.startup;
246  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
247  cpu_run_cost = cpu_per_tuple * baserel->tuples;
248  /* tlist eval costs are paid per output row, not per tuple scanned */
249  startup_cost += path->pathtarget->cost.startup;
250  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
251 
252  /* Adjust costing for parallelism, if used. */
253  if (path->parallel_workers > 0)
254  {
255  double parallel_divisor = get_parallel_divisor(path);
256 
257  /* The CPU cost is divided among all the workers. */
258  cpu_run_cost /= parallel_divisor;
259 
260  /*
261  * It may be possible to amortize some of the I/O cost, but probably
262  * not very much, because most operating systems already do aggressive
263  * prefetching. For now, we assume that the disk run cost can't be
264  * amortized at all.
265  */
266 
267  /*
268  * In the case of a parallel plan, the row count needs to represent
269  * the number of tuples processed per worker.
270  */
271  path->rows = clamp_row_est(path->rows / parallel_divisor);
272  }
273 
274  path->startup_cost = startup_cost;
275  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
276 }
PathTarget * pathtarget
Definition: relation.h:1047
double tuples
Definition: relation.h:625
Oid reltablespace
Definition: relation.h:614
int parallel_workers
Definition: relation.h:1053
bool enable_seqscan
Definition: costsize.c:125
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:613
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
BlockNumber pages
Definition: relation.h:624
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
double clamp_row_est(double nrows)
Definition: costsize.c:185
double Cost
Definition: nodes.h:644

◆ cost_sort()

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

Definition at line 1658 of file costsize.c.

References cpu_operator_cost, disable_cost, enable_sort, LOG2, random_page_cost, relation_byte_size(), Path::rows, seq_page_cost, Path::startup_cost, Path::total_cost, and tuplesort_merge_order().

Referenced by choose_hashed_setop(), create_gather_merge_path(), create_groupingsets_path(), create_merge_append_path(), create_sort_path(), create_unique_path(), initial_cost_mergejoin(), label_sort_with_costsize(), and plan_cluster_use_sort().

1662 {
1663  Cost startup_cost = input_cost;
1664  Cost run_cost = 0;
1665  double input_bytes = relation_byte_size(tuples, width);
1666  double output_bytes;
1667  double output_tuples;
1668  long sort_mem_bytes = sort_mem * 1024L;
1669 
1670  if (!enable_sort)
1671  startup_cost += disable_cost;
1672 
1673  path->rows = tuples;
1674 
1675  /*
1676  * We want to be sure the cost of a sort is never estimated as zero, even
1677  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1678  */
1679  if (tuples < 2.0)
1680  tuples = 2.0;
1681 
1682  /* Include the default cost-per-comparison */
1683  comparison_cost += 2.0 * cpu_operator_cost;
1684 
1685  /* Do we have a useful LIMIT? */
1686  if (limit_tuples > 0 && limit_tuples < tuples)
1687  {
1688  output_tuples = limit_tuples;
1689  output_bytes = relation_byte_size(output_tuples, width);
1690  }
1691  else
1692  {
1693  output_tuples = tuples;
1694  output_bytes = input_bytes;
1695  }
1696 
1697  if (output_bytes > sort_mem_bytes)
1698  {
1699  /*
1700  * We'll have to use a disk-based sort of all the tuples
1701  */
1702  double npages = ceil(input_bytes / BLCKSZ);
1703  double nruns = input_bytes / sort_mem_bytes;
1704  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1705  double log_runs;
1706  double npageaccesses;
1707 
1708  /*
1709  * CPU costs
1710  *
1711  * Assume about N log2 N comparisons
1712  */
1713  startup_cost += comparison_cost * tuples * LOG2(tuples);
1714 
1715  /* Disk costs */
1716 
1717  /* Compute logM(r) as log(r) / log(M) */
1718  if (nruns > mergeorder)
1719  log_runs = ceil(log(nruns) / log(mergeorder));
1720  else
1721  log_runs = 1.0;
1722  npageaccesses = 2.0 * npages * log_runs;
1723  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1724  startup_cost += npageaccesses *
1725  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1726  }
1727  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1728  {
1729  /*
1730  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1731  * a total number of tuple comparisons of N log2 K; but the constant
1732  * factor is a bit higher than for quicksort. Tweak it so that the
1733  * cost curve is continuous at the crossover point.
1734  */
1735  startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1736  }
1737  else
1738  {
1739  /* We'll use plain quicksort on all the input tuples */
1740  startup_cost += comparison_cost * tuples * LOG2(tuples);
1741  }
1742 
1743  /*
1744  * Also charge a small amount (arbitrarily set equal to operator cost) per
1745  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1746  * doesn't do qual-checking or projection, so it has less overhead than
1747  * most plan nodes. Note it's correct to use tuples not output_tuples
1748  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1749  * counting the LIMIT otherwise.
1750  */
1751  run_cost += cpu_operator_cost * tuples;
1752 
1753  path->startup_cost = startup_cost;
1754  path->total_cost = startup_cost + run_cost;
1755 }
bool enable_sort
Definition: costsize.c:130
double random_page_cost
Definition: costsize.c:112
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5319
Cost total_cost
Definition: relation.h:1058
#define LOG2(x)
Definition: costsize.c:101
double rows
Definition: relation.h:1056
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2351
double seq_page_cost
Definition: costsize.c:111
double Cost
Definition: nodes.h:644

◆ cost_subplan()

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

Definition at line 3511 of file costsize.c.

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::plan_rows, QualCost::startup, Plan::startup_cost, SubPlan::startup_cost, SubPlan::subLinkType, SubPlan::testexpr, Plan::total_cost, and SubPlan::useHashTable.

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

3512 {
3513  QualCost sp_cost;
3514 
3515  /* Figure any cost for evaluating the testexpr */
3516  cost_qual_eval(&sp_cost,
3517  make_ands_implicit((Expr *) subplan->testexpr),
3518  root);
3519 
3520  if (subplan->useHashTable)
3521  {
3522  /*
3523  * If we are using a hash table for the subquery outputs, then the
3524  * cost of evaluating the query is a one-time cost. We charge one
3525  * cpu_operator_cost per tuple for the work of loading the hashtable,
3526  * too.
3527  */
3528  sp_cost.startup += plan->total_cost +
3529  cpu_operator_cost * plan->plan_rows;
3530 
3531  /*
3532  * The per-tuple costs include the cost of evaluating the lefthand
3533  * expressions, plus the cost of probing the hashtable. We already
3534  * accounted for the lefthand expressions as part of the testexpr, and
3535  * will also have counted one cpu_operator_cost for each comparison
3536  * operator. That is probably too low for the probing cost, but it's
3537  * hard to make a better estimate, so live with it for now.
3538  */
3539  }
3540  else
3541  {
3542  /*
3543  * Otherwise we will be rescanning the subplan output on each
3544  * evaluation. We need to estimate how much of the output we will
3545  * actually need to scan. NOTE: this logic should agree with the
3546  * tuple_fraction estimates used by make_subplan() in
3547  * plan/subselect.c.
3548  */
3549  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3550 
3551  if (subplan->subLinkType == EXISTS_SUBLINK)
3552  {
3553  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3554  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3555  }
3556  else if (subplan->subLinkType == ALL_SUBLINK ||
3557  subplan->subLinkType == ANY_SUBLINK)
3558  {
3559  /* assume we need 50% of the tuples */
3560  sp_cost.per_tuple += 0.50 * plan_run_cost;
3561  /* also charge a cpu_operator_cost per row examined */
3562  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3563  }
3564  else
3565  {
3566  /* assume we need all tuples */
3567  sp_cost.per_tuple += plan_run_cost;
3568  }
3569 
3570  /*
3571  * Also account for subplan's startup cost. If the subplan is
3572  * uncorrelated or undirect correlated, AND its topmost node is one
3573  * that materializes its output, assume that we'll only need to pay
3574  * its startup cost once; otherwise assume we pay the startup cost
3575  * every time.
3576  */
3577  if (subplan->parParam == NIL &&
3579  sp_cost.startup += plan->startup_cost;
3580  else
3581  sp_cost.per_tuple += plan->startup_cost;
3582  }
3583 
3584  subplan->startup_cost = sp_cost.startup;
3585  subplan->per_call_cost = sp_cost.per_tuple;
3586 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:131
SubLinkType subLinkType
Definition: primnodes.h:684
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:381
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Cost startup_cost
Definition: plannodes.h:125
double cpu_operator_cost
Definition: costsize.c:115
Node * testexpr
Definition: primnodes.h:686
Cost per_call_cost
Definition: primnodes.h:713
List * parParam
Definition: primnodes.h:709
#define nodeTag(nodeptr)
Definition: nodes.h:518
Cost total_cost
Definition: plannodes.h:126
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:577
bool useHashTable
Definition: primnodes.h:698
Cost startup_cost
Definition: primnodes.h:712
double clamp_row_est(double nrows)
Definition: costsize.c:185
double Cost
Definition: nodes.h:644

◆ cost_subqueryscan()

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

Definition at line 1281 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), SubqueryScanPath::path, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::rows, Path::rows, RTE_SUBQUERY, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, SubqueryScanPath::subpath, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_subqueryscan_path().

1283 {
1284  Cost startup_cost;
1285  Cost run_cost;
1286  QualCost qpqual_cost;
1287  Cost cpu_per_tuple;
1288 
1289  /* Should only be applied to base relations that are subqueries */
1290  Assert(baserel->relid > 0);
1291  Assert(baserel->rtekind == RTE_SUBQUERY);
1292 
1293  /* Mark the path with the correct row estimate */
1294  if (param_info)
1295  path->path.rows = param_info->ppi_rows;
1296  else
1297  path->path.rows = baserel->rows;
1298 
1299  /*
1300  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1301  * any restriction clauses and tlist that will be attached to the
1302  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1303  * projection overhead.
1304  */
1305  path->path.startup_cost = path->subpath->startup_cost;
1306  path->path.total_cost = path->subpath->total_cost;
1307 
1308  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1309 
1310  startup_cost = qpqual_cost.startup;
1311  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1312  run_cost = cpu_per_tuple * baserel->tuples;
1313 
1314  /* tlist eval costs are paid per output row, not per tuple scanned */
1315  startup_cost += path->path.pathtarget->cost.startup;
1316  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1317 
1318  path->path.startup_cost += startup_cost;
1319  path->path.total_cost += startup_cost + run_cost;
1320 }
PathTarget * pathtarget
Definition: relation.h:1047
double tuples
Definition: relation.h:625
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:1057
Index relid
Definition: relation.h:613
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
double Cost
Definition: nodes.h:644

◆ cost_tableexprscan()

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

◆ cost_tablefuncscan()

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

Definition at line 1391 of file costsize.c.

References Assert, PathTarget::cost, cost_qual_eval_node(), cpu_tuple_cost, get_restriction_qual_cost(), Path::pathtarget, QualCost::per_tuple, planner_rt_fetch, ParamPathInfo::ppi_rows, RelOptInfo::relid, 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().

1393 {
1394  Cost startup_cost = 0;
1395  Cost run_cost = 0;
1396  QualCost qpqual_cost;
1397  Cost cpu_per_tuple;
1398  RangeTblEntry *rte;
1399  QualCost exprcost;
1400 
1401  /* Should only be applied to base relations that are functions */
1402  Assert(baserel->relid > 0);
1403  rte = planner_rt_fetch(baserel->relid, root);
1404  Assert(rte->rtekind == RTE_TABLEFUNC);
1405 
1406  /* Mark the path with the correct row estimate */
1407  if (param_info)
1408  path->rows = param_info->ppi_rows;
1409  else
1410  path->rows = baserel->rows;
1411 
1412  /*
1413  * Estimate costs of executing the table func expression(s).
1414  *
1415  * XXX in principle we ought to charge tuplestore spill costs if the
1416  * number of rows is large. However, given how phony our rowcount
1417  * estimates for tablefuncs tend to be, there's not a lot of point in that
1418  * refinement right now.
1419  */
1420  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1421 
1422  startup_cost += exprcost.startup + exprcost.per_tuple;
1423 
1424  /* Add scanning CPU costs */
1425  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1426 
1427  startup_cost += qpqual_cost.startup;
1428  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1429  run_cost += cpu_per_tuple * baserel->tuples;
1430 
1431  /* tlist eval costs are paid per output row, not per tuple scanned */
1432  startup_cost += path->pathtarget->cost.startup;
1433  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1434 
1435  path->startup_cost = startup_cost;
1436  path->total_cost = startup_cost + run_cost;
1437 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3737
PathTarget * pathtarget
Definition: relation.h:1047
double tuples
Definition: relation.h:625
Definition: nodes.h:513
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
TableFunc * tablefunc
Definition: parsenodes.h:1019
Cost startup_cost
Definition: relation.h:1057
Index relid
Definition: relation.h:613
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
RTEKind rtekind
Definition: parsenodes.h:959
double Cost
Definition: nodes.h:644

◆ cost_tidscan()

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

Definition at line 1178 of file costsize.c.

References ScalarArrayOpExpr::args, Assert, RelOptInfo::baserestrictcost, PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_tidscan, estimate_array_length(), get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, lfirst, lsecond, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, RelOptInfo::relid, RelOptInfo::reltablespace, RelOptInfo::rows, Path::rows, RTE_RELATION, RelOptInfo::rtekind, QualCost::startup, Path::startup_cost, and Path::total_cost.

Referenced by create_tidscan_path().

1180 {
1181  Cost startup_cost = 0;
1182  Cost run_cost = 0;
1183  bool isCurrentOf = false;
1184  QualCost qpqual_cost;
1185  Cost cpu_per_tuple;
1186  QualCost tid_qual_cost;
1187  int ntuples;
1188  ListCell *l;
1189  double spc_random_page_cost;
1190 
1191  /* Should only be applied to base relations */
1192  Assert(baserel->relid > 0);
1193  Assert(baserel->rtekind == RTE_RELATION);
1194 
1195  /* Mark the path with the correct row estimate */
1196  if (param_info)
1197  path->rows = param_info->ppi_rows;
1198  else
1199  path->rows = baserel->rows;
1200 
1201  /* Count how many tuples we expect to retrieve */
1202  ntuples = 0;
1203  foreach(l, tidquals)
1204  {
1205  if (IsA(lfirst(l), ScalarArrayOpExpr))
1206  {
1207  /* Each element of the array yields 1 tuple */
1209  Node *arraynode = (Node *) lsecond(saop->args);
1210 
1211  ntuples += estimate_array_length(arraynode);
1212  }
1213  else if (IsA(lfirst(l), CurrentOfExpr))
1214  {
1215  /* CURRENT OF yields 1 tuple */
1216  isCurrentOf = true;
1217  ntuples++;
1218  }
1219  else
1220  {
1221  /* It's just CTID = something, count 1 tuple */
1222  ntuples++;
1223  }
1224  }
1225 
1226  /*
1227  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1228  * understands how to do it correctly. Therefore, honor enable_tidscan
1229  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1230  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1231  * subtract off here; that's to prevent other plan types such as seqscan
1232  * from winning.
1233  */
1234  if (isCurrentOf)
1235  {
1237  startup_cost -= disable_cost;
1238  }
1239  else if (!enable_tidscan)
1240  startup_cost += disable_cost;
1241 
1242  /*
1243  * The TID qual expressions will be computed once, any other baserestrict
1244  * quals once per retrieved tuple.
1245  */
1246  cost_qual_eval(&tid_qual_cost, tidquals, root);
1247 
1248  /* fetch estimated page cost for tablespace containing table */
1250  &spc_random_page_cost,
1251  NULL);
1252 
1253  /* disk costs --- assume each tuple on a different page */
1254  run_cost += spc_random_page_cost * ntuples;
1255 
1256  /* Add scanning CPU costs */
1257  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1258 
1259  /* XXX currently we assume TID quals are a subset of qpquals */
1260  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1261  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1262  tid_qual_cost.per_tuple;
1263  run_cost += cpu_per_tuple * ntuples;
1264 
1265  /* tlist eval costs are paid per output row, not per tuple scanned */
1266  startup_cost += path->pathtarget->cost.startup;
1267  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1268 
1269  path->startup_cost = startup_cost;
1270  path->total_cost = startup_cost + run_cost;
1271 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
PathTarget * pathtarget
Definition: relation.h:1047
bool enable_tidscan
Definition: costsize.c:129
Oid reltablespace
Definition: relation.h:614
Definition: nodes.h:513
#define lsecond(l)
Definition: pg_list.h:116
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2167
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:182
Index relid
Definition: relation.h:613
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
QualCost baserestrictcost
Definition: relation.h:646
double Cost
Definition: nodes.h:644

◆ cost_valuesscan()

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

Definition at line 1447 of file costsize.c.

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

Referenced by create_valuesscan_path().

1449 {
1450  Cost startup_cost = 0;
1451  Cost run_cost = 0;
1452  QualCost qpqual_cost;
1453  Cost cpu_per_tuple;
1454 
1455  /* Should only be applied to base relations that are values lists */
1456  Assert(baserel->relid > 0);
1457  Assert(baserel->rtekind == RTE_VALUES);
1458 
1459  /* Mark the path with the correct row estimate */
1460  if (param_info)
1461  path->rows = param_info->ppi_rows;
1462  else
1463  path->rows = baserel->rows;
1464 
1465  /*
1466  * For now, estimate list evaluation cost at one operator eval per list
1467  * (probably pretty bogus, but is it worth being smarter?)
1468  */
1469  cpu_per_tuple = cpu_operator_cost;
1470 
1471  /* Add scanning CPU costs */
1472  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1473 
1474  startup_cost += qpqual_cost.startup;
1475  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1476  run_cost += cpu_per_tuple * baserel->tuples;
1477 
1478  /* tlist eval costs are paid per output row, not per tuple scanned */
1479  startup_cost += path->pathtarget->cost.startup;
1480  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1481 
1482  path->startup_cost = startup_cost;
1483  path->total_cost = startup_cost + run_cost;
1484 }
PathTarget * pathtarget
Definition: relation.h:1047
double tuples
Definition: relation.h:625
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:1057
double cpu_operator_cost
Definition: costsize.c:115
Index relid
Definition: relation.h:613
RTEKind rtekind
Definition: relation.h:615
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3990
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
double Cost
Definition: nodes.h:644

◆ cost_windowagg()

void cost_windowagg ( Path path,
PlannerInfo root,
List windowFuncs,
int  numPartCols,
int  numOrderCols,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 2175 of file costsize.c.

References WindowFunc::aggfilter, WindowFunc::args, cost_qual_eval_node(), cpu_operator_cost, cpu_tuple_cost, get_func_cost(), lfirst_node, QualCost::per_tuple, Path::rows, QualCost::startup, Path::startup_cost, Path::total_cost, and WindowFunc::winfnoid.

Referenced by create_windowagg_path().

2179 {
2180  Cost startup_cost;
2181  Cost total_cost;
2182  ListCell *lc;
2183 
2184  startup_cost = input_startup_cost;
2185  total_cost = input_total_cost;
2186 
2187  /*
2188  * Window functions are assumed to cost their stated execution cost, plus
2189  * the cost of evaluating their input expressions, per tuple. Since they
2190  * may in fact evaluate their inputs at multiple rows during each cycle,
2191  * this could be a drastic underestimate; but without a way to know how
2192  * many rows the window function will fetch, it's hard to do better. In
2193  * any case, it's a good estimate for all the built-in window functions,
2194  * so we'll just do this for now.
2195  */
2196  foreach(lc, windowFuncs)
2197  {
2198  WindowFunc *wfunc = lfirst_node(WindowFunc, lc);
2199  Cost wfunccost;
2200  QualCost argcosts;
2201 
2202  wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
2203 
2204  /* also add the input expressions' cost to per-input-row costs */
2205  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
2206  startup_cost += argcosts.startup;
2207  wfunccost += argcosts.per_tuple;
2208 
2209  /*
2210  * Add the filter's cost to per-input-row costs. XXX We should reduce
2211  * input expression costs according to filter selectivity.
2212  */
2213  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
2214  startup_cost += argcosts.startup;
2215  wfunccost += argcosts.per_tuple;
2216 
2217  total_cost += wfunccost * input_tuples;
2218  }
2219 
2220  /*
2221  * We also charge cpu_operator_cost per grouping column per tuple for
2222  * grouping comparisons, plus cpu_tuple_cost per tuple for general
2223  * overhead.
2224  *
2225  * XXX this neglects costs of spooling the data to disk when it overflows
2226  * work_mem. Sooner or later that should get accounted for.
2227  */
2228  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
2229  total_cost += cpu_tuple_cost * input_tuples;
2230 
2231  path->rows = input_tuples;
2232  path->startup_cost = startup_cost;
2233  path->total_cost = total_cost;
2234 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3737
List * args
Definition: primnodes.h:359
Definition: nodes.h:513
float4 get_func_cost(Oid funcid)
Definition: lsyscache.c:1645
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:1057
#define lfirst_node(type, lc)
Definition: pg_list.h:109
double cpu_operator_cost
Definition: costsize.c:115
Oid winfnoid
Definition: primnodes.h:355
Cost total_cost
Definition: relation.h:1058
Expr * aggfilter
Definition: primnodes.h:360
double rows
Definition: relation.h:1056
double cpu_tuple_cost
Definition: costsize.c:113
double Cost
Definition: nodes.h:644

◆ final_cost_hashjoin()

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

Definition at line 3256 of file costsize.c.

References approx_tuple_count(), Assert, bms_is_subset(), clamp_row_est(), RestrictInfo::clause, PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_hashjoin, estimate_hash_bucket_stats(), get_leftop(), get_parallel_divisor(), get_rightop(), HashPath::inner_rows_total, JoinCostWorkspace::inner_rows_total, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, RestrictInfo::left_bucketsize, RestrictInfo::left_mcvfreq, RestrictInfo::left_relids, lfirst_node, SemiAntiJoinFactors::match_count, HashPath::num_batches, JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, HashPath::path_hashclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::relids, RestrictInfo::right_bucketsize, RestrictInfo::right_mcvfreq, RestrictInfo::right_relids, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_hashjoin_path().

3259 {
3260  Path *outer_path = path->jpath.outerjoinpath;
3261  Path *inner_path = path->jpath.innerjoinpath;
3262  double outer_path_rows = outer_path->rows;
3263  double inner_path_rows = inner_path->rows;
3264  double inner_path_rows_total = workspace->inner_rows_total;
3265  List *hashclauses = path->path_hashclauses;
3266  Cost startup_cost = workspace->startup_cost;
3267  Cost run_cost = workspace->run_cost;
3268  int numbuckets = workspace->numbuckets;
3269  int numbatches = workspace->numbatches;
3270  Cost cpu_per_tuple;
3271  QualCost hash_qual_cost;
3272  QualCost qp_qual_cost;
3273  double hashjointuples;
3274  double virtualbuckets;
3275  Selectivity innerbucketsize;
3276  Selectivity innermcvfreq;
3277  ListCell *hcl;
3278 
3279  /* Mark the path with the correct row estimate */
3280  if (path->jpath.path.param_info)
3281  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
3282  else
3283  path->jpath.path.rows = path->jpath.path.parent->rows;
3284 
3285  /* For partial paths, scale row estimate. */
3286  if (path->jpath.path.parallel_workers > 0)
3287  {
3288  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
3289 
3290  path->jpath.path.rows =
3291  clamp_row_est(path->jpath.path.rows / parallel_divisor);
3292  }
3293 
3294  /*
3295  * We could include disable_cost in the preliminary estimate, but that
3296  * would amount to optimizing for the case where the join method is
3297  * disabled, which doesn't seem like the way to bet.
3298  */
3299  if (!enable_hashjoin)
3300  startup_cost += disable_cost;
3301 
3302  /* mark the path with estimated # of batches */
3303  path->num_batches = numbatches;
3304 
3305  /* store the total number of tuples (sum of partial row estimates) */
3306  path->inner_rows_total = inner_path_rows_total;
3307 
3308  /* and compute the number of "virtual" buckets in the whole join */
3309  virtualbuckets = (double) numbuckets * (double) numbatches;
3310 
3311  /*
3312  * Determine bucketsize fraction and MCV frequency for the inner relation.
3313  * We use the smallest bucketsize or MCV frequency estimated for any
3314  * individual hashclause; this is undoubtedly conservative.
3315  *
3316  * BUT: if inner relation has been unique-ified, we can assume it's good
3317  * for hashing. This is important both because it's the right answer, and
3318  * because we avoid contaminating the cache with a value that's wrong for
3319  * non-unique-ified paths.
3320  */
3321  if (IsA(inner_path, UniquePath))
3322  {
3323  innerbucketsize = 1.0 / virtualbuckets;
3324  innermcvfreq = 0.0;
3325  }
3326  else
3327  {
3328  innerbucketsize = 1.0;
3329  innermcvfreq = 1.0;
3330  foreach(hcl, hashclauses)
3331  {
3332  RestrictInfo *restrictinfo = lfirst_node(RestrictInfo, hcl);
3333  Selectivity thisbucketsize;
3334  Selectivity thismcvfreq;
3335 
3336  /*
3337  * First we have to figure out which side of the hashjoin clause
3338  * is the inner side.
3339  *
3340  * Since we tend to visit the same clauses over and over when
3341  * planning a large query, we cache the bucket stats estimates in
3342  * the RestrictInfo node to avoid repeated lookups of statistics.
3343  */
3344  if (bms_is_subset(restrictinfo->right_relids,
3345  inner_path->parent->relids))
3346  {
3347  /* righthand side is inner */
3348  thisbucketsize = restrictinfo->right_bucketsize;
3349  if (thisbucketsize < 0)
3350  {
3351  /* not cached yet */
3353  get_rightop(restrictinfo->clause),
3354  virtualbuckets,
3355  &restrictinfo->right_mcvfreq,
3356  &restrictinfo->right_bucketsize);
3357  thisbucketsize = restrictinfo->right_bucketsize;
3358  }
3359  thismcvfreq = restrictinfo->right_mcvfreq;
3360  }
3361  else
3362  {
3363  Assert(bms_is_subset(restrictinfo->left_relids,
3364  inner_path->parent->relids));
3365  /* lefthand side is inner */
3366  thisbucketsize = restrictinfo->left_bucketsize;
3367  if (thisbucketsize < 0)
3368  {
3369  /* not cached yet */
3371  get_leftop(restrictinfo->clause),
3372  virtualbuckets,
3373  &restrictinfo->left_mcvfreq,
3374  &restrictinfo->left_bucketsize);
3375  thisbucketsize = restrictinfo->left_bucketsize;
3376  }
3377  thismcvfreq = restrictinfo->left_mcvfreq;
3378  }
3379 
3380  if (innerbucketsize > thisbucketsize)
3381  innerbucketsize = thisbucketsize;
3382  if (innermcvfreq > thismcvfreq)
3383  innermcvfreq = thismcvfreq;
3384  }
3385  }
3386 
3387  /*
3388  * If the bucket holding the inner MCV would exceed work_mem, we don't
3389  * want to hash unless there is really no other alternative, so apply
3390  * disable_cost. (The executor normally copes with excessive memory usage
3391  * by splitting batches, but obviously it cannot separate equal values
3392  * that way, so it will be unable to drive the batch size below work_mem
3393  * when this is true.)
3394  */
3395  if (relation_byte_size(clamp_row_est(inner_path_rows * innermcvfreq),
3396  inner_path->pathtarget->width) >
3397  (work_mem * 1024L))
3398  startup_cost += disable_cost;
3399 
3400  /*
3401  * Compute cost of the hashquals and qpquals (other restriction clauses)
3402  * separately.
3403  */
3404  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3405  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3406  qp_qual_cost.startup -= hash_qual_cost.startup;
3407  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
3408 
3409  /* CPU costs */
3410 
3411  if (path->jpath.jointype == JOIN_SEMI ||
3412  path->jpath.jointype == JOIN_ANTI ||
3413  extra->inner_unique)
3414  {
3415  double outer_matched_rows;
3416  Selectivity inner_scan_frac;
3417 
3418  /*
3419  * With a SEMI or ANTI join, or if the innerrel is known unique, the
3420  * executor will stop after the first match.
3421  *
3422  * For an outer-rel row that has at least one match, we can expect the
3423  * bucket scan to stop after a fraction 1/(match_count+1) of the
3424  * bucket's rows, if the matches are evenly distributed. Since they
3425  * probably aren't quite evenly distributed, we apply a fuzz factor of
3426  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
3427  * to clamp inner_scan_frac to at most 1.0; but since match_count is
3428  * at least 1, no such clamp is needed now.)
3429  */
3430  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
3431  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
3432 
3433  startup_cost += hash_qual_cost.startup;
3434  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
3435  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
3436 
3437  /*
3438  * For unmatched outer-rel rows, the picture is quite a lot different.
3439  * In the first place, there is no reason to assume that these rows
3440  * preferentially hit heavily-populated buckets; instead assume they
3441  * are uncorrelated with the inner distribution and so they see an
3442  * average bucket size of inner_path_rows / virtualbuckets. In the
3443  * second place, it seems likely that they will have few if any exact
3444  * hash-code matches and so very few of the tuples in the bucket will
3445  * actually require eval of the hash quals. We don't have any good
3446  * way to estimate how many will, but for the moment assume that the
3447  * effective cost per bucket entry is one-tenth what it is for
3448  * matchable tuples.
3449  */
3450  run_cost += hash_qual_cost.per_tuple *
3451  (outer_path_rows - outer_matched_rows) *
3452  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
3453 
3454  /* Get # of tuples that will pass the basic join */
3455  if (path->jpath.jointype == JOIN_SEMI)
3456  hashjointuples = outer_matched_rows;
3457  else
3458  hashjointuples = outer_path_rows - outer_matched_rows;
3459  }
3460  else
3461  {
3462  /*
3463  * The number of tuple comparisons needed is the number of outer
3464  * tuples times the typical number of tuples in a hash bucket, which
3465  * is the inner relation size times its bucketsize fraction. At each
3466  * one, we need to evaluate the hashjoin quals. But actually,
3467  * charging the full qual eval cost at each tuple is pessimistic,
3468  * since we don't evaluate the quals unless the hash values match
3469  * exactly. For lack of a better idea, halve the cost estimate to
3470  * allow for that.
3471  */
3472  startup_cost += hash_qual_cost.startup;
3473  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
3474  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
3475 
3476  /*
3477  * Get approx # tuples passing the hashquals. We use
3478  * approx_tuple_count here because we need an estimate done with
3479  * JOIN_INNER semantics.
3480  */
3481  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
3482  }
3483 
3484  /*
3485  * For each tuple that gets through the hashjoin proper, we charge
3486  * cpu_tuple_cost plus the cost of evaluating additional restriction
3487  * clauses that are to be applied at the join. (This is pessimistic since
3488  * not all of the quals may get evaluated at each tuple.)
3489  */
3490  startup_cost += qp_qual_cost.startup;
3491  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3492  run_cost += cpu_per_tuple * hashjointuples;
3493 
3494  /* tlist eval costs are paid per output row, not per tuple scanned */
3495  startup_cost += path->jpath.path.pathtarget->cost.startup;
3496  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3497 
3498  path->jpath.path.startup_cost = startup_cost;
3499  path->jpath.path.total_cost = startup_cost + run_cost;
3500 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
JoinPath jpath
Definition: relation.h:1468
PathTarget * pathtarget
Definition: relation.h:1047
SemiAntiJoinFactors semifactors
Definition: relation.h:2288
int num_batches
Definition: relation.h:1470
Selectivity right_mcvfreq
Definition: relation.h:1911
Selectivity outer_match_frac
Definition: relation.h:2265
Path * innerjoinpath
Definition: relation.h:1395
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4232
int parallel_workers
Definition: relation.h:1053
ParamPathInfo * param_info
Definition: relation.h:1049
Relids left_relids
Definition: relation.h:1874
double Selectivity
Definition: nodes.h:643
double inner_rows_total
Definition: relation.h:1471
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Node * get_leftop(const Expr *clause)
Definition: clauses.c:202
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
List * joinrestrictinfo
Definition: relation.h:1397
RelOptInfo * parent
Definition: relation.h:1046
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:352
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
Relids relids
Definition: relation.h:585
double rint(double x)
Definition: rint.c:22
Expr * clause
Definition: relation.h:1847
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5319
Path * outerjoinpath
Definition: relation.h:1394
double inner_rows_total
Definition: relation.h:2326
int work_mem
Definition: globals.c:113
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
Selectivity left_bucketsize
Definition: relation.h:1908
Relids right_relids
Definition: relation.h:1875
Path path
Definition: relation.h:1387
#define Assert(condition)
Definition: c.h:688
double rows
Definition: relation.h:1056
Selectivity left_mcvfreq
Definition: relation.h:1910
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
Node * get_rightop(const Expr *clause)
Definition: clauses.c:219
double ppi_rows
Definition: relation.h:1006
bool enable_hashjoin
Definition: costsize.c:135
int width
Definition: relation.h:979
Selectivity match_count
Definition: relation.h:2266
Selectivity right_bucketsize
Definition: relation.h:1909
JoinType jointype
Definition: relation.h:1389
void estimate_hash_bucket_stats(PlannerInfo *root, Node *hashkey, double nbuckets, Selectivity *mcv_freq, Selectivity *bucketsize_frac)
Definition: selfuncs.c:3761
List * path_hashclauses
Definition: relation.h:1469
double clamp_row_est(double nrows)
Definition: costsize.c:185
Definition: pg_list.h:45
double Cost
Definition: nodes.h:644

◆ final_cost_mergejoin()

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

Definition at line 2827 of file costsize.c.

References approx_tuple_count(), clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_material, enable_mergejoin, ExecSupportsMarkRestore(), get_parallel_divisor(), JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, MergePath::innersortkeys, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, MergePath::jpath, list_length(), MergePath::materialize_inner, NIL, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, MergePath::path_mergeclauses, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, relation_byte_size(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, MergePath::skip_mark_restore, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_mergejoin_path().

2830 {
2831  Path *outer_path = path->jpath.outerjoinpath;
2832  Path *inner_path = path->jpath.innerjoinpath;
2833  double inner_path_rows = inner_path->rows;
2834  List *mergeclauses = path->path_mergeclauses;
2835  List *innersortkeys = path->innersortkeys;
2836  Cost startup_cost = workspace->startup_cost;
2837  Cost run_cost = workspace->run_cost;
2838  Cost inner_run_cost = workspace->inner_run_cost;
2839  double outer_rows = workspace->outer_rows;
2840  double inner_rows = workspace->inner_rows;
2841  double outer_skip_rows = workspace->outer_skip_rows;
2842  double inner_skip_rows = workspace->inner_skip_rows;
2843  Cost cpu_per_tuple,
2844  bare_inner_cost,
2845  mat_inner_cost;
2846  QualCost merge_qual_cost;
2847  QualCost qp_qual_cost;
2848  double mergejointuples,
2849  rescannedtuples;
2850  double rescanratio;
2851 
2852  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2853  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2854  inner_path_rows = 1;
2855 
2856  /* Mark the path with the correct row estimate */
2857  if (path->jpath.path.param_info)
2858  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2859  else
2860  path->jpath.path.rows = path->jpath.path.parent->rows;
2861 
2862  /* For partial paths, scale row estimate. */
2863  if (path->jpath.path.parallel_workers > 0)
2864  {
2865  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
2866 
2867  path->jpath.path.rows =
2868  clamp_row_est(path->jpath.path.rows / parallel_divisor);
2869  }
2870 
2871  /*
2872  * We could include disable_cost in the preliminary estimate, but that
2873  * would amount to optimizing for the case where the join method is
2874  * disabled, which doesn't seem like the way to bet.
2875  */
2876  if (!enable_mergejoin)
2877  startup_cost += disable_cost;
2878 
2879  /*
2880  * Compute cost of the mergequals and qpquals (other restriction clauses)
2881  * separately.
2882  */
2883  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2884  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2885  qp_qual_cost.startup -= merge_qual_cost.startup;
2886  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2887 
2888  /*
2889  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2890  * executor will stop scanning for matches after the first match. When
2891  * all the joinclauses are merge clauses, this means we don't ever need to
2892  * back up the merge, and so we can skip mark/restore overhead.
2893  */
2894  if ((path->jpath.jointype == JOIN_SEMI ||
2895  path->jpath.jointype == JOIN_ANTI ||
2896  extra->inner_unique) &&
2899  path->skip_mark_restore = true;
2900  else
2901  path->skip_mark_restore = false;
2902 
2903  /*
2904  * Get approx # tuples passing the mergequals. We use approx_tuple_count
2905  * here because we need an estimate done with JOIN_INNER semantics.
2906  */
2907  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2908 
2909  /*
2910  * When there are equal merge keys in the outer relation, the mergejoin
2911  * must rescan any matching tuples in the inner relation. This means
2912  * re-fetching inner tuples; we have to estimate how often that happens.
2913  *
2914  * For regular inner and outer joins, the number of re-fetches can be
2915  * estimated approximately as size of merge join output minus size of
2916  * inner relation. Assume that the distinct key values are 1, 2, ..., and
2917  * denote the number of values of each key in the outer relation as m1,
2918  * m2, ...; in the inner relation, n1, n2, ... Then we have
2919  *
2920  * size of join = m1 * n1 + m2 * n2 + ...
2921  *
2922  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2923  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2924  * relation
2925  *
2926  * This equation works correctly for outer tuples having no inner match
2927  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2928  * are effectively subtracting those from the number of rescanned tuples,
2929  * when we should not. Can we do better without expensive selectivity
2930  * computations?
2931  *
2932  * The whole issue is moot if we are working from a unique-ified outer
2933  * input, or if we know we don't need to mark/restore at all.
2934  */
2935  if (IsA(outer_path, UniquePath) ||path->skip_mark_restore)
2936  rescannedtuples = 0;
2937  else
2938  {
2939  rescannedtuples = mergejointuples - inner_path_rows;
2940  /* Must clamp because of possible underestimate */
2941  if (rescannedtuples < 0)
2942  rescannedtuples = 0;
2943  }
2944  /* We'll inflate various costs this much to account for rescanning */
2945  rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
2946 
2947  /*
2948  * Decide whether we want to materialize the inner input to shield it from
2949  * mark/restore and performing re-fetches. Our cost model for regular
2950  * re-fetches is that a re-fetch costs the same as an original fetch,
2951  * which is probably an overestimate; but on the other hand we ignore the
2952  * bookkeeping costs of mark/restore. Not clear if it's worth developing
2953  * a more refined model. So we just need to inflate the inner run cost by
2954  * rescanratio.
2955  */
2956  bare_inner_cost = inner_run_cost * rescanratio;
2957 
2958  /*
2959  * When we interpose a Material node the re-fetch cost is assumed to be
2960  * just cpu_operator_cost per tuple, independently of the underlying
2961  * plan's cost; and we charge an extra cpu_operator_cost per original
2962  * fetch as well. Note that we're assuming the materialize node will
2963  * never spill to disk, since it only has to remember tuples back to the
2964  * last mark. (If there are a huge number of duplicates, our other cost
2965  * factors will make the path so expensive that it probably won't get
2966  * chosen anyway.) So we don't use cost_rescan here.
2967  *
2968  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
2969  * of the generated Material node.
2970  */
2971  mat_inner_cost = inner_run_cost +
2972  cpu_operator_cost * inner_path_rows * rescanratio;
2973 
2974  /*
2975  * If we don't need mark/restore at all, we don't need materialization.
2976  */
2977  if (path->skip_mark_restore)
2978  path->materialize_inner = false;
2979 
2980  /*
2981  * Prefer materializing if it looks cheaper, unless the user has asked to
2982  * suppress materialization.
2983  */
2984  else if (enable_material && mat_inner_cost < bare_inner_cost)
2985  path->materialize_inner = true;
2986 
2987  /*
2988  * Even if materializing doesn't look cheaper, we *must* do it if the
2989  * inner path is to be used directly (without sorting) and it doesn't
2990  * support mark/restore.
2991  *
2992  * Since the inner side must be ordered, and only Sorts and IndexScans can
2993  * create order to begin with, and they both support mark/restore, you
2994  * might think there's no problem --- but you'd be wrong. Nestloop and
2995  * merge joins can *preserve* the order of their inputs, so they can be
2996  * selected as the input of a mergejoin, and they don't support
2997  * mark/restore at present.
2998  *
2999  * We don't test the value of enable_material here, because
3000  * materialization is required for correctness in this case, and turning
3001  * it off does not entitle us to deliver an invalid plan.
3002  */
3003  else if (innersortkeys == NIL &&
3004  !ExecSupportsMarkRestore(inner_path))
3005  path->materialize_inner = true;
3006 
3007  /*
3008  * Also, force materializing if the inner path is to be sorted and the
3009  * sort is expected to spill to disk. This is because the final merge
3010  * pass can be done on-the-fly if it doesn't have to support mark/restore.
3011  * We don't try to adjust the cost estimates for this consideration,
3012  * though.
3013  *
3014  * Since materialization is a performance optimization in this case,
3015  * rather than necessary for correctness, we skip it if enable_material is
3016  * off.
3017  */
3018  else if (enable_material && innersortkeys != NIL &&
3019  relation_byte_size(inner_path_rows,
3020  inner_path->pathtarget->width) >
3021  (work_mem * 1024L))
3022  path->materialize_inner = true;
3023  else
3024  path->materialize_inner = false;
3025 
3026  /* Charge the right incremental cost for the chosen case */
3027  if (path->materialize_inner)
3028  run_cost += mat_inner_cost;
3029  else
3030  run_cost += bare_inner_cost;
3031 
3032  /* CPU costs */
3033 
3034  /*
3035  * The number of tuple comparisons needed is approximately number of outer
3036  * rows plus number of inner rows plus number of rescanned tuples (can we
3037  * refine this?). At each one, we need to evaluate the mergejoin quals.
3038  */
3039  startup_cost += merge_qual_cost.startup;
3040  startup_cost += merge_qual_cost.per_tuple *
3041  (outer_skip_rows + inner_skip_rows * rescanratio);
3042  run_cost += merge_qual_cost.per_tuple *
3043  ((outer_rows - outer_skip_rows) +
3044  (inner_rows - inner_skip_rows) * rescanratio);
3045 
3046  /*
3047  * For each tuple that gets through the mergejoin proper, we charge
3048  * cpu_tuple_cost plus the cost of evaluating additional restriction
3049  * clauses that are to be applied at the join. (This is pessimistic since
3050  * not all of the quals may get evaluated at each tuple.)
3051  *
3052  * Note: we could adjust for SEMI/ANTI joins skipping some qual
3053  * evaluations here, but it's probably not worth the trouble.
3054  */
3055  startup_cost += qp_qual_cost.startup;
3056  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3057  run_cost += cpu_per_tuple * mergejointuples;
3058 
3059  /* tlist eval costs are paid per output row, not per tuple scanned */
3060  startup_cost += path->jpath.path.pathtarget->cost.startup;
3061  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3062 
3063  path->jpath.path.startup_cost = startup_cost;
3064  path->jpath.path.total_cost = startup_cost + run_cost;
3065 }
#define NIL
Definition: pg_list.h:69
List * path_mergeclauses
Definition: relation.h:1450
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
PathTarget * pathtarget
Definition: relation.h:1047
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:405
bool materialize_inner
Definition: relation.h:1454
Path * innerjoinpath
Definition: relation.h:1395
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:4232
int parallel_workers
Definition: relation.h:1053
ParamPathInfo * param_info
Definition: relation.h:1049
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
bool skip_mark_restore
Definition: relation.h:1453
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
List * joinrestrictinfo
Definition: relation.h:1397
RelOptInfo * parent
Definition: relation.h:1046
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
double cpu_operator_cost
Definition: costsize.c:115
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:5319
Path * outerjoinpath
Definition: relation.h:1394
int work_mem
Definition: globals.c:113
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
double outer_skip_rows
Definition: relation.h:2320
bool enable_mergejoin
Definition: costsize.c:134
Path path
Definition: relation.h:1387
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
static int list_length(const List *l)
Definition: pg_list.h:89
List * innersortkeys
Definition: relation.h:1452
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
int width
Definition: relation.h:979
JoinType jointype
Definition: relation.h:1389
JoinPath jpath
Definition: relation.h:1449
double inner_skip_rows
Definition: relation.h:2321
double clamp_row_est(double nrows)
Definition: costsize.c:185
Definition: pg_list.h:45
double Cost
Definition: nodes.h:644
bool enable_material
Definition: costsize.c:133

◆ final_cost_nestloop()

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

Definition at line 2390 of file costsize.c.

References clamp_row_est(), PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_nestloop, get_parallel_divisor(), has_indexed_join_quals(), JoinCostWorkspace::inner_rescan_run_cost, JoinCostWorkspace::inner_run_cost, JoinPathExtraData::inner_unique, JoinPath::innerjoinpath, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, SemiAntiJoinFactors::match_count, SemiAntiJoinFactors::outer_match_frac, JoinPath::outerjoinpath, Path::parallel_workers, Path::param_info, Path::parent, JoinPath::path, Path::pathtarget, QualCost::per_tuple, ParamPathInfo::ppi_rows, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, JoinPathExtraData::semifactors, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, and Path::total_cost.

Referenced by create_nestloop_path().

2393 {
2394  Path *outer_path = path->outerjoinpath;
2395  Path *inner_path = path->innerjoinpath;
2396  double outer_path_rows = outer_path->rows;
2397  double inner_path_rows = inner_path->rows;
2398  Cost startup_cost = workspace->startup_cost;
2399  Cost run_cost = workspace->run_cost;
2400  Cost cpu_per_tuple;
2401  QualCost restrict_qual_cost;
2402  double ntuples;
2403 
2404  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2405  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2406  outer_path_rows = 1;
2407  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2408  inner_path_rows = 1;
2409 
2410  /* Mark the path with the correct row estimate */
2411  if (path->path.param_info)
2412  path->path.rows = path->path.param_info->ppi_rows;
2413  else
2414  path->path.rows = path->path.parent->rows;
2415 
2416  /* For partial paths, scale row estimate. */
2417  if (path->path.parallel_workers > 0)
2418  {
2419  double parallel_divisor = get_parallel_divisor(&path->path);
2420 
2421  path->path.rows =
2422  clamp_row_est(path->path.rows / parallel_divisor);
2423  }
2424 
2425  /*
2426  * We could include disable_cost in the preliminary estimate, but that
2427  * would amount to optimizing for the case where the join method is
2428  * disabled, which doesn't seem like the way to bet.
2429  */
2430  if (!enable_nestloop)
2431  startup_cost += disable_cost;
2432 
2433  /* cost of inner-relation source data (we already dealt with outer rel) */
2434 
2435  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI ||
2436  extra->inner_unique)
2437  {
2438  /*
2439  * With a SEMI or ANTI join, or if the innerrel is known unique, the
2440  * executor will stop after the first match.
2441  */
2442  Cost inner_run_cost = workspace->inner_run_cost;
2443  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2444  double outer_matched_rows;
2445  double outer_unmatched_rows;
2446  Selectivity inner_scan_frac;
2447 
2448  /*
2449  * For an outer-rel row that has at least one match, we can expect the
2450  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2451  * rows, if the matches are evenly distributed. Since they probably
2452  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2453  * that fraction. (If we used a larger fuzz factor, we'd have to
2454  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2455  * least 1, no such clamp is needed now.)
2456  */
2457  outer_matched_rows = rint(outer_path_rows * extra->semifactors.outer_match_frac);
2458  outer_unmatched_rows = outer_path_rows - outer_matched_rows;
2459  inner_scan_frac = 2.0 / (extra->semifactors.match_count + 1.0);
2460 
2461  /*
2462  * Compute number of tuples processed (not number emitted!). First,
2463  * account for successfully-matched outer rows.
2464  */
2465  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2466 
2467  /*
2468  * Now we need to estimate the actual costs of scanning the inner
2469  * relation, which may be quite a bit less than N times inner_run_cost
2470  * due to early scan stops. We consider two cases. If the inner path
2471  * is an indexscan using all the joinquals as indexquals, then an
2472  * unmatched outer row results in an indexscan returning no rows,
2473  * which is probably quite cheap. Otherwise, the executor will have
2474  * to scan the whole inner rel for an unmatched row; not so cheap.
2475  */
2476  if (has_indexed_join_quals(path))
2477  {
2478  /*
2479  * Successfully-matched outer rows will only require scanning
2480  * inner_scan_frac of the inner relation. In this case, we don't
2481  * need to charge the full inner_run_cost even when that's more
2482  * than inner_rescan_run_cost, because we can assume that none of
2483  * the inner scans ever scan the whole inner relation. So it's
2484  * okay to assume that all the inner scan executions can be
2485  * fractions of the full cost, even if materialization is reducing
2486  * the rescan cost. At this writing, it's impossible to get here
2487  * for a materialized inner scan, so inner_run_cost and
2488  * inner_rescan_run_cost will be the same anyway; but just in
2489  * case, use inner_run_cost for the first matched tuple and
2490  * inner_rescan_run_cost for additional ones.
2491  */
2492  run_cost += inner_run_cost * inner_scan_frac;
2493  if (outer_matched_rows > 1)
2494  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2495 
2496  /*
2497  * Add the cost of inner-scan executions for unmatched outer rows.
2498  * We estimate this as the same cost as returning the first tuple
2499  * of a nonempty scan. We consider that these are all rescans,
2500  * since we used inner_run_cost once already.
2501  */
2502  run_cost += outer_unmatched_rows *
2503  inner_rescan_run_cost / inner_path_rows;
2504 
2505  /*
2506  * We won't be evaluating any quals at all for unmatched rows, so
2507  * don't add them to ntuples.
2508  */
2509  }
2510  else
2511  {
2512  /*
2513  * Here, a complicating factor is that rescans may be cheaper than
2514  * first scans. If we never scan all the way to the end of the
2515  * inner rel, it might be (depending on the plan type) that we'd
2516  * never pay the whole inner first-scan run cost. However it is
2517  * difficult to estimate whether that will happen (and it could
2518  * not happen if there are any unmatched outer rows!), so be
2519  * conservative and always charge the whole first-scan cost once.
2520  * We consider this charge to correspond to the first unmatched
2521  * outer row, unless there isn't one in our estimate, in which
2522  * case blame it on the first matched row.
2523  */
2524 
2525  /* First, count all unmatched join tuples as being processed */
2526  ntuples += outer_unmatched_rows * inner_path_rows;
2527 
2528  /* Now add the forced full scan, and decrement appropriate count */
2529  run_cost += inner_run_cost;
2530  if (outer_unmatched_rows >= 1)
2531  outer_unmatched_rows -= 1;
2532  else
2533  outer_matched_rows -= 1;
2534 
2535  /* Add inner run cost for additional outer tuples having matches */
2536  if (outer_matched_rows > 0)
2537  run_cost += outer_matched_rows * inner_rescan_run_cost * inner_scan_frac;
2538 
2539  /* Add inner run cost for additional unmatched outer tuples */
2540  if (outer_unmatched_rows > 0)
2541  run_cost += outer_unmatched_rows * inner_rescan_run_cost;
2542  }
2543  }
2544  else
2545  {
2546  /* Normal-case source costs were included in preliminary estimate */
2547 
2548  /* Compute number of tuples processed (not number emitted!) */
2549  ntuples = outer_path_rows * inner_path_rows;
2550  }
2551 
2552  /* CPU costs */
2553  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2554  startup_cost += restrict_qual_cost.startup;
2555  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2556  run_cost += cpu_per_tuple * ntuples;
2557 
2558  /* tlist eval costs are paid per output row, not per tuple scanned */
2559  startup_cost += path->path.pathtarget->cost.startup;
2560  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
2561 
2562  path->path.startup_cost = startup_cost;
2563  path->path.total_cost = startup_cost + run_cost;
2564 }
PathTarget * pathtarget
Definition: relation.h:1047
SemiAntiJoinFactors semifactors
Definition: relation.h:2288
bool enable_nestloop
Definition: costsize.c:132
Selectivity outer_match_frac
Definition: relation.h:2265
Path * innerjoinpath
Definition: relation.h:1395
int parallel_workers
Definition: relation.h:1053
ParamPathInfo * param_info
Definition: relation.h:1049
double Selectivity
Definition: nodes.h:643
Cost inner_rescan_run_cost
Definition: relation.h:2315
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3711
Cost startup_cost
Definition: relation.h:1057
Cost disable_cost
Definition: costsize.c:121
List * joinrestrictinfo
Definition: relation.h:1397
RelOptInfo * parent
Definition: relation.h:1046
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
double rint(double x)
Definition: rint.c:22
Path * outerjoinpath
Definition: relation.h:1394
double rows
Definition: relation.h:588
Cost total_cost
Definition: relation.h:1058
Path path
Definition: relation.h:1387
static bool has_indexed_join_quals(NestPath *joinpath)
Definition: costsize.c:4139
double rows
Definition: relation.h:1056
QualCost cost
Definition: relation.h:978
double cpu_tuple_cost
Definition: costsize.c:113
double ppi_rows
Definition: relation.h:1006
Selectivity match_count
Definition: relation.h:2266
JoinType jointype
Definition: relation.h:1389
double clamp_row_est(double nrows)
Definition: costsize.c:185
double Cost
Definition: nodes.h:644

◆ get_parameterized_baserel_size()

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

Definition at line 4318 of file costsize.c.

References RelOptInfo::baserestrictinfo, clamp_row_est(), clauselist_selectivity(), JOIN_INNER, list_concat(), list_copy(), RelOptInfo::relid, RelOptInfo::rows, and RelOptInfo::tuples.

Referenced by get_baserel_parampathinfo().

4320 {
4321  List *allclauses;
4322  double nrows;
4323 
4324  /*
4325  * Estimate the number of rows returned by the parameterized scan, knowing
4326  * that it will apply all the extra join clauses as well as the rel's own
4327  * restriction clauses. Note that we force the clauses to be treated as
4328  * non-join clauses during selectivity estimation.
4329  */
4330  allclauses = list_concat(list_copy(param_clauses),
4331  rel->baserestrictinfo);
4332  nrows = rel->tuples *
4334  allclauses,
4335  rel->relid, /* do not use 0! */
4336  JOIN_INNER,
4337  NULL);
4338  nrows = clamp_row_est(nrows);
4339  /* For safety, make sure result is not more than the base estimate */
4340  if (nrows > rel->rows)
4341  nrows = rel->rows;
4342  return nrows;
4343 }
double tuples
Definition: relation.h:625
List * baserestrictinfo
Definition: relation.h:645
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
Index relid
Definition: relation.h:613
double rows
Definition: relation.h:588
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:99
double clamp_row_est(double nrows)
Definition: costsize.c:185
Definition: pg_list.h:45

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

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

Referenced by get_joinrel_parampathinfo().

4404 {
4405  double nrows;
4406 
4407  /*
4408  * Estimate the number of rows returned by the parameterized join as the
4409  * sizes of the input paths times the selectivity of the clauses that have
4410  * ended up at this join node.
4411  *
4412  * As with set_joinrel_size_estimates, the rowcount estimate could depend
4413  * on the pair of input paths provided, though ideally we'd get the same
4414  * estimate for any pair with the same parameterization.
4415  */
4416  nrows = calc_joinrel_size_estimate(root,
4417  outer_path->parent,
4418  inner_path->parent,
4419  outer_path->rows,
4420  inner_path->rows,
4421  sjinfo,
4422  restrict_clauses);
4423  /* For safety, make sure result is not more than the base estimate */
4424  if (nrows > rel->rows)
4425  nrows = rel->rows;
4426  return nrows;
4427 }
RelOptInfo * parent
Definition: relation.h:1046
double rows
Definition: relation.h:588
double rows
Definition: relation.h:1056
static double calc_joinrel_size_estimate(PlannerInfo *root, RelOptInfo *outer_rel, RelOptInfo *inner_rel, double outer_rows, double inner_rows, SpecialJoinInfo *sjinfo, List *restrictlist)
Definition: costsize.c:4439

◆ index_pages_fetched()

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

Definition at line 827 of file costsize.c.

References Assert, effective_cache_size, Max, T, and PlannerInfo::total_table_pages.

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

829 {
830  double pages_fetched;
831  double total_pages;
832  double T,
833  b;
834 
835  /* T is # pages in table, but don't allow it to be zero */
836  T = (pages > 1) ? (double) pages : 1.0;
837 
838  /* Compute number of pages assumed to be competing for cache space */
839  total_pages = root->total_table_pages + index_pages;
840  total_pages = Max(total_pages, 1.0);
841  Assert(T <= total_pages);
842 
843  /* b is pro-rated share of effective_cache_size */
844  b = (double) effective_cache_size * T / total_pages;
845 
846  /* force it positive and integral */
847  if (b <= 1.0)
848  b = 1.0;
849  else
850  b = ceil(b);
851 
852  /* This part is the Mackert and Lohman formula */
853  if (T <= b)
854  {
855  pages_fetched =
856  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
857  if (pages_fetched >= T)
858  pages_fetched = T;
859  else
860  pages_fetched = ceil(pages_fetched);
861  }
862  else
863  {
864  double lim;
865 
866  lim = (2.0 * T * b) / (2.0 * T - b);
867  if (tuples_fetched <= lim)
868  {
869  pages_fetched =
870  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
871  }
872  else
873  {
874  pages_fetched =
875  b + (tuples_fetched - lim) * (T - b) / T;
876  }
877  pages_fetched = ceil(pages_fetched);
878  }
879  return pages_fetched;
880 }
int effective_cache_size
Definition: costsize.c:119
static const uint32 T[65]
Definition: md5.c:101
double total_table_pages
Definition: relation.h:292
#define Max(x, y)
Definition: c.h:840
#define Assert(condition)
Definition: c.h:688

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

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

Referenced by try_hashjoin_path(), and try_partial_hashjoin_path().

3154 {
3155  Cost startup_cost = 0;
3156  Cost run_cost = 0;
3157  double outer_path_rows = outer_path->rows;
3158  double inner_path_rows = inner_path->rows;
3159  double inner_path_rows_total = inner_path_rows;
3160  int num_hashclauses = list_length(hashclauses);
3161  int numbuckets;
3162  int numbatches;
3163  int num_skew_mcvs;
3164  size_t space_allowed; /* unused */
3165 
3166  /* cost of source data */
3167  startup_cost += outer_path->startup_cost;
3168  run_cost += outer_path->total_cost - outer_path->startup_cost;
3169  startup_cost += inner_path->total_cost;
3170 
3171  /*
3172  * Cost of computing hash function: must do it once per input tuple. We
3173  * charge one cpu_operator_cost for each column's hash function. Also,
3174  * tack on one cpu_tuple_cost per inner row, to model the costs of
3175  * inserting the row into the hashtable.
3176  *
3177  * XXX when a hashclause is more complex than a single operator, we really
3178  * should charge the extra eval costs of the left or right side, as
3179  * appropriate, here. This seems more work than it's worth at the moment.
3180  */
3181  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
3182  * inner_path_rows;
3183  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
3184 
3185  /*
3186  * If this is a parallel hash build, then the value we have for
3187  * inner_rows_total currently refers only to the rows returned by each
3188  * participant. For shared hash table size estimation, we need the total
3189  * number, so we need to undo the division.
3190  */
3191  if (parallel_hash)
3192  inner_path_rows_total *= get_parallel_divisor(inner_path);
3193 
3194  /*
3195  * Get hash table size that executor would use for inner relation.
3196  *
3197  * XXX for the moment, always assume that skew optimization will be
3198  * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
3199  * trying to determine that for sure.
3200  *
3201  * XXX at some point it might be interesting to try to account for skew
3202  * optimization in the cost estimate, but for now, we don't.
3203  */
3204  ExecChooseHashTableSize(inner_path_rows_total,
3205  inner_path->pathtarget->width,
3206  true, /* useskew */
3207  parallel_hash, /* try_combined_work_mem */
3208  outer_path->parallel_workers,
3209  &space_allowed,
3210  &numbuckets,
3211  &numbatches,
3212  &num_skew_mcvs);
3213 
3214  /*
3215  * If inner relation is too big then we will need to "batch" the join,
3216  * which implies writing and reading most of the tuples to disk an extra
3217  * time. Charge seq_page_cost per page, since the I/O should be nice and
3218  * sequential. Writing the inner rel counts as startup cost, all the rest
3219  * as run cost.
3220  */
3221  if (numbatches > 1)
3222  {
3223  double outerpages = page_size(outer_path_rows,
3224  outer_path->pathtarget->width);
3225  double innerpages = page_size(inner_path_rows,
3226  inner_path->pathtarget->width);
3227 
3228  startup_cost += seq_page_cost * innerpages;
3229  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
3230  }
3231 
3232  /* CPU costs left for later */
3233 
3234  /* Public result fields */
3235  workspace->startup_cost = startup_cost;
3236  workspace->total_cost = startup_cost + run_cost;
3237  /* Save private data for final_cost_hashjoin */
3238  workspace->run_cost = run_cost;
3239  workspace->numbuckets = numbuckets;
3240  workspace->numbatches = numbatches;
3241  workspace->inner_rows_total = inner_path_rows_total;
3242 }
PathTarget * pathtarget
Definition: relation.h:1047
int parallel_workers
Definition: relation.h:1053
static double page_size(double tuples, int width)
Definition: costsize.c:5330
Cost startup_cost
Definition: relation.h:1057
static double get_parallel_divisor(Path *path)
Definition: costsize.c:5340
double cpu_operator_cost
Definition: costsize.c:115
double inner_rows_total
Definition: relation.h:2326
Cost total_cost
Definition: relation.h:1058
double rows
Definition: relation.h:1056
static int list_length(const List *l)
Definition: pg_list.h:89
double cpu_tuple_cost
Definition: costsize.c:113
int width
Definition: relation.h:979
double seq_page_cost
Definition: costsize.c:111
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, bool try_combined_work_mem, int parallel_workers, size_t *space_allowed, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:661
double Cost
Definition: nodes.h:644

◆ initial_cost_mergejoin()

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

Definition at line 2597 of file costsize.c.

References Assert, bms_is_subset(), cached_scansel(), clamp_row_est(), cost_sort(), EquivalenceClass::ec_collation, elog, ERROR, JoinCostWorkspace::inner_rows, JoinCostWorkspace::inner_run_cost, JoinCostWorkspace::inner_skip_rows, JOIN_ANTI, JOIN_FULL, JOIN_LEFT, JOIN_RIGHT, RestrictInfo::left_relids, MergeScanSelCache::leftendsel, MergeScanSelCache::leftstartsel, linitial, JoinCostWorkspace::outer_rows, JoinCostWorkspace::outer_skip_rows, Path::parent, Path::pathkeys, Path::pathtarget, PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, RelOptInfo::relids, MergeScanSelCache::rightendsel, MergeScanSelCache::rightstartsel, rint(), Path::rows, JoinCostWorkspace::run_cost, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, JoinCostWorkspace::total_cost, PathTarget::width, and work_mem.

Referenced by try_mergejoin_path(), and try_partial_mergejoin_path().

2603 {
2604  Cost startup_cost = 0;
2605  Cost run_cost = 0;
2606  double outer_path_rows = outer_path->rows;
2607  double inner_path_rows = inner_path->rows;
2608  Cost inner_run_cost;
2609  double outer_rows,
2610  inner_rows,
2611  outer_skip_rows,
2612  inner_skip_rows;
2613  Selectivity outerstartsel,
2614  outerendsel,
2615  innerstartsel,
2616  innerendsel;
2617  Path sort_path; /* dummy for result of cost_sort */
2618 
2619  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2620  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2621  outer_path_rows = 1;
2622  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2623  inner_path_rows = 1;
2624 
2625  /*
2626  * A merge join will stop as soon as it exhausts either input stream
2627  * (unless it's an outer join, in which case the outer side has to be
2628  * scanned all the way anyway). Estimate fraction of the left and right
2629  * inputs that will actually need to be scanned. Likewise, we can
2630  * estimate the number of rows that will be skipped before the first join
2631  * pair is found, which should be factored into startup cost. We use only
2632  * the first (most significant) merge clause for this purpose. Since
2633  * mergejoinscansel() is a fairly expensive computation, we cache the
2634  * results in the merge clause RestrictInfo.
2635  */
2636  if (mergeclauses && jointype != JOIN_FULL)
2637  {
2638  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
2639