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

Go to the source code of this file.

Typedefs

typedef void(* set_rel_pathlist_hook_type) (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)
 
typedef void(* set_join_pathlist_hook_type) (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra)
 
typedef RelOptInfo *(* join_search_hook_type) (PlannerInfo *root, int levels_needed, List *initial_rels)
 
typedef bool(* ec_matches_callback_type) (PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, EquivalenceMember *em, void *arg)
 

Enumerations

enum  PathKeysComparison { PATHKEYS_EQUAL , PATHKEYS_BETTER1 , PATHKEYS_BETTER2 , PATHKEYS_DIFFERENT }
 

Functions

RelOptInfomake_one_rel (PlannerInfo *root, List *joinlist)
 
RelOptInfostandard_join_search (PlannerInfo *root, int levels_needed, List *initial_rels)
 
void generate_gather_paths (PlannerInfo *root, RelOptInfo *rel, bool override_rows)
 
void generate_useful_gather_paths (PlannerInfo *root, RelOptInfo *rel, bool override_rows)
 
int compute_parallel_worker (RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
 
void create_partial_bitmap_paths (PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual)
 
void generate_partitionwise_join_paths (PlannerInfo *root, RelOptInfo *rel)
 
void create_index_paths (PlannerInfo *root, RelOptInfo *rel)
 
bool relation_has_unique_index_for (PlannerInfo *root, RelOptInfo *rel, List *restrictlist, List *exprlist, List *oprlist)
 
bool indexcol_is_bool_constant_for_query (PlannerInfo *root, IndexOptInfo *index, int indexcol)
 
bool match_index_to_operand (Node *operand, int indexcol, IndexOptInfo *index)
 
void check_index_predicates (PlannerInfo *root, RelOptInfo *rel)
 
bool create_tidscan_paths (PlannerInfo *root, RelOptInfo *rel)
 
void add_paths_to_joinrel (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist)
 
void join_search_one_level (PlannerInfo *root, int level)
 
RelOptInfomake_join_rel (PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 
Relids add_outer_joins_to_relids (PlannerInfo *root, Relids input_relids, SpecialJoinInfo *sjinfo, List **pushed_down_joins)
 
bool have_join_order_restriction (PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 
bool have_dangerous_phv (PlannerInfo *root, Relids outer_relids, Relids inner_params)
 
void mark_dummy_rel (RelOptInfo *rel)
 
void init_dummy_sjinfo (SpecialJoinInfo *sjinfo, Relids left_relids, Relids right_relids)
 
bool process_equivalence (PlannerInfo *root, RestrictInfo **p_restrictinfo, JoinDomain *jdomain)
 
Exprcanonicalize_ec_expression (Expr *expr, Oid req_type, Oid req_collation)
 
void reconsider_outer_join_clauses (PlannerInfo *root)
 
EquivalenceClassget_eclass_for_sort_expr (PlannerInfo *root, Expr *expr, List *opfamilies, Oid opcintype, Oid collation, Index sortref, Relids rel, bool create_it)
 
EquivalenceMemberfind_ec_member_matching_expr (EquivalenceClass *ec, Expr *expr, Relids relids)
 
EquivalenceMemberfind_computable_ec_member (PlannerInfo *root, EquivalenceClass *ec, List *exprs, Relids relids, bool require_parallel_safe)
 
bool relation_can_be_sorted_early (PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, bool require_parallel_safe)
 
void generate_base_implied_equalities (PlannerInfo *root)
 
Listgenerate_join_implied_equalities (PlannerInfo *root, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo)
 
Listgenerate_join_implied_equalities_for_ecs (PlannerInfo *root, List *eclasses, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel)
 
bool exprs_known_equal (PlannerInfo *root, Node *item1, Node *item2)
 
EquivalenceClassmatch_eclasses_to_foreign_key_col (PlannerInfo *root, ForeignKeyOptInfo *fkinfo, int colno)
 
RestrictInfofind_derived_clause_for_ec_member (EquivalenceClass *ec, EquivalenceMember *em)
 
void add_child_rel_equivalences (PlannerInfo *root, AppendRelInfo *appinfo, RelOptInfo *parent_rel, RelOptInfo *child_rel)
 
void add_child_join_rel_equivalences (PlannerInfo *root, int nappinfos, AppendRelInfo **appinfos, RelOptInfo *parent_joinrel, RelOptInfo *child_joinrel)
 
void add_setop_child_rel_equivalences (PlannerInfo *root, RelOptInfo *child_rel, List *child_tlist, List *setop_pathkeys)
 
Listgenerate_implied_equalities_for_column (PlannerInfo *root, RelOptInfo *rel, ec_matches_callback_type callback, void *callback_arg, Relids prohibited_rels)
 
bool have_relevant_eclass_joinclause (PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 
bool has_relevant_eclass_joinclause (PlannerInfo *root, RelOptInfo *rel1)
 
bool eclass_useful_for_merging (PlannerInfo *root, EquivalenceClass *eclass, RelOptInfo *rel)
 
bool is_redundant_derived_clause (RestrictInfo *rinfo, List *clauselist)
 
bool is_redundant_with_indexclauses (RestrictInfo *rinfo, List *indexclauses)
 
PathKeysComparison compare_pathkeys (List *keys1, List *keys2)
 
bool pathkeys_contained_in (List *keys1, List *keys2)
 
bool pathkeys_count_contained_in (List *keys1, List *keys2, int *n_common)
 
Listget_useful_group_keys_orderings (PlannerInfo *root, Path *path)
 
Pathget_cheapest_path_for_pathkeys (List *paths, List *pathkeys, Relids required_outer, CostSelector cost_criterion, bool require_parallel_safe)
 
Pathget_cheapest_fractional_path_for_pathkeys (List *paths, List *pathkeys, Relids required_outer, double fraction)
 
Pathget_cheapest_parallel_safe_total_inner (List *paths)
 
Listbuild_index_pathkeys (PlannerInfo *root, IndexOptInfo *index, ScanDirection scandir)
 
Listbuild_partition_pathkeys (PlannerInfo *root, RelOptInfo *partrel, ScanDirection scandir, bool *partialkeys)
 
Listbuild_expression_pathkey (PlannerInfo *root, Expr *expr, Oid opno, Relids rel, bool create_it)
 
Listconvert_subquery_pathkeys (PlannerInfo *root, RelOptInfo *rel, List *subquery_pathkeys, List *subquery_tlist)
 
Listbuild_join_pathkeys (PlannerInfo *root, RelOptInfo *joinrel, JoinType jointype, List *outer_pathkeys)
 
Listmake_pathkeys_for_sortclauses (PlannerInfo *root, List *sortclauses, List *tlist)
 
Listmake_pathkeys_for_sortclauses_extended (PlannerInfo *root, List **sortclauses, List *tlist, bool remove_redundant, bool *sortable, bool set_ec_sortref)
 
void initialize_mergeclause_eclasses (PlannerInfo *root, RestrictInfo *restrictinfo)
 
void update_mergeclause_eclasses (PlannerInfo *root, RestrictInfo *restrictinfo)
 
Listfind_mergeclauses_for_outer_pathkeys (PlannerInfo *root, List *pathkeys, List *restrictinfos)
 
Listselect_outer_pathkeys_for_merge (PlannerInfo *root, List *mergeclauses, RelOptInfo *joinrel)
 
Listmake_inner_pathkeys_for_merge (PlannerInfo *root, List *mergeclauses, List *outer_pathkeys)
 
Listtrim_mergeclauses_for_inner_pathkeys (PlannerInfo *root, List *mergeclauses, List *pathkeys)
 
Listtruncate_useless_pathkeys (PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
 
bool has_useful_pathkeys (PlannerInfo *root, RelOptInfo *rel)
 
Listappend_pathkeys (List *target, List *source)
 
PathKeymake_canonical_pathkey (PlannerInfo *root, EquivalenceClass *eclass, Oid opfamily, int strategy, bool nulls_first)
 
void add_paths_to_append_rel (PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
 

Variables

PGDLLIMPORT bool enable_geqo
 
PGDLLIMPORT int geqo_threshold
 
PGDLLIMPORT int min_parallel_table_scan_size
 
PGDLLIMPORT int min_parallel_index_scan_size
 
PGDLLIMPORT bool enable_group_by_reordering
 
PGDLLIMPORT set_rel_pathlist_hook_type set_rel_pathlist_hook
 
PGDLLIMPORT set_join_pathlist_hook_type set_join_pathlist_hook
 
PGDLLIMPORT join_search_hook_type join_search_hook
 

Typedef Documentation

◆ ec_matches_callback_type

typedef bool(* ec_matches_callback_type) (PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, EquivalenceMember *em, void *arg)

Definition at line 119 of file paths.h.

◆ join_search_hook_type

typedef RelOptInfo*(* join_search_hook_type) (PlannerInfo *root, int levels_needed, List *initial_rels)

Definition at line 46 of file paths.h.

◆ set_join_pathlist_hook_type

typedef void(* set_join_pathlist_hook_type) (PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra)

Definition at line 37 of file paths.h.

◆ set_rel_pathlist_hook_type

typedef void(* set_rel_pathlist_hook_type) (PlannerInfo *root, RelOptInfo *rel, Index rti, RangeTblEntry *rte)

Definition at line 30 of file paths.h.

Enumeration Type Documentation

◆ PathKeysComparison

Enumerator
PATHKEYS_EQUAL 
PATHKEYS_BETTER1 
PATHKEYS_BETTER2 
PATHKEYS_DIFFERENT 

Definition at line 200 of file paths.h.

201 {
202  PATHKEYS_EQUAL, /* pathkeys are identical */
203  PATHKEYS_BETTER1, /* pathkey 1 is a superset of pathkey 2 */
204  PATHKEYS_BETTER2, /* vice versa */
205  PATHKEYS_DIFFERENT, /* neither pathkey includes the other */
PathKeysComparison
Definition: paths.h:201
@ PATHKEYS_BETTER2
Definition: paths.h:204
@ PATHKEYS_BETTER1
Definition: paths.h:203
@ PATHKEYS_DIFFERENT
Definition: paths.h:205
@ PATHKEYS_EQUAL
Definition: paths.h:202

Function Documentation

◆ add_child_join_rel_equivalences()

void add_child_join_rel_equivalences ( PlannerInfo root,
int  nappinfos,
AppendRelInfo **  appinfos,
RelOptInfo parent_joinrel,
RelOptInfo child_joinrel 
)

Definition at line 2758 of file equivclass.c.

2762 {
2763  Relids top_parent_relids = child_joinrel->top_parent_relids;
2764  Relids child_relids = child_joinrel->relids;
2765  Bitmapset *matching_ecs;
2766  MemoryContext oldcontext;
2767  int i;
2768 
2769  Assert(IS_JOIN_REL(child_joinrel) && IS_JOIN_REL(parent_joinrel));
2770 
2771  /* We need consider only ECs that mention the parent joinrel */
2772  matching_ecs = get_eclass_indexes_for_relids(root, top_parent_relids);
2773 
2774  /*
2775  * If we're being called during GEQO join planning, we still have to
2776  * create any new EC members in the main planner context, to avoid having
2777  * a corrupt EC data structure after the GEQO context is reset. This is
2778  * problematic since we'll leak memory across repeated GEQO cycles. For
2779  * now, though, bloat is better than crash. If it becomes a real issue
2780  * we'll have to do something to avoid generating duplicate EC members.
2781  */
2782  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
2783 
2784  i = -1;
2785  while ((i = bms_next_member(matching_ecs, i)) >= 0)
2786  {
2787  EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2788  int num_members;
2789 
2790  /*
2791  * If this EC contains a volatile expression, then generating child
2792  * EMs would be downright dangerous, so skip it. We rely on a
2793  * volatile EC having only one EM.
2794  */
2795  if (cur_ec->ec_has_volatile)
2796  continue;
2797 
2798  /* Sanity check on get_eclass_indexes_for_relids result */
2799  Assert(bms_overlap(top_parent_relids, cur_ec->ec_relids));
2800 
2801  /*
2802  * We don't use foreach() here because there's no point in scanning
2803  * newly-added child members, so we can stop after the last
2804  * pre-existing EC member.
2805  */
2806  num_members = list_length(cur_ec->ec_members);
2807  for (int pos = 0; pos < num_members; pos++)
2808  {
2809  EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
2810 
2811  if (cur_em->em_is_const)
2812  continue; /* ignore consts here */
2813 
2814  /*
2815  * We consider only original EC members here, not
2816  * already-transformed child members.
2817  */
2818  if (cur_em->em_is_child)
2819  continue; /* ignore children here */
2820 
2821  /*
2822  * We may ignore expressions that reference a single baserel,
2823  * because add_child_rel_equivalences should have handled them.
2824  */
2825  if (bms_membership(cur_em->em_relids) != BMS_MULTIPLE)
2826  continue;
2827 
2828  /* Does this member reference child's topmost parent rel? */
2829  if (bms_overlap(cur_em->em_relids, top_parent_relids))
2830  {
2831  /* Yes, generate transformed child version */
2832  Expr *child_expr;
2833  Relids new_relids;
2834 
2835  if (parent_joinrel->reloptkind == RELOPT_JOINREL)
2836  {
2837  /* Simple single-level transformation */
2838  child_expr = (Expr *)
2840  (Node *) cur_em->em_expr,
2841  nappinfos, appinfos);
2842  }
2843  else
2844  {
2845  /* Must do multi-level transformation */
2846  Assert(parent_joinrel->reloptkind == RELOPT_OTHER_JOINREL);
2847  child_expr = (Expr *)
2849  (Node *) cur_em->em_expr,
2850  child_joinrel,
2851  child_joinrel->top_parent);
2852  }
2853 
2854  /*
2855  * Transform em_relids to match. Note we do *not* do
2856  * pull_varnos(child_expr) here, as for example the
2857  * transformation might have substituted a constant, but we
2858  * don't want the child member to be marked as constant.
2859  */
2860  new_relids = bms_difference(cur_em->em_relids,
2861  top_parent_relids);
2862  new_relids = bms_add_members(new_relids, child_relids);
2863 
2864  (void) add_eq_member(cur_ec, child_expr, new_relids,
2865  cur_em->em_jdomain,
2866  cur_em, cur_em->em_datatype);
2867  }
2868  }
2869  }
2870 
2871  MemoryContextSwitchTo(oldcontext);
2872 }
Node * adjust_appendrel_attrs(PlannerInfo *root, Node *node, int nappinfos, AppendRelInfo **appinfos)
Definition: appendinfo.c:200
Node * adjust_appendrel_attrs_multilevel(PlannerInfo *root, Node *node, RelOptInfo *childrel, RelOptInfo *parentrel)
Definition: appendinfo.c:525
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
Bitmapset * bms_difference(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:346
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:917
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:781
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:582
@ BMS_MULTIPLE
Definition: bitmapset.h:73
#define Assert(condition)
Definition: c.h:858
static EquivalenceMember * add_eq_member(EquivalenceClass *ec, Expr *expr, Relids relids, JoinDomain *jdomain, EquivalenceMember *parent, Oid datatype)
Definition: equivclass.c:517
static Bitmapset * get_eclass_indexes_for_relids(PlannerInfo *root, Relids relids)
Definition: equivclass.c:3333
int i
Definition: isn.c:73
#define IS_JOIN_REL(rel)
Definition: pathnodes.h:838
@ RELOPT_JOINREL
Definition: pathnodes.h:822
@ RELOPT_OTHER_JOINREL
Definition: pathnodes.h:824
static int list_length(const List *l)
Definition: pg_list.h:152
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
MemoryContextSwitchTo(old_ctx)
tree ctl root
Definition: radixtree.h:1886
JoinDomain * em_jdomain
Definition: pathnodes.h:1439
Definition: nodes.h:129
Relids relids
Definition: pathnodes.h:865
Relids top_parent_relids
Definition: pathnodes.h:1003
RelOptKind reloptkind
Definition: pathnodes.h:859

References add_eq_member(), adjust_appendrel_attrs(), adjust_appendrel_attrs_multilevel(), Assert, bms_add_members(), bms_difference(), bms_membership(), BMS_MULTIPLE, bms_next_member(), bms_overlap(), EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_members, EquivalenceClass::ec_relids, EquivalenceMember::em_datatype, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_jdomain, EquivalenceMember::em_relids, get_eclass_indexes_for_relids(), i, IS_JOIN_REL, list_length(), list_nth(), MemoryContextSwitchTo(), RelOptInfo::relids, RELOPT_JOINREL, RELOPT_OTHER_JOINREL, RelOptInfo::reloptkind, root, and RelOptInfo::top_parent_relids.

Referenced by build_child_join_rel().

◆ add_child_rel_equivalences()

void add_child_rel_equivalences ( PlannerInfo root,
AppendRelInfo appinfo,
RelOptInfo parent_rel,
RelOptInfo child_rel 
)

Definition at line 2636 of file equivclass.c.

2640 {
2641  Relids top_parent_relids = child_rel->top_parent_relids;
2642  Relids child_relids = child_rel->relids;
2643  int i;
2644 
2645  /*
2646  * EC merging should be complete already, so we can use the parent rel's
2647  * eclass_indexes to avoid searching all of root->eq_classes.
2648  */
2649  Assert(root->ec_merging_done);
2650  Assert(IS_SIMPLE_REL(parent_rel));
2651 
2652  i = -1;
2653  while ((i = bms_next_member(parent_rel->eclass_indexes, i)) >= 0)
2654  {
2655  EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2656  int num_members;
2657 
2658  /*
2659  * If this EC contains a volatile expression, then generating child
2660  * EMs would be downright dangerous, so skip it. We rely on a
2661  * volatile EC having only one EM.
2662  */
2663  if (cur_ec->ec_has_volatile)
2664  continue;
2665 
2666  /* Sanity check eclass_indexes only contain ECs for parent_rel */
2667  Assert(bms_is_subset(top_parent_relids, cur_ec->ec_relids));
2668 
2669  /*
2670  * We don't use foreach() here because there's no point in scanning
2671  * newly-added child members, so we can stop after the last
2672  * pre-existing EC member.
2673  */
2674  num_members = list_length(cur_ec->ec_members);
2675  for (int pos = 0; pos < num_members; pos++)
2676  {
2677  EquivalenceMember *cur_em = (EquivalenceMember *) list_nth(cur_ec->ec_members, pos);
2678 
2679  if (cur_em->em_is_const)
2680  continue; /* ignore consts here */
2681 
2682  /*
2683  * We consider only original EC members here, not
2684  * already-transformed child members. Otherwise, if some original
2685  * member expression references more than one appendrel, we'd get
2686  * an O(N^2) explosion of useless derived expressions for
2687  * combinations of children. (But add_child_join_rel_equivalences
2688  * may add targeted combinations for partitionwise-join purposes.)
2689  */
2690  if (cur_em->em_is_child)
2691  continue; /* ignore children here */
2692 
2693  /*
2694  * Consider only members that reference and can be computed at
2695  * child's topmost parent rel. In particular we want to exclude
2696  * parent-rel Vars that have nonempty varnullingrels. Translating
2697  * those might fail, if the transformed expression wouldn't be a
2698  * simple Var; and in any case it wouldn't produce a member that
2699  * has any use in creating plans for the child rel.
2700  */
2701  if (bms_is_subset(cur_em->em_relids, top_parent_relids) &&
2702  !bms_is_empty(cur_em->em_relids))
2703  {
2704  /* OK, generate transformed child version */
2705  Expr *child_expr;
2706  Relids new_relids;
2707 
2708  if (parent_rel->reloptkind == RELOPT_BASEREL)
2709  {
2710  /* Simple single-level transformation */
2711  child_expr = (Expr *)
2713  (Node *) cur_em->em_expr,
2714  1, &appinfo);
2715  }
2716  else
2717  {
2718  /* Must do multi-level transformation */
2719  child_expr = (Expr *)
2721  (Node *) cur_em->em_expr,
2722  child_rel,
2723  child_rel->top_parent);
2724  }
2725 
2726  /*
2727  * Transform em_relids to match. Note we do *not* do
2728  * pull_varnos(child_expr) here, as for example the
2729  * transformation might have substituted a constant, but we
2730  * don't want the child member to be marked as constant.
2731  */
2732  new_relids = bms_difference(cur_em->em_relids,
2733  top_parent_relids);
2734  new_relids = bms_add_members(new_relids, child_relids);
2735 
2736  (void) add_eq_member(cur_ec, child_expr, new_relids,
2737  cur_em->em_jdomain,
2738  cur_em, cur_em->em_datatype);
2739 
2740  /* Record this EC index for the child rel */
2741  child_rel->eclass_indexes = bms_add_member(child_rel->eclass_indexes, i);
2742  }
2743  }
2744  }
2745 }
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define bms_is_empty(a)
Definition: bitmapset.h:118
#define IS_SIMPLE_REL(rel)
Definition: pathnodes.h:833
@ RELOPT_BASEREL
Definition: pathnodes.h:821
Bitmapset * eclass_indexes
Definition: pathnodes.h:946

References add_eq_member(), adjust_appendrel_attrs(), adjust_appendrel_attrs_multilevel(), Assert, bms_add_member(), bms_add_members(), bms_difference(), bms_is_empty, bms_is_subset(), bms_next_member(), EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_members, EquivalenceClass::ec_relids, RelOptInfo::eclass_indexes, EquivalenceMember::em_datatype, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_jdomain, EquivalenceMember::em_relids, i, IS_SIMPLE_REL, list_length(), list_nth(), RelOptInfo::relids, RELOPT_BASEREL, RelOptInfo::reloptkind, root, and RelOptInfo::top_parent_relids.

Referenced by set_append_rel_size().

◆ add_outer_joins_to_relids()

Relids add_outer_joins_to_relids ( PlannerInfo root,
Relids  input_relids,
SpecialJoinInfo sjinfo,
List **  pushed_down_joins 
)

Definition at line 801 of file joinrels.c.

804 {
805  /* Nothing to do if this isn't an outer join with an assigned relid. */
806  if (sjinfo == NULL || sjinfo->ojrelid == 0)
807  return input_relids;
808 
809  /*
810  * If it's not a left join, we have no rules that would permit executing
811  * it in non-syntactic order, so just form the syntactic relid set. (This
812  * is just a quick-exit test; we'd come to the same conclusion anyway,
813  * since its commute_below_l and commute_above_l sets must be empty.)
814  */
815  if (sjinfo->jointype != JOIN_LEFT)
816  return bms_add_member(input_relids, sjinfo->ojrelid);
817 
818  /*
819  * We cannot add the OJ relid if this join has been pushed into the RHS of
820  * a syntactically-lower left join per OJ identity 3. (If it has, then we
821  * cannot claim that its outputs represent the final state of its RHS.)
822  * There will not be any other OJs that can be added either, so we're
823  * done.
824  */
825  if (!bms_is_subset(sjinfo->commute_below_l, input_relids))
826  return input_relids;
827 
828  /* OK to add OJ's own relid */
829  input_relids = bms_add_member(input_relids, sjinfo->ojrelid);
830 
831  /*
832  * Contrariwise, if we are now forming the final result of such a commuted
833  * pair of OJs, it's time to add the relid(s) of the pushed-down join(s).
834  * We can skip this if this join was never a candidate to be pushed up.
835  */
836  if (sjinfo->commute_above_l)
837  {
838  Relids commute_above_rels = bms_copy(sjinfo->commute_above_l);
839  ListCell *lc;
840 
841  /*
842  * The current join could complete the nulling of more than one
843  * pushed-down join, so we have to examine all the SpecialJoinInfos.
844  * Because join_info_list was built in bottom-up order, it's
845  * sufficient to traverse it once: an ojrelid we add in one loop
846  * iteration would not have affected decisions of earlier iterations.
847  */
848  foreach(lc, root->join_info_list)
849  {
850  SpecialJoinInfo *othersj = (SpecialJoinInfo *) lfirst(lc);
851 
852  if (othersj == sjinfo ||
853  othersj->ojrelid == 0 || othersj->jointype != JOIN_LEFT)
854  continue; /* definitely not interesting */
855 
856  if (!bms_is_member(othersj->ojrelid, commute_above_rels))
857  continue;
858 
859  /* Add it if not already present but conditions now satisfied */
860  if (!bms_is_member(othersj->ojrelid, input_relids) &&
861  bms_is_subset(othersj->min_lefthand, input_relids) &&
862  bms_is_subset(othersj->min_righthand, input_relids) &&
863  bms_is_subset(othersj->commute_below_l, input_relids))
864  {
865  input_relids = bms_add_member(input_relids, othersj->ojrelid);
866  /* report such pushed down outer joins, if asked */
867  if (pushed_down_joins != NULL)
868  *pushed_down_joins = lappend(*pushed_down_joins, othersj);
869 
870  /*
871  * We must also check any joins that othersj potentially
872  * commutes with. They likewise must appear later in
873  * join_info_list than othersj itself, so we can visit them
874  * later in this loop.
875  */
876  commute_above_rels = bms_add_members(commute_above_rels,
877  othersj->commute_above_l);
878  }
879  }
880  }
881 
882  return input_relids;
883 }
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:510
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:122
List * lappend(List *list, void *datum)
Definition: list.c:339
@ JOIN_LEFT
Definition: nodes.h:294
#define lfirst(lc)
Definition: pg_list.h:172
Relids min_righthand
Definition: pathnodes.h:2895
Relids commute_above_l
Definition: pathnodes.h:2900
JoinType jointype
Definition: pathnodes.h:2898
Relids commute_below_l
Definition: pathnodes.h:2902
Relids min_lefthand
Definition: pathnodes.h:2894

References bms_add_member(), bms_add_members(), bms_copy(), bms_is_member(), bms_is_subset(), SpecialJoinInfo::commute_above_l, SpecialJoinInfo::commute_below_l, JOIN_LEFT, SpecialJoinInfo::jointype, lappend(), lfirst, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, SpecialJoinInfo::ojrelid, and root.

Referenced by generate_join_implied_equalities(), and make_join_rel().

◆ add_paths_to_append_rel()

void add_paths_to_append_rel ( PlannerInfo root,
RelOptInfo rel,
List live_childrels 
)

Definition at line 1310 of file allpaths.c.

1312 {
1313  List *subpaths = NIL;
1314  bool subpaths_valid = true;
1315  List *startup_subpaths = NIL;
1316  bool startup_subpaths_valid = true;
1317  List *partial_subpaths = NIL;
1318  List *pa_partial_subpaths = NIL;
1319  List *pa_nonpartial_subpaths = NIL;
1320  bool partial_subpaths_valid = true;
1321  bool pa_subpaths_valid;
1322  List *all_child_pathkeys = NIL;
1323  List *all_child_outers = NIL;
1324  ListCell *l;
1325  double partial_rows = -1;
1326 
1327  /* If appropriate, consider parallel append */
1328  pa_subpaths_valid = enable_parallel_append && rel->consider_parallel;
1329 
1330  /*
1331  * For every non-dummy child, remember the cheapest path. Also, identify
1332  * all pathkeys (orderings) and parameterizations (required_outer sets)
1333  * available for the non-dummy member relations.
1334  */
1335  foreach(l, live_childrels)
1336  {
1337  RelOptInfo *childrel = lfirst(l);
1338  ListCell *lcp;
1339  Path *cheapest_partial_path = NULL;
1340 
1341  /*
1342  * If child has an unparameterized cheapest-total path, add that to
1343  * the unparameterized Append path we are constructing for the parent.
1344  * If not, there's no workable unparameterized path.
1345  *
1346  * With partitionwise aggregates, the child rel's pathlist may be
1347  * empty, so don't assume that a path exists here.
1348  */
1349  if (childrel->pathlist != NIL &&
1350  childrel->cheapest_total_path->param_info == NULL)
1352  &subpaths, NULL);
1353  else
1354  subpaths_valid = false;
1355 
1356  /*
1357  * When the planner is considering cheap startup plans, we'll also
1358  * collect all the cheapest_startup_paths (if set) and build an
1359  * AppendPath containing those as subpaths.
1360  */
1361  if (rel->consider_startup && childrel->cheapest_startup_path != NULL)
1362  {
1363  /* cheapest_startup_path must not be a parameterized path. */
1364  Assert(childrel->cheapest_startup_path->param_info == NULL);
1366  &startup_subpaths,
1367  NULL);
1368  }
1369  else
1370  startup_subpaths_valid = false;
1371 
1372 
1373  /* Same idea, but for a partial plan. */
1374  if (childrel->partial_pathlist != NIL)
1375  {
1376  cheapest_partial_path = linitial(childrel->partial_pathlist);
1377  accumulate_append_subpath(cheapest_partial_path,
1378  &partial_subpaths, NULL);
1379  }
1380  else
1381  partial_subpaths_valid = false;
1382 
1383  /*
1384  * Same idea, but for a parallel append mixing partial and non-partial
1385  * paths.
1386  */
1387  if (pa_subpaths_valid)
1388  {
1389  Path *nppath = NULL;
1390 
1391  nppath =
1393 
1394  if (cheapest_partial_path == NULL && nppath == NULL)
1395  {
1396  /* Neither a partial nor a parallel-safe path? Forget it. */
1397  pa_subpaths_valid = false;
1398  }
1399  else if (nppath == NULL ||
1400  (cheapest_partial_path != NULL &&
1401  cheapest_partial_path->total_cost < nppath->total_cost))
1402  {
1403  /* Partial path is cheaper or the only option. */
1404  Assert(cheapest_partial_path != NULL);
1405  accumulate_append_subpath(cheapest_partial_path,
1406  &pa_partial_subpaths,
1407  &pa_nonpartial_subpaths);
1408  }
1409  else
1410  {
1411  /*
1412  * Either we've got only a non-partial path, or we think that
1413  * a single backend can execute the best non-partial path
1414  * faster than all the parallel backends working together can
1415  * execute the best partial path.
1416  *
1417  * It might make sense to be more aggressive here. Even if
1418  * the best non-partial path is more expensive than the best
1419  * partial path, it could still be better to choose the
1420  * non-partial path if there are several such paths that can
1421  * be given to different workers. For now, we don't try to
1422  * figure that out.
1423  */
1425  &pa_nonpartial_subpaths,
1426  NULL);
1427  }
1428  }
1429 
1430  /*
1431  * Collect lists of all the available path orderings and
1432  * parameterizations for all the children. We use these as a
1433  * heuristic to indicate which sort orderings and parameterizations we
1434  * should build Append and MergeAppend paths for.
1435  */
1436  foreach(lcp, childrel->pathlist)
1437  {
1438  Path *childpath = (Path *) lfirst(lcp);
1439  List *childkeys = childpath->pathkeys;
1440  Relids childouter = PATH_REQ_OUTER(childpath);
1441 
1442  /* Unsorted paths don't contribute to pathkey list */
1443  if (childkeys != NIL)
1444  {
1445  ListCell *lpk;
1446  bool found = false;
1447 
1448  /* Have we already seen this ordering? */
1449  foreach(lpk, all_child_pathkeys)
1450  {
1451  List *existing_pathkeys = (List *) lfirst(lpk);
1452 
1453  if (compare_pathkeys(existing_pathkeys,
1454  childkeys) == PATHKEYS_EQUAL)
1455  {
1456  found = true;
1457  break;
1458  }
1459  }
1460  if (!found)
1461  {
1462  /* No, so add it to all_child_pathkeys */
1463  all_child_pathkeys = lappend(all_child_pathkeys,
1464  childkeys);
1465  }
1466  }
1467 
1468  /* Unparameterized paths don't contribute to param-set list */
1469  if (childouter)
1470  {
1471  ListCell *lco;
1472  bool found = false;
1473 
1474  /* Have we already seen this param set? */
1475  foreach(lco, all_child_outers)
1476  {
1477  Relids existing_outers = (Relids) lfirst(lco);
1478 
1479  if (bms_equal(existing_outers, childouter))
1480  {
1481  found = true;
1482  break;
1483  }
1484  }
1485  if (!found)
1486  {
1487  /* No, so add it to all_child_outers */
1488  all_child_outers = lappend(all_child_outers,
1489  childouter);
1490  }
1491  }
1492  }
1493  }
1494 
1495  /*
1496  * If we found unparameterized paths for all children, build an unordered,
1497  * unparameterized Append path for the rel. (Note: this is correct even
1498  * if we have zero or one live subpath due to constraint exclusion.)
1499  */
1500  if (subpaths_valid)
1501  add_path(rel, (Path *) create_append_path(root, rel, subpaths, NIL,
1502  NIL, NULL, 0, false,
1503  -1));
1504 
1505  /* build an AppendPath for the cheap startup paths, if valid */
1506  if (startup_subpaths_valid)
1507  add_path(rel, (Path *) create_append_path(root, rel, startup_subpaths,
1508  NIL, NIL, NULL, 0, false, -1));
1509 
1510  /*
1511  * Consider an append of unordered, unparameterized partial paths. Make
1512  * it parallel-aware if possible.
1513  */
1514  if (partial_subpaths_valid && partial_subpaths != NIL)
1515  {
1516  AppendPath *appendpath;
1517  ListCell *lc;
1518  int parallel_workers = 0;
1519 
1520  /* Find the highest number of workers requested for any subpath. */
1521  foreach(lc, partial_subpaths)
1522  {
1523  Path *path = lfirst(lc);
1524 
1525  parallel_workers = Max(parallel_workers, path->parallel_workers);
1526  }
1527  Assert(parallel_workers > 0);
1528 
1529  /*
1530  * If the use of parallel append is permitted, always request at least
1531  * log2(# of children) workers. We assume it can be useful to have
1532  * extra workers in this case because they will be spread out across
1533  * the children. The precise formula is just a guess, but we don't
1534  * want to end up with a radically different answer for a table with N
1535  * partitions vs. an unpartitioned table with the same data, so the
1536  * use of some kind of log-scaling here seems to make some sense.
1537  */
1539  {
1540  parallel_workers = Max(parallel_workers,
1541  pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1542  parallel_workers = Min(parallel_workers,
1544  }
1545  Assert(parallel_workers > 0);
1546 
1547  /* Generate a partial append path. */
1548  appendpath = create_append_path(root, rel, NIL, partial_subpaths,
1549  NIL, NULL, parallel_workers,
1551  -1);
1552 
1553  /*
1554  * Make sure any subsequent partial paths use the same row count
1555  * estimate.
1556  */
1557  partial_rows = appendpath->path.rows;
1558 
1559  /* Add the path. */
1560  add_partial_path(rel, (Path *) appendpath);
1561  }
1562 
1563  /*
1564  * Consider a parallel-aware append using a mix of partial and non-partial
1565  * paths. (This only makes sense if there's at least one child which has
1566  * a non-partial path that is substantially cheaper than any partial path;
1567  * otherwise, we should use the append path added in the previous step.)
1568  */
1569  if (pa_subpaths_valid && pa_nonpartial_subpaths != NIL)
1570  {
1571  AppendPath *appendpath;
1572  ListCell *lc;
1573  int parallel_workers = 0;
1574 
1575  /*
1576  * Find the highest number of workers requested for any partial
1577  * subpath.
1578  */
1579  foreach(lc, pa_partial_subpaths)
1580  {
1581  Path *path = lfirst(lc);
1582 
1583  parallel_workers = Max(parallel_workers, path->parallel_workers);
1584  }
1585 
1586  /*
1587  * Same formula here as above. It's even more important in this
1588  * instance because the non-partial paths won't contribute anything to
1589  * the planned number of parallel workers.
1590  */
1591  parallel_workers = Max(parallel_workers,
1592  pg_leftmost_one_pos32(list_length(live_childrels)) + 1);
1593  parallel_workers = Min(parallel_workers,
1595  Assert(parallel_workers > 0);
1596 
1597  appendpath = create_append_path(root, rel, pa_nonpartial_subpaths,
1598  pa_partial_subpaths,
1599  NIL, NULL, parallel_workers, true,
1600  partial_rows);
1601  add_partial_path(rel, (Path *) appendpath);
1602  }
1603 
1604  /*
1605  * Also build unparameterized ordered append paths based on the collected
1606  * list of child pathkeys.
1607  */
1608  if (subpaths_valid)
1609  generate_orderedappend_paths(root, rel, live_childrels,
1610  all_child_pathkeys);
1611 
1612  /*
1613  * Build Append paths for each parameterization seen among the child rels.
1614  * (This may look pretty expensive, but in most cases of practical
1615  * interest, the child rels will expose mostly the same parameterizations,
1616  * so that not that many cases actually get considered here.)
1617  *
1618  * The Append node itself cannot enforce quals, so all qual checking must
1619  * be done in the child paths. This means that to have a parameterized
1620  * Append path, we must have the exact same parameterization for each
1621  * child path; otherwise some children might be failing to check the
1622  * moved-down quals. To make them match up, we can try to increase the
1623  * parameterization of lesser-parameterized paths.
1624  */
1625  foreach(l, all_child_outers)
1626  {
1627  Relids required_outer = (Relids) lfirst(l);
1628  ListCell *lcr;
1629 
1630  /* Select the child paths for an Append with this parameterization */
1631  subpaths = NIL;
1632  subpaths_valid = true;
1633  foreach(lcr, live_childrels)
1634  {
1635  RelOptInfo *childrel = (RelOptInfo *) lfirst(lcr);
1636  Path *subpath;
1637 
1638  if (childrel->pathlist == NIL)
1639  {
1640  /* failed to make a suitable path for this child */
1641  subpaths_valid = false;
1642  break;
1643  }
1644 
1646  childrel,
1647  required_outer);
1648  if (subpath == NULL)
1649  {
1650  /* failed to make a suitable path for this child */
1651  subpaths_valid = false;
1652  break;
1653  }
1654  accumulate_append_subpath(subpath, &subpaths, NULL);
1655  }
1656 
1657  if (subpaths_valid)
1658  add_path(rel, (Path *)
1659  create_append_path(root, rel, subpaths, NIL,
1660  NIL, required_outer, 0, false,
1661  -1));
1662  }
1663 
1664  /*
1665  * When there is only a single child relation, the Append path can inherit
1666  * any ordering available for the child rel's path, so that it's useful to
1667  * consider ordered partial paths. Above we only considered the cheapest
1668  * partial path for each child, but let's also make paths using any
1669  * partial paths that have pathkeys.
1670  */
1671  if (list_length(live_childrels) == 1)
1672  {
1673  RelOptInfo *childrel = (RelOptInfo *) linitial(live_childrels);
1674 
1675  /* skip the cheapest partial path, since we already used that above */
1676  for_each_from(l, childrel->partial_pathlist, 1)
1677  {
1678  Path *path = (Path *) lfirst(l);
1679  AppendPath *appendpath;
1680 
1681  /* skip paths with no pathkeys. */
1682  if (path->pathkeys == NIL)
1683  continue;
1684 
1685  appendpath = create_append_path(root, rel, NIL, list_make1(path),
1686  NIL, NULL,
1687  path->parallel_workers, true,
1688  partial_rows);
1689  add_partial_path(rel, (Path *) appendpath);
1690  }
1691  }
1692 }
static Path * get_cheapest_parameterized_child_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer)
Definition: allpaths.c:2007
static void generate_orderedappend_paths(PlannerInfo *root, RelOptInfo *rel, List *live_childrels, List *all_child_pathkeys)
Definition: allpaths.c:1722
static void accumulate_append_subpath(Path *path, List **subpaths, List **special_subpaths)
Definition: allpaths.c:2095
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
#define Min(x, y)
Definition: c.h:1004
#define Max(x, y)
Definition: c.h:998
int max_parallel_workers_per_gather
Definition: costsize.c:132
bool enable_parallel_append
Definition: costsize.c:150
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:310
Path * get_cheapest_parallel_safe_total_inner(List *paths)
Definition: pathkeys.c:697
PathKeysComparison compare_pathkeys(List *keys1, List *keys2)
Definition: pathkeys.c:302
AppendPath * create_append_path(PlannerInfo *root, RelOptInfo *rel, List *subpaths, List *partial_subpaths, List *pathkeys, Relids required_outer, int parallel_workers, bool parallel_aware, double rows)
Definition: pathnode.c:1244
void add_partial_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:747
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:420
#define PATH_REQ_OUTER(path)
Definition: pathnodes.h:1669
Bitmapset * Relids
Definition: pathnodes.h:30
static int pg_leftmost_one_pos32(uint32 word)
Definition: pg_bitutils.h:41
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
#define linitial(l)
Definition: pg_list.h:178
Definition: pg_list.h:54
List * pathkeys
Definition: pathnodes.h:1665
Cardinality rows
Definition: pathnodes.h:1660
int parallel_workers
Definition: pathnodes.h:1657
Cost total_cost
Definition: pathnodes.h:1662
bool consider_parallel
Definition: pathnodes.h:881
List * pathlist
Definition: pathnodes.h:892
struct Path * cheapest_startup_path
Definition: pathnodes.h:895
struct Path * cheapest_total_path
Definition: pathnodes.h:896
bool consider_startup
Definition: pathnodes.h:877
List * partial_pathlist
Definition: pathnodes.h:894

References accumulate_append_subpath(), add_partial_path(), add_path(), Assert, bms_equal(), RelOptInfo::cheapest_startup_path, RelOptInfo::cheapest_total_path, compare_pathkeys(), RelOptInfo::consider_parallel, RelOptInfo::consider_startup, create_append_path(), enable_parallel_append, for_each_from, generate_orderedappend_paths(), get_cheapest_parallel_safe_total_inner(), get_cheapest_parameterized_child_path(), lappend(), lfirst, linitial, list_length(), list_make1, Max, max_parallel_workers_per_gather, Min, NIL, Path::parallel_workers, RelOptInfo::partial_pathlist, AppendPath::path, PATH_REQ_OUTER, Path::pathkeys, PATHKEYS_EQUAL, RelOptInfo::pathlist, pg_leftmost_one_pos32(), root, Path::rows, subpath(), and Path::total_cost.

Referenced by apply_scanjoin_target_to_paths(), create_partitionwise_grouping_paths(), generate_partitionwise_join_paths(), and set_append_rel_pathlist().

◆ add_paths_to_joinrel()

void add_paths_to_joinrel ( PlannerInfo root,
RelOptInfo joinrel,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
SpecialJoinInfo sjinfo,
List restrictlist 
)

Definition at line 125 of file joinpath.c.

132 {
133  JoinPathExtraData extra;
134  bool mergejoin_allowed = true;
135  ListCell *lc;
136  Relids joinrelids;
137 
138  /*
139  * PlannerInfo doesn't contain the SpecialJoinInfos created for joins
140  * between child relations, even if there is a SpecialJoinInfo node for
141  * the join between the topmost parents. So, while calculating Relids set
142  * representing the restriction, consider relids of topmost parent of
143  * partitions.
144  */
145  if (joinrel->reloptkind == RELOPT_OTHER_JOINREL)
146  joinrelids = joinrel->top_parent_relids;
147  else
148  joinrelids = joinrel->relids;
149 
150  extra.restrictlist = restrictlist;
151  extra.mergeclause_list = NIL;
152  extra.sjinfo = sjinfo;
153  extra.param_source_rels = NULL;
154 
155  /*
156  * See if the inner relation is provably unique for this outer rel.
157  *
158  * We have some special cases: for JOIN_SEMI and JOIN_ANTI, it doesn't
159  * matter since the executor can make the equivalent optimization anyway;
160  * we need not expend planner cycles on proofs. For JOIN_UNIQUE_INNER, we
161  * must be considering a semijoin whose inner side is not provably unique
162  * (else reduce_unique_semijoins would've simplified it), so there's no
163  * point in calling innerrel_is_unique. However, if the LHS covers all of
164  * the semijoin's min_lefthand, then it's appropriate to set inner_unique
165  * because the path produced by create_unique_path will be unique relative
166  * to the LHS. (If we have an LHS that's only part of the min_lefthand,
167  * that is *not* true.) For JOIN_UNIQUE_OUTER, pass JOIN_INNER to avoid
168  * letting that value escape this module.
169  */
170  switch (jointype)
171  {
172  case JOIN_SEMI:
173  case JOIN_ANTI:
174 
175  /*
176  * XXX it may be worth proving this to allow a Memoize to be
177  * considered for Nested Loop Semi/Anti Joins.
178  */
179  extra.inner_unique = false; /* well, unproven */
180  break;
181  case JOIN_UNIQUE_INNER:
182  extra.inner_unique = bms_is_subset(sjinfo->min_lefthand,
183  outerrel->relids);
184  break;
185  case JOIN_UNIQUE_OUTER:
187  joinrel->relids,
188  outerrel->relids,
189  innerrel,
190  JOIN_INNER,
191  restrictlist,
192  false);
193  break;
194  default:
196  joinrel->relids,
197  outerrel->relids,
198  innerrel,
199  jointype,
200  restrictlist,
201  false);
202  break;
203  }
204 
205  /*
206  * Find potential mergejoin clauses. We can skip this if we are not
207  * interested in doing a mergejoin. However, mergejoin may be our only
208  * way of implementing a full outer join, so override enable_mergejoin if
209  * it's a full join.
210  */
211  if (enable_mergejoin || jointype == JOIN_FULL)
213  joinrel,
214  outerrel,
215  innerrel,
216  restrictlist,
217  jointype,
218  &mergejoin_allowed);
219 
220  /*
221  * If it's SEMI, ANTI, or inner_unique join, compute correction factors
222  * for cost estimation. These will be the same for all paths.
223  */
224  if (jointype == JOIN_SEMI || jointype == JOIN_ANTI || extra.inner_unique)
225  compute_semi_anti_join_factors(root, joinrel, outerrel, innerrel,
226  jointype, sjinfo, restrictlist,
227  &extra.semifactors);
228 
229  /*
230  * Decide whether it's sensible to generate parameterized paths for this
231  * joinrel, and if so, which relations such paths should require. There
232  * is usually no need to create a parameterized result path unless there
233  * is a join order restriction that prevents joining one of our input rels
234  * directly to the parameter source rel instead of joining to the other
235  * input rel. (But see allow_star_schema_join().) This restriction
236  * reduces the number of parameterized paths we have to deal with at
237  * higher join levels, without compromising the quality of the resulting
238  * plan. We express the restriction as a Relids set that must overlap the
239  * parameterization of any proposed join path. Note: param_source_rels
240  * should contain only baserels, not OJ relids, so starting from
241  * all_baserels not all_query_rels is correct.
242  */
243  foreach(lc, root->join_info_list)
244  {
245  SpecialJoinInfo *sjinfo2 = (SpecialJoinInfo *) lfirst(lc);
246 
247  /*
248  * SJ is relevant to this join if we have some part of its RHS
249  * (possibly not all of it), and haven't yet joined to its LHS. (This
250  * test is pretty simplistic, but should be sufficient considering the
251  * join has already been proven legal.) If the SJ is relevant, it
252  * presents constraints for joining to anything not in its RHS.
253  */
254  if (bms_overlap(joinrelids, sjinfo2->min_righthand) &&
255  !bms_overlap(joinrelids, sjinfo2->min_lefthand))
257  bms_difference(root->all_baserels,
258  sjinfo2->min_righthand));
259 
260  /* full joins constrain both sides symmetrically */
261  if (sjinfo2->jointype == JOIN_FULL &&
262  bms_overlap(joinrelids, sjinfo2->min_lefthand) &&
263  !bms_overlap(joinrelids, sjinfo2->min_righthand))
265  bms_difference(root->all_baserels,
266  sjinfo2->min_lefthand));
267  }
268 
269  /*
270  * However, when a LATERAL subquery is involved, there will simply not be
271  * any paths for the joinrel that aren't parameterized by whatever the
272  * subquery is parameterized by, unless its parameterization is resolved
273  * within the joinrel. So we might as well allow additional dependencies
274  * on whatever residual lateral dependencies the joinrel will have.
275  */
277  joinrel->lateral_relids);
278 
279  /*
280  * 1. Consider mergejoin paths where both relations must be explicitly
281  * sorted. Skip this if we can't mergejoin.
282  */
283  if (mergejoin_allowed)
284  sort_inner_and_outer(root, joinrel, outerrel, innerrel,
285  jointype, &extra);
286 
287  /*
288  * 2. Consider paths where the outer relation need not be explicitly
289  * sorted. This includes both nestloops and mergejoins where the outer
290  * path is already ordered. Again, skip this if we can't mergejoin.
291  * (That's okay because we know that nestloop can't handle
292  * right/right-anti/right-semi/full joins at all, so it wouldn't work in
293  * the prohibited cases either.)
294  */
295  if (mergejoin_allowed)
296  match_unsorted_outer(root, joinrel, outerrel, innerrel,
297  jointype, &extra);
298 
299 #ifdef NOT_USED
300 
301  /*
302  * 3. Consider paths where the inner relation need not be explicitly
303  * sorted. This includes mergejoins only (nestloops were already built in
304  * match_unsorted_outer).
305  *
306  * Diked out as redundant 2/13/2000 -- tgl. There isn't any really
307  * significant difference between the inner and outer side of a mergejoin,
308  * so match_unsorted_inner creates no paths that aren't equivalent to
309  * those made by match_unsorted_outer when add_paths_to_joinrel() is
310  * invoked with the two rels given in the other order.
311  */
312  if (mergejoin_allowed)
313  match_unsorted_inner(root, joinrel, outerrel, innerrel,
314  jointype, &extra);
315 #endif
316 
317  /*
318  * 4. Consider paths where both outer and inner relations must be hashed
319  * before being joined. As above, disregard enable_hashjoin for full
320  * joins, because there may be no other alternative.
321  */
322  if (enable_hashjoin || jointype == JOIN_FULL)
323  hash_inner_and_outer(root, joinrel, outerrel, innerrel,
324  jointype, &extra);
325 
326  /*
327  * 5. If inner and outer relations are foreign tables (or joins) belonging
328  * to the same server and assigned to the same user to check access
329  * permissions as, give the FDW a chance to push down joins.
330  */
331  if (joinrel->fdwroutine &&
332  joinrel->fdwroutine->GetForeignJoinPaths)
333  joinrel->fdwroutine->GetForeignJoinPaths(root, joinrel,
334  outerrel, innerrel,
335  jointype, &extra);
336 
337  /*
338  * 6. Finally, give extensions a chance to manipulate the path list. They
339  * could add new paths (such as CustomPaths) by calling add_path(), or
340  * add_partial_path() if parallel aware. They could also delete or modify
341  * paths added by the core code.
342  */
344  set_join_pathlist_hook(root, joinrel, outerrel, innerrel,
345  jointype, &extra);
346 }
bool innerrel_is_unique(PlannerInfo *root, Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache)
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1230
void compute_semi_anti_join_factors(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, SpecialJoinInfo *sjinfo, List *restrictlist, SemiAntiJoinFactors *semifactors)
Definition: costsize.c:4978
bool enable_hashjoin
Definition: costsize.c:146
bool enable_mergejoin
Definition: costsize.c:145
static List * select_mergejoin_clauses(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, List *restrictlist, JoinType jointype, bool *mergejoin_allowed)
Definition: joinpath.c:2484
static void sort_inner_and_outer(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra)
Definition: joinpath.c:1370
set_join_pathlist_hook_type set_join_pathlist_hook
Definition: joinpath.c:31
static void hash_inner_and_outer(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra)
Definition: joinpath.c:2229
static void match_unsorted_outer(PlannerInfo *root, RelOptInfo *joinrel, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, JoinPathExtraData *extra)
Definition: joinpath.c:1821
@ JOIN_SEMI
Definition: nodes.h:307
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_INNER
Definition: nodes.h:293
@ JOIN_UNIQUE_OUTER
Definition: nodes.h:316
@ JOIN_UNIQUE_INNER
Definition: nodes.h:317
@ JOIN_ANTI
Definition: nodes.h:308
List * mergeclause_list
Definition: pathnodes.h:3231
Relids param_source_rels
Definition: pathnodes.h:3235
SemiAntiJoinFactors semifactors
Definition: pathnodes.h:3234
SpecialJoinInfo * sjinfo
Definition: pathnodes.h:3233
Relids lateral_relids
Definition: pathnodes.h:907

References bms_add_members(), bms_difference(), bms_is_subset(), bms_join(), bms_overlap(), compute_semi_anti_join_factors(), enable_hashjoin, enable_mergejoin, hash_inner_and_outer(), JoinPathExtraData::inner_unique, innerrel_is_unique(), JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_SEMI, JOIN_UNIQUE_INNER, JOIN_UNIQUE_OUTER, SpecialJoinInfo::jointype, RelOptInfo::lateral_relids, lfirst, match_unsorted_outer(), JoinPathExtraData::mergeclause_list, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, JoinPathExtraData::param_source_rels, RelOptInfo::relids, RELOPT_OTHER_JOINREL, RelOptInfo::reloptkind, JoinPathExtraData::restrictlist, root, select_mergejoin_clauses(), JoinPathExtraData::semifactors, set_join_pathlist_hook, JoinPathExtraData::sjinfo, sort_inner_and_outer(), and RelOptInfo::top_parent_relids.

Referenced by populate_joinrel_with_paths().

◆ add_setop_child_rel_equivalences()

void add_setop_child_rel_equivalences ( PlannerInfo root,
RelOptInfo child_rel,
List child_tlist,
List setop_pathkeys 
)

Definition at line 2888 of file equivclass.c.

2890 {
2891  ListCell *lc;
2892  ListCell *lc2 = list_head(setop_pathkeys);
2893 
2894  foreach(lc, child_tlist)
2895  {
2896  TargetEntry *tle = lfirst_node(TargetEntry, lc);
2897  EquivalenceMember *parent_em;
2898  PathKey *pk;
2899 
2900  if (tle->resjunk)
2901  continue;
2902 
2903  if (lc2 == NULL)
2904  elog(ERROR, "too few pathkeys for set operation");
2905 
2906  pk = lfirst_node(PathKey, lc2);
2907  parent_em = linitial(pk->pk_eclass->ec_members);
2908 
2909  /*
2910  * We can safely pass the parent member as the first member in the
2911  * ec_members list as this is added first in generate_union_paths,
2912  * likewise, the JoinDomain can be that of the initial member of the
2913  * Pathkey's EquivalenceClass.
2914  */
2915  add_eq_member(pk->pk_eclass,
2916  tle->expr,
2917  child_rel->relids,
2918  parent_em->em_jdomain,
2919  parent_em,
2920  exprType((Node *) tle->expr));
2921 
2922  lc2 = lnext(setop_pathkeys, lc2);
2923  }
2924 
2925  /*
2926  * transformSetOperationStmt() ensures that the targetlist never contains
2927  * any resjunk columns, so all eclasses that exist in 'root' must have
2928  * received a new member in the loop above. Add them to the child_rel's
2929  * eclass_indexes.
2930  */
2931  child_rel->eclass_indexes = bms_add_range(child_rel->eclass_indexes, 0,
2932  list_length(root->eq_classes) - 1);
2933 }
Bitmapset * bms_add_range(Bitmapset *a, int lower, int upper)
Definition: bitmapset.c:1019
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
Expr * expr
Definition: primnodes.h:2186

References add_eq_member(), bms_add_range(), RelOptInfo::eclass_indexes, elog, EquivalenceMember::em_jdomain, ERROR, TargetEntry::expr, exprType(), lfirst_node, linitial, list_head(), list_length(), lnext(), RelOptInfo::relids, and root.

Referenced by build_setop_child_paths().

◆ append_pathkeys()

List* append_pathkeys ( List target,
List source 
)

Definition at line 106 of file pathkeys.c.

107 {
108  ListCell *lc;
109 
110  Assert(target != NIL);
111 
112  foreach(lc, source)
113  {
114  PathKey *pk = lfirst_node(PathKey, lc);
115 
116  if (!pathkey_is_redundant(pk, target))
117  target = lappend(target, pk);
118  }
119  return target;
120 }
static bool pathkey_is_redundant(PathKey *new_pathkey, List *pathkeys)
Definition: pathkeys.c:158
static rewind_source * source
Definition: pg_rewind.c:89

References Assert, lappend(), lfirst_node, NIL, pathkey_is_redundant(), and source.

Referenced by adjust_group_pathkeys_for_groupagg(), and make_pathkeys_for_window().

◆ build_expression_pathkey()

List* build_expression_pathkey ( PlannerInfo root,
Expr expr,
Oid  opno,
Relids  rel,
bool  create_it 
)

Definition at line 998 of file pathkeys.c.

1003 {
1004  List *pathkeys;
1005  Oid opfamily,
1006  opcintype;
1007  int16 strategy;
1008  PathKey *cpathkey;
1009 
1010  /* Find the operator in pg_amop --- failure shouldn't happen */
1011  if (!get_ordering_op_properties(opno,
1012  &opfamily, &opcintype, &strategy))
1013  elog(ERROR, "operator %u is not a valid ordering operator",
1014  opno);
1015 
1016  cpathkey = make_pathkey_from_sortinfo(root,
1017  expr,
1018  opfamily,
1019  opcintype,
1020  exprCollation((Node *) expr),
1021  (strategy == BTGreaterStrategyNumber),
1022  (strategy == BTGreaterStrategyNumber),
1023  0,
1024  rel,
1025  create_it);
1026 
1027  if (cpathkey)
1028  pathkeys = list_make1(cpathkey);
1029  else
1030  pathkeys = NIL;
1031 
1032  return pathkeys;
1033 }
signed short int16
Definition: c.h:493
bool get_ordering_op_properties(Oid opno, Oid *opfamily, Oid *opcintype, int16 *strategy)
Definition: lsyscache.c:207
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
static PathKey * make_pathkey_from_sortinfo(PlannerInfo *root, Expr *expr, Oid opfamily, Oid opcintype, Oid collation, bool reverse_sort, bool nulls_first, Index sortref, Relids rel, bool create_it)
Definition: pathkeys.c:197
unsigned int Oid
Definition: postgres_ext.h:31
#define BTGreaterStrategyNumber
Definition: stratnum.h:33

References BTGreaterStrategyNumber, elog, ERROR, exprCollation(), get_ordering_op_properties(), list_make1, make_pathkey_from_sortinfo(), NIL, and root.

Referenced by set_function_pathlist().

◆ build_index_pathkeys()

List* build_index_pathkeys ( PlannerInfo root,
IndexOptInfo index,
ScanDirection  scandir 
)

Definition at line 738 of file pathkeys.c.

741 {
742  List *retval = NIL;
743  ListCell *lc;
744  int i;
745 
746  if (index->sortopfamily == NULL)
747  return NIL; /* non-orderable index */
748 
749  i = 0;
750  foreach(lc, index->indextlist)
751  {
752  TargetEntry *indextle = (TargetEntry *) lfirst(lc);
753  Expr *indexkey;
754  bool reverse_sort;
755  bool nulls_first;
756  PathKey *cpathkey;
757 
758  /*
759  * INCLUDE columns are stored in index unordered, so they don't
760  * support ordered index scan.
761  */
762  if (i >= index->nkeycolumns)
763  break;
764 
765  /* We assume we don't need to make a copy of the tlist item */
766  indexkey = indextle->expr;
767 
768  if (ScanDirectionIsBackward(scandir))
769  {
770  reverse_sort = !index->reverse_sort[i];
771  nulls_first = !index->nulls_first[i];
772  }
773  else
774  {
775  reverse_sort = index->reverse_sort[i];
776  nulls_first = index->nulls_first[i];
777  }
778 
779  /*
780  * OK, try to make a canonical pathkey for this sort key.
781  */
782  cpathkey = make_pathkey_from_sortinfo(root,
783  indexkey,
784  index->sortopfamily[i],
785  index->opcintype[i],
786  index->indexcollations[i],
787  reverse_sort,
788  nulls_first,
789  0,
790  index->rel->relids,
791  false);
792 
793  if (cpathkey)
794  {
795  /*
796  * We found the sort key in an EquivalenceClass, so it's relevant
797  * for this query. Add it to list, unless it's redundant.
798  */
799  if (!pathkey_is_redundant(cpathkey, retval))
800  retval = lappend(retval, cpathkey);
801  }
802  else
803  {
804  /*
805  * Boolean index keys might be redundant even if they do not
806  * appear in an EquivalenceClass, because of our special treatment
807  * of boolean equality conditions --- see the comment for
808  * indexcol_is_bool_constant_for_query(). If that applies, we can
809  * continue to examine lower-order index columns. Otherwise, the
810  * sort key is not an interesting sort order for this query, so we
811  * should stop considering index columns; any lower-order sort
812  * keys won't be useful either.
813  */
815  break;
816  }
817 
818  i++;
819  }
820 
821  return retval;
822 }
bool indexcol_is_bool_constant_for_query(PlannerInfo *root, IndexOptInfo *index, int indexcol)
Definition: indxpath.c:3614
#define ScanDirectionIsBackward(direction)
Definition: sdir.h:50
Definition: type.h:95

References TargetEntry::expr, i, indexcol_is_bool_constant_for_query(), lappend(), lfirst, make_pathkey_from_sortinfo(), NIL, pathkey_is_redundant(), root, and ScanDirectionIsBackward.

Referenced by build_index_paths().

◆ build_join_pathkeys()

List* build_join_pathkeys ( PlannerInfo root,
RelOptInfo joinrel,
JoinType  jointype,
List outer_pathkeys 
)

Definition at line 1292 of file pathkeys.c.

1296 {
1297  /* RIGHT_SEMI should not come here */
1298  Assert(jointype != JOIN_RIGHT_SEMI);
1299 
1300  if (jointype == JOIN_FULL ||
1301  jointype == JOIN_RIGHT ||
1302  jointype == JOIN_RIGHT_ANTI)
1303  return NIL;
1304 
1305  /*
1306  * This used to be quite a complex bit of code, but now that all pathkey
1307  * sublists start out life canonicalized, we don't have to do a darn thing
1308  * here!
1309  *
1310  * We do, however, need to truncate the pathkeys list, since it may
1311  * contain pathkeys that were useful for forming this joinrel but are
1312  * uninteresting to higher levels.
1313  */
1314  return truncate_useless_pathkeys(root, joinrel, outer_pathkeys);
1315 }
@ JOIN_RIGHT
Definition: nodes.h:296
@ JOIN_RIGHT_SEMI
Definition: nodes.h:309
@ JOIN_RIGHT_ANTI
Definition: nodes.h:310
List * truncate_useless_pathkeys(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
Definition: pathkeys.c:2215

References Assert, JOIN_FULL, JOIN_RIGHT, JOIN_RIGHT_ANTI, JOIN_RIGHT_SEMI, NIL, root, and truncate_useless_pathkeys().

Referenced by consider_parallel_mergejoin(), consider_parallel_nestloop(), match_unsorted_outer(), and sort_inner_and_outer().

◆ build_partition_pathkeys()

List* build_partition_pathkeys ( PlannerInfo root,
RelOptInfo partrel,
ScanDirection  scandir,
bool partialkeys 
)

Definition at line 917 of file pathkeys.c.

919 {
920  List *retval = NIL;
921  PartitionScheme partscheme = partrel->part_scheme;
922  int i;
923 
924  Assert(partscheme != NULL);
925  Assert(partitions_are_ordered(partrel->boundinfo, partrel->live_parts));
926  /* For now, we can only cope with baserels */
927  Assert(IS_SIMPLE_REL(partrel));
928 
929  for (i = 0; i < partscheme->partnatts; i++)
930  {
931  PathKey *cpathkey;
932  Expr *keyCol = (Expr *) linitial(partrel->partexprs[i]);
933 
934  /*
935  * Try to make a canonical pathkey for this partkey.
936  *
937  * We assume the PartitionDesc lists any NULL partition last, so we
938  * treat the scan like a NULLS LAST index: we have nulls_first for
939  * backwards scan only.
940  */
941  cpathkey = make_pathkey_from_sortinfo(root,
942  keyCol,
943  partscheme->partopfamily[i],
944  partscheme->partopcintype[i],
945  partscheme->partcollation[i],
946  ScanDirectionIsBackward(scandir),
947  ScanDirectionIsBackward(scandir),
948  0,
949  partrel->relids,
950  false);
951 
952 
953  if (cpathkey)
954  {
955  /*
956  * We found the sort key in an EquivalenceClass, so it's relevant
957  * for this query. Add it to list, unless it's redundant.
958  */
959  if (!pathkey_is_redundant(cpathkey, retval))
960  retval = lappend(retval, cpathkey);
961  }
962  else
963  {
964  /*
965  * Boolean partition keys might be redundant even if they do not
966  * appear in an EquivalenceClass, because of our special treatment
967  * of boolean equality conditions --- see the comment for
968  * partkey_is_bool_constant_for_query(). If that applies, we can
969  * continue to examine lower-order partition keys. Otherwise, the
970  * sort key is not an interesting sort order for this query, so we
971  * should stop considering partition columns; any lower-order sort
972  * keys won't be useful either.
973  */
974  if (!partkey_is_bool_constant_for_query(partrel, i))
975  {
976  *partialkeys = true;
977  return retval;
978  }
979  }
980  }
981 
982  *partialkeys = false;
983  return retval;
984 }
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
Definition: partbounds.c:2852
static bool partkey_is_bool_constant_for_query(RelOptInfo *partrel, int partkeycol)
Definition: pathkeys.c:842
Bitmapset * live_parts
Definition: pathnodes.h:1033

References Assert, i, IS_SIMPLE_REL, lappend(), linitial, RelOptInfo::live_parts, make_pathkey_from_sortinfo(), NIL, PartitionSchemeData::partcollation, partitions_are_ordered(), partkey_is_bool_constant_for_query(), PartitionSchemeData::partnatts, PartitionSchemeData::partopcintype, PartitionSchemeData::partopfamily, pathkey_is_redundant(), RelOptInfo::relids, root, and ScanDirectionIsBackward.

Referenced by generate_orderedappend_paths().

◆ canonicalize_ec_expression()

Expr* canonicalize_ec_expression ( Expr expr,
Oid  req_type,
Oid  req_collation 
)

Definition at line 472 of file equivclass.c.

473 {
474  Oid expr_type = exprType((Node *) expr);
475 
476  /*
477  * For a polymorphic-input-type opclass, just keep the same exposed type.
478  * RECORD opclasses work like polymorphic-type ones for this purpose.
479  */
480  if (IsPolymorphicType(req_type) || req_type == RECORDOID)
481  req_type = expr_type;
482 
483  /*
484  * No work if the expression exposes the right type/collation already.
485  */
486  if (expr_type != req_type ||
487  exprCollation((Node *) expr) != req_collation)
488  {
489  /*
490  * If we have to change the type of the expression, set typmod to -1,
491  * since the new type may not have the same typmod interpretation.
492  * When we only have to change collation, preserve the exposed typmod.
493  */
494  int32 req_typmod;
495 
496  if (expr_type != req_type)
497  req_typmod = -1;
498  else
499  req_typmod = exprTypmod((Node *) expr);
500 
501  /*
502  * Use applyRelabelType so that we preserve const-flatness. This is
503  * important since eval_const_expressions has already been applied.
504  */
505  expr = (Expr *) applyRelabelType((Node *) expr,
506  req_type, req_typmod, req_collation,
507  COERCE_IMPLICIT_CAST, -1, false);
508  }
509 
510  return expr;
511 }
signed int int32
Definition: c.h:494
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
Node * applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation, bool overwrite_ok)
Definition: nodeFuncs.c:631
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:736

References applyRelabelType(), COERCE_IMPLICIT_CAST, exprCollation(), exprType(), and exprTypmod().

Referenced by convert_subquery_pathkeys(), get_eclass_for_sort_expr(), and process_equivalence().

◆ check_index_predicates()

void check_index_predicates ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 3244 of file indxpath.c.

3245 {
3246  List *clauselist;
3247  bool have_partial;
3248  bool is_target_rel;
3249  Relids otherrels;
3250  ListCell *lc;
3251 
3252  /* Indexes are available only on base or "other" member relations. */
3253  Assert(IS_SIMPLE_REL(rel));
3254 
3255  /*
3256  * Initialize the indrestrictinfo lists to be identical to
3257  * baserestrictinfo, and check whether there are any partial indexes. If
3258  * not, this is all we need to do.
3259  */
3260  have_partial = false;
3261  foreach(lc, rel->indexlist)
3262  {
3264 
3265  index->indrestrictinfo = rel->baserestrictinfo;
3266  if (index->indpred)
3267  have_partial = true;
3268  }
3269  if (!have_partial)
3270  return;
3271 
3272  /*
3273  * Construct a list of clauses that we can assume true for the purpose of
3274  * proving the index(es) usable. Restriction clauses for the rel are
3275  * always usable, and so are any join clauses that are "movable to" this
3276  * rel. Also, we can consider any EC-derivable join clauses (which must
3277  * be "movable to" this rel, by definition).
3278  */
3279  clauselist = list_copy(rel->baserestrictinfo);
3280 
3281  /* Scan the rel's join clauses */
3282  foreach(lc, rel->joininfo)
3283  {
3284  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3285 
3286  /* Check if clause can be moved to this rel */
3287  if (!join_clause_is_movable_to(rinfo, rel))
3288  continue;
3289 
3290  clauselist = lappend(clauselist, rinfo);
3291  }
3292 
3293  /*
3294  * Add on any equivalence-derivable join clauses. Computing the correct
3295  * relid sets for generate_join_implied_equalities is slightly tricky
3296  * because the rel could be a child rel rather than a true baserel, and in
3297  * that case we must subtract its parents' relid(s) from all_query_rels.
3298  * Additionally, we mustn't consider clauses that are only computable
3299  * after outer joins that can null the rel.
3300  */
3301  if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3302  otherrels = bms_difference(root->all_query_rels,
3303  find_childrel_parents(root, rel));
3304  else
3305  otherrels = bms_difference(root->all_query_rels, rel->relids);
3306  otherrels = bms_del_members(otherrels, rel->nulling_relids);
3307 
3308  if (!bms_is_empty(otherrels))
3309  clauselist =
3310  list_concat(clauselist,
3312  bms_union(rel->relids,
3313  otherrels),
3314  otherrels,
3315  rel,
3316  NULL));
3317 
3318  /*
3319  * Normally we remove quals that are implied by a partial index's
3320  * predicate from indrestrictinfo, indicating that they need not be
3321  * checked explicitly by an indexscan plan using this index. However, if
3322  * the rel is a target relation of UPDATE/DELETE/MERGE/SELECT FOR UPDATE,
3323  * we cannot remove such quals from the plan, because they need to be in
3324  * the plan so that they will be properly rechecked by EvalPlanQual
3325  * testing. Some day we might want to remove such quals from the main
3326  * plan anyway and pass them through to EvalPlanQual via a side channel;
3327  * but for now, we just don't remove implied quals at all for target
3328  * relations.
3329  */
3330  is_target_rel = (bms_is_member(rel->relid, root->all_result_relids) ||
3331  get_plan_rowmark(root->rowMarks, rel->relid) != NULL);
3332 
3333  /*
3334  * Now try to prove each index predicate true, and compute the
3335  * indrestrictinfo lists for partial indexes. Note that we compute the
3336  * indrestrictinfo list even for non-predOK indexes; this might seem
3337  * wasteful, but we may be able to use such indexes in OR clauses, cf
3338  * generate_bitmap_or_paths().
3339  */
3340  foreach(lc, rel->indexlist)
3341  {
3343  ListCell *lcr;
3344 
3345  if (index->indpred == NIL)
3346  continue; /* ignore non-partial indexes here */
3347 
3348  if (!index->predOK) /* don't repeat work if already proven OK */
3349  index->predOK = predicate_implied_by(index->indpred, clauselist,
3350  false);
3351 
3352  /* If rel is an update target, leave indrestrictinfo as set above */
3353  if (is_target_rel)
3354  continue;
3355 
3356  /* Else compute indrestrictinfo as the non-implied quals */
3357  index->indrestrictinfo = NIL;
3358  foreach(lcr, rel->baserestrictinfo)
3359  {
3360  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcr);
3361 
3362  /* predicate_implied_by() assumes first arg is immutable */
3363  if (contain_mutable_functions((Node *) rinfo->clause) ||
3365  index->indpred, false))
3366  index->indrestrictinfo = lappend(index->indrestrictinfo, rinfo);
3367  }
3368  }
3369 }
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:251
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:1161
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:370
List * generate_join_implied_equalities(PlannerInfo *root, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo)
Definition: equivclass.c:1381
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
@ RELOPT_OTHER_MEMBER_REL
Definition: pathnodes.h:823
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:152
PlanRowMark * get_plan_rowmark(List *rowmarks, Index rtindex)
Definition: preptlist.c:509
Relids find_childrel_parents(PlannerInfo *root, RelOptInfo *rel)
Definition: relnode.c:1521
bool join_clause_is_movable_to(RestrictInfo *rinfo, RelOptInfo *baserel)
Definition: restrictinfo.c:584
List * baserestrictinfo
Definition: pathnodes.h:979
List * joininfo
Definition: pathnodes.h:985
Index relid
Definition: pathnodes.h:912
List * indexlist
Definition: pathnodes.h:938
Relids nulling_relids
Definition: pathnodes.h:932
Expr * clause
Definition: pathnodes.h:2564

References Assert, RelOptInfo::baserestrictinfo, bms_del_members(), bms_difference(), bms_is_empty, bms_is_member(), bms_union(), RestrictInfo::clause, contain_mutable_functions(), find_childrel_parents(), generate_join_implied_equalities(), get_plan_rowmark(), RelOptInfo::indexlist, IS_SIMPLE_REL, join_clause_is_movable_to(), RelOptInfo::joininfo, lappend(), lfirst, list_concat(), list_copy(), list_make1, NIL, RelOptInfo::nulling_relids, predicate_implied_by(), RelOptInfo::relid, RelOptInfo::relids, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, and root.

Referenced by set_plain_rel_size(), and set_tablesample_rel_size().

◆ compare_pathkeys()

PathKeysComparison compare_pathkeys ( List keys1,
List keys2 
)

Definition at line 302 of file pathkeys.c.

303 {
304  ListCell *key1,
305  *key2;
306 
307  /*
308  * Fall out quickly if we are passed two identical lists. This mostly
309  * catches the case where both are NIL, but that's common enough to
310  * warrant the test.
311  */
312  if (keys1 == keys2)
313  return PATHKEYS_EQUAL;
314 
315  forboth(key1, keys1, key2, keys2)
316  {
317  PathKey *pathkey1 = (PathKey *) lfirst(key1);
318  PathKey *pathkey2 = (PathKey *) lfirst(key2);
319 
320  if (pathkey1 != pathkey2)
321  return PATHKEYS_DIFFERENT; /* no need to keep looking */
322  }
323 
324  /*
325  * If we reached the end of only one list, the other is longer and
326  * therefore not a subset.
327  */
328  if (key1 != NULL)
329  return PATHKEYS_BETTER1; /* key1 is longer */
330  if (key2 != NULL)
331  return PATHKEYS_BETTER2; /* key2 is longer */
332  return PATHKEYS_EQUAL;
333 }
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518

References forboth, lfirst, PATHKEYS_BETTER1, PATHKEYS_BETTER2, PATHKEYS_DIFFERENT, and PATHKEYS_EQUAL.

Referenced by add_partial_path(), add_partial_path_precheck(), add_path(), add_path_precheck(), add_paths_to_append_rel(), adjust_group_pathkeys_for_groupagg(), get_useful_group_keys_orderings(), pathkeys_contained_in(), and set_cheapest().

◆ compute_parallel_worker()

int compute_parallel_worker ( RelOptInfo rel,
double  heap_pages,
double  index_pages,
int  max_workers 
)

Definition at line 4210 of file allpaths.c.

4212 {
4213  int parallel_workers = 0;
4214 
4215  /*
4216  * If the user has set the parallel_workers reloption, use that; otherwise
4217  * select a default number of workers.
4218  */
4219  if (rel->rel_parallel_workers != -1)
4220  parallel_workers = rel->rel_parallel_workers;
4221  else
4222  {
4223  /*
4224  * If the number of pages being scanned is insufficient to justify a
4225  * parallel scan, just return zero ... unless it's an inheritance
4226  * child. In that case, we want to generate a parallel path here
4227  * anyway. It might not be worthwhile just for this relation, but
4228  * when combined with all of its inheritance siblings it may well pay
4229  * off.
4230  */
4231  if (rel->reloptkind == RELOPT_BASEREL &&
4232  ((heap_pages >= 0 && heap_pages < min_parallel_table_scan_size) ||
4233  (index_pages >= 0 && index_pages < min_parallel_index_scan_size)))
4234  return 0;
4235 
4236  if (heap_pages >= 0)
4237  {
4238  int heap_parallel_threshold;
4239  int heap_parallel_workers = 1;
4240 
4241  /*
4242  * Select the number of workers based on the log of the size of
4243  * the relation. This probably needs to be a good deal more
4244  * sophisticated, but we need something here for now. Note that
4245  * the upper limit of the min_parallel_table_scan_size GUC is
4246  * chosen to prevent overflow here.
4247  */
4248  heap_parallel_threshold = Max(min_parallel_table_scan_size, 1);
4249  while (heap_pages >= (BlockNumber) (heap_parallel_threshold * 3))
4250  {
4251  heap_parallel_workers++;
4252  heap_parallel_threshold *= 3;
4253  if (heap_parallel_threshold > INT_MAX / 3)
4254  break; /* avoid overflow */
4255  }
4256 
4257  parallel_workers = heap_parallel_workers;
4258  }
4259 
4260  if (index_pages >= 0)
4261  {
4262  int index_parallel_workers = 1;
4263  int index_parallel_threshold;
4264 
4265  /* same calculation as for heap_pages above */
4266  index_parallel_threshold = Max(min_parallel_index_scan_size, 1);
4267  while (index_pages >= (BlockNumber) (index_parallel_threshold * 3))
4268  {
4269  index_parallel_workers++;
4270  index_parallel_threshold *= 3;
4271  if (index_parallel_threshold > INT_MAX / 3)
4272  break; /* avoid overflow */
4273  }
4274 
4275  if (parallel_workers > 0)
4276  parallel_workers = Min(parallel_workers, index_parallel_workers);
4277  else
4278  parallel_workers = index_parallel_workers;
4279  }
4280  }
4281 
4282  /* In no case use more than caller supplied maximum number of workers */
4283  parallel_workers = Min(parallel_workers, max_workers);
4284 
4285  return parallel_workers;
4286 }
int min_parallel_index_scan_size
Definition: allpaths.c:82
int min_parallel_table_scan_size
Definition: allpaths.c:81
uint32 BlockNumber
Definition: block.h:31
int rel_parallel_workers
Definition: pathnodes.h:950

References Max, Min, min_parallel_index_scan_size, min_parallel_table_scan_size, RelOptInfo::rel_parallel_workers, RELOPT_BASEREL, and RelOptInfo::reloptkind.

Referenced by cost_index(), create_partial_bitmap_paths(), create_plain_partial_paths(), and plan_create_index_workers().

◆ convert_subquery_pathkeys()

List* convert_subquery_pathkeys ( PlannerInfo root,
RelOptInfo rel,
List subquery_pathkeys,
List subquery_tlist 
)

Definition at line 1052 of file pathkeys.c.

1055 {
1056  List *retval = NIL;
1057  int retvallen = 0;
1058  int outer_query_keys = list_length(root->query_pathkeys);
1059  ListCell *i;
1060 
1061  foreach(i, subquery_pathkeys)
1062  {
1063  PathKey *sub_pathkey = (PathKey *) lfirst(i);
1064  EquivalenceClass *sub_eclass = sub_pathkey->pk_eclass;
1065  PathKey *best_pathkey = NULL;
1066 
1067  if (sub_eclass->ec_has_volatile)
1068  {
1069  /*
1070  * If the sub_pathkey's EquivalenceClass is volatile, then it must
1071  * have come from an ORDER BY clause, and we have to match it to
1072  * that same targetlist entry.
1073  */
1074  TargetEntry *tle;
1075  Var *outer_var;
1076 
1077  if (sub_eclass->ec_sortref == 0) /* can't happen */
1078  elog(ERROR, "volatile EquivalenceClass has no sortref");
1079  tle = get_sortgroupref_tle(sub_eclass->ec_sortref, subquery_tlist);
1080  Assert(tle);
1081  /* Is TLE actually available to the outer query? */
1082  outer_var = find_var_for_subquery_tle(rel, tle);
1083  if (outer_var)
1084  {
1085  /* We can represent this sub_pathkey */
1086  EquivalenceMember *sub_member;
1087  EquivalenceClass *outer_ec;
1088 
1089  Assert(list_length(sub_eclass->ec_members) == 1);
1090  sub_member = (EquivalenceMember *) linitial(sub_eclass->ec_members);
1091 
1092  /*
1093  * Note: it might look funny to be setting sortref = 0 for a
1094  * reference to a volatile sub_eclass. However, the
1095  * expression is *not* volatile in the outer query: it's just
1096  * a Var referencing whatever the subquery emitted. (IOW, the
1097  * outer query isn't going to re-execute the volatile
1098  * expression itself.) So this is okay.
1099  */
1100  outer_ec =
1102  (Expr *) outer_var,
1103  sub_eclass->ec_opfamilies,
1104  sub_member->em_datatype,
1105  sub_eclass->ec_collation,
1106  0,
1107  rel->relids,
1108  false);
1109 
1110  /*
1111  * If we don't find a matching EC, sub-pathkey isn't
1112  * interesting to the outer query
1113  */
1114  if (outer_ec)
1115  best_pathkey =
1117  outer_ec,
1118  sub_pathkey->pk_opfamily,
1119  sub_pathkey->pk_strategy,
1120  sub_pathkey->pk_nulls_first);
1121  }
1122  }
1123  else
1124  {
1125  /*
1126  * Otherwise, the sub_pathkey's EquivalenceClass could contain
1127  * multiple elements (representing knowledge that multiple items
1128  * are effectively equal). Each element might match none, one, or
1129  * more of the output columns that are visible to the outer query.
1130  * This means we may have multiple possible representations of the
1131  * sub_pathkey in the context of the outer query. Ideally we
1132  * would generate them all and put them all into an EC of the
1133  * outer query, thereby propagating equality knowledge up to the
1134  * outer query. Right now we cannot do so, because the outer
1135  * query's EquivalenceClasses are already frozen when this is
1136  * called. Instead we prefer the one that has the highest "score"
1137  * (number of EC peers, plus one if it matches the outer
1138  * query_pathkeys). This is the most likely to be useful in the
1139  * outer query.
1140  */
1141  int best_score = -1;
1142  ListCell *j;
1143 
1144  foreach(j, sub_eclass->ec_members)
1145  {
1146  EquivalenceMember *sub_member = (EquivalenceMember *) lfirst(j);
1147  Expr *sub_expr = sub_member->em_expr;
1148  Oid sub_expr_type = sub_member->em_datatype;
1149  Oid sub_expr_coll = sub_eclass->ec_collation;
1150  ListCell *k;
1151 
1152  if (sub_member->em_is_child)
1153  continue; /* ignore children here */
1154 
1155  foreach(k, subquery_tlist)
1156  {
1157  TargetEntry *tle = (TargetEntry *) lfirst(k);
1158  Var *outer_var;
1159  Expr *tle_expr;
1160  EquivalenceClass *outer_ec;
1161  PathKey *outer_pk;
1162  int score;
1163 
1164  /* Is TLE actually available to the outer query? */
1165  outer_var = find_var_for_subquery_tle(rel, tle);
1166  if (!outer_var)
1167  continue;
1168 
1169  /*
1170  * The targetlist entry is considered to match if it
1171  * matches after sort-key canonicalization. That is
1172  * needed since the sub_expr has been through the same
1173  * process.
1174  */
1175  tle_expr = canonicalize_ec_expression(tle->expr,
1176  sub_expr_type,
1177  sub_expr_coll);
1178  if (!equal(tle_expr, sub_expr))
1179  continue;
1180 
1181  /* See if we have a matching EC for the TLE */
1182  outer_ec = get_eclass_for_sort_expr(root,
1183  (Expr *) outer_var,
1184  sub_eclass->ec_opfamilies,
1185  sub_expr_type,
1186  sub_expr_coll,
1187  0,
1188  rel->relids,
1189  false);
1190 
1191  /*
1192  * If we don't find a matching EC, this sub-pathkey isn't
1193  * interesting to the outer query
1194  */
1195  if (!outer_ec)
1196  continue;
1197 
1198  outer_pk = make_canonical_pathkey(root,
1199  outer_ec,
1200  sub_pathkey->pk_opfamily,
1201  sub_pathkey->pk_strategy,
1202  sub_pathkey->pk_nulls_first);
1203  /* score = # of equivalence peers */
1204  score = list_length(outer_ec->ec_members) - 1;
1205  /* +1 if it matches the proper query_pathkeys item */
1206  if (retvallen < outer_query_keys &&
1207  list_nth(root->query_pathkeys, retvallen) == outer_pk)
1208  score++;
1209  if (score > best_score)
1210  {
1211  best_pathkey = outer_pk;
1212  best_score = score;
1213  }
1214  }
1215  }
1216  }
1217 
1218  /*
1219  * If we couldn't find a representation of this sub_pathkey, we're
1220  * done (we can't use the ones to its right, either).
1221  */
1222  if (!best_pathkey)
1223  break;
1224 
1225  /*
1226  * Eliminate redundant ordering info; could happen if outer query
1227  * equivalences subquery keys...
1228  */
1229  if (!pathkey_is_redundant(best_pathkey, retval))
1230  {
1231  retval = lappend(retval, best_pathkey);
1232  retvallen++;
1233  }
1234  }
1235 
1236  return retval;
1237 }
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
Expr * canonicalize_ec_expression(Expr *expr, Oid req_type, Oid req_collation)
Definition: equivclass.c:472
EquivalenceClass * get_eclass_for_sort_expr(PlannerInfo *root, Expr *expr, List *opfamilies, Oid opcintype, Oid collation, Index sortref, Relids rel, bool create_it)
Definition: equivclass.c:587
int j
Definition: isn.c:74
static Var * find_var_for_subquery_tle(RelOptInfo *rel, TargetEntry *tle)
Definition: pathkeys.c:1249
PathKey * make_canonical_pathkey(PlannerInfo *root, EquivalenceClass *eclass, Oid opfamily, int strategy, bool nulls_first)
Definition: pathkeys.c:55
List * ec_opfamilies
Definition: pathnodes.h:1383
bool pk_nulls_first
Definition: pathnodes.h:1471
int pk_strategy
Definition: pathnodes.h:1470
Oid pk_opfamily
Definition: pathnodes.h:1469
Definition: primnodes.h:248
TargetEntry * get_sortgroupref_tle(Index sortref, List *targetList)
Definition: tlist.c:345

References Assert, canonicalize_ec_expression(), EquivalenceClass::ec_collation, EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_members, EquivalenceClass::ec_opfamilies, EquivalenceClass::ec_sortref, elog, EquivalenceMember::em_datatype, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, equal(), ERROR, TargetEntry::expr, find_var_for_subquery_tle(), get_eclass_for_sort_expr(), get_sortgroupref_tle(), i, j, lappend(), lfirst, linitial, list_length(), list_nth(), make_canonical_pathkey(), NIL, pathkey_is_redundant(), PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, RelOptInfo::relids, and root.

Referenced by build_setop_child_paths(), set_cte_pathlist(), and set_subquery_pathlist().

◆ create_index_paths()

void create_index_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 234 of file indxpath.c.

235 {
236  List *indexpaths;
237  List *bitindexpaths;
238  List *bitjoinpaths;
239  List *joinorclauses;
240  IndexClauseSet rclauseset;
241  IndexClauseSet jclauseset;
242  IndexClauseSet eclauseset;
243  ListCell *lc;
244 
245  /* Skip the whole mess if no indexes */
246  if (rel->indexlist == NIL)
247  return;
248 
249  /* Bitmap paths are collected and then dealt with at the end */
250  bitindexpaths = bitjoinpaths = joinorclauses = NIL;
251 
252  /* Examine each index in turn */
253  foreach(lc, rel->indexlist)
254  {
256 
257  /* Protect limited-size array in IndexClauseSets */
258  Assert(index->nkeycolumns <= INDEX_MAX_KEYS);
259 
260  /*
261  * Ignore partial indexes that do not match the query.
262  * (generate_bitmap_or_paths() might be able to do something with
263  * them, but that's of no concern here.)
264  */
265  if (index->indpred != NIL && !index->predOK)
266  continue;
267 
268  /*
269  * Identify the restriction clauses that can match the index.
270  */
271  MemSet(&rclauseset, 0, sizeof(rclauseset));
273 
274  /*
275  * Build index paths from the restriction clauses. These will be
276  * non-parameterized paths. Plain paths go directly to add_path(),
277  * bitmap paths are added to bitindexpaths to be handled below.
278  */
279  get_index_paths(root, rel, index, &rclauseset,
280  &bitindexpaths);
281 
282  /*
283  * Identify the join clauses that can match the index. For the moment
284  * we keep them separate from the restriction clauses. Note that this
285  * step finds only "loose" join clauses that have not been merged into
286  * EquivalenceClasses. Also, collect join OR clauses for later.
287  */
288  MemSet(&jclauseset, 0, sizeof(jclauseset));
290  &jclauseset, &joinorclauses);
291 
292  /*
293  * Look for EquivalenceClasses that can generate joinclauses matching
294  * the index.
295  */
296  MemSet(&eclauseset, 0, sizeof(eclauseset));
298  &eclauseset);
299 
300  /*
301  * If we found any plain or eclass join clauses, build parameterized
302  * index paths using them.
303  */
304  if (jclauseset.nonempty || eclauseset.nonempty)
306  &rclauseset,
307  &jclauseset,
308  &eclauseset,
309  &bitjoinpaths);
310  }
311 
312  /*
313  * Generate BitmapOrPaths for any suitable OR-clauses present in the
314  * restriction list. Add these to bitindexpaths.
315  */
316  indexpaths = generate_bitmap_or_paths(root, rel,
317  rel->baserestrictinfo, NIL);
318  bitindexpaths = list_concat(bitindexpaths, indexpaths);
319 
320  /*
321  * Likewise, generate BitmapOrPaths for any suitable OR-clauses present in
322  * the joinclause list. Add these to bitjoinpaths.
323  */
324  indexpaths = generate_bitmap_or_paths(root, rel,
325  joinorclauses, rel->baserestrictinfo);
326  bitjoinpaths = list_concat(bitjoinpaths, indexpaths);
327 
328  /*
329  * If we found anything usable, generate a BitmapHeapPath for the most
330  * promising combination of restriction bitmap index paths. Note there
331  * will be only one such path no matter how many indexes exist. This
332  * should be sufficient since there's basically only one figure of merit
333  * (total cost) for such a path.
334  */
335  if (bitindexpaths != NIL)
336  {
337  Path *bitmapqual;
338  BitmapHeapPath *bpath;
339 
340  bitmapqual = choose_bitmap_and(root, rel, bitindexpaths);
341  bpath = create_bitmap_heap_path(root, rel, bitmapqual,
342  rel->lateral_relids, 1.0, 0);
343  add_path(rel, (Path *) bpath);
344 
345  /* create a partial bitmap heap path */
346  if (rel->consider_parallel && rel->lateral_relids == NULL)
347  create_partial_bitmap_paths(root, rel, bitmapqual);
348  }
349 
350  /*
351  * Likewise, if we found anything usable, generate BitmapHeapPaths for the
352  * most promising combinations of join bitmap index paths. Our strategy
353  * is to generate one such path for each distinct parameterization seen
354  * among the available bitmap index paths. This may look pretty
355  * expensive, but usually there won't be very many distinct
356  * parameterizations. (This logic is quite similar to that in
357  * consider_index_join_clauses, but we're working with whole paths not
358  * individual clauses.)
359  */
360  if (bitjoinpaths != NIL)
361  {
362  List *all_path_outers;
363 
364  /* Identify each distinct parameterization seen in bitjoinpaths */
365  all_path_outers = NIL;
366  foreach(lc, bitjoinpaths)
367  {
368  Path *path = (Path *) lfirst(lc);
369  Relids required_outer = PATH_REQ_OUTER(path);
370 
371  all_path_outers = list_append_unique(all_path_outers,
372  required_outer);
373  }
374 
375  /* Now, for each distinct parameterization set ... */
376  foreach(lc, all_path_outers)
377  {
378  Relids max_outers = (Relids) lfirst(lc);
379  List *this_path_set;
380  Path *bitmapqual;
381  Relids required_outer;
382  double loop_count;
383  BitmapHeapPath *bpath;
384  ListCell *lcp;
385 
386  /* Identify all the bitmap join paths needing no more than that */
387  this_path_set = NIL;
388  foreach(lcp, bitjoinpaths)
389  {
390  Path *path = (Path *) lfirst(lcp);
391 
392  if (bms_is_subset(PATH_REQ_OUTER(path), max_outers))
393  this_path_set = lappend(this_path_set, path);
394  }
395 
396  /*
397  * Add in restriction bitmap paths, since they can be used
398  * together with any join paths.
399  */
400  this_path_set = list_concat(this_path_set, bitindexpaths);
401 
402  /* Select best AND combination for this parameterization */
403  bitmapqual = choose_bitmap_and(root, rel, this_path_set);
404 
405  /* And push that path into the mix */
406  required_outer = PATH_REQ_OUTER(bitmapqual);
407  loop_count = get_loop_count(root, rel->relid, required_outer);
408  bpath = create_bitmap_heap_path(root, rel, bitmapqual,
409  required_outer, loop_count, 0);
410  add_path(rel, (Path *) bpath);
411  }
412  }
413 }
void create_partial_bitmap_paths(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual)
Definition: allpaths.c:4174
#define MemSet(start, val, len)
Definition: c.h:1020
static Path * choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel, List *paths)
Definition: indxpath.c:1287
static void match_join_clauses_to_index(PlannerInfo *root, RelOptInfo *rel, IndexOptInfo *index, IndexClauseSet *clauseset, List **joinorclauses)
Definition: indxpath.c:1983
static void match_eclass_clauses_to_index(PlannerInfo *root, IndexOptInfo *index, IndexClauseSet *clauseset)
Definition: indxpath.c:2013
static void get_index_paths(PlannerInfo *root, RelOptInfo *rel, IndexOptInfo *index, IndexClauseSet *clauses, List **bitindexpaths)
Definition: indxpath.c:710
static double get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids)
Definition: indxpath.c:1829
static void consider_index_join_clauses(PlannerInfo *root, RelOptInfo *rel, IndexOptInfo *index, IndexClauseSet *rclauseset, IndexClauseSet *jclauseset, IndexClauseSet *eclauseset, List **bitindexpaths)
Definition: indxpath.c:431
static void match_restriction_clauses_to_index(PlannerInfo *root, IndexOptInfo *index, IndexClauseSet *clauseset)
Definition: indxpath.c:1968
static List * generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel, List *clauses, List *other_clauses)
Definition: indxpath.c:1180
List * list_append_unique(List *list, void *datum)
Definition: list.c:1343
BitmapHeapPath * create_bitmap_heap_path(PlannerInfo *root, RelOptInfo *rel, Path *bitmapqual, Relids required_outer, double loop_count, int parallel_degree)
Definition: pathnode.c:1042
#define INDEX_MAX_KEYS
bool nonempty
Definition: indxpath.c:54

References add_path(), Assert, RelOptInfo::baserestrictinfo, bms_is_subset(), choose_bitmap_and(), consider_index_join_clauses(), RelOptInfo::consider_parallel, create_bitmap_heap_path(), create_partial_bitmap_paths(), generate_bitmap_or_paths(), get_index_paths(), get_loop_count(), INDEX_MAX_KEYS, RelOptInfo::indexlist, lappend(), RelOptInfo::lateral_relids, lfirst, list_append_unique(), list_concat(), match_eclass_clauses_to_index(), match_join_clauses_to_index(), match_restriction_clauses_to_index(), MemSet, NIL, IndexClauseSet::nonempty, PATH_REQ_OUTER, RelOptInfo::relid, and root.

Referenced by set_plain_rel_pathlist().

◆ create_partial_bitmap_paths()

void create_partial_bitmap_paths ( PlannerInfo root,
RelOptInfo rel,
Path bitmapqual 
)

Definition at line 4174 of file allpaths.c.

4176 {
4177  int parallel_workers;
4178  double pages_fetched;
4179 
4180  /* Compute heap pages for bitmap heap scan */
4181  pages_fetched = compute_bitmap_pages(root, rel, bitmapqual, 1.0,
4182  NULL, NULL);
4183 
4184  parallel_workers = compute_parallel_worker(rel, pages_fetched, -1,
4186 
4187  if (parallel_workers <= 0)
4188  return;
4189 
4191  bitmapqual, rel->lateral_relids, 1.0, parallel_workers));
4192 }
int compute_parallel_worker(RelOptInfo *rel, double heap_pages, double index_pages, int max_workers)
Definition: allpaths.c:4210
double compute_bitmap_pages(PlannerInfo *root, RelOptInfo *baserel, Path *bitmapqual, double loop_count, Cost *cost_p, double *tuples_p)
Definition: costsize.c:6377

References add_partial_path(), compute_bitmap_pages(), compute_parallel_worker(), create_bitmap_heap_path(), RelOptInfo::lateral_relids, max_parallel_workers_per_gather, and root.

Referenced by create_index_paths().

◆ create_tidscan_paths()

bool create_tidscan_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 498 of file tidpath.c.

499 {
500  List *tidquals;
501  List *tidrangequals;
502  bool isCurrentOf;
503 
504  /*
505  * If any suitable quals exist in the rel's baserestrict list, generate a
506  * plain (unparameterized) TidPath with them.
507  *
508  * We skip this when enable_tidscan = false, except when the qual is
509  * CurrentOfExpr. In that case, a TID scan is the only correct path.
510  */
511  tidquals = TidQualFromRestrictInfoList(root, rel->baserestrictinfo, rel,
512  &isCurrentOf);
513 
514  if (tidquals != NIL && (enable_tidscan || isCurrentOf))
515  {
516  /*
517  * This path uses no join clauses, but it could still have required
518  * parameterization due to LATERAL refs in its tlist.
519  */
520  Relids required_outer = rel->lateral_relids;
521 
522  add_path(rel, (Path *) create_tidscan_path(root, rel, tidquals,
523  required_outer));
524 
525  /*
526  * When the qual is CurrentOfExpr, the path that we just added is the
527  * only one the executor can handle, so we should return before adding
528  * any others. Returning true lets the caller know not to add any
529  * others, either.
530  */
531  if (isCurrentOf)
532  return true;
533  }
534 
535  /* Skip the rest if TID scans are disabled. */
536  if (!enable_tidscan)
537  return false;
538 
539  /*
540  * If there are range quals in the baserestrict list, generate a
541  * TidRangePath.
542  */
544  rel);
545 
546  if (tidrangequals != NIL)
547  {
548  /*
549  * This path uses no join clauses, but it could still have required
550  * parameterization due to LATERAL refs in its tlist.
551  */
552  Relids required_outer = rel->lateral_relids;
553 
555  tidrangequals,
556  required_outer));
557  }
558 
559  /*
560  * Try to generate parameterized TidPaths using equality clauses extracted
561  * from EquivalenceClasses. (This is important since simple "t1.ctid =
562  * t2.ctid" clauses will turn into ECs.)
563  */
564  if (rel->has_eclass_joins)
565  {
566  List *clauses;
567 
568  /* Generate clauses, skipping any that join to lateral_referencers */
570  rel,
572  NULL,
573  rel->lateral_referencers);
574 
575  /* Generate a path for each usable join clause */
576  BuildParameterizedTidPaths(root, rel, clauses);
577  }
578 
579  /*
580  * Also consider parameterized TidPaths using "loose" join quals. Quals
581  * of the form "t1.ctid = t2.ctid" would turn into these if they are outer
582  * join quals, for example.
583  */
585 
586  return false;
587 }
bool enable_tidscan
Definition: costsize.c:138
List * generate_implied_equalities_for_column(PlannerInfo *root, RelOptInfo *rel, ec_matches_callback_type callback, void *callback_arg, Relids prohibited_rels)
Definition: equivclass.c:2960
TidPath * create_tidscan_path(PlannerInfo *root, RelOptInfo *rel, List *tidquals, Relids required_outer)
Definition: pathnode.c:1179
TidRangePath * create_tidrangescan_path(PlannerInfo *root, RelOptInfo *rel, List *tidrangequals, Relids required_outer)
Definition: pathnode.c:1208
Relids lateral_referencers
Definition: pathnodes.h:936
bool has_eclass_joins
Definition: pathnodes.h:987
static List * TidQualFromRestrictInfoList(PlannerInfo *root, List *rlist, RelOptInfo *rel, bool *isCurrentOf)
Definition: tidpath.c:281
static void BuildParameterizedTidPaths(PlannerInfo *root, RelOptInfo *rel, List *clauses)
Definition: tidpath.c:426
static List * TidRangeQualFromRestrictInfoList(List *rlist, RelOptInfo *rel)
Definition: tidpath.c:398
static bool ec_member_matches_ctid(PlannerInfo *root, RelOptInfo *rel, EquivalenceClass *ec, EquivalenceMember *em, void *arg)
Definition: tidpath.c:481

References add_path(), RelOptInfo::baserestrictinfo, BuildParameterizedTidPaths(), create_tidrangescan_path(), create_tidscan_path(), ec_member_matches_ctid(), enable_tidscan, generate_implied_equalities_for_column(), RelOptInfo::has_eclass_joins, RelOptInfo::joininfo, RelOptInfo::lateral_referencers, RelOptInfo::lateral_relids, NIL, root, TidQualFromRestrictInfoList(), and TidRangeQualFromRestrictInfoList().

Referenced by set_plain_rel_pathlist().

◆ eclass_useful_for_merging()

bool eclass_useful_for_merging ( PlannerInfo root,
EquivalenceClass eclass,
RelOptInfo rel 
)

Definition at line 3212 of file equivclass.c.

3215 {
3216  Relids relids;
3217  ListCell *lc;
3218 
3219  Assert(!eclass->ec_merged);
3220 
3221  /*
3222  * Won't generate joinclauses if const or single-member (the latter test
3223  * covers the volatile case too)
3224  */
3225  if (eclass->ec_has_const || list_length(eclass->ec_members) <= 1)
3226  return false;
3227 
3228  /*
3229  * Note we don't test ec_broken; if we did, we'd need a separate code path
3230  * to look through ec_sources. Checking the members anyway is OK as a
3231  * possibly-overoptimistic heuristic.
3232  */
3233 
3234  /* If specified rel is a child, we must consider the topmost parent rel */
3235  if (IS_OTHER_REL(rel))
3236  {
3238  relids = rel->top_parent_relids;
3239  }
3240  else
3241  relids = rel->relids;
3242 
3243  /* If rel already includes all members of eclass, no point in searching */
3244  if (bms_is_subset(eclass->ec_relids, relids))
3245  return false;
3246 
3247  /* To join, we need a member not in the given rel */
3248  foreach(lc, eclass->ec_members)
3249  {
3250  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc);
3251 
3252  if (cur_em->em_is_child)
3253  continue; /* ignore children here */
3254 
3255  if (!bms_overlap(cur_em->em_relids, relids))
3256  return true;
3257  }
3258 
3259  return false;
3260 }
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:848
static struct cvec * eclass(struct vars *v, chr c, int cases)
Definition: regc_locale.c:500

References Assert, bms_is_empty, bms_is_subset(), bms_overlap(), eclass(), EquivalenceMember::em_is_child, EquivalenceMember::em_relids, IS_OTHER_REL, lfirst, list_length(), RelOptInfo::relids, and RelOptInfo::top_parent_relids.

Referenced by get_useful_ecs_for_relation(), and pathkeys_useful_for_merging().

◆ exprs_known_equal()

bool exprs_known_equal ( PlannerInfo root,
Node item1,
Node item2 
)

Definition at line 2454 of file equivclass.c.

2455 {
2456  ListCell *lc1;
2457 
2458  foreach(lc1, root->eq_classes)
2459  {
2460  EquivalenceClass *ec = (EquivalenceClass *) lfirst(lc1);
2461  bool item1member = false;
2462  bool item2member = false;
2463  ListCell *lc2;
2464 
2465  /* Never match to a volatile EC */
2466  if (ec->ec_has_volatile)
2467  continue;
2468 
2469  foreach(lc2, ec->ec_members)
2470  {
2472 
2473  if (em->em_is_child)
2474  continue; /* ignore children here */
2475  if (equal(item1, em->em_expr))
2476  item1member = true;
2477  else if (equal(item2, em->em_expr))
2478  item2member = true;
2479  /* Exit as soon as equality is proven */
2480  if (item1member && item2member)
2481  return true;
2482  }
2483  }
2484  return false;
2485 }

References EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_members, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, equal(), lfirst, and root.

Referenced by add_unique_group_var().

◆ find_computable_ec_member()

EquivalenceMember* find_computable_ec_member ( PlannerInfo root,
EquivalenceClass ec,
List exprs,
Relids  relids,
bool  require_parallel_safe 
)

Definition at line 825 of file equivclass.c.

830 {
831  ListCell *lc;
832 
833  foreach(lc, ec->ec_members)
834  {
836  List *exprvars;
837  ListCell *lc2;
838 
839  /*
840  * We shouldn't be trying to sort by an equivalence class that
841  * contains a constant, so no need to consider such cases any further.
842  */
843  if (em->em_is_const)
844  continue;
845 
846  /*
847  * Ignore child members unless they belong to the requested rel.
848  */
849  if (em->em_is_child &&
850  !bms_is_subset(em->em_relids, relids))
851  continue;
852 
853  /*
854  * Match if all Vars and quasi-Vars are available in "exprs".
855  */
856  exprvars = pull_var_clause((Node *) em->em_expr,
860  foreach(lc2, exprvars)
861  {
862  if (!is_exprlist_member(lfirst(lc2), exprs))
863  break;
864  }
865  list_free(exprvars);
866  if (lc2)
867  continue; /* we hit a non-available Var */
868 
869  /*
870  * If requested, reject expressions that are not parallel-safe. We
871  * check this last because it's a rather expensive test.
872  */
873  if (require_parallel_safe &&
874  !is_parallel_safe(root, (Node *) em->em_expr))
875  continue;
876 
877  return em; /* found usable expression */
878  }
879 
880  return NULL;
881 }
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:753
static bool is_exprlist_member(Expr *node, List *exprs)
Definition: equivclass.c:891
void list_free(List *list)
Definition: list.c:1546
#define PVC_INCLUDE_WINDOWFUNCS
Definition: optimizer.h:188
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:190
#define PVC_INCLUDE_AGGREGATES
Definition: optimizer.h:186
List * pull_var_clause(Node *node, int flags)
Definition: var.c:607

References bms_is_subset(), EquivalenceClass::ec_members, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_relids, is_exprlist_member(), is_parallel_safe(), lfirst, list_free(), pull_var_clause(), PVC_INCLUDE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS, PVC_INCLUDE_WINDOWFUNCS, and root.

Referenced by prepare_sort_from_pathkeys(), and relation_can_be_sorted_early().

◆ find_derived_clause_for_ec_member()

RestrictInfo* find_derived_clause_for_ec_member ( EquivalenceClass ec,
EquivalenceMember em 
)

Definition at line 2596 of file equivclass.c.

2598 {
2599  ListCell *lc;
2600 
2601  Assert(ec->ec_has_const);
2602  Assert(!em->em_is_const);
2603  foreach(lc, ec->ec_derives)
2604  {
2605  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2606 
2607  /*
2608  * generate_base_implied_equalities_const will have put non-const
2609  * members on the left side of derived clauses.
2610  */
2611  if (rinfo->left_em == em)
2612  return rinfo;
2613  }
2614  return NULL;
2615 }

References Assert, EquivalenceClass::ec_derives, EquivalenceClass::ec_has_const, EquivalenceMember::em_is_const, and lfirst.

Referenced by get_foreign_key_join_selectivity().

◆ find_ec_member_matching_expr()

EquivalenceMember* find_ec_member_matching_expr ( EquivalenceClass ec,
Expr expr,
Relids  relids 
)

Definition at line 760 of file equivclass.c.

763 {
764  ListCell *lc;
765 
766  /* We ignore binary-compatible relabeling on both ends */
767  while (expr && IsA(expr, RelabelType))
768  expr = ((RelabelType *) expr)->arg;
769 
770  foreach(lc, ec->ec_members)
771  {
773  Expr *emexpr;
774 
775  /*
776  * We shouldn't be trying to sort by an equivalence class that
777  * contains a constant, so no need to consider such cases any further.
778  */
779  if (em->em_is_const)
780  continue;
781 
782  /*
783  * Ignore child members unless they belong to the requested rel.
784  */
785  if (em->em_is_child &&
786  !bms_is_subset(em->em_relids, relids))
787  continue;
788 
789  /*
790  * Match if same expression (after stripping relabel).
791  */
792  emexpr = em->em_expr;
793  while (emexpr && IsA(emexpr, RelabelType))
794  emexpr = ((RelabelType *) emexpr)->arg;
795 
796  if (equal(emexpr, expr))
797  return em;
798  }
799 
800  return NULL;
801 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
void * arg

References arg, bms_is_subset(), EquivalenceClass::ec_members, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_relids, equal(), IsA, and lfirst.

Referenced by make_unique_from_pathkeys(), prepare_sort_from_pathkeys(), and relation_can_be_sorted_early().

◆ find_mergeclauses_for_outer_pathkeys()

List* find_mergeclauses_for_outer_pathkeys ( PlannerInfo root,
List pathkeys,
List restrictinfos 
)

Definition at line 1527 of file pathkeys.c.

1530 {
1531  List *mergeclauses = NIL;
1532  ListCell *i;
1533 
1534  /* make sure we have eclasses cached in the clauses */
1535  foreach(i, restrictinfos)
1536  {
1537  RestrictInfo *rinfo = (RestrictInfo *) lfirst(i);
1538 
1540  }
1541 
1542  foreach(i, pathkeys)
1543  {
1544  PathKey *pathkey = (PathKey *) lfirst(i);
1545  EquivalenceClass *pathkey_ec = pathkey->pk_eclass;
1546  List *matched_restrictinfos = NIL;
1547  ListCell *j;
1548 
1549  /*----------
1550  * A mergejoin clause matches a pathkey if it has the same EC.
1551  * If there are multiple matching clauses, take them all. In plain
1552  * inner-join scenarios we expect only one match, because
1553  * equivalence-class processing will have removed any redundant
1554  * mergeclauses. However, in outer-join scenarios there might be
1555  * multiple matches. An example is
1556  *
1557  * select * from a full join b
1558  * on a.v1 = b.v1 and a.v2 = b.v2 and a.v1 = b.v2;
1559  *
1560  * Given the pathkeys ({a.v1}, {a.v2}) it is okay to return all three
1561  * clauses (in the order a.v1=b.v1, a.v1=b.v2, a.v2=b.v2) and indeed
1562  * we *must* do so or we will be unable to form a valid plan.
1563  *
1564  * We expect that the given pathkeys list is canonical, which means
1565  * no two members have the same EC, so it's not possible for this
1566  * code to enter the same mergeclause into the result list twice.
1567  *
1568  * It's possible that multiple matching clauses might have different
1569  * ECs on the other side, in which case the order we put them into our
1570  * result makes a difference in the pathkeys required for the inner
1571  * input rel. However this routine hasn't got any info about which
1572  * order would be best, so we don't worry about that.
1573  *
1574  * It's also possible that the selected mergejoin clauses produce
1575  * a noncanonical ordering of pathkeys for the inner side, ie, we
1576  * might select clauses that reference b.v1, b.v2, b.v1 in that
1577  * order. This is not harmful in itself, though it suggests that
1578  * the clauses are partially redundant. Since the alternative is
1579  * to omit mergejoin clauses and thereby possibly fail to generate a
1580  * plan altogether, we live with it. make_inner_pathkeys_for_merge()
1581  * has to delete duplicates when it constructs the inner pathkeys
1582  * list, and we also have to deal with such cases specially in
1583  * create_mergejoin_plan().
1584  *----------
1585  */
1586  foreach(j, restrictinfos)
1587  {
1588  RestrictInfo *rinfo = (RestrictInfo *) lfirst(j);
1589  EquivalenceClass *clause_ec;
1590 
1591  clause_ec = rinfo->outer_is_left ?
1592  rinfo->left_ec : rinfo->right_ec;
1593  if (clause_ec == pathkey_ec)
1594  matched_restrictinfos = lappend(matched_restrictinfos, rinfo);
1595  }
1596 
1597  /*
1598  * If we didn't find a mergeclause, we're done --- any additional
1599  * sort-key positions in the pathkeys are useless. (But we can still
1600  * mergejoin if we found at least one mergeclause.)
1601  */
1602  if (matched_restrictinfos == NIL)
1603  break;
1604 
1605  /*
1606  * If we did find usable mergeclause(s) for this sort-key position,
1607  * add them to result list.
1608  */
1609  mergeclauses = list_concat(mergeclauses, matched_restrictinfos);
1610  }
1611 
1612  return mergeclauses;
1613 }
void update_mergeclause_eclasses(PlannerInfo *root, RestrictInfo *restrictinfo)
Definition: pathkeys.c:1493

References i, j, lappend(), lfirst, list_concat(), NIL, root, and update_mergeclause_eclasses().

Referenced by generate_mergejoin_paths(), and sort_inner_and_outer().

◆ generate_base_implied_equalities()

void generate_base_implied_equalities ( PlannerInfo root)

Definition at line 1033 of file equivclass.c.

1034 {
1035  int ec_index;
1036  ListCell *lc;
1037 
1038  /*
1039  * At this point, we're done absorbing knowledge of equivalences in the
1040  * query, so no further EC merging should happen, and ECs remaining in the
1041  * eq_classes list can be considered canonical. (But note that it's still
1042  * possible for new single-member ECs to be added through
1043  * get_eclass_for_sort_expr().)
1044  */
1045  root->ec_merging_done = true;
1046 
1047  ec_index = 0;
1048  foreach(lc, root->eq_classes)
1049  {
1051  bool can_generate_joinclause = false;
1052  int i;
1053 
1054  Assert(ec->ec_merged == NULL); /* else shouldn't be in list */
1055  Assert(!ec->ec_broken); /* not yet anyway... */
1056 
1057  /*
1058  * Generate implied equalities that are restriction clauses.
1059  * Single-member ECs won't generate any deductions, either here or at
1060  * the join level.
1061  */
1062  if (list_length(ec->ec_members) > 1)
1063  {
1064  if (ec->ec_has_const)
1066  else
1068 
1069  /* Recover if we failed to generate required derived clauses */
1070  if (ec->ec_broken)
1072 
1073  /* Detect whether this EC might generate join clauses */
1074  can_generate_joinclause =
1076  }
1077 
1078  /*
1079  * Mark the base rels cited in each eclass (which should all exist by
1080  * now) with the eq_classes indexes of all eclasses mentioning them.
1081  * This will let us avoid searching in subsequent lookups. While
1082  * we're at it, we can mark base rels that have pending eclass joins;
1083  * this is a cheap version of has_relevant_eclass_joinclause().
1084  */
1085  i = -1;
1086  while ((i = bms_next_member(ec->ec_relids, i)) > 0)
1087  {
1088  RelOptInfo *rel = root->simple_rel_array[i];
1089 
1090  if (rel == NULL) /* must be an outer join */
1091  {
1092  Assert(bms_is_member(i, root->outer_join_rels));
1093  continue;
1094  }
1095 
1096  Assert(rel->reloptkind == RELOPT_BASEREL);
1097 
1099  ec_index);
1100 
1101  if (can_generate_joinclause)
1102  rel->has_eclass_joins = true;
1103  }
1104 
1105  ec_index++;
1106  }
1107 }
static void generate_base_implied_equalities_broken(PlannerInfo *root, EquivalenceClass *ec)
Definition: equivclass.c:1318
static void generate_base_implied_equalities_no_const(PlannerInfo *root, EquivalenceClass *ec)
Definition: equivclass.c:1208
static void generate_base_implied_equalities_const(PlannerInfo *root, EquivalenceClass *ec)
Definition: equivclass.c:1113
struct EquivalenceClass * ec_merged
Definition: pathnodes.h:1396

References Assert, bms_add_member(), bms_is_member(), bms_membership(), BMS_MULTIPLE, bms_next_member(), EquivalenceClass::ec_broken, EquivalenceClass::ec_has_const, EquivalenceClass::ec_members, EquivalenceClass::ec_merged, EquivalenceClass::ec_relids, RelOptInfo::eclass_indexes, generate_base_implied_equalities_broken(), generate_base_implied_equalities_const(), generate_base_implied_equalities_no_const(), RelOptInfo::has_eclass_joins, i, lfirst, list_length(), RELOPT_BASEREL, RelOptInfo::reloptkind, and root.

Referenced by query_planner().

◆ generate_gather_paths()

void generate_gather_paths ( PlannerInfo root,
RelOptInfo rel,
bool  override_rows 
)

Definition at line 3060 of file allpaths.c.

3061 {
3062  Path *cheapest_partial_path;
3063  Path *simple_gather_path;
3064  ListCell *lc;
3065  double rows;
3066  double *rowsp = NULL;
3067 
3068  /* If there are no partial paths, there's nothing to do here. */
3069  if (rel->partial_pathlist == NIL)
3070  return;
3071 
3072  /* Should we override the rel's rowcount estimate? */
3073  if (override_rows)
3074  rowsp = &rows;
3075 
3076  /*
3077  * The output of Gather is always unsorted, so there's only one partial
3078  * path of interest: the cheapest one. That will be the one at the front
3079  * of partial_pathlist because of the way add_partial_path works.
3080  */
3081  cheapest_partial_path = linitial(rel->partial_pathlist);
3082  rows = compute_gather_rows(cheapest_partial_path);
3083  simple_gather_path = (Path *)
3084  create_gather_path(root, rel, cheapest_partial_path, rel->reltarget,
3085  NULL, rowsp);
3086  add_path(rel, simple_gather_path);
3087 
3088  /*
3089  * For each useful ordering, we can consider an order-preserving Gather
3090  * Merge.
3091  */
3092  foreach(lc, rel->partial_pathlist)
3093  {
3094  Path *subpath = (Path *) lfirst(lc);
3095  GatherMergePath *path;
3096 
3097  if (subpath->pathkeys == NIL)
3098  continue;
3099 
3100  rows = compute_gather_rows(subpath);
3101  path = create_gather_merge_path(root, rel, subpath, rel->reltarget,
3102  subpath->pathkeys, NULL, rowsp);
3103  add_path(rel, &path->path);
3104  }
3105 }
double compute_gather_rows(Path *path)
Definition: costsize.c:6488
GatherMergePath * create_gather_merge_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, List *pathkeys, Relids required_outer, double *rows)
Definition: pathnode.c:1881
GatherPath * create_gather_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, PathTarget *target, Relids required_outer, double *rows)
Definition: pathnode.c:1960
struct PathTarget * reltarget
Definition: pathnodes.h:887

References add_path(), compute_gather_rows(), create_gather_merge_path(), create_gather_path(), lfirst, linitial, NIL, RelOptInfo::partial_pathlist, GatherMergePath::path, RelOptInfo::reltarget, root, and subpath().

Referenced by generate_useful_gather_paths().

◆ generate_implied_equalities_for_column()

List* generate_implied_equalities_for_column ( PlannerInfo root,
RelOptInfo rel,
ec_matches_callback_type  callback,
void *  callback_arg,
Relids  prohibited_rels 
)

Definition at line 2960 of file equivclass.c.

2965 {
2966  List *result = NIL;
2967  bool is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
2968  Relids parent_relids;
2969  int i;
2970 
2971  /* Should be OK to rely on eclass_indexes */
2972  Assert(root->ec_merging_done);
2973 
2974  /* Indexes are available only on base or "other" member relations. */
2975  Assert(IS_SIMPLE_REL(rel));
2976 
2977  /* If it's a child rel, we'll need to know what its parent(s) are */
2978  if (is_child_rel)
2979  parent_relids = find_childrel_parents(root, rel);
2980  else
2981  parent_relids = NULL; /* not used, but keep compiler quiet */
2982 
2983  i = -1;
2984  while ((i = bms_next_member(rel->eclass_indexes, i)) >= 0)
2985  {
2986  EquivalenceClass *cur_ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
2987  EquivalenceMember *cur_em;
2988  ListCell *lc2;
2989 
2990  /* Sanity check eclass_indexes only contain ECs for rel */
2991  Assert(is_child_rel || bms_is_subset(rel->relids, cur_ec->ec_relids));
2992 
2993  /*
2994  * Won't generate joinclauses if const or single-member (the latter
2995  * test covers the volatile case too)
2996  */
2997  if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
2998  continue;
2999 
3000  /*
3001  * Scan members, looking for a match to the target column. Note that
3002  * child EC members are considered, but only when they belong to the
3003  * target relation. (Unlike regular members, the same expression
3004  * could be a child member of more than one EC. Therefore, it's
3005  * potentially order-dependent which EC a child relation's target
3006  * column gets matched to. This is annoying but it only happens in
3007  * corner cases, so for now we live with just reporting the first
3008  * match. See also get_eclass_for_sort_expr.)
3009  */
3010  cur_em = NULL;
3011  foreach(lc2, cur_ec->ec_members)
3012  {
3013  cur_em = (EquivalenceMember *) lfirst(lc2);
3014  if (bms_equal(cur_em->em_relids, rel->relids) &&
3015  callback(root, rel, cur_ec, cur_em, callback_arg))
3016  break;
3017  cur_em = NULL;
3018  }
3019 
3020  if (!cur_em)
3021  continue;
3022 
3023  /*
3024  * Found our match. Scan the other EC members and attempt to generate
3025  * joinclauses.
3026  */
3027  foreach(lc2, cur_ec->ec_members)
3028  {
3029  EquivalenceMember *other_em = (EquivalenceMember *) lfirst(lc2);
3030  Oid eq_op;
3031  RestrictInfo *rinfo;
3032 
3033  if (other_em->em_is_child)
3034  continue; /* ignore children here */
3035 
3036  /* Make sure it'll be a join to a different rel */
3037  if (other_em == cur_em ||
3038  bms_overlap(other_em->em_relids, rel->relids))
3039  continue;
3040 
3041  /* Forget it if caller doesn't want joins to this rel */
3042  if (bms_overlap(other_em->em_relids, prohibited_rels))
3043  continue;
3044 
3045  /*
3046  * Also, if this is a child rel, avoid generating a useless join
3047  * to its parent rel(s).
3048  */
3049  if (is_child_rel &&
3050  bms_overlap(parent_relids, other_em->em_relids))
3051  continue;
3052 
3053  eq_op = select_equality_operator(cur_ec,
3054  cur_em->em_datatype,
3055  other_em->em_datatype);
3056  if (!OidIsValid(eq_op))
3057  continue;
3058 
3059  /* set parent_ec to mark as redundant with other joinclauses */
3060  rinfo = create_join_clause(root, cur_ec, eq_op,
3061  cur_em, other_em,
3062  cur_ec);
3063 
3064  result = lappend(result, rinfo);
3065  }
3066 
3067  /*
3068  * If somehow we failed to create any join clauses, we might as well
3069  * keep scanning the ECs for another match. But if we did make any,
3070  * we're done, because we don't want to return non-redundant clauses.
3071  */
3072  if (result)
3073  break;
3074  }
3075 
3076  return result;
3077 }
#define OidIsValid(objectId)
Definition: c.h:775
static RestrictInfo * create_join_clause(PlannerInfo *root, EquivalenceClass *ec, Oid opno, EquivalenceMember *leftem, EquivalenceMember *rightem, EquivalenceClass *parent_ec)
Definition: equivclass.c:1813
static Oid select_equality_operator(EquivalenceClass *ec, Oid lefttype, Oid righttype)
Definition: equivclass.c:1777
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:46

References Assert, bms_equal(), bms_is_subset(), bms_next_member(), bms_overlap(), callback(), create_join_clause(), EquivalenceClass::ec_has_const, EquivalenceClass::ec_members, EquivalenceClass::ec_relids, RelOptInfo::eclass_indexes, EquivalenceMember::em_datatype, EquivalenceMember::em_is_child, EquivalenceMember::em_relids, find_childrel_parents(), i, IS_SIMPLE_REL, lappend(), lfirst, list_length(), list_nth(), NIL, OidIsValid, RelOptInfo::relids, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, root, and select_equality_operator().

Referenced by create_tidscan_paths(), match_eclass_clauses_to_index(), and postgresGetForeignPaths().

◆ generate_join_implied_equalities()

List* generate_join_implied_equalities ( PlannerInfo root,
Relids  join_relids,
Relids  outer_relids,
RelOptInfo inner_rel,
SpecialJoinInfo sjinfo 
)

Definition at line 1381 of file equivclass.c.

1386 {
1387  List *result = NIL;
1388  Relids inner_relids = inner_rel->relids;
1389  Relids nominal_inner_relids;
1390  Relids nominal_join_relids;
1391  Bitmapset *matching_ecs;
1392  int i;
1393 
1394  /* If inner rel is a child, extra setup work is needed */
1395  if (IS_OTHER_REL(inner_rel))
1396  {
1397  Assert(!bms_is_empty(inner_rel->top_parent_relids));
1398 
1399  /* Fetch relid set for the topmost parent rel */
1400  nominal_inner_relids = inner_rel->top_parent_relids;
1401  /* ECs will be marked with the parent's relid, not the child's */
1402  nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1403  nominal_join_relids = add_outer_joins_to_relids(root,
1404  nominal_join_relids,
1405  sjinfo,
1406  NULL);
1407  }
1408  else
1409  {
1410  nominal_inner_relids = inner_relids;
1411  nominal_join_relids = join_relids;
1412  }
1413 
1414  /*
1415  * Examine all potentially-relevant eclasses.
1416  *
1417  * If we are considering an outer join, we must include "join" clauses
1418  * that mention either input rel plus the outer join's relid; these
1419  * represent post-join filter clauses that have to be applied at this
1420  * join. We don't have infrastructure that would let us identify such
1421  * eclasses cheaply, so just fall back to considering all eclasses
1422  * mentioning anything in nominal_join_relids.
1423  *
1424  * At inner joins, we can be smarter: only consider eclasses mentioning
1425  * both input rels.
1426  */
1427  if (sjinfo && sjinfo->ojrelid != 0)
1428  matching_ecs = get_eclass_indexes_for_relids(root, nominal_join_relids);
1429  else
1430  matching_ecs = get_common_eclass_indexes(root, nominal_inner_relids,
1431  outer_relids);
1432 
1433  i = -1;
1434  while ((i = bms_next_member(matching_ecs, i)) >= 0)
1435  {
1436  EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);
1437  List *sublist = NIL;
1438 
1439  /* ECs containing consts do not need any further enforcement */
1440  if (ec->ec_has_const)
1441  continue;
1442 
1443  /* Single-member ECs won't generate any deductions */
1444  if (list_length(ec->ec_members) <= 1)
1445  continue;
1446 
1447  /* Sanity check that this eclass overlaps the join */
1448  Assert(bms_overlap(ec->ec_relids, nominal_join_relids));
1449 
1450  if (!ec->ec_broken)
1452  ec,
1453  join_relids,
1454  outer_relids,
1455  inner_relids);
1456 
1457  /* Recover if we failed to generate required derived clauses */
1458  if (ec->ec_broken)
1460  ec,
1461  nominal_join_relids,
1462  outer_relids,
1463  nominal_inner_relids,
1464  inner_rel);
1465 
1466  result = list_concat(result, sublist);
1467  }
1468 
1469  return result;
1470 }
static List * generate_join_implied_equalities_normal(PlannerInfo *root, EquivalenceClass *ec, Relids join_relids, Relids outer_relids, Relids inner_relids)
Definition: equivclass.c:1552
static Bitmapset * get_common_eclass_indexes(PlannerInfo *root, Relids relids1, Relids relids2)
Definition: equivclass.c:3363
static List * generate_join_implied_equalities_broken(PlannerInfo *root, EquivalenceClass *ec, Relids nominal_join_relids, Relids outer_relids, Relids nominal_inner_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1728
Relids add_outer_joins_to_relids(PlannerInfo *root, Relids input_relids, SpecialJoinInfo *sjinfo, List **pushed_down_joins)
Definition: joinrels.c:801

References add_outer_joins_to_relids(), Assert, bms_is_empty, bms_next_member(), bms_overlap(), bms_union(), EquivalenceClass::ec_broken, EquivalenceClass::ec_has_const, EquivalenceClass::ec_members, EquivalenceClass::ec_relids, generate_join_implied_equalities_broken(), generate_join_implied_equalities_normal(), get_common_eclass_indexes(), get_eclass_indexes_for_relids(), i, IS_OTHER_REL, list_concat(), list_length(), list_nth(), NIL, SpecialJoinInfo::ojrelid, RelOptInfo::relids, root, and RelOptInfo::top_parent_relids.

Referenced by build_joinrel_restrictlist(), check_index_predicates(), get_baserel_parampathinfo(), get_joinrel_parampathinfo(), and reduce_unique_semijoins().

◆ generate_join_implied_equalities_for_ecs()

List* generate_join_implied_equalities_for_ecs ( PlannerInfo root,
List eclasses,
Relids  join_relids,
Relids  outer_relids,
RelOptInfo inner_rel 
)

Definition at line 1481 of file equivclass.c.

1486 {
1487  List *result = NIL;
1488  Relids inner_relids = inner_rel->relids;
1489  Relids nominal_inner_relids;
1490  Relids nominal_join_relids;
1491  ListCell *lc;
1492 
1493  /* If inner rel is a child, extra setup work is needed */
1494  if (IS_OTHER_REL(inner_rel))
1495  {
1496  Assert(!bms_is_empty(inner_rel->top_parent_relids));
1497 
1498  /* Fetch relid set for the topmost parent rel */
1499  nominal_inner_relids = inner_rel->top_parent_relids;
1500  /* ECs will be marked with the parent's relid, not the child's */
1501  nominal_join_relids = bms_union(outer_relids, nominal_inner_relids);
1502  }
1503  else
1504  {
1505  nominal_inner_relids = inner_relids;
1506  nominal_join_relids = join_relids;
1507  }
1508 
1509  foreach(lc, eclasses)
1510  {
1512  List *sublist = NIL;
1513 
1514  /* ECs containing consts do not need any further enforcement */
1515  if (ec->ec_has_const)
1516  continue;
1517 
1518  /* Single-member ECs won't generate any deductions */
1519  if (list_length(ec->ec_members) <= 1)
1520  continue;
1521 
1522  /* We can quickly ignore any that don't overlap the join, too */
1523  if (!bms_overlap(ec->ec_relids, nominal_join_relids))
1524  continue;
1525 
1526  if (!ec->ec_broken)
1528  ec,
1529  join_relids,
1530  outer_relids,
1531  inner_relids);
1532 
1533  /* Recover if we failed to generate required derived clauses */
1534  if (ec->ec_broken)
1536  ec,
1537  nominal_join_relids,
1538  outer_relids,
1539  nominal_inner_relids,
1540  inner_rel);
1541 
1542  result = list_concat(result, sublist);
1543  }
1544 
1545  return result;
1546 }

References Assert, bms_is_empty, bms_overlap(), bms_union(), EquivalenceClass::ec_broken, EquivalenceClass::ec_has_const, EquivalenceClass::ec_members, EquivalenceClass::ec_relids, generate_join_implied_equalities_broken(), generate_join_implied_equalities_normal(), IS_OTHER_REL, lfirst, list_concat(), list_length(), NIL, RelOptInfo::relids, root, and RelOptInfo::top_parent_relids.

Referenced by get_joinrel_parampathinfo().

◆ generate_partitionwise_join_paths()

void generate_partitionwise_join_paths ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 4298 of file allpaths.c.

4299 {
4300  List *live_children = NIL;
4301  int cnt_parts;
4302  int num_parts;
4303  RelOptInfo **part_rels;
4304 
4305  /* Handle only join relations here. */
4306  if (!IS_JOIN_REL(rel))
4307  return;
4308 
4309  /* We've nothing to do if the relation is not partitioned. */
4310  if (!IS_PARTITIONED_REL(rel))
4311  return;
4312 
4313  /* The relation should have consider_partitionwise_join set. */
4315 
4316  /* Guard against stack overflow due to overly deep partition hierarchy. */
4318 
4319  num_parts = rel->nparts;
4320  part_rels = rel->part_rels;
4321 
4322  /* Collect non-dummy child-joins. */
4323  for (cnt_parts = 0; cnt_parts < num_parts; cnt_parts++)
4324  {
4325  RelOptInfo *child_rel = part_rels[cnt_parts];
4326 
4327  /* If it's been pruned entirely, it's certainly dummy. */
4328  if (child_rel == NULL)
4329  continue;
4330 
4331  /* Make partitionwise join paths for this partitioned child-join. */
4333 
4334  /* If we failed to make any path for this child, we must give up. */
4335  if (child_rel->pathlist == NIL)
4336  {
4337  /*
4338  * Mark the parent joinrel as unpartitioned so that later
4339  * functions treat it correctly.
4340  */
4341  rel->nparts = 0;
4342  return;
4343  }
4344 
4345  /* Else, identify the cheapest path for it. */
4346  set_cheapest(child_rel);
4347 
4348  /* Dummy children need not be scanned, so ignore those. */
4349  if (IS_DUMMY_REL(child_rel))
4350  continue;
4351 
4352 #ifdef OPTIMIZER_DEBUG
4353  pprint(child_rel);
4354 #endif
4355 
4356  live_children = lappend(live_children, child_rel);
4357  }
4358 
4359  /* If all child-joins are dummy, parent join is also dummy. */
4360  if (!live_children)
4361  {
4362  mark_dummy_rel(rel);
4363  return;
4364  }
4365 
4366  /* Build additional paths for this rel from child-join paths. */
4367  add_paths_to_append_rel(root, rel, live_children);
4368  list_free(live_children);
4369 }
void generate_partitionwise_join_paths(PlannerInfo *root, RelOptInfo *rel)
Definition: allpaths.c:4298
void add_paths_to_append_rel(PlannerInfo *root, RelOptInfo *rel, List *live_childrels)
Definition: allpaths.c:1310
void pprint(const void *obj)
Definition: print.c:54
void mark_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1384
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:242
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1946
#define IS_PARTITIONED_REL(rel)
Definition: pathnodes.h:1056
void check_stack_depth(void)
Definition: postgres.c:3530
bool consider_partitionwise_join
Definition: pathnodes.h:993

References add_paths_to_append_rel(), Assert, check_stack_depth(), RelOptInfo::consider_partitionwise_join, IS_DUMMY_REL, IS_JOIN_REL, IS_PARTITIONED_REL, lappend(), list_free(), mark_dummy_rel(), NIL, RelOptInfo::nparts, RelOptInfo::pathlist, pprint(), root, and set_cheapest().

Referenced by merge_clump(), and standard_join_search().

◆ generate_useful_gather_paths()

void generate_useful_gather_paths ( PlannerInfo root,
RelOptInfo rel,
bool  override_rows 
)

Definition at line 3197 of file allpaths.c.

3198 {
3199  ListCell *lc;
3200  double rows;
3201  double *rowsp = NULL;
3202  List *useful_pathkeys_list = NIL;
3203  Path *cheapest_partial_path = NULL;
3204 
3205  /* If there are no partial paths, there's nothing to do here. */
3206  if (rel->partial_pathlist == NIL)
3207  return;
3208 
3209  /* Should we override the rel's rowcount estimate? */
3210  if (override_rows)
3211  rowsp = &rows;
3212 
3213  /* generate the regular gather (merge) paths */
3214  generate_gather_paths(root, rel, override_rows);
3215 
3216  /* consider incremental sort for interesting orderings */
3217  useful_pathkeys_list = get_useful_pathkeys_for_relation(root, rel, true);
3218 
3219  /* used for explicit (full) sort paths */
3220  cheapest_partial_path = linitial(rel->partial_pathlist);
3221 
3222  /*
3223  * Consider sorted paths for each interesting ordering. We generate both
3224  * incremental and full sort.
3225  */
3226  foreach(lc, useful_pathkeys_list)
3227  {
3228  List *useful_pathkeys = lfirst(lc);
3229  ListCell *lc2;
3230  bool is_sorted;
3231  int presorted_keys;
3232 
3233  foreach(lc2, rel->partial_pathlist)
3234  {
3235  Path *subpath = (Path *) lfirst(lc2);
3236  GatherMergePath *path;
3237 
3238  is_sorted = pathkeys_count_contained_in(useful_pathkeys,
3239  subpath->pathkeys,
3240  &presorted_keys);
3241 
3242  /*
3243  * We don't need to consider the case where a subpath is already
3244  * fully sorted because generate_gather_paths already creates a
3245  * gather merge path for every subpath that has pathkeys present.
3246  *
3247  * But since the subpath is already sorted, we know we don't need
3248  * to consider adding a sort (full or incremental) on top of it,
3249  * so we can continue here.
3250  */
3251  if (is_sorted)
3252  continue;
3253 
3254  /*
3255  * Try at least sorting the cheapest path and also try
3256  * incrementally sorting any path which is partially sorted
3257  * already (no need to deal with paths which have presorted keys
3258  * when incremental sort is disabled unless it's the cheapest
3259  * input path).
3260  */
3261  if (subpath != cheapest_partial_path &&
3262  (presorted_keys == 0 || !enable_incremental_sort))
3263  continue;
3264 
3265  /*
3266  * Consider regular sort for any path that's not presorted or if
3267  * incremental sort is disabled. We've no need to consider both
3268  * sort and incremental sort on the same path. We assume that
3269  * incremental sort is always faster when there are presorted
3270  * keys.
3271  *
3272  * This is not redundant with the gather paths created in
3273  * generate_gather_paths, because that doesn't generate ordered
3274  * output. Here we add an explicit sort to match the useful
3275  * ordering.
3276  */
3277  if (presorted_keys == 0 || !enable_incremental_sort)
3278  {
3280  rel,
3281  subpath,
3282  useful_pathkeys,
3283  -1.0);
3284  }
3285  else
3287  rel,
3288  subpath,
3289  useful_pathkeys,
3290  presorted_keys,
3291  -1);
3292  rows = compute_gather_rows(subpath);
3293  path = create_gather_merge_path(root, rel,
3294  subpath,
3295  rel->reltarget,
3296  subpath->pathkeys,
3297  NULL,
3298  rowsp);
3299 
3300  add_path(rel, &path->path);
3301  }
3302  }
3303 }
void generate_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3060
static List * get_useful_pathkeys_for_relation(PlannerInfo *root, RelOptInfo *rel, bool require_parallel_safe)
Definition: allpaths.c:3129
bool enable_incremental_sort
Definition: costsize.c:140
bool pathkeys_count_contained_in(List *keys1, List *keys2, int *n_common)
Definition: pathkeys.c:556
SortPath * create_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, double limit_tuples)
Definition: pathnode.c:2988
IncrementalSortPath * create_incremental_sort_path(PlannerInfo *root, RelOptInfo *rel, Path *subpath, List *pathkeys, int presorted_keys, double limit_tuples)
Definition: pathnode.c:2939

References add_path(), compute_gather_rows(), create_gather_merge_path(), create_incremental_sort_path(), create_sort_path(), enable_incremental_sort, generate_gather_paths(), get_useful_pathkeys_for_relation(), lfirst, linitial, NIL, RelOptInfo::partial_pathlist, GatherMergePath::path, pathkeys_count_contained_in(), RelOptInfo::reltarget, root, and subpath().

Referenced by apply_scanjoin_target_to_paths(), create_partial_distinct_paths(), gather_grouping_paths(), merge_clump(), set_rel_pathlist(), and standard_join_search().

◆ get_cheapest_fractional_path_for_pathkeys()

Path* get_cheapest_fractional_path_for_pathkeys ( List paths,
List pathkeys,
Relids  required_outer,
double  fraction 
)

Definition at line 664 of file pathkeys.c.

668 {
669  Path *matched_path = NULL;
670  ListCell *l;
671 
672  foreach(l, paths)
673  {
674  Path *path = (Path *) lfirst(l);
675 
676  /*
677  * Since cost comparison is a lot cheaper than pathkey comparison, do
678  * that first. (XXX is that still true?)
679  */
680  if (matched_path != NULL &&
681  compare_fractional_path_costs(matched_path, path, fraction) <= 0)
682  continue;
683 
684  if (pathkeys_contained_in(pathkeys, path->pathkeys) &&
685  bms_is_subset(PATH_REQ_OUTER(path), required_outer))
686  matched_path = path;
687  }
688  return matched_path;
689 }
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:341
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:115

References bms_is_subset(), compare_fractional_path_costs(), lfirst, PATH_REQ_OUTER, Path::pathkeys, and pathkeys_contained_in().

Referenced by build_minmax_path(), and generate_orderedappend_paths().

◆ get_cheapest_parallel_safe_total_inner()

Path* get_cheapest_parallel_safe_total_inner ( List paths)

Definition at line 697 of file pathkeys.c.

698 {
699  ListCell *l;
700 
701  foreach(l, paths)
702  {
703  Path *innerpath = (Path *) lfirst(l);
704 
705  if (innerpath->parallel_safe &&
706  bms_is_empty(PATH_REQ_OUTER(innerpath)))
707  return innerpath;
708  }
709 
710  return NULL;
711 }
bool parallel_safe
Definition: pathnodes.h:1655

References bms_is_empty, lfirst, Path::parallel_safe, and PATH_REQ_OUTER.

Referenced by add_paths_to_append_rel(), hash_inner_and_outer(), match_unsorted_outer(), and sort_inner_and_outer().

◆ get_cheapest_path_for_pathkeys()

Path* get_cheapest_path_for_pathkeys ( List paths,
List pathkeys,
Relids  required_outer,
CostSelector  cost_criterion,
bool  require_parallel_safe 
)

Definition at line 618 of file pathkeys.c.

622 {
623  Path *matched_path = NULL;
624  ListCell *l;
625 
626  foreach(l, paths)
627  {
628  Path *path = (Path *) lfirst(l);
629 
630  /* If required, reject paths that are not parallel-safe */
631  if (require_parallel_safe && !path->parallel_safe)
632  continue;
633 
634  /*
635  * Since cost comparison is a lot cheaper than pathkey comparison, do
636  * that first. (XXX is that still true?)
637  */
638  if (matched_path != NULL &&
639  compare_path_costs(matched_path, path, cost_criterion) <= 0)
640  continue;
641 
642  if (pathkeys_contained_in(pathkeys, path->pathkeys) &&
643  bms_is_subset(PATH_REQ_OUTER(path), required_outer))
644  matched_path = path;
645  }
646  return matched_path;
647 }
int compare_path_costs(Path *path1, Path *path2, CostSelector criterion)
Definition: pathnode.c:69

References bms_is_subset(), compare_path_costs(), lfirst, Path::parallel_safe, PATH_REQ_OUTER, Path::pathkeys, and pathkeys_contained_in().

Referenced by generate_mergejoin_paths(), generate_orderedappend_paths(), generate_union_paths(), and get_cheapest_parameterized_child_path().

◆ get_eclass_for_sort_expr()

EquivalenceClass* get_eclass_for_sort_expr ( PlannerInfo root,
Expr expr,
List opfamilies,
Oid  opcintype,
Oid  collation,
Index  sortref,
Relids  rel,
bool  create_it 
)

Definition at line 587 of file equivclass.c.

595 {
596  JoinDomain *jdomain;
597  Relids expr_relids;
598  EquivalenceClass *newec;
599  EquivalenceMember *newem;
600  ListCell *lc1;
601  MemoryContext oldcontext;
602 
603  /*
604  * Ensure the expression exposes the correct type and collation.
605  */
606  expr = canonicalize_ec_expression(expr, opcintype, collation);
607 
608  /*
609  * Since SortGroupClause nodes are top-level expressions (GROUP BY, ORDER
610  * BY, etc), they can be presumed to belong to the top JoinDomain.
611  */
612  jdomain = linitial_node(JoinDomain, root->join_domains);
613 
614  /*
615  * Scan through the existing EquivalenceClasses for a match
616  */
617  foreach(lc1, root->eq_classes)
618  {
619  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
620  ListCell *lc2;
621 
622  /*
623  * Never match to a volatile EC, except when we are looking at another
624  * reference to the same volatile SortGroupClause.
625  */
626  if (cur_ec->ec_has_volatile &&
627  (sortref == 0 || sortref != cur_ec->ec_sortref))
628  continue;
629 
630  if (collation != cur_ec->ec_collation)
631  continue;
632  if (!equal(opfamilies, cur_ec->ec_opfamilies))
633  continue;
634 
635  foreach(lc2, cur_ec->ec_members)
636  {
637  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
638 
639  /*
640  * Ignore child members unless they match the request.
641  */
642  if (cur_em->em_is_child &&
643  !bms_equal(cur_em->em_relids, rel))
644  continue;
645 
646  /*
647  * Match constants only within the same JoinDomain (see
648  * optimizer/README).
649  */
650  if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
651  continue;
652 
653  if (opcintype == cur_em->em_datatype &&
654  equal(expr, cur_em->em_expr))
655  return cur_ec; /* Match! */
656  }
657  }
658 
659  /* No match; does caller want a NULL result? */
660  if (!create_it)
661  return NULL;
662 
663  /*
664  * OK, build a new single-member EC
665  *
666  * Here, we must be sure that we construct the EC in the right context.
667  */
668  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
669 
670  newec = makeNode(EquivalenceClass);
671  newec->ec_opfamilies = list_copy(opfamilies);
672  newec->ec_collation = collation;
673  newec->ec_members = NIL;
674  newec->ec_sources = NIL;
675  newec->ec_derives = NIL;
676  newec->ec_relids = NULL;
677  newec->ec_has_const = false;
679  newec->ec_broken = false;
680  newec->ec_sortref = sortref;
681  newec->ec_min_security = UINT_MAX;
682  newec->ec_max_security = 0;
683  newec->ec_merged = NULL;
684 
685  if (newec->ec_has_volatile && sortref == 0) /* should not happen */
686  elog(ERROR, "volatile EquivalenceClass has no sortref");
687 
688  /*
689  * Get the precise set of relids appearing in the expression.
690  */
691  expr_relids = pull_varnos(root, (Node *) expr);
692 
693  newem = add_eq_member(newec, copyObject(expr), expr_relids,
694  jdomain, NULL, opcintype);
695 
696  /*
697  * add_eq_member doesn't check for volatile functions, set-returning
698  * functions, aggregates, or window functions, but such could appear in
699  * sort expressions; so we have to check whether its const-marking was
700  * correct.
701  */
702  if (newec->ec_has_const)
703  {
704  if (newec->ec_has_volatile ||
705  expression_returns_set((Node *) expr) ||
706  contain_agg_clause((Node *) expr) ||
707  contain_window_function((Node *) expr))
708  {
709  newec->ec_has_const = false;
710  newem->em_is_const = false;
711  }
712  }
713 
714  root->eq_classes = lappend(root->eq_classes, newec);
715 
716  /*
717  * If EC merging is already complete, we have to mop up by adding the new
718  * EC to the eclass_indexes of the relation(s) mentioned in it.
719  */
720  if (root->ec_merging_done)
721  {
722  int ec_index = list_length(root->eq_classes) - 1;
723  int i = -1;
724 
725  while ((i = bms_next_member(newec->ec_relids, i)) > 0)
726  {
727  RelOptInfo *rel = root->simple_rel_array[i];
728 
729  if (rel == NULL) /* must be an outer join */
730  {
731  Assert(bms_is_member(i, root->outer_join_rels));
732  continue;
733  }
734 
736 
738  ec_index);
739  }
740  }
741 
742  MemoryContextSwitchTo(oldcontext);
743 
744  return newec;
745 }
bool contain_agg_clause(Node *clause)
Definition: clauses.c:177
bool contain_window_function(Node *clause)
Definition: clauses.c:214
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:538
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:758
#define copyObject(obj)
Definition: nodes.h:224
#define makeNode(_type_)
Definition: nodes.h:155
#define linitial_node(type, l)
Definition: pg_list.h:181
Index ec_min_security
Definition: pathnodes.h:1394
Index ec_max_security
Definition: pathnodes.h:1395
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition: var.c:108

References add_eq_member(), Assert, bms_add_member(), bms_equal(), bms_is_member(), bms_next_member(), canonicalize_ec_expression(), contain_agg_clause(), contain_volatile_functions(), contain_window_function(), copyObject, EquivalenceClass::ec_broken, EquivalenceClass::ec_collation, EquivalenceClass::ec_derives, EquivalenceClass::ec_has_const, EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_max_security, EquivalenceClass::ec_members, EquivalenceClass::ec_merged, EquivalenceClass::ec_min_security, EquivalenceClass::ec_opfamilies, EquivalenceClass::ec_relids, EquivalenceClass::ec_sortref, EquivalenceClass::ec_sources, RelOptInfo::eclass_indexes, elog, EquivalenceMember::em_datatype, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_jdomain, EquivalenceMember::em_relids, equal(), ERROR, expression_returns_set(), i, lappend(), lfirst, linitial_node, list_copy(), list_length(), makeNode, MemoryContextSwitchTo(), NIL, pull_varnos(), RELOPT_BASEREL, RelOptInfo::reloptkind, and root.

Referenced by convert_subquery_pathkeys(), initialize_mergeclause_eclasses(), and make_pathkey_from_sortinfo().

◆ get_useful_group_keys_orderings()

List* get_useful_group_keys_orderings ( PlannerInfo root,
Path path 
)

Definition at line 465 of file pathkeys.c.

466 {
467  Query *parse = root->parse;
468  List *infos = NIL;
469  GroupByOrdering *info;
470 
471  List *pathkeys = root->group_pathkeys;
472  List *clauses = root->processed_groupClause;
473 
474  /* always return at least the original pathkeys/clauses */
475  info = makeNode(GroupByOrdering);
476  info->pathkeys = pathkeys;
477  info->clauses = clauses;
478  infos = lappend(infos, info);
479 
480  /*
481  * Should we try generating alternative orderings of the group keys? If
482  * not, we produce only the order specified in the query, i.e. the
483  * optimization is effectively disabled.
484  */
486  return infos;
487 
488  /*
489  * Grouping sets have own and more complex logic to decide the ordering.
490  */
491  if (parse->groupingSets)
492  return infos;
493 
494  /*
495  * If the path is sorted in some way, try reordering the group keys to
496  * match the path as much of the ordering as possible. Then thanks to
497  * incremental sort we would get this sort as cheap as possible.
498  */
499  if (path->pathkeys &&
500  !pathkeys_contained_in(path->pathkeys, root->group_pathkeys))
501  {
502  int n;
503 
504  n = group_keys_reorder_by_pathkeys(path->pathkeys, &pathkeys, &clauses,
505  root->num_groupby_pathkeys);
506 
507  if (n > 0 &&
508  (enable_incremental_sort || n == root->num_groupby_pathkeys) &&
509  compare_pathkeys(pathkeys, root->group_pathkeys) != PATHKEYS_EQUAL)
510  {
511  info = makeNode(GroupByOrdering);
512  info->pathkeys = pathkeys;
513  info->clauses = clauses;
514 
515  infos = lappend(infos, info);
516  }
517  }
518 
519 #ifdef USE_ASSERT_CHECKING
520  {
522  ListCell *lc;
523 
524  /* Test consistency of info structures */
525  for_each_from(lc, infos, 1)
526  {
527  ListCell *lc1,
528  *lc2;
529 
530  info = lfirst_node(GroupByOrdering, lc);
531 
532  Assert(list_length(info->clauses) == list_length(pinfo->clauses));
533  Assert(list_length(info->pathkeys) == list_length(pinfo->pathkeys));
534  Assert(list_difference(info->clauses, pinfo->clauses) == NIL);
535  Assert(list_difference_ptr(info->pathkeys, pinfo->pathkeys) == NIL);
536 
537  forboth(lc1, info->clauses, lc2, info->pathkeys)
538  {
540  PathKey *pk = lfirst_node(PathKey, lc2);
541 
542  Assert(pk->pk_eclass->ec_sortref == sgc->tleSortGroupRef);
543  }
544  }
545  }
546 #endif
547  return infos;
548 }
List * list_difference_ptr(const List *list1, const List *list2)
Definition: list.c:1263
List * list_difference(const List *list1, const List *list2)
Definition: list.c:1237
static int group_keys_reorder_by_pathkeys(List *pathkeys, List **group_pathkeys, List **group_clauses, int num_groupby_pathkeys)
Definition: pathkeys.c:368
bool enable_group_by_reordering
Definition: pathkeys.c:31
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:715
Index tleSortGroupRef
Definition: parsenodes.h:1442

References Assert, GroupByOrdering::clauses, compare_pathkeys(), enable_group_by_reordering, enable_incremental_sort, for_each_from, forboth, group_keys_reorder_by_pathkeys(), lappend(), lfirst_node, linitial_node, list_difference(), list_difference_ptr(), list_length(), makeNode, NIL, parse(), GroupByOrdering::pathkeys, Path::pathkeys, pathkeys_contained_in(), PATHKEYS_EQUAL, root, and SortGroupClause::tleSortGroupRef.

Referenced by add_paths_to_grouping_rel(), and create_partial_grouping_paths().

◆ has_relevant_eclass_joinclause()

bool has_relevant_eclass_joinclause ( PlannerInfo root,
RelOptInfo rel1 
)

Definition at line 3168 of file equivclass.c.

3169 {
3170  Bitmapset *matched_ecs;
3171  int i;
3172 
3173  /* Examine only eclasses mentioning rel1 */
3174  matched_ecs = get_eclass_indexes_for_relids(root, rel1->relids);
3175 
3176  i = -1;
3177  while ((i = bms_next_member(matched_ecs, i)) >= 0)
3178  {
3179  EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
3180  i);
3181 
3182  /*
3183  * Won't generate joinclauses if single-member (this test covers the
3184  * volatile case too)
3185  */
3186  if (list_length(ec->ec_members) <= 1)
3187  continue;
3188 
3189  /*
3190  * Per the comment in have_relevant_eclass_joinclause, it's sufficient
3191  * to find an EC that mentions both this rel and some other rel.
3192  */
3193  if (!bms_is_subset(ec->ec_relids, rel1->relids))
3194  return true;
3195  }
3196 
3197  return false;
3198 }

References bms_is_subset(), bms_next_member(), EquivalenceClass::ec_members, EquivalenceClass::ec_relids, get_eclass_indexes_for_relids(), i, list_length(), list_nth(), RelOptInfo::relids, and root.

Referenced by build_join_rel().

◆ has_useful_pathkeys()

bool has_useful_pathkeys ( PlannerInfo root,
RelOptInfo rel 
)

Definition at line 2261 of file pathkeys.c.

2262 {
2263  if (rel->joininfo != NIL || rel->has_eclass_joins)
2264  return true; /* might be able to use pathkeys for merging */
2265  if (root->group_pathkeys != NIL)
2266  return true; /* might be able to use pathkeys for grouping */
2267  if (root->query_pathkeys != NIL)
2268  return true; /* might be able to use them for ordering */
2269  return false; /* definitely useless */
2270 }

References RelOptInfo::has_eclass_joins, RelOptInfo::joininfo, NIL, and root.

Referenced by build_child_join_rel(), build_index_paths(), and set_append_rel_size().

◆ have_dangerous_phv()

bool have_dangerous_phv ( PlannerInfo root,
Relids  outer_relids,
Relids  inner_params 
)

Definition at line 1307 of file joinrels.c.

1309 {
1310  ListCell *lc;
1311 
1312  foreach(lc, root->placeholder_list)
1313  {
1314  PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
1315 
1316  if (!bms_is_subset(phinfo->ph_eval_at, inner_params))
1317  continue; /* ignore, could not be a nestloop param */
1318  if (!bms_overlap(phinfo->ph_eval_at, outer_relids))
1319  continue; /* ignore, not relevant to this join */
1320  if (bms_is_subset(phinfo->ph_eval_at, outer_relids))
1321  continue; /* safe, it can be eval'd within outerrel */
1322  /* Otherwise, it's potentially unsafe, so reject the join */
1323  return true;
1324  }
1325 
1326  /* OK to perform the join */
1327  return false;
1328 }
Relids ph_eval_at
Definition: pathnodes.h:3088

References bms_is_subset(), bms_overlap(), lfirst, PlaceHolderInfo::ph_eval_at, and root.

Referenced by join_is_legal(), and try_nestloop_path().

◆ have_join_order_restriction()

bool have_join_order_restriction ( PlannerInfo root,
RelOptInfo rel1,
RelOptInfo rel2 
)

Definition at line 1074 of file joinrels.c.

1076 {
1077  bool result = false;
1078  ListCell *l;
1079 
1080  /*
1081  * If either side has a direct lateral reference to the other, attempt the
1082  * join regardless of outer-join considerations.
1083  */
1084  if (bms_overlap(rel1->relids, rel2->direct_lateral_relids) ||
1086  return true;
1087 
1088  /*
1089  * Likewise, if both rels are needed to compute some PlaceHolderVar,
1090  * attempt the join regardless of outer-join considerations. (This is not
1091  * very desirable, because a PHV with a large eval_at set will cause a lot
1092  * of probably-useless joins to be considered, but failing to do this can
1093  * cause us to fail to construct a plan at all.)
1094  */
1095  foreach(l, root->placeholder_list)
1096  {
1097  PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l);
1098 
1099  if (bms_is_subset(rel1->relids, phinfo->ph_eval_at) &&
1100  bms_is_subset(rel2->relids, phinfo->ph_eval_at))
1101  return true;
1102  }
1103 
1104  /*
1105  * It's possible that the rels correspond to the left and right sides of a
1106  * degenerate outer join, that is, one with no joinclause mentioning the
1107  * non-nullable side; in which case we should force the join to occur.
1108  *
1109  * Also, the two rels could represent a clauseless join that has to be
1110  * completed to build up the LHS or RHS of an outer join.
1111  */
1112  foreach(l, root->join_info_list)
1113  {
1114  SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
1115 
1116  /* ignore full joins --- other mechanisms handle them */
1117  if (sjinfo->jointype == JOIN_FULL)
1118  continue;
1119 
1120  /* Can we perform the SJ with these rels? */
1121  if (bms_is_subset(sjinfo->min_lefthand, rel1->relids) &&
1122  bms_is_subset(sjinfo->min_righthand, rel2->relids))
1123  {
1124  result = true;
1125  break;
1126  }
1127  if (bms_is_subset(sjinfo->min_lefthand, rel2->relids) &&
1128  bms_is_subset(sjinfo->min_righthand, rel1->relids))
1129  {
1130  result = true;
1131  break;
1132  }
1133 
1134  /*
1135  * Might we need to join these rels to complete the RHS? We have to
1136  * use "overlap" tests since either rel might include a lower SJ that
1137  * has been proven to commute with this one.
1138  */
1139  if (bms_overlap(sjinfo->min_righthand, rel1->relids) &&
1140  bms_overlap(sjinfo->min_righthand, rel2->relids))
1141  {
1142  result = true;
1143  break;
1144  }
1145 
1146  /* Likewise for the LHS. */
1147  if (bms_overlap(sjinfo->min_lefthand, rel1->relids) &&
1148  bms_overlap(sjinfo->min_lefthand, rel2->relids))
1149  {
1150  result = true;
1151  break;
1152  }
1153  }
1154 
1155  /*
1156  * We do not force the join to occur if either input rel can legally be
1157  * joined to anything else using joinclauses. This essentially means that
1158  * clauseless bushy joins are put off as long as possible. The reason is
1159  * that when there is a join order restriction high up in the join tree
1160  * (that is, with many rels inside the LHS or RHS), we would otherwise
1161  * expend lots of effort considering very stupid join combinations within
1162  * its LHS or RHS.
1163  */
1164  if (result)
1165  {
1166  if (has_legal_joinclause(root, rel1) ||
1167  has_legal_joinclause(root, rel2))
1168  result = false;
1169  }
1170 
1171  return result;
1172 }
static bool has_legal_joinclause(PlannerInfo *root, RelOptInfo *rel)
Definition: joinrels.c:1243
Relids direct_lateral_relids
Definition: pathnodes.h:905

References bms_is_subset(), bms_overlap(), RelOptInfo::direct_lateral_relids, has_legal_joinclause(), JOIN_FULL, SpecialJoinInfo::jointype, lfirst, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, PlaceHolderInfo::ph_eval_at, RelOptInfo::relids, and root.

Referenced by desirable_join(), join_search_one_level(), and make_rels_by_clause_joins().

◆ have_relevant_eclass_joinclause()

bool have_relevant_eclass_joinclause ( PlannerInfo root,
RelOptInfo rel1,
RelOptInfo rel2 
)

Definition at line 3092 of file equivclass.c.

3094 {
3095  Bitmapset *matching_ecs;
3096  int i;
3097 
3098  /*
3099  * Examine only eclasses mentioning both rel1 and rel2.
3100  *
3101  * Note that we do not consider the possibility of an eclass generating
3102  * "join" clauses that mention just one of the rels plus an outer join
3103  * that could be formed from them. Although such clauses must be
3104  * correctly enforced when we form the outer join, they don't seem like
3105  * sufficient reason to prioritize this join over other ones. The join
3106  * ordering rules will force the join to be made when necessary.
3107  */
3108  matching_ecs = get_common_eclass_indexes(root, rel1->relids,
3109  rel2->relids);
3110 
3111  i = -1;
3112  while ((i = bms_next_member(matching_ecs, i)) >= 0)
3113  {
3114  EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
3115  i);
3116 
3117  /*
3118  * Sanity check that get_common_eclass_indexes gave only ECs
3119  * containing both rels.
3120  */
3121  Assert(bms_overlap(rel1->relids, ec->ec_relids));
3122  Assert(bms_overlap(rel2->relids, ec->ec_relids));
3123 
3124  /*
3125  * Won't generate joinclauses if single-member (this test covers the
3126  * volatile case too)
3127  */
3128  if (list_length(ec->ec_members) <= 1)
3129  continue;
3130 
3131  /*
3132  * We do not need to examine the individual members of the EC, because
3133  * all that we care about is whether each rel overlaps the relids of
3134  * at least one member, and get_common_eclass_indexes() and the single
3135  * member check above are sufficient to prove that. (As with
3136  * have_relevant_joinclause(), it is not necessary that the EC be able
3137  * to form a joinclause relating exactly the two given rels, only that
3138  * it be able to form a joinclause mentioning both, and this will
3139  * surely be true if both of them overlap ec_relids.)
3140  *
3141  * Note we don't test ec_broken; if we did, we'd need a separate code
3142  * path to look through ec_sources. Checking the membership anyway is
3143  * OK as a possibly-overoptimistic heuristic.
3144  *
3145  * We don't test ec_has_const either, even though a const eclass won't
3146  * generate real join clauses. This is because if we had "WHERE a.x =
3147  * b.y and a.x = 42", it is worth considering a join between a and b,
3148  * since the join result is likely to be small even though it'll end
3149  * up being an unqualified nestloop.
3150  */
3151 
3152  return true;
3153  }
3154 
3155  return false;
3156 }

References Assert, bms_next_member(), bms_overlap(), EquivalenceClass::ec_members, EquivalenceClass::ec_relids, get_common_eclass_indexes(), i, list_length(), list_nth(), RelOptInfo::relids, and root.

Referenced by have_relevant_joinclause().

◆ indexcol_is_bool_constant_for_query()

bool indexcol_is_bool_constant_for_query ( PlannerInfo root,
IndexOptInfo index,
int  indexcol 
)

Definition at line 3614 of file indxpath.c.

3617 {
3618  ListCell *lc;
3619 
3620  /* If the index isn't boolean, we can't possibly get a match */
3621  if (!IsBooleanOpfamily(index->opfamily[indexcol]))
3622  return false;
3623 
3624  /* Check each restriction clause for the index's rel */
3625  foreach(lc, index->rel->baserestrictinfo)
3626  {
3627  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3628 
3629  /*
3630  * As in match_clause_to_indexcol, never match pseudoconstants to
3631  * indexes. (It might be semantically okay to do so here, but the
3632  * odds of getting a match are negligible, so don't waste the cycles.)
3633  */
3634  if (rinfo->pseudoconstant)
3635  continue;
3636 
3637  /* See if we can match the clause's expression to the index column */
3638  if (match_boolean_index_clause(root, rinfo, indexcol, index))
3639  return true;
3640  }
3641 
3642  return false;
3643 }
static bool IsBooleanOpfamily(Oid opfamily)
Definition: indxpath.c:2280
static IndexClause * match_boolean_index_clause(PlannerInfo *root, RestrictInfo *rinfo, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:2305

References IsBooleanOpfamily(), lfirst, match_boolean_index_clause(), and root.

Referenced by build_index_pathkeys().

◆ init_dummy_sjinfo()

void init_dummy_sjinfo ( SpecialJoinInfo sjinfo,
Relids  left_relids,
Relids  right_relids 
)

Definition at line 669 of file joinrels.c.

671 {
672  sjinfo->type = T_SpecialJoinInfo;
673  sjinfo->min_lefthand = left_relids;
674  sjinfo->min_righthand = right_relids;
675  sjinfo->syn_lefthand = left_relids;
676  sjinfo->syn_righthand = right_relids;
677  sjinfo->jointype = JOIN_INNER;
678  sjinfo->ojrelid = 0;
679  sjinfo->commute_above_l = NULL;
680  sjinfo->commute_above_r = NULL;
681  sjinfo->commute_below_l = NULL;
682  sjinfo->commute_below_r = NULL;
683  /* we don't bother trying to make the remaining fields valid */
684  sjinfo->lhs_strict = false;
685  sjinfo->semi_can_btree = false;
686  sjinfo->semi_can_hash = false;
687  sjinfo->semi_operators = NIL;
688  sjinfo->semi_rhs_exprs = NIL;
689 }
Relids commute_above_r
Definition: pathnodes.h:2901
Relids syn_lefthand
Definition: pathnodes.h:2896
List * semi_rhs_exprs
Definition: pathnodes.h:2909
Relids syn_righthand
Definition: pathnodes.h:2897
Relids commute_below_r
Definition: pathnodes.h:2903
List * semi_operators
Definition: pathnodes.h:2908

References SpecialJoinInfo::commute_above_l, SpecialJoinInfo::commute_above_r, SpecialJoinInfo::commute_below_l, SpecialJoinInfo::commute_below_r, JOIN_INNER, SpecialJoinInfo::jointype, SpecialJoinInfo::lhs_strict, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, NIL, SpecialJoinInfo::ojrelid, SpecialJoinInfo::semi_can_btree, SpecialJoinInfo::semi_can_hash, SpecialJoinInfo::semi_operators, SpecialJoinInfo::semi_rhs_exprs, SpecialJoinInfo::syn_lefthand, and SpecialJoinInfo::syn_righthand.

Referenced by approx_tuple_count(), build_child_join_sjinfo(), compute_semi_anti_join_factors(), consider_new_or_clause(), and make_join_rel().

◆ initialize_mergeclause_eclasses()

void initialize_mergeclause_eclasses ( PlannerInfo root,
RestrictInfo restrictinfo 
)

Definition at line 1446 of file pathkeys.c.

1447 {
1448  Expr *clause = restrictinfo->clause;
1449  Oid lefttype,
1450  righttype;
1451 
1452  /* Should be a mergeclause ... */
1453  Assert(restrictinfo->mergeopfamilies != NIL);
1454  /* ... with links not yet set */
1455  Assert(restrictinfo->left_ec == NULL);
1456  Assert(restrictinfo->right_ec == NULL);
1457 
1458  /* Need the declared input types of the operator */
1459  op_input_types(((OpExpr *) clause)->opno, &lefttype, &righttype);
1460 
1461  /* Find or create a matching EquivalenceClass for each side */
1462  restrictinfo->left_ec =
1464  (Expr *) get_leftop(clause),
1465  restrictinfo->mergeopfamilies,
1466  lefttype,
1467  ((OpExpr *) clause)->inputcollid,
1468  0,
1469  NULL,
1470  true);
1471  restrictinfo->right_ec =
1473  (Expr *) get_rightop(clause),
1474  restrictinfo->mergeopfamilies,
1475  righttype,
1476  ((OpExpr *) clause)->inputcollid,
1477  0,
1478  NULL,
1479  true);
1480 }
void op_input_types(Oid opno, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:1358
static Node * get_rightop(const void *clause)
Definition: nodeFuncs.h:93
static Node * get_leftop(const void *clause)
Definition: nodeFuncs.h:81

References Assert, RestrictInfo::clause, get_eclass_for_sort_expr(), get_leftop(), get_rightop(), NIL, op_input_types(), and root.

Referenced by distribute_qual_to_rels().

◆ is_redundant_derived_clause()

bool is_redundant_derived_clause ( RestrictInfo rinfo,
List clauselist 
)

Definition at line 3270 of file equivclass.c.

3271 {
3272  EquivalenceClass *parent_ec = rinfo->parent_ec;
3273  ListCell *lc;
3274 
3275  /* Fail if it's not a potentially-redundant clause from some EC */
3276  if (parent_ec == NULL)
3277  return false;
3278 
3279  foreach(lc, clauselist)
3280  {
3281  RestrictInfo *otherrinfo = (RestrictInfo *) lfirst(lc);
3282 
3283  if (otherrinfo->parent_ec == parent_ec)
3284  return true;
3285  }
3286 
3287  return false;
3288 }

References lfirst.

Referenced by create_tidscan_plan().

◆ is_redundant_with_indexclauses()

bool is_redundant_with_indexclauses ( RestrictInfo rinfo,
List indexclauses 
)

Definition at line 3297 of file equivclass.c.

3298 {
3299  EquivalenceClass *parent_ec = rinfo->parent_ec;
3300  ListCell *lc;
3301 
3302  foreach(lc, indexclauses)
3303  {
3304  IndexClause *iclause = lfirst_node(IndexClause, lc);
3305  RestrictInfo *otherrinfo = iclause->rinfo;
3306 
3307  /* If indexclause is lossy, it won't enforce the condition exactly */
3308  if (iclause->lossy)
3309  continue;
3310 
3311  /* Match if it's same clause (pointer equality should be enough) */
3312  if (rinfo == otherrinfo)
3313  return true;
3314  /* Match if derived from same EC */
3315  if (parent_ec && otherrinfo->parent_ec == parent_ec)
3316  return true;
3317 
3318  /*
3319  * No need to look at the derived clauses in iclause->indexquals; they
3320  * couldn't match if the parent clause didn't.
3321  */
3322  }
3323 
3324  return false;
3325 }
struct RestrictInfo * rinfo
Definition: pathnodes.h:1758

References lfirst_node, IndexClause::lossy, and IndexClause::rinfo.

Referenced by create_indexscan_plan(), extract_nonindex_conditions(), and has_indexed_join_quals().

◆ join_search_one_level()

void join_search_one_level ( PlannerInfo root,
int  level 
)

Definition at line 72 of file joinrels.c.

73 {
74  List **joinrels = root->join_rel_level;
75  ListCell *r;
76  int k;
77 
78  Assert(joinrels[level] == NIL);
79 
80  /* Set join_cur_level so that new joinrels are added to proper list */
81  root->join_cur_level = level;
82 
83  /*
84  * First, consider left-sided and right-sided plans, in which rels of
85  * exactly level-1 member relations are joined against initial relations.
86  * We prefer to join using join clauses, but if we find a rel of level-1
87  * members that has no join clauses, we will generate Cartesian-product
88  * joins against all initial rels not already contained in it.
89  */
90  foreach(r, joinrels[level - 1])
91  {
92  RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
93 
94  if (old_rel->joininfo != NIL || old_rel->has_eclass_joins ||
95  has_join_restriction(root, old_rel))
96  {
97  int first_rel;
98 
99  /*
100  * There are join clauses or join order restrictions relevant to
101  * this rel, so consider joins between this rel and (only) those
102  * initial rels it is linked to by a clause or restriction.
103  *
104  * At level 2 this condition is symmetric, so there is no need to
105  * look at initial rels before this one in the list; we already
106  * considered such joins when we were at the earlier rel. (The
107  * mirror-image joins are handled automatically by make_join_rel.)
108  * In later passes (level > 2), we join rels of the previous level
109  * to each initial rel they don't already include but have a join
110  * clause or restriction with.
111  */
112  if (level == 2) /* consider remaining initial rels */
113  first_rel = foreach_current_index(r) + 1;
114  else
115  first_rel = 0;
116 
117  make_rels_by_clause_joins(root, old_rel, joinrels[1], first_rel);
118  }
119  else
120  {
121  /*
122  * Oops, we have a relation that is not joined to any other
123  * relation, either directly or by join-order restrictions.
124  * Cartesian product time.
125  *
126  * We consider a cartesian product with each not-already-included
127  * initial rel, whether it has other join clauses or not. At
128  * level 2, if there are two or more clauseless initial rels, we
129  * will redundantly consider joining them in both directions; but
130  * such cases aren't common enough to justify adding complexity to
131  * avoid the duplicated effort.
132  */
134  old_rel,
135  joinrels[1]);
136  }
137  }
138 
139  /*
140  * Now, consider "bushy plans" in which relations of k initial rels are
141  * joined to relations of level-k initial rels, for 2 <= k <= level-2.
142  *
143  * We only consider bushy-plan joins for pairs of rels where there is a
144  * suitable join clause (or join order restriction), in order to avoid
145  * unreasonable growth of planning time.
146  */
147  for (k = 2;; k++)
148  {
149  int other_level = level - k;
150 
151  /*
152  * Since make_join_rel(x, y) handles both x,y and y,x cases, we only
153  * need to go as far as the halfway point.
154  */
155  if (k > other_level)
156  break;
157 
158  foreach(r, joinrels[k])
159  {
160  RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
161  int first_rel;
162  ListCell *r2;
163 
164  /*
165  * We can ignore relations without join clauses here, unless they
166  * participate in join-order restrictions --- then we might have
167  * to force a bushy join plan.
168  */
169  if (old_rel->joininfo == NIL && !old_rel->has_eclass_joins &&
170  !has_join_restriction(root, old_rel))
171  continue;
172 
173  if (k == other_level) /* only consider remaining rels */
174  first_rel = foreach_current_index(r) + 1;
175  else
176  first_rel = 0;
177 
178  for_each_from(r2, joinrels[other_level], first_rel)
179  {
180  RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2);
181 
182  if (!bms_overlap(old_rel->relids, new_rel->relids))
183  {
184  /*
185  * OK, we can build a rel of the right level from this
186  * pair of rels. Do so if there is at least one relevant
187  * join clause or join order restriction.
188  */
189  if (have_relevant_joinclause(root, old_rel, new_rel) ||
190  have_join_order_restriction(root, old_rel, new_rel))
191  {
192  (void) make_join_rel(root, old_rel, new_rel);
193  }
194  }
195  }
196  }
197  }
198 
199  /*----------
200  * Last-ditch effort: if we failed to find any usable joins so far, force
201  * a set of cartesian-product joins to be generated. This handles the
202  * special case where all the available rels have join clauses but we
203  * cannot use any of those clauses yet. This can only happen when we are
204  * considering a join sub-problem (a sub-joinlist) and all the rels in the
205  * sub-problem have only join clauses with rels outside the sub-problem.
206  * An example is
207  *
208  * SELECT ... FROM a INNER JOIN b ON TRUE, c, d, ...
209  * WHERE a.w = c.x and b.y = d.z;
210  *
211  * If the "a INNER JOIN b" sub-problem does not get flattened into the
212  * upper level, we must be willing to make a cartesian join of a and b;
213  * but the code above will not have done so, because it thought that both
214  * a and b have joinclauses. We consider only left-sided and right-sided
215  * cartesian joins in this case (no bushy).
216  *----------
217  */
218  if (joinrels[level] == NIL)
219  {
220  /*
221  * This loop is just like the first one, except we always call
222  * make_rels_by_clauseless_joins().
223  */
224  foreach(r, joinrels[level - 1])
225  {
226  RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
227 
229  old_rel,
230  joinrels[1]);
231  }
232 
233  /*----------
234  * When special joins are involved, there may be no legal way
235  * to make an N-way join for some values of N. For example consider
236  *
237  * SELECT ... FROM t1 WHERE
238  * x IN (SELECT ... FROM t2,t3 WHERE ...) AND
239  * y IN (SELECT ... FROM t4,t5 WHERE ...)
240  *
241  * We will flatten this query to a 5-way join problem, but there are
242  * no 4-way joins that join_is_legal() will consider legal. We have
243  * to accept failure at level 4 and go on to discover a workable
244  * bushy plan at level 5.
245  *
246  * However, if there are no special joins and no lateral references
247  * then join_is_legal() should never fail, and so the following sanity
248  * check is useful.
249  *----------
250  */
251  if (joinrels[level] == NIL &&
252  root->join_info_list == NIL &&
253  !root->hasLateralRTEs)
254  elog(ERROR, "failed to build any %d-way joins", level);
255  }
256 }
bool have_relevant_joinclause(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
Definition: joininfo.c:39
static void make_rels_by_clauseless_joins(PlannerInfo *root, RelOptInfo *old_rel, List *other_rels)
Definition: joinrels.c:313
RelOptInfo * make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
Definition: joinrels.c:704
bool have_join_order_restriction(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
Definition: joinrels.c:1074
static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel)
Definition: joinrels.c:1187
static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel, List *other_rels, int first_rel_idx)
Definition: joinrels.c:279
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403

References Assert, bms_overlap(), elog, ERROR, for_each_from, foreach_current_index, RelOptInfo::has_eclass_joins, has_join_restriction(), have_join_order_restriction(), have_relevant_joinclause(), RelOptInfo::joininfo, lfirst, make_join_rel(), make_rels_by_clause_joins(), make_rels_by_clauseless_joins(), NIL, RelOptInfo::relids, and root.

Referenced by standard_join_search().

◆ make_canonical_pathkey()

PathKey* make_canonical_pathkey ( PlannerInfo root,
EquivalenceClass eclass,
Oid  opfamily,
int  strategy,
bool  nulls_first 
)

Definition at line 55 of file pathkeys.c.

58 {
59  PathKey *pk;
60  ListCell *lc;
61  MemoryContext oldcontext;
62 
63  /* Can't make canonical pathkeys if the set of ECs might still change */
64  if (!root->ec_merging_done)
65  elog(ERROR, "too soon to build canonical pathkeys");
66 
67  /* The passed eclass might be non-canonical, so chase up to the top */
68  while (eclass->ec_merged)
69  eclass = eclass->ec_merged;
70 
71  foreach(lc, root->canon_pathkeys)
72  {
73  pk = (PathKey *) lfirst(lc);
74  if (eclass == pk->pk_eclass &&
75  opfamily == pk->pk_opfamily &&
76  strategy == pk->pk_strategy &&
77  nulls_first == pk->pk_nulls_first)
78  return pk;
79  }
80 
81  /*
82  * Be sure canonical pathkeys are allocated in the main planning context.
83  * Not an issue in normal planning, but it is for GEQO.
84  */
85  oldcontext = MemoryContextSwitchTo(root->planner_cxt);
86 
87  pk = makeNode(PathKey);
88  pk->pk_eclass = eclass;
89  pk->pk_opfamily = opfamily;
90  pk->pk_strategy = strategy;
91  pk->pk_nulls_first = nulls_first;
92 
93  root->canon_pathkeys = lappend(root->canon_pathkeys, pk);
94 
95  MemoryContextSwitchTo(oldcontext);
96 
97  return pk;
98 }

References eclass(), elog, ERROR, lappend(), lfirst, makeNode, MemoryContextSwitchTo(), PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, and root.

Referenced by convert_subquery_pathkeys(), get_useful_pathkeys_for_relation(), make_inner_pathkeys_for_merge(), make_pathkey_from_sortinfo(), and select_outer_pathkeys_for_merge().

◆ make_inner_pathkeys_for_merge()

List* make_inner_pathkeys_for_merge ( PlannerInfo root,
List mergeclauses,
List outer_pathkeys 
)

Definition at line 1838 of file pathkeys.c.

1841 {
1842  List *pathkeys = NIL;
1843  EquivalenceClass *lastoeclass;
1844  PathKey *opathkey;
1845  ListCell *lc;
1846  ListCell *lop;
1847 
1848  lastoeclass = NULL;
1849  opathkey = NULL;
1850  lop = list_head(outer_pathkeys);
1851 
1852  foreach(lc, mergeclauses)
1853  {
1854  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1855  EquivalenceClass *oeclass;
1856  EquivalenceClass *ieclass;
1857  PathKey *pathkey;
1858 
1860 
1861  if (rinfo->outer_is_left)
1862  {
1863  oeclass = rinfo->left_ec;
1864  ieclass = rinfo->right_ec;
1865  }
1866  else
1867  {
1868  oeclass = rinfo->right_ec;
1869  ieclass = rinfo->left_ec;
1870  }
1871 
1872  /* outer eclass should match current or next pathkeys */
1873  /* we check this carefully for debugging reasons */
1874  if (oeclass != lastoeclass)
1875  {
1876  if (!lop)
1877  elog(ERROR, "too few pathkeys for mergeclauses");
1878  opathkey = (PathKey *) lfirst(lop);
1879  lop = lnext(outer_pathkeys, lop);
1880  lastoeclass = opathkey->pk_eclass;
1881  if (oeclass != lastoeclass)
1882  elog(ERROR, "outer pathkeys do not match mergeclause");
1883  }
1884 
1885  /*
1886  * Often, we'll have same EC on both sides, in which case the outer
1887  * pathkey is also canonical for the inner side, and we can skip a
1888  * useless search.
1889  */
1890  if (ieclass == oeclass)
1891  pathkey = opathkey;
1892  else
1893  pathkey = make_canonical_pathkey(root,
1894  ieclass,
1895  opathkey->pk_opfamily,
1896  opathkey->pk_strategy,
1897  opathkey->pk_nulls_first);
1898 
1899  /*
1900  * Don't generate redundant pathkeys (which can happen if multiple
1901  * mergeclauses refer to the same EC). Because we do this, the output
1902  * pathkey list isn't necessarily ordered like the mergeclauses, which
1903  * complicates life for create_mergejoin_plan(). But if we didn't,
1904  * we'd have a noncanonical sort key list, which would be bad; for one
1905  * reason, it certainly wouldn't match any available sort order for
1906  * the input relation.
1907  */
1908  if (!pathkey_is_redundant(pathkey, pathkeys))
1909  pathkeys = lappend(pathkeys, pathkey);
1910  }
1911 
1912  return pathkeys;
1913 }

References elog, ERROR, lappend(), lfirst, list_head(), lnext(), make_canonical_pathkey(), NIL, pathkey_is_redundant(), PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, root, and update_mergeclause_eclasses().

Referenced by generate_mergejoin_paths(), and sort_inner_and_outer().

◆ make_join_rel()

RelOptInfo* make_join_rel ( PlannerInfo root,
RelOptInfo rel1,
RelOptInfo rel2 
)

Definition at line 704 of file joinrels.c.

705 {
706  Relids joinrelids;
707  SpecialJoinInfo *sjinfo;
708  bool reversed;
709  List *pushed_down_joins = NIL;
710  SpecialJoinInfo sjinfo_data;
711  RelOptInfo *joinrel;
712  List *restrictlist;
713 
714  /* We should never try to join two overlapping sets of rels. */
715  Assert(!bms_overlap(rel1->relids, rel2->relids));
716 
717  /* Construct Relids set that identifies the joinrel (without OJ as yet). */
718  joinrelids = bms_union(rel1->relids, rel2->relids);
719 
720  /* Check validity and determine join type. */
721  if (!join_is_legal(root, rel1, rel2, joinrelids,
722  &sjinfo, &reversed))
723  {
724  /* invalid join path */
725  bms_free(joinrelids);
726  return NULL;
727  }
728 
729  /*
730  * Add outer join relid(s) to form the canonical relids. Any added outer
731  * joins besides sjinfo itself are appended to pushed_down_joins.
732  */
733  joinrelids = add_outer_joins_to_relids(root, joinrelids, sjinfo,
734  &pushed_down_joins);
735 
736  /* Swap rels if needed to match the join info. */
737  if (reversed)
738  {
739  RelOptInfo *trel = rel1;
740 
741  rel1 = rel2;
742  rel2 = trel;
743  }
744 
745  /*
746  * If it's a plain inner join, then we won't have found anything in
747  * join_info_list. Make up a SpecialJoinInfo so that selectivity
748  * estimation functions will know what's being joined.
749  */
750  if (sjinfo == NULL)
751  {
752  sjinfo = &sjinfo_data;
753  init_dummy_sjinfo(sjinfo, rel1->relids, rel2->relids);
754  }
755 
756  /*
757  * Find or build the join RelOptInfo, and compute the restrictlist that
758  * goes with this particular joining.
759  */
760  joinrel = build_join_rel(root, joinrelids, rel1, rel2,
761  sjinfo, pushed_down_joins,
762  &restrictlist);
763 
764  /*
765  * If we've already proven this join is empty, we needn't consider any
766  * more paths for it.
767  */
768  if (is_dummy_rel(joinrel))
769  {
770  bms_free(joinrelids);
771  return joinrel;
772  }
773 
774  /* Add paths to the join relation. */
775  populate_joinrel_with_paths(root, rel1, rel2, joinrel, sjinfo,
776  restrictlist);
777 
778  bms_free(joinrelids);
779 
780  return joinrel;
781 }
void bms_free(Bitmapset *a)
Definition: bitmapset.c:239
static void populate_joinrel_with_paths(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2, RelOptInfo *joinrel, SpecialJoinInfo *sjinfo, List *restrictlist)
Definition: joinrels.c:893
bool is_dummy_rel(RelOptInfo *rel)
Definition: joinrels.c:1335
void init_dummy_sjinfo(SpecialJoinInfo *sjinfo, Relids left_relids, Relids right_relids)
Definition: joinrels.c:669
static bool join_is_legal(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2, Relids joinrelids, SpecialJoinInfo **sjinfo_p, bool *reversed_p)
Definition: joinrels.c:349
RelOptInfo * build_join_rel(PlannerInfo *root, Relids joinrelids, RelOptInfo *outer_rel, RelOptInfo *inner_rel, SpecialJoinInfo *sjinfo, List *pushed_down_joins, List **restrictlist_ptr)
Definition: relnode.c:665

References add_outer_joins_to_relids(), Assert, bms_free(), bms_overlap(), bms_union(), build_join_rel(), init_dummy_sjinfo(), is_dummy_rel(), join_is_legal(), NIL, populate_joinrel_with_paths(), RelOptInfo::relids, and root.

Referenced by join_search_one_level(), make_rels_by_clause_joins(), make_rels_by_clauseless_joins(), and merge_clump().

◆ make_one_rel()

RelOptInfo* make_one_rel ( PlannerInfo root,
List joinlist 
)

Definition at line 171 of file allpaths.c.

172 {
173  RelOptInfo *rel;
174  Index rti;
175  double total_pages;
176 
177  /* Mark base rels as to whether we care about fast-start plans */
179 
180  /*
181  * Compute size estimates and consider_parallel flags for each base rel.
182  */
184 
185  /*
186  * We should now have size estimates for every actual table involved in
187  * the query, and we also know which if any have been deleted from the
188  * query by join removal, pruned by partition pruning, or eliminated by
189  * constraint exclusion. So we can now compute total_table_pages.
190  *
191  * Note that appendrels are not double-counted here, even though we don't
192  * bother to distinguish RelOptInfos for appendrel parents, because the
193  * parents will have pages = 0.
194  *
195  * XXX if a table is self-joined, we will count it once per appearance,
196  * which perhaps is the wrong thing ... but that's not completely clear,
197  * and detecting self-joins here is difficult, so ignore it for now.
198  */
199  total_pages = 0;
200  for (rti = 1; rti < root->simple_rel_array_size; rti++)
201  {
202  RelOptInfo *brel = root->simple_rel_array[rti];
203 
204  /* there may be empty slots corresponding to non-baserel RTEs */
205  if (brel == NULL)
206  continue;
207 
208  Assert(brel->relid == rti); /* sanity check on array */
209 
210  if (IS_DUMMY_REL(brel))
211  continue;
212 
213  if (IS_SIMPLE_REL(brel))
214  total_pages += (double) brel->pages;
215  }
216  root->total_table_pages = total_pages;
217 
218  /*
219  * Generate access paths for each base rel.
220  */
222 
223  /*
224  * Generate access paths for the entire join tree.
225  */
226  rel = make_rel_from_joinlist(root, joinlist);
227 
228  /*
229  * The result should join all and only the query's base + outer-join rels.
230  */
231  Assert(bms_equal(rel->relids, root->all_query_rels));
232 
233  return rel;
234 }
static void set_base_rel_sizes(PlannerInfo *root)
Definition: allpaths.c:290
static void set_base_rel_consider_startup(PlannerInfo *root)
Definition: allpaths.c:247
static void set_base_rel_pathlists(PlannerInfo *root)
Definition: allpaths.c:333
static RelOptInfo * make_rel_from_joinlist(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:3313
unsigned int Index
Definition: c.h:614
BlockNumber pages
Definition: pathnodes.h:942

References Assert, bms_equal(), IS_DUMMY_REL, IS_SIMPLE_REL, make_rel_from_joinlist(), RelOptInfo::pages, RelOptInfo::relid, RelOptInfo::relids, root, set_base_rel_consider_startup(), set_base_rel_pathlists(), and set_base_rel_sizes().

Referenced by query_planner().

◆ make_pathkeys_for_sortclauses()

List* make_pathkeys_for_sortclauses ( PlannerInfo root,
List sortclauses,
List tlist 
)

Definition at line 1333 of file pathkeys.c.

1336 {
1337  List *result;
1338  bool sortable;
1339 
1341  &sortclauses,
1342  tlist,
1343  false,
1344  &sortable,
1345  false);
1346  /* It's caller error if not all clauses were sortable */
1347  Assert(sortable);
1348  return result;
1349 }
List * make_pathkeys_for_sortclauses_extended(PlannerInfo *root, List **sortclauses, List *tlist, bool remove_redundant, bool *sortable, bool set_ec_sortref)
Definition: pathkeys.c:1374

References Assert, make_pathkeys_for_sortclauses_extended(), and root.

Referenced by adjust_group_pathkeys_for_groupagg(), generate_nonunion_paths(), generate_union_paths(), grouping_planner(), make_pathkeys_for_window(), minmax_qp_callback(), and standard_qp_callback().

◆ make_pathkeys_for_sortclauses_extended()

List* make_pathkeys_for_sortclauses_extended ( PlannerInfo root,
List **  sortclauses,
List tlist,
bool  remove_redundant,
bool sortable,
bool  set_ec_sortref 
)

Definition at line 1374 of file pathkeys.c.

1380 {
1381  List *pathkeys = NIL;
1382  ListCell *l;
1383 
1384  *sortable = true;
1385  foreach(l, *sortclauses)
1386  {
1387  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
1388  Expr *sortkey;
1389  PathKey *pathkey;
1390 
1391  sortkey = (Expr *) get_sortgroupclause_expr(sortcl, tlist);
1392  if (!OidIsValid(sortcl->sortop))
1393  {
1394  *sortable = false;
1395  continue;
1396  }
1397  pathkey = make_pathkey_from_sortop(root,
1398  sortkey,
1399  sortcl->sortop,
1400  sortcl->nulls_first,
1401  sortcl->tleSortGroupRef,
1402  true);
1403  if (pathkey->pk_eclass->ec_sortref == 0 && set_ec_sortref)
1404  {
1405  /*
1406  * Copy the sortref if it hasn't been set yet. That may happen if
1407  * the EquivalenceClass was constructed from a WHERE clause, i.e.
1408  * it doesn't have a target reference at all.
1409  */
1410  pathkey->pk_eclass->ec_sortref = sortcl->tleSortGroupRef;
1411  }
1412 
1413  /* Canonical form eliminates redundant ordering keys */
1414  if (!pathkey_is_redundant(pathkey, pathkeys))
1415  pathkeys = lappend(pathkeys, pathkey);
1416  else if (remove_redundant)
1417  *sortclauses = foreach_delete_current(*sortclauses, l);
1418  }
1419  return pathkeys;
1420 }
static PathKey * make_pathkey_from_sortop(PlannerInfo *root, Expr *expr, Oid ordering_op, bool nulls_first, Index sortref, bool create_it)
Definition: pathkeys.c:255
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
Node * get_sortgroupclause_expr(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:379

References foreach_delete_current, get_sortgroupclause_expr(), lappend(), lfirst, make_pathkey_from_sortop(), NIL, SortGroupClause::nulls_first, OidIsValid, pathkey_is_redundant(), root, SortGroupClause::sortop, and SortGroupClause::tleSortGroupRef.

Referenced by make_pathkeys_for_sortclauses(), make_pathkeys_for_window(), and standard_qp_callback().

◆ mark_dummy_rel()

void mark_dummy_rel ( RelOptInfo rel)

Definition at line 1384 of file joinrels.c.

1385 {
1386  MemoryContext oldcontext;
1387 
1388  /* Already marked? */
1389  if (is_dummy_rel(rel))
1390  return;
1391 
1392  /* No, so choose correct context to make the dummy path in */
1393  oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
1394 
1395  /* Set dummy size estimate */
1396  rel->rows = 0;
1397 
1398  /* Evict any previously chosen paths */
1399  rel->pathlist = NIL;
1400  rel->partial_pathlist = NIL;
1401 
1402  /* Set up the dummy path */
1403  add_path(rel, (Path *) create_append_path(NULL, rel, NIL, NIL,
1404  NIL, rel->lateral_relids,
1405  0, false, -1));
1406 
1407  /* Set or update cheapest_total_path and related fields */
1408  set_cheapest(rel);
1409 
1410  MemoryContextSwitchTo(oldcontext);
1411 }
MemoryContext GetMemoryChunkContext(void *pointer)
Definition: mcxt.c:707
Cardinality rows
Definition: pathnodes.h:871

References add_path(), create_append_path(), GetMemoryChunkContext(), is_dummy_rel(), RelOptInfo::lateral_relids, MemoryContextSwitchTo(), NIL, RelOptInfo::partial_pathlist, RelOptInfo::pathlist, RelOptInfo::rows, and set_cheapest().

Referenced by build_simple_rel(), generate_partitionwise_join_paths(), and populate_joinrel_with_paths().

◆ match_eclasses_to_foreign_key_col()

EquivalenceClass* match_eclasses_to_foreign_key_col ( PlannerInfo root,
ForeignKeyOptInfo fkinfo,
int  colno 
)

Definition at line 2505 of file equivclass.c.

2508 {
2509  Index var1varno = fkinfo->con_relid;
2510  AttrNumber var1attno = fkinfo->conkey[colno];
2511  Index var2varno = fkinfo->ref_relid;
2512  AttrNumber var2attno = fkinfo->confkey[colno];
2513  Oid eqop = fkinfo->conpfeqop[colno];
2514  RelOptInfo *rel1 = root->simple_rel_array[var1varno];
2515  RelOptInfo *rel2 = root->simple_rel_array[var2varno];
2516  List *opfamilies = NIL; /* compute only if needed */
2517  Bitmapset *matching_ecs;
2518  int i;
2519 
2520  /* Consider only eclasses mentioning both relations */
2521  Assert(root->ec_merging_done);
2522  Assert(IS_SIMPLE_REL(rel1));
2523  Assert(IS_SIMPLE_REL(rel2));
2524  matching_ecs = bms_intersect(rel1->eclass_indexes,
2525  rel2->eclass_indexes);
2526 
2527  i = -1;
2528  while ((i = bms_next_member(matching_ecs, i)) >= 0)
2529  {
2530  EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,
2531  i);
2532  EquivalenceMember *item1_em = NULL;
2533  EquivalenceMember *item2_em = NULL;
2534  ListCell *lc2;
2535 
2536  /* Never match to a volatile EC */
2537  if (ec->ec_has_volatile)
2538  continue;
2539  /* Note: it seems okay to match to "broken" eclasses here */
2540 
2541  foreach(lc2, ec->ec_members)
2542  {
2544  Var *var;
2545 
2546  if (em->em_is_child)
2547  continue; /* ignore children here */
2548 
2549  /* EM must be a Var, possibly with RelabelType */
2550  var = (Var *) em->em_expr;
2551  while (var && IsA(var, RelabelType))
2552  var = (Var *) ((RelabelType *) var)->arg;
2553  if (!(var && IsA(var, Var)))
2554  continue;
2555 
2556  /* Match? */
2557  if (var->varno == var1varno && var->varattno == var1attno)
2558  item1_em = em;
2559  else if (var->varno == var2varno && var->varattno == var2attno)
2560  item2_em = em;
2561 
2562  /* Have we found both PK and FK column in this EC? */
2563  if (item1_em && item2_em)
2564  {
2565  /*
2566  * Succeed if eqop matches EC's opfamilies. We could test
2567  * this before scanning the members, but it's probably cheaper
2568  * to test for member matches first.
2569  */
2570  if (opfamilies == NIL) /* compute if we didn't already */
2571  opfamilies = get_mergejoin_opfamilies(eqop);
2572  if (equal(opfamilies, ec->ec_opfamilies))
2573  {
2574  fkinfo->eclass[colno] = ec;
2575  fkinfo->fk_eclass_member[colno] = item2_em;
2576  return ec;
2577  }
2578  /* Otherwise, done with this EC, move on to the next */
2579  break;
2580  }
2581  }
2582  }
2583  return NULL;
2584 }
int16 AttrNumber
Definition: attnum.h:21
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:292
List * get_mergejoin_opfamilies(Oid opno)
Definition: lsyscache.c:366
while(p+4<=pend)
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: pathnodes.h:1250
struct EquivalenceMember * fk_eclass_member[INDEX_MAX_KEYS]
Definition: pathnodes.h:1252
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255

References Assert, bms_intersect(), bms_next_member(), ForeignKeyOptInfo::con_relid, EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_members, EquivalenceClass::ec_opfamilies, ForeignKeyOptInfo::eclass, RelOptInfo::eclass_indexes, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, equal(), ForeignKeyOptInfo::fk_eclass_member, get_mergejoin_opfamilies(), i, IS_SIMPLE_REL, IsA, lfirst, list_nth(), NIL, ForeignKeyOptInfo::ref_relid, root, Var::varattno, Var::varno, and while().

Referenced by match_foreign_keys_to_quals().

◆ match_index_to_operand()

bool match_index_to_operand ( Node operand,
int  indexcol,
IndexOptInfo index 
)

Definition at line 3665 of file indxpath.c.

3668 {
3669  int indkey;
3670 
3671  /*
3672  * Ignore any RelabelType node above the operand. This is needed to be
3673  * able to apply indexscanning in binary-compatible-operator cases. Note:
3674  * we can assume there is at most one RelabelType node;
3675  * eval_const_expressions() will have simplified if more than one.
3676  */
3677  if (operand && IsA(operand, RelabelType))
3678  operand = (Node *) ((RelabelType *) operand)->arg;
3679 
3680  indkey = index->indexkeys[indexcol];
3681  if (indkey != 0)
3682  {
3683  /*
3684  * Simple index column; operand must be a matching Var.
3685  */
3686  if (operand && IsA(operand, Var) &&
3687  index->rel->relid == ((Var *) operand)->varno &&
3688  indkey == ((Var *) operand)->varattno &&
3689  ((Var *) operand)->varnullingrels == NULL)
3690  return true;
3691  }
3692  else
3693  {
3694  /*
3695  * Index expression; find the correct expression. (This search could
3696  * be avoided, at the cost of complicating all the callers of this
3697  * routine; doesn't seem worth it.)
3698  */
3699  ListCell *indexpr_item;
3700  int i;
3701  Node *indexkey;
3702 
3703  indexpr_item = list_head(index->indexprs);
3704  for (i = 0; i < indexcol; i++)
3705  {
3706  if (index->indexkeys[i] == 0)
3707  {
3708  if (indexpr_item == NULL)
3709  elog(ERROR, "wrong number of index expressions");
3710  indexpr_item = lnext(index->indexprs, indexpr_item);
3711  }
3712  }
3713  if (indexpr_item == NULL)
3714  elog(ERROR, "wrong number of index expressions");
3715  indexkey = (Node *) lfirst(indexpr_item);
3716 
3717  /*
3718  * Does it match the operand? Again, strip any relabeling.
3719  */
3720  if (indexkey && IsA(indexkey, RelabelType))
3721  indexkey = (Node *) ((RelabelType *) indexkey)->arg;
3722 
3723  if (equal(indexkey, operand))
3724  return true;
3725  }
3726 
3727  return false;
3728 }

References arg, elog, equal(), ERROR, i, IsA, lfirst, list_head(), and lnext().

Referenced by ec_member_matches_indexcol(), expand_indexqual_rowcompare(), get_actual_variable_range(), match_boolean_index_clause(), match_clause_to_indexcol(), match_clause_to_ordering_op(), match_funcclause_to_indexcol(), match_opclause_to_indexcol(), match_rowcompare_to_indexcol(), match_saopclause_to_indexcol(), and relation_has_unique_index_for().

◆ pathkeys_contained_in()

◆ pathkeys_count_contained_in()

bool pathkeys_count_contained_in ( List keys1,
List keys2,
int *  n_common 
)

Definition at line 556 of file pathkeys.c.

557 {
558  int n = 0;
559  ListCell *key1,
560  *key2;
561 
562  /*
563  * See if we can avoiding looping through both lists. This optimization
564  * gains us several percent in planning time in a worst-case test.
565  */
566  if (keys1 == keys2)
567  {
568  *n_common = list_length(keys1);
569  return true;
570  }
571  else if (keys1 == NIL)
572  {
573  *n_common = 0;
574  return true;
575  }
576  else if (keys2 == NIL)
577  {
578  *n_common = 0;
579  return false;
580  }
581 
582  /*
583  * If both lists are non-empty, iterate through both to find out how many
584  * items are shared.
585  */
586  forboth(key1, keys1, key2, keys2)
587  {
588  PathKey *pathkey1 = (PathKey *) lfirst(key1);
589  PathKey *pathkey2 = (PathKey *) lfirst(key2);
590 
591  if (pathkey1 != pathkey2)
592  {
593  *n_common = n;
594  return false;
595  }
596  n++;
597  }
598 
599  /* If we ended with a null value, then we've processed the whole list. */
600  *n_common = n;
601  return (key1 == NULL);
602 }

References forboth, lfirst, list_length(), and NIL.

Referenced by build_setop_child_paths(), create_final_distinct_paths(), create_one_window_path(), create_ordered_paths(), create_partial_distinct_paths(), create_window_paths(), gather_grouping_paths(), generate_useful_gather_paths(), make_ordered_path(), pathkeys_useful_for_ordering(), and pathkeys_useful_for_setop().

◆ process_equivalence()

bool process_equivalence ( PlannerInfo root,
RestrictInfo **  p_restrictinfo,
JoinDomain jdomain 
)

Definition at line 118 of file equivclass.c.

121 {
122  RestrictInfo *restrictinfo = *p_restrictinfo;
123  Expr *clause = restrictinfo->clause;
124  Oid opno,
125  collation,
126  item1_type,
127  item2_type;
128  Expr *item1;
129  Expr *item2;
130  Relids item1_relids,
131  item2_relids;
132  List *opfamilies;
133  EquivalenceClass *ec1,
134  *ec2;
135  EquivalenceMember *em1,
136  *em2;
137  ListCell *lc1;
138  int ec2_idx;
139 
140  /* Should not already be marked as having generated an eclass */
141  Assert(restrictinfo->left_ec == NULL);
142  Assert(restrictinfo->right_ec == NULL);
143 
144  /* Reject if it is potentially postponable by security considerations */
145  if (restrictinfo->security_level > 0 && !restrictinfo->leakproof)
146  return false;
147 
148  /* Extract info from given clause */
149  Assert(is_opclause(clause));
150  opno = ((OpExpr *) clause)->opno;
151  collation = ((OpExpr *) clause)->inputcollid;
152  item1 = (Expr *) get_leftop(clause);
153  item2 = (Expr *) get_rightop(clause);
154  item1_relids = restrictinfo->left_relids;
155  item2_relids = restrictinfo->right_relids;
156 
157  /*
158  * Ensure both input expressions expose the desired collation (their types
159  * should be OK already); see comments for canonicalize_ec_expression.
160  */
161  item1 = canonicalize_ec_expression(item1,
162  exprType((Node *) item1),
163  collation);
164  item2 = canonicalize_ec_expression(item2,
165  exprType((Node *) item2),
166  collation);
167 
168  /*
169  * Clauses of the form X=X cannot be translated into EquivalenceClasses.
170  * We'd either end up with a single-entry EC, losing the knowledge that
171  * the clause was present at all, or else make an EC with duplicate
172  * entries, causing other issues.
173  */
174  if (equal(item1, item2))
175  {
176  /*
177  * If the operator is strict, then the clause can be treated as just
178  * "X IS NOT NULL". (Since we know we are considering a top-level
179  * qual, we can ignore the difference between FALSE and NULL results.)
180  * It's worth making the conversion because we'll typically get a much
181  * better selectivity estimate than we would for X=X.
182  *
183  * If the operator is not strict, we can't be sure what it will do
184  * with NULLs, so don't attempt to optimize it.
185  */
186  set_opfuncid((OpExpr *) clause);
187  if (func_strict(((OpExpr *) clause)->opfuncid))
188  {
189  NullTest *ntest = makeNode(NullTest);
190 
191  ntest->arg = item1;
192  ntest->nulltesttype = IS_NOT_NULL;
193  ntest->argisrow = false; /* correct even if composite arg */
194  ntest->location = -1;
195 
196  *p_restrictinfo =
198  (Expr *) ntest,
199  restrictinfo->is_pushed_down,
200  restrictinfo->has_clone,
201  restrictinfo->is_clone,
202  restrictinfo->pseudoconstant,
203  restrictinfo->security_level,
204  NULL,
205  restrictinfo->incompatible_relids,
206  restrictinfo->outer_relids);
207  }
208  return false;
209  }
210 
211  /*
212  * We use the declared input types of the operator, not exprType() of the
213  * inputs, as the nominal datatypes for opfamily lookup. This presumes
214  * that btree operators are always registered with amoplefttype and
215  * amoprighttype equal to their declared input types. We will need this
216  * info anyway to build EquivalenceMember nodes, and by extracting it now
217  * we can use type comparisons to short-circuit some equal() tests.
218  */
219  op_input_types(opno, &item1_type, &item2_type);
220 
221  opfamilies = restrictinfo->mergeopfamilies;
222 
223  /*
224  * Sweep through the existing EquivalenceClasses looking for matches to
225  * item1 and item2. These are the possible outcomes:
226  *
227  * 1. We find both in the same EC. The equivalence is already known, so
228  * there's nothing to do.
229  *
230  * 2. We find both in different ECs. Merge the two ECs together.
231  *
232  * 3. We find just one. Add the other to its EC.
233  *
234  * 4. We find neither. Make a new, two-entry EC.
235  *
236  * Note: since all ECs are built through this process or the similar
237  * search in get_eclass_for_sort_expr(), it's impossible that we'd match
238  * an item in more than one existing nonvolatile EC. So it's okay to stop
239  * at the first match.
240  */
241  ec1 = ec2 = NULL;
242  em1 = em2 = NULL;
243  ec2_idx = -1;
244  foreach(lc1, root->eq_classes)
245  {
246  EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
247  ListCell *lc2;
248 
249  /* Never match to a volatile EC */
250  if (cur_ec->ec_has_volatile)
251  continue;
252 
253  /*
254  * The collation has to match; check this first since it's cheaper
255  * than the opfamily comparison.
256  */
257  if (collation != cur_ec->ec_collation)
258  continue;
259 
260  /*
261  * A "match" requires matching sets of btree opfamilies. Use of
262  * equal() for this test has implications discussed in the comments
263  * for get_mergejoin_opfamilies().
264  */
265  if (!equal(opfamilies, cur_ec->ec_opfamilies))
266  continue;
267 
268  foreach(lc2, cur_ec->ec_members)
269  {
270  EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
271 
272  Assert(!cur_em->em_is_child); /* no children yet */
273 
274  /*
275  * Match constants only within the same JoinDomain (see
276  * optimizer/README).
277  */
278  if (cur_em->em_is_const && cur_em->em_jdomain != jdomain)
279  continue;
280 
281  if (!ec1 &&
282  item1_type == cur_em->em_datatype &&
283  equal(item1, cur_em->em_expr))
284  {
285  ec1 = cur_ec;
286  em1 = cur_em;
287  if (ec2)
288  break;
289  }
290 
291  if (!ec2 &&
292  item2_type == cur_em->em_datatype &&
293  equal(item2, cur_em->em_expr))
294  {
295  ec2 = cur_ec;
296  ec2_idx = foreach_current_index(lc1);
297  em2 = cur_em;
298  if (ec1)
299  break;
300  }
301  }
302 
303  if (ec1 && ec2)
304  break;
305  }
306 
307  /* Sweep finished, what did we find? */
308 
309  if (ec1 && ec2)
310  {
311  /* If case 1, nothing to do, except add to sources */
312  if (ec1 == ec2)
313  {
314  ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
315  ec1->ec_min_security = Min(ec1->ec_min_security,
316  restrictinfo->security_level);
317  ec1->ec_max_security = Max(ec1->ec_max_security,
318  restrictinfo->security_level);
319  /* mark the RI as associated with this eclass */
320  restrictinfo->left_ec = ec1;
321  restrictinfo->right_ec = ec1;
322  /* mark the RI as usable with this pair of EMs */
323  restrictinfo->left_em = em1;
324  restrictinfo->right_em = em2;
325  return true;
326  }
327 
328  /*
329  * Case 2: need to merge ec1 and ec2. This should never happen after
330  * the ECs have reached canonical state; otherwise, pathkeys could be
331  * rendered non-canonical by the merge, and relation eclass indexes
332  * would get broken by removal of an eq_classes list entry.
333  */
334  if (root->ec_merging_done)
335  elog(ERROR, "too late to merge equivalence classes");
336 
337  /*
338  * We add ec2's items to ec1, then set ec2's ec_merged link to point
339  * to ec1 and remove ec2 from the eq_classes list. We cannot simply
340  * delete ec2 because that could leave dangling pointers in existing
341  * PathKeys. We leave it behind with a link so that the merged EC can
342  * be found.
343  */
344  ec1->ec_members = list_concat(ec1->ec_members, ec2->ec_members);
345  ec1->ec_sources = list_concat(ec1->ec_sources, ec2->ec_sources);
346  ec1->ec_derives = list_concat(ec1->ec_derives, ec2->ec_derives);
347  ec1->ec_relids = bms_join(ec1->ec_relids, ec2->ec_relids);
348  ec1->ec_has_const |= ec2->ec_has_const;
349  /* can't need to set has_volatile */
350  ec1->ec_min_security = Min(ec1->ec_min_security,
351  ec2->ec_min_security);
352  ec1->ec_max_security = Max(ec1->ec_max_security,
353  ec2->ec_max_security);
354  ec2->ec_merged = ec1;
355  root->eq_classes = list_delete_nth_cell(root->eq_classes, ec2_idx);
356  /* just to avoid debugging confusion w/ dangling pointers: */
357  ec2->ec_members = NIL;
358  ec2->ec_sources = NIL;
359  ec2->ec_derives = NIL;
360  ec2->ec_relids = NULL;
361  ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
362  ec1->ec_min_security = Min(ec1->ec_min_security,
363  restrictinfo->security_level);
364  ec1->ec_max_security = Max(ec1->ec_max_security,
365  restrictinfo->security_level);
366  /* mark the RI as associated with this eclass */
367  restrictinfo->left_ec = ec1;
368  restrictinfo->right_ec = ec1;
369  /* mark the RI as usable with this pair of EMs */
370  restrictinfo->left_em = em1;
371  restrictinfo->right_em = em2;
372  }
373  else if (ec1)
374  {
375  /* Case 3: add item2 to ec1 */
376  em2 = add_eq_member(ec1, item2, item2_relids,
377  jdomain, NULL, item2_type);
378  ec1->ec_sources = lappend(ec1->ec_sources, restrictinfo);
379  ec1->ec_min_security = Min(ec1->ec_min_security,
380  restrictinfo->security_level);
381  ec1->ec_max_security = Max(ec1->ec_max_security,
382  restrictinfo->security_level);
383  /* mark the RI as associated with this eclass */
384  restrictinfo->left_ec = ec1;
385  restrictinfo->right_ec = ec1;
386  /* mark the RI as usable with this pair of EMs */
387  restrictinfo->left_em = em1;
388  restrictinfo->right_em = em2;
389  }
390  else if (ec2)
391  {
392  /* Case 3: add item1 to ec2 */
393  em1 = add_eq_member(ec2, item1, item1_relids,
394  jdomain, NULL, item1_type);
395  ec2->ec_sources = lappend(ec2->ec_sources, restrictinfo);
396  ec2->ec_min_security = Min(ec2->ec_min_security,
397  restrictinfo->security_level);
398  ec2->ec_max_security = Max(ec2->ec_max_security,
399  restrictinfo->security_level);
400  /* mark the RI as associated with this eclass */
401  restrictinfo->left_ec = ec2;
402  restrictinfo->right_ec = ec2;
403  /* mark the RI as usable with this pair of EMs */
404  restrictinfo->left_em = em1;
405  restrictinfo->right_em = em2;
406  }
407  else
408  {
409  /* Case 4: make a new, two-entry EC */
411 
412  ec->ec_opfamilies = opfamilies;
413  ec->ec_collation = collation;
414  ec->ec_members = NIL;
415  ec->ec_sources = list_make1(restrictinfo);
416  ec->ec_derives = NIL;
417  ec->ec_relids = NULL;
418  ec->ec_has_const = false;
419  ec->ec_has_volatile = false;
420  ec->ec_broken = false;
421  ec->ec_sortref = 0;
422  ec->ec_min_security = restrictinfo->security_level;
423  ec->ec_max_security = restrictinfo->security_level;
424  ec->ec_merged = NULL;
425  em1 = add_eq_member(ec, item1, item1_relids,
426  jdomain, NULL, item1_type);
427  em2 = add_eq_member(ec, item2, item2_relids,
428  jdomain, NULL, item2_type);
429 
430  root->eq_classes = lappend(root->eq_classes, ec);
431 
432  /* mark the RI as associated with this eclass */
433  restrictinfo->left_ec = ec;
434  restrictinfo->right_ec = ec;
435  /* mark the RI as usable with this pair of EMs */
436  restrictinfo->left_em = em1;
437  restrictinfo->right_em = em2;
438  }
439 
440  return true;
441 }
List * list_delete_nth_cell(List *list, int n)
Definition: list.c:767
bool func_strict(Oid funcid)
Definition: lsyscache.c:1761
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1862
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:74
@ IS_NOT_NULL
Definition: primnodes.h:1948
RestrictInfo * make_restrictinfo(PlannerInfo *root, Expr *clause, bool is_pushed_down, bool has_clone, bool is_clone, bool pseudoconstant, Index security_level, Relids required_relids, Relids incompatible_relids, Relids outer_relids)
Definition: restrictinfo.c:63
NullTestType nulltesttype
Definition: primnodes.h:1955
ParseLoc location
Definition: primnodes.h:1958
Expr * arg
Definition: primnodes.h:1954
bool is_pushed_down
Definition: pathnodes.h:2567
Index security_level
Definition: pathnodes.h:2586
Relids outer_relids
Definition: pathnodes.h:2601
Relids incompatible_relids
Definition: pathnodes.h:2598
bool has_clone
Definition: pathnodes.h:2576

References add_eq_member(), NullTest::arg, Assert, bms_join(), canonicalize_ec_expression(), RestrictInfo::clause, EquivalenceClass::ec_broken, EquivalenceClass::ec_collation, EquivalenceClass::ec_derives, EquivalenceClass::ec_has_const, EquivalenceClass::ec_has_volatile, EquivalenceClass::ec_max_security, EquivalenceClass::ec_members, EquivalenceClass::ec_merged, EquivalenceClass::ec_min_security, EquivalenceClass::ec_opfamilies, EquivalenceClass::ec_relids, EquivalenceClass::ec_sortref, EquivalenceClass::ec_sources, elog, EquivalenceMember::em_datatype, EquivalenceMember::em_expr, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_jdomain, equal(), ERROR, exprType(), foreach_current_index, func_strict(), get_leftop(), get_rightop(), RestrictInfo::has_clone, RestrictInfo::incompatible_relids, RestrictInfo::is_clone, IS_NOT_NULL, is_opclause(), RestrictInfo::is_pushed_down, lappend(), lfirst, list_concat(), list_delete_nth_cell(), list_make1, NullTest::location, make_restrictinfo(), makeNode, Max, Min, NIL, NullTest::nulltesttype, op_input_types(), RestrictInfo::outer_relids, root, RestrictInfo::security_level, and set_opfuncid().

Referenced by distribute_qual_to_rels(), reconsider_full_join_clause(), and reconsider_outer_join_clause().

◆ reconsider_outer_join_clauses()

void reconsider_outer_join_clauses ( PlannerInfo root)

Definition at line 1997 of file equivclass.c.

1998 {
1999  bool found;
2000  ListCell *cell;
2001 
2002  /* Outer loop repeats until we find no more deductions */
2003  do
2004  {
2005  found = false;
2006 
2007  /* Process the LEFT JOIN clauses */
2008  foreach(cell, root->left_join_clauses)
2009  {
2010  OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2011 
2012  if (reconsider_outer_join_clause(root, ojcinfo, true))
2013  {
2014  RestrictInfo *rinfo = ojcinfo->rinfo;
2015 
2016  found = true;
2017  /* remove it from the list */
2018  root->left_join_clauses =
2019  foreach_delete_current(root->left_join_clauses, cell);
2020  /* throw back a dummy replacement clause (see notes above) */
2021  rinfo = make_restrictinfo(root,
2022  (Expr *) makeBoolConst(true, false),
2023  rinfo->is_pushed_down,
2024  rinfo->has_clone,
2025  rinfo->is_clone,
2026  false, /* pseudoconstant */
2027  0, /* security_level */
2028  rinfo->required_relids,
2029  rinfo->incompatible_relids,
2030  rinfo->outer_relids);
2032  }
2033  }
2034 
2035  /* Process the RIGHT JOIN clauses */
2036  foreach(cell, root->right_join_clauses)
2037  {
2038  OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2039 
2040  if (reconsider_outer_join_clause(root, ojcinfo, false))
2041  {
2042  RestrictInfo *rinfo = ojcinfo->rinfo;
2043 
2044  found = true;
2045  /* remove it from the list */
2046  root->right_join_clauses =
2047  foreach_delete_current(root->right_join_clauses, cell);
2048  /* throw back a dummy replacement clause (see notes above) */
2049  rinfo = make_restrictinfo(root,
2050  (Expr *) makeBoolConst(true, false),
2051  rinfo->is_pushed_down,
2052  rinfo->has_clone,
2053  rinfo->is_clone,
2054  false, /* pseudoconstant */
2055  0, /* security_level */
2056  rinfo->required_relids,
2057  rinfo->incompatible_relids,
2058  rinfo->outer_relids);
2060  }
2061  }
2062 
2063  /* Process the FULL JOIN clauses */
2064  foreach(cell, root->full_join_clauses)
2065  {
2066  OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2067 
2068  if (reconsider_full_join_clause(root, ojcinfo))
2069  {
2070  RestrictInfo *rinfo = ojcinfo->rinfo;
2071 
2072  found = true;
2073  /* remove it from the list */
2074  root->full_join_clauses =
2075  foreach_delete_current(root->full_join_clauses, cell);
2076  /* throw back a dummy replacement clause (see notes above) */
2077  rinfo = make_restrictinfo(root,
2078  (Expr *) makeBoolConst(true, false),
2079  rinfo->is_pushed_down,
2080  rinfo->has_clone,
2081  rinfo->is_clone,
2082  false, /* pseudoconstant */
2083  0, /* security_level */
2084  rinfo->required_relids,
2085  rinfo->incompatible_relids,
2086  rinfo->outer_relids);
2088  }
2089  }
2090  } while (found);
2091 
2092  /* Now, any remaining clauses have to be thrown back */
2093  foreach(cell, root->left_join_clauses)
2094  {
2095  OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2096 
2098  }
2099  foreach(cell, root->right_join_clauses)
2100  {
2101  OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2102 
2104  }
2105  foreach(cell, root->full_join_clauses)
2106  {
2107  OuterJoinClauseInfo *ojcinfo = (OuterJoinClauseInfo *) lfirst(cell);
2108 
2110  }
2111 }
static bool reconsider_outer_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo, bool outer_on_left)
Definition: equivclass.c:2119
static bool reconsider_full_join_clause(PlannerInfo *root, OuterJoinClauseInfo *ojcinfo)
Definition: equivclass.c:2242
void distribute_restrictinfo_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo)
Definition: initsplan.c:2836
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:359
RestrictInfo * rinfo
Definition: pathnodes.h:2923
Relids required_relids
Definition: pathnodes.h:2595

References distribute_restrictinfo_to_rels(), foreach_delete_current, RestrictInfo::has_clone, RestrictInfo::incompatible_relids, RestrictInfo::is_clone, RestrictInfo::is_pushed_down, lfirst, make_restrictinfo(), makeBoolConst(), RestrictInfo::outer_relids, reconsider_full_join_clause(), reconsider_outer_join_clause(), RestrictInfo::required_relids, OuterJoinClauseInfo::rinfo, and root.

Referenced by query_planner().

◆ relation_can_be_sorted_early()

bool relation_can_be_sorted_early ( PlannerInfo root,
RelOptInfo rel,
EquivalenceClass ec,
bool  require_parallel_safe 
)

Definition at line 922 of file equivclass.c.

924 {
925  PathTarget *target = rel->reltarget;
926  EquivalenceMember *em;
927  ListCell *lc;
928 
929  /*
930  * Reject volatile ECs immediately; such sorts must always be postponed.
931  */
932  if (ec->ec_has_volatile)
933  return false;
934 
935  /*
936  * Try to find an EM directly matching some reltarget member.
937  */
938  foreach(lc, target->exprs)
939  {
940  Expr *targetexpr = (Expr *) lfirst(lc);
941 
942  em = find_ec_member_matching_expr(ec, targetexpr, rel->relids);
943  if (!em)
944  continue;
945 
946  /*
947  * Reject expressions involving set-returning functions, as those
948  * can't be computed early either. (Note: this test and the following
949  * one are effectively checking properties of targetexpr, so there's
950  * no point in asking whether some other EC member would be better.)
951  */
952  if (expression_returns_set((Node *) em->em_expr))
953  continue;
954 
955  /*
956  * If requested, reject expressions that are not parallel-safe. We
957  * check this last because it's a rather expensive test.
958  */
959  if (require_parallel_safe &&
960  !is_parallel_safe(root, (Node *) em->em_expr))
961  continue;
962 
963  return true;
964  }
965 
966  /*
967  * Try to find an expression computable from the reltarget.
968  */
969  em = find_computable_ec_member(root, ec, target->exprs, rel->relids,
970  require_parallel_safe);
971  if (!em)
972  return false;
973 
974  /*
975  * Reject expressions involving set-returning functions, as those can't be
976  * computed early either. (There's no point in looking for another EC
977  * member in this case; since SRFs can't appear in WHERE, they cannot
978  * belong to multi-member ECs.)
979  */
980  if (expression_returns_set((Node *) em->em_expr))
981  return false;
982 
983  return true;
984 }
EquivalenceMember * find_ec_member_matching_expr(EquivalenceClass *ec, Expr *expr, Relids relids)
Definition: equivclass.c:760
EquivalenceMember * find_computable_ec_member(PlannerInfo *root, EquivalenceClass *ec, List *exprs, Relids relids, bool require_parallel_safe)
Definition: equivclass.c:825
List * exprs
Definition: pathnodes.h:1533

References EquivalenceClass::ec_has_volatile, EquivalenceMember::em_expr, expression_returns_set(), PathTarget::exprs, find_computable_ec_member(), find_ec_member_matching_expr(), is_parallel_safe(), lfirst, RelOptInfo::relids, RelOptInfo::reltarget, and root.

Referenced by get_useful_pathkeys_for_relation().

◆ relation_has_unique_index_for()

bool relation_has_unique_index_for ( PlannerInfo root,
RelOptInfo rel,
List restrictlist,
List exprlist,
List oprlist 
)

Definition at line 3440 of file indxpath.c.

3443 {
3444  ListCell *ic;
3445 
3446  Assert(list_length(exprlist) == list_length(oprlist));
3447 
3448  /* Short-circuit if no indexes... */
3449  if (rel->indexlist == NIL)
3450  return false;
3451 
3452  /*
3453  * Examine the rel's restriction clauses for usable var = const clauses
3454  * that we can add to the restrictlist.
3455  */
3456  foreach(ic, rel->baserestrictinfo)
3457  {
3458  RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(ic);
3459 
3460  /*
3461  * Note: can_join won't be set for a restriction clause, but
3462  * mergeopfamilies will be if it has a mergejoinable operator and
3463  * doesn't contain volatile functions.
3464  */
3465  if (restrictinfo->mergeopfamilies == NIL)
3466  continue; /* not mergejoinable */
3467 
3468  /*
3469  * The clause certainly doesn't refer to anything but the given rel.
3470  * If either side is pseudoconstant then we can use it.
3471  */
3472  if (bms_is_empty(restrictinfo->left_relids))
3473  {
3474  /* righthand side is inner */
3475  restrictinfo->outer_is_left = true;
3476  }
3477  else if (bms_is_empty(restrictinfo->right_relids))
3478  {
3479  /* lefthand side is inner */
3480  restrictinfo->outer_is_left = false;
3481  }
3482  else
3483  continue;
3484 
3485  /* OK, add to list */
3486  restrictlist = lappend(restrictlist, restrictinfo);
3487  }
3488 
3489  /* Short-circuit the easy case */
3490  if (restrictlist == NIL && exprlist == NIL)
3491  return false;
3492 
3493  /* Examine each index of the relation ... */
3494  foreach(ic, rel->indexlist)
3495  {
3496  IndexOptInfo *ind = (IndexOptInfo *) lfirst(ic);
3497  int c;
3498 
3499  /*
3500  * If the index is not unique, or not immediately enforced, or if it's
3501  * a partial index, it's useless here. We're unable to make use of
3502  * predOK partial unique indexes due to the fact that
3503  * check_index_predicates() also makes use of join predicates to
3504  * determine if the partial index is usable. Here we need proofs that
3505  * hold true before any joins are evaluated.
3506  */
3507  if (!ind->unique || !ind->immediate || ind->indpred != NIL)
3508  continue;
3509 
3510  /*
3511  * Try to find each index column in the lists of conditions. This is
3512  * O(N^2) or worse, but we expect all the lists to be short.
3513  */
3514  for (c = 0; c < ind->nkeycolumns; c++)
3515  {
3516  bool matched = false;
3517  ListCell *lc;
3518  ListCell *lc2;
3519 
3520  foreach(lc, restrictlist)
3521  {
3522  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3523  Node *rexpr;
3524 
3525  /*
3526  * The condition's equality operator must be a member of the
3527  * index opfamily, else it is not asserting the right kind of
3528  * equality behavior for this index. We check this first
3529  * since it's probably cheaper than match_index_to_operand().
3530  */
3531  if (!list_member_oid(rinfo->mergeopfamilies, ind->opfamily[c]))
3532  continue;
3533 
3534  /*
3535  * XXX at some point we may need to check collations here too.
3536  * For the moment we assume all collations reduce to the same
3537  * notion of equality.
3538  */
3539 
3540  /* OK, see if the condition operand matches the index key */
3541  if (rinfo->outer_is_left)
3542  rexpr = get_rightop(rinfo->clause);
3543  else
3544  rexpr = get_leftop(rinfo->clause);
3545 
3546  if (match_index_to_operand(rexpr, c, ind))
3547  {
3548  matched = true; /* column is unique */
3549  break;
3550  }
3551  }
3552 
3553  if (matched)
3554  continue;
3555 
3556  forboth(lc, exprlist, lc2, oprlist)
3557  {
3558  Node *expr = (Node *) lfirst(lc);
3559  Oid opr = lfirst_oid(lc2);
3560 
3561  /* See if the expression matches the index key */
3562  if (!match_index_to_operand(expr, c, ind))
3563  continue;
3564 
3565  /*
3566  * The equality operator must be a member of the index
3567  * opfamily, else it is not asserting the right kind of
3568  * equality behavior for this index. We assume the caller
3569  * determined it is an equality operator, so we don't need to
3570  * check any more tightly than this.
3571  */
3572  if (!op_in_opfamily(opr, ind->opfamily[c]))
3573  continue;
3574 
3575  /*
3576  * XXX at some point we may need to check collations here too.
3577  * For the moment we assume all collations reduce to the same
3578  * notion of equality.
3579  */
3580 
3581  matched = true; /* column is unique */
3582  break;
3583  }
3584 
3585  if (!matched)
3586  break; /* no match; this index doesn't help us */
3587  }
3588 
3589  /* Matched all key columns of this index? */
3590  if (c == ind->nkeycolumns)
3591  return true;
3592  }
3593 
3594  return false;
3595 }
bool match_index_to_operand(Node *operand, int indexcol, IndexOptInfo *index)
Definition: indxpath.c:3665
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:722
bool op_in_opfamily(Oid opno, Oid opfamily)
Definition: lsyscache.c:66
#define lfirst_oid(lc)
Definition: pg_list.h:174
char * c

References Assert, RelOptInfo::baserestrictinfo, bms_is_empty, RestrictInfo::clause, forboth, get_leftop(), get_rightop(), RelOptInfo::indexlist, lappend(), lfirst, lfirst_oid, list_length(), list_member_oid(), match_index_to_operand(), NIL, and op_in_opfamily().

Referenced by create_unique_path(), and rel_is_distinct_for().

◆ select_outer_pathkeys_for_merge()

List* select_outer_pathkeys_for_merge ( PlannerInfo root,
List mergeclauses,
RelOptInfo joinrel 
)

Definition at line 1642 of file pathkeys.c.

1645 {
1646  List *pathkeys = NIL;
1647  int nClauses = list_length(mergeclauses);
1648  EquivalenceClass **ecs;
1649  int *scores;
1650  int necs;
1651  ListCell *lc;
1652  int j;
1653 
1654  /* Might have no mergeclauses */
1655  if (nClauses == 0)
1656  return NIL;
1657 
1658  /*
1659  * Make arrays of the ECs used by the mergeclauses (dropping any
1660  * duplicates) and their "popularity" scores.
1661  */
1662  ecs = (EquivalenceClass **) palloc(nClauses * sizeof(EquivalenceClass *));
1663  scores = (int *) palloc(nClauses * sizeof(int));
1664  necs = 0;
1665 
1666  foreach(lc, mergeclauses)
1667  {
1668  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1669  EquivalenceClass *oeclass;
1670  int score;
1671  ListCell *lc2;
1672 
1673  /* get the outer eclass */
1675 
1676  if (rinfo->outer_is_left)
1677  oeclass = rinfo->left_ec;
1678  else
1679  oeclass = rinfo->right_ec;
1680 
1681  /* reject duplicates */
1682  for (j = 0; j < necs; j++)
1683  {
1684  if (ecs[j] == oeclass)
1685  break;
1686  }
1687  if (j < necs)
1688  continue;
1689 
1690  /* compute score */
1691  score = 0;
1692  foreach(lc2, oeclass->ec_members)
1693  {
1695 
1696  /* Potential future join partner? */
1697  if (!em->em_is_const && !em->em_is_child &&
1698  !bms_overlap(em->em_relids, joinrel->relids))
1699  score++;
1700  }
1701 
1702  ecs[necs] = oeclass;
1703  scores[necs] = score;
1704  necs++;
1705  }
1706 
1707  /*
1708  * Find out if we have all the ECs mentioned in query_pathkeys; if so we
1709  * can generate a sort order that's also useful for final output. If we
1710  * only have a prefix of the query_pathkeys, and that prefix is the entire
1711  * join condition, then it's useful to use the prefix as the pathkeys as
1712  * this increases the chances that an incremental sort will be able to be
1713  * used by the upper planner.
1714  */
1715  if (root->query_pathkeys)
1716  {
1717  int matches = 0;
1718 
1719  foreach(lc, root->query_pathkeys)
1720  {
1721  PathKey *query_pathkey = (PathKey *) lfirst(lc);
1722  EquivalenceClass *query_ec = query_pathkey->pk_eclass;
1723 
1724  for (j = 0; j < necs; j++)
1725  {
1726  if (ecs[j] == query_ec)
1727  break; /* found match */
1728  }
1729  if (j >= necs)
1730  break; /* didn't find match */
1731 
1732  matches++;
1733  }
1734  /* if we got to the end of the list, we have them all */
1735  if (lc == NULL)
1736  {
1737  /* copy query_pathkeys as starting point for our output */
1738  pathkeys = list_copy(root->query_pathkeys);
1739  /* mark their ECs as already-emitted */
1740  foreach(lc, root->query_pathkeys)
1741  {
1742  PathKey *query_pathkey = (PathKey *) lfirst(lc);
1743  EquivalenceClass *query_ec = query_pathkey->pk_eclass;
1744 
1745  for (j = 0; j < necs; j++)
1746  {
1747  if (ecs[j] == query_ec)
1748  {
1749  scores[j] = -1;
1750  break;
1751  }
1752  }
1753  }
1754  }
1755 
1756  /*
1757  * If we didn't match to all of the query_pathkeys, but did match to
1758  * all of the join clauses then we'll make use of these as partially
1759  * sorted input is better than nothing for the upper planner as it may
1760  * lead to incremental sorts instead of full sorts.
1761  */
1762  else if (matches == nClauses)
1763  {
1764  pathkeys = list_copy_head(root->query_pathkeys, matches);
1765 
1766  /* we have all of the join pathkeys, so nothing more to do */
1767  pfree(ecs);
1768  pfree(scores);
1769 
1770  return pathkeys;
1771  }
1772  }
1773 
1774  /*
1775  * Add remaining ECs to the list in popularity order, using a default sort
1776  * ordering. (We could use qsort() here, but the list length is usually
1777  * so small it's not worth it.)
1778  */
1779  for (;;)
1780  {
1781  int best_j;
1782  int best_score;
1783  EquivalenceClass *ec;
1784  PathKey *pathkey;
1785 
1786  best_j = 0;
1787  best_score = scores[0];
1788  for (j = 1; j < necs; j++)
1789  {
1790  if (scores[j] > best_score)
1791  {
1792  best_j = j;
1793  best_score = scores[j];
1794  }
1795  }
1796  if (best_score < 0)
1797  break; /* all done */
1798  ec = ecs[best_j];
1799  scores[best_j] = -1;
1800  pathkey = make_canonical_pathkey(root,
1801  ec,
1804  false);
1805  /* can't be redundant because no duplicate ECs */
1806  Assert(!pathkey_is_redundant(pathkey, pathkeys));
1807  pathkeys = lappend(pathkeys, pathkey);
1808  }
1809 
1810  pfree(ecs);
1811  pfree(scores);
1812 
1813  return pathkeys;
1814 }
List * list_copy_head(const List *oldlist, int len)
Definition: list.c:1593
void pfree(void *pointer)
Definition: mcxt.c:1521
void * palloc(Size size)
Definition: mcxt.c:1317
#define linitial_oid(l)
Definition: pg_list.h:180
#define BTLessStrategyNumber
Definition: stratnum.h:29

References Assert, bms_overlap(), BTLessStrategyNumber, EquivalenceClass::ec_members, EquivalenceClass::ec_opfamilies, EquivalenceMember::em_is_child, EquivalenceMember::em_is_const, EquivalenceMember::em_relids, j, lappend(), lfirst, linitial_oid, list_copy(), list_copy_head(), list_length(), make_canonical_pathkey(), NIL, palloc(), pathkey_is_redundant(), pfree(), RelOptInfo::relids, root, and update_mergeclause_eclasses().

Referenced by sort_inner_and_outer().

◆ standard_join_search()

RelOptInfo* standard_join_search ( PlannerInfo root,
int  levels_needed,
List initial_rels 
)

Definition at line 3418 of file allpaths.c.

3419 {
3420  int lev;
3421  RelOptInfo *rel;
3422 
3423  /*
3424  * This function cannot be invoked recursively within any one planning
3425  * problem, so join_rel_level[] can't be in use already.
3426  */
3427  Assert(root->join_rel_level == NULL);
3428 
3429  /*
3430  * We employ a simple "dynamic programming" algorithm: we first find all
3431  * ways to build joins of two jointree items, then all ways to build joins
3432  * of three items (from two-item joins and single items), then four-item
3433  * joins, and so on until we have considered all ways to join all the
3434  * items into one rel.
3435  *
3436  * root->join_rel_level[j] is a list of all the j-item rels. Initially we
3437  * set root->join_rel_level[1] to represent all the single-jointree-item
3438  * relations.
3439  */
3440  root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
3441 
3442  root->join_rel_level[1] = initial_rels;
3443 
3444  for (lev = 2; lev <= levels_needed; lev++)
3445  {
3446  ListCell *lc;
3447 
3448  /*
3449  * Determine all possible pairs of relations to be joined at this
3450  * level, and build paths for making each one from every available
3451  * pair of lower-level relations.
3452  */
3454 
3455  /*
3456  * Run generate_partitionwise_join_paths() and
3457  * generate_useful_gather_paths() for each just-processed joinrel. We
3458  * could not do this earlier because both regular and partial paths
3459  * can get added to a particular joinrel at multiple times within
3460  * join_search_one_level.
3461  *
3462  * After that, we're done creating paths for the joinrel, so run
3463  * set_cheapest().
3464  */
3465  foreach(lc, root->join_rel_level[lev])
3466  {
3467  rel = (RelOptInfo *) lfirst(lc);
3468 
3469  /* Create paths for partitionwise joins. */
3471 
3472  /*
3473  * Except for the topmost scan/join rel, consider gathering
3474  * partial paths. We'll do the same for the topmost scan/join rel
3475  * once we know the final targetlist (see grouping_planner's and
3476  * its call to apply_scanjoin_target_to_paths).
3477  */
3478  if (!bms_equal(rel->relids, root->all_query_rels))
3479  generate_useful_gather_paths(root, rel, false);
3480 
3481  /* Find and save the cheapest paths for this rel */
3482  set_cheapest(rel);
3483 
3484 #ifdef OPTIMIZER_DEBUG
3485  pprint(rel);
3486 #endif
3487  }
3488  }
3489 
3490  /*
3491  * We should have a single rel at the final level.
3492  */
3493  if (root->join_rel_level[levels_needed] == NIL)
3494  elog(ERROR, "failed to build any %d-way joins", levels_needed);
3495  Assert(list_length(root->join_rel_level[levels_needed]) == 1);
3496 
3497  rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
3498 
3499  root->join_rel_level = NULL;
3500 
3501  return rel;
3502 }
void generate_useful_gather_paths(PlannerInfo *root, RelOptInfo *rel, bool override_rows)
Definition: allpaths.c:3197
void join_search_one_level(PlannerInfo *root, int level)
Definition: joinrels.c:72
void * palloc0(Size size)
Definition: mcxt.c:1347

References Assert, bms_equal(), elog, ERROR, generate_partitionwise_join_paths(), generate_useful_gather_paths(), join_search_one_level(), lfirst, linitial, list_length(), NIL, palloc0(), pprint(), RelOptInfo::relids, root, and set_cheapest().

Referenced by make_rel_from_joinlist().

◆ trim_mergeclauses_for_inner_pathkeys()

List* trim_mergeclauses_for_inner_pathkeys ( PlannerInfo root,
List mergeclauses,
List pathkeys 
)

Definition at line 1941 of file pathkeys.c.

1944 {
1945  List *new_mergeclauses = NIL;
1946  PathKey *pathkey;
1947  EquivalenceClass *pathkey_ec;
1948  bool matched_pathkey;
1949  ListCell *lip;
1950  ListCell *i;
1951 
1952  /* No pathkeys => no mergeclauses (though we don't expect this case) */
1953  if (pathkeys == NIL)
1954  return NIL;
1955  /* Initialize to consider first pathkey */
1956  lip = list_head(pathkeys);
1957  pathkey = (PathKey *) lfirst(lip);
1958  pathkey_ec = pathkey->pk_eclass;
1959  lip = lnext(pathkeys, lip);
1960  matched_pathkey = false;
1961 
1962  /* Scan mergeclauses to see how many we can use */
1963  foreach(i, mergeclauses)
1964  {
1965  RestrictInfo *rinfo = (RestrictInfo *) lfirst(i);
1966  EquivalenceClass *clause_ec;
1967 
1968  /* Assume we needn't do update_mergeclause_eclasses again here */
1969 
1970  /* Check clause's inner-rel EC against current pathkey */
1971  clause_ec = rinfo->outer_is_left ?
1972  rinfo->right_ec : rinfo->left_ec;
1973 
1974  /* If we don't have a match, attempt to advance to next pathkey */
1975  if (clause_ec != pathkey_ec)
1976  {
1977  /* If we had no clauses matching this inner pathkey, must stop */
1978  if (!matched_pathkey)
1979  break;
1980 
1981  /* Advance to next inner pathkey, if any */
1982  if (lip == NULL)
1983  break;
1984  pathkey = (PathKey *) lfirst(lip);
1985  pathkey_ec = pathkey->pk_eclass;
1986  lip = lnext(pathkeys, lip);
1987  matched_pathkey = false;
1988  }
1989 
1990  /* If mergeclause matches current inner pathkey, we can use it */
1991  if (clause_ec == pathkey_ec)
1992  {
1993  new_mergeclauses = lappend(new_mergeclauses, rinfo);
1994  matched_pathkey = true;
1995  }
1996  else
1997  {
1998  /* Else, no hope of adding any more mergeclauses */
1999  break;
2000  }
2001  }
2002 
2003  return new_mergeclauses;
2004 }

References i, lappend(), lfirst, list_head(), lnext(), and NIL.

Referenced by generate_mergejoin_paths().

◆ truncate_useless_pathkeys()

List* truncate_useless_pathkeys ( PlannerInfo root,
RelOptInfo rel,
List pathkeys 
)

Definition at line 2215 of file pathkeys.c.

2218 {
2219  int nuseful;
2220  int nuseful2;
2221 
2222  nuseful = pathkeys_useful_for_merging(root, rel, pathkeys);
2223  nuseful2 = pathkeys_useful_for_ordering(root, pathkeys);
2224  if (nuseful2 > nuseful)
2225  nuseful = nuseful2;
2226  nuseful2 = pathkeys_useful_for_grouping(root, pathkeys);
2227  if (nuseful2 > nuseful)
2228  nuseful = nuseful2;
2229  nuseful2 = pathkeys_useful_for_setop(root, pathkeys);
2230  if (nuseful2 > nuseful)
2231  nuseful = nuseful2;
2232 
2233  /*
2234  * Note: not safe to modify input list destructively, but we can avoid
2235  * copying the list if we're not actually going to change it
2236  */
2237  if (nuseful == 0)
2238  return NIL;
2239  else if (nuseful == list_length(pathkeys))
2240  return pathkeys;
2241  else
2242  return list_copy_head(pathkeys, nuseful);
2243 }
static int pathkeys_useful_for_setop(PlannerInfo *root, List *pathkeys)
Definition: pathkeys.c:2200
static int pathkeys_useful_for_ordering(PlannerInfo *root, List *pathkeys)
Definition: pathkeys.c:2140
static int pathkeys_useful_for_grouping(PlannerInfo *root, List *pathkeys)
Definition: pathkeys.c:2170
static int pathkeys_useful_for_merging(PlannerInfo *root, RelOptInfo *rel, List *pathkeys)
Definition: pathkeys.c:2036

References list_copy_head(), list_length(), NIL, pathkeys_useful_for_grouping(), pathkeys_useful_for_merging(), pathkeys_useful_for_ordering(), pathkeys_useful_for_setop(), and root.

Referenced by build_index_paths(), and build_join_pathkeys().

◆ update_mergeclause_eclasses()

void update_mergeclause_eclasses ( PlannerInfo root,
RestrictInfo restrictinfo 
)

Definition at line 1493 of file pathkeys.c.

1494 {
1495  /* Should be a merge clause ... */
1496  Assert(restrictinfo->mergeopfamilies != NIL);
1497  /* ... with pointers already set */
1498  Assert(restrictinfo->left_ec != NULL);
1499  Assert(restrictinfo->right_ec != NULL);
1500 
1501  /* Chase up to the top as needed */
1502  while (restrictinfo->left_ec->ec_merged)
1503  restrictinfo->left_ec = restrictinfo->left_ec->ec_merged;
1504  while (restrictinfo->right_ec->ec_merged)
1505  restrictinfo->right_ec = restrictinfo->right_ec->ec_merged;
1506 }

References Assert, and NIL.

Referenced by find_mergeclauses_for_outer_pathkeys(), get_useful_ecs_for_relation(), make_inner_pathkeys_for_merge(), pathkeys_useful_for_merging(), select_mergejoin_clauses(), and select_outer_pathkeys_for_merge().

Variable Documentation

◆ enable_geqo

PGDLLIMPORT bool enable_geqo
extern

Definition at line 79 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ enable_group_by_reordering

PGDLLIMPORT bool enable_group_by_reordering
extern

Definition at line 31 of file pathkeys.c.

Referenced by get_useful_group_keys_orderings().

◆ geqo_threshold

PGDLLIMPORT int geqo_threshold
extern

Definition at line 80 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ join_search_hook

PGDLLIMPORT join_search_hook_type join_search_hook
extern

Definition at line 88 of file allpaths.c.

Referenced by make_rel_from_joinlist().

◆ min_parallel_index_scan_size

PGDLLIMPORT int min_parallel_index_scan_size
extern

Definition at line 82 of file allpaths.c.

Referenced by compute_parallel_worker(), and parallel_vacuum_compute_workers().

◆ min_parallel_table_scan_size

PGDLLIMPORT int min_parallel_table_scan_size
extern

Definition at line 81 of file allpaths.c.

Referenced by compute_parallel_worker().

◆ set_join_pathlist_hook

PGDLLIMPORT set_join_pathlist_hook_type set_join_pathlist_hook
extern

Definition at line 31 of file joinpath.c.

Referenced by add_paths_to_joinrel().

◆ set_rel_pathlist_hook

PGDLLIMPORT set_rel_pathlist_hook_type set_rel_pathlist_hook
extern

Definition at line 85 of file allpaths.c.

Referenced by set_rel_pathlist().