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

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

References rint().

Referenced by approx_tuple_count(), bernoulli_samplescangetsamplesize(), calc_joinrel_size_estimate(), compute_bitmap_pages(), 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(), 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().

173 {
174  /*
175  * Force estimate to be at least one row, to make explain output look
176  * better and to avoid possible divide-by-zero when interpolating costs.
177  * Make it an integer, too.
178  */
179  if (nrows <= 1.0)
180  nrows = 1.0;
181  else
182  nrows = rint(nrows);
183 
184  return nrows;
185 }
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:174
Expr * get_notclausearg(Expr *notclause)
Definition: clauses.c:264
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Index varlevelsup
Definition: primnodes.h:151
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2399
Expr * orclause
Definition: relation.h:1668
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1568
double tuples
Definition: relation.h:529
Selectivity rowcomparesel(PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:2116
Relids clause_relids
Definition: relation.h:1652
bool pseudoconstant
Definition: relation.h:1645
Definition: nodes.h:508
double Selectivity
Definition: nodes.h:631
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:141
#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:1759
Selectivity norm_selec
Definition: relation.h:1675
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:1659
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:401
Selectivity outer_selec
Definition: relation.h:1678
bool not_clause(Node *clause)
Definition: clauses.c:235
Expr * clause
Definition: relation.h:1637
Index varno
Definition: primnodes.h:144
char * s2
bool or_clause(Node *clause)
Definition: clauses.c:279
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
Oid inputcollid
Definition: primnodes.h:478
void * arg
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1605
Oid opno
Definition: primnodes.h:473
#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:219
List * args
Definition: primnodes.h:479
Selectivity booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1494
Selectivity boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
Definition: selfuncs.c:1455
bool constisnull
Definition: primnodes.h:175
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:559
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:1652
bool pseudoconstant
Definition: relation.h:1645
Definition: nodes.h:508
Relids left_relids
Definition: relation.h:1664
double Selectivity
Definition: nodes.h:631
#define lsecond(l)
Definition: pg_list.h:114
void pfree(void *pointer)
Definition: mcxt.c:992
#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:1659
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:1637
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:604
char * s2
Relids right_relids
Definition: relation.h:1665
#define NULL
Definition: c.h:226
#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:473
List * args
Definition: primnodes.h:479
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 4830 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().

4832 {
4833  Cost indexTotalCost;
4834  Selectivity indexSelectivity;
4835  double T;
4836  double pages_fetched;
4837  double tuples_fetched;
4838 
4839  /*
4840  * Fetch total cost of obtaining the bitmap, as well as its total
4841  * selectivity.
4842  */
4843  cost_bitmap_tree_node(bitmapqual, &indexTotalCost, &indexSelectivity);
4844 
4845  /*
4846  * Estimate number of main-table pages fetched.
4847  */
4848  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
4849 
4850  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
4851 
4852  if (loop_count > 1)
4853  {
4854  /*
4855  * For repeated bitmap scans, scale up the number of tuples fetched in
4856  * the Mackert and Lohman formula by the number of scans, so that we
4857  * estimate the number of pages fetched by all the scans. Then
4858  * pro-rate for one scan.
4859  */
4860  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
4861  baserel->pages,
4862  get_indexpath_pages(bitmapqual),
4863  root);
4864  pages_fetched /= loop_count;
4865  }
4866  else
4867  {
4868  /*
4869  * For a single scan, the number of heap pages that need to be fetched
4870  * is the same as the Mackert and Lohman formula for the case T <= b
4871  * (ie, no re-reads needed).
4872  */
4873  pages_fetched =
4874  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
4875  }
4876 
4877  if (pages_fetched >= T)
4878  pages_fetched = T;
4879  else
4880  pages_fetched = ceil(pages_fetched);
4881 
4882  if (cost)
4883  *cost = indexTotalCost;
4884  if (tuple)
4885  *tuple = tuples_fetched;
4886 
4887  return pages_fetched;
4888 }
double tuples
Definition: relation.h:529
double Selectivity
Definition: nodes.h:631
static const uint32 T[65]
Definition: md5.c:101
BlockNumber pages
Definition: relation.h:528
static double get_indexpath_pages(Path *bitmapqual)
Definition: costsize.c:803
double clamp_row_est(double nrows)
Definition: costsize.c:172
double index_pages_fetched(double tuples_fetched, BlockNumber pages, double index_pages, PlannerInfo *root)
Definition: costsize.c:738
double Cost
Definition: nodes.h:632
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:940
void compute_semi_anti_join_factors ( PlannerInfo root,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
SpecialJoinInfo sjinfo,
List restrictlist,
SemiAntiJoinFactors semifactors 
)

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

3513 {
3514  Selectivity jselec;
3515  Selectivity nselec;
3516  Selectivity avgmatch;
3517  SpecialJoinInfo norm_sjinfo;
3518  List *joinquals;
3519  ListCell *l;
3520 
3521  /* Should only be called in these cases */
3522  Assert(jointype == JOIN_SEMI || jointype == JOIN_ANTI);
3523 
3524  /*
3525  * In an ANTI join, we must ignore clauses that are "pushed down", since
3526  * those won't affect the match logic. In a SEMI join, we do not
3527  * distinguish joinquals from "pushed down" quals, so just use the whole
3528  * restrictinfo list.
3529  */
3530  if (jointype == JOIN_ANTI)
3531  {
3532  joinquals = NIL;
3533  foreach(l, restrictlist)
3534  {
3535  RestrictInfo *rinfo = castNode(RestrictInfo, lfirst(l));
3536 
3537  if (!rinfo->is_pushed_down)
3538  joinquals = lappend(joinquals, rinfo);
3539  }
3540  }
3541  else
3542  joinquals = restrictlist;
3543 
3544  /*
3545  * Get the JOIN_SEMI or JOIN_ANTI selectivity of the join clauses.
3546  */
3547  jselec = clauselist_selectivity(root,
3548  joinquals,
3549  0,
3550  jointype,
3551  sjinfo);
3552 
3553  /*
3554  * Also get the normal inner-join selectivity of the join clauses.
3555  */
3556  norm_sjinfo.type = T_SpecialJoinInfo;
3557  norm_sjinfo.min_lefthand = outerrel->relids;
3558  norm_sjinfo.min_righthand = innerrel->relids;
3559  norm_sjinfo.syn_lefthand = outerrel->relids;
3560  norm_sjinfo.syn_righthand = innerrel->relids;
3561  norm_sjinfo.jointype = JOIN_INNER;
3562  /* we don't bother trying to make the remaining fields valid */
3563  norm_sjinfo.lhs_strict = false;
3564  norm_sjinfo.delay_upper_joins = false;
3565  norm_sjinfo.semi_can_btree = false;
3566  norm_sjinfo.semi_can_hash = false;
3567  norm_sjinfo.semi_operators = NIL;
3568  norm_sjinfo.semi_rhs_exprs = NIL;
3569 
3570  nselec = clauselist_selectivity(root,
3571  joinquals,
3572  0,
3573  JOIN_INNER,
3574  &norm_sjinfo);
3575 
3576  /* Avoid leaking a lot of ListCells */
3577  if (jointype == JOIN_ANTI)
3578  list_free(joinquals);
3579 
3580  /*
3581  * jselec can be interpreted as the fraction of outer-rel rows that have
3582  * any matches (this is true for both SEMI and ANTI cases). And nselec is
3583  * the fraction of the Cartesian product that matches. So, the average
3584  * number of matches for each outer-rel row that has at least one match is
3585  * nselec * inner_rows / jselec.
3586  *
3587  * Note: it is correct to use the inner rel's "rows" count here, even
3588  * though we might later be considering a parameterized inner path with
3589  * fewer rows. This is because we have included all the join clauses in
3590  * the selectivity estimate.
3591  */
3592  if (jselec > 0) /* protect against zero divide */
3593  {
3594  avgmatch = nselec * innerrel->rows / jselec;
3595  /* Clamp to sane range */
3596  avgmatch = Max(1.0, avgmatch);
3597  }
3598  else
3599  avgmatch = 1.0;
3600 
3601  semifactors->outer_match_frac = jselec;
3602  semifactors->match_count = avgmatch;
3603 }
#define NIL
Definition: pg_list.h:69
bool semi_can_btree
Definition: relation.h:1815
Relids min_righthand
Definition: relation.h:1808
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Selectivity outer_match_frac
Definition: relation.h:2032
NodeTag type
Definition: relation.h:1806
double Selectivity
Definition: nodes.h:631
Relids syn_lefthand
Definition: relation.h:1809
Relids syn_righthand
Definition: relation.h:1810
List * semi_rhs_exprs
Definition: relation.h:1818
bool semi_can_hash
Definition: relation.h:1816
Relids relids
Definition: relation.h:490
List * lappend(List *list, void *datum)
Definition: list.c:128
bool delay_upper_joins
Definition: relation.h:1813
double rows
Definition: relation.h:493
bool is_pushed_down
Definition: relation.h:1639
#define Max(x, y)
Definition: c.h:796
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
JoinType jointype
Definition: relation.h:1811
Selectivity match_count
Definition: relation.h:2033
List * semi_operators
Definition: relation.h:1817
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:1807
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 1691 of file costsize.c.

References AGG_HASHED, 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().

1696 {
1697  double output_tuples;
1698  Cost startup_cost;
1699  Cost total_cost;
1700  AggClauseCosts dummy_aggcosts;
1701 
1702  /* Use all-zero per-aggregate costs if NULL is passed */
1703  if (aggcosts == NULL)
1704  {
1705  Assert(aggstrategy == AGG_HASHED);
1706  MemSet(&dummy_aggcosts, 0, sizeof(AggClauseCosts));
1707  aggcosts = &dummy_aggcosts;
1708  }
1709 
1710  /*
1711  * The transCost.per_tuple component of aggcosts should be charged once
1712  * per input tuple, corresponding to the costs of evaluating the aggregate
1713  * transfns and their input expressions (with any startup cost of course
1714  * charged but once). The finalCost component is charged once per output
1715  * tuple, corresponding to the costs of evaluating the finalfns.
1716  *
1717  * If we are grouping, we charge an additional cpu_operator_cost per
1718  * grouping column per input tuple for grouping comparisons.
1719  *
1720  * We will produce a single output tuple if not grouping, and a tuple per
1721  * group otherwise. We charge cpu_tuple_cost for each output tuple.
1722  *
1723  * Note: in this cost model, AGG_SORTED and AGG_HASHED have exactly the
1724  * same total CPU cost, but AGG_SORTED has lower startup cost. If the
1725  * input path is already sorted appropriately, AGG_SORTED should be
1726  * preferred (since it has no risk of memory overflow). This will happen
1727  * as long as the computed total costs are indeed exactly equal --- but if
1728  * there's roundoff error we might do the wrong thing. So be sure that
1729  * the computations below form the same intermediate values in the same
1730  * order.
1731  */
1732  if (aggstrategy == AGG_PLAIN)
1733  {
1734  startup_cost = input_total_cost;
1735  startup_cost += aggcosts->transCost.startup;
1736  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1737  startup_cost += aggcosts->finalCost;
1738  /* we aren't grouping */
1739  total_cost = startup_cost + cpu_tuple_cost;
1740  output_tuples = 1;
1741  }
1742  else if (aggstrategy == AGG_SORTED)
1743  {
1744  /* Here we are able to deliver output on-the-fly */
1745  startup_cost = input_startup_cost;
1746  total_cost = input_total_cost;
1747  /* calcs phrased this way to match HASHED case, see note above */
1748  total_cost += aggcosts->transCost.startup;
1749  total_cost += aggcosts->transCost.per_tuple * input_tuples;
1750  total_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1751  total_cost += aggcosts->finalCost * numGroups;
1752  total_cost += cpu_tuple_cost * numGroups;
1753  output_tuples = numGroups;
1754  }
1755  else
1756  {
1757  /* must be AGG_HASHED */
1758  startup_cost = input_total_cost;
1759  if (!enable_hashagg)
1760  startup_cost += disable_cost;
1761  startup_cost += aggcosts->transCost.startup;
1762  startup_cost += aggcosts->transCost.per_tuple * input_tuples;
1763  startup_cost += (cpu_operator_cost * numGroupCols) * input_tuples;
1764  total_cost = startup_cost;
1765  total_cost += aggcosts->finalCost * numGroups;
1766  total_cost += cpu_tuple_cost * numGroups;
1767  output_tuples = numGroups;
1768  }
1769 
1770  path->rows = output_tuples;
1771  path->startup_cost = startup_cost;
1772  path->total_cost = total_cost;
1773 }
#define MemSet(start, val, len)
Definition: c.h:853
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:906
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:907
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
double cpu_tuple_cost
Definition: costsize.c:106
bool enable_hashagg
Definition: costsize.c:124
double Cost
Definition: nodes.h:632
void cost_bitmap_and_node ( BitmapAndPath path,
PlannerInfo root 
)

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

984 {
985  Cost totalCost;
986  Selectivity selec;
987  ListCell *l;
988 
989  /*
990  * We estimate AND selectivity on the assumption that the inputs are
991  * independent. This is probably often wrong, but we don't have the info
992  * to do better.
993  *
994  * The runtime cost of the BitmapAnd itself is estimated at 100x
995  * cpu_operator_cost for each tbm_intersect needed. Probably too small,
996  * definitely too simplistic?
997  */
998  totalCost = 0.0;
999  selec = 1.0;
1000  foreach(l, path->bitmapquals)
1001  {
1002  Path *subpath = (Path *) lfirst(l);
1003  Cost subCost;
1004  Selectivity subselec;
1005 
1006  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1007 
1008  selec *= subselec;
1009 
1010  totalCost += subCost;
1011  if (l != list_head(path->bitmapquals))
1012  totalCost += 100.0 * cpu_operator_cost;
1013  }
1014  path->bitmapselectivity = selec;
1015  path->path.rows = 0; /* per above, not used */
1016  path->path.startup_cost = totalCost;
1017  path->path.total_cost = totalCost;
1018 }
double Selectivity
Definition: nodes.h:631
Selectivity bitmapselectivity
Definition: relation.h:1016
List * bitmapquals
Definition: relation.h:1015
Cost startup_cost
Definition: relation.h:906
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:907
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
Definition: relation.h:888
double Cost
Definition: nodes.h:632
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:940
void cost_bitmap_heap_scan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
Path bitmapqual,
double  loop_count 
)

Definition at line 853 of file costsize.c.

References Assert, compute_bitmap_pages(), PathTarget::cost, cpu_tuple_cost, disable_cost, enable_bitmapscan, get_restriction_qual_cost(), get_tablespace_page_costs(), IsA, RelOptInfo::pages, 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().

856 {
857  Cost startup_cost = 0;
858  Cost run_cost = 0;
859  Cost indexTotalCost;
860  QualCost qpqual_cost;
861  Cost cpu_per_tuple;
862  Cost cost_per_page;
863  double tuples_fetched;
864  double pages_fetched;
865  double spc_seq_page_cost,
866  spc_random_page_cost;
867  double T;
868 
869  /* Should only be applied to base relations */
870  Assert(IsA(baserel, RelOptInfo));
871  Assert(baserel->relid > 0);
872  Assert(baserel->rtekind == RTE_RELATION);
873 
874  /* Mark the path with the correct row estimate */
875  if (param_info)
876  path->rows = param_info->ppi_rows;
877  else
878  path->rows = baserel->rows;
879 
880  if (!enable_bitmapscan)
881  startup_cost += disable_cost;
882 
883  pages_fetched = compute_bitmap_pages(root, baserel, bitmapqual,
884  loop_count, &indexTotalCost,
885  &tuples_fetched);
886 
887  startup_cost += indexTotalCost;
888  T = (baserel->pages > 1) ? (double) baserel->pages : 1.0;
889 
890  /* Fetch estimated page costs for tablespace containing table. */
892  &spc_random_page_cost,
893  &spc_seq_page_cost);
894 
895  /*
896  * For small numbers of pages we should charge spc_random_page_cost
897  * apiece, while if nearly all the table's pages are being read, it's more
898  * appropriate to charge spc_seq_page_cost apiece. The effect is
899  * nonlinear, too. For lack of a better idea, interpolate like this to
900  * determine the cost per page.
901  */
902  if (pages_fetched >= 2.0)
903  cost_per_page = spc_random_page_cost -
904  (spc_random_page_cost - spc_seq_page_cost)
905  * sqrt(pages_fetched / T);
906  else
907  cost_per_page = spc_random_page_cost;
908 
909  run_cost += pages_fetched * cost_per_page;
910 
911  /*
912  * Estimate CPU costs per tuple.
913  *
914  * Often the indexquals don't need to be rechecked at each tuple ... but
915  * not always, especially not if there are enough tuples involved that the
916  * bitmaps become lossy. For the moment, just assume they will be
917  * rechecked always. This means we charge the full freight for all the
918  * scan clauses.
919  */
920  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
921 
922  startup_cost += qpqual_cost.startup;
923  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
924 
925  run_cost += cpu_per_tuple * tuples_fetched;
926 
927  /* tlist eval costs are paid per output row, not per tuple scanned */
928  startup_cost += path->pathtarget->cost.startup;
929  run_cost += path->pathtarget->cost.per_tuple * path->rows;
930 
931  path->startup_cost = startup_cost;
932  path->total_cost = startup_cost + run_cost;
933 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
Oid reltablespace
Definition: relation.h:519
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
static const uint32 T[65]
Definition: md5.c:101
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
bool enable_bitmapscan
Definition: costsize.c:121
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
BlockNumber pages
Definition: relation.h:528
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, int loop_count, Cost *cost, double *tuple)
Definition: costsize.c:4830
double Cost
Definition: nodes.h:632
void cost_bitmap_or_node ( BitmapOrPath path,
PlannerInfo root 
)

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

1028 {
1029  Cost totalCost;
1030  Selectivity selec;
1031  ListCell *l;
1032 
1033  /*
1034  * We estimate OR selectivity on the assumption that the inputs are
1035  * non-overlapping, since that's often the case in "x IN (list)" type
1036  * situations. Of course, we clamp to 1.0 at the end.
1037  *
1038  * The runtime cost of the BitmapOr itself is estimated at 100x
1039  * cpu_operator_cost for each tbm_union needed. Probably too small,
1040  * definitely too simplistic? We are aware that the tbm_unions are
1041  * optimized out when the inputs are BitmapIndexScans.
1042  */
1043  totalCost = 0.0;
1044  selec = 0.0;
1045  foreach(l, path->bitmapquals)
1046  {
1047  Path *subpath = (Path *) lfirst(l);
1048  Cost subCost;
1049  Selectivity subselec;
1050 
1051  cost_bitmap_tree_node(subpath, &subCost, &subselec);
1052 
1053  selec += subselec;
1054 
1055  totalCost += subCost;
1056  if (l != list_head(path->bitmapquals) &&
1057  !IsA(subpath, IndexPath))
1058  totalCost += 100.0 * cpu_operator_cost;
1059  }
1060  path->bitmapselectivity = Min(selec, 1.0);
1061  path->path.rows = 0; /* per above, not used */
1062  path->path.startup_cost = totalCost;
1063  path->path.total_cost = totalCost;
1064 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define Min(x, y)
Definition: c.h:802
double Selectivity
Definition: nodes.h:631
List * bitmapquals
Definition: relation.h:1028
Cost startup_cost
Definition: relation.h:906
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:1029
Cost total_cost
Definition: relation.h:907
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
Definition: relation.h:888
double Cost
Definition: nodes.h:632
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
void cost_bitmap_tree_node(Path *path, Cost *cost, Selectivity *selec)
Definition: costsize.c:940
void cost_bitmap_tree_node ( Path path,
Cost cost,
Selectivity selec 
)

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

941 {
942  if (IsA(path, IndexPath))
943  {
944  *cost = ((IndexPath *) path)->indextotalcost;
945  *selec = ((IndexPath *) path)->indexselectivity;
946 
947  /*
948  * Charge a small amount per retrieved tuple to reflect the costs of
949  * manipulating the bitmap. This is mostly to make sure that a bitmap
950  * scan doesn't look to be the same cost as an indexscan to retrieve a
951  * single tuple.
952  */
953  *cost += 0.1 * cpu_operator_cost * path->rows;
954  }
955  else if (IsA(path, BitmapAndPath))
956  {
957  *cost = path->total_cost;
958  *selec = ((BitmapAndPath *) path)->bitmapselectivity;
959  }
960  else if (IsA(path, BitmapOrPath))
961  {
962  *cost = path->total_cost;
963  *selec = ((BitmapOrPath *) path)->bitmapselectivity;
964  }
965  else
966  {
967  elog(ERROR, "unrecognized node type: %d", nodeTag(path));
968  *cost = *selec = 0; /* keep compiler quiet */
969  }
970 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define ERROR
Definition: elog.h:43
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
#define nodeTag(nodeptr)
Definition: nodes.h:513
#define elog
Definition: elog.h:219
void cost_ctescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1340 {
1341  Cost startup_cost = 0;
1342  Cost run_cost = 0;
1343  QualCost qpqual_cost;
1344  Cost cpu_per_tuple;
1345 
1346  /* Should only be applied to base relations that are CTEs */
1347  Assert(baserel->relid > 0);
1348  Assert(baserel->rtekind == RTE_CTE);
1349 
1350  /* Mark the path with the correct row estimate */
1351  if (param_info)
1352  path->rows = param_info->ppi_rows;
1353  else
1354  path->rows = baserel->rows;
1355 
1356  /* Charge one CPU tuple cost per row for tuplestore manipulation */
1357  cpu_per_tuple = cpu_tuple_cost;
1358 
1359  /* Add scanning CPU costs */
1360  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1361 
1362  startup_cost += qpqual_cost.startup;
1363  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1364  run_cost += cpu_per_tuple * baserel->tuples;
1365 
1366  /* tlist eval costs are paid per output row, not per tuple scanned */
1367  startup_cost += path->pathtarget->cost.startup;
1368  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1369 
1370  path->startup_cost = startup_cost;
1371  path->total_cost = startup_cost + run_cost;
1372 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double Cost
Definition: nodes.h:632
void cost_functionscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1229 {
1230  Cost startup_cost = 0;
1231  Cost run_cost = 0;
1232  QualCost qpqual_cost;
1233  Cost cpu_per_tuple;
1234  RangeTblEntry *rte;
1235  QualCost exprcost;
1236 
1237  /* Should only be applied to base relations that are functions */
1238  Assert(baserel->relid > 0);
1239  rte = planner_rt_fetch(baserel->relid, root);
1240  Assert(rte->rtekind == RTE_FUNCTION);
1241 
1242  /* Mark the path with the correct row estimate */
1243  if (param_info)
1244  path->rows = param_info->ppi_rows;
1245  else
1246  path->rows = baserel->rows;
1247 
1248  /*
1249  * Estimate costs of executing the function expression(s).
1250  *
1251  * Currently, nodeFunctionscan.c always executes the functions to
1252  * completion before returning any rows, and caches the results in a
1253  * tuplestore. So the function eval cost is all startup cost, and per-row
1254  * costs are minimal.
1255  *
1256  * XXX in principle we ought to charge tuplestore spill costs if the
1257  * number of rows is large. However, given how phony our rowcount
1258  * estimates for functions tend to be, there's not a lot of point in that
1259  * refinement right now.
1260  */
1261  cost_qual_eval_node(&exprcost, (Node *) rte->functions, root);
1262 
1263  startup_cost += exprcost.startup + exprcost.per_tuple;
1264 
1265  /* Add scanning CPU costs */
1266  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1267 
1268  startup_cost += qpqual_cost.startup;
1269  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1270  run_cost += cpu_per_tuple * baserel->tuples;
1271 
1272  /* tlist eval costs are paid per output row, not per tuple scanned */
1273  startup_cost += path->pathtarget->cost.startup;
1274  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1275 
1276  path->startup_cost = startup_cost;
1277  path->total_cost = startup_cost + run_cost;
1278 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3225
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Definition: nodes.h:508
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
Cost startup_cost
Definition: relation.h:906
Index relid
Definition: relation.h:518
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
List * functions
Definition: parsenodes.h:931
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
RTEKind rtekind
Definition: parsenodes.h:882
double Cost
Definition: nodes.h:632
void cost_gather ( GatherPath path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info,
double *  rows 
)

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

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

1857 {
1858  Cost startup_cost;
1859  Cost total_cost;
1860 
1861  startup_cost = input_startup_cost;
1862  total_cost = input_total_cost;
1863 
1864  /*
1865  * Charge one cpu_operator_cost per comparison per input tuple. We assume
1866  * all columns get compared at most of the tuples.
1867  */
1868  total_cost += cpu_operator_cost * input_tuples * numGroupCols;
1869 
1870  path->rows = numGroups;
1871  path->startup_cost = startup_cost;
1872  path->total_cost = total_cost;
1873 }
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
double Cost
Definition: nodes.h:632
void cost_index ( IndexPath path,
PlannerInfo root,
double  loop_count,
bool  partial_path 
)

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

396 {
397  IndexOptInfo *index = path->indexinfo;
398  RelOptInfo *baserel = index->rel;
399  bool indexonly = (path->path.pathtype == T_IndexOnlyScan);
400  amcostestimate_function amcostestimate;
401  List *qpquals;
402  Cost startup_cost = 0;
403  Cost run_cost = 0;
404  Cost cpu_run_cost = 0;
405  Cost indexStartupCost;
406  Cost indexTotalCost;
407  Selectivity indexSelectivity;
408  double indexCorrelation,
409  csquared;
410  double spc_seq_page_cost,
411  spc_random_page_cost;
412  Cost min_IO_cost,
413  max_IO_cost;
414  QualCost qpqual_cost;
415  Cost cpu_per_tuple;
416  double tuples_fetched;
417  double pages_fetched;
418  double rand_heap_pages;
419  double index_pages;
420 
421  /* Should only be applied to base relations */
422  Assert(IsA(baserel, RelOptInfo) &&
423  IsA(index, IndexOptInfo));
424  Assert(baserel->relid > 0);
425  Assert(baserel->rtekind == RTE_RELATION);
426 
427  /*
428  * Mark the path with the correct row estimate, and identify which quals
429  * will need to be enforced as qpquals. We need not check any quals that
430  * are implied by the index's predicate, so we can use indrestrictinfo not
431  * baserestrictinfo as the list of relevant restriction clauses for the
432  * rel.
433  */
434  if (path->path.param_info)
435  {
436  path->path.rows = path->path.param_info->ppi_rows;
437  /* qpquals come from the rel's restriction clauses and ppi_clauses */
438  qpquals = list_concat(
440  path->indexquals),
442  path->indexquals));
443  }
444  else
445  {
446  path->path.rows = baserel->rows;
447  /* qpquals come from just the rel's restriction clauses */
449  path->indexquals);
450  }
451 
452  if (!enable_indexscan)
453  startup_cost += disable_cost;
454  /* we don't need to check enable_indexonlyscan; indxpath.c does that */
455 
456  /*
457  * Call index-access-method-specific code to estimate the processing cost
458  * for scanning the index, as well as the selectivity of the index (ie,
459  * the fraction of main-table tuples we will have to retrieve) and its
460  * correlation to the main-table tuple order. We need a cast here because
461  * relation.h uses a weak function type to avoid including amapi.h.
462  */
463  amcostestimate = (amcostestimate_function) index->amcostestimate;
464  amcostestimate(root, path, loop_count,
465  &indexStartupCost, &indexTotalCost,
466  &indexSelectivity, &indexCorrelation,
467  &index_pages);
468 
469  /*
470  * Save amcostestimate's results for possible use in bitmap scan planning.
471  * We don't bother to save indexStartupCost or indexCorrelation, because a
472  * bitmap scan doesn't care about either.
473  */
474  path->indextotalcost = indexTotalCost;
475  path->indexselectivity = indexSelectivity;
476 
477  /* all costs for touching index itself included here */
478  startup_cost += indexStartupCost;
479  run_cost += indexTotalCost - indexStartupCost;
480 
481  /* estimate number of main-table tuples fetched */
482  tuples_fetched = clamp_row_est(indexSelectivity * baserel->tuples);
483 
484  /* fetch estimated page costs for tablespace containing table */
486  &spc_random_page_cost,
487  &spc_seq_page_cost);
488 
489  /*----------
490  * Estimate number of main-table pages fetched, and compute I/O cost.
491  *
492  * When the index ordering is uncorrelated with the table ordering,
493  * we use an approximation proposed by Mackert and Lohman (see
494  * index_pages_fetched() for details) to compute the number of pages
495  * fetched, and then charge spc_random_page_cost per page fetched.
496  *
497  * When the index ordering is exactly correlated with the table ordering
498  * (just after a CLUSTER, for example), the number of pages fetched should
499  * be exactly selectivity * table_size. What's more, all but the first
500  * will be sequential fetches, not the random fetches that occur in the
501  * uncorrelated case. So if the number of pages is more than 1, we
502  * ought to charge
503  * spc_random_page_cost + (pages_fetched - 1) * spc_seq_page_cost
504  * For partially-correlated indexes, we ought to charge somewhere between
505  * these two estimates. We currently interpolate linearly between the
506  * estimates based on the correlation squared (XXX is that appropriate?).
507  *
508  * If it's an index-only scan, then we will not need to fetch any heap
509  * pages for which the visibility map shows all tuples are visible.
510  * Hence, reduce the estimated number of heap fetches accordingly.
511  * We use the measured fraction of the entire heap that is all-visible,
512  * which might not be particularly relevant to the subset of the heap
513  * that this query will fetch; but it's not clear how to do better.
514  *----------
515  */
516  if (loop_count > 1)
517  {
518  /*
519  * For repeated indexscans, the appropriate estimate for the
520  * uncorrelated case is to scale up the number of tuples fetched in
521  * the Mackert and Lohman formula by the number of scans, so that we
522  * estimate the number of pages fetched by all the scans; then
523  * pro-rate the costs for one scan. In this case we assume all the
524  * fetches are random accesses.
525  */
526  pages_fetched = index_pages_fetched(tuples_fetched * loop_count,
527  baserel->pages,
528  (double) index->pages,
529  root);
530 
531  if (indexonly)
532  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
533 
534  rand_heap_pages = pages_fetched;
535 
536  max_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
537 
538  /*
539  * In the perfectly correlated case, the number of pages touched by
540  * each scan is selectivity * table_size, and we can use the Mackert
541  * and Lohman formula at the page level to estimate how much work is
542  * saved by caching across scans. We still assume all the fetches are
543  * random, though, which is an overestimate that's hard to correct for
544  * without double-counting the cache effects. (But in most cases
545  * where such a plan is actually interesting, only one page would get
546  * fetched per scan anyway, so it shouldn't matter much.)
547  */
548  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
549 
550  pages_fetched = index_pages_fetched(pages_fetched * loop_count,
551  baserel->pages,
552  (double) index->pages,
553  root);
554 
555  if (indexonly)
556  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
557 
558  min_IO_cost = (pages_fetched * spc_random_page_cost) / loop_count;
559  }
560  else
561  {
562  /*
563  * Normal case: apply the Mackert and Lohman formula, and then
564  * interpolate between that and the correlation-derived result.
565  */
566  pages_fetched = index_pages_fetched(tuples_fetched,
567  baserel->pages,
568  (double) index->pages,
569  root);
570 
571  if (indexonly)
572  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
573 
574  rand_heap_pages = pages_fetched;
575 
576  /* max_IO_cost is for the perfectly uncorrelated case (csquared=0) */
577  max_IO_cost = pages_fetched * spc_random_page_cost;
578 
579  /* min_IO_cost is for the perfectly correlated case (csquared=1) */
580  pages_fetched = ceil(indexSelectivity * (double) baserel->pages);
581 
582  if (indexonly)
583  pages_fetched = ceil(pages_fetched * (1.0 - baserel->allvisfrac));
584 
585  if (pages_fetched > 0)
586  {
587  min_IO_cost = spc_random_page_cost;
588  if (pages_fetched > 1)
589  min_IO_cost += (pages_fetched - 1) * spc_seq_page_cost;
590  }
591  else
592  min_IO_cost = 0;
593  }
594 
595  if (partial_path)
596  {
597  /*
598  * Estimate the number of parallel workers required to scan index. Use
599  * the number of heap pages computed considering heap fetches won't be
600  * sequential as for parallel scans the pages are accessed in random
601  * order.
602  */
604  (BlockNumber) rand_heap_pages,
605  (BlockNumber) index_pages);
606 
607  /*
608  * Fall out if workers can't be assigned for parallel scan, because in
609  * such a case this path will be rejected. So there is no benefit in
610  * doing extra computation.
611  */
612  if (path->path.parallel_workers <= 0)
613  return;
614 
615  path->path.parallel_aware = true;
616  }
617 
618  /*
619  * Now interpolate based on estimated index order correlation to get total
620  * disk I/O cost for main table accesses.
621  */
622  csquared = indexCorrelation * indexCorrelation;
623 
624  run_cost += max_IO_cost + csquared * (min_IO_cost - max_IO_cost);
625 
626  /*
627  * Estimate CPU costs per tuple.
628  *
629  * What we want here is cpu_tuple_cost plus the evaluation costs of any
630  * qual clauses that we have to evaluate as qpquals.
631  */
632  cost_qual_eval(&qpqual_cost, qpquals, root);
633 
634  startup_cost += qpqual_cost.startup;
635  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
636 
637  cpu_run_cost += cpu_per_tuple * tuples_fetched;
638 
639  /* tlist eval costs are paid per output row, not per tuple scanned */
640  startup_cost += path->path.pathtarget->cost.startup;
641  cpu_run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
642 
643  /* Adjust costing for parallelism, if used. */
644  if (path->path.parallel_workers > 0)
645  {
646  double parallel_divisor = get_parallel_divisor(&path->path);
647 
648  path->path.rows = clamp_row_est(path->path.rows / parallel_divisor);
649 
650  /* The CPU cost is divided among all the workers. */
651  cpu_run_cost /= parallel_divisor;
652  }
653 
654  run_cost += cpu_run_cost;
655 
656  path->path.startup_cost = startup_cost;
657  path->path.total_cost = startup_cost + run_cost;
658 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
Path path
Definition: relation.h:971
IndexOptInfo * indexinfo
Definition: relation.h:972
int compute_parallel_worker(RelOptInfo *rel, BlockNumber heap_pages, BlockNumber index_pages)
Definition: allpaths.c:2887
double tuples
Definition: relation.h:529
Oid reltablespace
Definition: relation.h:519
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
List * list_concat(List *list1, List *list2)
Definition: list.c:321
uint32 BlockNumber
Definition: block.h:31
static List * extract_nonindex_conditions(List *qual_clauses, List *indexquals)
Definition: costsize.c:678
double Selectivity
Definition: nodes.h:631
Cost startup
Definition: relation.h:45
double allvisfrac
Definition: relation.h:530
Definition: type.h:90
BlockNumber pages
Definition: relation.h:593
NodeTag pathtype
Definition: relation.h:892
Cost per_tuple
Definition: relation.h:46
List * indexquals
Definition: relation.h:974
RelOptInfo * rel
Definition: relation.h:590
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Cost startup_cost
Definition: relation.h:906
Cost indextotalcost
Definition: relation.h:979
Cost disable_cost
Definition: costsize.c:114
Selectivity indexselectivity
Definition: relation.h:980
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
List * indrestrictinfo
Definition: relation.h:615
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
BlockNumber pages
Definition: relation.h:528
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
List * ppi_clauses
Definition: relation.h:855
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
bool parallel_aware
Definition: relation.h:899
void(* amcostestimate)()
Definition: relation.h:634
double clamp_row_est(double nrows)
Definition: costsize.c:172
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:738
double Cost
Definition: nodes.h:632
void cost_material ( Path path,
Cost  input_startup_cost,
Cost  input_total_cost,
double  tuples,
int  width 
)

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

1640 {
1641  Cost startup_cost = input_startup_cost;
1642  Cost run_cost = input_total_cost - input_startup_cost;
1643  double nbytes = relation_byte_size(tuples, width);
1644  long work_mem_bytes = work_mem * 1024L;
1645 
1646  path->rows = tuples;
1647 
1648  /*
1649  * Whether spilling or not, charge 2x cpu_operator_cost per tuple to
1650  * reflect bookkeeping overhead. (This rate must be more than what
1651  * cost_rescan charges for materialize, ie, cpu_operator_cost per tuple;
1652  * if it is exactly the same then there will be a cost tie between
1653  * nestloop with A outer, materialized B inner and nestloop with B outer,
1654  * materialized A inner. The extra cost ensures we'll prefer
1655  * materializing the smaller rel.) Note that this is normally a good deal
1656  * less than cpu_tuple_cost; which is OK because a Material plan node
1657  * doesn't do qual-checking or projection, so it's got less overhead than
1658  * most plan nodes.
1659  */
1660  run_cost += 2 * cpu_operator_cost * tuples;
1661 
1662  /*
1663  * If we will spill to disk, charge at the rate of seq_page_cost per page.
1664  * This cost is assumed to be evenly spread through the plan run phase,
1665  * which isn't exactly accurate but our cost model doesn't allow for
1666  * nonuniform costs within the run phase.
1667  */
1668  if (nbytes > work_mem_bytes)
1669  {
1670  double npages = ceil(nbytes / BLCKSZ);
1671 
1672  run_cost += seq_page_cost * npages;
1673  }
1674 
1675  path->startup_cost = startup_cost;
1676  path->total_cost = startup_cost + run_cost;
1677 }
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4780
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:632
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 1586 of file costsize.c.

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

Referenced by create_merge_append_path().

1590 {
1591  Cost startup_cost = 0;
1592  Cost run_cost = 0;
1593  Cost comparison_cost;
1594  double N;
1595  double logN;
1596 
1597  /*
1598  * Avoid log(0)...
1599  */
1600  N = (n_streams < 2) ? 2.0 : (double) n_streams;
1601  logN = LOG2(N);
1602 
1603  /* Assumed cost per tuple comparison */
1604  comparison_cost = 2.0 * cpu_operator_cost;
1605 
1606  /* Heap creation cost */
1607  startup_cost += comparison_cost * N * logN;
1608 
1609  /* Per-tuple heap maintenance cost */
1610  run_cost += tuples * comparison_cost * logN;
1611 
1612  /*
1613  * Also charge a small amount (arbitrarily set equal to operator cost) per
1614  * extracted tuple. We don't charge cpu_tuple_cost because a MergeAppend
1615  * node doesn't do qual-checking or projection, so it has less overhead
1616  * than most plan nodes.
1617  */
1618  run_cost += cpu_operator_cost * tuples;
1619 
1620  path->startup_cost = startup_cost + input_startup_cost;
1621  path->total_cost = startup_cost + run_cost + input_total_cost;
1622 }
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
#define LOG2(x)
Definition: costsize.c:101
double Cost
Definition: nodes.h:632
void cost_qual_eval ( QualCost cost,
List quals,
PlannerInfo root 
)

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

3200 {
3201  cost_qual_eval_context context;
3202  ListCell *l;
3203 
3204  context.root = root;
3205  context.total.startup = 0;
3206  context.total.per_tuple = 0;
3207 
3208  /* We don't charge any cost for the implicit ANDing at top level ... */
3209 
3210  foreach(l, quals)
3211  {
3212  Node *qual = (Node *) lfirst(l);
3213 
3214  cost_qual_eval_walker(qual, &context);
3215  }
3216 
3217  *cost = context.total;
3218 }
PlannerInfo * root
Definition: costsize.c:132
Definition: nodes.h:508
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:3239
#define lfirst(lc)
Definition: pg_list.h:106
void cost_qual_eval_node ( QualCost cost,
Node qual,
PlannerInfo root 
)

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

3226 {
3227  cost_qual_eval_context context;
3228 
3229  context.root = root;
3230  context.total.startup = 0;
3231  context.total.per_tuple = 0;
3232 
3233  cost_qual_eval_walker(qual, &context);
3234 
3235  *cost = context.total;
3236 }
PlannerInfo * root
Definition: costsize.c:132
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:3239
void cost_recursive_union ( Path runion,
Path nrterm,
Path rterm 
)

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

1383 {
1384  Cost startup_cost;
1385  Cost total_cost;
1386  double total_rows;
1387 
1388  /* We probably have decent estimates for the non-recursive term */
1389  startup_cost = nrterm->startup_cost;
1390  total_cost = nrterm->total_cost;
1391  total_rows = nrterm->rows;
1392 
1393  /*
1394  * We arbitrarily assume that about 10 recursive iterations will be
1395  * needed, and that we've managed to get a good fix on the cost and output
1396  * size of each one of them. These are mighty shaky assumptions but it's
1397  * hard to see how to do better.
1398  */
1399  total_cost += 10 * rterm->total_cost;
1400  total_rows += 10 * rterm->rows;
1401 
1402  /*
1403  * Also charge cpu_tuple_cost per row to account for the costs of
1404  * manipulating the tuplestores. (We don't worry about possible
1405  * spill-to-disk costs.)
1406  */
1407  total_cost += cpu_tuple_cost * total_rows;
1408 
1409  runion->startup_cost = startup_cost;
1410  runion->total_cost = total_cost;
1411  runion->rows = total_rows;
1412  runion->pathtarget->width = Max(nrterm->pathtarget->width,
1413  rterm->pathtarget->width);
1414 }
PathTarget * pathtarget
Definition: relation.h:895
Cost startup_cost
Definition: relation.h:906
Cost total_cost
Definition: relation.h:907
#define Max(x, y)
Definition: c.h:796
double rows
Definition: relation.h:905
double cpu_tuple_cost
Definition: costsize.c:106
int width
Definition: relation.h:827
double Cost
Definition: nodes.h:632
void cost_samplescan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

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

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

198 {
199  Cost startup_cost = 0;
200  Cost cpu_run_cost;
201  Cost disk_run_cost;
202  double spc_seq_page_cost;
203  QualCost qpqual_cost;
204  Cost cpu_per_tuple;
205 
206  /* Should only be applied to base relations */
207  Assert(baserel->relid > 0);
208  Assert(baserel->rtekind == RTE_RELATION);
209 
210  /* Mark the path with the correct row estimate */
211  if (param_info)
212  path->rows = param_info->ppi_rows;
213  else
214  path->rows = baserel->rows;
215 
216  if (!enable_seqscan)
217  startup_cost += disable_cost;
218 
219  /* fetch estimated page cost for tablespace containing table */
221  NULL,
222  &spc_seq_page_cost);
223 
224  /*
225  * disk costs
226  */
227  disk_run_cost = spc_seq_page_cost * baserel->pages;
228 
229  /* CPU costs */
230  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
231 
232  startup_cost += qpqual_cost.startup;
233  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
234  cpu_run_cost = cpu_per_tuple * baserel->tuples;
235  /* tlist eval costs are paid per output row, not per tuple scanned */
236  startup_cost += path->pathtarget->cost.startup;
237  cpu_run_cost += path->pathtarget->cost.per_tuple * path->rows;
238 
239  /* Adjust costing for parallelism, if used. */
240  if (path->parallel_workers > 0)
241  {
242  double parallel_divisor = get_parallel_divisor(path);
243 
244  /* The CPU cost is divided among all the workers. */
245  cpu_run_cost /= parallel_divisor;
246 
247  /*
248  * It may be possible to amortize some of the I/O cost, but probably
249  * not very much, because most operating systems already do aggressive
250  * prefetching. For now, we assume that the disk run cost can't be
251  * amortized at all.
252  */
253 
254  /*
255  * In the case of a parallel plan, the row count needs to represent
256  * the number of tuples processed per worker.
257  */
258  path->rows = clamp_row_est(path->rows / parallel_divisor);
259  }
260 
261  path->startup_cost = startup_cost;
262  path->total_cost = startup_cost + cpu_run_cost + disk_run_cost;
263 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Oid reltablespace
Definition: relation.h:519
int parallel_workers
Definition: relation.h:901
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:906
Cost disable_cost
Definition: costsize.c:114
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
void get_tablespace_page_costs(Oid spcid, double *spc_random_page_cost, double *spc_seq_page_cost)
Definition: spccache.c:178
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
BlockNumber pages
Definition: relation.h:528
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double clamp_row_est(double nrows)
Definition: costsize.c:172
double Cost
Definition: nodes.h:632
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 1462 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_groupingsets_path(), create_merge_append_path(), create_sort_path(), create_unique_path(), initial_cost_mergejoin(), label_sort_with_costsize(), and plan_cluster_use_sort().

1466 {
1467  Cost startup_cost = input_cost;
1468  Cost run_cost = 0;
1469  double input_bytes = relation_byte_size(tuples, width);
1470  double output_bytes;
1471  double output_tuples;
1472  long sort_mem_bytes = sort_mem * 1024L;
1473 
1474  if (!enable_sort)
1475  startup_cost += disable_cost;
1476 
1477  path->rows = tuples;
1478 
1479  /*
1480  * We want to be sure the cost of a sort is never estimated as zero, even
1481  * if passed-in tuple count is zero. Besides, mustn't do log(0)...
1482  */
1483  if (tuples < 2.0)
1484  tuples = 2.0;
1485 
1486  /* Include the default cost-per-comparison */
1487  comparison_cost += 2.0 * cpu_operator_cost;
1488 
1489  /* Do we have a useful LIMIT? */
1490  if (limit_tuples > 0 && limit_tuples < tuples)
1491  {
1492  output_tuples = limit_tuples;
1493  output_bytes = relation_byte_size(output_tuples, width);
1494  }
1495  else
1496  {
1497  output_tuples = tuples;
1498  output_bytes = input_bytes;
1499  }
1500 
1501  if (output_bytes > sort_mem_bytes)
1502  {
1503  /*
1504  * We'll have to use a disk-based sort of all the tuples
1505  */
1506  double npages = ceil(input_bytes / BLCKSZ);
1507  double nruns = input_bytes / sort_mem_bytes;
1508  double mergeorder = tuplesort_merge_order(sort_mem_bytes);
1509  double log_runs;
1510  double npageaccesses;
1511 
1512  /*
1513  * CPU costs
1514  *
1515  * Assume about N log2 N comparisons
1516  */
1517  startup_cost += comparison_cost * tuples * LOG2(tuples);
1518 
1519  /* Disk costs */
1520 
1521  /* Compute logM(r) as log(r) / log(M) */
1522  if (nruns > mergeorder)
1523  log_runs = ceil(log(nruns) / log(mergeorder));
1524  else
1525  log_runs = 1.0;
1526  npageaccesses = 2.0 * npages * log_runs;
1527  /* Assume 3/4ths of accesses are sequential, 1/4th are not */
1528  startup_cost += npageaccesses *
1529  (seq_page_cost * 0.75 + random_page_cost * 0.25);
1530  }
1531  else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes)
1532  {
1533  /*
1534  * We'll use a bounded heap-sort keeping just K tuples in memory, for
1535  * a total number of tuple comparisons of N log2 K; but the constant
1536  * factor is a bit higher than for quicksort. Tweak it so that the
1537  * cost curve is continuous at the crossover point.
1538  */
1539  startup_cost += comparison_cost * tuples * LOG2(2.0 * output_tuples);
1540  }
1541  else
1542  {
1543  /* We'll use plain quicksort on all the input tuples */
1544  startup_cost += comparison_cost * tuples * LOG2(tuples);
1545  }
1546 
1547  /*
1548  * Also charge a small amount (arbitrarily set equal to operator cost) per
1549  * extracted tuple. We don't charge cpu_tuple_cost because a Sort node
1550  * doesn't do qual-checking or projection, so it has less overhead than
1551  * most plan nodes. Note it's correct to use tuples not output_tuples
1552  * here --- the upper LIMIT will pro-rate the run cost so we'd be double
1553  * counting the LIMIT otherwise.
1554  */
1555  run_cost += cpu_operator_cost * tuples;
1556 
1557  path->startup_cost = startup_cost;
1558  path->total_cost = startup_cost + run_cost;
1559 }
bool enable_sort
Definition: costsize.c:123
double random_page_cost
Definition: costsize.c:105
Cost startup_cost
Definition: relation.h:906
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:4780
Cost total_cost
Definition: relation.h:907
#define LOG2(x)
Definition: costsize.c:101
double rows
Definition: relation.h:905
int tuplesort_merge_order(int64 allowedMem)
Definition: tuplesort.c:2289
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:632
void cost_subplan ( PlannerInfo root,
SubPlan subplan,
Plan plan 
)

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

3000 {
3001  QualCost sp_cost;
3002 
3003  /* Figure any cost for evaluating the testexpr */
3004  cost_qual_eval(&sp_cost,
3005  make_ands_implicit((Expr *) subplan->testexpr),
3006  root);
3007 
3008  if (subplan->useHashTable)
3009  {
3010  /*
3011  * If we are using a hash table for the subquery outputs, then the
3012  * cost of evaluating the query is a one-time cost. We charge one
3013  * cpu_operator_cost per tuple for the work of loading the hashtable,
3014  * too.
3015  */
3016  sp_cost.startup += plan->total_cost +
3017  cpu_operator_cost * plan->plan_rows;
3018 
3019  /*
3020  * The per-tuple costs include the cost of evaluating the lefthand
3021  * expressions, plus the cost of probing the hashtable. We already
3022  * accounted for the lefthand expressions as part of the testexpr, and
3023  * will also have counted one cpu_operator_cost for each comparison
3024  * operator. That is probably too low for the probing cost, but it's
3025  * hard to make a better estimate, so live with it for now.
3026  */
3027  }
3028  else
3029  {
3030  /*
3031  * Otherwise we will be rescanning the subplan output on each
3032  * evaluation. We need to estimate how much of the output we will
3033  * actually need to scan. NOTE: this logic should agree with the
3034  * tuple_fraction estimates used by make_subplan() in
3035  * plan/subselect.c.
3036  */
3037  Cost plan_run_cost = plan->total_cost - plan->startup_cost;
3038 
3039  if (subplan->subLinkType == EXISTS_SUBLINK)
3040  {
3041  /* we only need to fetch 1 tuple; clamp to avoid zero divide */
3042  sp_cost.per_tuple += plan_run_cost / clamp_row_est(plan->plan_rows);
3043  }
3044  else if (subplan->subLinkType == ALL_SUBLINK ||
3045  subplan->subLinkType == ANY_SUBLINK)
3046  {
3047  /* assume we need 50% of the tuples */
3048  sp_cost.per_tuple += 0.50 * plan_run_cost;
3049  /* also charge a cpu_operator_cost per row examined */
3050  sp_cost.per_tuple += 0.50 * plan->plan_rows * cpu_operator_cost;
3051  }
3052  else
3053  {
3054  /* assume we need all tuples */
3055  sp_cost.per_tuple += plan_run_cost;
3056  }
3057 
3058  /*
3059  * Also account for subplan's startup cost. If the subplan is
3060  * uncorrelated or undirect correlated, AND its topmost node is one
3061  * that materializes its output, assume that we'll only need to pay
3062  * its startup cost once; otherwise assume we pay the startup cost
3063  * every time.
3064  */
3065  if (subplan->parParam == NIL &&
3067  sp_cost.startup += plan->startup_cost;
3068  else
3069  sp_cost.per_tuple += plan->startup_cost;
3070  }
3071 
3072  subplan->startup_cost = sp_cost.startup;
3073  subplan->per_call_cost = sp_cost.per_tuple;
3074 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:117
SubLinkType subLinkType
Definition: primnodes.h:661
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:3199
Cost startup_cost
Definition: plannodes.h:111
double cpu_operator_cost
Definition: costsize.c:108
Node * testexpr
Definition: primnodes.h:663
Cost per_call_cost
Definition: primnodes.h:689
List * parParam
Definition: primnodes.h:685
#define nodeTag(nodeptr)
Definition: nodes.h:513
Cost total_cost
Definition: plannodes.h:112
bool ExecMaterializesOutput(NodeTag plantype)
Definition: execAmi.c:561
bool useHashTable
Definition: primnodes.h:675
Cost startup_cost
Definition: primnodes.h:688
double clamp_row_est(double nrows)
Definition: costsize.c:172
double Cost
Definition: nodes.h:632
void cost_subqueryscan ( SubqueryScanPath path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1180 {
1181  Cost startup_cost;
1182  Cost run_cost;
1183  QualCost qpqual_cost;
1184  Cost cpu_per_tuple;
1185 
1186  /* Should only be applied to base relations that are subqueries */
1187  Assert(baserel->relid > 0);
1188  Assert(baserel->rtekind == RTE_SUBQUERY);
1189 
1190  /* Mark the path with the correct row estimate */
1191  if (param_info)
1192  path->path.rows = param_info->ppi_rows;
1193  else
1194  path->path.rows = baserel->rows;
1195 
1196  /*
1197  * Cost of path is cost of evaluating the subplan, plus cost of evaluating
1198  * any restriction clauses and tlist that will be attached to the
1199  * SubqueryScan node, plus cpu_tuple_cost to account for selection and
1200  * projection overhead.
1201  */
1202  path->path.startup_cost = path->subpath->startup_cost;
1203  path->path.total_cost = path->subpath->total_cost;
1204 
1205  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1206 
1207  startup_cost = qpqual_cost.startup;
1208  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple;
1209  run_cost = cpu_per_tuple * baserel->tuples;
1210 
1211  /* tlist eval costs are paid per output row, not per tuple scanned */
1212  startup_cost += path->path.pathtarget->cost.startup;
1213  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
1214 
1215  path->path.startup_cost += startup_cost;
1216  path->path.total_cost += startup_cost + run_cost;
1217 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double Cost
Definition: nodes.h:632
void cost_tidscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
List tidquals,
ParamPathInfo param_info 
)

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

1077 {
1078  Cost startup_cost = 0;
1079  Cost run_cost = 0;
1080  bool isCurrentOf = false;
1081  QualCost qpqual_cost;
1082  Cost cpu_per_tuple;
1083  QualCost tid_qual_cost;
1084  int ntuples;
1085  ListCell *l;
1086  double spc_random_page_cost;
1087 
1088  /* Should only be applied to base relations */
1089  Assert(baserel->relid > 0);
1090  Assert(baserel->rtekind == RTE_RELATION);
1091 
1092  /* Mark the path with the correct row estimate */
1093  if (param_info)
1094  path->rows = param_info->ppi_rows;
1095  else
1096  path->rows = baserel->rows;
1097 
1098  /* Count how many tuples we expect to retrieve */
1099  ntuples = 0;
1100  foreach(l, tidquals)
1101  {
1102  if (IsA(lfirst(l), ScalarArrayOpExpr))
1103  {
1104  /* Each element of the array yields 1 tuple */
1106  Node *arraynode = (Node *) lsecond(saop->args);
1107 
1108  ntuples += estimate_array_length(arraynode);
1109  }
1110  else if (IsA(lfirst(l), CurrentOfExpr))
1111  {
1112  /* CURRENT OF yields 1 tuple */
1113  isCurrentOf = true;
1114  ntuples++;
1115  }
1116  else
1117  {
1118  /* It's just CTID = something, count 1 tuple */
1119  ntuples++;
1120  }
1121  }
1122 
1123  /*
1124  * We must force TID scan for WHERE CURRENT OF, because only nodeTidscan.c
1125  * understands how to do it correctly. Therefore, honor enable_tidscan
1126  * only when CURRENT OF isn't present. Also note that cost_qual_eval
1127  * counts a CurrentOfExpr as having startup cost disable_cost, which we
1128  * subtract off here; that's to prevent other plan types such as seqscan
1129  * from winning.
1130  */
1131  if (isCurrentOf)
1132  {
1134  startup_cost -= disable_cost;
1135  }
1136  else if (!enable_tidscan)
1137  startup_cost += disable_cost;
1138 
1139  /*
1140  * The TID qual expressions will be computed once, any other baserestrict
1141  * quals once per retrieved tuple.
1142  */
1143  cost_qual_eval(&tid_qual_cost, tidquals, root);
1144 
1145  /* fetch estimated page cost for tablespace containing table */
1147  &spc_random_page_cost,
1148  NULL);
1149 
1150  /* disk costs --- assume each tuple on a different page */
1151  run_cost += spc_random_page_cost * ntuples;
1152 
1153  /* Add scanning CPU costs */
1154  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1155 
1156  /* XXX currently we assume TID quals are a subset of qpquals */
1157  startup_cost += qpqual_cost.startup + tid_qual_cost.per_tuple;
1158  cpu_per_tuple = cpu_tuple_cost + qpqual_cost.per_tuple -
1159  tid_qual_cost.per_tuple;
1160  run_cost += cpu_per_tuple * ntuples;
1161 
1162  /* tlist eval costs are paid per output row, not per tuple scanned */
1163  startup_cost += path->pathtarget->cost.startup;
1164  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1165 
1166  path->startup_cost = startup_cost;
1167  path->total_cost = startup_cost + run_cost;
1168 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
bool enable_tidscan
Definition: costsize.c:122
Oid reltablespace
Definition: relation.h:519
Definition: nodes.h:508
#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:2078
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Cost startup_cost
Definition: relation.h:906
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:178
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
QualCost baserestrictcost
Definition: relation.h:546
double Cost
Definition: nodes.h:632
void cost_valuesscan ( Path path,
PlannerInfo root,
RelOptInfo baserel,
ParamPathInfo param_info 
)

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

1290 {
1291  Cost startup_cost = 0;
1292  Cost run_cost = 0;
1293  QualCost qpqual_cost;
1294  Cost cpu_per_tuple;
1295 
1296  /* Should only be applied to base relations that are values lists */
1297  Assert(baserel->relid > 0);
1298  Assert(baserel->rtekind == RTE_VALUES);
1299 
1300  /* Mark the path with the correct row estimate */
1301  if (param_info)
1302  path->rows = param_info->ppi_rows;
1303  else
1304  path->rows = baserel->rows;
1305 
1306  /*
1307  * For now, estimate list evaluation cost at one operator eval per list
1308  * (probably pretty bogus, but is it worth being smarter?)
1309  */
1310  cpu_per_tuple = cpu_operator_cost;
1311 
1312  /* Add scanning CPU costs */
1313  get_restriction_qual_cost(root, baserel, param_info, &qpqual_cost);
1314 
1315  startup_cost += qpqual_cost.startup;
1316  cpu_per_tuple += cpu_tuple_cost + qpqual_cost.per_tuple;
1317  run_cost += cpu_per_tuple * baserel->tuples;
1318 
1319  /* tlist eval costs are paid per output row, not per tuple scanned */
1320  startup_cost += path->pathtarget->cost.startup;
1321  run_cost += path->pathtarget->cost.per_tuple * path->rows;
1322 
1323  path->startup_cost = startup_cost;
1324  path->total_cost = startup_cost + run_cost;
1325 }
PathTarget * pathtarget
Definition: relation.h:895
double tuples
Definition: relation.h:529
Cost startup
Definition: relation.h:45
Cost per_tuple
Definition: relation.h:46
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Index relid
Definition: relation.h:518
RTEKind rtekind
Definition: relation.h:520
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
static void get_restriction_qual_cost(PlannerInfo *root, RelOptInfo *baserel, ParamPathInfo *param_info, QualCost *qpqual_cost)
Definition: costsize.c:3466
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
double Cost
Definition: nodes.h:632
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 1783 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().

1787 {
1788  Cost startup_cost;
1789  Cost total_cost;
1790  ListCell *lc;
1791 
1792  startup_cost = input_startup_cost;
1793  total_cost = input_total_cost;
1794 
1795  /*
1796  * Window functions are assumed to cost their stated execution cost, plus
1797  * the cost of evaluating their input expressions, per tuple. Since they
1798  * may in fact evaluate their inputs at multiple rows during each cycle,
1799  * this could be a drastic underestimate; but without a way to know how
1800  * many rows the window function will fetch, it's hard to do better. In
1801  * any case, it's a good estimate for all the built-in window functions,
1802  * so we'll just do this for now.
1803  */
1804  foreach(lc, windowFuncs)
1805  {
1806  WindowFunc *wfunc = castNode(WindowFunc, lfirst(lc));
1807  Cost wfunccost;
1808  QualCost argcosts;
1809 
1810  wfunccost = get_func_cost(wfunc->winfnoid) * cpu_operator_cost;
1811 
1812  /* also add the input expressions' cost to per-input-row costs */
1813  cost_qual_eval_node(&argcosts, (Node *) wfunc->args, root);
1814  startup_cost += argcosts.startup;
1815  wfunccost += argcosts.per_tuple;
1816 
1817  /*
1818  * Add the filter's cost to per-input-row costs. XXX We should reduce
1819  * input expression costs according to filter selectivity.
1820  */
1821  cost_qual_eval_node(&argcosts, (Node *) wfunc->aggfilter, root);
1822  startup_cost += argcosts.startup;
1823  wfunccost += argcosts.per_tuple;
1824 
1825  total_cost += wfunccost * input_tuples;
1826  }
1827 
1828  /*
1829  * We also charge cpu_operator_cost per grouping column per tuple for
1830  * grouping comparisons, plus cpu_tuple_cost per tuple for general
1831  * overhead.
1832  *
1833  * XXX this neglects costs of spooling the data to disk when it overflows
1834  * work_mem. Sooner or later that should get accounted for.
1835  */
1836  total_cost += cpu_operator_cost * (numPartCols + numOrderCols) * input_tuples;
1837  total_cost += cpu_tuple_cost * input_tuples;
1838 
1839  path->rows = input_tuples;
1840  path->startup_cost = startup_cost;
1841  path->total_cost = total_cost;
1842 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3225
List * args
Definition: primnodes.h:337
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Definition: nodes.h:508
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:906
double cpu_operator_cost
Definition: costsize.c:108
Oid winfnoid
Definition: primnodes.h:333
Cost total_cost
Definition: relation.h:907
#define lfirst(lc)
Definition: pg_list.h:106
Expr * aggfilter
Definition: primnodes.h:338
double rows
Definition: relation.h:905
double cpu_tuple_cost
Definition: costsize.c:106
double Cost
Definition: nodes.h:632
void final_cost_hashjoin ( PlannerInfo root,
HashPath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

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

2784 {
2785  Path *outer_path = path->jpath.outerjoinpath;
2786  Path *inner_path = path->jpath.innerjoinpath;
2787  double outer_path_rows = outer_path->rows;
2788  double inner_path_rows = inner_path->rows;
2789  List *hashclauses = path->path_hashclauses;
2790  Cost startup_cost = workspace->startup_cost;
2791  Cost run_cost = workspace->run_cost;
2792  int numbuckets = workspace->numbuckets;
2793  int numbatches = workspace->numbatches;
2794  Cost cpu_per_tuple;
2795  QualCost hash_qual_cost;
2796  QualCost qp_qual_cost;
2797  double hashjointuples;
2798  double virtualbuckets;
2799  Selectivity innerbucketsize;
2800  ListCell *hcl;
2801 
2802  /* Mark the path with the correct row estimate */
2803  if (path->jpath.path.param_info)
2804  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2805  else
2806  path->jpath.path.rows = path->jpath.path.parent->rows;
2807 
2808  /* For partial paths, scale row estimate. */
2809  if (path->jpath.path.parallel_workers > 0)
2810  path->jpath.path.rows /= get_parallel_divisor(&path->jpath.path);
2811 
2812  /*
2813  * We could include disable_cost in the preliminary estimate, but that
2814  * would amount to optimizing for the case where the join method is
2815  * disabled, which doesn't seem like the way to bet.
2816  */
2817  if (!enable_hashjoin)
2818  startup_cost += disable_cost;
2819 
2820  /* mark the path with estimated # of batches */
2821  path->num_batches = numbatches;
2822 
2823  /* and compute the number of "virtual" buckets in the whole join */
2824  virtualbuckets = (double) numbuckets *(double) numbatches;
2825 
2826  /*
2827  * Determine bucketsize fraction for inner relation. We use the smallest
2828  * bucketsize estimated for any individual hashclause; this is undoubtedly
2829  * conservative.
2830  *
2831  * BUT: if inner relation has been unique-ified, we can assume it's good
2832  * for hashing. This is important both because it's the right answer, and
2833  * because we avoid contaminating the cache with a value that's wrong for
2834  * non-unique-ified paths.
2835  */
2836  if (IsA(inner_path, UniquePath))
2837  innerbucketsize = 1.0 / virtualbuckets;
2838  else
2839  {
2840  innerbucketsize = 1.0;
2841  foreach(hcl, hashclauses)
2842  {
2843  RestrictInfo *restrictinfo = castNode(RestrictInfo, lfirst(hcl));
2844  Selectivity thisbucketsize;
2845 
2846  /*
2847  * First we have to figure out which side of the hashjoin clause
2848  * is the inner side.
2849  *
2850  * Since we tend to visit the same clauses over and over when
2851  * planning a large query, we cache the bucketsize estimate in the
2852  * RestrictInfo node to avoid repeated lookups of statistics.
2853  */
2854  if (bms_is_subset(restrictinfo->right_relids,
2855  inner_path->parent->relids))
2856  {
2857  /* righthand side is inner */
2858  thisbucketsize = restrictinfo->right_bucketsize;
2859  if (thisbucketsize < 0)
2860  {
2861  /* not cached yet */
2862  thisbucketsize =
2864  get_rightop(restrictinfo->clause),
2865  virtualbuckets);
2866  restrictinfo->right_bucketsize = thisbucketsize;
2867  }
2868  }
2869  else
2870  {
2871  Assert(bms_is_subset(restrictinfo->left_relids,
2872  inner_path->parent->relids));
2873  /* lefthand side is inner */
2874  thisbucketsize = restrictinfo->left_bucketsize;
2875  if (thisbucketsize < 0)
2876  {
2877  /* not cached yet */
2878  thisbucketsize =
2880  get_leftop(restrictinfo->clause),
2881  virtualbuckets);
2882  restrictinfo->left_bucketsize = thisbucketsize;
2883  }
2884  }
2885 
2886  if (innerbucketsize > thisbucketsize)
2887  innerbucketsize = thisbucketsize;
2888  }
2889  }
2890 
2891  /*
2892  * Compute cost of the hashquals and qpquals (other restriction clauses)
2893  * separately.
2894  */
2895  cost_qual_eval(&hash_qual_cost, hashclauses, root);
2896  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2897  qp_qual_cost.startup -= hash_qual_cost.startup;
2898  qp_qual_cost.per_tuple -= hash_qual_cost.per_tuple;
2899 
2900  /* CPU costs */
2901 
2902  if (path->jpath.jointype == JOIN_SEMI || path->jpath.jointype == JOIN_ANTI)
2903  {
2904  double outer_matched_rows;
2905  Selectivity inner_scan_frac;
2906 
2907  /*
2908  * SEMI or ANTI join: executor will stop after first match.
2909  *
2910  * For an outer-rel row that has at least one match, we can expect the
2911  * bucket scan to stop after a fraction 1/(match_count+1) of the
2912  * bucket's rows, if the matches are evenly distributed. Since they
2913  * probably aren't quite evenly distributed, we apply a fuzz factor of
2914  * 2.0 to that fraction. (If we used a larger fuzz factor, we'd have
2915  * to clamp inner_scan_frac to at most 1.0; but since match_count is
2916  * at least 1, no such clamp is needed now.)
2917  */
2918  outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2919  inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2920 
2921  startup_cost += hash_qual_cost.startup;
2922  run_cost += hash_qual_cost.per_tuple * outer_matched_rows *
2923  clamp_row_est(inner_path_rows * innerbucketsize * inner_scan_frac) * 0.5;
2924 
2925  /*
2926  * For unmatched outer-rel rows, the picture is quite a lot different.
2927  * In the first place, there is no reason to assume that these rows
2928  * preferentially hit heavily-populated buckets; instead assume they
2929  * are uncorrelated with the inner distribution and so they see an
2930  * average bucket size of inner_path_rows / virtualbuckets. In the
2931  * second place, it seems likely that they will have few if any exact
2932  * hash-code matches and so very few of the tuples in the bucket will
2933  * actually require eval of the hash quals. We don't have any good
2934  * way to estimate how many will, but for the moment assume that the
2935  * effective cost per bucket entry is one-tenth what it is for
2936  * matchable tuples.
2937  */
2938  run_cost += hash_qual_cost.per_tuple *
2939  (outer_path_rows - outer_matched_rows) *
2940  clamp_row_est(inner_path_rows / virtualbuckets) * 0.05;
2941 
2942  /* Get # of tuples that will pass the basic join */
2943  if (path->jpath.jointype == JOIN_SEMI)
2944  hashjointuples = outer_matched_rows;
2945  else
2946  hashjointuples = outer_path_rows - outer_matched_rows;
2947  }
2948  else
2949  {
2950  /*
2951  * The number of tuple comparisons needed is the number of outer
2952  * tuples times the typical number of tuples in a hash bucket, which
2953  * is the inner relation size times its bucketsize fraction. At each
2954  * one, we need to evaluate the hashjoin quals. But actually,
2955  * charging the full qual eval cost at each tuple is pessimistic,
2956  * since we don't evaluate the quals unless the hash values match
2957  * exactly. For lack of a better idea, halve the cost estimate to
2958  * allow for that.
2959  */
2960  startup_cost += hash_qual_cost.startup;
2961  run_cost += hash_qual_cost.per_tuple * outer_path_rows *
2962  clamp_row_est(inner_path_rows * innerbucketsize) * 0.5;
2963 
2964  /*
2965  * Get approx # tuples passing the hashquals. We use
2966  * approx_tuple_count here because we need an estimate done with
2967  * JOIN_INNER semantics.
2968  */
2969  hashjointuples = approx_tuple_count(root, &path->jpath, hashclauses);
2970  }
2971 
2972  /*
2973  * For each tuple that gets through the hashjoin proper, we charge
2974  * cpu_tuple_cost plus the cost of evaluating additional restriction
2975  * clauses that are to be applied at the join. (This is pessimistic since
2976  * not all of the quals may get evaluated at each tuple.)
2977  */
2978  startup_cost += qp_qual_cost.startup;
2979  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2980  run_cost += cpu_per_tuple * hashjointuples;
2981 
2982  /* tlist eval costs are paid per output row, not per tuple scanned */
2983  startup_cost += path->jpath.path.pathtarget->cost.startup;
2984  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
2985 
2986  path->jpath.path.startup_cost = startup_cost;
2987  path->jpath.path.total_cost = startup_cost + run_cost;
2988 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
JoinPath jpath
Definition: relation.h:1282
PathTarget * pathtarget
Definition: relation.h:895
int num_batches
Definition: relation.h:1284
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
Selectivity outer_match_frac
Definition: relation.h:2032
Path * innerjoinpath
Definition: relation.h:1217
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:3709
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
Relids left_relids
Definition: relation.h:1664
double Selectivity
Definition: nodes.h:631
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:3199
Node * get_leftop(const Expr *clause)
Definition: clauses.c:198
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1219
RelOptInfo * parent
Definition: relation.h:894
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:307
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
Relids relids
Definition: relation.h:490
double rint(double x)
Definition: rint.c:22
Expr * clause
Definition: relation.h:1637
Path * outerjoinpath
Definition: relation.h:1216
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
Selectivity left_bucketsize
Definition: relation.h:1698
Relids right_relids
Definition: relation.h:1665
Path path
Definition: relation.h:1212
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
Node * get_rightop(const Expr *clause)
Definition: clauses.c:215
double ppi_rows
Definition: relation.h:854
bool enable_hashjoin
Definition: costsize.c:128
Selectivity estimate_hash_bucketsize(PlannerInfo *root, Node *hashkey, double nbuckets)
Definition: selfuncs.c:3554
Selectivity match_count
Definition: relation.h:2033
Selectivity right_bucketsize
Definition: relation.h:1699
JoinType jointype
Definition: relation.h:1214
List * path_hashclauses
Definition: relation.h:1283
double clamp_row_est(double nrows)
Definition: costsize.c:172
Definition: pg_list.h:45
Definition: relation.h:888
double Cost
Definition: nodes.h:632
void final_cost_mergejoin ( PlannerInfo root,
MergePath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo 
)

Definition at line 2390 of file costsize.c.

References approx_tuple_count(), 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().

2393 {
2394  Path *outer_path = path->jpath.outerjoinpath;
2395  Path *inner_path = path->jpath.innerjoinpath;
2396  double inner_path_rows = inner_path->rows;
2397  List *mergeclauses = path->path_mergeclauses;
2398  List *innersortkeys = path->innersortkeys;
2399  Cost startup_cost = workspace->startup_cost;
2400  Cost run_cost = workspace->run_cost;
2401  Cost inner_run_cost = workspace->inner_run_cost;
2402  double outer_rows = workspace->outer_rows;
2403  double inner_rows = workspace->inner_rows;
2404  double outer_skip_rows = workspace->outer_skip_rows;
2405  double inner_skip_rows = workspace->inner_skip_rows;
2406  Cost cpu_per_tuple,
2407  bare_inner_cost,
2408  mat_inner_cost;
2409  QualCost merge_qual_cost;
2410  QualCost qp_qual_cost;
2411  double mergejointuples,
2412  rescannedtuples;
2413  double rescanratio;
2414 
2415  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2416  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2417  inner_path_rows = 1;
2418 
2419  /* Mark the path with the correct row estimate */
2420  if (path->jpath.path.param_info)
2421  path->jpath.path.rows = path->jpath.path.param_info->ppi_rows;
2422  else
2423  path->jpath.path.rows = path->jpath.path.parent->rows;
2424 
2425  /* For partial paths, scale row estimate. */
2426  if (path->jpath.path.parallel_workers > 0)
2427  path->jpath.path.rows /= get_parallel_divisor(&path->jpath.path);
2428 
2429  /*
2430  * We could include disable_cost in the preliminary estimate, but that
2431  * would amount to optimizing for the case where the join method is
2432  * disabled, which doesn't seem like the way to bet.
2433  */
2434  if (!enable_mergejoin)
2435  startup_cost += disable_cost;
2436 
2437  /*
2438  * Compute cost of the mergequals and qpquals (other restriction clauses)
2439  * separately.
2440  */
2441  cost_qual_eval(&merge_qual_cost, mergeclauses, root);
2442  cost_qual_eval(&qp_qual_cost, path->jpath.joinrestrictinfo, root);
2443  qp_qual_cost.startup -= merge_qual_cost.startup;
2444  qp_qual_cost.per_tuple -= merge_qual_cost.per_tuple;
2445 
2446  /*
2447  * Get approx # tuples passing the mergequals. We use approx_tuple_count
2448  * here because we need an estimate done with JOIN_INNER semantics.
2449  */
2450  mergejointuples = approx_tuple_count(root, &path->jpath, mergeclauses);
2451 
2452  /*
2453  * When there are equal merge keys in the outer relation, the mergejoin
2454  * must rescan any matching tuples in the inner relation. This means
2455  * re-fetching inner tuples; we have to estimate how often that happens.
2456  *
2457  * For regular inner and outer joins, the number of re-fetches can be
2458  * estimated approximately as size of merge join output minus size of
2459  * inner relation. Assume that the distinct key values are 1, 2, ..., and
2460  * denote the number of values of each key in the outer relation as m1,
2461  * m2, ...; in the inner relation, n1, n2, ... Then we have
2462  *
2463  * size of join = m1 * n1 + m2 * n2 + ...
2464  *
2465  * number of rescanned tuples = (m1 - 1) * n1 + (m2 - 1) * n2 + ... = m1 *
2466  * n1 + m2 * n2 + ... - (n1 + n2 + ...) = size of join - size of inner
2467  * relation
2468  *
2469  * This equation works correctly for outer tuples having no inner match
2470  * (nk = 0), but not for inner tuples having no outer match (mk = 0); we
2471  * are effectively subtracting those from the number of rescanned tuples,
2472  * when we should not. Can we do better without expensive selectivity
2473  * computations?
2474  *
2475  * The whole issue is moot if we are working from a unique-ified outer
2476  * input.
2477  */
2478  if (IsA(outer_path, UniquePath))
2479  rescannedtuples = 0;
2480  else
2481  {
2482  rescannedtuples = mergejointuples - inner_path_rows;
2483  /* Must clamp because of possible underestimate */
2484  if (rescannedtuples < 0)
2485  rescannedtuples = 0;
2486  }
2487  /* We'll inflate various costs this much to account for rescanning */
2488  rescanratio = 1.0 + (rescannedtuples / inner_path_rows);
2489 
2490  /*
2491  * Decide whether we want to materialize the inner input to shield it from
2492  * mark/restore and performing re-fetches. Our cost model for regular
2493  * re-fetches is that a re-fetch costs the same as an original fetch,
2494  * which is probably an overestimate; but on the other hand we ignore the
2495  * bookkeeping costs of mark/restore. Not clear if it's worth developing
2496  * a more refined model. So we just need to inflate the inner run cost by
2497  * rescanratio.
2498  */
2499  bare_inner_cost = inner_run_cost * rescanratio;
2500 
2501  /*
2502  * When we interpose a Material node the re-fetch cost is assumed to be
2503  * just cpu_operator_cost per tuple, independently of the underlying
2504  * plan's cost; and we charge an extra cpu_operator_cost per original
2505  * fetch as well. Note that we're assuming the materialize node will
2506  * never spill to disk, since it only has to remember tuples back to the
2507  * last mark. (If there are a huge number of duplicates, our other cost
2508  * factors will make the path so expensive that it probably won't get
2509  * chosen anyway.) So we don't use cost_rescan here.
2510  *
2511  * Note: keep this estimate in sync with create_mergejoin_plan's labeling
2512  * of the generated Material node.
2513  */
2514  mat_inner_cost = inner_run_cost +
2515  cpu_operator_cost * inner_path_rows * rescanratio;
2516 
2517  /*
2518  * Prefer materializing if it looks cheaper, unless the user has asked to
2519  * suppress materialization.
2520  */
2521  if (enable_material && mat_inner_cost < bare_inner_cost)
2522  path->materialize_inner = true;
2523 
2524  /*
2525  * Even if materializing doesn't look cheaper, we *must* do it if the
2526  * inner path is to be used directly (without sorting) and it doesn't
2527  * support mark/restore.
2528  *
2529  * Since the inner side must be ordered, and only Sorts and IndexScans can
2530  * create order to begin with, and they both support mark/restore, you
2531  * might think there's no problem --- but you'd be wrong. Nestloop and
2532  * merge joins can *preserve* the order of their inputs, so they can be
2533  * selected as the input of a mergejoin, and they don't support
2534  * mark/restore at present.
2535  *
2536  * We don't test the value of enable_material here, because
2537  * materialization is required for correctness in this case, and turning
2538  * it off does not entitle us to deliver an invalid plan.
2539  */
2540  else if (innersortkeys == NIL &&
2541  !ExecSupportsMarkRestore(inner_path))
2542  path->materialize_inner = true;
2543 
2544  /*
2545  * Also, force materializing if the inner path is to be sorted and the
2546  * sort is expected to spill to disk. This is because the final merge
2547  * pass can be done on-the-fly if it doesn't have to support mark/restore.
2548  * We don't try to adjust the cost estimates for this consideration,
2549  * though.
2550  *
2551  * Since materialization is a performance optimization in this case,
2552  * rather than necessary for correctness, we skip it if enable_material is
2553  * off.
2554  */
2555  else if (enable_material && innersortkeys != NIL &&
2556  relation_byte_size(inner_path_rows,
2557  inner_path->pathtarget->width) >
2558  (work_mem * 1024L))
2559  path->materialize_inner = true;
2560  else
2561  path->materialize_inner = false;
2562 
2563  /* Charge the right incremental cost for the chosen case */
2564  if (path->materialize_inner)
2565  run_cost += mat_inner_cost;
2566  else
2567  run_cost += bare_inner_cost;
2568 
2569  /* CPU costs */
2570 
2571  /*
2572  * The number of tuple comparisons needed is approximately number of outer
2573  * rows plus number of inner rows plus number of rescanned tuples (can we
2574  * refine this?). At each one, we need to evaluate the mergejoin quals.
2575  */
2576  startup_cost += merge_qual_cost.startup;
2577  startup_cost += merge_qual_cost.per_tuple *
2578  (outer_skip_rows + inner_skip_rows * rescanratio);
2579  run_cost += merge_qual_cost.per_tuple *
2580  ((outer_rows - outer_skip_rows) +
2581  (inner_rows - inner_skip_rows) * rescanratio);
2582 
2583  /*
2584  * For each tuple that gets through the mergejoin proper, we charge
2585  * cpu_tuple_cost plus the cost of evaluating additional restriction
2586  * clauses that are to be applied at the join. (This is pessimistic since
2587  * not all of the quals may get evaluated at each tuple.)
2588  *
2589  * Note: we could adjust for SEMI/ANTI joins skipping some qual
2590  * evaluations here, but it's probably not worth the trouble.
2591  */
2592  startup_cost += qp_qual_cost.startup;
2593  cpu_per_tuple = cpu_tuple_cost + qp_qual_cost.per_tuple;
2594  run_cost += cpu_per_tuple * mergejointuples;
2595 
2596  /* tlist eval costs are paid per output row, not per tuple scanned */
2597  startup_cost += path->jpath.path.pathtarget->cost.startup;
2598  run_cost += path->jpath.path.pathtarget->cost.per_tuple * path->jpath.path.rows;
2599 
2600  path->jpath.path.startup_cost = startup_cost;
2601  path->jpath.path.total_cost = startup_cost + run_cost;
2602 }
#define NIL
Definition: pg_list.h:69
List * path_mergeclauses
Definition: relation.h:1265
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
PathTarget * pathtarget
Definition: relation.h:895
bool ExecSupportsMarkRestore(Path *pathnode)
Definition: execAmi.c:390
bool materialize_inner
Definition: relation.h:1268
Path * innerjoinpath
Definition: relation.h:1217
static double approx_tuple_count(PlannerInfo *root, JoinPath *path, List *quals)
Definition: costsize.c:3709
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
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:3199
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1219
RelOptInfo * parent
Definition: relation.h:894
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
double cpu_operator_cost
Definition: costsize.c:108
static double relation_byte_size(double tuples, int width)
Definition: costsize.c:4780
Path * outerjoinpath
Definition: relation.h:1216
int work_mem
Definition: globals.c:112
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
double outer_skip_rows
Definition: relation.h:2084
bool enable_mergejoin
Definition: costsize.c:127
Path path
Definition: relation.h:1212
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
List * innersortkeys
Definition: relation.h:1267
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
int width
Definition: relation.h:827
JoinPath jpath
Definition: relation.h:1264
double inner_skip_rows
Definition: relation.h:2085
Definition: pg_list.h:45
Definition: relation.h:888
double Cost
Definition: nodes.h:632
bool enable_material
Definition: costsize.c:126
void final_cost_nestloop ( PlannerInfo root,
NestPath path,
JoinCostWorkspace workspace,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

Definition at line 1976 of file costsize.c.

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

1980 {
1981  Path *outer_path = path->outerjoinpath;
1982  Path *inner_path = path->innerjoinpath;
1983  double outer_path_rows = outer_path->rows;
1984  double inner_path_rows = inner_path->rows;
1985  Cost startup_cost = workspace->startup_cost;
1986  Cost run_cost = workspace->run_cost;
1987  Cost cpu_per_tuple;
1988  QualCost restrict_qual_cost;
1989  double ntuples;
1990 
1991  /* Protect some assumptions below that rowcounts aren't zero or NaN */
1992  if (outer_path_rows <= 0 || isnan(outer_path_rows))
1993  outer_path_rows = 1;
1994  if (inner_path_rows <= 0 || isnan(inner_path_rows))
1995  inner_path_rows = 1;
1996 
1997  /* Mark the path with the correct row estimate */
1998  if (path->path.param_info)
1999  path->path.rows = path->path.param_info->ppi_rows;
2000  else
2001  path->path.rows = path->path.parent->rows;
2002 
2003  /* For partial paths, scale row estimate. */
2004  if (path->path.parallel_workers > 0)
2005  path->path.rows /= get_parallel_divisor(&path->path);
2006 
2007  /*
2008  * We could include disable_cost in the preliminary estimate, but that
2009  * would amount to optimizing for the case where the join method is
2010  * disabled, which doesn't seem like the way to bet.
2011  */
2012  if (!enable_nestloop)
2013  startup_cost += disable_cost;
2014 
2015  /* cost of inner-relation source data (we already dealt with outer rel) */
2016 
2017  if (path->jointype == JOIN_SEMI || path->jointype == JOIN_ANTI)
2018  {
2019  /*
2020  * SEMI or ANTI join: executor will stop after first match.
2021  */
2022  Cost inner_run_cost = workspace->inner_run_cost;
2023  Cost inner_rescan_run_cost = workspace->inner_rescan_run_cost;
2024  double outer_matched_rows;
2025  Selectivity inner_scan_frac;
2026 
2027  /*
2028  * For an outer-rel row that has at least one match, we can expect the
2029  * inner scan to stop after a fraction 1/(match_count+1) of the inner
2030  * rows, if the matches are evenly distributed. Since they probably
2031  * aren't quite evenly distributed, we apply a fuzz factor of 2.0 to
2032  * that fraction. (If we used a larger fuzz factor, we'd have to
2033  * clamp inner_scan_frac to at most 1.0; but since match_count is at
2034  * least 1, no such clamp is needed now.)
2035  */
2036  outer_matched_rows = rint(outer_path_rows * semifactors->outer_match_frac);
2037  inner_scan_frac = 2.0 / (semifactors->match_count + 1.0);
2038 
2039  /*
2040  * Compute number of tuples processed (not number emitted!). First,
2041  * account for successfully-matched outer rows.
2042  */
2043  ntuples = outer_matched_rows * inner_path_rows * inner_scan_frac;
2044 
2045  /*
2046  * Now we need to estimate the actual costs of scanning the inner
2047  * relation, which may be quite a bit less than N times inner_run_cost
2048  * due to early scan stops. We consider two cases. If the inner path
2049  * is an indexscan using all the joinquals as indexquals, then an
2050  * unmatched outer row results in an indexscan returning no rows,
2051  * which is probably quite cheap. Otherwise, the executor will have
2052  * to scan the whole inner rel for an unmatched row; not so cheap.
2053  */
2054  if (has_indexed_join_quals(path))
2055  {
2056  /*
2057  * Successfully-matched outer rows will only require scanning
2058  * inner_scan_frac of the inner relation. In this case, we don't
2059  * need to charge the full inner_run_cost even when that's more
2060  * than inner_rescan_run_cost, because we can assume that none of
2061  * the inner scans ever scan the whole inner relation. So it's
2062  * okay to assume that all the inner scan executions can be
2063  * fractions of the full cost, even if materialization is reducing
2064  * the rescan cost. At this writing, it's impossible to get here
2065  * for a materialized inner scan, so inner_run_cost and
2066  * inner_rescan_run_cost will be the same anyway; but just in
2067  * case, use inner_run_cost for the first matched tuple and
2068  * inner_rescan_run_cost for additional ones.
2069  */
2070  run_cost += inner_run_cost * inner_scan_frac;
2071  if (outer_matched_rows > 1)
2072  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2073 
2074  /*
2075  * Add the cost of inner-scan executions for unmatched outer rows.
2076  * We estimate this as the same cost as returning the first tuple
2077  * of a nonempty scan. We consider that these are all rescans,
2078  * since we used inner_run_cost once already.
2079  */
2080  run_cost += (outer_path_rows - outer_matched_rows) *
2081  inner_rescan_run_cost / inner_path_rows;
2082 
2083  /*
2084  * We won't be evaluating any quals at all for unmatched rows, so
2085  * don't add them to ntuples.
2086  */
2087  }
2088  else
2089  {
2090  /*
2091  * Here, a complicating factor is that rescans may be cheaper than
2092  * first scans. If we never scan all the way to the end of the
2093  * inner rel, it might be (depending on the plan type) that we'd
2094  * never pay the whole inner first-scan run cost. However it is
2095  * difficult to estimate whether that will happen (and it could
2096  * not happen if there are any unmatched outer rows!), so be
2097  * conservative and always charge the whole first-scan cost once.
2098  */
2099  run_cost += inner_run_cost;
2100 
2101  /* Add inner run cost for additional outer tuples having matches */
2102  if (outer_matched_rows > 1)
2103  run_cost += (outer_matched_rows - 1) * inner_rescan_run_cost * inner_scan_frac;
2104 
2105  /* Add inner run cost for unmatched outer tuples */
2106  run_cost += (outer_path_rows - outer_matched_rows) *
2107  inner_rescan_run_cost;
2108 
2109  /* And count the unmatched join tuples as being processed */
2110  ntuples += (outer_path_rows - outer_matched_rows) *
2111  inner_path_rows;
2112  }
2113  }
2114  else
2115  {
2116  /* Normal-case source costs were included in preliminary estimate */
2117 
2118  /* Compute number of tuples processed (not number emitted!) */
2119  ntuples = outer_path_rows * inner_path_rows;
2120  }
2121 
2122  /* CPU costs */
2123  cost_qual_eval(&restrict_qual_cost, path->joinrestrictinfo, root);
2124  startup_cost += restrict_qual_cost.startup;
2125  cpu_per_tuple = cpu_tuple_cost + restrict_qual_cost.per_tuple;
2126  run_cost += cpu_per_tuple * ntuples;
2127 
2128  /* tlist eval costs are paid per output row, not per tuple scanned */
2129  startup_cost += path->path.pathtarget->cost.startup;
2130  run_cost += path->path.pathtarget->cost.per_tuple * path->path.rows;
2131 
2132  path->path.startup_cost = startup_cost;
2133  path->path.total_cost = startup_cost + run_cost;
2134 }
PathTarget * pathtarget
Definition: relation.h:895
bool enable_nestloop
Definition: costsize.c:125
Selectivity outer_match_frac
Definition: relation.h:2032
Path * innerjoinpath
Definition: relation.h:1217
int parallel_workers
Definition: relation.h:901
ParamPathInfo * param_info
Definition: relation.h:897
double Selectivity
Definition: nodes.h:631
Cost inner_rescan_run_cost
Definition: relation.h:2079
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:3199
Cost startup_cost
Definition: relation.h:906
Cost disable_cost
Definition: costsize.c:114
List * joinrestrictinfo
Definition: relation.h:1219
RelOptInfo * parent
Definition: relation.h:894
static double get_parallel_divisor(Path *path)
Definition: costsize.c:4801
double rint(double x)
Definition: rint.c:22
Path * outerjoinpath
Definition: relation.h:1216
double rows
Definition: relation.h:493
Cost total_cost
Definition: relation.h:907
Path path
Definition: relation.h:1212
static bool has_indexed_join_quals(NestPath *joinpath)
Definition: costsize.c:3616
double rows
Definition: relation.h:905
QualCost cost
Definition: relation.h:826
double cpu_tuple_cost
Definition: costsize.c:106
double ppi_rows
Definition: relation.h:854
Selectivity match_count
Definition: relation.h:2033
JoinType jointype
Definition: relation.h:1214
Definition: relation.h:888
double Cost
Definition: nodes.h:632
double get_parameterized_baserel_size ( PlannerInfo root,
RelOptInfo rel,
List param_clauses 
)

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

3797 {
3798  List *allclauses;
3799  double nrows;
3800 
3801  /*
3802  * Estimate the number of rows returned by the parameterized scan, knowing
3803  * that it will apply all the extra join clauses as well as the rel's own
3804  * restriction clauses. Note that we force the clauses to be treated as
3805  * non-join clauses during selectivity estimation.
3806  */
3807  allclauses = list_concat(list_copy(param_clauses),
3808  rel->baserestrictinfo);
3809  nrows = rel->tuples *
3811  allclauses,
3812  rel->relid, /* do not use 0! */
3813  JOIN_INNER,
3814  NULL);
3815  nrows = clamp_row_est(nrows);
3816  /* For safety, make sure result is not more than the base estimate */
3817  if (nrows > rel->rows)
3818  nrows = rel->rows;
3819  return nrows;
3820 }
double tuples
Definition: relation.h:529
List * baserestrictinfo
Definition: relation.h:544
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:518
double rows
Definition: relation.h:493
#define NULL
Definition: c.h:226
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:172
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 3876 of file costsize.c.

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

Referenced by get_joinrel_parampathinfo().

3881 {
3882  double nrows;
3883 
3884  /*
3885  * Estimate the number of rows returned by the parameterized join as the
3886  * sizes of the input paths times the selectivity of the clauses that have
3887  * ended up at this join node.
3888  *
3889  * As with set_joinrel_size_estimates, the rowcount estimate could depend
3890  * on the pair of input paths provided, though ideally we'd get the same
3891  * estimate for any pair with the same parameterization.
3892  */
3893  nrows = calc_joinrel_size_estimate(root,
3894  outer_path->parent,
3895  inner_path->parent,
3896  outer_path->rows,
3897  inner_path->rows,
3898  sjinfo,
3899  restrict_clauses);
3900  /* For safety, make sure result is not more than the base estimate */
3901  if (nrows > rel->rows)
3902  nrows = rel->rows;
3903  return nrows;
3904 }
RelOptInfo * parent
Definition: relation.h:894
double rows
Definition: relation.h:493
double rows
Definition: relation.h:905
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:3916
double index_pages_fetched ( double  tuples_fetched,
BlockNumber  pages,
double  index_pages,
PlannerInfo root 
)

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

740 {
741  double pages_fetched;
742  double total_pages;
743  double T,
744  b;
745 
746  /* T is # pages in table, but don't allow it to be zero */
747  T = (pages > 1) ? (double) pages : 1.0;
748 
749  /* Compute number of pages assumed to be competing for cache space */
750  total_pages = root->total_table_pages + index_pages;
751  total_pages = Max(total_pages, 1.0);
752  Assert(T <= total_pages);
753 
754  /* b is pro-rated share of effective_cache_size */
755  b = (double) effective_cache_size *T / total_pages;
756 
757  /* force it positive and integral */
758  if (b <= 1.0)
759  b = 1.0;
760  else
761  b = ceil(b);
762 
763  /* This part is the Mackert and Lohman formula */
764  if (T <= b)
765  {
766  pages_fetched =
767  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
768  if (pages_fetched >= T)
769  pages_fetched = T;
770  else
771  pages_fetched = ceil(pages_fetched);
772  }
773  else
774  {
775  double lim;
776 
777  lim = (2.0 * T * b) / (2.0 * T - b);
778  if (tuples_fetched <= lim)
779  {
780  pages_fetched =
781  (2.0 * T * tuples_fetched) / (2.0 * T + tuples_fetched);
782  }
783  else
784  {
785  pages_fetched =
786  b + (tuples_fetched - lim) * (T - b) / T;
787  }
788  pages_fetched = ceil(pages_fetched);
789  }
790  return pages_fetched;
791 }
int effective_cache_size
Definition: costsize.c:112
static const uint32 T[65]
Definition: md5.c:101
double total_table_pages
Definition: relation.h:284
#define Max(x, y)
Definition: c.h:796
#define Assert(condition)
Definition: c.h:671
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 2686 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().

2692 {
2693  Cost startup_cost = 0;
2694  Cost run_cost = 0;
2695  double outer_path_rows = outer_path->rows;
2696  double inner_path_rows = inner_path->rows;
2697  int num_hashclauses = list_length(hashclauses);
2698  int numbuckets;
2699  int numbatches;
2700  int num_skew_mcvs;
2701 
2702  /* cost of source data */
2703  startup_cost += outer_path->startup_cost;
2704  run_cost += outer_path->total_cost - outer_path->startup_cost;
2705  startup_cost += inner_path->total_cost;
2706 
2707  /*
2708  * Cost of computing hash function: must do it once per input tuple. We
2709  * charge one cpu_operator_cost for each column's hash function. Also,
2710  * tack on one cpu_tuple_cost per inner row, to model the costs of
2711  * inserting the row into the hashtable.
2712  *
2713  * XXX when a hashclause is more complex than a single operator, we really
2714  * should charge the extra eval costs of the left or right side, as
2715  * appropriate, here. This seems more work than it's worth at the moment.
2716  */
2717  startup_cost += (cpu_operator_cost * num_hashclauses + cpu_tuple_cost)
2718  * inner_path_rows;
2719  run_cost += cpu_operator_cost * num_hashclauses * outer_path_rows;
2720 
2721  /*
2722  * Get hash table size that executor would use for inner relation.
2723  *
2724  * XXX for the moment, always assume that skew optimization will be
2725  * performed. As long as SKEW_WORK_MEM_PERCENT is small, it's not worth
2726  * trying to determine that for sure.
2727  *
2728  * XXX at some point it might be interesting to try to account for skew
2729  * optimization in the cost estimate, but for now, we don't.
2730  */
2731  ExecChooseHashTableSize(inner_path_rows,
2732  inner_path->pathtarget->width,
2733  true, /* useskew */
2734  &numbuckets,
2735  &numbatches,
2736  &num_skew_mcvs);
2737 
2738  /*
2739  * If inner relation is too big then we will need to "batch" the join,
2740  * which implies writing and reading most of the tuples to disk an extra
2741  * time. Charge seq_page_cost per page, since the I/O should be nice and
2742  * sequential. Writing the inner rel counts as startup cost, all the rest
2743  * as run cost.
2744  */
2745  if (numbatches > 1)
2746  {
2747  double outerpages = page_size(outer_path_rows,
2748  outer_path->pathtarget->width);
2749  double innerpages = page_size(inner_path_rows,
2750  inner_path->pathtarget->width);
2751 
2752  startup_cost += seq_page_cost * innerpages;
2753  run_cost += seq_page_cost * (innerpages + 2 * outerpages);
2754  }
2755 
2756  /* CPU costs left for later */
2757 
2758  /* Public result fields */
2759  workspace->startup_cost = startup_cost;
2760  workspace->total_cost = startup_cost + run_cost;
2761  /* Save private data for final_cost_hashjoin */
2762  workspace->run_cost = run_cost;
2763  workspace->numbuckets = numbuckets;
2764  workspace->numbatches = numbatches;
2765 }
PathTarget * pathtarget
Definition: relation.h:895
static double page_size(double tuples, int width)
Definition: costsize.c:4791
void ExecChooseHashTableSize(double ntuples, int tupwidth, bool useskew, int *numbuckets, int *numbatches, int *num_skew_mcvs)
Definition: nodeHash.c:404
Cost startup_cost
Definition: relation.h:906
double cpu_operator_cost
Definition: costsize.c:108
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
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:827
double seq_page_cost
Definition: costsize.c:104
double Cost
Definition: nodes.h:632
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 2167 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().

2173 {
2174  Cost startup_cost = 0;
2175  Cost run_cost = 0;
2176  double outer_path_rows = outer_path->rows;
2177  double inner_path_rows = inner_path->rows;
2178  Cost inner_run_cost;
2179  double outer_rows,
2180  inner_rows,
2181  outer_skip_rows,
2182  inner_skip_rows;
2183  Selectivity outerstartsel,
2184  outerendsel,
2185  innerstartsel,
2186  innerendsel;
2187  Path sort_path; /* dummy for result of cost_sort */
2188 
2189  /* Protect some assumptions below that rowcounts aren't zero or NaN */
2190  if (outer_path_rows <= 0 || isnan(outer_path_rows))
2191  outer_path_rows = 1;
2192  if (inner_path_rows <= 0 || isnan(inner_path_rows))
2193  inner_path_rows = 1;
2194 
2195  /*
2196  * A merge join will stop as soon as it exhausts either input stream
2197  * (unless it's an outer join, in which case the outer side has to be
2198  * scanned all the way anyway). Estimate fraction of the left and right
2199  * inputs that will actually need to be scanned. Likewise, we can
2200  * estimate the number of rows that will be skipped before the first join
2201  * pair is found, which should be factored into startup cost. We use only
2202  * the first (most significant) merge clause for this purpose. Since
2203  * mergejoinscansel() is a fairly expensive computation, we cache the
2204  * results in the merge clause RestrictInfo.
2205  */
2206  if (mergeclauses && jointype != JOIN_FULL)
2207  {
2208  RestrictInfo *firstclause = (RestrictInfo *) linitial(mergeclauses);
2209  List *opathkeys;
2210  List *ipathkeys;
2211  PathKey *opathkey;
2212  PathKey *ipathkey;
2213  MergeScanSelCache *cache;
2214 
2215  /* Get the input pathkeys to determine the sort-order details */
2216  opathkeys = outersortkeys ? outersortkeys : outer_path->pathkeys;
2217  ipathkeys = innersortkeys ? innersortkeys : inner_path->pathkeys;
2218  Assert(opathkeys);
2219  Assert(ipathkeys);
2220  opathkey = (PathKey *) linitial(opathkeys);
2221  ipathkey = (PathKey *) linitial(ipathkeys);
2222  /* debugging check */
2223  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
2224  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation ||
2225  opathkey->pk_strategy != ipathkey->pk_strategy ||
2226  opathkey->pk_nulls_first != ipathkey->pk_nulls_first)
2227  elog(ERROR, "left and right pathkeys do not match in mergejoin");
2228 
2229  /* Get the selectivity with caching */
2230  cache = cached_scansel(root, firstclause, opathkey);
2231 
2232  if (bms_is_subset(firstclause->left_relids,
2233  outer_path->parent->relids))
2234  {
2235  /* left side of clause is outer */
2236  outerstartsel = cache->leftstartsel;
2237  outerendsel = cache->leftendsel;
2238  innerstartsel = cache->rightstartsel;
2239  innerendsel = cache->rightendsel;
2240  }
2241  else
2242  {
2243  /* left side of clause is inner */
2244  outerstartsel = cache->rightstartsel;
2245  outerendsel = cache->rightendsel;
2246  innerstartsel = cache->leftstartsel;
2247  innerendsel = cache->leftendsel;
2248  }
2249  if (jointype == JOIN_LEFT ||
2250  jointype == JOIN_ANTI)
2251  {
2252  outerstartsel = 0.0;
2253  outerendsel = 1.0;
2254  }
2255  else if (jointype == JOIN_RIGHT)
2256  {
2257  innerstartsel = 0.0;
2258  innerendsel = 1.0;
2259  }
2260  }
2261  else
2262  {
2263  /* cope with clauseless or full mergejoin */
2264  outerstartsel = innerstartsel = 0.0;
2265  outerendsel = innerendsel = 1.0;
2266  }
2267 
2268  /*
2269  * Convert selectivities to row counts. We force outer_rows and
2270  * inner_rows to be at least 1, but the skip_rows estimates can be zero.
2271  */
2272  outer_skip_rows = rint(outer_path_rows * outerstartsel);
2273  inner_skip_rows = rint(inner_path_rows * innerstartsel);
2274  outer_rows = clamp_row_est(outer_path_rows * outerendsel);
2275  inner_rows = clamp_row_est(inner_path_rows * innerendsel);
2276 
2277  Assert(outer_skip_rows <= outer_rows);
2278  Assert(inner_skip_rows <= inner_rows);
2279 
2280  /*
2281  * Readjust scan selectivities to account for above rounding. This is
2282  * normally an insignificant effect, but when there are only a few rows in
2283  * the inputs, failing to do this makes for a large percentage error.
2284  */
2285  outerstartsel = outer_skip_rows / outer_path_rows;
2286  innerstartsel = inner_skip_rows / inner_path_rows;
2287  outerendsel = outer_rows / outer_path_rows;
2288  innerendsel = inner_rows / inner_path_rows;
2289 
2290  Assert(outerstartsel <= outerendsel);
2291  Assert(innerstartsel <= innerendsel);
2292 
2293  /* cost of source data */
2294 
2295  if (outersortkeys) /* do we need to sort outer? */
2296  {
2297  cost_sort(&sort_path,
2298  root,
2299  outersortkeys,
2300  outer_path->total_cost,
2301  outer_path_rows,
2302  outer_path->pathtarget->width,
2303  0.0,
2304  work_mem,
2305  -1.0);
2306  startup_cost += sort_path.startup_cost;
2307  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2308  * outerstartsel;
2309  run_cost += (sort_path.total_cost - sort_path.startup_cost)
2310  * (outerendsel - outerstartsel);
2311  }
2312  else
2313  {
2314  startup_cost += outer_path->startup_cost;
2315  startup_cost += (outer_path->total_cost - outer_path->startup_cost)
2316  * outerstartsel;
2317  run_cost += (outer_path->total_cost - outer_path->startup_cost)
2318  * (outerendsel - outerstartsel);
2319  }
2320 
2321  if (innersortkeys) /* do we need to sort inner? */
2322  {
2323  cost_sort(&sort_path,
2324  root,
2325  innersortkeys,
2326  inner_path->total_cost,
2327  inner_path_rows,
2328  inner_path->pathtarget->width,
2329  0.0,
2330  work_mem,
2331  -1.0);
2332  startup_cost += sort_path.startup_cost;
2333  startup_cost += (sort_path.total_cost - sort_path.startup_cost)
2334  * innerstartsel;
2335  inner_run_cost = (sort_path.total_cost - sort_path.startup_cost)
2336  * (innerendsel - innerstartsel);
2337  }
2338  else
2339  {
2340  startup_cost += inner_path->startup_cost;
2341  startup_cost += (inner_path->total_cost - inner_path->startup_cost)
2342  * innerstartsel;
2343  inner_run_cost = (inner_path->total_cost - inner_path->startup_cost)
2344  * (innerendsel - innerstartsel);
2345  }
2346 
2347  /*
2348  * We can't yet determine whether rescanning occurs, or whether
2349  * materialization of the inner input should be done. The minimum
2350  * possible inner input cost, regardless of rescan and materialization
2351  * considerations, is inner_run_cost. We include that in
2352  * workspace->total_cost, but not yet in run_cost.
2353  */
2354 
2355  /* CPU costs left for later */
2356 
2357  /* Public result fields */
2358  workspace->startup_cost = startup_cost;
2359  workspace->total_cost = startup_cost + run_cost + inner_run_cost;
2360  /* Save private data for final_cost_mergejoin */
2361  workspace->run_cost = run_cost;
2362  workspace->inner_run_cost = inner_run_cost;
2363  workspace->outer_rows = outer_rows;
2364  workspace->inner_rows = inner_rows;
2365  workspace->outer_skip_rows = outer_skip_rows;
2366  workspace->inner_skip_rows = inner_skip_rows;
2367 }
Selectivity leftendsel
Definition: relation.h:1718
PathTarget * pathtarget
Definition: relation.h:895
static MergeScanSelCache * cached_scansel(PlannerInfo *root, RestrictInfo *rinfo, PathKey *pathkey)
Definition: costsize.c:2608
Relids left_relids
Definition: relation.h:1664
double Selectivity
Definition: nodes.h:631
int pk_strategy
Definition: relation.h:793
#define linitial(l)
Definition: pg_list.h:110
bool pk_nulls_first
Definition: relation.h:794
#define ERROR
Definition: elog.h:43
Cost startup_cost
Definition: relation.h:906
RelOptInfo * parent
Definition: relation.h:894
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:307
Selectivity rightstartsel
Definition: relation.h:1719
Relids relids
Definition: relation.h:490
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:1462
int work_mem
Definition: globals.c:112
Cost total_cost
Definition: relation.h:907
double outer_skip_rows
Definition: relation.h:2084
List * pathkeys
Definition: relation.h:909
#define Assert(condition)
Definition: c.h:671
double rows
Definition: relation.h:905
EquivalenceClass * pk_eclass
Definition: relation.h:791
Oid pk_opfamily
Definition: relation.h:792
int width
Definition: relation.h:827
#define elog
Definition: elog.h:219
double inner_skip_rows
Definition: relation.h:2085
double clamp_row_est(double nrows)
Definition: costsize.c:172
Definition: pg_list.h:45
Definition: relation.h:888
Selectivity rightendsel
Definition: relation.h:1720
double Cost
Definition: nodes.h:632
Selectivity leftstartsel
Definition: relation.h:1717
void initial_cost_nestloop ( PlannerInfo root,
JoinCostWorkspace workspace,
JoinType  jointype,
Path outer_path,
Path inner_path,
SpecialJoinInfo sjinfo,
SemiAntiJoinFactors semifactors 
)

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

1906 {
1907  Cost startup_cost = 0;
1908  Cost run_cost = 0;
1909  double outer_path_rows = outer_path->rows;
1910  Cost inner_rescan_start_cost;
1911  Cost inner_rescan_total_cost;
1912  Cost inner_run_cost;
1913  Cost inner_rescan_run_cost;
1914 
1915  /* estimate costs to rescan the inner relation */
1916  cost_rescan(root, inner_path,
1917  &inner_rescan_start_cost,
1918  &inner_rescan_total_cost);
1919 
1920  /* cost of source data */
1921 
1922  /*
1923  * NOTE: clearly, we must pay both outer and inner paths' startup_cost
1924  * before we can start returning tuples, so the join's startup cost is
1925  * their sum. We'll also pay the inner path's rescan startup cost
1926  * multiple times.
1927  */
1928  startup_cost += outer_path->startup_cost + inner_path->startup_cost;
1929  run_cost += outer_path->total_cost - outer_path->startup_cost;
1930  if (outer_path_rows > 1)
1931  run_cost += (outer_path_rows - 1) * inner_rescan_start_cost;
1932 
1933  inner_run_cost = inner_path->total_cost - inner_path->startup_cost;
1934  inner_rescan_run_cost = inner_rescan_total_cost - inner_rescan_start_cost;
1935 
1936  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
1937  {
1938  /*
1939  * SEMI or ANTI join: executor will stop after first match.
1940  *
1941  * Getting decent estimates requires inspection of the join quals,
1942  * which we choose to postpone to final_cost_nestloop.
1943  */
1944 
1945  /* Save private data for final_cost_nestloop */
1946  workspace->inner_run_cost = inner_run_cost;
1947  workspace->inner_rescan_run_cost = inner_rescan_run_cost;
1948  }
1949  else
1950  {
1951  /* Normal case; we'll scan whole input rel for each outer row */
1952  run_cost += inner_run_cost;
1953  if (outer_path_rows > 1)
1954  run_cost += (outer_path_rows - 1) * inner_rescan_run_cost;
1955  }
1956 
1957  /* CPU costs left for later */
1958 
1959  /* Public result fields */
1960  workspace->startup_cost = startup_cost;
1961  workspace->total_cost = startup_cost + run_cost;
1962  /* Save private data for final_cost_nestloop */
1963  workspace->run_cost = run_cost;
1964 }
static void cost_rescan(PlannerInfo *root, Path *path, Cost *rescan_startup_cost, Cost *rescan_total_cost)
Definition: costsize.c:3092
Cost inner_rescan_run_cost
Definition: relation.h:2079
Cost startup_cost
Definition: relation.h:906
Cost total_cost
Definition: relation.h:907
double rows
Definition: relation.h:905
double Cost
Definition: nodes.h:632
void set_baserel_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 3765 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_tablesample_rel_size(), and set_values_size_estimates().

3766 {
3767  double nrows;
3768 
3769  /* Should only be applied to base relations */
3770  Assert(rel->relid > 0);
3771 
3772  nrows = rel->tuples *
3774  rel->baserestrictinfo,
3775  0,
3776  JOIN_INNER,
3777  NULL);
3778 
3779  rel->rows = clamp_row_est(nrows);
3780 
3782 
3783  set_rel_width(root, rel);
3784 }
double tuples
Definition: relation.h:529
List * baserestrictinfo
Definition: relation.h:544
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4544
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Index relid
Definition: relation.h:518
double rows
Definition: relation.h:493
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
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:172
QualCost baserestrictcost
Definition: relation.h:546
void set_cte_size_estimates ( PlannerInfo root,
RelOptInfo rel,
double  cte_rows 
)

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

4467 {
4468  RangeTblEntry *rte;
4469 
4470  /* Should only be applied to base relations that are CTE references */
4471  Assert(rel->relid > 0);
4472  rte = planner_rt_fetch(rel->relid, root);
4473  Assert(rte->rtekind == RTE_CTE);
4474 
4475  if (rte->self_reference)
4476  {
4477  /*
4478  * In a self-reference, arbitrarily assume the average worktable size
4479  * is about 10 times the nonrecursive term's size.
4480  */
4481  rel->tuples = 10 * cte_rows;
4482  }
4483  else
4484  {
4485  /* Otherwise just believe the CTE's rowcount estimate */
4486  rel->tuples = cte_rows;
4487  }
4488 
4489  /* Now estimate number of output rows, etc */
4490  set_baserel_size_estimates(root, rel);
4491 }
double tuples
Definition: relation.h:529
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
Index relid
Definition: relation.h:518
bool self_reference
Definition: parsenodes.h:944
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:3765
#define Assert(condition)
Definition: c.h:671
RTEKind rtekind
Definition: parsenodes.h:882
void set_foreign_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

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

4510 {
4511  /* Should only be applied to base relations */
4512  Assert(rel->relid > 0);
4513 
4514  rel->rows = 1000; /* entirely bogus default estimate */
4515 
4517 
4518  set_rel_width(root, rel);
4519 }
List * baserestrictinfo
Definition: relation.h:544
static void set_rel_width(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:4544
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3199
Index relid
Definition: relation.h:518
double rows
Definition: relation.h:493
#define Assert(condition)
Definition: c.h:671
QualCost baserestrictcost
Definition: relation.h:546
void set_function_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

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

4397 {
4398  RangeTblEntry *rte;
4399  ListCell *lc;
4400 
4401  /* Should only be applied to base relations that are functions */
4402  Assert(rel->relid > 0);
4403  rte = planner_rt_fetch(rel->relid, root);
4404  Assert(rte->rtekind == RTE_FUNCTION);
4405 
4406  /*
4407  * Estimate number of rows the functions will return. The rowcount of the
4408  * node is that of the largest function result.
4409  */
4410  rel->tuples = 0;
4411  foreach(lc, rte->functions)
4412  {
4413  RangeTblFunction *rtfunc = (RangeTblFunction *) lfirst(lc);
4414  double ntup = expression_returns_set_rows(rtfunc->funcexpr);
4415 
4416  if (ntup > rel->tuples)
4417  rel->tuples = ntup;
4418  }
4419 
4420  /* Now estimate number of output rows, etc */
4421  set_baserel_size_estimates(root, rel);
4422 }
double expression_returns_set_rows(Node *clause)
Definition: clauses.c:801
double tuples
Definition: relation.h:529
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
Index relid
Definition: relation.h:518
void set_baserel_size_estimates(PlannerInfo *root, RelOptInfo *rel)
Definition: costsize.c:3765
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
List * functions
Definition: parsenodes.h:931
RTEKind rtekind
Definition: parsenodes.h:882
void set_joinrel_size_estimates ( PlannerInfo root,
RelOptInfo rel,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
SpecialJoinInfo sjinfo,
List restrictlist 
)

Definition at line 3845 of file costsize.c.

References calc_joinrel_size_estimate(), and RelOptInfo::rows.

Referenced by build_join_rel().

3850 {
3851  rel->rows = calc_joinrel_size_estimate(root,
3852  outer_rel,
3853  inner_rel,
3854  outer_rel->rows,
3855  inner_rel->rows,
3856  sjinfo,
3857  restrictlist);
3858 }
double rows
Definition: relation.h:493
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:3916
PathTarget* set_pathtarget_cost_width ( PlannerInfo root,
PathTarget target 
)

Definition at line 4702 of file costsize.c.

References Assert, RelOptInfo::attr_widths, PathTarget::cost, cost_qual_eval_node(), PathTarget::exprs, exprType(), exprTypmod(), get_typavgwidth(), IsA, lfirst, RelOptInfo::max_attr, RelOptInfo::min_attr, NULL, QualCost::per_tuple, PlannerInfo::simple_rel_array, PlannerInfo::simple_rel_array_size, QualCost::startup, RangeQueryClause::var, Var::varattno, Var::varlevelsup, Var::varno, Var::vartype, Var::vartypmod, and PathTarget::width.

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

4703 {
4704  int32 tuple_width = 0;
4705  ListCell *lc;
4706 
4707  /* Vars are assumed to have cost zero, but other exprs do not */
4708  target->cost.startup = 0;
4709  target->cost.per_tuple = 0;
4710 
4711  foreach(lc, target->exprs)
4712  {
4713  Node *node = (Node *) lfirst(lc);
4714 
4715  if (IsA(node, Var))
4716  {
4717  Var *var = (Var *) node;
4718  int32 item_width;
4719 
4720  /* We should not see any upper-level Vars here */
4721  Assert(var->varlevelsup == 0);
4722 
4723  /* Try to get data from RelOptInfo cache */
4724  if (var->varno < root->simple_rel_array_size)
4725  {
4726  RelOptInfo *rel = root->simple_rel_array[var->varno];
4727 
4728  if (rel != NULL &&
4729  var->varattno >= rel->min_attr &&
4730  var->varattno <= rel->max_attr)
4731  {
4732  int ndx = var->varattno - rel->min_attr;
4733 
4734  if (rel->attr_widths[ndx] > 0)
4735  {
4736  tuple_width += rel->attr_widths[ndx];
4737  continue;
4738  }
4739  }
4740  }
4741 
4742  /*
4743  * No cached data available, so estimate using just the type info.
4744  */
4745  item_width = get_typavgwidth(var->vartype, var->vartypmod);
4746  Assert(item_width > 0);
4747  tuple_width += item_width;
4748  }
4749  else
4750  {
4751  /*
4752  * Handle general expressions using type info.
4753  */
4754  int32 item_width;
4755  QualCost cost;
4756 
4757  item_width = get_typavgwidth(exprType(node), exprTypmod(node));
4758  Assert(item_width > 0);
4759  tuple_width += item_width;
4760 
4761  /* Account for cost, too */
4762  cost_qual_eval_node(&cost, node, root);
4763  target->cost.startup += cost.startup;
4764  target->cost.per_tuple += cost.per_tuple;
4765  }
4766  }
4767 
4768  Assert(tuple_width >= 0);
4769  target->width = tuple_width;
4770 
4771  return target;
4772 }
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:3225
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Index varlevelsup
Definition: primnodes.h:151
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:273
Definition: nodes.h:508
AttrNumber varattno
Definition: primnodes.h:146
Definition: primnodes.h:141
Cost startup
Definition: relation.h:45
signed int int32
Definition: c.h:253
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
Cost per_tuple
Definition: relation.h:46
Oid vartype
Definition: primnodes.h:148
int simple_rel_array_size
Definition: relation.h:177
Index varno
Definition: primnodes.h:144
List * exprs
Definition: relation.h:824
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2296
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
QualCost cost
Definition: relation.h:826
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int width
Definition: relation.h:827
AttrNumber max_attr
Definition: relation.h:522
int32 * attr_widths
Definition: relation.h:524
int32 vartypmod
Definition: primnodes.h:149
AttrNumber min_attr
Definition: relation.h:521
void set_subquery_size_estimates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4314 of file costsize.c.

References Assert, RelOptInfo::attr_widths, castNode, RelOptInfo::cheapest_total_path, TargetEntry::expr, fetch_upper_rel(), find_base_rel(), IsA, lfirst, RelOptInfo::max_attr, RelOptInfo::min_attr, NULL, PlannerInfo::parse, PG_USED_FOR_ASSERTS_ONLY, planner_rt_fetch, RelOptInfo::relid, TargetEntry::resjunk, TargetEntry::resno, Path::rows, RTE_SUBQUERY, set_baserel_size_estimates(), Query::setOperations, RelOptInfo::subroot, Query::targetList, RelOptInfo::tuples, UPPERREL_FINAL, RangeQueryClause::var, Var::varattno, and Var::varno.

Referenced by recurse_set_operations(), and set_subquery_pathlist().

4315 {
4316  PlannerInfo *subroot = rel->subroot;
4317  RelOptInfo *sub_final_rel;
4319  ListCell *lc;
4320 
4321  /* Should only be applied to base relations that are subqueries */
4322  Assert(rel->relid > 0);
4323  rte = planner_rt_fetch(rel->relid, root);
4324  Assert(rte->rtekind == RTE_SUBQUERY);
4325 
4326  /*
4327  * Copy raw number of output rows from subquery. All of its paths should
4328  * have the same output rowcount, so just look at cheapest-total.
4329  */
4330  sub_final_rel = fetch_upper_rel(subroot, UPPERREL_FINAL, NULL);
4331  rel->tuples = sub_final_rel->cheapest_total_path->rows;
4332 
4333  /*
4334  * Compute per-output-column width estimates by examining the subquery's
4335  * targetlist. For any output that is a plain Var, get the width estimate
4336  * that was made while planning the subquery. Otherwise, we leave it to
4337  * set_rel_width to fill in a datatype-based default estimate.
4338  */
4339  foreach(lc, subroot->parse->targetList)
4340  {
4341  TargetEntry *te = castNode(TargetEntry, lfirst(lc));
4342  Node *texpr = (Node *) te->expr;
4343  int32 item_width = 0;
4344 
4345  /* junk columns aren't visible to upper query */
4346  if (te->resjunk)
4347  continue;
4348 
4349  /*
4350  * The subquery could be an expansion of a view that's had columns
4351  * added to it since the current query was parsed, so that there are
4352  * non-junk tlist columns in it that don't correspond to any column
4353  * visible at our query level. Ignore such columns.
4354  */
4355  if (te->resno < rel->min_attr || te->resno > rel->max_attr)
4356  continue;
4357 
4358  /*
4359  * XXX This currently doesn't work for subqueries containing set
4360  * operations, because the Vars in their tlists are bogus references
4361  * to the first leaf subquery, which wouldn't give the right answer
4362  * even if we could still get to its PlannerInfo.
4363  *
4364  * Also, the subquery could be an appendrel for which all branches are
4365  * known empty due to constraint exclusion, in which case
4366  * set_append_rel_pathlist will have left the attr_widths set to zero.
4367  *
4368  * In either case, we just leave the width estimate zero until
4369  * set_rel_width fixes it.
4370  */
4371  if (IsA(texpr, Var) &&
4372  subroot->parse->setOperations == NULL)
4373  {
4374  Var *var = (Var *) texpr;
4375  RelOptInfo *subrel = find_base_rel(subroot, var->varno);
4376 
4377  item_width = subrel->attr_widths[var->varattno - subrel->min_attr];
4378  }
4379  rel->attr_widths[te->resno - rel->min_attr] = item_width;
4380  }
4381 
4382  /* Now estimate number of output rows, etc */
4383  set_baserel_size_estimates(root, rel);
4384 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
Query * parse
Definition: relation.h:152
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
double tuples
Definition: relation.h:529
Definition: nodes.h:508
AttrNumber varattno
Definition: primnodes.h:146