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 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  DebugParallelMode { DEBUG_PARALLEL_OFF , DEBUG_PARALLEL_ON , DEBUG_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)
 
long clamp_cardinality_to_long (Cardinality x)
 
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 (PlannerInfo *root, 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 double recursive_worktable_factor
 
PGDLLIMPORT int effective_cache_size
 
PGDLLIMPORT int debug_parallel_query
 
PGDLLIMPORT bool parallel_leader_participation
 

Macro Definition Documentation

◆ HAVE_INDEXOPTINFO_TYPEDEF

#define HAVE_INDEXOPTINFO_TYPEDEF   1

Definition at line 41 of file optimizer.h.

◆ HAVE_PLANNERINFO_TYPEDEF

#define HAVE_PLANNERINFO_TYPEDEF   1

Definition at line 35 of file optimizer.h.

◆ HAVE_SPECIALJOININFO_TYPEDEF

#define HAVE_SPECIALJOININFO_TYPEDEF   1

Definition at line 45 of file optimizer.h.

◆ PVC_INCLUDE_AGGREGATES

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

Definition at line 183 of file optimizer.h.

◆ PVC_INCLUDE_PLACEHOLDERS

#define PVC_INCLUDE_PLACEHOLDERS
Value:
0x0010 /* include PlaceHolderVars in
* output list */

Definition at line 187 of file optimizer.h.

◆ PVC_INCLUDE_WINDOWFUNCS

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

Definition at line 185 of file optimizer.h.

◆ PVC_RECURSE_AGGREGATES

#define PVC_RECURSE_AGGREGATES   0x0002 /* recurse into Aggref arguments */

Definition at line 184 of file optimizer.h.

◆ PVC_RECURSE_PLACEHOLDERS

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

Definition at line 188 of file optimizer.h.

◆ PVC_RECURSE_WINDOWFUNCS

#define PVC_RECURSE_WINDOWFUNCS   0x0008 /* recurse into WindowFunc arguments */

Definition at line 186 of file optimizer.h.

Typedef Documentation

◆ IndexOptInfo

typedef struct IndexOptInfo IndexOptInfo

Definition at line 1 of file optimizer.h.

◆ PlannerInfo

typedef struct PlannerInfo PlannerInfo

Definition at line 1 of file optimizer.h.

◆ SpecialJoinInfo

Definition at line 1 of file optimizer.h.

Enumeration Type Documentation

◆ DebugParallelMode

Enumerator
DEBUG_PARALLEL_OFF 
DEBUG_PARALLEL_ON 
DEBUG_PARALLEL_REGRESS 

Definition at line 103 of file optimizer.h.

104 {
DebugParallelMode
Definition: optimizer.h:104
@ DEBUG_PARALLEL_REGRESS
Definition: optimizer.h:107
@ DEBUG_PARALLEL_ON
Definition: optimizer.h:106
@ DEBUG_PARALLEL_OFF
Definition: optimizer.h:105

Function Documentation

◆ canonicalize_qual()

Expr* canonicalize_qual ( Expr qual,
bool  is_check 
)

Definition at line 294 of file prepqual.c.

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 }
Assert(fmt[strlen(fmt) - 1] !='\n')
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
static Expr * find_duplicate_ors(Expr *qual, bool is_check)
Definition: prepqual.c:407
Definition: pg_list.h:54

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

◆ clamp_cardinality_to_long()

long clamp_cardinality_to_long ( Cardinality  x)

Definition at line 226 of file costsize.c.

227 {
228  /*
229  * Just for paranoia's sake, ensure we do something sane with negative or
230  * NaN values.
231  */
232  if (isnan(x))
233  return LONG_MAX;
234  if (x <= 0)
235  return 0;
236 
237  /*
238  * If "long" is 64 bits, then LONG_MAX cannot be represented exactly as a
239  * double. Casting it to double and back may well result in overflow due
240  * to rounding, so avoid doing that. We trust that any double value that
241  * compares strictly less than "(double) LONG_MAX" will cast to a
242  * representable "long" value.
243  */
244  return (x < (double) LONG_MAX) ? (long) x : LONG_MAX;
245 }
int x
Definition: isn.c:71

References x.

Referenced by buildSubPlanHash(), create_recursiveunion_plan(), create_setop_plan(), and make_agg().

◆ clamp_row_est()

double clamp_row_est ( double  nrows)

Definition at line 203 of file costsize.c.

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

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(), cost_subqueryscan(), 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_cte_size_estimates(), set_foreign_size(), system_rows_samplescangetsamplesize(), system_samplescangetsamplesize(), and system_time_samplescangetsamplesize().

◆ clause_selectivity()

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

Definition at line 669 of file clausesel.c.

674 {
675  return clause_selectivity_ext(root, clause, varRelid,
676  jointype, sjinfo, true);
677 }
Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats)
Definition: clausesel.c:686

References clause_selectivity_ext().

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

◆ clause_selectivity_ext()

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

Definition at line 686 of file clausesel.c.

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

References arg, generate_unaccent_rules::args, FuncExpr::args, OpExpr::args, bms_is_member(), booltestsel(), boolvarsel(), RestrictInfo::clause, clauselist_selectivity_ext(), clauselist_selectivity_or(), CurrentOfExpr::cvarno, DatumGetBool(), DEBUG4, elog(), estimate_expression_value(), find_base_rel(), FuncExpr::funcid, function_selectivity(), get_notclausearg(), is_andclause(), is_funcclause(), is_notclause(), is_opclause(), is_orclause(), IsA, JOIN_INNER, join_selectivity(), nulltestsel(), OpExpr::opno, restriction_selectivity(), rowcomparesel(), s1, scalararraysel(), treat_as_join_clause(), RelOptInfo::tuples, and RangeQueryClause::var.

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

◆ clauselist_selectivity()

◆ 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.

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 = (rinfo->num_base_rels == 1) &&
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 }
int NumRelids(PlannerInfo *root, Node *clause)
Definition: clauses.c:2047
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:2005
bool is_pseudo_constant_clause_relids(Node *clause, Relids relids)
Definition: clauses.c:2025
static void addRangeClause(RangeQueryClause **rqlist, Node *clause, bool varonleft, bool isLTsel, Selectivity s2)
Definition: clausesel.c:429
static RelOptInfo * find_single_rel_for_clauses(PlannerInfo *root, List *clauses)
Definition: clausesel.c:525
Selectivity statext_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, RelOptInfo *rel, Bitmapset **estimatedclauses, bool is_or)
RegProcedure get_oprrest(Oid opno)
Definition: lsyscache.c:1539
void pfree(void *pointer)
Definition: mcxt.c:1456
@ RTE_RELATION
Definition: parsenodes.h:1014
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define linitial(l)
Definition: pg_list.h:178
#define lsecond(l)
Definition: pg_list.h:183
char * s2
@ IS_NULL
Definition: primnodes.h:1677
#define DEFAULT_RANGE_INEQ_SEL
Definition: selfuncs.h:40
#define DEFAULT_INEQ_SEL
Definition: selfuncs.h:37
Selectivity hibound
Definition: clausesel.c:40
Selectivity lobound
Definition: clausesel.c:39
struct RangeQueryClause * next
Definition: clausesel.c:35
List * statlist
Definition: pathnodes.h:925
RTEKind rtekind
Definition: pathnodes.h:907

References addRangeClause(), generate_unaccent_rules::args, OpExpr::args, bms_is_member(), RestrictInfo::clause, 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, lfirst, linitial, list_length(), RangeQueryClause::lobound, lsecond, RangeQueryClause::next, NIL, nulltestsel(), NumRelids(), OpExpr::opno, pfree(), 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().

◆ 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 441 of file var.c.

442 {
443  int sublevels_up = levelsup;
444 
447  (void *) &sublevels_up,
448  0);
449 }
#define query_or_expression_tree_walker(n, w, c, f)
Definition: nodeFuncs.h:169
static bool contain_vars_of_level_walker(Node *node, int *sublevels_up)
Definition: var.c:452

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(), rewriteRuleAction(), transformAExprIn(), transformRangeFunction(), transformRangeTableFunc(), transformSetOperationTree(), and transformValuesClause().

◆ contain_volatile_functions()

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 590 of file clauses.c.

591 {
593 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:603

References contain_volatile_functions_not_nextval_walker().

Referenced by BeginCopyFrom().

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2204 of file clauses.c.

2205 {
2206  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2207 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2210

References convert_saop_to_hashed_saop_walker().

Referenced by preprocess_expression().

◆ count_nonjunk_tlist_entries()

int count_nonjunk_tlist_entries ( List tlist)

Definition at line 186 of file tlist.c.

187 {
188  int len = 0;
189  ListCell *l;
190 
191  foreach(l, tlist)
192  {
193  TargetEntry *tle = (TargetEntry *) lfirst(l);
194 
195  if (!tle->resjunk)
196  len++;
197  }
198  return len;
199 }
const void size_t len

References len, and lfirst.

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

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2312 of file clauses.c.

2313 {
2315 
2316  context.boundParams = root->glob->boundParams; /* bound Params */
2317  /* we do not need to mark the plan as depending on inlined functions */
2318  context.root = NULL;
2319  context.active_fns = NIL; /* nothing being recursively simplified */
2320  context.case_val = NULL; /* no CASE being examined */
2321  context.estimate = true; /* unsafe transformations OK */
2322  return eval_const_expressions_mutator(node, &context);
2323 }
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2357
PlannerGlobal * glob
Definition: pathnodes.h:202
ParamListInfo boundParams
Definition: clauses.c:63

References eval_const_expressions_context::active_fns, eval_const_expressions_context::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().

◆ eval_const_expressions()

◆ evaluate_expr()

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

Definition at line 4879 of file clauses.c.

4881 {
4882  EState *estate;
4883  ExprState *exprstate;
4884  MemoryContext oldcontext;
4885  Datum const_val;
4886  bool const_is_null;
4887  int16 resultTypLen;
4888  bool resultTypByVal;
4889 
4890  /*
4891  * To use the executor, we need an EState.
4892  */
4893  estate = CreateExecutorState();
4894 
4895  /* We can use the estate's working context to avoid memory leaks. */
4896  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4897 
4898  /* Make sure any opfuncids are filled in. */
4899  fix_opfuncids((Node *) expr);
4900 
4901  /*
4902  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4903  * because it'd result in recursively invoking eval_const_expressions.)
4904  */
4905  exprstate = ExecInitExpr(expr, NULL);
4906 
4907  /*
4908  * And evaluate it.
4909  *
4910  * It is OK to use a default econtext because none of the ExecEvalExpr()
4911  * code used in this situation will use econtext. That might seem
4912  * fortuitous, but it's not so unreasonable --- a constant expression does
4913  * not depend on context, by definition, n'est ce pas?
4914  */
4915  const_val = ExecEvalExprSwitchContext(exprstate,
4916  GetPerTupleExprContext(estate),
4917  &const_is_null);
4918 
4919  /* Get info needed about result datatype */
4920  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4921 
4922  /* Get back to outer memory context */
4923  MemoryContextSwitchTo(oldcontext);
4924 
4925  /*
4926  * Must copy result out of sub-context used by expression eval.
4927  *
4928  * Also, if it's varlena, forcibly detoast it. This protects us against
4929  * storing TOAST pointers into plans that might outlive the referenced
4930  * data. (makeConst would handle detoasting anyway, but it's worth a few
4931  * extra lines here so that we can do the copy and detoast in one step.)
4932  */
4933  if (!const_is_null)
4934  {
4935  if (resultTypLen == -1)
4936  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4937  else
4938  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4939  }
4940 
4941  /* Release all the junk we just created */
4942  FreeExecutorState(estate);
4943 
4944  /*
4945  * Make the constant result node.
4946  */
4947  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4948  resultTypLen,
4949  const_val, const_is_null,
4950  resultTypByVal);
4951 }
signed short int16
Definition: c.h:477
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:132
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:127
EState * CreateExecutorState(void)
Definition: execUtils.c:93
void FreeExecutorState(EState *estate)
Definition: execUtils.c:194
#define GetPerTupleExprContext(estate)
Definition: executor.h:549
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:347
#define PG_DETOAST_DATUM_COPY(datum)
Definition: fmgr.h:242
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2209
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition: makefuncs.c:302
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1750
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
uintptr_t Datum
Definition: postgres.h:64
MemoryContext es_query_cxt
Definition: execnodes.h:659

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

◆ 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 6431 of file planner.c.

6432 {
6433  Node *result;
6434 
6435  /*
6436  * Convert named-argument function calls, insert default arguments and
6437  * simplify constant subexprs
6438  */
6439  result = eval_const_expressions(NULL, (Node *) expr);
6440 
6441  /* Fill in opfuncid values if missing */
6442  fix_opfuncids(result);
6443 
6444  return (Expr *) result;
6445 }
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2171

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

◆ expression_planner_with_deps()

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

Definition at line 6458 of file planner.c.

6461 {
6462  Node *result;
6463  PlannerGlobal glob;
6464  PlannerInfo root;
6465 
6466  /* Make up dummy planner state so we can use setrefs machinery */
6467  MemSet(&glob, 0, sizeof(glob));
6468  glob.type = T_PlannerGlobal;
6469  glob.relationOids = NIL;
6470  glob.invalItems = NIL;
6471 
6472  MemSet(&root, 0, sizeof(root));
6473  root.type = T_PlannerInfo;
6474  root.glob = &glob;
6475 
6476  /*
6477  * Convert named-argument function calls, insert default arguments and
6478  * simplify constant subexprs. Collect identities of inlined functions
6479  * and elided domains, too.
6480  */
6481  result = eval_const_expressions(&root, (Node *) expr);
6482 
6483  /* Fill in opfuncid values if missing */
6484  fix_opfuncids(result);
6485 
6486  /*
6487  * Now walk the finished expression to find anything else we ought to
6488  * record as an expression dependency.
6489  */
6490  (void) extract_query_dependencies_walker(result, &root);
6491 
6492  *relationOids = glob.relationOids;
6493  *invalItems = glob.invalItems;
6494 
6495  return (Expr *) result;
6496 }
#define MemSet(start, val, len)
Definition: c.h:1004
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3525
List * invalItems
Definition: pathnodes.h:132
List * relationOids
Definition: pathnodes.h:129

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

Referenced by GetCachedExpression().

◆ extract_query_dependencies()

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

Definition at line 3489 of file setrefs.c.

3493 {
3494  PlannerGlobal glob;
3495  PlannerInfo root;
3496 
3497  /* Make up dummy planner state so we can use this module's machinery */
3498  MemSet(&glob, 0, sizeof(glob));
3499  glob.type = T_PlannerGlobal;
3500  glob.relationOids = NIL;
3501  glob.invalItems = NIL;
3502  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3503  glob.dependsOnRole = false;
3504 
3505  MemSet(&root, 0, sizeof(root));
3506  root.type = T_PlannerInfo;
3507  root.glob = &glob;
3508 
3509  (void) extract_query_dependencies_walker(query, &root);
3510 
3511  *relationOids = glob.relationOids;
3512  *invalItems = glob.invalItems;
3513  *hasRowSecurity = glob.dependsOnRole;
3514 }
bool dependsOnRole
Definition: pathnodes.h:150

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

Referenced by CompleteCachedPlan(), and RevalidateCachedQuery().

◆ flatten_join_alias_vars()

Node* flatten_join_alias_vars ( PlannerInfo root,
Query query,
Node node 
)

Definition at line 744 of file var.c.

745 {
747 
748  /*
749  * We do not expect this to be applied to the whole Query, only to
750  * expressions or LATERAL subqueries. Hence, if the top node is a Query,
751  * it's okay to immediately increment sublevels_up.
752  */
753  Assert(node != (Node *) query);
754 
755  context.root = root;
756  context.query = query;
757  context.sublevels_up = 0;
758  /* flag whether join aliases could possibly contain SubLinks */
759  context.possible_sublink = query->hasSubLinks;
760  /* if hasSubLinks is already true, no need to work hard */
761  context.inserted_sublink = query->hasSubLinks;
762 
763  return flatten_join_alias_vars_mutator(node, &context);
764 }
PlannerInfo * root
Definition: var.c:65
static Node * flatten_join_alias_vars_mutator(Node *node, flatten_join_alias_vars_context *context)
Definition: var.c:767

References Assert(), flatten_join_alias_vars_mutator(), flatten_join_alias_vars_context::inserted_sublink, flatten_join_alias_vars_context::possible_sublink, flatten_join_alias_vars_context::query, flatten_join_alias_vars_context::root, and flatten_join_alias_vars_context::sublevels_up.

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

◆ get_sortgroupclause_expr()

Node* get_sortgroupclause_expr ( SortGroupClause sgClause,
List targetList 
)

Definition at line 379 of file tlist.c.

380 {
381  TargetEntry *tle = get_sortgroupclause_tle(sgClause, targetList);
382 
383  return (Node *) tle->expr;
384 }
Expr * expr
Definition: primnodes.h:1886
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:367

References TargetEntry::expr, and get_sortgroupclause_tle().

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

◆ get_sortgroupclause_tle()

◆ get_sortgrouplist_exprs()

List* get_sortgrouplist_exprs ( List sgClauses,
List targetList 
)

Definition at line 392 of file tlist.c.

393 {
394  List *result = NIL;
395  ListCell *l;
396 
397  foreach(l, sgClauses)
398  {
399  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
400  Node *sortexpr;
401 
402  sortexpr = get_sortgroupclause_expr(sortcl, targetList);
403  result = lappend(result, sortexpr);
404  }
405  return result;
406 }
List * lappend(List *list, void *datum)
Definition: list.c:338
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

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

Referenced by create_final_distinct_paths(), create_partial_distinct_paths(), estimate_path_cost_size(), get_number_of_groups(), and group_by_has_partkey().

◆ get_sortgroupref_clause()

SortGroupClause* get_sortgroupref_clause ( Index  sortref,
List clauses 
)

Definition at line 422 of file tlist.c.

423 {
424  ListCell *l;
425 
426  foreach(l, clauses)
427  {
429 
430  if (cl->tleSortGroupRef == sortref)
431  return cl;
432  }
433 
434  elog(ERROR, "ORDER/GROUP BY expression not found in list");
435  return NULL; /* keep compiler quiet */
436 }
#define ERROR
Definition: elog.h:39

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

Referenced by preprocess_groupclause().

◆ get_sortgroupref_clause_noerr()

SortGroupClause* get_sortgroupref_clause_noerr ( Index  sortref,
List clauses 
)

Definition at line 443 of file tlist.c.

444 {
445  ListCell *l;
446 
447  foreach(l, clauses)
448  {
450 
451  if (cl->tleSortGroupRef == sortref)
452  return cl;
453  }
454 
455  return NULL;
456 }

References lfirst, and SortGroupClause::tleSortGroupRef.

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

◆ get_sortgroupref_tle()

TargetEntry* get_sortgroupref_tle ( Index  sortref,
List targetList 
)

Definition at line 345 of file tlist.c.

346 {
347  ListCell *l;
348 
349  foreach(l, targetList)
350  {
351  TargetEntry *tle = (TargetEntry *) lfirst(l);
352 
353  if (tle->ressortgroupref == sortref)
354  return tle;
355  }
356 
357  elog(ERROR, "ORDER/GROUP BY expression not found in targetlist");
358  return NULL; /* keep compiler quiet */
359 }
Index ressortgroupref
Definition: primnodes.h:1892

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

◆ is_pseudo_constant_for_index()

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

Definition at line 3799 of file indxpath.c.

3800 {
3801  /* pull_varnos is cheaper than volatility check, so do that first */
3802  if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
3803  return false; /* no good, contains Var of table */
3804  if (contain_volatile_functions(expr))
3805  return false; /* no good, volatile comparison value */
3806  return true;
3807 }
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:483
Definition: type.h:95
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:108

References bms_is_member(), contain_volatile_functions(), and pull_varnos().

◆ locate_var_of_level()

int locate_var_of_level ( Node node,
int  levelsup 
)

Definition at line 509 of file var.c.

510 {
512 
513  context.var_location = -1; /* in case we find nothing */
514  context.sublevels_up = levelsup;
515 
518  (void *) &context,
519  0);
520 
521  return context.var_location;
522 }
static bool locate_var_of_level_walker(Node *node, locate_var_of_level_context *context)
Definition: var.c:525

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

◆ negate_clause()

Node* negate_clause ( Node node)

Definition at line 74 of file prepqual.c.

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 }
Oid get_negator(Oid opno)
Definition: lsyscache.c:1515
Expr * make_notclause(Expr *notclause)
Definition: makefuncs.c:671
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:639
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:360
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:655
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define makeNode(_type_)
Definition: nodes.h:176
#define InvalidOid
Definition: postgres_ext.h:36
Node * negate_clause(Node *node)
Definition: prepqual.c:74
char * c
@ IS_NOT_TRUE
Definition: primnodes.h:1701
@ IS_NOT_FALSE
Definition: primnodes.h:1701
@ IS_NOT_UNKNOWN
Definition: primnodes.h:1701
@ IS_TRUE
Definition: primnodes.h:1701
@ IS_UNKNOWN
Definition: primnodes.h:1701
@ IS_FALSE
Definition: primnodes.h:1701
@ AND_EXPR
Definition: primnodes.h:858
@ OR_EXPR
Definition: primnodes.h:858
@ NOT_EXPR
Definition: primnodes.h:858
@ IS_NOT_NULL
Definition: primnodes.h:1677
BoolExprType boolop
Definition: primnodes.h:866
List * args
Definition: primnodes.h:867
BoolTestType booltesttype
Definition: primnodes.h:1708
Expr * arg
Definition: primnodes.h:1707
NullTestType nulltesttype
Definition: primnodes.h:1684
int location
Definition: primnodes.h:1687
Expr * arg
Definition: primnodes.h:1683
int location
Definition: primnodes.h:766

References AND_EXPR, NullTest::arg, BooleanTest::arg, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, BoolExpr::boolop, BooleanTest::booltesttype, DatumGetBool(), elog(), ERROR, get_negator(), 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, NIL, nodeTag, NOT_EXPR, NullTest::nulltesttype, OpExpr::opno, ScalarArrayOpExpr::opno, OR_EXPR, and ScalarArrayOpExpr::useOr.

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

◆ plan_cluster_use_sort()

bool plan_cluster_use_sort ( Oid  tableOid,
Oid  indexOid 
)

Definition at line 6511 of file planner.c.

6512 {
6513  PlannerInfo *root;
6514  Query *query;
6515  PlannerGlobal *glob;
6516  RangeTblEntry *rte;
6517  RelOptInfo *rel;
6518  IndexOptInfo *indexInfo;
6519  QualCost indexExprCost;
6520  Cost comparisonCost;
6521  Path *seqScanPath;
6522  Path seqScanAndSortPath;
6523  IndexPath *indexScanPath;
6524  ListCell *lc;
6525 
6526  /* We can short-circuit the cost comparison if indexscans are disabled */
6527  if (!enable_indexscan)
6528  return true; /* use sort */
6529 
6530  /* Set up mostly-dummy planner state */
6531  query = makeNode(Query);
6532  query->commandType = CMD_SELECT;
6533 
6534  glob = makeNode(PlannerGlobal);
6535 
6536  root = makeNode(PlannerInfo);
6537  root->parse = query;
6538  root->glob = glob;
6539  root->query_level = 1;
6540  root->planner_cxt = CurrentMemoryContext;
6541  root->wt_param_id = -1;
6543 
6544  /* Build a minimal RTE for the rel */
6545  rte = makeNode(RangeTblEntry);
6546  rte->rtekind = RTE_RELATION;
6547  rte->relid = tableOid;
6548  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6550  rte->lateral = false;
6551  rte->inh = false;
6552  rte->inFromCl = true;
6553  query->rtable = list_make1(rte);
6554  addRTEPermissionInfo(&query->rteperminfos, rte);
6555 
6556  /* Set up RTE/RelOptInfo arrays */
6558 
6559  /* Build RelOptInfo */
6560  rel = build_simple_rel(root, 1, NULL);
6561 
6562  /* Locate IndexOptInfo for the target index */
6563  indexInfo = NULL;
6564  foreach(lc, rel->indexlist)
6565  {
6566  indexInfo = lfirst_node(IndexOptInfo, lc);
6567  if (indexInfo->indexoid == indexOid)
6568  break;
6569  }
6570 
6571  /*
6572  * It's possible that get_relation_info did not generate an IndexOptInfo
6573  * for the desired index; this could happen if it's not yet reached its
6574  * indcheckxmin usability horizon, or if it's a system index and we're
6575  * ignoring system indexes. In such cases we should tell CLUSTER to not
6576  * trust the index contents but use seqscan-and-sort.
6577  */
6578  if (lc == NULL) /* not in the list? */
6579  return true; /* use sort */
6580 
6581  /*
6582  * Rather than doing all the pushups that would be needed to use
6583  * set_baserel_size_estimates, just do a quick hack for rows and width.
6584  */
6585  rel->rows = rel->tuples;
6586  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6587 
6588  root->total_table_pages = rel->pages;
6589 
6590  /*
6591  * Determine eval cost of the index expressions, if any. We need to
6592  * charge twice that amount for each tuple comparison that happens during
6593  * the sort, since tuplesort.c will have to re-evaluate the index
6594  * expressions each time. (XXX that's pretty inefficient...)
6595  */
6596  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6597  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6598 
6599  /* Estimate the cost of seq scan + sort */
6600  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6601  cost_sort(&seqScanAndSortPath, root, NIL,
6602  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6603  comparisonCost, maintenance_work_mem, -1.0);
6604 
6605  /* Estimate the cost of index scan */
6606  indexScanPath = create_index_path(root, indexInfo,
6607  NIL, NIL, NIL, NIL,
6608  ForwardScanDirection, false,
6609  NULL, 1.0, false);
6610 
6611  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6612 }
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4371
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:2096
bool enable_indexscan
Definition: costsize.c:136
int maintenance_work_mem
Definition: globals.c:127
#define AccessShareLock
Definition: lockdefs.h:36
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
double Cost
Definition: nodes.h:262
@ CMD_SELECT
Definition: nodes.h:276
RTEPermissionInfo * addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
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:995
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:929
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define list_make1(x1)
Definition: pg_list.h:212
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1180
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:93
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:191
@ ForwardScanDirection
Definition: sdir.h:28
Path path
Definition: pathnodes.h:1677
Cost total_cost
Definition: pathnodes.h:1630
Index query_level
Definition: pathnodes.h:205
List * join_domains
Definition: pathnodes.h:308
int wt_param_id
Definition: pathnodes.h:521
Cardinality total_table_pages
Definition: pathnodes.h:475
Query * parse
Definition: pathnodes.h:199
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47
List * rtable
Definition: parsenodes.h:175
CmdType commandType
Definition: parsenodes.h:128
RTEKind rtekind
Definition: parsenodes.h:1033
struct PathTarget * reltarget
Definition: pathnodes.h:878
BlockNumber pages
Definition: pathnodes.h:927
List * indexlist
Definition: pathnodes.h:923
Cardinality rows
Definition: pathnodes.h:862

References AccessShareLock, addRTEPermissionInfo(), 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, RangeTblEntry::inFromCl, RangeTblEntry::inh, PlannerInfo::join_domains, RangeTblEntry::lateral, lfirst_node, list_make1, maintenance_work_mem, makeNode, NIL, RelOptInfo::pages, PlannerInfo::parse, IndexPath::path, QualCost::per_tuple, 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().

◆ plan_create_index_workers()

int plan_create_index_workers ( Oid  tableOid,
Oid  indexOid 
)

Definition at line 6631 of file planner.c.

6632 {
6633  PlannerInfo *root;
6634  Query *query;
6635  PlannerGlobal *glob;
6636  RangeTblEntry *rte;
6637  Relation heap;
6638  Relation index;
6639  RelOptInfo *rel;
6640  int parallel_workers;
6641  BlockNumber heap_blocks;
6642  double reltuples;
6643  double allvisfrac;
6644 
6645  /*
6646  * We don't allow performing parallel operation in standalone backend or
6647  * when parallelism is disabled.
6648  */
6650  return 0;
6651 
6652  /* Set up largely-dummy planner state */
6653  query = makeNode(Query);
6654  query->commandType = CMD_SELECT;
6655 
6656  glob = makeNode(PlannerGlobal);
6657 
6658  root = makeNode(PlannerInfo);
6659  root->parse = query;
6660  root->glob = glob;
6661  root->query_level = 1;
6662  root->planner_cxt = CurrentMemoryContext;
6663  root->wt_param_id = -1;
6665 
6666  /*
6667  * Build a minimal RTE.
6668  *
6669  * Mark the RTE with inh = true. This is a kludge to prevent
6670  * get_relation_info() from fetching index info, which is necessary
6671  * because it does not expect that any IndexOptInfo is currently
6672  * undergoing REINDEX.
6673  */
6674  rte = makeNode(RangeTblEntry);
6675  rte->rtekind = RTE_RELATION;
6676  rte->relid = tableOid;
6677  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6679  rte->lateral = false;
6680  rte->inh = true;
6681  rte->inFromCl = true;
6682  query->rtable = list_make1(rte);
6683  addRTEPermissionInfo(&query->rteperminfos, rte);
6684 
6685  /* Set up RTE/RelOptInfo arrays */
6687 
6688  /* Build RelOptInfo */
6689  rel = build_simple_rel(root, 1, NULL);
6690 
6691  /* Rels are assumed already locked by the caller */
6692  heap = table_open(tableOid, NoLock);
6693  index = index_open(indexOid, NoLock);
6694 
6695  /*
6696  * Determine if it's safe to proceed.
6697  *
6698  * Currently, parallel workers can't access the leader's temporary tables.
6699  * Furthermore, any index predicate or index expressions must be parallel
6700  * safe.
6701  */
6702  if (heap->rd_rel->relpersistence == RELPERSISTENCE_TEMP ||
6705  {
6706  parallel_workers = 0;
6707  goto done;
6708  }
6709 
6710  /*
6711  * If parallel_workers storage parameter is set for the table, accept that
6712  * as the number of parallel worker processes to launch (though still cap
6713  * at max_parallel_maintenance_workers). Note that we deliberately do not
6714  * consider any other factor when parallel_workers is set. (e.g., memory
6715  * use by workers.)
6716  */
6717  if (rel->rel_parallel_workers != -1)
6718  {
6719  parallel_workers = Min(rel->rel_parallel_workers,
6721  goto done;
6722  }
6723 
6724  /*
6725  * Estimate heap relation size ourselves, since rel->pages cannot be
6726  * trusted (heap RTE was marked as inheritance parent)
6727  */
6728  estimate_rel_size(heap, NULL, &heap_blocks, &reltuples, &allvisfrac);
6729 
6730  /*
6731  * Determine number of workers to scan the heap relation using generic
6732  * model
6733  */
6734  parallel_workers = compute_parallel_worker(rel, heap_blocks, -1,
6736 
6737  /*
6738  * Cap workers based on available maintenance_work_mem as needed.
6739  *
6740  * Note that each tuplesort participant receives an even share of the
6741  * total maintenance_work_mem budget. Aim to leave participants
6742  * (including the leader as a participant) with no less than 32MB of
6743  * memory. This leaves cases where maintenance_work_mem is set to 64MB
6744  * immediately past the threshold of being capable of launching a single
6745  * parallel worker to sort.
6746  */
6747  while (parallel_workers > 0 &&
6748  maintenance_work_mem / (parallel_workers + 1) < 32768L)
6749  parallel_workers--;
6750 
6751 done:
6753  table_close(heap, NoLock);
6754 
6755  return parallel_workers;
6756 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4210
uint32 BlockNumber
Definition: block.h:31
#define Min(x, y)
Definition: c.h:988
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:670
int max_parallel_maintenance_workers
Definition: globals.c:128
bool IsUnderPostmaster
Definition: globals.c:113
void index_close(Relation relation, LOCKMODE lockmode)
Definition: indexam.c:158
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition: indexam.c:132
#define NoLock
Definition: lockdefs.h:34
void estimate_rel_size(Relation rel, int32 *attr_widths, BlockNumber *pages, double *tuples, double *allvisfrac)
Definition: plancat.c:1013
List * RelationGetIndexPredicate(Relation relation)
Definition: relcache.c:5086
List * RelationGetIndexExpressions(Relation relation)
Definition: relcache.c:4973
int rel_parallel_workers
Definition: pathnodes.h:935
Form_pg_class rd_rel
Definition: rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References AccessShareLock, addRTEPermissionInfo(), 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, PlannerInfo::join_domains, RangeTblEntry::lateral, list_make1, maintenance_work_mem, makeNode, max_parallel_maintenance_workers, Min, NoLock, PlannerInfo::parse, 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().

◆ 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 152 of file predtest.c.

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

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

◆ predicate_refuted_by()

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

Definition at line 222 of file predtest.c.

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

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

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

◆ pull_var_clause()

List* pull_var_clause ( Node node,
int  flags 
)

Definition at line 607 of file var.c.

608 {
609  pull_var_clause_context context;
610 
611  /* Assert that caller has not specified inconsistent flags */
618 
619  context.varlist = NIL;
620  context.flags = flags;
621 
622  pull_var_clause_walker(node, &context);
623  return context.varlist;
624 }
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:184
#define PVC_RECURSE_PLACEHOLDERS
Definition: optimizer.h:188
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:186
#define PVC_INCLUDE_WINDOWFUNCS
Definition: optimizer.h:185
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:187
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:183
static bool pull_var_clause_walker(Node *node, pull_var_clause_context *context)
Definition: var.c:627

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 add_paths_with_pathkeys_for_rel(), AddRelationNewConstraints(), build_base_rel_tlists(), build_remote_returning(), build_tlist_to_deparse(), CreateTriggerFiringOn(), 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().

◆ pull_varattnos()

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

◆ pull_varnos()

Bitmapset* pull_varnos ( PlannerInfo root,
Node node 
)

Definition at line 108 of file var.c.

109 {
110  pull_varnos_context context;
111 
112  context.varnos = NULL;
113  context.root = root;
114  context.sublevels_up = 0;
115 
116  /*
117  * Must be prepared to start with a Query or a bare expression tree; if
118  * it's a Query, we don't want to increment sublevels_up.
119  */
122  (void *) &context,
123  0);
124 
125  return context.varnos;
126 }
PlannerInfo * root
Definition: var.c:35
int sublevels_up
Definition: var.c:36
Relids varnos
Definition: var.c:34
static bool pull_varnos_walker(Node *node, pull_varnos_context *context)
Definition: var.c:155

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(), pg_get_expr_worker(), process_implied_equality(), and remove_rel_from_query().

◆ pull_varnos_of_level()

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

Definition at line 134 of file var.c.

135 {
136  pull_varnos_context context;
137 
138  context.varnos = NULL;
139  context.root = root;
140  context.sublevels_up = levelsup;
141 
142  /*
143  * Must be prepared to start with a Query or a bare expression tree; if
144  * it's a Query, we don't want to increment sublevels_up.
145  */
148  (void *) &context,
149  0);
150 
151  return context.varnos;
152 }

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 add_nullingrels_if_needed(), is_simple_subquery(), and jointree_contains_lateral_outer_refs().

◆ pull_vars_of_level()

List* pull_vars_of_level ( Node node,
int  levelsup 
)

Definition at line 335 of file var.c.

336 {
337  pull_vars_context context;
338 
339  context.vars = NIL;
340  context.sublevels_up = levelsup;
341 
342  /*
343  * Must be prepared to start with a Query or a bare expression tree; if
344  * it's a Query, we don't want to increment sublevels_up.
345  */
348  (void *) &context,
349  0);
350 
351  return context.vars;
352 }
int sublevels_up
Definition: var.c:48
List * vars
Definition: var.c:47
static bool pull_vars_walker(Node *node, pull_vars_context *context)
Definition: var.c:355

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

Variable Documentation

◆ cpu_index_tuple_cost

PGDLLIMPORT double cpu_index_tuple_cost
extern

Definition at line 123 of file costsize.c.

Referenced by genericcostestimate(), and gincostestimate().

◆ cpu_operator_cost

◆ cpu_tuple_cost

◆ debug_parallel_query

PGDLLIMPORT int debug_parallel_query
extern

Definition at line 73 of file planner.c.

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

◆ effective_cache_size

PGDLLIMPORT int effective_cache_size
extern

Definition at line 129 of file costsize.c.

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

◆ parallel_leader_participation

PGDLLIMPORT bool parallel_leader_participation
extern

Definition at line 74 of file planner.c.

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

◆ parallel_setup_cost

PGDLLIMPORT double parallel_setup_cost
extern

Definition at line 126 of file costsize.c.

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

◆ parallel_tuple_cost

PGDLLIMPORT double parallel_tuple_cost
extern

Definition at line 125 of file costsize.c.

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

◆ random_page_cost

PGDLLIMPORT double random_page_cost
extern

◆ recursive_worktable_factor

PGDLLIMPORT double recursive_worktable_factor
extern

Definition at line 127 of file costsize.c.

Referenced by set_cte_size_estimates().

◆ seq_page_cost