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  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)
 
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 force_parallel_mode
 
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

◆ ForceParallelMode

Enumerator
FORCE_PARALLEL_OFF 
FORCE_PARALLEL_ON 
FORCE_PARALLEL_REGRESS 

Definition at line 103 of file optimizer.h.

104 {
ForceParallelMode
Definition: optimizer.h:104
@ FORCE_PARALLEL_ON
Definition: optimizer.h:106
@ FORCE_PARALLEL_OFF
Definition: optimizer.h:105
@ FORCE_PARALLEL_REGRESS
Definition: optimizer.h:107

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

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

203 {
204  /*
205  * Avoid infinite and NaN row estimates. Costs derived from such values
206  * are going to be useless. Also force the estimate to be at least one
207  * row, to make explain output look better and to avoid possible
208  * divide-by-zero when interpolating costs. Make it an integer, too.
209  */
210  if (nrows > MAXIMUM_ROWCOUNT || isnan(nrows))
211  nrows = MAXIMUM_ROWCOUNT;
212  else if (nrows <= 1.0)
213  nrows = 1.0;
214  else
215  nrows = rint(nrows);
216 
217  return nrows;
218 }
#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:428
Node * estimate_expression_value(PlannerInfo *root, Node *node)
Definition: clauses.c:2275
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:393
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:674
List * args
Definition: primnodes.h:692
Definition: nodes.h:129
Oid opno
Definition: primnodes.h:742
List * args
Definition: primnodes.h:760
Cardinality tuples
Definition: pathnodes.h:938
Expr * clause
Definition: pathnodes.h:2517
Definition: primnodes.h:223
int varno
Definition: primnodes.h:230
Index varlevelsup
Definition: primnodes.h:255

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:2010
bool is_pseudo_constant_clause(Node *clause)
Definition: clauses.c:1968
bool is_pseudo_constant_clause_relids(Node *clause, Relids relids)
Definition: clauses.c:1988
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:1436
@ RTE_RELATION
Definition: parsenodes.h:1013
#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:1513
#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:935
RTEKind rtekind
Definition: pathnodes.h:917

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(), 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 555 of file clauses.c.

556 {
558 }
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition: clauses.c:568

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 2167 of file clauses.c.

2168 {
2169  (void) convert_saop_to_hashed_saop_walker(node, NULL);
2170 }
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition: clauses.c:2173

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(), transformMultiAssignRef(), and transformSubLink().

◆ estimate_expression_value()

Node* estimate_expression_value ( PlannerInfo root,
Node node 
)

Definition at line 2275 of file clauses.c.

2276 {
2278 
2279  context.boundParams = root->glob->boundParams; /* bound Params */
2280  /* we do not need to mark the plan as depending on inlined functions */
2281  context.root = NULL;
2282  context.active_fns = NIL; /* nothing being recursively simplified */
2283  context.case_val = NULL; /* no CASE being examined */
2284  context.estimate = true; /* unsafe transformations OK */
2285  return eval_const_expressions_mutator(node, &context);
2286 }
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition: clauses.c:2320
PlannerGlobal * glob
Definition: pathnodes.h:205
ParamListInfo boundParams
Definition: clauses.c:61

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 4809 of file clauses.c.

4811 {
4812  EState *estate;
4813  ExprState *exprstate;
4814  MemoryContext oldcontext;
4815  Datum const_val;
4816  bool const_is_null;
4817  int16 resultTypLen;
4818  bool resultTypByVal;
4819 
4820  /*
4821  * To use the executor, we need an EState.
4822  */
4823  estate = CreateExecutorState();
4824 
4825  /* We can use the estate's working context to avoid memory leaks. */
4826  oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4827 
4828  /* Make sure any opfuncids are filled in. */
4829  fix_opfuncids((Node *) expr);
4830 
4831  /*
4832  * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4833  * because it'd result in recursively invoking eval_const_expressions.)
4834  */
4835  exprstate = ExecInitExpr(expr, NULL);
4836 
4837  /*
4838  * And evaluate it.
4839  *
4840  * It is OK to use a default econtext because none of the ExecEvalExpr()
4841  * code used in this situation will use econtext. That might seem
4842  * fortuitous, but it's not so unreasonable --- a constant expression does
4843  * not depend on context, by definition, n'est ce pas?
4844  */
4845  const_val = ExecEvalExprSwitchContext(exprstate,
4846  GetPerTupleExprContext(estate),
4847  &const_is_null);
4848 
4849  /* Get info needed about result datatype */
4850  get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4851 
4852  /* Get back to outer memory context */
4853  MemoryContextSwitchTo(oldcontext);
4854 
4855  /*
4856  * Must copy result out of sub-context used by expression eval.
4857  *
4858  * Also, if it's varlena, forcibly detoast it. This protects us against
4859  * storing TOAST pointers into plans that might outlive the referenced
4860  * data. (makeConst would handle detoasting anyway, but it's worth a few
4861  * extra lines here so that we can do the copy and detoast in one step.)
4862  */
4863  if (!const_is_null)
4864  {
4865  if (resultTypLen == -1)
4866  const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4867  else
4868  const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4869  }
4870 
4871  /* Release all the junk we just created */
4872  FreeExecutorState(estate);
4873 
4874  /*
4875  * Make the constant result node.
4876  */
4877  return (Expr *) makeConst(result_type, result_typmod, result_collation,
4878  resultTypLen,
4879  const_val, const_is_null,
4880  resultTypByVal);
4881 }
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:124
EState * CreateExecutorState(void)
Definition: execUtils.c:93
void FreeExecutorState(EState *estate)
Definition: execUtils.c:193
#define GetPerTupleExprContext(estate)
Definition: executor.h:538
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:336
#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:301
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1641
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:656

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

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

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

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

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 3477 of file setrefs.c.

3481 {
3482  PlannerGlobal glob;
3483  PlannerInfo root;
3484 
3485  /* Make up dummy planner state so we can use this module's machinery */
3486  MemSet(&glob, 0, sizeof(glob));
3487  glob.type = T_PlannerGlobal;
3488  glob.relationOids = NIL;
3489  glob.invalItems = NIL;
3490  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3491  glob.dependsOnRole = false;
3492 
3493  MemSet(&root, 0, sizeof(root));
3494  root.type = T_PlannerInfo;
3495  root.glob = &glob;
3496 
3497  (void) extract_query_dependencies_walker(query, &root);
3498 
3499  *relationOids = glob.relationOids;
3500  *invalItems = glob.invalItems;
3501  *hasRowSecurity = glob.dependsOnRole;
3502 }
bool dependsOnRole
Definition: pathnodes.h:153

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:1722
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:1728

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 3798 of file indxpath.c.

3799 {
3800  /* pull_varnos is cheaper than volatility check, so do that first */
3801  if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
3802  return false; /* no good, contains Var of table */
3803  if (contain_volatile_functions(expr))
3804  return false; /* no good, volatile comparison value */
3805  return true;
3806 }
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:448
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:670
Expr * make_andclause(List *andclauses)
Definition: makefuncs.c:638
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:359
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:654
#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:1537
@ IS_NOT_FALSE
Definition: primnodes.h:1537
@ IS_NOT_UNKNOWN
Definition: primnodes.h:1537
@ IS_TRUE
Definition: primnodes.h:1537
@ IS_UNKNOWN
Definition: primnodes.h:1537
@ IS_FALSE
Definition: primnodes.h:1537
@ AND_EXPR
Definition: primnodes.h:855
@ OR_EXPR
Definition: primnodes.h:855
@ NOT_EXPR
Definition: primnodes.h:855
@ IS_NOT_NULL
Definition: primnodes.h:1513
BoolExprType boolop
Definition: primnodes.h:863
List * args
Definition: primnodes.h:864
BoolTestType booltesttype
Definition: primnodes.h:1544
Expr * arg
Definition: primnodes.h:1543
NullTestType nulltesttype
Definition: primnodes.h:1520
int location
Definition: primnodes.h:1523
Expr * arg
Definition: primnodes.h:1519
int location
Definition: primnodes.h:763

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

6515 {
6516  PlannerInfo *root;
6517  Query *query;
6518  PlannerGlobal *glob;
6519  RangeTblEntry *rte;
6520  RelOptInfo *rel;
6521  IndexOptInfo *indexInfo;
6522  QualCost indexExprCost;
6523  Cost comparisonCost;
6524  Path *seqScanPath;
6525  Path seqScanAndSortPath;
6526  IndexPath *indexScanPath;
6527  ListCell *lc;
6528 
6529  /* We can short-circuit the cost comparison if indexscans are disabled */
6530  if (!enable_indexscan)
6531  return true; /* use sort */
6532 
6533  /* Set up mostly-dummy planner state */
6534  query = makeNode(Query);
6535  query->commandType = CMD_SELECT;
6536 
6537  glob = makeNode(PlannerGlobal);
6538 
6539  root = makeNode(PlannerInfo);
6540  root->parse = query;
6541  root->glob = glob;
6542  root->query_level = 1;
6543  root->planner_cxt = CurrentMemoryContext;
6544  root->wt_param_id = -1;
6546 
6547  /* Build a minimal RTE for the rel */
6548  rte = makeNode(RangeTblEntry);
6549  rte->rtekind = RTE_RELATION;
6550  rte->relid = tableOid;
6551  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6553  rte->lateral = false;
6554  rte->inh = false;
6555  rte->inFromCl = true;
6556  query->rtable = list_make1(rte);
6557  addRTEPermissionInfo(&query->rteperminfos, rte);
6558 
6559  /* Set up RTE/RelOptInfo arrays */
6561 
6562  /* Build RelOptInfo */
6563  rel = build_simple_rel(root, 1, NULL);
6564 
6565  /* Locate IndexOptInfo for the target index */
6566  indexInfo = NULL;
6567  foreach(lc, rel->indexlist)
6568  {
6569  indexInfo = lfirst_node(IndexOptInfo, lc);
6570  if (indexInfo->indexoid == indexOid)
6571  break;
6572  }
6573 
6574  /*
6575  * It's possible that get_relation_info did not generate an IndexOptInfo
6576  * for the desired index; this could happen if it's not yet reached its
6577  * indcheckxmin usability horizon, or if it's a system index and we're
6578  * ignoring system indexes. In such cases we should tell CLUSTER to not
6579  * trust the index contents but use seqscan-and-sort.
6580  */
6581  if (lc == NULL) /* not in the list? */
6582  return true; /* use sort */
6583 
6584  /*
6585  * Rather than doing all the pushups that would be needed to use
6586  * set_baserel_size_estimates, just do a quick hack for rows and width.
6587  */
6588  rel->rows = rel->tuples;
6589  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6590 
6591  root->total_table_pages = rel->pages;
6592 
6593  /*
6594  * Determine eval cost of the index expressions, if any. We need to
6595  * charge twice that amount for each tuple comparison that happens during
6596  * the sort, since tuplesort.c will have to re-evaluate the index
6597  * expressions each time. (XXX that's pretty inefficient...)
6598  */
6599  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6600  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6601 
6602  /* Estimate the cost of seq scan + sort */
6603  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6604  cost_sort(&seqScanAndSortPath, root, NIL,
6605  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6606  comparisonCost, maintenance_work_mem, -1.0);
6607 
6608  /* Estimate the cost of index scan */
6609  indexScanPath = create_index_path(root, indexInfo,
6610  NIL, NIL, NIL, NIL,
6611  ForwardScanDirection, false,
6612  NULL, 1.0, false);
6613 
6614  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6615 }
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:4367
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:2095
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:91
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:189
@ ForwardScanDirection
Definition: sdir.h:28
Path path
Definition: pathnodes.h:1687
Cost total_cost
Definition: pathnodes.h:1640
Index query_level
Definition: pathnodes.h:208
List * join_domains
Definition: pathnodes.h:311
int wt_param_id
Definition: pathnodes.h:524
Cardinality total_table_pages
Definition: pathnodes.h:478
Query * parse
Definition: pathnodes.h:202
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:1032
struct PathTarget * reltarget
Definition: pathnodes.h:888
BlockNumber pages
Definition: pathnodes.h:937
List * indexlist
Definition: pathnodes.h:933
Cardinality rows
Definition: pathnodes.h:872

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

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

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

◆ 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

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

◆ force_parallel_mode

PGDLLIMPORT int force_parallel_mode
extern

Definition at line 73 of file planner.c.

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

◆ 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