PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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_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_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, 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, 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, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
void final_cost_nestloop (PlannerInfo *root, NestPath *path, JoinCostWorkspace *workspace, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
void initial_cost_mergejoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *mergeclauses, Path *outer_path, Path *inner_path, List *outersortkeys, List *innersortkeys, SpecialJoinInfo *sjinfo)
 
void final_cost_mergejoin (PlannerInfo *root, MergePath *path, JoinCostWorkspace *workspace, SpecialJoinInfo *sjinfo)
 
void initial_cost_hashjoin (PlannerInfo *root, JoinCostWorkspace *workspace, JoinType jointype, List *hashclauses, Path *outer_path, Path *inner_path, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
void final_cost_hashjoin (PlannerInfo *root, HashPath *path, JoinCostWorkspace *workspace, SpecialJoinInfo *sjinfo, SemiAntiJoinFactors *semifactors)
 
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_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
 
Cost disable_cost
 
int max_parallel_workers_per_gather
 
bool enable_seqscan
 
bool enable_indexscan
 
bool enable_indexonlyscan
 
bool enable_bitmapscan
 
bool enable_tidscan
 
bool enable_sort
 
bool enable_hashagg
 
bool enable_nestloop
 
bool enable_material
 
bool enable_mergejoin
 
bool enable_hashjoin
 
bool enable_gathermerge
 
int constraint_exclusion
 

Macro Definition Documentation

#define DEFAULT_CPU_INDEX_TUPLE_COST   0.005

Definition at line 27 of file cost.h.

#define DEFAULT_CPU_OPERATOR_COST   0.0025

Definition at line 28 of file cost.h.

#define DEFAULT_CPU_TUPLE_COST   0.01

Definition at line 26 of file cost.h.

#define DEFAULT_EFFECTIVE_CACHE_SIZE   524288 /* measured in pages */

Definition at line 32 of file cost.h.

#define DEFAULT_PARALLEL_SETUP_COST   1000.0

Definition at line 30 of file cost.h.

#define DEFAULT_PARALLEL_TUPLE_COST   0.1

Definition at line 29 of file cost.h.

#define DEFAULT_RANDOM_PAGE_COST   4.0

Definition at line 25 of file cost.h.

#define DEFAULT_SEQ_PAGE_COST   1.0

Definition at line 24 of file cost.h.

Enumeration Type Documentation

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

double clamp_row_est ( double  nrows)

Definition at line 173 of file costsize.c.

References rint().

Referenced by approx_tuple_count(), bernoulli_samplescangetsamplesize(), calc_joinrel_size_estimate(), compute_bitmap_pages(), cost_bitmap_heap_scan(), cost_index(), cost_seqscan(), cost_subplan(), create_bitmap_subplan(), create_limit_path(), estimate_hash_bucketsize(), 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().

174 {
175  /*
176  * Force estimate to be at least one row, to make explain output look
177  * better and to avoid possible divide-by-zero when interpolating costs.
178  * Make it an integer, too.
179  */
180  if (nrows <= 1.0)
181  nrows = 1.0;
182  else
183  nrows = rint(nrows);
184 
185  return nrows;
186 }
double rint(double x)
Definition: rint.c:22
Selectivity clause_selectivity ( PlannerInfo root,
Node clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 483 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(), NULL, 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 get_foreign_key_join_selectivity().

488 {
489  Selectivity s1 = 0.5; /* default for any unhandled clause type */
490  RestrictInfo *rinfo = NULL;
491  bool cacheable = false;
492 
493  if (clause == NULL) /* can this still happen? */
494  return s1;
495 
496  if (IsA(clause, RestrictInfo))
497  {
498  rinfo = (RestrictInfo *) clause;
499 
500  /*
501  * If the clause is marked pseudoconstant, then it will be used as a
502  * gating qual and should not affect selectivity estimates; hence
503  * return 1.0. The only exception is that a constant FALSE may be
504  * taken as having selectivity 0.0, since it will surely mean no rows
505  * out of the plan. This case is simple enough that we need not
506  * bother caching the result.
507  */
508  if (rinfo->pseudoconstant)
509  {
510  if (!IsA(rinfo->clause, Const))
511  return (Selectivity) 1.0;
512  }
513 
514  /*
515  * If the clause is marked redundant, always return 1.0.
516  */
517  if (rinfo->norm_selec > 1)
518  return (Selectivity) 1.0;
519 
520  /*
521  * If possible, cache the result of the selectivity calculation for
522  * the clause. We can cache if varRelid is zero or the clause
523  * contains only vars of that relid --- otherwise varRelid will affect
524  * the result, so mustn't cache. Outer join quals might be examined
525  * with either their join's actual jointype or JOIN_INNER, so we need
526  * two cache variables to remember both cases. Note: we assume the
527  * result won't change if we are switching the input relations or
528  * considering a unique-ified case, so we only need one cache variable
529  * for all non-JOIN_INNER cases.
530  */
531  if (varRelid == 0 ||
532  bms_is_subset_singleton(rinfo->clause_relids, varRelid))
533  {
534  /* Cacheable --- do we already have the result? */
535  if (jointype == JOIN_INNER)
536  {
537  if (rinfo->norm_selec >= 0)
538  return rinfo->norm_selec;
539  }
540  else
541  {
542  if (rinfo->outer_selec >= 0)
543  return rinfo->outer_selec;
544  }
545  cacheable = true;
546  }
547 
548  /*
549  * Proceed with examination of contained clause. If the clause is an
550  * OR-clause, we want to look at the variant with sub-RestrictInfos,
551  * so that per-subclause selectivities can be cached.
552  */
553  if (rinfo->orclause)
554  clause = (Node *) rinfo->orclause;
555  else
556  clause = (Node *) rinfo->clause;
557  }
558 
559  if (IsA(clause, Var))
560  {
561  Var *var = (Var *) clause;
562 
563  /*
564  * We probably shouldn't ever see an uplevel Var here, but if we do,
565  * return the default selectivity...
566  */
567  if (var->varlevelsup == 0 &&
568  (varRelid == 0 || varRelid == (int) var->varno))
569  {
570  /* Use the restriction selectivity function for a bool Var */
571  s1 = boolvarsel(root, (Node *) var, varRelid);
572  }
573  }
574  else if (IsA(clause, Const))
575  {
576  /* bool constant is pretty easy... */
577  Const *con = (Const *) clause;
578 
579  s1 = con->constisnull ? 0.0 :
580  DatumGetBool(con->constvalue) ? 1.0 : 0.0;
581  }
582  else if (IsA(clause, Param))
583  {
584  /* see if we can replace the Param */
585  Node *subst = estimate_expression_value(root, clause);
586 
587  if (IsA(subst, Const))
588  {
589  /* bool constant is pretty easy... */
590  Const *con = (Const *) subst;
591 
592  s1 = con->constisnull ? 0.0 :
593  DatumGetBool(con->constvalue) ? 1.0 : 0.0;
594  }
595  else
596  {
597  /* XXX any way to do better than default? */
598  }
599  }
600  else if (not_clause(clause))
601  {
602  /* inverse of the selectivity of the underlying clause */
603  s1 = 1.0 - clause_selectivity(root,
604  (Node *) get_notclausearg((Expr *) clause),
605  varRelid,
606  jointype,
607  sjinfo);
608  }
609  else if (and_clause(clause))
610  {
611  /* share code with clauselist_selectivity() */
612  s1 = clauselist_selectivity(root,
613  ((BoolExpr *) clause)->args,
614  varRelid,
615  jointype,
616  sjinfo);
617  }
618  else if (or_clause(clause))
619  {
620  /*
621  * Selectivities for an OR clause are computed as s1+s2 - s1*s2 to
622  * account for the probable overlap of selected tuple sets.
623  *
624  * XXX is this too conservative?
625  */
626  ListCell *arg;
627 
628  s1 = 0.0;
629  foreach(arg, ((BoolExpr *) clause)->args)
630  {
632  (Node *) lfirst(arg),
633  varRelid,
634  jointype,
635  sjinfo);
636 
637  s1 = s1 + s2 - s1 * s2;
638  }
639  }
640  else if (is_opclause(clause) || IsA(clause, DistinctExpr))
641  {
642  OpExpr *opclause = (OpExpr *) clause;
643  Oid opno = opclause->opno;
644 
645  if (treat_as_join_clause(clause, rinfo, varRelid, sjinfo))
646  {
647  /* Estimate selectivity for a join clause. */
648  s1 = join_selectivity(root, opno,
649  opclause->args,
650  opclause->inputcollid,
651  jointype,
652  sjinfo);
653  }
654  else
655  {
656  /* Estimate selectivity for a restriction clause. */
657  s1 = restriction_selectivity(root, opno,
658  opclause->args,
659  opclause->inputcollid,
660  varRelid);
661  }
662 
663  /*
664  * DistinctExpr has the same representation as OpExpr, but the
665  * contained operator is "=" not "<>", so we must negate the result.
666  * This estimation method doesn't give the right behavior for nulls,
667  * but it's better than doing nothing.
668  */
669  if (IsA(clause, DistinctExpr))
670  s1 = 1.0 - s1;
671  }
672  else if (IsA(clause, ScalarArrayOpExpr))
673  {
674  /* Use node specific selectivity calculation function */
675  s1 = scalararraysel(root,
676  (ScalarArrayOpExpr *) clause,
677  treat_as_join_clause(clause, rinfo,
678  varRelid, sjinfo),
679  varRelid,
680  jointype,
681  sjinfo);
682  }
683  else if (IsA(clause, RowCompareExpr))
684  {
685  /* Use node specific selectivity calculation function */
686  s1 = rowcomparesel(root,
687  (RowCompareExpr *) clause,
688  varRelid,
689  jointype,
690  sjinfo);
691  }
692  else if (IsA(clause, NullTest))
693  {
694  /* Use node specific selectivity calculation function */
695  s1 = nulltestsel(root,
696  ((NullTest *) clause)->nulltesttype,
697  (Node *) ((NullTest *) clause)->arg,
698  varRelid,
699  jointype,
700  sjinfo);
701  }
702  else if (IsA(clause, BooleanTest))
703  {
704  /* Use node specific selectivity calculation function */
705  s1 = booltestsel(root,
706  ((BooleanTest *) clause)->booltesttype,
707  (Node *) ((BooleanTest *) clause)->arg,
708  varRelid,
709  jointype,
710  sjinfo);
711  }
712  else if (IsA(clause, CurrentOfExpr))
713  {
714  /* CURRENT OF selects at most one row of its table */
715  CurrentOfExpr *cexpr = (CurrentOfExpr *) clause;
716  RelOptInfo *crel = find_base_rel(root, cexpr->cvarno);
717 
718  if (crel->tuples > 0)
719  s1 = 1.0 / crel->tuples;
720  }
721  else if (IsA(clause, RelabelType))
722  {
723  /* Not sure this case is needed, but it can't hurt */
724  s1 = clause_selectivity(root,
725  (Node *) ((RelabelType *) clause)->arg,
726  varRelid,
727  jointype,
728  sjinfo);
729  }
730  else if (IsA(clause, CoerceToDomain))
731  {
732  /* Not sure this case is needed, but it can't hurt */
733  s1 = clause_selectivity(root,
734  (Node *) ((CoerceToDomain *) clause)->arg,
735  varRelid,
736  jointype,
737  sjinfo);
738  }
739  else
740  {
741  /*
742  * For anything else, see if we can consider it as a boolean variable.
743  * This only works if it's an immutable expression in Vars of a single
744  * relation; but there's no point in us checking that here because
745  * boolvarsel() will do it internally, and return a suitable default
746  * selectivity if not.
747  */
748  s1 = boolvarsel(root, clause, varRelid);
749  }
750 
751  /* Cache the result if possible */
752  if (cacheable)
753  {
754  if (jointype == JOIN_INNER)
755  rinfo->norm_selec = s1;
756  else
757  rinfo->outer_selec = s1;
758  }
759 
760 #ifdef SELECTIVITY_DEBUG
761  elog(DEBUG4, "clause_selectivity: s1 %f", s1);
762 #endif /* SELECTIVITY_DEBUG */
763 
764  return s1;
765 }
Datum constvalue
Definition: primnodes.h:196
Expr * get_notclausearg(Expr *notclause)
Definition: clauses.c:264
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
Index varlevelsup
Definition: primnodes.h:173
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2399
Expr * orclause
Definition: relation.h:1730
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1635
double tuples
Definition: relation.h:534
Selectivity rowcomparesel(PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:2121
Relids clause_relids
Definition: relation.h:1714
bool pseudoconstant
Definition: relation.h:1707
Definition: nodes.h:506
double Selectivity
Definition: nodes.h:635
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:1764
Selectivity norm_selec
Definition: relation.h:1737
static bool treat_as_join_clause(Node *clause, RestrictInfo *rinfo, int varRelid, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:405
static bool bms_is_subset_singleton(const Bitmapset *s, int x)
Definition: clausesel.c:384
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:1664
bool and_clause(Node *clause)
Definition: clauses.c:313
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:483
#define DatumGetBool(X)
Definition: postgres.h:399
Selectivity outer_selec
Definition: relation.h:1740
bool not_clause(Node *clause)
Definition: clauses.c:235
Expr * clause
Definition: relation.h:1699
Index varno
Definition: primnodes.h:166
char * s2
bool or_clause(Node *clause)
Definition: clauses.c:279
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
Oid inputcollid
Definition: primnodes.h:500
void * arg
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1672
Oid opno
Definition: primnodes.h:495
#define elog
Definition: elog.h:219
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:223
List * args
Definition: primnodes.h:501
Selectivity booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1499
Selectivity boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
Definition: selfuncs.c:1460
bool constisnull
Definition: primnodes.h:197
Selectivity clauselist_selectivity ( PlannerInfo root,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo 
)

Definition at line 92 of file clausesel.c.

References addRangeClause(), generate_unaccent_rules::args, OpExpr::args, bms_membership(), BMS_SINGLETON, RestrictInfo::clause, RestrictInfo::clause_relids, clause_selectivity(), DEFAULT_INEQ_SEL, DEFAULT_RANGE_INEQ_SEL, 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, NULL, nulltestsel(), NumRelids(), OpExpr::opno, pfree(), RestrictInfo::pseudoconstant, RestrictInfo::right_relids, s1, s2, and RangeQueryClause::var.

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

97 {
98  Selectivity s1 = 1.0;
99  RangeQueryClause *rqlist = NULL;
100  ListCell *l;
101 
102  /*
103  * If there's exactly one clause, then no use in trying to match up pairs,
104  * so just go directly to clause_selectivity().
105  */
106  if (list_length(clauses) == 1)
107  return clause_selectivity(root, (Node *) linitial(clauses),
108  varRelid, jointype, sjinfo);
109 
110  /*
111  * Initial scan over clauses. Anything that doesn't look like a potential
112  * rangequery clause gets multiplied into s1 and forgotten. Anything that
113  * does gets inserted into an rqlist entry.
114  */
115  foreach(l, clauses)
116  {
117  Node *clause = (Node *) lfirst(l);
118  RestrictInfo *rinfo;
119  Selectivity s2;
120 
121  /* Always compute the selectivity using clause_selectivity */
122  s2 = clause_selectivity(root, clause, varRelid, jointype, sjinfo);
123 
124  /*
125  * Check for being passed a RestrictInfo.
126  *
127  * If it's a pseudoconstant RestrictInfo, then s2 is either 1.0 or
128  * 0.0; just use that rather than looking for range pairs.
129  */
130  if (IsA(clause, RestrictInfo))
131  {
132  rinfo = (RestrictInfo *) clause;
133  if (rinfo->pseudoconstant)
134  {
135  s1 = s1 * s2;
136  continue;
137  }
138  clause = (Node *) rinfo->clause;
139  }
140  else
141  rinfo = NULL;
142 
143  /*
144  * See if it looks like a restriction clause with a pseudoconstant on
145  * one side. (Anything more complicated than that might not behave in
146  * the simple way we are expecting.) Most of the tests here can be
147  * done more efficiently with rinfo than without.
148  */
149  if (is_opclause(clause) && list_length(((OpExpr *) clause)->args) == 2)
150  {
151  OpExpr *expr = (OpExpr *) clause;
152  bool varonleft = true;
153  bool ok;
154 
155  if (rinfo)
156  {
157  ok = (bms_membership(rinfo->clause_relids) == BMS_SINGLETON) &&
159  rinfo->right_relids) ||
160  (varonleft = false,
162  rinfo->left_relids)));
163  }
164  else
165  {
166  ok = (NumRelids(clause) == 1) &&
168  (varonleft = false,
170  }
171 
172  if (ok)
173  {
174  /*
175  * If it's not a "<" or ">" operator, just merge the
176  * selectivity in generically. But if it's the right oprrest,
177  * add the clause to rqlist for later processing.
178  */
179  switch (get_oprrest(expr->opno))
180  {
181  case F_SCALARLTSEL:
182  addRangeClause(&rqlist, clause,
183  varonleft, true, s2);
184  break;
185  case F_SCALARGTSEL:
186  addRangeClause(&rqlist, clause,
187  varonleft, false, s2);
188  break;
189  default:
190  /* Just merge the selectivity in generically */
191  s1 = s1 * s2;
192  break;
193  }
194  continue; /* drop to loop bottom */
195  }
196  }
197 
198  /* Not the right form, so treat it generically. */
199  s1 = s1 * s2;
200  }
201 
202  /*
203  * Now scan the rangequery pair list.
204  */
205  while (rqlist != NULL)
206  {
207  RangeQueryClause *rqnext;
208 
209  if (rqlist->have_lobound && rqlist->have_hibound)
210  {
211  /* Successfully matched a pair of range clauses */
212  Selectivity s2;
213 
214  /*
215  * Exact equality to the default value probably means the
216  * selectivity function punted. This is not airtight but should
217  * be good enough.
218  */
219  if (rqlist->hibound == DEFAULT_INEQ_SEL ||
220  rqlist->lobound == DEFAULT_INEQ_SEL)
221  {
223  }
224  else
225  {
226  s2 = rqlist->hibound + rqlist->lobound - 1.0;
227 
228  /* Adjust for double-exclusion of NULLs */
229  s2 += nulltestsel(root, IS_NULL, rqlist->var,
230  varRelid, jointype, sjinfo);
231 
232  /*
233  * A zero or slightly negative s2 should be converted into a
234  * small positive value; we probably are dealing with a very
235  * tight range and got a bogus result due to roundoff errors.
236  * However, if s2 is very negative, then we probably have
237  * default selectivity estimates on one or both sides of the
238  * range that we failed to recognize above for some reason.
239  */
240  if (s2 <= 0.0)
241  {
242  if (s2 < -0.01)
243  {
244  /*
245  * No data available --- use a default estimate that
246  * is small, but not real small.
247  */
249  }
250  else
251  {
252  /*
253  * It's just roundoff error; use a small positive
254  * value
255  */
256  s2 = 1.0e-10;
257  }
258  }
259  }
260  /* Merge in the selectivity of the pair of clauses */
261  s1 *= s2;
262  }
263  else
264  {
265  /* Only found one of a pair, merge it in generically */
266  if (rqlist->have_lobound)
267  s1 *= rqlist->lobound;
268  else
269  s1 *= rqlist->hibound;
270  }
271  /* release storage and advance */
272  rqnext = rqlist->next;
273  pfree(rqlist);
274  rqlist = rqnext;
275  }
276 
277  return s1;
278 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
bool is_pseudo_constant_clause_relids(Node *clause, Relids relids)
Definition: clauses.c:2161
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Relids clause_relids
Definition: relation.h:1714
bool pseudoconstant
Definition: relation.h:1707
Definition: nodes.h:506
Relids left_relids
Definition: relation.h:1726
double Selectivity
Definition: nodes.h:635
#define lsecond(l)
Definition: pg_list.h:114
void pfree(void *pointer)
Definition: mcxt.c:950
#define linitial(l)
Definition: pg_list.h:110
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:1664
Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:483
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:2141
struct RangeQueryClause * next
Definition: clausesel.c:33
static void addRangeClause(RangeQueryClause **rqlist, Node *clause, bool varonleft, bool isLTsel, Selectivity s2)
Definition: clausesel.c:286
Selectivity hibound
Definition: clausesel.c:38
Expr * clause
Definition: relation.h:1699
Selectivity lobound
Definition: clausesel.c:37
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1329
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:634
char * s2
Relids right_relids
Definition: relation.h:1727
#define NULL
Definition: c.h:229
#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:495
List * args
Definition: primnodes.h:501
int NumRelids(Node *clause)
Definition: clauses.c:2183
double compute_bitmap_pages ( PlannerInfo root,
RelOptInfo baserel,
Path bitmapqual,
int  loop_count,
Cost cost,
double *  tuple 
)

Definition at line 5024 of file costsize.c.

References clamp_row_est(), cost_bitmap_tree_node(), get_indexpath_pages(), index_pages_fetched(), RelOptInfo::pages, T, and RelOptInfo::tuples.

Referenced by cost_bitmap_heap_scan(), and create_partial_bitmap_paths().

5026 {
5027  Cost indexTotalCost;
5028  Selectivity indexSelectivity;
5029  double T;
5030  double pages_fetched;
5031  double tuples_fetched;
5032 
5033  /*
5034  * Fetch total cost of obtaining the bitmap, as well as its total
5035  * selectivity.
5036  */
5037  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
5038 
5039  /*
5040  * Estimate number of main-table pages fetched.
5041  */
5042  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
5043 
5044  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
5045 
5046  if (loop_count > 1)
5047  {
5048  /*
5049  * For repeated bitmap scans, scale up the number of tuples fetched in
5050  * the Mackert and Lohman formula by the number of scans, so that we
5051  * estimate the number of pages fetched by all the scans. Then
5052  * pro-rate for one scan.
5053  */
5054  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
5055  baserel->pages,
5056  get_indexpath_pages(bitmapqual),
5057  root);
5058  pages_fetched /= loop_count;
5059  }
5060  else
5061  {
5062  /*
5063  * For a single scan, the number of heap pages that need to be fetched
5064  * is the same as the Mackert and Lohman formula for the case T <= b
5065  * (ie, no re-reads needed).
5066  */
5067  pages_fetched =
5068  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
5069  }
5070 
5071  if (pages_fetched >= T)
5072  pages_fetched = T;
5073  else
5074  pages_fetched = ceil(pages_fetched);
5075 
5076  if (cost)
5077  *cost = indexTotalCost;
5078  if (tuple)
5079  *tuple = tuples_fetched;
5080 
5081  return pages_fetched;
5082 }
double tuples
Definition: relation.h:534
double Selectivity
Definition: nodes.h:635
static const uint32 T[65]
Definition: md5.c:101
BlockNumber pages
Definition: relation.h:533
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:878
double clamp_row_est(double nrows)
Definition: costsize.c:173
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:813
double Cost
Definition: nodes.h:636
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1029
void compute_semi_anti_join_factors ( PlannerInfo root,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
SpecialJoinInfo sjinfo,
List restrictlist,
SemiAntiJoinFactors semifactors 
)

Definition at line 3671 of file costsize.c.

References Assert, castNode, clauselist_selectivity(), SpecialJoinInfo::delay_upper_joins, RestrictInfo::is_pushed_down, JOIN_ANTI, JOIN_INNER, JOIN_SEMI, SpecialJoinInfo::jointype, lappend(), lfirst, 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().

3678 {
3679  Selectivity jselec;
3680  Selectivity nselec;
3681  Selectivity avgmatch;
3682  SpecialJoinInfo norm_sjinfo;
3683  List *joinquals;
3684  ListCell *l;
3685 
3686  /* Should only be called in these cases */
3687  Assert(jointype == JOIN_SEMI || jointype == JOIN_ANTI);
3688 
3689  /*
3690  * In an ANTI join, we must ignore clauses that are "pushed down", since
3691  * those won't affect the match logic. In a SEMI join, we do not
3692  * distinguish joinquals from "pushed down" quals, so just use the whole
3693  * restrictinfo list.
3694  */
3695  if (jointype == JOIN_ANTI)
3696  {
3697  joinquals = NIL;
3698  foreach(l, restrictlist)
3699  {
3700  RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
3701 
3702  if (!rinfo->is_pushed_down)
3703  joinquals = lappend(joinquals, rinfo);
3704  }
3705  }
3706  else
3707  joinquals = restrictlist;
3708 
3709  /*
3710  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
3711  */
3712  jselec = clauselist_selectivity(root,
3713  joinquals,
3714  0,
3715  jointype,
3716  sjinfo);
3717 
3718  /*
3719  * Also get the normal inner-join selectivity of the join clauses.
3720  */
3721  norm_sjinfo.type = T_SpecialJoinInfo;
3722  norm_sjinfo.min_lefthand = outerrel->relids;
3723  norm_sjinfo.min_righthand = innerrel->relids;
3724  norm_sjinfo.syn_lefthand = outerrel->relids;
3725  norm_sjinfo.syn_righthand = innerrel->relids;
3726  norm_sjinfo.jointype = JOIN_INNER;
3727  /* we don't bother trying to make the remaining fields valid */
3728  norm_sjinfo.lhs_strict = false;
3729  norm_sjinfo.delay_upper_joins = false;
3730  norm_sjinfo.semi_can_btree = false;
3731  norm_sjinfo.semi_can_hash = false;
3732  norm_sjinfo.semi_operators = NIL;
3733  norm_sjinfo.semi_rhs_exprs = NIL;
3734 
3735  nselec = clauselist_selectivity(root,
3736  joinquals,
3737  0,
3738  JOIN_INNER,
3739  &norm_sjinfo);
3740 
3741  /* Avoid leaking a lot of ListCells */
3742  if (jointype == JOIN_ANTI)
3743  list_free(joinquals);
3744 
3745  /*
3746  * jselec can be interpreted as the fraction of outer-rel rows that have
3747  * any matches (this is true for both SEMI and ANTI cases). And nselec is
3748  * the fraction of the Cartesian product that matches. So, the average
3749  * number of matches for each outer-rel row that has at least one match is
3750  * nselec * inner_rows / jselec.
3751  *
3752  * Note: it is correct to use the inner rel's "rows" count here, even
3753  * though we might later be considering a parameterized inner path with
3754  * fewer rows. This is because we have included all the join clauses in
3755  * the selectivity estimate.
3756  */
3757  if (jselec > 0) /* protect against zero divide */
3758  {
3759  avgmatch = nselec * innerrel->rows / jselec;
3760  /* Clamp to sane range */
3761  avgmatch = Max(1.0, avgmatch);
3762  }
3763  else
3764  avgmatch = 1.0;
3765 
3766  semifactors->outer_match_frac = jselec;
3767  semifactors->match_count = avgmatch;
3768 }
#define NIL
Definition: pg_list.h:69
bool semi_can_btree
Definition: relation.h:1877
Relids min_righthand
Definition: relation.h:1870
#define castNode(_type_, nodeptr)
Definition: nodes.h:575
Selectivity outer_match_frac
Definition: relation.h:2113
NodeTag type
Definition: relation.h:1868
double Selectivity
Definition: nodes.h:635
Relids syn_lefthand
Definition: relation.h:1871
Relids syn_righthand
Definition: relation.h:1872
List * semi_rhs_exprs
Definition: relation.h:1880
bool semi_can_hash
Definition: relation.h:1878
Relids relids
Definition: relation.h:494
List * lappend(List *list, void *datum)
Definition: list.c:128
bool delay_upper_joins
Definition: relation.h:1875
double rows
Definition: relation.h:497
bool is_pushed_down
Definition: relation.h:1701
#define Max(x, y)
Definition: c.h:800
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
JoinType jointype
Definition: relation.h:1873
Selectivity match_count
Definition: relation.h:2114
List * semi_operators
Definition: relation.h:1879
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:92
Definition: pg_list.h:45
Relids min_lefthand
Definition: relation.h:1869
void cost_agg ( Path path,
PlannerInfo root,
AggStrategy  aggstrategy,
const AggClauseCosts aggcosts,
int  numGroupCols,
double  numGroups,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 1836 of file costsize.c.

References AGG_HASHED, AGG_MIXED, AGG_PLAIN, AGG_SORTED, Assert, cpu_operator_cost, cpu_tuple_cost, disable_cost, enable_hashagg, AggClauseCosts::finalCost, MemSet, NULL, 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().

1841 {
1842  double output_tuples;
1843  Cost startup_cost;
1844  Cost total_cost;
1845  AggClauseCosts dummy_aggcosts;
1846 
1847  /* Use all-zero per-aggregate costs if NULL is passed */
1848  if (aggcosts == NULL)
1849  {
1850  Assert(aggstrategy == AGG_HASHED);
1851  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1852  aggcosts = &dummy_aggcosts;
1853  }
1854 
1855  /*
1856  * The transCost.per_tuple component of aggcosts should be charged once
1857  * per input tuple, corresponding to the costs of evaluating the aggregate
1858  * transfns and their input expressions (with any startup cost of course
1859  * charged but once). The finalCost component is charged once per output
1860  * tuple, corresponding to the costs of evaluating the finalfns.
1861  *
1862  * If we are grouping, we charge an additional cpu_operator_cost per
1863  * grouping column per input tuple for grouping comparisons.
1864  *
1865  * We will produce a single output tuple if not grouping, and a tuple per
1866  * group otherwise. We charge cpu_tuple_cost for each output tuple.
1867  *
1868  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1869  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1870  * input path is already sorted appropriately, AGG_SORTED should be
1871  * preferred (since it has no risk of memory overflow). This will happen
1872  * as long as the computed total costs are indeed exactly equal --- but if
1873  * there's roundoff error we might do the wrong thing. So be sure that
1874  * the computations below form the same intermediate values in the same
1875  * order.
1876  */
1877  if (aggstrategy == AGG_PLAIN)
1878  {
1879  startup_cost = input_total_cost;
1880  startup_cost += aggcosts->transCost.startup;
1881  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1882  startup_cost += aggcosts->finalCost;
1883  /* we aren't grouping */
1884  total_cost = startup_cost + cpu_tuple_cost;
1885  output_tuples = 1;
1886  }
1887  else if (aggstrategy == AGG_SORTED || aggstrategy == AGG_MIXED)
1888  {
1889  /* Here we are able to deliver output on-the-fly */
1890  startup_cost = input_startup_cost;
1891  total_cost = input_total_cost;
1892  if (aggstrategy == AGG_MIXED && !enable_hashagg)
1893  {
1894  startup_cost += disable_cost;
1895  total_cost += disable_cost;
1896  }
1897  /* calcs phrased this way to match HASHED case, see note above */
1898  total_cost += aggcosts->transCost.startup;
1899  total_cost += aggcosts->transCost.per_tuple * input_tuples;
1900  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1901  total_cost += aggcosts->finalCost * numGroups;
1902  total_cost += cpu_tuple_cost * numGroups;
1903  output_tuples = numGroups;
1904  }
1905  else
1906  {
1907  /* must be AGG_HASHED */
1908  startup_cost = input_total_cost;
1909  if (!enable_hashagg)
1910  startup_cost += disable_cost;
1911  startup_cost += aggcosts->transCost.startup;
1912  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1913  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1914  total_cost = startup_cost;
1915  total_cost += aggcosts->finalCost * numGroups;
1916  total_cost += cpu_tuple_cost * numGroups;
1917  output_tuples = numGroups;
1918  }
1919 
1920  path->rows = output_tuples;
1921  path->startup_cost = startup_cost;
1922  path->total_cost = total_cost;
1923 }
#define MemSet(start, val, len)
Definition: c.h:857
QualCost transCost
Definition: relation.h:62
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
double cpu_operator_cost
Definition: costsize.c:108
Cost finalCost
Definition: relation.h:63
Cost total_cost
Definition: relation.h:930
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
double cpu_tuple_cost
Definition: costsize.c:106
bool enable_hashagg
Definition: costsize.c:124
double Cost
Definition: nodes.h:636
void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

Definition at line 1072 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().

1073 {
1074  Cost totalCost;
1075  Selectivity selec;
1076  ListCell *l;
1077 
1078  /*
1079  * We estimate AND selectivity on the assumption that the inputs are
1080  * independent. This is probably often wrong, but we don't have the info
1081  * to do better.
1082  *
1083  * The runtime cost of the BitmapAnd itself is estimated at 100x
1084  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
1085  * definitely too simplistic?
1086  */
1087  totalCost = 0.0;
1088  selec = 1.0;
1089  foreach(l, path->bitmapquals)
1090  {
1091  Path *subpath = (Path *) lfirst(l);
1092  Cost subCost;
1093  Selectivity subselec;
1094 
1095  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1096 
1097  selec *= subselec;
1098 
1099  totalCost += subCost;
1100  if (l != list_head(path->bitmapquals))
1101  totalCost += 100.0 * cpu_operator_cost;
1102  }
1103  path->bitmapselectivity = selec;
1104  path->path.rows = 0; /* per above, not used */
1105  path->path.startup_cost = totalCost;
1106  path->path.total_cost = totalCost;
1107 }
double Selectivity
Definition: nodes.h:635
Selectivity bitmapselectivity
Definition: relation.h:1039
List * bitmapquals
Definition: relation.h:1038
Cost startup_cost
Definition: relation.h:929
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:930
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:928
Definition: relation.h:911
double Cost
Definition: nodes.h:636
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1029
void cost_bitmap_heap_scan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
Path bitmapqual,
double  loop_count 
)

Definition at line 928 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().

931 {
932  Cost startup_cost = 0;
933  Cost run_cost = 0;
934  Cost indexTotalCost;
935  QualCost qpqual_cost;
936  Cost cpu_per_tuple;
937  Cost cost_per_page;
938  Cost cpu_run_cost;
939  double tuples_fetched;
940  double pages_fetched;
941  double spc_seq_page_cost,
942  spc_random_page_cost;
943  double T;
944 
945  /* Should only be applied to base relations */
946  Assert(IsA(baserel, RelOptInfo));
947  Assert(baserel->relid > 0);
948  Assert(baserel->rtekind == RTE_RELATION);
949 
950  /* Mark the path with the correct row estimate */
951  if (param_info)
952  path->rows = param_info->ppi_rows;
953  else
954  path->rows = baserel->rows;
955 
956  if (!enable_bitmapscan)
957  startup_cost += disable_cost;
958 
959  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
960  loop_count, &indexTotalCost,
961  &tuples_fetched);
962 
963  startup_cost += indexTotalCost;
964  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
965 
966  /* Fetch estimated page costs for tablespace containing table. */
968  &spc_random_page_cost,
969  &spc_seq_page_cost);
970 
971  /*
972  * For small numbers of pages we should charge spc_random_page_cost
973  * apiece, while if nearly all the table's pages are being read, it's more
974  * appropriate to charge spc_seq_page_cost apiece. The effect is
975  * nonlinear, too. For lack of a better idea, interpolate like this to
976  * determine the cost per page.
977  */
978  if (pages_fetched >= 2.0)
979  cost_per_page = spc_random_page_cost -
980  (spc_random_page_cost - spc_seq_page_cost)
981  * sqrt(pages_fetched / T);
982  else
983  cost_per_page = spc_random_page_cost;
984 
985  run_cost += pages_fetched * cost_per_page;
986 
987  /*
988  * Estimate CPU costs per tuple.
989  *
990  * Often the indexquals don't need to be rechecked at each tuple ... but
991  * not always, especially not if there are enough tuples involved that the
992  * bitmaps become lossy. For the moment, just assume they will be
993  * rechecked always. This means we charge the full freight for all the
994  * scan clauses.
995  */
996  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
997 
998  startup_cost += qpqual_cost.startup;
999  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1000  cpu_run_cost = cpu_per_tuple * tuples_fetched;
1001 
1002  /* Adjust costing for parallelism, if used. */
1003  if (path->parallel_workers > 0)
1004  {
1005  double parallel_divisor = get_parallel_divisor(path);
1006 
1007  /* The CPU cost is divided among all the workers. */
1008  cpu_run_cost /= parallel_divisor;
1009 
1010  path->rows = clamp_row_est(path->rows / parallel_divisor);
1011  }
1012 
1013 
1014  run_cost += cpu_run_cost;
1015 
1016  /* tlist eval costs are paid per output row, not per tuple scanned */
1017  startup_cost += path->pathtarget->cost.startup;
1018  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1019 
1020  path->startup_cost = startup_cost;
1021  path->total_cost = startup_cost + run_cost;
1022 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
PathTarget * pathtarget
Definition: relation.h:918
Oid reltablespace
Definition: relation.h:523
int parallel_workers
Definition: relation.h:924
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
static const uint32 T[65]
Definition: md5.c:101
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4995
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:522
bool enable_bitmapscan
Definition: costsize.c:121
RTEKind rtekind
Definition: relation.h:524
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
BlockNumber pages
Definition: relation.h:533
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
double clamp_row_est(double nrows)
Definition: costsize.c:173
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:5024
double Cost
Definition: nodes.h:636
void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

Definition at line 1116 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().

1117 {
1118  Cost totalCost;
1119  Selectivity selec;
1120  ListCell *l;
1121 
1122  /*
1123  * We estimate OR selectivity on the assumption that the inputs are
1124  * non-overlapping, since that's often the case in "x IN (list)" type
1125  * situations. Of course, we clamp to 1.0 at the end.
1126  *
1127  * The runtime cost of the BitmapOr itself is estimated at 100x
1128  * cpu_operator_cost for each tbm_union needed. Probably too small,
1129  * definitely too simplistic? We are aware that the tbm_unions are
1130  * optimized out when the inputs are BitmapIndexScans.
1131  */
1132  totalCost = 0.0;
1133  selec = 0.0;
1134  foreach(l, path->bitmapquals)
1135  {
1136  Path *subpath = (Path *) lfirst(l);
1137  Cost subCost;
1138  Selectivity subselec;
1139 
1140  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1141 
1142  selec += subselec;
1143 
1144  totalCost += subCost;
1145  if (l != list_head(path->bitmapquals) &&
1146  !IsA(subpath, IndexPath))
1147  totalCost += 100.0 * cpu_operator_cost;
1148  }
1149  path->bitmapselectivity = Min(selec, 1.0);
1150  path->path.rows = 0; /* per above, not used */
1151  path->path.startup_cost = totalCost;
1152  path->path.total_cost = totalCost;
1153 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
#define Min(x, y)
Definition: c.h:806
double Selectivity
Definition: nodes.h:635
List * bitmapquals
Definition: relation.h:1051
Cost startup_cost
Definition: relation.h:929
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
double cpu_operator_cost
Definition: costsize.c:108
Selectivity bitmapselectivity
Definition: relation.h:1052
Cost total_cost
Definition: relation.h:930
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:928
Definition: relation.h:911
double Cost
Definition: nodes.h:636
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:1029
void cost_bitmap_tree_node ( Path path,
Cost cost,
Selectivity selec 
)

Definition at line 1029 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().

1030 {
1031  if (IsA(path, IndexPath))
1032  {
1033  *cost = ((IndexPath *) path)->indextotalcost;
1034  *selec = ((IndexPath *) path)->indexselectivity;
1035 
1036  /*
1037  * Charge a small amount per retrieved tuple to reflect the costs of
1038  * manipulating the bitmap. This is mostly to make sure that a bitmap
1039  * scan doesn't look to be the same cost as an indexscan to retrieve a
1040  * single tuple.
1041  */
1042  *cost += 0.1 * cpu_operator_cost * path->rows;
1043  }
1044  else if (IsA(path, BitmapAndPath))
1045  {
1046  *cost = path->total_cost;
1047  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
1048  }
1049  else if (IsA(path, BitmapOrPath))
1050  {
1051  *cost = path->total_cost;
1052  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
1053  }
1054  else
1055  {
1056  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
1057  *cost = *selec = 0; /* keep compiler quiet */
1058  }
1059 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
#define ERROR
Definition: elog.h:43
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:930
double rows
Definition: relation.h:928
#define nodeTag(nodeptr)
Definition: nodes.h:511
#define elog
Definition: elog.h:219
void cost_ctescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1483 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().

1485 {
1486  Cost startup_cost = 0;
1487  Cost run_cost = 0;
1488  QualCost qpqual_cost;
1489  Cost cpu_per_tuple;
1490 
1491  /* Should only be applied to base relations that are CTEs */
1492  Assert(baserel->relid > 0);
1493  Assert(baserel->rtekind == RTE_CTE);
1494 
1495  /* Mark the path with the correct row estimate */
1496  if (param_info)
1497  path->rows = param_info->ppi_rows;
1498  else
1499  path->rows = baserel->rows;
1500 
1501  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1502  cpu_per_tuple = cpu_tuple_cost;
1503 
1504  /* Add scanning CPU costs */
1505  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1506 
1507  startup_cost += qpqual_cost.startup;
1508  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1509  run_cost += cpu_per_tuple * baserel->tuples;
1510 
1511  /* tlist eval costs are paid per output row, not per tuple scanned */
1512  startup_cost += path->pathtarget->cost.startup;
1513  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1514 
1515  path->startup_cost = startup_cost;
1516  path->total_cost = startup_cost + run_cost;
1517 }
PathTarget * pathtarget
Definition: relation.h:918
double tuples
Definition: relation.h:534
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:929
Index relid
Definition: relation.h:522
RTEKind rtekind
Definition: relation.h:524
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
double Cost
Definition: nodes.h:636
void cost_functionscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1316 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().

1318 {
1319  Cost startup_cost = 0;
1320  Cost run_cost = 0;
1321  QualCost qpqual_cost;
1322  Cost cpu_per_tuple;
1323  RangeTblEntry *rte;
1324  QualCost exprcost;
1325 
1326  /* Should only be applied to base relations that are functions */
1327  Assert(baserel->relid > 0);
1328  rte = planner_rt_fetch(baserel->relid, root);
1329  Assert(rte->rtekind == RTE_FUNCTION);
1330 
1331  /* Mark the path with the correct row estimate */
1332  if (param_info)
1333  path->rows = param_info->ppi_rows;
1334  else
1335  path->rows = baserel->rows;
1336 
1337  /*
1338  * Estimate costs of executing the function expression(s).
1339  *
1340  * Currently, nodeFunctionscan.c always executes the functions to
1341  * completion before returning any rows, and caches the results in a
1342  * tuplestore. So the function eval cost is all startup cost, and per-row
1343  * costs are minimal.
1344  *
1345  * XXX in principle we ought to charge tuplestore spill costs if the
1346  * number of rows is large. However, given how phony our rowcount
1347  * estimates for functions tend to be, there's not a lot of point in that
1348  * refinement right now.
1349  */
1350  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1351 
1352  startup_cost += exprcost.startup + exprcost.per_tuple;
1353 
1354  /* Add scanning CPU costs */
1355  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1356 
1357  startup_cost += qpqual_cost.startup;
1358  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1359  run_cost += cpu_per_tuple * baserel->tuples;
1360 
1361  /* tlist eval costs are paid per output row, not per tuple scanned */
1362  startup_cost += path->pathtarget->cost.startup;
1363  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1364 
1365  path->startup_cost = startup_cost;
1366  path->total_cost = startup_cost + run_cost;
1367 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3390
PathTarget * pathtarget
Definition: relation.h:918
double tuples
Definition: relation.h:534
Definition: nodes.h:506
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:324
Cost startup_cost
Definition: relation.h:929
Index relid
Definition: relation.h:522
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
#define Assert(condition)
Definition: c.h:675
List * functions
Definition: parsenodes.h:965
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
RTEKind rtekind
Definition: parsenodes.h:916
double Cost
Definition: nodes.h:636
void cost_gather ( GatherPath path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
double *  rows 
)

Definition at line 349 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().

352 {
353  Cost startup_cost = 0;
354  Cost run_cost = 0;
355 
356  /* Mark the path with the correct row estimate */
357  if (rows)
358  path->path.rows = *rows;
359  else if (param_info)
360  path->path.rows = param_info->ppi_rows;
361  else
362  path->path.rows = rel->rows;
363 
364  startup_cost = path->subpath->startup_cost;
365 
366  run_cost = path->subpath->total_cost - path->subpath->startup_cost;
367 
368  /* Parallel setup and communication cost. */
369  startup_cost += parallel_setup_cost;
370  run_cost += parallel_tuple_cost * path->path.rows;
371 
372  path->path.startup_cost = startup_cost;
373  path->path.total_cost = (startup_cost + run_cost);
374 }
double parallel_setup_cost
Definition: costsize.c:110
Cost startup_cost
Definition: relation.h:929
Path * subpath
Definition: relation.h:1229
Cost total_cost
Definition: relation.h:930
double rows
Definition: relation.h:928
double ppi_rows
Definition: relation.h:877
Path path
Definition: relation.h:1228
double Cost
Definition: nodes.h:636
double parallel_tuple_cost
Definition: costsize.c:109
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 387 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().

391 {
392  Cost startup_cost = 0;
393  Cost run_cost = 0;
394  Cost comparison_cost;
395  double N;
396  double logN;
397 
398  /* Mark the path with the correct row estimate */
399  if (rows)
400  path->path.rows = *rows;
401  else if (param_info)
402  path->path.rows = param_info->ppi_rows;
403  else
404  path->path.rows = rel->rows;
405 
406  if (!enable_gathermerge)
407  startup_cost += disable_cost;
408 
409  /*
410  * Add one to the number of workers to account for the leader. This might
411  * be overgenerous since the leader will do less work than other workers
412  * in typical cases, but we'll go with it for now.
413  */
414  Assert(path->num_workers > 0);
415  N = (double) path->num_workers + 1;
416  logN = LOG2(N);
417 
418  /* Assumed cost per tuple comparison */
419  comparison_cost = 2.0 * cpu_operator_cost;
420 
421  /* Heap creation cost */
422  startup_cost += comparison_cost * N * logN;
423 
424  /* Per-tuple heap maintenance cost */
425  run_cost += path->path.rows * comparison_cost * logN;
426 
427  /* small cost for heap management, like cost_merge_append */
428  run_cost += cpu_operator_cost * path->path.rows;
429 
430  /*
431  * Parallel setup and communication cost. Since Gather Merge, unlike
432  * Gather, requires us to block until a tuple is available from every
433  * worker, we bump the IPC cost up a little bit as compared with Gather.
434  * For lack of a better idea, charge an extra 5%.
435  */
436  startup_cost += parallel_setup_cost;
437  run_cost += parallel_tuple_cost * path->path.rows * 1.05;
438 
439  path->path.startup_cost = startup_cost + input_startup_cost;
440  path->path.total_cost = (startup_cost + run_cost + input_total_cost);
441 }
double parallel_setup_cost
Definition: costsize.c:110
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
double cpu_operator_cost
Definition: costsize.c:108
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
#define LOG2(x)
Definition: costsize.c:101
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
double ppi_rows
Definition: relation.h:877
bool enable_gathermerge
Definition: costsize.c:129
double Cost
Definition: nodes.h:636
double parallel_tuple_cost
Definition: costsize.c:109
void cost_group ( Path path,
PlannerInfo root,
int  numGroupCols,
double  numGroups,
Cost  input_startup_cost,
Cost  input_total_cost,
double  input_tuples 
)

Definition at line 2003 of file costsize.c.

References cpu_operator_cost, Path::rows, Path::startup_cost, and Path::total_cost.

Referenced by choose_hashed_setop(), and create_group_path().

2007 {
2008  Cost startup_cost;
2009  Cost total_cost;
2010 
2011  startup_cost = input_startup_cost;
2012  total_cost = input_total_cost;
2013 
2014  /*
2015  * Charge one cpu_operator_cost per comparison per input tuple. We assume
2016  * all columns get compared at most of the tuples.
2017  */
2018  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
2019 
2020  path->rows = numGroups;
2021  path->startup_cost = startup_cost;
2022  path->total_cost = total_cost;
2023 }
Cost startup_cost
Definition: relation.h:929
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:930
double rows
Definition: relation.h:928
double Cost
Definition: nodes.h:636
void cost_index ( IndexPath path,
PlannerInfo root,
double  loop_count,
bool  partial_path 
)

Definition at line 462 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(), 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().

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

Definition at line 1782 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().

1785 {
1786  Cost startup_cost = input_startup_cost;
1787  Cost run_cost = input_total_cost - input_startup_cost;
1788  double nbytes = relation_byte_size(tuples, width);
1789  long work_mem_bytes = work_mem * 1024L;
1790 
1791  path->rows = tuples;
1792 
1793  /*
1794  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1795  * reflect bookkeeping overhead. (This rate must be more than what
1796  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1797  * if it is exactly the same then there will be a cost tie between
1798  * nestloop with A outer, materialized B inner and nestloop with B outer,
1799  * materialized A inner. The extra cost ensures we'll prefer
1800  * materializing the smaller rel.) Note that this is normally a good deal
1801  * less than cpu_tuple_cost; which is OK because a Material plan node
1802  * doesn't do qual-checking or projection, so it's got less overhead than
1803  * most plan nodes.
1804  */
1805  run_cost += 2 * cpu_operator_cost * tuples;
1806 
1807  /*
1808  * If we will spill to disk, charge at the rate of seq_page_cost per page.
1809  * This cost is assumed to be evenly spread through the plan run phase,
1810  * which isn't exactly accurate but our cost model doesn't allow for
1811  * nonuniform costs within the run phase.
1812  */
1813  if (nbytes > work_mem_bytes)
1814  {
1815  double npages = ceil(nbytes / BLCKSZ);
1816 
1817  run_cost += seq_page_cost * npages;
1818  }
1819 
1820  path->startup_cost = startup_cost;
1821  path->total_cost = startup_cost + run_cost;
1822 }
Cost startup_cost
Definition: relation.h:929
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4974
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:930
double rows
Definition: relation.h:928
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:636
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 1731 of file costsize.c.

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

Referenced by create_merge_append_path().

1735 {
1736  Cost startup_cost = 0;
1737  Cost run_cost = 0;
1738  Cost comparison_cost;
1739  double N;
1740  double logN;
1741 
1742  /*
1743  * Avoid log(0)...
1744  */
1745  N = (n_streams < 2) ? 2.0 : (double) n_streams;
1746  logN = LOG2(N);
1747 
1748  /* Assumed cost per tuple comparison */
1749  comparison_cost = 2.0 * cpu_operator_cost;
1750 
1751  /* Heap creation cost */
1752  startup_cost += comparison_cost * N * logN;
1753 
1754  /* Per-tuple heap maintenance cost */
1755  run_cost += tuples * comparison_cost * logN;
1756 
1757  /*
1758  * Also charge a small amount (arbitrarily set equal to operator cost) per
1759  * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1760  * node doesn't do qual-checking or projection, so it has less overhead
1761  * than most plan nodes.
1762  */
1763  run_cost += cpu_operator_cost * tuples;
1764 
1765  path->startup_cost = startup_cost + input_startup_cost;
1766  path->total_cost = startup_cost + run_cost + input_total_cost;
1767 }
Cost startup_cost
Definition: relation.h:929
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:930
#define LOG2(x)
Definition: costsize.c:101
double Cost
Definition: nodes.h:636
void cost_qual_eval ( QualCost cost,
List quals,
PlannerInfo root 
)

Definition at line 3364 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_index(), cost_subplan(), cost_tidscan(), 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().

3365 {
3366  cost_qual_eval_context context;
3367  ListCell *l;
3368 
3369  context.root = root;
3370  context.total.startup = 0;
3371  context.total.per_tuple = 0;
3372 
3373  /* We don't charge any cost for the implicit ANDing at top level ... */
3374 
3375  foreach(l, quals)
3376  {
3377  Node *qual = (Node *) lfirst(l);
3378 
3379  cost_qual_eval_walker(qual, &context);
3380  }
3381 
3382  *cost = context.total;
3383 }
PlannerInfo * root
Definition: costsize.c:133
Definition: nodes.h:506
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:3404
#define lfirst(lc)
Definition: pg_list.h:106
void cost_qual_eval_node ( QualCost cost,
Node qual,
PlannerInfo root 
)

Definition at line 3390 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_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().

3391 {
3392  cost_qual_eval_context context;
3393 
3394  context.root = root;
3395  context.total.startup = 0;
3396  context.total.per_tuple = 0;
3397 
3398  cost_qual_eval_walker(qual, &context);
3399 
3400  *cost = context.total;
3401 }
PlannerInfo * root
Definition: costsize.c:133
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:3404
void cost_recursive_union ( Path runion,
Path nrterm,
Path rterm 
)

Definition at line 1527 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().

1528 {
1529  Cost startup_cost;
1530  Cost total_cost;
1531  double total_rows;
1532 
1533  /* We probably have decent estimates for the non-recursive term */
1534  startup_cost = nrterm->startup_cost;
1535  total_cost = nrterm->total_cost;
1536  total_rows = nrterm->rows;
1537 
1538  /*
1539  * We arbitrarily assume that about 10 recursive iterations will be
1540  * needed, and that we've managed to get a good fix on the cost and output
1541  * size of each one of them. These are mighty shaky assumptions but it's
1542  * hard to see how to do better.
1543  */
1544  total_cost += 10 * rterm->total_cost;
1545  total_rows += 10 * rterm->rows;
1546 
1547  /*
1548  * Also charge cpu_tuple_cost per row to account for the costs of
1549  * manipulating the tuplestores. (We don't worry about possible
1550  * spill-to-disk costs.)
1551  */
1552  total_cost += cpu_tuple_cost * total_rows;
1553 
1554  runion->startup_cost = startup_cost;
1555  runion->total_cost = total_cost;
1556  runion->rows = total_rows;
1557  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1558  rterm->pathtarget->width);
1559 }
PathTarget * pathtarget
Definition: relation.h:918
Cost startup_cost
Definition: relation.h:929
Cost total_cost
Definition: relation.h:930
#define Max(x, y)
Definition: c.h:800
double rows
Definition: relation.h:928
double cpu_tuple_cost
Definition: costsize.c:106
int width
Definition: relation.h:850
double Cost
Definition: nodes.h:636
void cost_samplescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 274 of file costsize.c.

References Assert, PathTarget::cost, cpu_tuple_cost, get_restriction_qual_cost(), get_tablespace_page_costs(), GetTsmRoutine(), TsmRoutine::NextSampleBlock, NULL, 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().

276 {
277  Cost startup_cost = 0;
278  Cost run_cost = 0;
279  RangeTblEntry *rte;
280  TableSampleClause *tsc;
281  TsmRoutine *tsm;
282  double spc_seq_page_cost,
283  spc_random_page_cost,
284  spc_page_cost;
285  QualCost qpqual_cost;
286  Cost cpu_per_tuple;
287 
288  /* Should only be applied to base relations with tablesample clauses */
289  Assert(baserel->relid > 0);
290  rte = planner_rt_fetch(baserel->relid, root);
291  Assert(rte->rtekind == RTE_RELATION);
292  tsc = rte->tablesample;
293  Assert(tsc != NULL);
294  tsm = GetTsmRoutine(tsc->tsmhandler);
295 
296  /* Mark the path with the correct row estimate */
297  if (param_info)
298  path->rows = param_info->ppi_rows;
299  else
300  path->rows = baserel->rows;
301 
302  /* fetch estimated page cost for tablespace containing table */
304  &spc_random_page_cost,
305  &spc_seq_page_cost);
306 
307  /* if NextSampleBlock is used, assume random access, else sequential */
308  spc_page_cost = (tsm->NextSampleBlock != NULL) ?
309  spc_random_page_cost : spc_seq_page_cost;
310 
311  /*
312  * disk costs (recall that baserel->pages has already been set to the
313  * number of pages the sampling method will visit)
314  */
315  run_cost += spc_page_cost * baserel->pages;
316 
317  /*
318  * CPU costs (recall that baserel->tuples has already been set to the
319  * number of tuples the sampling method will select). Note that we ignore
320  * execution cost of the TABLESAMPLE parameter expressions; they will be
321  * evaluated only once per scan, and in most usages they'll likely be
322  * simple constants anyway. We also don't charge anything for the
323  * calculations the sampling method might do internally.
324  */
325  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
326 
327  startup_cost += qpqual_cost.startup;
328  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
329  run_cost += cpu_per_tuple * baserel->tuples;
330  /* tlist eval costs are paid per output row, not per tuple scanned */
331  startup_cost += path->pathtarget->cost.startup;
332  run_cost += path->pathtarget->cost.per_tuple * path->rows;
333 
334  path->startup_cost = startup_cost;
335  path->total_cost = startup_cost + run_cost;
336 }
PathTarget * pathtarget
Definition: relation.h:918
double tuples
Definition: relation.h:534
Oid reltablespace
Definition: relation.h:523
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:324
Cost startup_cost
Definition: relation.h:929
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:522
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
TsmRoutine * GetTsmRoutine(Oid tsmhandler)
Definition: tablesample.c:27
BlockNumber pages
Definition: relation.h:533
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
RTEKind rtekind
Definition: parsenodes.h:916
struct TableSampleClause * tablesample
Definition: parsenodes.h:929
double Cost
Definition: nodes.h:636
void cost_seqscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 197 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(), NULL, 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().

199 {
200  Cost startup_cost = 0;
201  Cost cpu_run_cost;
202  Cost disk_run_cost;
203  double spc_seq_page_cost;
204  QualCost qpqual_cost;
205  Cost cpu_per_tuple;
206 
207  /* Should only be applied to base relations */
208  Assert(baserel->relid > 0);
209  Assert(baserel->rtekind == RTE_RELATION);
210 
211  /* Mark the path with the correct row estimate */
212  if (param_info)
213  path->rows = param_info->ppi_rows;
214  else
215  path->rows = baserel->rows;
216 
217  if (!enable_seqscan)
218  startup_cost += disable_cost;
219 
220  /* fetch estimated page cost for tablespace containing table */
222  NULL,
223  &spc_seq_page_cost);
224 
225  /*
226  * disk costs
227  */
228  disk_run_cost = spc_seq_page_cost * baserel->pages;
229 
230  /* CPU costs */
231  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
232 
233  startup_cost += qpqual_cost.startup;
234  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
235  cpu_run_cost = cpu_per_tuple * baserel->tuples;
236  /* tlist eval costs are paid per output row, not per tuple scanned */
237  startup_cost += path->pathtarget->cost.startup;
238  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
239 
240  /* Adjust costing for parallelism, if used. */
241  if (path->parallel_workers > 0)
242  {
243  double parallel_divisor = get_parallel_divisor(path);
244 
245  /* The CPU cost is divided among all the workers. */
246  cpu_run_cost /= parallel_divisor;
247 
248  /*
249  * It may be possible to amortize some of the I/O cost, but probably
250  * not very much, because most operating systems already do aggressive
251  * prefetching. For now, we assume that the disk run cost can't be
252  * amortized at all.
253  */
254 
255  /*
256  * In the case of a parallel plan, the row count needs to represent
257  * the number of tuples processed per worker.
258  */
259  path->rows = clamp_row_est(path->rows / parallel_divisor);
260  }
261 
262  path->startup_cost = startup_cost;
263  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
264 }
PathTarget * pathtarget
Definition: relation.h:918
double tuples
Definition: relation.h:534
Oid reltablespace
Definition: relation.h:523
int parallel_workers
Definition: relation.h:924
bool enable_seqscan
Definition: costsize.c:118
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4995
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:522
RTEKind rtekind
Definition: relation.h:524
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
BlockNumber pages
Definition: relation.h:533
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
double clamp_row_est(double nrows)
Definition: costsize.c:173
double Cost
Definition: nodes.h:636
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 1607 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().

1611 {
1612  Cost startup_cost = input_cost;
1613  Cost run_cost = 0;
1614  double input_bytes = relation_byte_size(tuples, width);
1615  double output_bytes;
1616  double output_tuples;
1617  long sort_mem_bytes = sort_mem * 1024L;
1618 
1619  if (!enable_sort)
1620  startup_cost += disable_cost;
1621 
1622  path->rows = tuples;
1623 
1624  /*
1625  * We want to be sure the cost of a sort is never estimated as zero, even
1626  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1627  */
1628  if (tuples < 2.0)
1629  tuples = 2.0;
1630 
1631  /* Include the default cost-per-comparison */
1632  comparison_cost += 2.0 * cpu_operator_cost;
1633 
1634  /* Do we have a useful LIMIT? */
1635  if (limit_tuples > 0 && limit_tuples < tuples)
1636  {
1637  output_tuples = limit_tuples;
1638  output_bytes = relation_byte_size(output_tuples, width);
1639  }
1640  else
1641  {
1642  output_tuples = tuples;
1643  output_bytes = input_bytes;
1644  }
1645 
1646  if (output_bytes > sort_mem_bytes)
1647  {
1648  /*
1649  * We'll have to use a disk-based sort of all the tuples
1650  */
1651  double npages = ceil(input_bytes / BLCKSZ);
1652  double nruns = input_bytes / sort_mem_bytes;
1653  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1654  double log_runs;
1655  double npageaccesses;
1656 
1657  /*
1658  * CPU costs
1659  *
1660  * Assume about N log2 N comparisons
1661  */
1662  startup_cost += comparison_cost * tuples * LOG2(tuples);
1663 
1664  /* Disk costs */
1665 
1666  /* Compute logM(r) as log(r) / log(M) */
1667  if (nruns > mergeorder)
1668  log_runs = ceil(log(nruns) / log(mergeorder));
1669  else
1670  log_runs = 1.0;
1671  npageaccesses = 2.0 * npages * log_runs;
1672  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1673  startup_cost += npageaccesses *
1674  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1675  }
1676  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1677  {
1678  /*
1679  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1680  * a total number of tuple comparisons of N log2 K; but the constant
1681  * factor is a bit higher than for quicksort. Tweak it so that the
1682  * cost curve is continuous at the crossover point.
1683  */
1684  startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1685  }
1686  else
1687  {
1688  /* We'll use plain quicksort on all the input tuples */
1689  startup_cost += comparison_cost * tuples * LOG2(tuples);
1690  }
1691 
1692  /*
1693  * Also charge a small amount (arbitrarily set equal to operator cost) per
1694  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1695  * doesn't do qual-checking or projection, so it has less overhead than
1696  * most plan nodes. Note it's correct to use tuples not output_tuples
1697  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1698  * counting the LIMIT otherwise.
1699  */
1700  run_cost += cpu_operator_cost * tuples;
1701 
1702  path->startup_cost = startup_cost;
1703  path->total_cost = startup_cost + run_cost;
1704 }
bool enable_sort
Definition: costsize.c:123
double random_page_cost
Definition: costsize.c:105
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4974
Cost total_cost
Definition: relation.h:930
#define LOG2(x)
Definition: costsize.c:101
double rows
Definition: relation.h:928
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2289
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:636
void cost_subplan ( PlannerInfo root,
SubPlan subplan,
Plan plan 
)

Definition at line 3164 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().

3165 {
3166  QualCost sp_cost;
3167 
3168  /* Figure any cost for evaluating the testexpr */
3169  cost_qual_eval(&sp_cost,
3170  make_ands_implicit((Expr *) subplan->testexpr),
3171  root);
3172 
3173  if (subplan->useHashTable)
3174  {
3175  /*
3176  * If we are using a hash table for the subquery outputs, then the
3177  * cost of evaluating the query is a one-time cost. We charge one
3178  * cpu_operator_cost per tuple for the work of loading the hashtable,
3179  * too.
3180  */
3181  sp_cost.startup += plan->total_cost +
3182  cpu_operator_cost * plan->plan_rows;
3183 
3184  /*
3185  * The per-tuple costs include the cost of evaluating the lefthand
3186  * expressions, plus the cost of probing the hashtable. We already
3187  * accounted for the lefthand expressions as part of the testexpr, and
3188  * will also have counted one cpu_operator_cost for each comparison
3189  * operator. That is probably too low for the probing cost, but it's
3190  * hard to make a better estimate, so live with it for now.
3191  */
3192  }
3193  else
3194  {
3195  /*
3196  * Otherwise we will be rescanning the subplan output on each
3197  * evaluation. We need to estimate how much of the output we will
3198  * actually need to scan. NOTE: this logic should agree with the
3199  * tuple_fraction estimates used by make_subplan() in
3200  * plan/subselect.c.
3201  */
3202  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3203 
3204  if (subplan->subLinkType == EXISTS_SUBLINK)
3205  {
3206  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3207  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3208  }
3209  else if (subplan->subLinkType == ALL_SUBLINK ||
3210  subplan->subLinkType == ANY_SUBLINK)
3211  {
3212  /* assume we need 50% of the tuples */
3213  sp_cost.per_tuple += 0.50 * plan_run_cost;
3214  /* also charge a cpu_operator_cost per row examined */
3215  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3216  }
3217  else
3218  {
3219  /* assume we need all tuples */
3220  sp_cost.per_tuple += plan_run_cost;
3221  }
3222 
3223  /*
3224  * Also account for subplan's startup cost. If the subplan is
3225  * uncorrelated or undirect correlated, AND its topmost node is one
3226  * that materializes its output, assume that we'll only need to pay
3227  * its startup cost once; otherwise assume we pay the startup cost
3228  * every time.
3229  */
3230  if (subplan->parParam == NIL &&
3232  sp_cost.startup += plan->startup_cost;
3233  else
3234  sp_cost.per_tuple += plan->startup_cost;
3235  }
3236 
3237  subplan->startup_cost = sp_cost.startup;
3238  subplan->per_call_cost = sp_cost.per_tuple;
3239 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:120
SubLinkType subLinkType
Definition: primnodes.h:683
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
List * make_ands_implicit(Expr *clause)
Definition: clauses.c:377
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3364
Cost startup_cost
Definition: plannodes.h:114
double cpu_operator_cost
Definition: costsize.c:108
Node * testexpr
Definition: primnodes.h:685
Cost per_call_cost
Definition: primnodes.h:711
List * parParam
Definition: primnodes.h:707
#define nodeTag(nodeptr)
Definition: nodes.h:511
Cost total_cost
Definition: plannodes.h:115
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:566
bool useHashTable
Definition: primnodes.h:697
Cost startup_cost
Definition: primnodes.h:710
double clamp_row_est(double nrows)
Definition: costsize.c:173
double Cost
Definition: nodes.h:636
void cost_subqueryscan ( SubqueryScanPath path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1267 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().

1269 {
1270  Cost startup_cost;
1271  Cost run_cost;
1272  QualCost qpqual_cost;
1273  Cost cpu_per_tuple;
1274 
1275  /* Should only be applied to base relations that are subqueries */
1276  Assert(baserel->relid > 0);
1277  Assert(baserel->rtekind == RTE_SUBQUERY);
1278 
1279  /* Mark the path with the correct row estimate */
1280  if (param_info)
1281  path->path.rows = param_info->ppi_rows;
1282  else
1283  path->path.rows = baserel->rows;
1284 
1285  /*
1286  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1287  * any restriction clauses and tlist that will be attached to the
1288  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1289  * projection overhead.
1290  */
1291  path->path.startup_cost = path->subpath->startup_cost;
1292  path->path.total_cost = path->subpath->total_cost;
1293 
1294  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1295 
1296  startup_cost = qpqual_cost.startup;
1297  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1298  run_cost = cpu_per_tuple * baserel->tuples;
1299 
1300  /* tlist eval costs are paid per output row, not per tuple scanned */
1301  startup_cost += path->path.pathtarget->cost.startup;
1302  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1303 
1304  path->path.startup_cost += startup_cost;
1305  path->path.total_cost += startup_cost + run_cost;
1306 }
PathTarget * pathtarget
Definition: relation.h:918
double tuples
Definition: relation.h:534
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:929
Index relid
Definition: relation.h:522
RTEKind rtekind
Definition: relation.h:524
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
double Cost
Definition: nodes.h:636
void cost_tableexprscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)
void cost_tablefuncscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1377 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().

1379 {
1380  Cost startup_cost = 0;
1381  Cost run_cost = 0;
1382  QualCost qpqual_cost;
1383  Cost cpu_per_tuple;
1384  RangeTblEntry *rte;
1385  QualCost exprcost;
1386 
1387  /* Should only be applied to base relations that are functions */
1388  Assert(baserel->relid > 0);
1389  rte = planner_rt_fetch(baserel->relid, root);
1390  Assert(rte->rtekind == RTE_TABLEFUNC);
1391 
1392  /* Mark the path with the correct row estimate */
1393  if (param_info)
1394  path->rows = param_info->ppi_rows;
1395  else
1396  path->rows = baserel->rows;
1397 
1398  /*
1399  * Estimate costs of executing the table func expression(s).
1400  *
1401  * XXX in principle we ought to charge tuplestore spill costs if the
1402  * number of rows is large. However, given how phony our rowcount
1403  * estimates for tablefuncs tend to be, there's not a lot of point in that
1404  * refinement right now.
1405  */
1406  cost_qual_eval_node(&exprcost, (Node *) rte->tablefunc, root);
1407 
1408  startup_cost += exprcost.startup + exprcost.per_tuple;
1409 
1410  /* Add scanning CPU costs */
1411  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1412 
1413  startup_cost += qpqual_cost.startup;
1414  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1415  run_cost += cpu_per_tuple * baserel->tuples;
1416 
1417  /* tlist eval costs are paid per output row, not per tuple scanned */
1418  startup_cost += path->pathtarget->cost.startup;
1419  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1420 
1421  path->startup_cost = startup_cost;
1422  path->total_cost = startup_cost + run_cost;
1423 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3390
PathTarget * pathtarget
Definition: relation.h:918
double tuples
Definition: relation.h:534
Definition: nodes.h:506
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:324
TableFunc * tablefunc
Definition: parsenodes.h:971
Cost startup_cost
Definition: relation.h:929
Index relid
Definition: relation.h:522
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
RTEKind rtekind
Definition: parsenodes.h:916
double Cost
Definition: nodes.h:636
void cost_tidscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
List tidquals,
ParamPathInfo param_info 
)

Definition at line 1164 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, NULL, 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().

1166 {
1167  Cost startup_cost = 0;
1168  Cost run_cost = 0;
1169  bool isCurrentOf = false;
1170  QualCost qpqual_cost;
1171  Cost cpu_per_tuple;
1172  QualCost tid_qual_cost;
1173  int ntuples;
1174  ListCell *l;
1175  double spc_random_page_cost;
1176 
1177  /* Should only be applied to base relations */
1178  Assert(baserel->relid > 0);
1179  Assert(baserel->rtekind == RTE_RELATION);
1180 
1181  /* Mark the path with the correct row estimate */
1182  if (param_info)
1183  path->rows = param_info->ppi_rows;
1184  else
1185  path->rows = baserel->rows;
1186 
1187  /* Count how many tuples we expect to retrieve */
1188  ntuples = 0;
1189  foreach(l, tidquals)
1190  {
1191  if (IsA(lfirst(l), ScalarArrayOpExpr))
1192  {
1193  /* Each element of the array yields 1 tuple */
1195  Node *arraynode = (Node *) lsecond(saop->args);
1196 
1197  ntuples += estimate_array_length(arraynode);
1198  }
1199  else if (IsA(lfirst(l), CurrentOfExpr))
1200  {
1201  /* CURRENT OF yields 1 tuple */
1202  isCurrentOf = true;
1203  ntuples++;
1204  }
1205  else
1206  {
1207  /* It's just CTID = something, count 1 tuple */
1208  ntuples++;
1209  }
1210  }
1211 
1212  /*
1213  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1214  * understands how to do it correctly. Therefore, honor enable_tidscan
1215  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1216  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1217  * subtract off here; that's to prevent other plan types such as seqscan
1218  * from winning.
1219  */
1220  if (isCurrentOf)
1221  {
1223  startup_cost -= disable_cost;
1224  }
1225  else if (!enable_tidscan)
1226  startup_cost += disable_cost;
1227 
1228  /*
1229  * The TID qual expressions will be computed once, any other baserestrict
1230  * quals once per retrieved tuple.
1231  */
1232  cost_qual_eval(&tid_qual_cost, tidquals, root);
1233 
1234  /* fetch estimated page cost for tablespace containing table */
1236  &spc_random_page_cost,
1237  NULL);
1238 
1239  /* disk costs --- assume each tuple on a different page */
1240  run_cost += spc_random_page_cost * ntuples;
1241 
1242  /* Add scanning CPU costs */
1243  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1244 
1245  /* XXX currently we assume TID quals are a subset of qpquals */
1246  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1247  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1248  tid_qual_cost.per_tuple;
1249  run_cost += cpu_per_tuple * ntuples;
1250 
1251  /* tlist eval costs are paid per output row, not per tuple scanned */
1252  startup_cost += path->pathtarget->cost.startup;
1253  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1254 
1255  path->startup_cost = startup_cost;
1256  path->total_cost = startup_cost + run_cost;
1257 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
PathTarget * pathtarget
Definition: relation.h:918
bool enable_tidscan
Definition: costsize.c:122
Oid reltablespace
Definition: relation.h:523
Definition: nodes.h:506
#define lsecond(l)
Definition: pg_list.h:114
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
int estimate_array_length(Node *arrayexpr)
Definition: selfuncs.c:2083
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3364
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
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:522
RTEKind rtekind
Definition: relation.h:524
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
QualCost baserestrictcost
Definition: relation.h:551
double Cost
Definition: nodes.h:636
void cost_valuesscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

Definition at line 1433 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().

1435 {
1436  Cost startup_cost = 0;
1437  Cost run_cost = 0;
1438  QualCost qpqual_cost;
1439  Cost cpu_per_tuple;
1440 
1441  /* Should only be applied to base relations that are values lists */
1442  Assert(baserel->relid > 0);
1443  Assert(baserel->rtekind == RTE_VALUES);
1444 
1445  /* Mark the path with the correct row estimate */
1446  if (param_info)
1447  path->rows = param_info->ppi_rows;
1448  else
1449  path->rows = baserel->rows;
1450 
1451  /*
1452  * For now, estimate list evaluation cost at one operator eval per list
1453  * (probably pretty bogus, but is it worth being smarter?)
1454  */
1455  cpu_per_tuple = cpu_operator_cost;
1456 
1457  /* Add scanning CPU costs */
1458  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1459 
1460  startup_cost += qpqual_cost.startup;
1461  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1462  run_cost += cpu_per_tuple * baserel->tuples;
1463 
1464  /* tlist eval costs are paid per output row, not per tuple scanned */
1465  startup_cost += path->pathtarget->cost.startup;
1466  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1467 
1468  path->startup_cost = startup_cost;
1469  path->total_cost = startup_cost + run_cost;
1470 }
PathTarget * pathtarget
Definition: relation.h:918
double tuples
Definition: relation.h:534
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:929
double cpu_operator_cost
Definition: costsize.c:108
Index relid
Definition: relation.h:522
RTEKind rtekind
Definition: relation.h:524
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3631
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
double Cost
Definition: nodes.h:636
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 1933 of file costsize.c.

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

Referenced by create_windowagg_path().

1937 {
1938  Cost startup_cost;
1939  Cost total_cost;
1940  ListCell *lc;
1941 
1942  startup_cost = input_startup_cost;
1943  total_cost = input_total_cost;
1944 
1945  /*
1946  * Window functions are assumed to cost their stated execution cost, plus
1947  * the cost of evaluating their input expressions, per tuple. Since they
1948  * may in fact evaluate their inputs at multiple rows during each cycle,
1949  * this could be a drastic underestimate; but without a way to know how
1950  * many rows the window function will fetch, it's hard to do better. In
1951  * any case, it's a good estimate for all the built-in window functions,
1952  * so we'll just do this for now.
1953  */
1954  foreach(lc, windowFuncs)
1955  {
1956  WindowFunc *wfunc = castNode(WindowFunc, lfirst(lc));
1957  Cost wfunccost;
1958  QualCost argcosts;
1959 
1960  wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1961 
1962  /* also add the input expressions' cost to per-input-row costs */
1963  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1964  startup_cost += argcosts.startup;
1965  wfunccost += argcosts.per_tuple;
1966 
1967  /*
1968  * Add the filter's cost to per-input-row costs. XXX We should reduce
1969  * input expression costs according to filter selectivity.
1970  */
1971  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
1972  startup_cost += argcosts.startup;
1973  wfunccost += argcosts.per_tuple;
1974 
1975  total_cost += wfunccost * input_tuples;
1976  }
1977 
1978  /*
1979  * We also charge cpu_operator_cost per grouping column per tuple for
1980  * grouping comparisons, plus cpu_tuple_cost per tuple for general
1981  * overhead.
1982  *
1983  * XXX this neglects costs of spooling the data to disk when it overflows
1984  * work_mem. Sooner or later that should get accounted for.
1985  */
1986  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1987  total_cost += cpu_tuple_cost * input_tuples;
1988 
1989  path->rows = input_tuples;
1990  path->startup_cost = startup_cost;
1991  path->total_cost = total_cost;
1992 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3390
List * args
Definition: primnodes.h:359
#define castNode(_type_, nodeptr)
Definition: nodes.h:575
Definition: nodes.h:506
float4 get_func_cost(Oid funcid)
Definition: lsyscache.c:1609
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:929
double cpu_operator_cost
Definition: costsize.c:108
Oid winfnoid
Definition: primnodes.h:355
Cost total_cost
Definition: relation.h:930
#define lfirst(lc)
Definition: pg_list.h:106
Expr * aggfilter
Definition: primnodes.h:360
double rows
Definition: relation.h:928
double cpu_tuple_cost
Definition: costsize.c:106
double Cost
Definition: nodes.h:636
void final_cost_hashjoin ( PlannerInfo root,
HashPath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 2940 of file costsize.c.

References approx_tuple_count(), Assert, bms_is_subset(), castNode, clamp_row_est(), RestrictInfo::clause, PathTarget::cost, cost_qual_eval(), cpu_tuple_cost, disable_cost, enable_hashjoin, estimate_hash_bucketsize(), get_leftop(), get_parallel_divisor(), get_rightop(), JoinPath::innerjoinpath, IsA, JOIN_ANTI, JOIN_SEMI, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, RestrictInfo::left_bucketsize, RestrictInfo::left_relids, lfirst, 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, RelOptInfo::relids, RestrictInfo::right_bucketsize, RestrictInfo::right_relids, rint(), RelOptInfo::rows, Path::rows, JoinCostWorkspace::run_cost, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, and Path::total_cost.

Referenced by create_hashjoin_path().

2944 {
2945  Path *outer_path = path->jpath.outerjoinpath;
2946  Path *inner_path = path->jpath.innerjoinpath;
2947  double outer_path_rows = outer_path->rows;
2948  double inner_path_rows = inner_path->rows;
2949  List *hashclauses = path->path_hashclauses;
2950  Cost startup_cost = workspace->startup_cost;
2951  Cost run_cost = workspace->run_cost;
2952  int numbuckets = workspace->numbuckets;
2953  int numbatches = workspace->numbatches;
2954  Cost cpu_per_tuple;
2955  QualCost hash_qual_cost;
2956  QualCost qp_qual_cost;
2957  double hashjointuples;
2958  double virtualbuckets;
2959  Selectivity innerbucketsize;
2960  ListCell *hcl;
2961 
2962  /* Mark the path with the correct row estimate */
2963  if (path->jpath.path.param_info)
2964  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2965  else
2966  path->jpath.path.rows = path->jpath.path.parent->rows;
2967 
2968  /* For partial paths, scale row estimate. */
2969  if (path->jpath.path.parallel_workers > 0)
2970  {
2971  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
2972 
2973  path->jpath.path.rows =
2974  clamp_row_est(path->jpath.path.rows / parallel_divisor);
2975  }
2976 
2977  /*
2978  * We could include disable_cost in the preliminary estimate, but that
2979  * would amount to optimizing for the case where the join method is
2980  * disabled, which doesn't seem like the way to bet.
2981  */
2982  if (!enable_hashjoin)
2983  startup_cost += disable_cost;
2984 
2985  /* mark the path with estimated # of batches */
2986  path->num_batches = numbatches;
2987 
2988  /* and compute the number of "virtual" buckets in the whole join */
2989  virtualbuckets = (double) numbuckets *(double) numbatches;
2990 
2991  /*
2992  * Determine bucketsize fraction for inner relation. We use the smallest
2993  * bucketsize estimated for any individual hashclause; this is undoubtedly
2994  * conservative.
2995  *
2996  * BUT: if inner relation has been unique-ified, we can assume it's good
2997  * for hashing. This is important both because it's the right answer, and
2998  * because we avoid contaminating the cache with a value that's wrong for
2999  * non-unique-ified paths.
3000  */
3001  if (IsA(inner_path, UniquePath))
3002  innerbucketsize = 1.0 / virtualbuckets;
3003  else
3004  {
3005  innerbucketsize = 1.0;
3006  foreach(hcl, hashclauses)
3007  {
3008  RestrictInfo *restrictinfo = castNode(RestrictInfo, lfirst(hcl));
3009  Selectivity thisbucketsize;
3010 
3011  /*
3012  * First we have to figure out which side of the hashjoin clause
3013  * is the inner side.
3014  *
3015  * Since we tend to visit the same clauses over and over when
3016  * planning a large query, we cache the bucketsize estimate in the
3017  * RestrictInfo node to avoid repeated lookups of statistics.
3018  */
3019  if (bms_is_subset(restrictinfo->right_relids,
3020  inner_path->parent->relids))
3021  {
3022  /* righthand side is inner */
3023  thisbucketsize = restrictinfo->right_bucketsize;
3024  if (thisbucketsize < 0)
3025  {
3026  /* not cached yet */
3027  thisbucketsize =
3029  get_rightop(restrictinfo->clause),
3030  virtualbuckets);
3031  restrictinfo->right_bucketsize = thisbucketsize;
3032  }
3033  }
3034  else
3035  {
3036  Assert(bms_is_subset(restrictinfo->left_relids,
3037  inner_path->parent->relids));
3038  /* lefthand side is inner */
3039  thisbucketsize = restrictinfo->left_bucketsize;
3040  if (thisbucketsize < 0)
3041  {
3042  /* not cached yet */
3043  thisbucketsize =
3045  get_leftop(restrictinfo->clause),
3046  virtualbuckets);
3047  restrictinfo->left_bucketsize = thisbucketsize;
3048  }
3049  }
3050 
3051  if (innerbucketsize > thisbucketsize)
3052  innerbucketsize = thisbucketsize;
3053  }
3054  }
3055 
3056  /*
3057  * Compute cost of the hashquals and qpquals (other restriction clauses)
3058  * separately.
3059  */
3060  cost_qual_eval(&hash_qual_cost, hashclauses, root);
3061  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
3062  qp_qual_cost.startup -= hash_qual_cost.startup;
3063  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
3064 
3065  /* CPU costs */
3066 
3067  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI)
3068  {
3069  double outer_matched_rows;
3070  Selectivity inner_scan_frac;
3071 
3072  /*
3073  * SEMI or ANTI join: executor will stop after first match.
3074  *
3075  * For an outer-rel row that has at least one match, we can expect the
3076  * bucket scan to stop after a fraction 1/(match_count+1) of the
3077  * bucket's rows, if the matches are evenly distributed. Since they
3078  * probably aren't quite evenly distributed, we apply a fuzz factor of
3079  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
3080  * to clamp inner_scan_frac to at most 1.0; but since match_count is
3081  * at least 1, no such clamp is needed now.)
3082  */
3083  outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
3084  inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
3085 
3086  startup_cost += hash_qual_cost.startup;
3087  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
3088  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
3089 
3090  /*
3091  * For unmatched outer-rel rows, the picture is quite a lot different.
3092  * In the first place, there is no reason to assume that these rows
3093  * preferentially hit heavily-populated buckets; instead assume they
3094  * are uncorrelated with the inner distribution and so they see an
3095  * average bucket size of inner_path_rows / virtualbuckets. In the
3096  * second place, it seems likely that they will have few if any exact
3097  * hash-code matches and so very few of the tuples in the bucket will
3098  * actually require eval of the hash quals. We don't have any good
3099  * way to estimate how many will, but for the moment assume that the
3100  * effective cost per bucket entry is one-tenth what it is for
3101  * matchable tuples.
3102  */
3103  run_cost += hash_qual_cost.per_tuple *
3104  (outer_path_rows - outer_matched_rows) *
3105  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
3106 
3107  /* Get # of tuples that will pass the basic join */
3108  if (path->jpath.jointype == JOIN_SEMI)
3109  hashjointuples = outer_matched_rows;
3110  else
3111  hashjointuples = outer_path_rows - outer_matched_rows;
3112  }
3113  else
3114  {
3115  /*
3116  * The number of tuple comparisons needed is the number of outer
3117  * tuples times the typical number of tuples in a hash bucket, which
3118  * is the inner relation size times its bucketsize fraction. At each
3119  * one, we need to evaluate the hashjoin quals. But actually,
3120  * charging the full qual eval cost at each tuple is pessimistic,
3121  * since we don't evaluate the quals unless the hash values match
3122  * exactly. For lack of a better idea, halve the cost estimate to
3123  * allow for that.
3124  */
3125  startup_cost += hash_qual_cost.startup;
3126  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
3127  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
3128 
3129  /*
3130  * Get approx # tuples passing the hashquals. We use
3131  * approx_tuple_count here because we need an estimate done with
3132  * JOIN_INNER semantics.
3133  */
3134  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
3135  }
3136 
3137  /*
3138  * For each tuple that gets through the hashjoin proper, we charge
3139  * cpu_tuple_cost plus the cost of evaluating additional restriction
3140  * clauses that are to be applied at the join. (This is pessimistic since
3141  * not all of the quals may get evaluated at each tuple.)
3142  */
3143  startup_cost += qp_qual_cost.startup;
3144  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
3145  run_cost += cpu_per_tuple * hashjointuples;
3146 
3147  /* tlist eval costs are paid per output row, not per tuple scanned */
3148  startup_cost += path->jpath.path.pathtarget->cost.startup;
3149  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
3150 
3151  path->jpath.path.startup_cost = startup_cost;
3152  path->jpath.path.total_cost = startup_cost + run_cost;
3153 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
JoinPath jpath
Definition: relation.h:1322
PathTarget * pathtarget
Definition: relation.h:918
int num_batches
Definition: relation.h:1324
#define castNode(_type_, nodeptr)
Definition: nodes.h:575
Selectivity outer_match_frac
Definition: relation.h:2113
Path * innerjoinpath
Definition: relation.h:1257
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:3874
int parallel_workers
Definition: relation.h:924
ParamPathInfo * param_info
Definition: relation.h:920
Relids left_relids
Definition: relation.h:1726
double Selectivity
Definition: nodes.h:635
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:3364
Node * get_leftop(const Expr *clause)
Definition: clauses.c:198
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1259
RelOptInfo * parent
Definition: relation.h:917
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4995
Relids relids
Definition: relation.h:494
double rint(double x)
Definition: rint.c:22
Expr * clause
Definition: relation.h:1699
Path * outerjoinpath
Definition: relation.h:1256
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
Selectivity left_bucketsize
Definition: relation.h:1760
Relids right_relids
Definition: relation.h:1727
Path path
Definition: relation.h:1252
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
Node * get_rightop(const Expr *clause)
Definition: clauses.c:215
double ppi_rows
Definition: relation.h:877
bool enable_hashjoin
Definition: costsize.c:128
Selectivity estimate_hash_bucketsize(PlannerInfo *root, Node *hashkey, double nbuckets)
Definition: selfuncs.c:3600
Selectivity match_count
Definition: relation.h:2114
Selectivity right_bucketsize
Definition: relation.h:1761
JoinType jointype
Definition: relation.h:1254
List * path_hashclauses
Definition: relation.h:1323
double clamp_row_est(double nrows)
Definition: costsize.c:173
Definition: pg_list.h:45
Definition: relation.h:911
double Cost
Definition: nodes.h:636
void final_cost_mergejoin ( PlannerInfo root,
MergePath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo 
)

Definition at line 2545 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, JoinPath::innerjoinpath, MergePath::innersortkeys, IsA, JoinPath::joinrestrictinfo, MergePath::jpath, 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, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, Path::total_cost, PathTarget::width, and work_mem.

Referenced by create_mergejoin_path().

2548 {
2549  Path *outer_path = path->jpath.outerjoinpath;
2550  Path *inner_path = path->jpath.innerjoinpath;
2551  double inner_path_rows = inner_path->rows;
2552  List *mergeclauses = path->path_mergeclauses;
2553  List *innersortkeys = path->innersortkeys;
2554  Cost startup_cost = workspace->startup_cost;
2555  Cost run_cost = workspace->run_cost;
2556  Cost inner_run_cost = workspace->inner_run_cost;
2557  double outer_rows = workspace->outer_rows;
2558  double inner_rows = workspace->inner_rows;
2559  double outer_skip_rows = workspace->outer_skip_rows;
2560  double inner_skip_rows = workspace->inner_skip_rows;
2561  Cost cpu_per_tuple,
2562  bare_inner_cost,
2563  mat_inner_cost;
2564  QualCost merge_qual_cost;
2565  QualCost qp_qual_cost;
2566  double mergejointuples,
2567  rescannedtuples;
2568  double rescanratio;
2569 
2570  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2571  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2572  inner_path_rows = 1;
2573 
2574  /* Mark the path with the correct row estimate */
2575  if (path->jpath.path.param_info)
2576  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2577  else
2578  path->jpath.path.rows = path->jpath.path.parent->rows;
2579 
2580  /* For partial paths, scale row estimate. */
2581  if (path->jpath.path.parallel_workers > 0)
2582  {
2583  double parallel_divisor = get_parallel_divisor(&path->jpath.path);
2584 
2585  path->jpath.path.rows =
2586  clamp_row_est(path->jpath.path.rows / parallel_divisor);
2587  }
2588 
2589  /*
2590  * We could include disable_cost in the preliminary estimate, but that
2591  * would amount to optimizing for the case where the join method is
2592  * disabled, which doesn't seem like the way to bet.
2593  */
2594  if (!enable_mergejoin)
2595  startup_cost += disable_cost;
2596 
2597  /*
2598  * Compute cost of the mergequals and qpquals (other restriction clauses)
2599  * separately.
2600  */
2601  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2602  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2603  qp_qual_cost.startup -= merge_qual_cost.startup;
2604  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2605 
2606  /*
2607  * Get approx # tuples passing the mergequals. We use approx_tuple_count
2608  * here because we need an estimate done with JOIN_INNER semantics.
2609  */
2610  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2611 
2612  /*
2613  * When there are equal merge keys in the outer relation, the mergejoin
2614  * must rescan any matching tuples in the inner relation. This means
2615  * re-fetching inner tuples; we have to estimate how often that happens.
2616  *
2617  * For regular inner and outer joins, the number of re-fetches can be
2618  * estimated approximately as size of merge join output minus size of
2619  * inner relation. Assume that the distinct key values are 1, 2, ..., and
2620  * denote the number of values of each key in the outer relation as m1,
2621  * m2, ...; in the inner relation, n1, n2, ... Then we have
2622  *
2623  * size of join = m1 * n1 + m2 * n2 + ...
2624  *
2625  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2626  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2627  * relation
2628  *
2629  * This equation works correctly for outer tuples having no inner match
2630  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2631  * are effectively subtracting those from the number of rescanned tuples,
2632  * when we should not. Can we do better without expensive selectivity
2633  * computations?
2634  *
2635  * The whole issue is moot if we are working from a unique-ified outer
2636  * input.
2637  */
2638  if (IsA(outer_path, UniquePath))
2639  rescannedtuples = 0;
2640  else
2641  {
2642  rescannedtuples = mergejointuples - inner_path_rows;
2643  /* Must clamp because of possible underestimate */
2644  if (rescannedtuples < 0)
2645  rescannedtuples = 0;
2646  }
2647  /* We'll inflate various costs this much to account for rescanning */
2648  rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
2649 
2650  /*
2651  * Decide whether we want to materialize the inner input to shield it from
2652  * mark/restore and performing re-fetches. Our cost model for regular
2653  * re-fetches is that a re-fetch costs the same as an original fetch,
2654  * which is probably an overestimate; but on the other hand we ignore the
2655  * bookkeeping costs of mark/restore. Not clear if it's worth developing
2656  * a more refined model. So we just need to inflate the inner run cost by
2657  * rescanratio.
2658  */
2659  bare_inner_cost = inner_run_cost * rescanratio;
2660 
2661  /*
2662  * When we interpose a Material node the re-fetch cost is assumed to be
2663  * just cpu_operator_cost per tuple, independently of the underlying
2664  * plan's cost; and we charge an extra cpu_operator_cost per original
2665  * fetch as well. Note that we're assuming the materialize node will
2666  * never spill to disk, since it only has to remember tuples back to the
2667  * last mark. (If there are a huge number of duplicates, our other cost
2668  * factors will make the path so expensive that it probably won't get
2669  * chosen anyway.) So we don't use cost_rescan here.
2670  *
2671  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
2672  * of the generated Material node.
2673  */
2674  mat_inner_cost = inner_run_cost +
2675  cpu_operator_cost * inner_path_rows * rescanratio;
2676 
2677  /*
2678  * Prefer materializing if it looks cheaper, unless the user has asked to
2679  * suppress materialization.
2680  */
2681  if (enable_material && mat_inner_cost < bare_inner_cost)
2682  path->materialize_inner = true;
2683 
2684  /*
2685  * Even if materializing doesn't look cheaper, we *must* do it if the
2686  * inner path is to be used directly (without sorting) and it doesn't
2687  * support mark/restore.
2688  *
2689  * Since the inner side must be ordered, and only Sorts and IndexScans can
2690  * create order to begin with, and they both support mark/restore, you
2691  * might think there's no problem --- but you'd be wrong. Nestloop and
2692  * merge joins can *preserve* the order of their inputs, so they can be
2693  * selected as the input of a mergejoin, and they don't support
2694  * mark/restore at present.
2695  *
2696  * We don't test the value of enable_material here, because
2697  * materialization is required for correctness in this case, and turning
2698  * it off does not entitle us to deliver an invalid plan.
2699  */
2700  else if (innersortkeys == NIL &&
2701  !ExecSupportsMarkRestore(inner_path))
2702  path->materialize_inner = true;
2703 
2704  /*
2705  * Also, force materializing if the inner path is to be sorted and the
2706  * sort is expected to spill to disk. This is because the final merge
2707  * pass can be done on-the-fly if it doesn't have to support mark/restore.
2708  * We don't try to adjust the cost estimates for this consideration,
2709  * though.
2710  *
2711  * Since materialization is a performance optimization in this case,
2712  * rather than necessary for correctness, we skip it if enable_material is
2713  * off.
2714  */
2715  else if (enable_material && innersortkeys != NIL &&
2716  relation_byte_size(inner_path_rows,
2717  inner_path->pathtarget->width) >
2718  (work_mem * 1024L))
2719  path->materialize_inner = true;
2720  else
2721  path->materialize_inner = false;
2722 
2723  /* Charge the right incremental cost for the chosen case */
2724  if (path->materialize_inner)
2725  run_cost += mat_inner_cost;
2726  else
2727  run_cost += bare_inner_cost;
2728 
2729  /* CPU costs */
2730 
2731  /*
2732  * The number of tuple comparisons needed is approximately number of outer
2733  * rows plus number of inner rows plus number of rescanned tuples (can we
2734  * refine this?). At each one, we need to evaluate the mergejoin quals.
2735  */
2736  startup_cost += merge_qual_cost.startup;
2737  startup_cost += merge_qual_cost.per_tuple *
2738  (outer_skip_rows + inner_skip_rows * rescanratio);
2739  run_cost += merge_qual_cost.per_tuple *
2740  ((outer_rows - outer_skip_rows) +
2741  (inner_rows - inner_skip_rows) * rescanratio);
2742 
2743  /*
2744  * For each tuple that gets through the mergejoin proper, we charge
2745  * cpu_tuple_cost plus the cost of evaluating additional restriction
2746  * clauses that are to be applied at the join. (This is pessimistic since
2747  * not all of the quals may get evaluated at each tuple.)
2748  *
2749  * Note: we could adjust for SEMI/ANTI joins skipping some qual
2750  * evaluations here, but it's probably not worth the trouble.
2751  */
2752  startup_cost += qp_qual_cost.startup;
2753  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2754  run_cost += cpu_per_tuple * mergejointuples;
2755 
2756  /* tlist eval costs are paid per output row, not per tuple scanned */
2757  startup_cost += path->jpath.path.pathtarget->cost.startup;
2758  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
2759 
2760  path->jpath.path.startup_cost = startup_cost;
2761  path->jpath.path.total_cost = startup_cost + run_cost;
2762 }
#define NIL
Definition: pg_list.h:69
List * path_mergeclauses
Definition: relation.h:1305
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
PathTarget * pathtarget
Definition: relation.h:918
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:395
bool materialize_inner
Definition: relation.h:1308
Path * innerjoinpath
Definition: relation.h:1257
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:3874
int parallel_workers
Definition: relation.h:924
ParamPathInfo * param_info
Definition: relation.h:920
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:3364
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1259
RelOptInfo * parent
Definition: relation.h:917
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4995
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4974
Path * outerjoinpath
Definition: relation.h:1256
int work_mem
Definition: globals.c:112
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
double outer_skip_rows
Definition: relation.h:2165
bool enable_mergejoin
Definition: costsize.c:127
Path path
Definition: relation.h:1252
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
List * innersortkeys
Definition: relation.h:1307
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
int width
Definition: relation.h:850
JoinPath jpath
Definition: relation.h:1304
double inner_skip_rows
Definition: relation.h:2166
double clamp_row_est(double nrows)
Definition: costsize.c:173
Definition: pg_list.h:45
Definition: relation.h:911
double Cost
Definition: nodes.h:636
bool enable_material
Definition: costsize.c:126
void final_cost_nestloop ( PlannerInfo root,
NestPath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 2126 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, 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, QualCost::startup, Path::startup_cost, JoinCostWorkspace::startup_cost, and Path::total_cost.

Referenced by create_nestloop_path().

2130 {
2131  Path *outer_path = path->outerjoinpath;
2132  Path *inner_path = path->innerjoinpath;
2133  double outer_path_rows = outer_path->rows;
2134  double inner_path_rows = inner_path->rows;
2135  Cost startup_cost = workspace->startup_cost;
2136  Cost run_cost = workspace->run_cost;
2137  Cost cpu_per_tuple;
2138  QualCost restrict_qual_cost;
2139  double ntuples;
2140 
2141  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2142  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2143  outer_path_rows = 1;
2144  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2145  inner_path_rows = 1;
2146 
2147  /* Mark the path with the correct row estimate */
2148  if (path->path.param_info)
2149  path->path.rows = path->path.param_info->ppi_rows;
2150  else
2151  path->path.rows = path->path.parent->rows;
2152 
2153  /* For partial paths, scale row estimate. */
2154  if (path->path.parallel_workers > 0)
2155  {
2156  double parallel_divisor = get_parallel_divisor(&path->path);
2157 
2158  path->path.rows =
2159  clamp_row_est(path->path.rows / parallel_divisor);
2160  }
2161 
2162  /*
2163  * We could include disable_cost in the preliminary estimate, but that
2164  * would amount to optimizing for the case where the join method is
2165  * disabled, which doesn't seem like the way to bet.
2166  */
2167  if (!enable_nestloop)
2168  startup_cost += disable_cost;
2169 
2170  /* cost of inner-relation source data (we already dealt with outer rel) */
2171 
2172  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI)
2173  {
2174  /*
2175  * SEMI or ANTI join: executor will stop after first match.
2176  */
2177  Cost inner_run_cost = workspace->inner_run_cost;
2178  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2179  double outer_matched_rows;
2180  Selectivity inner_scan_frac;
2181 
2182  /*
2183  * For an outer-rel row that has at least one match, we can expect the
2184  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2185  * rows, if the matches are evenly distributed. Since they probably
2186  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2187  * that fraction. (If we used a larger fuzz factor, we'd have to
2188  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2189  * least 1, no such clamp is needed now.)
2190  */
2191  outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2192  inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2193 
2194  /*
2195  * Compute number of tuples processed (not number emitted!). First,
2196  * account for successfully-matched outer rows.
2197  */
2198  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2199 
2200  /*
2201  * Now we need to estimate the actual costs of scanning the inner
2202  * relation, which may be quite a bit less than N times inner_run_cost
2203  * due to early scan stops. We consider two cases. If the inner path
2204  * is an indexscan using all the joinquals as indexquals, then an
2205  * unmatched outer row results in an indexscan returning no rows,
2206  * which is probably quite cheap. Otherwise, the executor will have
2207  * to scan the whole inner rel for an unmatched row; not so cheap.
2208  */
2209  if (has_indexed_join_quals(path))
2210  {
2211  /*
2212  * Successfully-matched outer rows will only require scanning
2213  * inner_scan_frac of the inner relation. In this case, we don't
2214  * need to charge the full inner_run_cost even when that's more
2215  * than inner_rescan_run_cost, because we can assume that none of
2216  * the inner scans ever scan the whole inner relation. So it's
2217  * okay to assume that all the inner scan executions can be
2218  * fractions of the full cost, even if materialization is reducing
2219  * the rescan cost. At this writing, it's impossible to get here
2220  * for a materialized inner scan, so inner_run_cost and
2221  * inner_rescan_run_cost will be the same anyway; but just in
2222  * case, use inner_run_cost for the first matched tuple and
2223  * inner_rescan_run_cost for additional ones.
2224  */
2225  run_cost += inner_run_cost * inner_scan_frac;
2226  if (outer_matched_rows > 1)
2227  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2228 
2229  /*
2230  * Add the cost of inner-scan executions for unmatched outer rows.
2231  * We estimate this as the same cost as returning the first tuple
2232  * of a nonempty scan. We consider that these are all rescans,
2233  * since we used inner_run_cost once already.
2234  */
2235  run_cost += (outer_path_rows - outer_matched_rows) *
2236  inner_rescan_run_cost / inner_path_rows;
2237 
2238  /*
2239  * We won't be evaluating any quals at all for unmatched rows, so
2240  * don't add them to ntuples.
2241  */
2242  }
2243  else
2244  {
2245  /*
2246  * Here, a complicating factor is that rescans may be cheaper than
2247  * first scans. If we never scan all the way to the end of the
2248  * inner rel, it might be (depending on the plan type) that we'd
2249  * never pay the whole inner first-scan run cost. However it is
2250  * difficult to estimate whether that will happen (and it could
2251  * not happen if there are any unmatched outer rows!), so be
2252  * conservative and always charge the whole first-scan cost once.
2253  */
2254  run_cost += inner_run_cost;
2255 
2256  /* Add inner run cost for additional outer tuples having matches */
2257  if (outer_matched_rows > 1)
2258  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2259 
2260  /* Add inner run cost for unmatched outer tuples */
2261  run_cost += (outer_path_rows - outer_matched_rows) *
2262  inner_rescan_run_cost;
2263 
2264  /* And count the unmatched join tuples as being processed */
2265  ntuples += (outer_path_rows - outer_matched_rows) *
2266  inner_path_rows;
2267  }
2268  }
2269  else
2270  {
2271  /* Normal-case source costs were included in preliminary estimate */
2272 
2273  /* Compute number of tuples processed (not number emitted!) */
2274  ntuples = outer_path_rows * inner_path_rows;
2275  }
2276 
2277  /* CPU costs */
2278  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2279  startup_cost += restrict_qual_cost.startup;
2280  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2281  run_cost += cpu_per_tuple * ntuples;
2282 
2283  /* tlist eval costs are paid per output row, not per tuple scanned */
2284  startup_cost += path->path.pathtarget->cost.startup;
2285  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
2286 
2287  path->path.startup_cost = startup_cost;
2288  path->path.total_cost = startup_cost + run_cost;
2289 }
PathTarget * pathtarget
Definition: relation.h:918
bool enable_nestloop
Definition: costsize.c:125
Selectivity outer_match_frac
Definition: relation.h:2113
Path * innerjoinpath
Definition: relation.h:1257
int parallel_workers
Definition: relation.h:924
ParamPathInfo * param_info
Definition: relation.h:920
double Selectivity
Definition: nodes.h:635
Cost inner_rescan_run_cost
Definition: relation.h:2160
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:3364
Cost startup_cost
Definition: relation.h:929
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1259
RelOptInfo * parent
Definition: relation.h:917
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4995
double rint(double x)
Definition: rint.c:22
Path * outerjoinpath
Definition: relation.h:1256
double rows
Definition: relation.h:497
Cost total_cost
Definition: relation.h:930
Path path
Definition: relation.h:1252
static bool has_indexed_join_quals(NestPath *joinpath)
Definition: costsize.c:3781
double rows
Definition: relation.h:928
QualCost cost
Definition: relation.h:849
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:877
Selectivity match_count
Definition: relation.h:2114
JoinType jointype
Definition: relation.h:1254
double clamp_row_est(double nrows)
Definition: costsize.c:173
Definition: relation.h:911
double Cost
Definition: nodes.h:636
double get_parameterized_baserel_size ( PlannerInfo root,
RelOptInfo rel,
List param_clauses 
)

Definition at line 3960 of file costsize.c.

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

Referenced by get_baserel_parampathinfo().

3962 {
3963  List *allclauses;
3964  double nrows;
3965 
3966  /*
3967  * Estimate the number of rows returned by the parameterized scan, knowing
3968  * that it will apply all the extra join clauses as well as the rel's own
3969  * restriction clauses. Note that we force the clauses to be treated as
3970  * non-join clauses during selectivity estimation.
3971  */
3972  allclauses = list_concat(list_copy(param_clauses),
3973  rel->baserestrictinfo);
3974  nrows = rel->tuples *
3976  allclauses,
3977  rel->relid, /* do not use 0! */
3978  JOIN_INNER,
3979  NULL);
3980  nrows = clamp_row_est(nrows);
3981  /* For safety, make sure result is not more than the base estimate */
3982  if (nrows > rel->rows)
3983  nrows = rel->rows;
3984  return nrows;
3985 }
double tuples
Definition: relation.h:534
List * baserestrictinfo
Definition: relation.h:549
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:522
double rows
Definition: relation.h:497
#define NULL
Definition: c.h:229
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
double clamp_row_est(double nrows)
Definition: costsize.c:173
Definition: pg_list.h:45
double get_parameterized_joinrel_size ( PlannerInfo root,
RelOptInfo rel,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
List restrict_clauses 
)

Definition at line 4041 of file costsize.c.

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

Referenced by get_joinrel_parampathinfo().

4046 {
4047  double nrows;
4048 
4049  /*
4050  * Estimate the number of rows returned by the parameterized join as the
4051  * sizes of the input paths times the selectivity of the clauses that have
4052  * ended up at this join node.
4053  *
4054  * As with set_joinrel_size_estimates, the rowcount estimate could depend
4055  * on the pair of input paths provided, though ideally we'd get the same
4056  * estimate for any pair with the same parameterization.
4057  */
4058  nrows = calc_joinrel_size_estimate(root,
4059  outer_path->parent,
4060  inner_path->parent,
4061  outer_path->rows,
4062  inner_path->rows,
4063  sjinfo,
4064  restrict_clauses);
4065  /* For safety, make sure result is not more than the base estimate */
4066  if (nrows > rel->rows)
4067  nrows = rel->rows;
4068  return nrows;
4069 }
RelOptInfo * parent
Definition: relation.h:917
double rows
Definition: relation.h:497
double rows
Definition: relation.h:928
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:4081
double index_pages_fetched ( double  tuples_fetched,
BlockNumber  pages,
double  index_pages,
PlannerInfo root 
)

Definition at line 813 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().

815 {
816  double pages_fetched;
817  double total_pages;
818  double T,
819  b;
820 
821  /* T is # pages in table, but don't allow it to be zero */
822  T = (pages > 1) ? (double) pages : 1.0;
823 
824  /* Compute number of pages assumed to be competing for cache space */
825  total_pages = root->total_table_pages + index_pages;
826  total_pages = Max(total_pages, 1.0);
827  Assert(T <= total_pages);
828 
829  /* b is pro-rated share of effective_cache_size */
830  b = (double) effective_cache_size *T / total_pages;
831 
832  /* force it positive and integral */
833  if (b <= 1.0)
834  b = 1.0;
835  else
836  b = ceil(b);
837 
838  /* This part is the Mackert and Lohman formula */
839  if (T <= b)
840  {
841  pages_fetched =
842  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
843  if (pages_fetched >= T)
844  pages_fetched = T;
845  else
846  pages_fetched = ceil(pages_fetched);
847  }
848  else
849  {
850  double lim;
851 
852  lim = (2.0 * T * b) / (2.0 * T - b);
853  if (tuples_fetched <= lim)
854  {
855  pages_fetched =
856  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
857  }
858  else
859  {
860  pages_fetched =
861  b + (tuples_fetched - lim) * (T - b) / T;
862  }
863  pages_fetched = ceil(pages_fetched);
864  }
865  return pages_fetched;
866 }
int effective_cache_size
Definition: costsize.c:112
static const uint32 T[65]
Definition: md5.c:101
double total_table_pages
Definition: relation.h:288
#define Max(x, y)
Definition: c.h:800
#define Assert(condition)
Definition: c.h:675
void initial_cost_hashjoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List hashclauses,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 2846 of file costsize.c.

References cpu_operator_cost, cpu_tuple_cost, ExecChooseHashTableSize(), list_length(), JoinCostWorkspace::numbatches, JoinCostWorkspace::numbuckets, page_size(), 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().

2852 {
2853  Cost startup_cost = 0;
2854  Cost run_cost = 0;
2855  double outer_path_rows = outer_path->rows;
2856  double inner_path_rows = inner_path->rows;
2857  int num_hashclauses = list_length(hashclauses);
2858  int numbuckets;
2859  int numbatches;
2860  int num_skew_mcvs;
2861 
2862  /* cost of source data */
2863  startup_cost += outer_path->startup_cost;
2864  run_cost += outer_path->total_cost - outer_path->startup_cost;
2865  startup_cost += inner_path->total_cost;
2866 
2867  /*
2868  * Cost of computing hash function: must do it once per input tuple. We
2869  * charge one cpu_operator_cost for each column's hash function. Also,
2870  * tack on one cpu_tuple_cost per inner row, to model the costs of
2871  * inserting the row into the hashtable.
2872  *
2873  * XXX when a hashclause is more complex than a single operator, we really
2874  * should charge the extra eval costs of the left or right side, as
2875  * appropriate, here. This seems more work than it's worth at the moment.
2876  */
2877  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2878  * inner_path_rows;
2879  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2880 
2881  /*
2882  * Get hash table size that executor would use for inner relation.
2883  *
2884  * XXX for the moment, always assume that skew optimization will be
2885  * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2886  * trying to determine that for sure.
2887  *
2888  * XXX at some point it might be interesting to try to account for skew
2889  * optimization in the cost estimate, but for now, we don't.
2890  */
2891  ExecChooseHashTableSize(inner_path_rows,
2892  inner_path->pathtarget->width,
2893  true, /* useskew */
2894  &numbuckets,
2895  &numbatches,
2896  &num_skew_mcvs);
2897 
2898  /*
2899  * If inner relation is too big then we will need to "batch" the join,
2900  * which implies writing and reading most of the tuples to disk an extra
2901  * time. Charge seq_page_cost per page, since the I/O should be nice and
2902  * sequential. Writing the inner rel counts as startup cost, all the rest
2903  * as run cost.
2904  */
2905  if (numbatches > 1)
2906  {
2907  double outerpages = page_size(outer_path_rows,
2908  outer_path->pathtarget->width);
2909  double innerpages = page_size(inner_path_rows,
2910  inner_path->pathtarget->width);
2911 
2912  startup_cost += seq_page_cost * innerpages;
2913  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2914  }
2915 
2916  /* CPU costs left for later */
2917 
2918  /* Public result fields */
2919  workspace->startup_cost = startup_cost;
2920  workspace->total_cost = startup_cost + run_cost;
2921  /* Save private data for final_cost_hashjoin */
2922  workspace->run_cost = run_cost;
2923  workspace->numbuckets = numbuckets;
2924  workspace->numbatches = numbatches;
2925 }
PathTarget * pathtarget
Definition: relation.h:918
static double page_size(double tuples, int width)
Definition: costsize.c:4985
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:400
Cost startup_cost
Definition: relation.h:929
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:930
double rows
Definition: relation.h:928
static int list_length(const List *l)
Definition: pg_list.h:89
double cpu_tuple_cost
Definition: costsize.c:106
int width
Definition: relation.h:850
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:636
void initial_cost_mergejoin ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
List mergeclauses,
Path outer_path,
Path inner_path,
List outersortkeys,
List innersortkeys,
SpecialJoinInfo sjinfo 
)

Definition at line 2322 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().

2328 {
2329  Cost startup_cost = 0;
2330  Cost run_cost = 0;
2331  double outer_path_rows = outer_path->rows;
2332  double inner_path_rows = inner_path->rows;
2333  Cost inner_run_cost;
2334  double outer_rows,
2335  inner_rows,
2336  outer_skip_rows,
2337  inner_skip_rows;
2338  Selectivity outerstartsel,
2339  outerendsel,
2340  innerstartsel,
2341  innerendsel;
2342  Path sort_path; /* dummy for result of cost_sort */
2343 
2344  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2345  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2346  outer_path_rows = 1;
2347  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2348  inner_path_rows = 1;
2349 
2350  /*
2351  * A merge join will stop as soon as it exhausts either input stream
2352  * (unless it's an outer join, in which case the outer side has to be
2353  * scanned all the way anyway). Estimate fraction of the left and right
2354  * inputs that will actually need to be scanned. Likewise, we can
2355  * estimate the number of rows that will be skipped before the first join
2356  * pair is found, which should be factored into startup cost. We use only
2357  * the first (most significant) merge clause for this purpose. Since
2358  * mergejoinscansel() is a fairly expensive computation, we cache the
2359  * results in the merge clause RestrictInfo.
2360  */
2361  if (mergeclauses && jointype != JOIN_FULL)
2362  {
2363  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
2364  List *opathkeys;
2365  List *ipathkeys;
2366  PathKey *opathkey;
2367  PathKey *ipathkey;
2368  MergeScanSelCache *cache;
2369 
2370  /* Get the input pathkeys to determine the sort-order details */
2371  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
2372  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
2373  Assert(opathkeys);
2374  Assert(ipathkeys);
2375  opathkey = (PathKey *) linitial(opathkeys);
2376  ipathkey = (PathKey *) linitial(ipathkeys);
2377  /* debugging check */
2378  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2379  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2380  opathkey->pk_strategy != ipathkey->pk_strategy ||
2381  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2382  elog(ERROR, "left and right pathkeys do not match in mergejoin");
2383 
2384  /* Get the selectivity with caching */
2385  cache = cached_scansel(root, firstclause, opathkey);
2386 
2387  if (bms_is_subset(firstclause->left_relids,
2388  outer_path->parent->relids))
2389  {
2390  /* left side of clause is outer */
2391  outerstartsel = cache->leftstartsel;
2392  outerendsel = cache->leftendsel;
2393  innerstartsel = cache->rightstartsel;
2394  innerendsel = cache->rightendsel;
2395  }
2396  else
2397  {
2398  /* left side of clause is inner */
2399  outerstartsel = cache->rightstartsel;
2400  outerendsel = cache->rightendsel;
2401  innerstartsel = cache->leftstartsel;
2402  innerendsel = cache->leftendsel;
2403  }
2404  if (jointype == JOIN_LEFT ||
2405  jointype == JOIN_ANTI)
2406  {
2407  outerstartsel = 0.0;
2408  outerendsel = 1.0;
2409  }
2410  else if (jointype == JOIN_RIGHT)
2411  {
2412  innerstartsel = 0.0;
2413  innerendsel = 1.0;
2414  }
2415  }
2416  else
2417  {
2418  /* cope with clauseless or full mergejoin */
2419  outerstartsel = innerstartsel = 0.0;
2420  outerendsel = innerendsel = 1.0;
2421  }
2422 
2423  /*
2424  * Convert selectivities to row counts. We force outer_rows and
2425  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
2426  */
2427  outer_skip_rows = rint(outer_path_rows * outerstartsel);
2428  inner_skip_rows = rint(inner_path_rows * innerstartsel);
2429  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
2430  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
2431 
2432  Assert(outer_skip_rows <= outer_rows);
2433  Assert(inner_skip_rows <= inner_rows);
2434 
2435  /*
2436  * Readjust scan selectivities to account for above rounding. This is
2437  * normally an insignificant effect, but when there are only a few rows in
2438  * the inputs, failing to do this makes for a large percentage error.
2439  */
2440  outerstartsel = outer_skip_rows / outer_path_rows;
2441  innerstartsel = inner_skip_rows / inner_path_rows;
2442  outerendsel = outer_rows / outer_path_rows;
2443  innerendsel = inner_rows / inner_path_rows;
2444 
2445  Assert(outerstartsel <= outerendsel);
2446  Assert(innerstartsel <= innerendsel);
2447 
2448  /* cost of source data */
2449 
2450  if (outersortkeys) /* do we need to sort outer? */
2451  {
2452  cost_sort(&sort_path,
2453  root,
2454  outersortkeys,
2455  outer_path->total_cost,
2456  outer_path_rows,
2457  outer_path->pathtarget->width,
2458  0.0,
2459  work_mem,
2460  -1.0);
2461  startup_cost += sort_path.startup_cost;
2462  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2463  * outerstartsel;
2464  run_cost += (sort_path.total_cost - sort_path.startup_cost)
2465  * (outerendsel - outerstartsel);
2466  }
2467  else
2468  {
2469  startup_cost += outer_path->startup_cost;
2470  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
2471  * outerstartsel;
2472  run_cost += (outer_path->total_cost - outer_path->startup_cost)
2473  * (outerendsel - outerstartsel);
2474  }
2475 
2476  if (innersortkeys) /* do we need to sort inner? */
2477  {
2478  cost_sort(&sort_path,
2479  root,
2480  innersortkeys,
2481  inner_path->total_cost,
2482  inner_path_rows,
2483  inner_path->pathtarget->width,
2484  0.0,
2485  work_mem,
2486  -1.0);
2487  startup_cost += sort_path.startup_cost;
2488  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2489  * innerstartsel;
2490  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
2491  * (innerendsel - innerstartsel);
2492  }
2493  else
2494  {
2495  startup_cost += inner_path->startup_cost;
2496  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
2497  * innerstartsel;
2498  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
2499  * (innerendsel - innerstartsel);
2500  }
2501 
2502  /*
2503  * We can't yet determine whether rescanning occurs, or whether
2504  * materialization of the inner input should be done. The minimum
2505  * possible inner input cost, regardless of rescan and materialization
2506  * considerations, is inner_run_cost. We include that in
2507  * workspace->total_cost, but not yet in run_cost.
2508  */
2509 
2510  /* CPU costs left for later */
2511 
2512  /* Public result fields */
2513  workspace->startup_cost = startup_cost;
2514  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
2515  /* Save private data for final_cost_mergejoin */
2516  workspace->run_cost = run_cost;
2517  workspace->inner_run_cost = inner_run_cost;
2518  workspace->outer_rows = outer_rows;
2519  workspace->inner_rows = inner_rows;
2520  workspace->outer_skip_rows = outer_skip_rows;
2521  workspace->inner_skip_rows = inner_skip_rows;
2522 }
Selectivity leftendsel
Definition: relation.h:1780
PathTarget * pathtarget
Definition: relation.h:918
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:2768
Relids left_relids
Definition: relation.h:1726
double Selectivity
Definition: nodes.h:635
int pk_strategy
Definition: relation.h:816
#define linitial(l)
Definition: pg_list.h:110
bool pk_nulls_first
Definition: relation.h:817
#define ERROR
Definition: elog.h:43
Cost startup_cost
Definition: relation.h:929
RelOptInfo * parent
Definition: relation.h:917
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
Selectivity rightstartsel
Definition: relation.h:1781
Relids relids
Definition: relation.h:494
double rint(double x)
Definition: rint.c:22
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1607
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:930
double outer_skip_rows
Definition: relation.h:2165
List * pathkeys
Definition: relation.h:932
#define Assert(condition)
Definition: c.h:675
double rows
Definition: relation.h:928
EquivalenceClass * pk_eclass
Definition: relation.h:814
Oid pk_opfamily
Definition: relation.h:815
int width
Definition: relation.h:850
#define elog
Definition: elog.h:219
double inner_skip_rows
Definition: relation.h:2166
double clamp_row_est(double nrows)
Definition: costsize.c:173
Definition: pg_list.h:45
Definition: relation.h:911
Selectivity rightendsel
Definition: relation.h:1782
double Cost
Definition: nodes.h:636
Selectivity leftstartsel
Definition: relation.h:1779
void initial_cost_nestloop ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 2051 of file costsize.c.

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

Referenced by try_nestloop_path(), and try_partial_nestloop_path().

2056 {
2057  Cost startup_cost = 0;
2058  Cost run_cost = 0;
2059  double outer_path_rows = outer_path->rows;
2060  Cost inner_rescan_start_cost;
2061  Cost inner_rescan_total_cost;
2062  Cost inner_run_cost;
2063  Cost inner_rescan_run_cost;
2064 
2065  /* estimate costs to rescan the inner relation */
2066  cost_rescan(root, inner_path,
2067  &inner_rescan_start_cost,
2068  &inner_rescan_total_cost);
2069 
2070  /* cost of source data */
2071 
2072  /*
2073  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
2074  * before we can start returning tuples, so the join's startup cost is
2075  * their sum. We'll also pay the inner path's rescan startup cost
2076  * multiple times.
2077  */
2078  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
2079  run_cost += outer_path->total_cost - outer_path->startup_cost;
2080  if (outer_path_rows > 1)
2081  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
2082 
2083  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
2084  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
2085 
2086  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
2087  {
2088  /*
2089  * SEMI or ANTI join: executor will stop after first match.
2090  *
2091  * Getting decent estimates requires inspection of the join quals,
2092  * which we choose to postpone to final_cost_nestloop.
2093  */
2094 
2095  /* Save private data for final_cost_nestloop */
2096  workspace->inner_run_cost = inner_run_cost;
2097  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
2098  }
2099  else
2100  {
2101  /* Normal case; we'll scan whole input rel for each outer row */
2102  run_cost += inner_run_cost;
2103  if (outer_path_rows > 1)
2104  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
2105  }
2106 
2107  /* CPU costs left for later */
2108 
2109  /* Public result fields */
2110  workspace->startup_cost = startup_cost;
2111  workspace->total_cost = startup_cost + run_cost;
2112  /* Save private data for final_cost_nestloop */
2113  workspace->run_cost = run_cost;
2114 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:3257
Cost inner_rescan_run_cost
Definition: relation.h:2160
Cost startup_cost
Definition: relation.h:929
Cost total_cost
Definition: relation.h:930
double rows
Definition: relation.h:928
double Cost
Definition: nodes.h:636
void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 3930 of file costsize.c.

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

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

3931 {
3932  double nrows;
3933 
3934  /* Should only be applied to base relations */
3935  Assert(rel->relid > 0);
3936 
3937  nrows = rel->tuples *
3939  rel->baserestrictinfo,
3940  0,
3941  JOIN_INNER,
3942  NULL);
3943 
3944  rel->rows = clamp_row_est(nrows);
3945 
3947 
3948  set_rel_width(root, rel);
3949 }
double tuples
Definition: relation.h:534
List * baserestrictinfo
Definition: relation.h:549
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4738
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3364
Index relid
Definition: relation.h:522
double rows
Definition: relation.h:497
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:92
double clamp_row_est(double nrows)
Definition: costsize.c:173
QualCost baserestrictcost
Definition: relation.h:551
void set_cte_size_estimates ( PlannerInfo root,
RelOptInfo rel,
double  cte_rows 
)

Definition at line 4660 of file costsize.c.

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

Referenced by set_cte_pathlist(), and set_worktable_pathlist().

4661 {
4662  RangeTblEntry *rte;
4663 
4664  /* Should only be applied to base relations that are CTE references */
4665  Assert(rel->relid > 0);
4666  rte = planner_rt_fetch(rel->relid, root);
4667  Assert(rte->rtekind == RTE_CTE);
4668 
4669  if (rte->self_reference)
4670  {
4671  /*
4672  * In a self-reference, arbitrarily assume the average worktable size
4673  * is about 10 times the nonrecursive term's size.
4674  */
4675  rel->tuples = 10 * cte_rows;
4676  }
4677  else
4678  {
4679  /* Otherwise just believe the CTE's rowcount estimate */
4680  rel->tuples = cte_rows;
4681  }
4682 
4683  /* Now estimate number of output rows, etc */
4684  set_baserel_size_estimates(root, rel);
4685 }
double tuples
Definition: relation.h:534
#define planner_rt_fetch(rti, root)
Definition: relation.h:324
Index relid
Definition: relation.h:522
bool self_reference
Definition: parsenodes.h:983
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:3930
#define Assert(condition)
Definition: c.h:675
RTEKind rtekind
Definition: parsenodes.h:916
void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4703 of file costsize.c.

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

Referenced by set_foreign_size().

4704 {
4705  /* Should only be applied to base relations */
4706  Assert(rel->relid > 0);
4707 
4708  rel->rows = 1000; /* entirely bogus default estimate */
4709 
4711 
4712  set_rel_width(root, rel);
4713 }
List * baserestrictinfo
Definition: relation.h:549
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4738
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3364
Index relid
Definition: relation.h:522
double rows
Definition: relation.h:497
#define Assert(condition)
Definition: c.h:675
QualCost baserestrictcost
Definition: relation.h:551
void set_function_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4563 of file costsize.c.

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

Referenced by set_rel_size().

4564 {
4565  RangeTblEntry *rte;
4566  ListCell *lc;
4567 
4568  /* Should only be applied to base relations that are functions */
4569  Assert(rel->relid > 0);
4570  rte = planner_rt_fetch(rel->relid, root);
4571  Assert(rte->rtekind == RTE_FUNCTION);
4572 
4573  /*
4574  * Estimate number of rows the functions will return. The rowcount of the
4575  * node is that of the largest function result.
4576  */
4577  rel->tuples = 0;
4578  foreach(lc, rte->functions)
4579  {
4580  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
4581  double ntup = expression_returns_set_rows(rtfunc->funcexpr);
4582 
4583  if (ntup > rel->tuples)
4584  rel->tuples = ntup;
4585  }
4586 
4587  /* Now estimate number of output rows, etc */
4588  set_baserel_size_estimates(root, rel);
4589 }
double expression_returns_set_rows(Node *clause)
Definition: clauses.c:801
double tuples
Definition: relation.h:534
#define planner_rt_fetch(rti, root)
Definition: relation.h:324