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

Go to the source code of this file.

Macros

#define IS_SRF_CALL(node)
 
#define HAVE_PLANNERINFO_TYPEDEF   1
 
#define HAVE_INDEXOPTINFO_TYPEDEF   1
 
#define HAVE_SPECIALJOININFO_TYPEDEF   1
 
#define PVC_INCLUDE_AGGREGATES   0x0001 /* include Aggrefs in output list */
 
#define PVC_RECURSE_AGGREGATES   0x0002 /* recurse into Aggref arguments */
 
#define PVC_INCLUDE_WINDOWFUNCS   0x0004 /* include WindowFuncs in output list */
 
#define PVC_RECURSE_WINDOWFUNCS   0x0008 /* recurse into WindowFunc arguments */
 
#define PVC_INCLUDE_PLACEHOLDERS
 
#define PVC_RECURSE_PLACEHOLDERS
 

Typedefs

typedef struct PlannerInfo PlannerInfo
 
typedef struct IndexOptInfo IndexOptInfo
 
typedef struct SpecialJoinInfo SpecialJoinInfo
 

Enumerations

enum  ForceParallelMode { FORCE_PARALLEL_OFF, FORCE_PARALLEL_ON, FORCE_PARALLEL_REGRESS }
 

Functions

Selectivity clause_selectivity (PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity clause_selectivity_ext (PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
 
Selectivity clauselist_selectivity (PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
 
Selectivity clauselist_selectivity_ext (PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
 
double clamp_row_est (double nrows)
 
bool is_pseudo_constant_for_index (PlannerInfo *root, Node *expr, IndexOptInfo *index)
 
struct PlannedStmtplanner (Query *parse, const char *query_string, int cursorOptions, struct ParamListInfoData *boundParams)
 
Exprexpression_planner (Expr *expr)
 
Exprexpression_planner_with_deps (Expr *expr, List **relationOids, List **invalItems)
 
bool plan_cluster_use_sort (Oid tableOid, Oid indexOid)
 
int plan_create_index_workers (Oid tableOid, Oid indexOid)
 
void extract_query_dependencies (Node *query, List **relationOids, List **invalItems, bool *hasRowSecurity)
 
Nodenegate_clause (Node *node)
 
Exprcanonicalize_qual (Expr *qual, bool is_check)
 
bool contain_mutable_functions (Node *clause)
 
bool contain_volatile_functions (Node *clause)
 
bool contain_volatile_functions_not_nextval (Node *clause)
 
Nodeeval_const_expressions (PlannerInfo *root, Node *node)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
Listexpand_function_arguments (List *args, Oid result_type, struct HeapTupleData *func_tuple)
 
bool predicate_implied_by (List *predicate_list, List *clause_list, bool weak)
 
bool predicate_refuted_by (List *predicate_list, List *clause_list, bool weak)
 
int count_nonjunk_tlist_entries (List *tlist)
 
TargetEntryget_sortgroupref_tle (Index sortref, List *targetList)
 
TargetEntryget_sortgroupclause_tle (SortGroupClause *sgClause, List *targetList)
 
Nodeget_sortgroupclause_expr (SortGroupClause *sgClause, List *targetList)
 
Listget_sortgrouplist_exprs (List *sgClauses, List *targetList)
 
SortGroupClauseget_sortgroupref_clause (Index sortref, List *clauses)
 
SortGroupClauseget_sortgroupref_clause_noerr (Index sortref, List *clauses)
 
Bitmapsetpull_varnos (PlannerInfo *root, Node *node)
 
Bitmapsetpull_varnos_of_level (PlannerInfo *root, Node *node, int levelsup)
 
void pull_varattnos (Node *node, Index varno, Bitmapset **varattnos)
 
Listpull_vars_of_level (Node *node, int levelsup)
 
bool contain_var_clause (Node *node)
 
bool contain_vars_of_level (Node *node, int levelsup)
 
int locate_var_of_level (Node *node, int levelsup)
 
Listpull_var_clause (Node *node, int flags)
 
Nodeflatten_join_alias_vars (Query *query, Node *node)
 

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
 
int force_parallel_mode
 
bool parallel_leader_participation
 

Macro Definition Documentation

◆ HAVE_INDEXOPTINFO_TYPEDEF

#define HAVE_INDEXOPTINFO_TYPEDEF   1

Definition at line 46 of file optimizer.h.

◆ HAVE_PLANNERINFO_TYPEDEF

#define HAVE_PLANNERINFO_TYPEDEF   1

Definition at line 40 of file optimizer.h.

◆ HAVE_SPECIALJOININFO_TYPEDEF

#define HAVE_SPECIALJOININFO_TYPEDEF   1

Definition at line 50 of file optimizer.h.

◆ IS_SRF_CALL

#define IS_SRF_CALL (   node)
Value:
((IsA(node, FuncExpr) && ((FuncExpr *) (node))->funcretset) || \
(IsA(node, OpExpr) && ((OpExpr *) (node))->opretset))
#define IsA(nodeptr, _type_)
Definition: nodes.h:584

Definition at line 28 of file optimizer.h.

Referenced by find_em_expr_usable_for_sorting_rel(), split_pathtarget_at_srfs(), and split_pathtarget_walker().

◆ PVC_INCLUDE_AGGREGATES

#define PVC_INCLUDE_AGGREGATES   0x0001 /* include Aggrefs in output list */

◆ PVC_INCLUDE_PLACEHOLDERS

◆ PVC_INCLUDE_WINDOWFUNCS

#define PVC_INCLUDE_WINDOWFUNCS   0x0004 /* include WindowFuncs in output list */

◆ PVC_RECURSE_AGGREGATES

◆ PVC_RECURSE_PLACEHOLDERS

#define PVC_RECURSE_PLACEHOLDERS
Value:
0x0020 /* recurse into PlaceHolderVar
* arguments */

Definition at line 189 of file optimizer.h.

Referenced by build_tlist_to_deparse(), estimate_num_groups(), pull_var_clause(), and pull_var_clause_walker().

◆ PVC_RECURSE_WINDOWFUNCS

Typedef Documentation

◆ IndexOptInfo

typedef struct IndexOptInfo IndexOptInfo

Definition at line 45 of file optimizer.h.

◆ PlannerInfo

typedef struct PlannerInfo PlannerInfo

Definition at line 39 of file optimizer.h.

◆ SpecialJoinInfo

Definition at line 49 of file optimizer.h.

Enumeration Type Documentation

◆ ForceParallelMode

Enumerator
FORCE_PARALLEL_OFF 
FORCE_PARALLEL_ON 
FORCE_PARALLEL_REGRESS 

Definition at line 106 of file optimizer.h.

Function Documentation

◆ canonicalize_qual()

Expr* canonicalize_qual ( Expr qual,
bool  is_check 
)

Definition at line 292 of file prepqual.c.

References Assert, find_duplicate_ors(), and IsA.

Referenced by ConstraintImpliedByRelConstraint(), convert_EXISTS_to_ANY(), DoCopy(), get_proposed_default_constraint(), get_relation_constraints(), preprocess_expression(), and RelationGetIndexPredicate().

293 {
294  Expr *newqual;
295 
296  /* Quick exit for empty qual */
297  if (qual == NULL)
298  return NULL;
299 
300  /* This should not be invoked on quals in implicit-AND format */
301  Assert(!IsA(qual, List));
302 
303  /*
304  * Pull up redundant subclauses in OR-of-AND trees. We do this only
305  * within the top-level AND/OR structure; there's no point in looking
306  * deeper. Also remove any NULL constants in the top-level structure.
307  */
308  newqual = find_duplicate_ors(qual, is_check);
309 
310  return newqual;
311 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
static Expr * find_duplicate_ors(Expr *qual, bool is_check)
Definition: prepqual.c:405
#define Assert(condition)
Definition: c.h:804
Definition: pg_list.h:50

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 196 of file costsize.c.

References MAXIMUM_ROWCOUNT.

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

197 {
198  /*
199  * Avoid infinite and NaN row estimates. Costs derived from such values
200  * are going to be useless. Also force the estimate to be at least one
201  * row, to make explain output look better and to avoid possible
202  * divide-by-zero when interpolating costs. Make it an integer, too.
203  */
204  if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
205  nrows = MAXIMUM_ROWCOUNT;
206  else if (nrows <= 1.0)
207  nrows = 1.0;
208  else
209  nrows = rint(nrows);
210 
211  return nrows;
212 }
#define MAXIMUM_ROWCOUNT
Definition: costsize.c:116

◆ clause_selectivity()

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

Definition at line 690 of file clausesel.c.

References clause_selectivity_ext().

Referenced by approx_tuple_count(), booltestsel(), consider_new_or_clause(), and get_foreign_key_join_selectivity().

695 {
696  return clause_selectivity_ext(root, clause, varRelid,
697  jointype, sjinfo, true);
698 }
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:707

◆ clause_selectivity_ext()

Selectivity clause_selectivity_ext ( PlannerInfo root,
Node clause,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo,
bool  use_extended_stats 
)

Definition at line 707 of file clausesel.c.

References arg, generate_unaccent_rules::args, FuncExpr::args, OpExpr::args, bms_is_subset_singleton(), booltestsel(), boolvarsel(), RestrictInfo::clause, RestrictInfo::clause_relids, clause_selectivity_ext(), clauselist_selectivity_ext(), clauselist_selectivity_or(), Const::constisnull, Const::constvalue, CurrentOfExpr::cvarno, DatumGetBool, DEBUG4, elog, estimate_expression_value(), find_base_rel(), FuncExpr::funcid, function_selectivity(), get_notclausearg(), FuncExpr::inputcollid, OpExpr::inputcollid, is_andclause(), is_funcclause(), is_notclause(), is_opclause(), is_orclause(), IsA, JOIN_INNER, join_selectivity(), RestrictInfo::norm_selec, nulltestsel(), OpExpr::opno, RestrictInfo::orclause, RestrictInfo::outer_selec, RestrictInfo::pseudoconstant, restriction_selectivity(), rowcomparesel(), s1, scalararraysel(), treat_as_join_clause(), RelOptInfo::tuples, RangeQueryClause::var, Var::varlevelsup, and Var::varno.

Referenced by clause_selectivity(), clause_selectivity_ext(), clauselist_selectivity_ext(), clauselist_selectivity_or(), and statext_mcv_clauselist_selectivity().

713 {
714  Selectivity s1 = 0.5; /* default for any unhandled clause type */
715  RestrictInfo *rinfo = NULL;
716  bool cacheable = false;
717 
718  if (clause == NULL) /* can this still happen? */
719  return s1;
720 
721  if (IsA(clause, RestrictInfo))
722  {
723  rinfo = (RestrictInfo *) clause;
724 
725  /*
726  * If the clause is marked pseudoconstant, then it will be used as a
727  * gating qual and should not affect selectivity estimates; hence
728  * return 1.0. The only exception is that a constant FALSE may be
729  * taken as having selectivity 0.0, since it will surely mean no rows
730  * out of the plan. This case is simple enough that we need not
731  * bother caching the result.
732  */
733  if (rinfo->pseudoconstant)
734  {
735  if (!IsA(rinfo->clause, Const))
736  return (Selectivity) 1.0;
737  }
738 
739  /*
740  * If the clause is marked redundant, always return 1.0.
741  */
742  if (rinfo->norm_selec > 1)
743  return (Selectivity) 1.0;
744 
745  /*
746  * If possible, cache the result of the selectivity calculation for
747  * the clause. We can cache if varRelid is zero or the clause
748  * contains only vars of that relid --- otherwise varRelid will affect
749  * the result, so mustn't cache. Outer join quals might be examined
750  * with either their join's actual jointype or JOIN_INNER, so we need
751  * two cache variables to remember both cases. Note: we assume the
752  * result won't change if we are switching the input relations or
753  * considering a unique-ified case, so we only need one cache variable
754  * for all non-JOIN_INNER cases.
755  */
756  if (varRelid == 0 ||
757  bms_is_subset_singleton(rinfo->clause_relids, varRelid))
758  {
759  /* Cacheable --- do we already have the result? */
760  if (jointype == JOIN_INNER)
761  {
762  if (rinfo->norm_selec >= 0)
763  return rinfo->norm_selec;
764  }
765  else
766  {
767  if (rinfo->outer_selec >= 0)
768  return rinfo->outer_selec;
769  }
770  cacheable = true;
771  }
772 
773  /*
774  * Proceed with examination of contained clause. If the clause is an
775  * OR-clause, we want to look at the variant with sub-RestrictInfos,
776  * so that per-subclause selectivities can be cached.
777  */
778  if (rinfo->orclause)
779  clause = (Node *) rinfo->orclause;
780  else
781  clause = (Node *) rinfo->clause;
782  }
783 
784  if (IsA(clause, Var))
785  {
786  Var *var = (Var *) clause;
787 
788  /*
789  * We probably shouldn't ever see an uplevel Var here, but if we do,
790  * return the default selectivity...
791  */
792  if (var->varlevelsup == 0 &&
793  (varRelid == 0 || varRelid == (int) var->varno))
794  {
795  /* Use the restriction selectivity function for a bool Var */
796  s1 = boolvarsel(root, (Node *) var, varRelid);
797  }
798  }
799  else if (IsA(clause, Const))
800  {
801  /* bool constant is pretty easy... */
802  Const *con = (Const *) clause;
803 
804  s1 = con->constisnull ? 0.0 :
805  DatumGetBool(con->constvalue) ? 1.0 : 0.0;
806  }
807  else if (IsA(clause, Param))
808  {
809  /* see if we can replace the Param */
810  Node *subst = estimate_expression_value(root, clause);
811 
812  if (IsA(subst, Const))
813  {
814  /* bool constant is pretty easy... */
815  Const *con = (Const *) subst;
816 
817  s1 = con->constisnull ? 0.0 :
818  DatumGetBool(con->constvalue) ? 1.0 : 0.0;
819  }
820  else
821  {
822  /* XXX any way to do better than default? */
823  }
824  }
825  else if (is_notclause(clause))
826  {
827  /* inverse of the selectivity of the underlying clause */
828  s1 = 1.0 - clause_selectivity_ext(root,
829  (Node *) get_notclausearg((Expr *) clause),
830  varRelid,
831  jointype,
832  sjinfo,
833  use_extended_stats);
834  }
835  else if (is_andclause(clause))
836  {
837  /* share code with clauselist_selectivity() */
838  s1 = clauselist_selectivity_ext(root,
839  ((BoolExpr *) clause)->args,
840  varRelid,
841  jointype,
842  sjinfo,
843  use_extended_stats);
844  }
845  else if (is_orclause(clause))
846  {
847  /*
848  * Almost the same thing as clauselist_selectivity, but with the
849  * clauses connected by OR.
850  */
851  s1 = clauselist_selectivity_or(root,
852  ((BoolExpr *) clause)->args,
853  varRelid,
854  jointype,
855  sjinfo,
856  use_extended_stats);
857  }
858  else if (is_opclause(clause) || IsA(clause, DistinctExpr))
859  {
860  OpExpr *opclause = (OpExpr *) clause;
861  Oid opno = opclause->opno;
862 
863  if (treat_as_join_clause(root, clause, rinfo, varRelid, sjinfo))
864  {
865  /* Estimate selectivity for a join clause. */
866  s1 = join_selectivity(root, opno,
867  opclause->args,
868  opclause->inputcollid,
869  jointype,
870  sjinfo);
871  }
872  else
873  {
874  /* Estimate selectivity for a restriction clause. */
875  s1 = restriction_selectivity(root, opno,
876  opclause->args,
877  opclause->inputcollid,
878  varRelid);
879  }
880 
881  /*
882  * DistinctExpr has the same representation as OpExpr, but the
883  * contained operator is "=" not "<>", so we must negate the result.
884  * This estimation method doesn't give the right behavior for nulls,
885  * but it's better than doing nothing.
886  */
887  if (IsA(clause, DistinctExpr))
888  s1 = 1.0 - s1;
889  }
890  else if (is_funcclause(clause))
891  {
892  FuncExpr *funcclause = (FuncExpr *) clause;
893 
894  /* Try to get an estimate from the support function, if any */
895  s1 = function_selectivity(root,
896  funcclause->funcid,
897  funcclause->args,
898  funcclause->inputcollid,
899  treat_as_join_clause(root, clause, rinfo,
900  varRelid, sjinfo),
901  varRelid,
902  jointype,
903  sjinfo);
904  }
905  else if (IsA(clause, ScalarArrayOpExpr))
906  {
907  /* Use node specific selectivity calculation function */
908  s1 = scalararraysel(root,
909  (ScalarArrayOpExpr *) clause,
910  treat_as_join_clause(root, clause, rinfo,
911  varRelid, sjinfo),
912  varRelid,
913  jointype,
914  sjinfo);
915  }
916  else if (IsA(clause, RowCompareExpr))
917  {
918  /* Use node specific selectivity calculation function */
919  s1 = rowcomparesel(root,
920  (RowCompareExpr *) clause,
921  varRelid,
922  jointype,
923  sjinfo);
924  }
925  else if (IsA(clause, NullTest))
926  {
927  /* Use node specific selectivity calculation function */
928  s1 = nulltestsel(root,
929  ((NullTest *) clause)->nulltesttype,
930  (Node *) ((NullTest *) clause)->arg,
931  varRelid,
932  jointype,
933  sjinfo);
934  }
935  else if (IsA(clause, BooleanTest))
936  {
937  /* Use node specific selectivity calculation function */
938  s1 = booltestsel(root,
939  ((BooleanTest *) clause)->booltesttype,
940  (Node *) ((BooleanTest *) clause)->arg,
941  varRelid,
942  jointype,
943  sjinfo);
944  }
945  else if (IsA(clause, CurrentOfExpr))
946  {
947  /* CURRENT OF selects at most one row of its table */
948  CurrentOfExpr *cexpr = (CurrentOfExpr *) clause;
949  RelOptInfo *crel = find_base_rel(root, cexpr->cvarno);
950 
951  if (crel->tuples > 0)
952  s1 = 1.0 / crel->tuples;
953  }
954  else if (IsA(clause, RelabelType))
955  {
956  /* Not sure this case is needed, but it can't hurt */
957  s1 = clause_selectivity_ext(root,
958  (Node *) ((RelabelType *) clause)->arg,
959  varRelid,
960  jointype,
961  sjinfo,
962  use_extended_stats);
963  }
964  else if (IsA(clause, CoerceToDomain))
965  {
966  /* Not sure this case is needed, but it can't hurt */
967  s1 = clause_selectivity_ext(root,
968  (Node *) ((CoerceToDomain *) clause)->arg,
969  varRelid,
970  jointype,
971  sjinfo,
972  use_extended_stats);
973  }
974  else
975  {
976  /*
977  * For anything else, see if we can consider it as a boolean variable.
978  * This only works if it's an immutable expression in Vars of a single
979  * relation; but there's no point in us checking that here because
980  * boolvarsel() will do it internally, and return a suitable default
981  * selectivity if not.
982  */
983  s1 = boolvarsel(root, clause, varRelid);
984  }
985 
986  /* Cache the result if possible */
987  if (cacheable)
988  {
989  if (jointype == JOIN_INNER)
990  rinfo->norm_selec = s1;
991  else
992  rinfo->outer_selec = s1;
993  }
994 
995 #ifdef SELECTIVITY_DEBUG
996  elog(DEBUG4, "clause_selectivity: s1 %f", s1);
997 #endif /* SELECTIVITY_DEBUG */
998 
999  return s1;
1000 }
Datum constvalue
Definition: primnodes.h:214
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
Index varlevelsup
Definition: primnodes.h:191
List * args
Definition: primnodes.h:498
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2055
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:106
Expr * orclause
Definition: pathnodes.h:2037
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1782
double tuples
Definition: pathnodes.h:710
Selectivity rowcomparesel(PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:2170
Relids clause_relids
Definition: pathnodes.h:2021
bool pseudoconstant
Definition: pathnodes.h:2014
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:97
Definition: nodes.h:533
double Selectivity
Definition: nodes.h:666
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:181
#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:1813
static bool is_funcclause(const void *clause)
Definition: nodeFuncs.h:59
Selectivity norm_selec
Definition: pathnodes.h:2044
static bool bms_is_subset_singleton(const Bitmapset *s, int x)
Definition: clausesel.c:591
Oid funcid
Definition: primnodes.h:490
char * s1
Selectivity nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1695
Selectivity function_selectivity(PlannerInfo *root, Oid funcid, List *args, Oid inputcollid, bool is_join, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1862
#define DatumGetBool(X)
Definition: postgres.h:393
Selectivity outer_selec
Definition: pathnodes.h:2047
Expr * clause
Definition: pathnodes.h:2006
Index varno
Definition: primnodes.h:184
static bool is_notclause(const void *clause)
Definition: nodeFuncs.h:115
static bool treat_as_join_clause(PlannerInfo *root, Node *clause, RestrictInfo *rinfo, int varRelid, SpecialJoinInfo *sjinfo)
Definition: clausesel.c:612
static Selectivity clauselist_selectivity_or(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:361
static Expr * get_notclausearg(const void *notclause)
Definition: nodeFuncs.h:124
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:707
Oid inputcollid
Definition: primnodes.h:497
Oid inputcollid
Definition: primnodes.h:542
Selectivity clauselist_selectivity_ext(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:119
#define elog(elevel,...)
Definition: elog.h:227
void * arg
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1821
Oid opno
Definition: primnodes.h:537
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374
List * args
Definition: primnodes.h:543
Selectivity booltestsel(PlannerInfo *root, BoolTestType booltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1537
Selectivity boolvarsel(PlannerInfo *root, Node *arg, int varRelid)
Definition: selfuncs.c:1509
bool constisnull
Definition: primnodes.h:215

◆ clauselist_selectivity()

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

Definition at line 102 of file clausesel.c.

References clauselist_selectivity_ext().

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

107 {
108  return clauselist_selectivity_ext(root, clauses, varRelid,
109  jointype, sjinfo, true);
110 }
Selectivity clauselist_selectivity_ext(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:119

◆ clauselist_selectivity_ext()

Selectivity clauselist_selectivity_ext ( PlannerInfo root,
List clauses,
int  varRelid,
JoinType  jointype,
SpecialJoinInfo sjinfo,
bool  use_extended_stats 
)

Definition at line 119 of file clausesel.c.

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

Referenced by clause_selectivity_ext(), clauselist_apply_dependencies(), clauselist_selectivity(), and statext_mcv_clauselist_selectivity().

125 {
126  Selectivity s1 = 1.0;
127  RelOptInfo *rel;
128  Bitmapset *estimatedclauses = NULL;
129  RangeQueryClause *rqlist = NULL;
130  ListCell *l;
131  int listidx;
132 
133  /*
134  * If there's exactly one clause, just go directly to
135  * clause_selectivity_ext(). None of what we might do below is relevant.
136  */
137  if (list_length(clauses) == 1)
138  return clause_selectivity_ext(root, (Node *) linitial(clauses),
139  varRelid, jointype, sjinfo,
140  use_extended_stats);
141 
142  /*
143  * Determine if these clauses reference a single relation. If so, and if
144  * it has extended statistics, try to apply those.
145  */
146  rel = find_single_rel_for_clauses(root, clauses);
147  if (use_extended_stats && rel && rel->rtekind == RTE_RELATION && rel->statlist != NIL)
148  {
149  /*
150  * Estimate as many clauses as possible using extended statistics.
151  *
152  * 'estimatedclauses' is populated with the 0-based list position
153  * index of clauses estimated here, and that should be ignored below.
154  */
155  s1 = statext_clauselist_selectivity(root, clauses, varRelid,
156  jointype, sjinfo, rel,
157  &estimatedclauses, false);
158  }
159 
160  /*
161  * Apply normal selectivity estimates for remaining clauses. We'll be
162  * careful to skip any clauses which were already estimated above.
163  *
164  * Anything that doesn't look like a potential rangequery clause gets
165  * multiplied into s1 and forgotten. Anything that does gets inserted into
166  * an rqlist entry.
167  */
168  listidx = -1;
169  foreach(l, clauses)
170  {
171  Node *clause = (Node *) lfirst(l);
172  RestrictInfo *rinfo;
173  Selectivity s2;
174 
175  listidx++;
176 
177  /*
178  * Skip this clause if it's already been estimated by some other
179  * statistics above.
180  */
181  if (bms_is_member(listidx, estimatedclauses))
182  continue;
183 
184  /* Compute the selectivity of this clause in isolation */
185  s2 = clause_selectivity_ext(root, clause, varRelid, jointype, sjinfo,
186  use_extended_stats);
187 
188  /*
189  * Check for being passed a RestrictInfo.
190  *
191  * If it's a pseudoconstant RestrictInfo, then s2 is either 1.0 or
192  * 0.0; just use that rather than looking for range pairs.
193  */
194  if (IsA(clause, RestrictInfo))
195  {
196  rinfo = (RestrictInfo *) clause;
197  if (rinfo->pseudoconstant)
198  {
199  s1 = s1 * s2;
200  continue;
201  }
202  clause = (Node *) rinfo->clause;
203  }
204  else
205  rinfo = NULL;
206 
207  /*
208  * See if it looks like a restriction clause with a pseudoconstant on
209  * one side. (Anything more complicated than that might not behave in
210  * the simple way we are expecting.) Most of the tests here can be
211  * done more efficiently with rinfo than without.
212  */
213  if (is_opclause(clause) && list_length(((OpExpr *) clause)->args) == 2)
214  {
215  OpExpr *expr = (OpExpr *) clause;
216  bool varonleft = true;
217  bool ok;
218 
219  if (rinfo)
220  {
221  ok = (bms_membership(rinfo->clause_relids) == BMS_SINGLETON) &&
223  rinfo->right_relids) ||
224  (varonleft = false,
226  rinfo->left_relids)));
227  }
228  else
229  {
230  ok = (NumRelids(root, clause) == 1) &&
232  (varonleft = false,
234  }
235 
236  if (ok)
237  {
238  /*
239  * If it's not a "<"/"<="/">"/">=" operator, just merge the
240  * selectivity in generically. But if it's the right oprrest,
241  * add the clause to rqlist for later processing.
242  */
243  switch (get_oprrest(expr->opno))
244  {
245  case F_SCALARLTSEL:
246  case F_SCALARLESEL:
247  addRangeClause(&rqlist, clause,
248  varonleft, true, s2);
249  break;
250  case F_SCALARGTSEL:
251  case F_SCALARGESEL:
252  addRangeClause(&rqlist, clause,
253  varonleft, false, s2);
254  break;
255  default:
256  /* Just merge the selectivity in generically */
257  s1 = s1 * s2;
258  break;
259  }
260  continue; /* drop to loop bottom */
261  }
262  }
263 
264  /* Not the right form, so treat it generically. */
265  s1 = s1 * s2;
266  }
267 
268  /*
269  * Now scan the rangequery pair list.
270  */
271  while (rqlist != NULL)
272  {
273  RangeQueryClause *rqnext;
274 
275  if (rqlist->have_lobound && rqlist->have_hibound)
276  {
277  /* Successfully matched a pair of range clauses */
278  Selectivity s2;
279 
280  /*
281  * Exact equality to the default value probably means the
282  * selectivity function punted. This is not airtight but should
283  * be good enough.
284  */
285  if (rqlist->hibound == DEFAULT_INEQ_SEL ||
286  rqlist->lobound == DEFAULT_INEQ_SEL)
287  {
289  }
290  else
291  {
292  s2 = rqlist->hibound + rqlist->lobound - 1.0;
293 
294  /* Adjust for double-exclusion of NULLs */
295  s2 += nulltestsel(root, IS_NULL, rqlist->var,
296  varRelid, jointype, sjinfo);
297 
298  /*
299  * A zero or slightly negative s2 should be converted into a
300  * small positive value; we probably are dealing with a very
301  * tight range and got a bogus result due to roundoff errors.
302  * However, if s2 is very negative, then we probably have
303  * default selectivity estimates on one or both sides of the
304  * range that we failed to recognize above for some reason.
305  */
306  if (s2 <= 0.0)
307  {
308  if (s2 < -0.01)
309  {
310  /*
311  * No data available --- use a default estimate that
312  * is small, but not real small.
313  */
315  }
316  else
317  {
318  /*
319  * It's just roundoff error; use a small positive
320  * value
321  */
322  s2 = 1.0e-10;
323  }
324  }
325  }
326  /* Merge in the selectivity of the pair of clauses */
327  s1 *= s2;
328  }
329  else
330  {
331  /* Only found one of a pair, merge it in generically */
332  if (rqlist->have_lobound)
333  s1 *= rqlist->lobound;
334  else
335  s1 *= rqlist->hibound;
336  }
337  /* release storage and advance */
338  rqnext = rqlist->next;
339  pfree(rqlist);
340  rqlist = rqnext;
341  }
342 
343  return s1;
344 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:584
List * statlist
Definition: pathnodes.h:708
bool is_pseudo_constant_clause_relids(Node *clause, Relids relids)
Definition: clauses.c:1878
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Relids clause_relids
Definition: pathnodes.h:2021
bool pseudoconstant
Definition: pathnodes.h:2014
Definition: nodes.h:533
Relids left_relids
Definition: pathnodes.h:2033
double Selectivity
Definition: nodes.h:666
Selectivity statext_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
#define lsecond(l)
Definition: pg_list.h:179
void pfree(void *pointer)
Definition: mcxt.c:1057
#define linitial(l)
Definition: pg_list.h:174
char * s1
Selectivity nulltestsel(PlannerInfo *root, NullTestType nulltesttype, Node *arg, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:1695
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:1858
struct RangeQueryClause * next
Definition: clausesel.c:35
static void addRangeClause(RangeQueryClause **rqlist, Node *clause, bool varonleft, bool isLTsel, Selectivity s2)
Definition: clausesel.c:429
Selectivity hibound
Definition: clausesel.c:40
Expr * clause
Definition: pathnodes.h:2006
int NumRelids(PlannerInfo *root, Node *clause)
Definition: clauses.c:1900
Selectivity lobound
Definition: clausesel.c:39
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1528
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:672
char * s2
RTEKind rtekind
Definition: pathnodes.h:700
static RelOptInfo * find_single_rel_for_clauses(PlannerInfo *root, List *clauses)
Definition: clausesel.c:525
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:707
Relids right_relids
Definition: pathnodes.h:2034
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define DEFAULT_RANGE_INEQ_SEL
Definition: selfuncs.h:40
Oid opno
Definition: primnodes.h:537
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
List * args
Definition: primnodes.h:543
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427

◆ contain_mutable_functions()

◆ contain_var_clause()

bool contain_var_clause ( Node node)

◆ contain_vars_of_level()

bool contain_vars_of_level ( Node node,
int  levelsup 
)

Definition at line 396 of file var.c.

References contain_vars_of_level_walker(), and query_or_expression_tree_walker().

Referenced by apply_child_basequals(), checkExprIsVarFree(), convert_ANY_sublink_to_join(), convert_EXISTS_sublink_to_join(), convert_EXISTS_to_ANY(), pull_up_simple_values(), pullup_replace_vars_callback(), transformAExprIn(), transformInsertStmt(), transformRangeFunction(), transformRangeTableFunc(), transformSetOperationTree(), and transformValuesClause().

397 {
398  int sublevels_up = levelsup;
399 
402  (void *) &sublevels_up,
403  0);
404 }
bool query_or_expression_tree_walker(Node *node, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:3442
static bool contain_vars_of_level_walker(Node *node, int *sublevels_up)
Definition: var.c:407

◆ contain_volatile_functions()

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 487 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

488 {
490 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:500

◆ count_nonjunk_tlist_entries()

int count_nonjunk_tlist_entries ( List tlist)

Definition at line 203 of file tlist.c.

References lfirst, and TargetEntry::resjunk.

Referenced by get_update_query_targetlist_def(), transformMultiAssignRef(), and transformSubLink().

204 {
205  int len = 0;
206  ListCell *l;
207 
208  foreach(l, tlist)
209  {
210  TargetEntry *tle = (TargetEntry *) lfirst(l);
211 
212  if (!tle->resjunk)
213  len++;
214  }
215  return len;
216 }
bool resjunk
Definition: primnodes.h:1438
#define lfirst(lc)
Definition: pg_list.h:169

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2055 of file clauses.c.

References eval_const_expressions_context::active_fns, eval_const_expressions_context::boundParams, PlannerGlobal::boundParams, eval_const_expressions_context::case_val, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), PlannerInfo::glob, NIL, and eval_const_expressions_context::root.

Referenced by array_unnest_support(), bernoulli_samplescangetsamplesize(), clause_selectivity_ext(), generate_series_int4_support(), generate_series_int8_support(), get_restriction_variable(), gincost_opexpr(), gincost_scalararrayopexpr(), preprocess_limit(), scalararraysel(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

2056 {
2058 
2059  context.boundParams = root->glob->boundParams; /* bound Params */
2060  /* we do not need to mark the plan as depending on inlined functions */
2061  context.root = NULL;
2062  context.active_fns = NIL; /* nothing being recursively simplified */
2063  context.case_val = NULL; /* no CASE being examined */
2064  context.estimate = true; /* unsafe transformations OK */
2065  return eval_const_expressions_mutator(node, &context);
2066 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2100
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:175
ParamListInfo boundParams
Definition: pathnodes.h:105

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2022 of file clauses.c.

References eval_const_expressions_context::active_fns, eval_const_expressions_context::boundParams, PlannerGlobal::boundParams, eval_const_expressions_context::case_val, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), PlannerInfo::glob, NIL, and eval_const_expressions_context::root.

Referenced by apply_child_basequals(), ATExecAttachPartition(), ConstraintImpliedByRelConstraint(), convert_EXISTS_to_ANY(), DoCopy(), expression_planner(), expression_planner_with_deps(), get_proposed_default_constraint(), get_relation_constraints(), preprocess_expression(), preprocess_function_rtes(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), and simplify_EXISTS_query().

2023 {
2025 
2026  if (root)
2027  context.boundParams = root->glob->boundParams; /* bound Params */
2028  else
2029  context.boundParams = NULL;
2030  context.root = root; /* for inlined-function dependencies */
2031  context.active_fns = NIL; /* nothing being recursively simplified */
2032  context.case_val = NULL; /* no CASE being examined */
2033  context.estimate = false; /* safe transformations only */
2034  return eval_const_expressions_mutator(node, &context);
2035 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2100
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:175
ParamListInfo boundParams
Definition: pathnodes.h:105

◆ evaluate_expr()

Expr* evaluate_expr ( Expr expr,
Oid  result_type,
int32  result_typmod,
Oid  result_collation 
)

Definition at line 4497 of file clauses.c.

References CreateExecutorState(), datumCopy(), EState::es_query_cxt, ExecEvalExprSwitchContext(), ExecInitExpr(), fix_opfuncids(), FreeExecutorState(), get_typlenbyval(), GetPerTupleExprContext, makeConst(), MemoryContextSwitchTo(), PG_DETOAST_DATUM_COPY, and PointerGetDatum.

Referenced by eval_const_expressions_mutator(), evaluate_function(), and transformPartitionBoundValue().

4499 {
4500  EState *estate;
4501  ExprState *exprstate;
4502  MemoryContext oldcontext;
4503  Datum const_val;
4504  bool const_is_null;
4505  int16 resultTypLen;
4506  bool resultTypByVal;
4507 
4508  /*
4509  * To use the executor, we need an EState.
4510  */
4511  estate = CreateExecutorState();
4512 
4513  /* We can use the estate's working context to avoid memory leaks. */
4514  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4515 
4516  /* Make sure any opfuncids are filled in. */
4517  fix_opfuncids((Node *) expr);
4518 
4519  /*
4520  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4521  * because it'd result in recursively invoking eval_const_expressions.)
4522  */
4523  exprstate = ExecInitExpr(expr, NULL);
4524 
4525  /*
4526  * And evaluate it.
4527  *
4528  * It is OK to use a default econtext because none of the ExecEvalExpr()
4529  * code used in this situation will use econtext. That might seem
4530  * fortuitous, but it's not so unreasonable --- a constant expression does
4531  * not depend on context, by definition, n'est ce pas?
4532  */
4533  const_val = ExecEvalExprSwitchContext(exprstate,
4534  GetPerTupleExprContext(estate),
4535  &const_is_null);
4536 
4537  /* Get info needed about result datatype */
4538  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4539 
4540  /* Get back to outer memory context */
4541  MemoryContextSwitchTo(oldcontext);
4542 
4543  /*
4544  * Must copy result out of sub-context used by expression eval.
4545  *
4546  * Also, if it's varlena, forcibly detoast it. This protects us against
4547  * storing TOAST pointers into plans that might outlive the referenced
4548  * data. (makeConst would handle detoasting anyway, but it's worth a few
4549  * extra lines here so that we can do the copy and detoast in one step.)
4550  */
4551  if (!const_is_null)
4552  {
4553  if (resultTypLen == -1)
4554  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4555  else
4556  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4557  }
4558 
4559  /* Release all the junk we just created */
4560  FreeExecutorState(estate);
4561 
4562  /*
4563  * Make the constant result node.
4564  */
4565  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4566  resultTypLen,
4567  const_val, const_is_null,
4568  resultTypByVal);
4569 }
signed short int16
Definition: c.h:428
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:307
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
#define PointerGetDatum(X)
Definition: postgres.h:556
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1633
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:533
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:299
void FreeExecutorState(EState *estate)
Definition: execUtils.c:186
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
MemoryContext es_query_cxt
Definition: execnodes.h:572
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
EState * CreateExecutorState(void)
Definition: execUtils.c:90
uintptr_t Datum
Definition: postgres.h:367
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2198
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:123

◆ expand_function_arguments()

List* expand_function_arguments ( List args,
Oid  result_type,
struct HeapTupleData func_tuple 
)

◆ expression_planner()

Expr* expression_planner ( Expr expr)

Definition at line 6165 of file planner.c.

References eval_const_expressions(), and fix_opfuncids().

Referenced by ATExecAddColumn(), ATPrepAlterColumnType(), BeginCopyFrom(), CheckMutability(), ComputePartitionAttrs(), ExecPrepareCheck(), ExecPrepareExpr(), ExecPrepareQual(), load_domaintype_info(), set_baserel_partition_constraint(), slot_fill_defaults(), StoreAttrDefault(), and transformPartitionBoundValue().

6166 {
6167  Node *result;
6168 
6169  /*
6170  * Convert named-argument function calls, insert default arguments and
6171  * simplify constant subexprs
6172  */
6173  result = eval_const_expressions(NULL, (Node *) expr);
6174 
6175  /* Fill in opfuncid values if missing */
6176  fix_opfuncids(result);
6177 
6178  return (Expr *) result;
6179 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1633
Definition: nodes.h:533
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2022

◆ expression_planner_with_deps()

Expr* expression_planner_with_deps ( Expr expr,
List **  relationOids,
List **  invalItems 
)

Definition at line 6192 of file planner.c.

References eval_const_expressions(), extract_query_dependencies_walker(), fix_opfuncids(), PlannerInfo::glob, PlannerGlobal::invalItems, MemSet, NIL, PlannerGlobal::relationOids, T_PlannerGlobal, T_PlannerInfo, PlannerGlobal::type, and PlannerInfo::type.

Referenced by GetCachedExpression().

6195 {
6196  Node *result;
6197  PlannerGlobal glob;
6198  PlannerInfo root;
6199 
6200  /* Make up dummy planner state so we can use setrefs machinery */
6201  MemSet(&glob, 0, sizeof(glob));
6202  glob.type = T_PlannerGlobal;
6203  glob.relationOids = NIL;
6204  glob.invalItems = NIL;
6205 
6206  MemSet(&root, 0, sizeof(root));
6207  root.type = T_PlannerInfo;
6208  root.glob = &glob;
6209 
6210  /*
6211  * Convert named-argument function calls, insert default arguments and
6212  * simplify constant subexprs. Collect identities of inlined functions
6213  * and elided domains, too.
6214  */
6215  result = eval_const_expressions(&root, (Node *) expr);
6216 
6217  /* Fill in opfuncid values if missing */
6218  fix_opfuncids(result);
6219 
6220  /*
6221  * Now walk the finished expression to find anything else we ought to
6222  * record as an expression dependency.
6223  */
6224  (void) extract_query_dependencies_walker(result, &root);
6225 
6226  *relationOids = glob.relationOids;
6227  *invalItems = glob.invalItems;
6228 
6229  return (Expr *) result;
6230 }
#define NIL
Definition: pg_list.h:65
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1633
Definition: nodes.h:533
#define MemSet(start, val, len)
Definition: c.h:1008
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2022
PlannerGlobal * glob
Definition: pathnodes.h:175
List * invalItems
Definition: pathnodes.h:123
NodeTag type
Definition: pathnodes.h:171
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3022
NodeTag type
Definition: pathnodes.h:103
List * relationOids
Definition: pathnodes.h:121

◆ extract_query_dependencies()

void extract_query_dependencies ( Node query,
List **  relationOids,
List **  invalItems,
bool hasRowSecurity 
)

Definition at line 2986 of file setrefs.c.

References PlannerGlobal::dependsOnRole, extract_query_dependencies_walker(), PlannerInfo::glob, PlannerGlobal::invalItems, MemSet, NIL, PlannerGlobal::relationOids, T_PlannerGlobal, T_PlannerInfo, PlannerGlobal::type, and PlannerInfo::type.

Referenced by CompleteCachedPlan(), and RevalidateCachedQuery().

2990 {
2991  PlannerGlobal glob;
2992  PlannerInfo root;
2993 
2994  /* Make up dummy planner state so we can use this module's machinery */
2995  MemSet(&glob, 0, sizeof(glob));
2996  glob.type = T_PlannerGlobal;
2997  glob.relationOids = NIL;
2998  glob.invalItems = NIL;
2999  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3000  glob.dependsOnRole = false;
3001 
3002  MemSet(&root, 0, sizeof(root));
3003  root.type = T_PlannerInfo;
3004  root.glob = &glob;
3005 
3006  (void) extract_query_dependencies_walker(query, &root);
3007 
3008  *relationOids = glob.relationOids;
3009  *invalItems = glob.invalItems;
3010  *hasRowSecurity = glob.dependsOnRole;
3011 }
#define NIL
Definition: pg_list.h:65
#define MemSet(start, val, len)
Definition: c.h:1008
bool dependsOnRole
Definition: pathnodes.h:135
PlannerGlobal * glob
Definition: pathnodes.h:175
List * invalItems
Definition: pathnodes.h:123
NodeTag type
Definition: pathnodes.h:171
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3022
NodeTag type
Definition: pathnodes.h:103
List * relationOids
Definition: pathnodes.h:121

◆ flatten_join_alias_vars()

Node* flatten_join_alias_vars ( Query query,
Node node 
)

Definition at line 697 of file var.c.

References flatten_join_alias_vars_mutator(), Query::hasSubLinks, flatten_join_alias_vars_context::inserted_sublink, flatten_join_alias_vars_context::possible_sublink, flatten_join_alias_vars_context::query, and flatten_join_alias_vars_context::sublevels_up.

Referenced by finalize_grouping_exprs_walker(), parseCheckAggregates(), preprocess_expression(), pull_up_simple_subquery(), and subquery_planner().

698 {
700 
701  context.query = query;
702  context.sublevels_up = 0;
703  /* flag whether join aliases could possibly contain SubLinks */
704  context.possible_sublink = query->hasSubLinks;
705  /* if hasSubLinks is already true, no need to work hard */
706  context.inserted_sublink = query->hasSubLinks;
707 
708  return flatten_join_alias_vars_mutator(node, &context);
709 }
bool hasSubLinks
Definition: parsenodes.h:128
static Node * flatten_join_alias_vars_mutator(Node *node, flatten_join_alias_vars_context *context)
Definition: var.c:712

◆ get_sortgroupclause_expr()

Node* get_sortgroupclause_expr ( SortGroupClause sgClause,
List targetList 
)

Definition at line 396 of file tlist.c.

References TargetEntry::expr, and get_sortgroupclause_tle().

Referenced by get_sortgrouplist_exprs(), make_pathkeys_for_sortclauses(), transformAggregateCall(), and transformWindowDefinitions().

397 {
398  TargetEntry *tle = get_sortgroupclause_tle(sgClause, targetList);
399 
400  return (Node *) tle->expr;
401 }
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:384
Definition: nodes.h:533
Expr * expr
Definition: primnodes.h:1431

◆ get_sortgroupclause_tle()

◆ get_sortgrouplist_exprs()

List* get_sortgrouplist_exprs ( List sgClauses,
List targetList 
)

Definition at line 409 of file tlist.c.

References get_sortgroupclause_expr(), lappend(), lfirst, and NIL.

Referenced by create_distinct_paths(), estimate_path_cost_size(), get_number_of_groups(), and group_by_has_partkey().

410 {
411  List *result = NIL;
412  ListCell *l;
413 
414  foreach(l, sgClauses)
415  {
416  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
417  Node *sortexpr;
418 
419  sortexpr = get_sortgroupclause_expr(sortcl, targetList);
420  result = lappend(result, sortexpr);
421  }
422  return result;
423 }
#define NIL
Definition: pg_list.h:65
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:396
Definition: nodes.h:533
List * lappend(List *list, void *datum)
Definition: list.c:336
#define lfirst(lc)
Definition: pg_list.h:169
Definition: pg_list.h:50

◆ get_sortgroupref_clause()

SortGroupClause* get_sortgroupref_clause ( Index  sortref,
List clauses 
)

Definition at line 439 of file tlist.c.

References elog, ERROR, lfirst, and SortGroupClause::tleSortGroupRef.

Referenced by preprocess_groupclause().

440 {
441  ListCell *l;
442 
443  foreach(l, clauses)
444  {
446 
447  if (cl->tleSortGroupRef == sortref)
448  return cl;
449  }
450 
451  elog(ERROR, "ORDER/GROUP BY expression not found in list");
452  return NULL; /* keep compiler quiet */
453 }
Index tleSortGroupRef
Definition: parsenodes.h:1262
#define ERROR
Definition: elog.h:45
#define lfirst(lc)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:227

◆ get_sortgroupref_clause_noerr()

SortGroupClause* get_sortgroupref_clause_noerr ( Index  sortref,
List clauses 
)

Definition at line 460 of file tlist.c.

References lfirst, and SortGroupClause::tleSortGroupRef.

Referenced by find_em_expr_for_input_target(), foreign_grouping_ok(), make_group_input_target(), and make_partial_grouping_target().

461 {
462  ListCell *l;
463 
464  foreach(l, clauses)
465  {
467 
468  if (cl->tleSortGroupRef == sortref)
469  return cl;
470  }
471 
472  return NULL;
473 }
Index tleSortGroupRef
Definition: parsenodes.h:1262
#define lfirst(lc)
Definition: pg_list.h:169

◆ get_sortgroupref_tle()

TargetEntry* get_sortgroupref_tle ( Index  sortref,
List targetList 
)

Definition at line 362 of file tlist.c.

References elog, ERROR, lfirst, and TargetEntry::ressortgroupref.

Referenced by convert_subquery_pathkeys(), deparseSortGroupClause(), foreign_expr_walker(), get_rule_sortgroupclause(), get_sortgroupclause_tle(), make_unique_from_pathkeys(), prepare_sort_from_pathkeys(), and transformDistinctOnClause().

363 {
364  ListCell *l;
365 
366  foreach(l, targetList)
367  {
368  TargetEntry *tle = (TargetEntry *) lfirst(l);
369 
370  if (tle->ressortgroupref == sortref)
371  return tle;
372  }
373 
374  elog(ERROR, "ORDER/GROUP BY expression not found in targetlist");
375  return NULL; /* keep compiler quiet */
376 }
#define ERROR
Definition: elog.h:45
#define lfirst(lc)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:227
Index ressortgroupref
Definition: primnodes.h:1434

◆ is_pseudo_constant_for_index()

bool is_pseudo_constant_for_index ( PlannerInfo root,
Node expr,
IndexOptInfo index 
)

Definition at line 3817 of file indxpath.c.

References bms_is_member(), contain_volatile_functions(), pull_varnos(), IndexOptInfo::rel, and RelOptInfo::relid.

3818 {
3819  /* pull_varnos is cheaper than volatility check, so do that first */
3820  if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
3821  return false; /* no good, contains Var of table */
3822  if (contain_volatile_functions(expr))
3823  return false; /* no good, volatile comparison value */
3824  return true;
3825 }
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:97
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:437
RelOptInfo * rel
Definition: pathnodes.h:826
Index relid
Definition: pathnodes.h:698
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427

◆ locate_var_of_level()

int locate_var_of_level ( Node node,
int  levelsup 
)

Definition at line 464 of file var.c.

References locate_var_of_level_walker(), query_or_expression_tree_walker(), locate_var_of_level_context::sublevels_up, and locate_var_of_level_context::var_location.

Referenced by check_agg_arguments(), checkExprIsVarFree(), and transformSetOperationTree().

465 {
467 
468  context.var_location = -1; /* in case we find nothing */
469  context.sublevels_up = levelsup;
470 
473  (void *) &context,
474  0);
475 
476  return context.var_location;
477 }
bool query_or_expression_tree_walker(Node *node, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:3442
static bool locate_var_of_level_walker(Node *node, locate_var_of_level_context *context)
Definition: var.c:480

◆ negate_clause()

Node* negate_clause ( Node node)

Definition at line 74 of file prepqual.c.

References AND_EXPR, NullTest::arg, BooleanTest::arg, NullTest::argisrow, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, BoolExpr::boolop, BooleanTest::booltesttype, Const::constisnull, Const::constvalue, DatumGetBool, elog, ERROR, get_negator(), OpExpr::inputcollid, ScalarArrayOpExpr::inputcollid, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, lappend(), lfirst, linitial, OpExpr::location, ScalarArrayOpExpr::location, NullTest::location, BooleanTest::location, make_andclause(), make_notclause(), make_orclause(), makeBoolConst(), makeNode, negate_clause(), NIL, nodeTag, NOT_EXPR, NullTest::nulltesttype, OpExpr::opcollid, OpExpr::opfuncid, ScalarArrayOpExpr::opfuncid, OpExpr::opno, ScalarArrayOpExpr::opno, OpExpr::opresulttype, OpExpr::opretset, OR_EXPR, T_BooleanTest, T_BoolExpr, T_Const, T_NullTest, T_OpExpr, T_ScalarArrayOpExpr, and ScalarArrayOpExpr::useOr.

Referenced by eval_const_expressions_mutator(), match_boolean_partition_clause(), negate_clause(), and simplify_boolean_equality().

75 {
76  if (node == NULL) /* should not happen */
77  elog(ERROR, "can't negate an empty subexpression");
78  switch (nodeTag(node))
79  {
80  case T_Const:
81  {
82  Const *c = (Const *) node;
83 
84  /* NOT NULL is still NULL */
85  if (c->constisnull)
86  return makeBoolConst(false, true);
87  /* otherwise pretty easy */
88  return makeBoolConst(!DatumGetBool(c->constvalue), false);
89  }
90  break;
91  case T_OpExpr:
92  {
93  /*
94  * Negate operator if possible: (NOT (< A B)) => (>= A B)
95  */
96  OpExpr *opexpr = (OpExpr *) node;
97  Oid negator = get_negator(opexpr->opno);
98 
99  if (negator)
100  {
101  OpExpr *newopexpr = makeNode(OpExpr);
102 
103  newopexpr->opno = negator;
104  newopexpr->opfuncid = InvalidOid;
105  newopexpr->opresulttype = opexpr->opresulttype;
106  newopexpr->opretset = opexpr->opretset;
107  newopexpr->opcollid = opexpr->opcollid;
108  newopexpr->inputcollid = opexpr->inputcollid;
109  newopexpr->args = opexpr->args;
110  newopexpr->location = opexpr->location;
111  return (Node *) newopexpr;
112  }
113  }
114  break;
115  case T_ScalarArrayOpExpr:
116  {
117  /*
118  * Negate a ScalarArrayOpExpr if its operator has a negator;
119  * for example x = ANY (list) becomes x <> ALL (list)
120  */
121  ScalarArrayOpExpr *saopexpr = (ScalarArrayOpExpr *) node;
122  Oid negator = get_negator(saopexpr->opno);
123 
124  if (negator)
125  {
127 
128  newopexpr->opno = negator;
129  newopexpr->opfuncid = InvalidOid;
130  newopexpr->useOr = !saopexpr->useOr;
131  newopexpr->inputcollid = saopexpr->inputcollid;
132  newopexpr->args = saopexpr->args;
133  newopexpr->location = saopexpr->location;
134  return (Node *) newopexpr;
135  }
136  }
137  break;
138  case T_BoolExpr:
139  {
140  BoolExpr *expr = (BoolExpr *) node;
141 
142  switch (expr->boolop)
143  {
144  /*--------------------
145  * Apply DeMorgan's Laws:
146  * (NOT (AND A B)) => (OR (NOT A) (NOT B))
147  * (NOT (OR A B)) => (AND (NOT A) (NOT B))
148  * i.e., swap AND for OR and negate each subclause.
149  *
150  * If the input is already AND/OR flat and has no NOT
151  * directly above AND or OR, this transformation preserves
152  * those properties. For example, if no direct child of
153  * the given AND clause is an AND or a NOT-above-OR, then
154  * the recursive calls of negate_clause() can't return any
155  * OR clauses. So we needn't call pull_ors() before
156  * building a new OR clause. Similarly for the OR case.
157  *--------------------
158  */
159  case AND_EXPR:
160  {
161  List *nargs = NIL;
162  ListCell *lc;
163 
164  foreach(lc, expr->args)
165  {
166  nargs = lappend(nargs,
167  negate_clause(lfirst(lc)));
168  }
169  return (Node *) make_orclause(nargs);
170  }
171  break;
172  case OR_EXPR:
173  {
174  List *nargs = NIL;
175  ListCell *lc;
176 
177  foreach(lc, expr->args)
178  {
179  nargs = lappend(nargs,
180  negate_clause(lfirst(lc)));
181  }
182  return (Node *) make_andclause(nargs);
183  }
184  break;
185  case NOT_EXPR:
186 
187  /*
188  * NOT underneath NOT: they cancel. We assume the
189  * input is already simplified, so no need to recurse.
190  */
191  return (Node *) linitial(expr->args);
192  default:
193  elog(ERROR, "unrecognized boolop: %d",
194  (int) expr->boolop);
195  break;
196  }
197  }
198  break;
199  case T_NullTest:
200  {
201  NullTest *expr = (NullTest *) node;
202 
203  /*
204  * In the rowtype case, the two flavors of NullTest are *not*
205  * logical inverses, so we can't simplify. But it does work
206  * for scalar datatypes.
207  */
208  if (!expr->argisrow)
209  {
210  NullTest *newexpr = makeNode(NullTest);
211 
212  newexpr->arg = expr->arg;
213  newexpr->nulltesttype = (expr->nulltesttype == IS_NULL ?
214  IS_NOT_NULL : IS_NULL);
215  newexpr->argisrow = expr->argisrow;
216  newexpr->location = expr->location;
217  return (Node *) newexpr;
218  }
219  }
220  break;
221  case T_BooleanTest:
222  {
223  BooleanTest *expr = (BooleanTest *) node;
224  BooleanTest *newexpr = makeNode(BooleanTest);
225 
226  newexpr->arg = expr->arg;
227  switch (expr->booltesttype)
228  {
229  case IS_TRUE:
230  newexpr->booltesttype = IS_NOT_TRUE;
231  break;
232  case IS_NOT_TRUE:
233  newexpr->booltesttype = IS_TRUE;
234  break;
235  case IS_FALSE:
236  newexpr->booltesttype = IS_NOT_FALSE;
237  break;
238  case IS_NOT_FALSE:
239  newexpr->booltesttype = IS_FALSE;
240  break;
241  case IS_UNKNOWN:
242  newexpr->booltesttype = IS_NOT_UNKNOWN;
243  break;
244  case IS_NOT_UNKNOWN:
245  newexpr->booltesttype = IS_UNKNOWN;
246  break;
247  default:
248  elog(ERROR, "unrecognized booltesttype: %d",
249  (int) expr->booltesttype);
250  break;
251  }
252  newexpr->location = expr->location;
253  return (Node *) newexpr;
254  }
255  break;
256  default:
257  /* else fall through */
258  break;
259  }
260 
261  /*
262  * Otherwise we don't know how to simplify this, so just tack on an
263  * explicit NOT node.
264  */
265  return (Node *) make_notclause((Expr *) node);
266 }
Datum constvalue
Definition: primnodes.h:214
#define NIL
Definition: pg_list.h:65
Expr * make_notclause(Expr *notclause)
Definition: makefuncs.c:668
Node * negate_clause(Node *node)
Definition: prepqual.c:74
Definition: nodes.h:533
unsigned int Oid
Definition: postgres_ext.h:31
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:652
Oid opresulttype
Definition: primnodes.h:539
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:45
BoolExprType boolop
Definition: primnodes.h:603
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:357
Expr * arg
Definition: primnodes.h:1243
char * c
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:636
int location
Definition: primnodes.h:544
Expr * arg
Definition: primnodes.h:1266
#define DatumGetBool(X)
Definition: postgres.h:393
Oid opcollid
Definition: primnodes.h:541
Definition: nodes.h:156
List * lappend(List *list, void *datum)
Definition: list.c:336
BoolTestType booltesttype
Definition: primnodes.h:1267
Oid opfuncid
Definition: primnodes.h:538
NullTestType nulltesttype
Definition: primnodes.h:1244
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:581
#define lfirst(lc)
Definition: pg_list.h:169
int location
Definition: primnodes.h:1246
Oid inputcollid
Definition: primnodes.h:542
List * args
Definition: primnodes.h:604
#define nodeTag(nodeptr)
Definition: nodes.h:538
#define elog(elevel,...)
Definition: elog.h:227
bool argisrow
Definition: primnodes.h:1245
Oid opno
Definition: primnodes.h:537
Oid get_negator(Oid opno)
Definition: lsyscache.c:1504
List * args
Definition: primnodes.h:543
Definition: pg_list.h:50
bool constisnull
Definition: primnodes.h:215
bool opretset
Definition: primnodes.h:540

◆ plan_cluster_use_sort()

bool plan_cluster_use_sort ( Oid  tableOid,
Oid  indexOid 
)

Definition at line 6245 of file planner.c.

References AccessShareLock, build_simple_rel(), CMD_SELECT, Query::commandType, cost_qual_eval(), cost_sort(), create_index_path(), create_seqscan_path(), CurrentMemoryContext, enable_indexscan, ForwardScanDirection, get_relation_data_width(), PlannerInfo::glob, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, RangeTblEntry::inFromCl, RangeTblEntry::inh, RangeTblEntry::lateral, lfirst_node, list_make1, maintenance_work_mem, makeNode, NIL, RelOptInfo::pages, PlannerInfo::parse, IndexPath::path, QualCost::per_tuple, PlannerInfo::planner_cxt, PlannerInfo::query_level, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::rellockmode, RelOptInfo::reltarget, RelOptInfo::rows, Query::rtable, RTE_RELATION, RangeTblEntry::rtekind, setup_simple_rel_arrays(), QualCost::startup, Path::total_cost, PlannerInfo::total_table_pages, RelOptInfo::tuples, PathTarget::width, and PlannerInfo::wt_param_id.

Referenced by copy_table_data().

6246 {
6247  PlannerInfo *root;
6248  Query *query;
6249  PlannerGlobal *glob;
6250  RangeTblEntry *rte;
6251  RelOptInfo *rel;
6252  IndexOptInfo *indexInfo;
6253  QualCost indexExprCost;
6254  Cost comparisonCost;
6255  Path *seqScanPath;
6256  Path seqScanAndSortPath;
6257  IndexPath *indexScanPath;
6258  ListCell *lc;
6259 
6260  /* We can short-circuit the cost comparison if indexscans are disabled */
6261  if (!enable_indexscan)
6262  return true; /* use sort */
6263 
6264  /* Set up mostly-dummy planner state */
6265  query = makeNode(Query);
6266  query->commandType = CMD_SELECT;
6267 
6268  glob = makeNode(PlannerGlobal);
6269 
6270  root = makeNode(PlannerInfo);
6271  root->parse = query;
6272  root->glob = glob;
6273  root->query_level = 1;
6275  root->wt_param_id = -1;
6276 
6277  /* Build a minimal RTE for the rel */
6278  rte = makeNode(RangeTblEntry);
6279  rte->rtekind = RTE_RELATION;
6280  rte->relid = tableOid;
6281  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6283  rte->lateral = false;
6284  rte->inh = false;
6285  rte->inFromCl = true;
6286  query->rtable = list_make1(rte);
6287 
6288  /* Set up RTE/RelOptInfo arrays */
6290 
6291  /* Build RelOptInfo */
6292  rel = build_simple_rel(root, 1, NULL);
6293 
6294  /* Locate IndexOptInfo for the target index */
6295  indexInfo = NULL;
6296  foreach(lc, rel->indexlist)
6297  {
6298  indexInfo = lfirst_node(IndexOptInfo, lc);
6299  if (indexInfo->indexoid == indexOid)
6300  break;
6301  }
6302 
6303  /*
6304  * It's possible that get_relation_info did not generate an IndexOptInfo
6305  * for the desired index; this could happen if it's not yet reached its
6306  * indcheckxmin usability horizon, or if it's a system index and we're
6307  * ignoring system indexes. In such cases we should tell CLUSTER to not
6308  * trust the index contents but use seqscan-and-sort.
6309  */
6310  if (lc == NULL) /* not in the list? */
6311  return true; /* use sort */
6312 
6313  /*
6314  * Rather than doing all the pushups that would be needed to use
6315  * set_baserel_size_estimates, just do a quick hack for rows and width.
6316  */
6317  rel->rows = rel->tuples;
6318  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6319 
6320  root->total_table_pages = rel->pages;
6321 
6322  /*
6323  * Determine eval cost of the index expressions, if any. We need to
6324  * charge twice that amount for each tuple comparison that happens during
6325  * the sort, since tuplesort.c will have to re-evaluate the index
6326  * expressions each time. (XXX that's pretty inefficient...)
6327  */
6328  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6329  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6330 
6331  /* Estimate the cost of seq scan + sort */
6332  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6333  cost_sort(&seqScanAndSortPath, root, NIL,
6334  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6335  comparisonCost, maintenance_work_mem, -1.0);
6336 
6337  /* Estimate the cost of index scan */
6338  indexScanPath = create_index_path(root, indexInfo,
6339  NIL, NIL, NIL, NIL,
6340  ForwardScanDirection, false,
6341  NULL, 1.0, false);
6342 
6343  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6344 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:173
Path path
Definition: pathnodes.h:1216
double tuples
Definition: pathnodes.h:710
#define AccessShareLock
Definition: lockdefs.h:36
Cost startup
Definition: pathnodes.h:45
#define list_make1(x1)
Definition: pg_list.h:206
Cost per_tuple
Definition: pathnodes.h:46
int wt_param_id
Definition: pathnodes.h:357
List * rtable
Definition: parsenodes.h:137
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4161
#define lfirst_node(type, lc)
Definition: pg_list.h:172
IndexPath * create_index_path(PlannerInfo *root, IndexOptInfo *index, List *indexclauses, List *indexorderbys, List *indexorderbycols, List *pathkeys, ScanDirection indexscandir, bool indexonly, Relids required_outer, double loop_count, bool partial_path)
Definition: pathnode.c:997
PlannerGlobal * glob
Definition: pathnodes.h:175
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:194
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
double total_table_pages
Definition: pathnodes.h:327
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1148
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:2032
List * indexlist
Definition: pathnodes.h:707
double rows
Definition: pathnodes.h:673
int maintenance_work_mem
Definition: globals.c:124
Cost total_cost
Definition: pathnodes.h:1166
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:581
BlockNumber pages
Definition: pathnodes.h:709
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:83
Index query_level
Definition: pathnodes.h:177
RTEKind rtekind
Definition: parsenodes.h:981
MemoryContext planner_cxt
Definition: pathnodes.h:325
struct PathTarget * reltarget
Definition: pathnodes.h:681
bool enable_indexscan
Definition: costsize.c:133
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:929
double Cost
Definition: nodes.h:667
List * indexprs
Definition: pathnodes.h:849

◆ plan_create_index_workers()

int plan_create_index_workers ( Oid  tableOid,
Oid  indexOid 
)

Definition at line 6363 of file planner.c.

References AccessShareLock, build_simple_rel(), CMD_SELECT, Query::commandType, compute_parallel_worker(), CurrentMemoryContext, estimate_rel_size(), PlannerInfo::glob, index_close(), index_open(), RangeTblEntry::inFromCl, RangeTblEntry::inh, is_parallel_safe(), IsUnderPostmaster, RangeTblEntry::lateral, list_make1, maintenance_work_mem, makeNode, max_parallel_maintenance_workers, Min, NoLock, PlannerInfo::parse, PlannerInfo::planner_cxt, PlannerInfo::query_level, RelationData::rd_rel, RelOptInfo::rel_parallel_workers, RelationGetIndexExpressions(), RelationGetIndexPredicate(), RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::rellockmode, Query::rtable, RTE_RELATION, RangeTblEntry::rtekind, setup_simple_rel_arrays(), table_close(), table_open(), and PlannerInfo::wt_param_id.

Referenced by index_build().

6364 {
6365  PlannerInfo *root;
6366  Query *query;
6367  PlannerGlobal *glob;
6368  RangeTblEntry *rte;
6369  Relation heap;
6370  Relation index;
6371  RelOptInfo *rel;
6372  int parallel_workers;
6373  BlockNumber heap_blocks;
6374  double reltuples;
6375  double allvisfrac;
6376 
6377  /*
6378  * We don't allow performing parallel operation in standalone backend or
6379  * when parallelism is disabled.
6380  */
6382  return 0;
6383 
6384  /* Set up largely-dummy planner state */
6385  query = makeNode(Query);
6386  query->commandType = CMD_SELECT;
6387 
6388  glob = makeNode(PlannerGlobal);
6389 
6390  root = makeNode(PlannerInfo);
6391  root->parse = query;
6392  root->glob = glob;
6393  root->query_level = 1;
6395  root->wt_param_id = -1;
6396 
6397  /*
6398  * Build a minimal RTE.
6399  *
6400  * Mark the RTE with inh = true. This is a kludge to prevent
6401  * get_relation_info() from fetching index info, which is necessary
6402  * because it does not expect that any IndexOptInfo is currently
6403  * undergoing REINDEX.
6404  */
6405  rte = makeNode(RangeTblEntry);
6406  rte->rtekind = RTE_RELATION;
6407  rte->relid = tableOid;
6408  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6410  rte->lateral = false;
6411  rte->inh = true;
6412  rte->inFromCl = true;
6413  query->rtable = list_make1(rte);
6414 
6415  /* Set up RTE/RelOptInfo arrays */
6417 
6418  /* Build RelOptInfo */
6419  rel = build_simple_rel(root, 1, NULL);
6420 
6421  /* Rels are assumed already locked by the caller */
6422  heap = table_open(tableOid, NoLock);
6423  index = index_open(indexOid, NoLock);
6424 
6425  /*
6426  * Determine if it's safe to proceed.
6427  *
6428  * Currently, parallel workers can't access the leader's temporary tables.
6429  * Furthermore, any index predicate or index expressions must be parallel
6430  * safe.
6431  */
6432  if (heap->rd_rel->relpersistence == RELPERSISTENCE_TEMP ||
6433  !is_parallel_safe(root, (Node *) RelationGetIndexExpressions(index)) ||
6434  !is_parallel_safe(root, (Node *) RelationGetIndexPredicate(index)))
6435  {
6436  parallel_workers = 0;
6437  goto done;
6438  }
6439 
6440  /*
6441  * If parallel_workers storage parameter is set for the table, accept that
6442  * as the number of parallel worker processes to launch (though still cap
6443  * at max_parallel_maintenance_workers). Note that we deliberately do not
6444  * consider any other factor when parallel_workers is set. (e.g., memory
6445  * use by workers.)
6446  */
6447  if (rel->rel_parallel_workers != -1)
6448  {
6449  parallel_workers = Min(rel->rel_parallel_workers,
6451  goto done;
6452  }
6453 
6454  /*
6455  * Estimate heap relation size ourselves, since rel->pages cannot be
6456  * trusted (heap RTE was marked as inheritance parent)
6457  */
6458  estimate_rel_size(heap, NULL, &heap_blocks, &reltuples, &allvisfrac);
6459 
6460  /*
6461  * Determine number of workers to scan the heap relation using generic
6462  * model
6463  */
6464  parallel_workers = compute_parallel_worker(rel, heap_blocks, -1,
6466 
6467  /*
6468  * Cap workers based on available maintenance_work_mem as needed.
6469  *
6470  * Note that each tuplesort participant receives an even share of the
6471  * total maintenance_work_mem budget. Aim to leave participants
6472  * (including the leader as a participant) with no less than 32MB of
6473  * memory. This leaves cases where maintenance_work_mem is set to 64MB
6474  * immediately past the threshold of being capable of launching a single
6475  * parallel worker to sort.
6476  */
6477  while (parallel_workers > 0 &&
6478  maintenance_work_mem / (parallel_workers + 1) < 32768L)
6479  parallel_workers--;
6480 
6481 done:
6482  index_close(index, NoLock);
6483  table_close(heap, NoLock);
6484 
6485  return parallel_workers;
6486 }
Query * parse
Definition: pathnodes.h:173
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:3746
#define Min(x, y)
Definition: c.h:986
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:533
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:110
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4873
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:206
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:567
int wt_param_id
Definition: pathnodes.h:357
List * rtable
Definition: parsenodes.h:137
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4760
PlannerGlobal * glob
Definition: pathnodes.h:175
bool IsUnderPostmaster
Definition: globals.c:110
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:194
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:968
int rel_parallel_workers
Definition: pathnodes.h:716
int max_parallel_maintenance_workers
Definition: globals.c:125
int maintenance_work_mem
Definition: globals.c:124
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:581
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:83
Index query_level
Definition: pathnodes.h:177
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
RTEKind rtekind
Definition: parsenodes.h:981
MemoryContext planner_cxt
Definition: pathnodes.h:325
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132

◆ planner()

struct PlannedStmt* planner ( Query parse,
const char *  query_string,
int  cursorOptions,
struct ParamListInfoData boundParams 
)

◆ predicate_implied_by()

bool predicate_implied_by ( List predicate_list,
List clause_list,
bool  weak 
)

Definition at line 151 of file predtest.c.

References linitial, list_length(), NIL, and predicate_implied_by_recurse().

Referenced by add_predicate_to_index_quals(), build_paths_for_OR(), check_index_predicates(), choose_bitmap_and(), ConstraintImpliedByRelConstraint(), create_bitmap_scan_plan(), create_bitmap_subplan(), create_indexscan_plan(), infer_arbiter_indexes(), and test_predtest().

153 {
154  Node *p,
155  *c;
156 
157  if (predicate_list == NIL)
158  return true; /* no predicate: implication is vacuous */
159  if (clause_list == NIL)
160  return false; /* no restriction: implication must fail */
161 
162  /*
163  * If either input is a single-element list, replace it with its lone
164  * member; this avoids one useless level of AND-recursion. We only need
165  * to worry about this at top level, since eval_const_expressions should
166  * have gotten rid of any trivial ANDs or ORs below that.
167  */
168  if (list_length(predicate_list) == 1)
169  p = (Node *) linitial(predicate_list);
170  else
171  p = (Node *) predicate_list;
172  if (list_length(clause_list) == 1)
173  c = (Node *) linitial(clause_list);
174  else
175  c = (Node *) clause_list;
176 
177  /* And away we go ... */
178  return predicate_implied_by_recurse(c, p, weak);
179 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:533
#define linitial(l)
Definition: pg_list.h:174
char * c
static int list_length(const List *l)
Definition: pg_list.h:149
static bool predicate_implied_by_recurse(Node *clause, Node *predicate, bool weak)
Definition: predtest.c:289

◆ predicate_refuted_by()

bool predicate_refuted_by ( List predicate_list,
List clause_list,
bool  weak 
)

Definition at line 221 of file predtest.c.

References linitial, list_length(), NIL, and predicate_refuted_by_recurse().

Referenced by gen_partprune_steps_internal(), relation_excluded_by_constraints(), and test_predtest().

223 {
224  Node *p,
225  *c;
226 
227  if (predicate_list == NIL)
228  return false; /* no predicate: no refutation is possible */
229  if (clause_list == NIL)
230  return false; /* no restriction: refutation must fail */
231 
232  /*
233  * If either input is a single-element list, replace it with its lone
234  * member; this avoids one useless level of AND-recursion. We only need
235  * to worry about this at top level, since eval_const_expressions should
236  * have gotten rid of any trivial ANDs or ORs below that.
237  */
238  if (list_length(predicate_list) == 1)
239  p = (Node *) linitial(predicate_list);
240  else
241  p = (Node *) predicate_list;
242  if (list_length(clause_list) == 1)
243  c = (Node *) linitial(clause_list);
244  else
245  c = (Node *) clause_list;
246 
247  /* And away we go ... */
248  return predicate_refuted_by_recurse(c, p, weak);
249 }
#define NIL
Definition: pg_list.h:65
Definition: nodes.h:533
#define linitial(l)
Definition: pg_list.h:174
char * c
static bool predicate_refuted_by_recurse(Node *clause, Node *predicate, bool weak)
Definition: predtest.c:530
static int list_length(const List *l)
Definition: pg_list.h:149

◆ pull_var_clause()

List* pull_var_clause ( Node node,
int  flags 
)

Definition at line 562 of file var.c.

References Assert, pull_var_clause_context::flags, NIL, pull_var_clause_walker(), PVC_INCLUDE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS, PVC_INCLUDE_WINDOWFUNCS, PVC_RECURSE_AGGREGATES, PVC_RECURSE_PLACEHOLDERS, PVC_RECURSE_WINDOWFUNCS, and pull_var_clause_context::varlist.

Referenced by AddRelationNewConstraints(), build_base_rel_tlists(), build_remote_returning(), build_tlist_to_deparse(), CreateTrigger(), distribute_qual_to_rels(), estimate_num_groups(), find_placeholders_in_expr(), fix_placeholder_input_needed_levels(), foreign_grouping_ok(), generate_base_implied_equalities_no_const(), make_group_input_target(), make_partial_grouping_target(), make_sort_input_target(), make_window_input_target(), prepare_sort_from_pathkeys(), preprocess_targetlist(), process_implied_equality(), qual_is_pushdown_safe(), and StoreRelCheck().

563 {
564  pull_var_clause_context context;
565 
566  /* Assert that caller has not specified inconsistent flags */
573 
574  context.varlist = NIL;
575  context.flags = flags;
576 
577  pull_var_clause_walker(node, &context);
578  return context.varlist;
579 }
#define NIL
Definition: pg_list.h:65
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:189
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:183
#define PVC_INCLUDE_WINDOWFUNCS
Definition: optimizer.h:185
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:187
#define Assert(condition)
Definition: c.h:804
static bool pull_var_clause_walker(Node *node, pull_var_clause_context *context)
Definition: var.c:582
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:186
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:184

◆ pull_varattnos()

void pull_varattnos ( Node node,
Index  varno,
Bitmapset **  varattnos 
)

Definition at line 246 of file var.c.

References pull_varattnos_walker(), pull_varattnos_context::varattnos, and pull_varattnos_context::varno.

Referenced by check_index_only(), check_selective_binary_conversion(), ComputePartitionAttrs(), create_foreignscan_plan(), DefineIndex(), deparseReturningList(), fill_extraUpdatedCols(), has_partition_attrs(), postgresGetForeignRelSize(), RelationGetIndexAttrBitmap(), and remove_unused_subquery_outputs().

247 {
248  pull_varattnos_context context;
249 
250  context.varattnos = *varattnos;
251  context.varno = varno;
252 
253  (void) pull_varattnos_walker(node, &context);
254 
255  *varattnos = context.varattnos;
256 }
Bitmapset * varattnos
Definition: var.c:41
static bool pull_varattnos_walker(Node *node, pull_varattnos_context *context)
Definition: var.c:259

◆ pull_varnos()

Bitmapset* pull_varnos ( PlannerInfo root,
Node node 
)

Definition at line 97 of file var.c.

References pull_varnos_walker(), query_or_expression_tree_walker(), pull_varnos_context::root, pull_varnos_context::sublevels_up, and pull_varnos_context::varnos.

Referenced by compute_semijoin_info(), convert_ANY_sublink_to_join(), convert_EXISTS_sublink_to_join(), cost_incremental_sort(), distribute_qual_to_rels(), examine_variable(), expand_indexqual_rowcompare(), find_placeholder_info(), get_eclass_for_sort_expr(), is_pseudo_constant_for_index(), IsTidEqualAnyClause(), join_is_removable(), make_outerjoininfo(), make_restrictinfo_internal(), match_rowcompare_to_indexcol(), match_saopclause_to_indexcol(), NumRelids(), process_implied_equality(), pullup_replace_vars_callback(), and reduce_outer_joins_pass2().

98 {
99  pull_varnos_context context;
100 
101  context.varnos = NULL;
102  context.root = root;
103  context.sublevels_up = 0;
104 
105  /*
106  * Must be prepared to start with a Query or a bare expression tree; if
107  * it's a Query, we don't want to increment sublevels_up.
108  */
111  (void *) &context,
112  0);
113 
114  return context.varnos;
115 }
static bool pull_varnos_walker(Node *node, pull_varnos_context *context)
Definition: var.c:144
int sublevels_up
Definition: var.c:36
Relids varnos
Definition: var.c:34
PlannerInfo * root
Definition: var.c:35
bool query_or_expression_tree_walker(Node *node, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:3442

◆ pull_varnos_of_level()

Bitmapset* pull_varnos_of_level ( PlannerInfo root,
Node node,
int  levelsup 
)

Definition at line 123 of file var.c.

References pull_varnos_walker(), query_or_expression_tree_walker(), pull_varnos_context::root, pull_varnos_context::sublevels_up, and pull_varnos_context::varnos.

Referenced by is_simple_subquery(), and jointree_contains_lateral_outer_refs().

124 {
125  pull_varnos_context context;
126 
127  context.varnos = NULL;
128  context.root = root;
129  context.sublevels_up = levelsup;
130 
131  /*
132  * Must be prepared to start with a Query or a bare expression tree; if
133  * it's a Query, we don't want to increment sublevels_up.
134  */
137  (void *) &context,
138  0);
139 
140  return context.varnos;
141 }
static bool pull_varnos_walker(Node *node, pull_varnos_context *context)
Definition: var.c:144
int sublevels_up
Definition: var.c:36
Relids varnos
Definition: var.c:34
PlannerInfo * root
Definition: var.c:35
bool query_or_expression_tree_walker(Node *node, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:3442

◆ pull_vars_of_level()

List* pull_vars_of_level ( Node node,
int  levelsup 
)

Definition at line 290 of file var.c.

References NIL, pull_vars_walker(), query_or_expression_tree_walker(), pull_vars_context::sublevels_up, and pull_vars_context::vars.

Referenced by extract_lateral_references().

291 {
292  pull_vars_context context;
293 
294  context.vars = NIL;
295  context.sublevels_up = levelsup;
296 
297  /*
298  * Must be prepared to start with a Query or a bare expression tree; if
299  * it's a Query, we don't want to increment sublevels_up.
300  */
303  (void *) &context,
304  0);
305 
306  return context.vars;
307 }
int sublevels_up
Definition: var.c:48
#define NIL
Definition: pg_list.h:65
static bool pull_vars_walker(Node *node, pull_vars_context *context)
Definition: var.c:310
List * vars
Definition: var.c:47
bool query_or_expression_tree_walker(Node *node, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:3442

Variable Documentation

◆ cpu_index_tuple_cost

PGDLLIMPORT double cpu_index_tuple_cost

Definition at line 121 of file costsize.c.

Referenced by genericcostestimate(), and gincostestimate().

◆ cpu_operator_cost

◆ cpu_tuple_cost

◆ effective_cache_size

PGDLLIMPORT int effective_cache_size

Definition at line 126 of file costsize.c.

Referenced by gistBuildCallback(), gistInitBuffering(), and index_pages_fetched().

◆ force_parallel_mode

int force_parallel_mode

Definition at line 70 of file planner.c.

Referenced by HandleParallelMessage(), query_planner(), and standard_planner().

◆ parallel_leader_participation

bool parallel_leader_participation

Definition at line 71 of file planner.c.

Referenced by ExecGather(), ExecGatherMerge(), ExecInitGather(), and get_parallel_divisor().

◆ parallel_setup_cost

PGDLLIMPORT double parallel_setup_cost

Definition at line 124 of file costsize.c.

Referenced by cost_gather(), cost_gather_merge(), and standard_planner().

◆ parallel_tuple_cost

PGDLLIMPORT double parallel_tuple_cost

Definition at line 123 of file costsize.c.

Referenced by cost_gather(), cost_gather_merge(), and standard_planner().

◆ random_page_cost

PGDLLIMPORT double random_page_cost

◆ seq_page_cost