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)
 
void convert_saop_to_hashed_saop (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, bool include_out_arguments, 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:590

Definition at line 28 of file optimizer.h.

Referenced by relation_can_be_sorted_early(), 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 192 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 294 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().

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

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

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

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

◆ 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:219
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Index varlevelsup
Definition: primnodes.h:196
List * args
Definition: primnodes.h:503
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2233
static bool is_orclause(const void *clause)
Definition: nodeFuncs.h:106
Expr * orclause
Definition: pathnodes.h:2079
Selectivity restriction_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, int varRelid)
Definition: plancat.c:1825
double tuples
Definition: pathnodes.h:716
Selectivity rowcomparesel(PlannerInfo *root, RowCompareExpr *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: selfuncs.c:2170
Relids clause_relids
Definition: pathnodes.h:2063
bool pseudoconstant
Definition: pathnodes.h:2053
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:97
Definition: nodes.h:539
double Selectivity
Definition: nodes.h:672
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
#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:2086
static bool bms_is_subset_singleton(const Bitmapset *s, int x)
Definition: clausesel.c:591
Oid funcid
Definition: primnodes.h:495
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:1905
#define DatumGetBool(X)
Definition: postgres.h:437
Selectivity outer_selec
Definition: pathnodes.h:2089
Expr * clause
Definition: pathnodes.h:2045
Index varno
Definition: primnodes.h:189
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:502
Oid inputcollid
Definition: primnodes.h:547
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:232
void * arg
Selectivity join_selectivity(PlannerInfo *root, Oid operatorid, List *args, Oid inputcollid, JoinType jointype, SpecialJoinInfo *sjinfo)
Definition: plancat.c:1864
Oid opno
Definition: primnodes.h:542
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:548
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:220

◆ 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:590
List * statlist
Definition: pathnodes.h:714
bool is_pseudo_constant_clause_relids(Node *clause, Relids relids)
Definition: clauses.c:1949
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Relids clause_relids
Definition: pathnodes.h:2063
bool pseudoconstant
Definition: pathnodes.h:2053
Definition: nodes.h:539
Relids left_relids
Definition: pathnodes.h:2075
double Selectivity
Definition: nodes.h:672
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:1169
#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:1929
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:2045
int NumRelids(PlannerInfo *root, Node *clause)
Definition: clauses.c:1971
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:706
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:2076
#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:542
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
List * args
Definition: primnodes.h:548
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:3461
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 558 of file clauses.c.

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

559 {
561 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:571

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2125 of file clauses.c.

References convert_saop_to_hashed_saop_walker().

Referenced by preprocess_expression().

2126 {
2127  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2128 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2131

◆ count_nonjunk_tlist_entries()

int count_nonjunk_tlist_entries ( List tlist)

Definition at line 175 of file tlist.c.

References lfirst, and TargetEntry::resjunk.

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

176 {
177  int len = 0;
178  ListCell *l;
179 
180  foreach(l, tlist)
181  {
182  TargetEntry *tle = (TargetEntry *) lfirst(l);
183 
184  if (!tle->resjunk)
185  len++;
186  }
187  return len;
188 }
bool resjunk
Definition: primnodes.h:1461
#define lfirst(lc)
Definition: pg_list.h:169

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

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

2234 {
2236 
2237  context.boundParams = root->glob->boundParams; /* bound Params */
2238  /* we do not need to mark the plan as depending on inlined functions */
2239  context.root = NULL;
2240  context.active_fns = NIL; /* nothing being recursively simplified */
2241  context.case_val = NULL; /* no CASE being examined */
2242  context.estimate = true; /* unsafe transformations OK */
2243  return eval_const_expressions_mutator(node, &context);
2244 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2278
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:163
ParamListInfo boundParams
Definition: pathnodes.h:93

◆ eval_const_expressions()

Node* eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2093 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(), DetachAddConstraintIfNeeded(), DoCopy(), expression_planner(), expression_planner_with_deps(), fetch_statentries_for_relation(), get_proposed_default_constraint(), get_relation_constraints(), get_relation_statistics(), preprocess_expression(), preprocess_function_rtes(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), and simplify_EXISTS_query().

2094 {
2096 
2097  if (root)
2098  context.boundParams = root->glob->boundParams; /* bound Params */
2099  else
2100  context.boundParams = NULL;
2101  context.root = root; /* for inlined-function dependencies */
2102  context.active_fns = NIL; /* nothing being recursively simplified */
2103  context.case_val = NULL; /* no CASE being examined */
2104  context.estimate = false; /* safe transformations only */
2105  return eval_const_expressions_mutator(node, &context);
2106 }
#define NIL
Definition: pg_list.h:65
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2278
ParamListInfo boundParams
Definition: clauses.c:59
PlannerGlobal * glob
Definition: pathnodes.h:163
ParamListInfo boundParams
Definition: pathnodes.h:93

◆ evaluate_expr()

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

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

4780 {
4781  EState *estate;
4782  ExprState *exprstate;
4783  MemoryContext oldcontext;
4784  Datum const_val;
4785  bool const_is_null;
4786  int16 resultTypLen;
4787  bool resultTypByVal;
4788 
4789  /*
4790  * To use the executor, we need an EState.
4791  */
4792  estate = CreateExecutorState();
4793 
4794  /* We can use the estate's working context to avoid memory leaks. */
4795  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4796 
4797  /* Make sure any opfuncids are filled in. */
4798  fix_opfuncids((Node *) expr);
4799 
4800  /*
4801  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4802  * because it'd result in recursively invoking eval_const_expressions.)
4803  */
4804  exprstate = ExecInitExpr(expr, NULL);
4805 
4806  /*
4807  * And evaluate it.
4808  *
4809  * It is OK to use a default econtext because none of the ExecEvalExpr()
4810  * code used in this situation will use econtext. That might seem
4811  * fortuitous, but it's not so unreasonable --- a constant expression does
4812  * not depend on context, by definition, n'est ce pas?
4813  */
4814  const_val = ExecEvalExprSwitchContext(exprstate,
4815  GetPerTupleExprContext(estate),
4816  &const_is_null);
4817 
4818  /* Get info needed about result datatype */
4819  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4820 
4821  /* Get back to outer memory context */
4822  MemoryContextSwitchTo(oldcontext);
4823 
4824  /*
4825  * Must copy result out of sub-context used by expression eval.
4826  *
4827  * Also, if it's varlena, forcibly detoast it. This protects us against
4828  * storing TOAST pointers into plans that might outlive the referenced
4829  * data. (makeConst would handle detoasting anyway, but it's worth a few
4830  * extra lines here so that we can do the copy and detoast in one step.)
4831  */
4832  if (!const_is_null)
4833  {
4834  if (resultTypLen == -1)
4835  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4836  else
4837  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4838  }
4839 
4840  /* Release all the junk we just created */
4841  FreeExecutorState(estate);
4842 
4843  /*
4844  * Make the constant result node.
4845  */
4846  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4847  resultTypLen,
4848  const_val, const_is_null,
4849  resultTypByVal);
4850 }
signed short int16
Definition: c.h:428
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:331
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
#define PointerGetDatum(X)
Definition: postgres.h:600
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:539
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:533
MemoryContext es_query_cxt
Definition: execnodes.h:600
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:411
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,
bool  include_out_arguments,
Oid  result_type,
struct HeapTupleData func_tuple 
)

◆ expression_planner()

Expr* expression_planner ( Expr expr)

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

5654 {
5655  Node *result;
5656 
5657  /*
5658  * Convert named-argument function calls, insert default arguments and
5659  * simplify constant subexprs
5660  */
5661  result = eval_const_expressions(NULL, (Node *) expr);
5662 
5663  /* Fill in opfuncid values if missing */
5664  fix_opfuncids(result);
5665 
5666  return (Expr *) result;
5667 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
Definition: nodes.h:539
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2093

◆ expression_planner_with_deps()

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

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

5683 {
5684  Node *result;
5685  PlannerGlobal glob;
5686  PlannerInfo root;
5687 
5688  /* Make up dummy planner state so we can use setrefs machinery */
5689  MemSet(&glob, 0, sizeof(glob));
5690  glob.type = T_PlannerGlobal;
5691  glob.relationOids = NIL;
5692  glob.invalItems = NIL;
5693 
5694  MemSet(&root, 0, sizeof(root));
5695  root.type = T_PlannerInfo;
5696  root.glob = &glob;
5697 
5698  /*
5699  * Convert named-argument function calls, insert default arguments and
5700  * simplify constant subexprs. Collect identities of inlined functions
5701  * and elided domains, too.
5702  */
5703  result = eval_const_expressions(&root, (Node *) expr);
5704 
5705  /* Fill in opfuncid values if missing */
5706  fix_opfuncids(result);
5707 
5708  /*
5709  * Now walk the finished expression to find anything else we ought to
5710  * record as an expression dependency.
5711  */
5712  (void) extract_query_dependencies_walker(result, &root);
5713 
5714  *relationOids = glob.relationOids;
5715  *invalItems = glob.invalItems;
5716 
5717  return (Expr *) result;
5718 }
#define NIL
Definition: pg_list.h:65
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1652
Definition: nodes.h:539
#define MemSet(start, val, len)
Definition: c.h:1008
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2093
PlannerGlobal * glob
Definition: pathnodes.h:163
List * invalItems
Definition: pathnodes.h:111
NodeTag type
Definition: pathnodes.h:159
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3069
NodeTag type
Definition: pathnodes.h:91
List * relationOids
Definition: pathnodes.h:109

◆ extract_query_dependencies()

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

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

3037 {
3038  PlannerGlobal glob;
3039  PlannerInfo root;
3040 
3041  /* Make up dummy planner state so we can use this module's machinery */
3042  MemSet(&glob, 0, sizeof(glob));
3043  glob.type = T_PlannerGlobal;
3044  glob.relationOids = NIL;
3045  glob.invalItems = NIL;
3046  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3047  glob.dependsOnRole = false;
3048 
3049  MemSet(&root, 0, sizeof(root));
3050  root.type = T_PlannerInfo;
3051  root.glob = &glob;
3052 
3053  (void) extract_query_dependencies_walker(query, &root);
3054 
3055  *relationOids = glob.relationOids;
3056  *invalItems = glob.invalItems;
3057  *hasRowSecurity = glob.dependsOnRole;
3058 }
#define NIL
Definition: pg_list.h:65
#define MemSet(start, val, len)
Definition: c.h:1008
bool dependsOnRole
Definition: pathnodes.h:123
PlannerGlobal * glob
Definition: pathnodes.h:163
List * invalItems
Definition: pathnodes.h:111
NodeTag type
Definition: pathnodes.h:159
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3069
NodeTag type
Definition: pathnodes.h:91
List * relationOids
Definition: pathnodes.h:109

◆ 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:136
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 368 of file tlist.c.

References TargetEntry::expr, and get_sortgroupclause_tle().

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

369 {
370  TargetEntry *tle = get_sortgroupclause_tle(sgClause, targetList);
371 
372  return (Node *) tle->expr;
373 }
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:356
Definition: nodes.h:539
Expr * expr
Definition: primnodes.h:1454

◆ get_sortgroupclause_tle()

◆ get_sortgrouplist_exprs()

List* get_sortgrouplist_exprs ( List sgClauses,
List targetList 
)

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

382 {
383  List *result = NIL;
384  ListCell *l;
385 
386  foreach(l, sgClauses)
387  {
388  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
389  Node *sortexpr;
390 
391  sortexpr = get_sortgroupclause_expr(sortcl, targetList);
392  result = lappend(result, sortexpr);
393  }
394  return result;
395 }
#define NIL
Definition: pg_list.h:65
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:368
Definition: nodes.h:539
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 411 of file tlist.c.

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

Referenced by preprocess_groupclause().

412 {
413  ListCell *l;
414 
415  foreach(l, clauses)
416  {
418 
419  if (cl->tleSortGroupRef == sortref)
420  return cl;
421  }
422 
423  elog(ERROR, "ORDER/GROUP BY expression not found in list");
424  return NULL; /* keep compiler quiet */
425 }
Index tleSortGroupRef
Definition: parsenodes.h:1283
#define ERROR
Definition: elog.h:46
#define lfirst(lc)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:232

◆ get_sortgroupref_clause_noerr()

SortGroupClause* get_sortgroupref_clause_noerr ( Index  sortref,
List clauses 
)

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

433 {
434  ListCell *l;
435 
436  foreach(l, clauses)
437  {
439 
440  if (cl->tleSortGroupRef == sortref)
441  return cl;
442  }
443 
444  return NULL;
445 }
Index tleSortGroupRef
Definition: parsenodes.h:1283
#define lfirst(lc)
Definition: pg_list.h:169

◆ get_sortgroupref_tle()

TargetEntry* get_sortgroupref_tle ( Index  sortref,
List targetList 
)

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

335 {
336  ListCell *l;
337 
338  foreach(l, targetList)
339  {
340  TargetEntry *tle = (TargetEntry *) lfirst(l);
341 
342  if (tle->ressortgroupref == sortref)
343  return tle;
344  }
345 
346  elog(ERROR, "ORDER/GROUP BY expression not found in targetlist");
347  return NULL; /* keep compiler quiet */
348 }
#define ERROR
Definition: elog.h:46
#define lfirst(lc)
Definition: pg_list.h:169
#define elog(elevel,...)
Definition: elog.h:232
Index ressortgroupref
Definition: primnodes.h:1457

◆ is_pseudo_constant_for_index()

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

Definition at line 3818 of file indxpath.c.

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

3819 {
3820  /* pull_varnos is cheaper than volatility check, so do that first */
3821  if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
3822  return false; /* no good, contains Var of table */
3823  if (contain_volatile_functions(expr))
3824  return false; /* no good, volatile comparison value */
3825  return true;
3826 }
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:97
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:451
RelOptInfo * rel
Definition: pathnodes.h:832
Index relid
Definition: pathnodes.h:704
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:3461
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(), ScalarArrayOpExpr::hashfuncid, 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(), ScalarArrayOpExpr::negfuncid, 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->hashfuncid = InvalidOid;
131  newopexpr->negfuncid = InvalidOid;
132  newopexpr->useOr = !saopexpr->useOr;
133  newopexpr->inputcollid = saopexpr->inputcollid;
134  newopexpr->args = saopexpr->args;
135  newopexpr->location = saopexpr->location;
136  return (Node *) newopexpr;
137  }
138  }
139  break;
140  case T_BoolExpr:
141  {
142  BoolExpr *expr = (BoolExpr *) node;
143 
144  switch (expr->boolop)
145  {
146  /*--------------------
147  * Apply DeMorgan's Laws:
148  * (NOT (AND A B)) => (OR (NOT A) (NOT B))
149  * (NOT (OR A B)) => (AND (NOT A) (NOT B))
150  * i.e., swap AND for OR and negate each subclause.
151  *
152  * If the input is already AND/OR flat and has no NOT
153  * directly above AND or OR, this transformation preserves
154  * those properties. For example, if no direct child of
155  * the given AND clause is an AND or a NOT-above-OR, then
156  * the recursive calls of negate_clause() can't return any
157  * OR clauses. So we needn't call pull_ors() before
158  * building a new OR clause. Similarly for the OR case.
159  *--------------------
160  */
161  case AND_EXPR:
162  {
163  List *nargs = NIL;
164  ListCell *lc;
165 
166  foreach(lc, expr->args)
167  {
168  nargs = lappend(nargs,
169  negate_clause(lfirst(lc)));
170  }
171  return (Node *) make_orclause(nargs);
172  }
173  break;
174  case OR_EXPR:
175  {
176  List *nargs = NIL;
177  ListCell *lc;
178 
179  foreach(lc, expr->args)
180  {
181  nargs = lappend(nargs,
182  negate_clause(lfirst(lc)));
183  }
184  return (Node *) make_andclause(nargs);
185  }
186  break;
187  case NOT_EXPR:
188 
189  /*
190  * NOT underneath NOT: they cancel. We assume the
191  * input is already simplified, so no need to recurse.
192  */
193  return (Node *) linitial(expr->args);
194  default:
195  elog(ERROR, "unrecognized boolop: %d",
196  (int) expr->boolop);
197  break;
198  }
199  }
200  break;
201  case T_NullTest:
202  {
203  NullTest *expr = (NullTest *) node;
204 
205  /*
206  * In the rowtype case, the two flavors of NullTest are *not*
207  * logical inverses, so we can't simplify. But it does work
208  * for scalar datatypes.
209  */
210  if (!expr->argisrow)
211  {
212  NullTest *newexpr = makeNode(NullTest);
213 
214  newexpr->arg = expr->arg;
215  newexpr->nulltesttype = (expr->nulltesttype == IS_NULL ?
216  IS_NOT_NULL : IS_NULL);
217  newexpr->argisrow = expr->argisrow;
218  newexpr->location = expr->location;
219  return (Node *) newexpr;
220  }
221  }
222  break;
223  case T_BooleanTest:
224  {
225  BooleanTest *expr = (BooleanTest *) node;
226  BooleanTest *newexpr = makeNode(BooleanTest);
227 
228  newexpr->arg = expr->arg;
229  switch (expr->booltesttype)
230  {
231  case IS_TRUE:
232  newexpr->booltesttype = IS_NOT_TRUE;
233  break;
234  case IS_NOT_TRUE:
235  newexpr->booltesttype = IS_TRUE;
236  break;
237  case IS_FALSE:
238  newexpr->booltesttype = IS_NOT_FALSE;
239  break;
240  case IS_NOT_FALSE:
241  newexpr->booltesttype = IS_FALSE;
242  break;
243  case IS_UNKNOWN:
244  newexpr->booltesttype = IS_NOT_UNKNOWN;
245  break;
246  case IS_NOT_UNKNOWN:
247  newexpr->booltesttype = IS_UNKNOWN;
248  break;
249  default:
250  elog(ERROR, "unrecognized booltesttype: %d",
251  (int) expr->booltesttype);
252  break;
253  }
254  newexpr->location = expr->location;
255  return (Node *) newexpr;
256  }
257  break;
258  default:
259  /* else fall through */
260  break;
261  }
262 
263  /*
264  * Otherwise we don't know how to simplify this, so just tack on an
265  * explicit NOT node.
266  */
267  return (Node *) make_notclause((Expr *) node);
268 }
Datum constvalue
Definition: primnodes.h:219
#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:539
unsigned int Oid
Definition: postgres_ext.h:31
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:652
Oid opresulttype
Definition: primnodes.h:544
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
BoolExprType boolop
Definition: primnodes.h:625
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:357
Expr * arg
Definition: primnodes.h:1265
char * c
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:636
int location
Definition: primnodes.h:549
Expr * arg
Definition: primnodes.h:1288
#define DatumGetBool(X)
Definition: postgres.h:437
Oid opcollid
Definition: primnodes.h:546
Definition: nodes.h:158
List * lappend(List *list, void *datum)
Definition: list.c:336
BoolTestType booltesttype
Definition: primnodes.h:1289
Oid opfuncid
Definition: primnodes.h:543
NullTestType nulltesttype
Definition: primnodes.h:1266
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:587
#define lfirst(lc)
Definition: pg_list.h:169
int location
Definition: primnodes.h:1268
Oid inputcollid
Definition: primnodes.h:547
List * args
Definition: primnodes.h:626
#define nodeTag(nodeptr)
Definition: nodes.h:544
#define elog(elevel,...)
Definition: elog.h:232
bool argisrow
Definition: primnodes.h:1267
Oid opno
Definition: primnodes.h:542
Oid get_negator(Oid opno)
Definition: lsyscache.c:1504
List * args
Definition: primnodes.h:548
Definition: pg_list.h:50
bool constisnull
Definition: primnodes.h:220
bool opretset
Definition: primnodes.h:545

◆ plan_cluster_use_sort()

bool plan_cluster_use_sort ( Oid  tableOid,
Oid  indexOid 
)

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

5734 {
5735  PlannerInfo *root;
5736  Query *query;
5737  PlannerGlobal *glob;
5738  RangeTblEntry *rte;
5739  RelOptInfo *rel;
5740  IndexOptInfo *indexInfo;
5741  QualCost indexExprCost;
5742  Cost comparisonCost;
5743  Path *seqScanPath;
5744  Path seqScanAndSortPath;
5745  IndexPath *indexScanPath;
5746  ListCell *lc;
5747 
5748  /* We can short-circuit the cost comparison if indexscans are disabled */
5749  if (!enable_indexscan)
5750  return true; /* use sort */
5751 
5752  /* Set up mostly-dummy planner state */
5753  query = makeNode(Query);
5754  query->commandType = CMD_SELECT;
5755 
5756  glob = makeNode(PlannerGlobal);
5757 
5758  root = makeNode(PlannerInfo);
5759  root->parse = query;
5760  root->glob = glob;
5761  root->query_level = 1;
5763  root->wt_param_id = -1;
5764 
5765  /* Build a minimal RTE for the rel */
5766  rte = makeNode(RangeTblEntry);
5767  rte->rtekind = RTE_RELATION;
5768  rte->relid = tableOid;
5769  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
5771  rte->lateral = false;
5772  rte->inh = false;
5773  rte->inFromCl = true;
5774  query->rtable = list_make1(rte);
5775 
5776  /* Set up RTE/RelOptInfo arrays */
5778 
5779  /* Build RelOptInfo */
5780  rel = build_simple_rel(root, 1, NULL);
5781 
5782  /* Locate IndexOptInfo for the target index */
5783  indexInfo = NULL;
5784  foreach(lc, rel->indexlist)
5785  {
5786  indexInfo = lfirst_node(IndexOptInfo, lc);
5787  if (indexInfo->indexoid == indexOid)
5788  break;
5789  }
5790 
5791  /*
5792  * It's possible that get_relation_info did not generate an IndexOptInfo
5793  * for the desired index; this could happen if it's not yet reached its
5794  * indcheckxmin usability horizon, or if it's a system index and we're
5795  * ignoring system indexes. In such cases we should tell CLUSTER to not
5796  * trust the index contents but use seqscan-and-sort.
5797  */
5798  if (lc == NULL) /* not in the list? */
5799  return true; /* use sort */
5800 
5801  /*
5802  * Rather than doing all the pushups that would be needed to use
5803  * set_baserel_size_estimates, just do a quick hack for rows and width.
5804  */
5805  rel->rows = rel->tuples;
5806  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
5807 
5808  root->total_table_pages = rel->pages;
5809 
5810  /*
5811  * Determine eval cost of the index expressions, if any. We need to
5812  * charge twice that amount for each tuple comparison that happens during
5813  * the sort, since tuplesort.c will have to re-evaluate the index
5814  * expressions each time. (XXX that's pretty inefficient...)
5815  */
5816  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
5817  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
5818 
5819  /* Estimate the cost of seq scan + sort */
5820  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
5821  cost_sort(&seqScanAndSortPath, root, NIL,
5822  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
5823  comparisonCost, maintenance_work_mem, -1.0);
5824 
5825  /* Estimate the cost of index scan */
5826  indexScanPath = create_index_path(root, indexInfo,
5827  NIL, NIL, NIL, NIL,
5828  ForwardScanDirection, false,
5829  NULL, 1.0, false);
5830 
5831  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
5832 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
Path path
Definition: pathnodes.h:1236
double tuples
Definition: pathnodes.h:716
#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:363
List * rtable
Definition: parsenodes.h:147
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4308
#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:163
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:194
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
double total_table_pages
Definition: pathnodes.h:336
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1139
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:2036
List * indexlist
Definition: pathnodes.h:713
double rows
Definition: pathnodes.h:679
int maintenance_work_mem
Definition: globals.c:126
Cost total_cost
Definition: pathnodes.h:1186
CmdType commandType
Definition: parsenodes.h:120
#define makeNode(_type_)
Definition: nodes.h:587
BlockNumber pages
Definition: pathnodes.h:715
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:83
Index query_level
Definition: pathnodes.h:165
RTEKind rtekind
Definition: parsenodes.h:995
MemoryContext planner_cxt
Definition: pathnodes.h:334
struct PathTarget * reltarget
Definition: pathnodes.h:687
bool enable_indexscan
Definition: costsize.c:134
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:929
double Cost
Definition: nodes.h:673
List * indexprs
Definition: pathnodes.h:855

◆ plan_create_index_workers()

int plan_create_index_workers ( Oid  tableOid,
Oid  indexOid 
)

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

5852 {
5853  PlannerInfo *root;
5854  Query *query;
5855  PlannerGlobal *glob;
5856  RangeTblEntry *rte;
5857  Relation heap;
5858  Relation index;
5859  RelOptInfo *rel;
5860  int parallel_workers;
5861  BlockNumber heap_blocks;
5862  double reltuples;
5863  double allvisfrac;
5864 
5865  /*
5866  * We don't allow performing parallel operation in standalone backend or
5867  * when parallelism is disabled.
5868  */
5870  return 0;
5871 
5872  /* Set up largely-dummy planner state */
5873  query = makeNode(Query);
5874  query->commandType = CMD_SELECT;
5875 
5876  glob = makeNode(PlannerGlobal);
5877 
5878  root = makeNode(PlannerInfo);
5879  root->parse = query;
5880  root->glob = glob;
5881  root->query_level = 1;
5883  root->wt_param_id = -1;
5884 
5885  /*
5886  * Build a minimal RTE.
5887  *
5888  * Mark the RTE with inh = true. This is a kludge to prevent
5889  * get_relation_info() from fetching index info, which is necessary
5890  * because it does not expect that any IndexOptInfo is currently
5891  * undergoing REINDEX.
5892  */
5893  rte = makeNode(RangeTblEntry);
5894  rte->rtekind = RTE_RELATION;
5895  rte->relid = tableOid;
5896  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
5898  rte->lateral = false;
5899  rte->inh = true;
5900  rte->inFromCl = true;
5901  query->rtable = list_make1(rte);
5902 
5903  /* Set up RTE/RelOptInfo arrays */
5905 
5906  /* Build RelOptInfo */
5907  rel = build_simple_rel(root, 1, NULL);
5908 
5909  /* Rels are assumed already locked by the caller */
5910  heap = table_open(tableOid, NoLock);
5911  index = index_open(indexOid, NoLock);
5912 
5913  /*
5914  * Determine if it's safe to proceed.
5915  *
5916  * Currently, parallel workers can't access the leader's temporary tables.
5917  * Furthermore, any index predicate or index expressions must be parallel
5918  * safe.
5919  */
5920  if (heap->rd_rel->relpersistence == RELPERSISTENCE_TEMP ||
5921  !is_parallel_safe(root, (Node *) RelationGetIndexExpressions(index)) ||
5922  !is_parallel_safe(root, (Node *) RelationGetIndexPredicate(index)))
5923  {
5924  parallel_workers = 0;
5925  goto done;
5926  }
5927 
5928  /*
5929  * If parallel_workers storage parameter is set for the table, accept that
5930  * as the number of parallel worker processes to launch (though still cap
5931  * at max_parallel_maintenance_workers). Note that we deliberately do not
5932  * consider any other factor when parallel_workers is set. (e.g., memory
5933  * use by workers.)
5934  */
5935  if (rel->rel_parallel_workers != -1)
5936  {
5937  parallel_workers = Min(rel->rel_parallel_workers,
5939  goto done;
5940  }
5941 
5942  /*
5943  * Estimate heap relation size ourselves, since rel->pages cannot be
5944  * trusted (heap RTE was marked as inheritance parent)
5945  */
5946  estimate_rel_size(heap, NULL, &heap_blocks, &reltuples, &allvisfrac);
5947 
5948  /*
5949  * Determine number of workers to scan the heap relation using generic
5950  * model
5951  */
5952  parallel_workers = compute_parallel_worker(rel, heap_blocks, -1,
5954 
5955  /*
5956  * Cap workers based on available maintenance_work_mem as needed.
5957  *
5958  * Note that each tuplesort participant receives an even share of the
5959  * total maintenance_work_mem budget. Aim to leave participants
5960  * (including the leader as a participant) with no less than 32MB of
5961  * memory. This leaves cases where maintenance_work_mem is set to 64MB
5962  * immediately past the threshold of being capable of launching a single
5963  * parallel worker to sort.
5964  */
5965  while (parallel_workers > 0 &&
5966  maintenance_work_mem / (parallel_workers + 1) < 32768L)
5967  parallel_workers--;
5968 
5969 done:
5970  index_close(index, NoLock);
5971  table_close(heap, NoLock);
5972 
5973  return parallel_workers;
5974 }
Query * parse
Definition: pathnodes.h:161
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:3749
#define Min(x, y)
Definition: c.h:986
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:539
uint32 BlockNumber
Definition: block.h:31
Form_pg_class rd_rel
Definition: rel.h:109
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:4920
Definition: type.h:89
#define list_make1(x1)
Definition: pg_list.h:206
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:638
int wt_param_id
Definition: pathnodes.h:363
List * rtable
Definition: parsenodes.h:147
#define NoLock
Definition: lockdefs.h:34
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4807
PlannerGlobal * glob
Definition: pathnodes.h:163
bool IsUnderPostmaster
Definition: globals.c:112
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:194
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:959
int rel_parallel_workers
Definition: pathnodes.h:722
int max_parallel_maintenance_workers
Definition: globals.c:127
int maintenance_work_mem
Definition: globals.c:126
CmdType commandType
Definition: parsenodes.h:120
#define makeNode(_type_)
Definition: nodes.h:587
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:83
Index query_level
Definition: pathnodes.h:165
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
RTEKind rtekind
Definition: parsenodes.h:995
MemoryContext planner_cxt
Definition: pathnodes.h:334
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:539
#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:539
#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(), CreateTriggerFiringOn(), dependency_is_compatible_expression(), distribute_qual_to_rels(), estimate_num_groups(), find_computable_ec_member(), 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(), 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:192
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:186
#define PVC_INCLUDE_WINDOWFUNCS
Definition: optimizer.h:188
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:190
#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:189
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:187

◆ 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(), remove_unused_subquery_outputs(), and statext_is_compatible_clause().

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:3461

◆ 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:3461

◆ 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:3461

Variable Documentation

◆ cpu_index_tuple_cost

PGDLLIMPORT double cpu_index_tuple_cost

Definition at line 122 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 127 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 125 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 124 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