/*------------------------------------------------------------------------- * * clausesel.c * Routines to compute clause selectivities * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/optimizer/path/clausesel.c * *------------------------------------------------------------------------- */ #include "postgres.h" /* [PG_CUSTOM: 1C_PLANNER] BEGIN: Применяется 1С-оценка многоколоночной equality/SAOP/join selectivity. */ #include "common/pg_prng.h" #include "utils/array.h" #include "access/genam.h" #include "access/htup_details.h" #include "catalog/pg_am_d.h" #include "commands/vacuum.h" #include "funcapi.h" #include "nodes/makefuncs.h" /* [PG_CUSTOM: 1C_PLANNER] END */ #include "nodes/nodeFuncs.h" #include "optimizer/clauses.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/plancat.h" /* [PG_CUSTOM: 1C_PLANNER] BEGIN: Применяется 1С-оценка многоколоночной equality/SAOP/join selectivity. */ #include "parser/parsetree.h" #include "statistics/statistics.h" #include "utils/fmgroids.h" #include "utils/lsyscache.h" #include "utils/rel.h" #include "utils/selfuncs.h" #include "utils/syscache.h" #include "utils/typcache.h" /* [PG_CUSTOM: 1C_PLANNER] END */ /* * Data structure for accumulating info about possible range-query * clause pairs in clauselist_selectivity. */ typedef struct RangeQueryClause { struct RangeQueryClause *next; /* next in linked list */ Node *var; /* The common variable of the clauses */ bool have_lobound; /* found a low-bound clause yet? */ bool have_hibound; /* found a high-bound clause yet? */ Selectivity lobound; /* Selectivity of a var > something clause */ Selectivity hibound; /* Selectivity of a var < something clause */ } RangeQueryClause; /* [PG_CUSTOM: 1C_PLANNER] BEGIN: Применяется 1С-оценка многоколоночной equality/SAOP/join selectivity. */ typedef struct MulticolumnEqClause { Var *var; Const *constval; int clauseindex; } MulticolumnEqClause; typedef struct MulticolumnEqCandidate { IndexOptInfo *index; int prefixlen; int matches[INDEX_MAX_KEYS]; } MulticolumnEqCandidate; typedef struct MulticolumnSaopClause { Var *var; Const *arrayconst; Oid opno; Oid inputcollid; Oid elemtype; int clauseindex; } MulticolumnSaopClause; typedef struct MulticolumnSaopCandidate { IndexOptInfo *index; int prefixlen; int eqmatches[INDEX_MAX_KEYS]; int saopmatches[INDEX_MAX_KEYS]; int nsaops; } MulticolumnSaopCandidate; typedef struct MulticolumnSaopValues { Datum *values; int nvalues; } MulticolumnSaopValues; typedef struct MulticolumnJoinClause { Var *vars[2]; int clauseindex; } MulticolumnJoinClause; typedef struct MulticolumnJoinCandidate { RelOptInfo *rels[2]; IndexOptInfo *indexes[2]; Oid eqopno; int prefixlen; int matches[INDEX_MAX_KEYS]; } MulticolumnJoinCandidate; typedef struct ExactSelfJoinClause { Node *clause; Var *vars[2]; int clauseindex; } ExactSelfJoinClause; /* [PG_CUSTOM: 1C_PLANNER] END */ static void addRangeClause(RangeQueryClause **rqlist, Node *clause, bool varonleft, bool isLTsel, Selectivity s2); /* [PG_CUSTOM: 1C_PLANNER] BEGIN: Применяется 1С-оценка многоколоночной equality/SAOP/join selectivity. */ static Var *get_multicolumn_eq_var(Node *node); static bool extract_multicolumn_eq_clause(PlannerInfo *root, Node *clause, int varRelid, MulticolumnEqClause *eqclause); static int find_usable_multicolumn_eq_prefix(PlannerInfo *root, RelOptInfo *rel, int varRelid, IndexOptInfo *index, MulticolumnEqClause *eqclauses, int neqclauses, MulticolumnEqCandidate *candidate); static bool find_best_multicolumn_eq_candidate(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset *estimatedclauses, MulticolumnEqCandidate *candidate); static Selectivity estimate_multicolumn_eq_candidate(RelOptInfo *rel, MulticolumnEqClause *eqclauses, MulticolumnEqCandidate *candidate); static bool apply_multicolumn_eq_selectivity(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset **estimatedclauses, Selectivity *s1); static bool extract_multicolumn_saop_clause(PlannerInfo *root, Node *clause, int varRelid, MulticolumnSaopClause *saopclause); static int find_usable_multicolumn_saop_prefix(PlannerInfo *root, RelOptInfo *rel, int varRelid, IndexOptInfo *index, MulticolumnEqClause *eqclauses, int neqclauses, MulticolumnSaopClause *saopclauses, int nsaopclauses, MulticolumnSaopCandidate *candidate); static bool find_best_multicolumn_saop_candidate(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset *estimatedclauses, MulticolumnSaopCandidate *candidate); static Selectivity estimate_multicolumn_saop_candidate(RelOptInfo *rel, MulticolumnEqClause *eqclauses, MulticolumnSaopClause *saopclauses, MulticolumnSaopCandidate *candidate); static Selectivity estimate_multicolumn_saop_variant(VariableStatData *vardata, TypeCacheEntry *typentry, TupleDesc tupdesc, Datum *values, bool *isnull); static Selectivity estimate_multicolumn_saop_exact(VariableStatData *vardata, TypeCacheEntry *typentry, TupleDesc tupdesc, Datum *values, bool *isnull, MulticolumnSaopValues *saopvalues, int *saoppositions, int nsaops, int depth); static void prepare_multicolumn_saop_values(MulticolumnSaopClause *saopclause, MulticolumnSaopValues *saopvalues); static bool apply_multicolumn_saop_selectivity(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset **estimatedclauses, Selectivity *s1); static bool extract_multicolumn_join_clause(PlannerInfo *root, Node *clause, int varRelid, SpecialJoinInfo *sjinfo, MulticolumnJoinClause *joinclause); static bool multicolumn_join_candidate_better(MulticolumnJoinCandidate *candidate, MulticolumnJoinCandidate *bestcandidate); static bool find_best_multicolumn_join_candidate_for_rels(PlannerInfo *root, RelOptInfo *rel0, RelOptInfo *rel1, MulticolumnJoinClause *joinclauses, int njoinclauses, MulticolumnJoinCandidate *candidate); static bool find_best_multicolumn_join_candidate(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, Bitmapset *estimatedclauses, MulticolumnJoinCandidate *candidate); static bool apply_multicolumn_join_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, Bitmapset **estimatedclauses, Selectivity *s1); static bool extract_exact_self_join_clause(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, ExactSelfJoinClause *joinclause); static bool apply_exact_self_join_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, Bitmapset **estimatedclauses, Selectivity *s1, bool use_extended_stats); /* [PG_CUSTOM: 1C_PLANNER] END */ static RelOptInfo *find_single_rel_for_clauses(PlannerInfo *root, List *clauses); /* [PG_CUSTOM: 1C_PLANNER] BEGIN: Применяется 1С-оценка многоколоночной equality/SAOP/join selectivity. */ static inline bool treat_as_join_clause(PlannerInfo *root, Node *clause, RestrictInfo *rinfo, int varRelid, SpecialJoinInfo *sjinfo); /* [PG_CUSTOM: 1C_PLANNER] END */ static Selectivity clauselist_selectivity_or(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats); /**************************************************************************** * ROUTINES TO COMPUTE SELECTIVITIES ****************************************************************************/ /* [PG_CUSTOM: 1C_PLANNER] BEGIN: Применяется 1С-оценка многоколоночной equality/SAOP/join selectivity. */ static Var * get_multicolumn_eq_var(Node *node) { if (IsA(node, RelabelType)) node = (Node *) ((RelabelType *) node)->arg; if (!IsA(node, Var)) return NULL; if (((Var *) node)->varlevelsup != 0 || ((Var *) node)->varattno <= 0) return NULL; return (Var *) node; } static bool extract_multicolumn_eq_clause(PlannerInfo *root, Node *clause, int varRelid, MulticolumnEqClause *eqclause) { RestrictInfo *rinfo = NULL; BoolExpr *boolclause; OpExpr *expr; Node *leftop; Node *rightop; Var *leftvar; Var *rightvar; Var *var; Node *other; bool ok; if (IsA(clause, RestrictInfo)) { rinfo = (RestrictInfo *) clause; if (rinfo->pseudoconstant || rinfo->orclause) return false; clause = (Node *) rinfo->clause; } if (rinfo != NULL && rinfo->num_base_rels != 1) return false; var = get_multicolumn_eq_var(clause); if (var != NULL) { if (var->vartype != BOOLOID) return false; if (rinfo == NULL && NumRelids(root, clause) != 1) return false; if (varRelid != 0 && var->varno != varRelid) return false; eqclause->var = var; eqclause->constval = (Const *) makeBoolConst(true, false); return true; } if (IsA(clause, BoolExpr)) { boolclause = (BoolExpr *) clause; if (boolclause->boolop != NOT_EXPR || list_length(boolclause->args) != 1) return false; var = get_multicolumn_eq_var(linitial(boolclause->args)); if (var == NULL || var->vartype != BOOLOID) return false; if (rinfo == NULL && NumRelids(root, clause) != 1) return false; if (varRelid != 0 && var->varno != varRelid) return false; eqclause->var = var; eqclause->constval = (Const *) makeBoolConst(false, false); return true; } if (!IsA(clause, OpExpr)) return false; expr = (OpExpr *) clause; if (list_length(expr->args) != 2 || get_oprrest(expr->opno) != F_EQSEL) return false; leftop = linitial(expr->args); rightop = lsecond(expr->args); leftvar = get_multicolumn_eq_var(leftop); rightvar = get_multicolumn_eq_var(rightop); if ((leftvar == NULL) == (rightvar == NULL)) return false; if (leftvar != NULL) { var = leftvar; other = rightop; } else { var = rightvar; other = leftop; } if (varRelid != 0 && var->varno != varRelid) return false; if (rinfo != NULL) { ok = (leftvar != NULL) ? is_pseudo_constant_clause_relids(other, rinfo->right_relids) : is_pseudo_constant_clause_relids(other, rinfo->left_relids); } else { ok = (NumRelids(root, clause) == 1) && is_pseudo_constant_clause(other); } if (!ok) return false; other = estimate_expression_value(root, other); if (!IsA(other, Const) || ((Const *) other)->constisnull) return false; eqclause->var = var; eqclause->constval = (Const *) other; return true; } static bool extract_multicolumn_saop_clause(PlannerInfo *root, Node *clause, int varRelid, MulticolumnSaopClause *saopclause) { RestrictInfo *rinfo = NULL; ScalarArrayOpExpr *expr; Node *scalar; Node *arrayexpr; Var *var; Node *folded; Oid elemtype; bool ok; if (IsA(clause, RestrictInfo)) { rinfo = (RestrictInfo *) clause; if (rinfo->pseudoconstant || rinfo->orclause) return false; clause = (Node *) rinfo->clause; } if (!IsA(clause, ScalarArrayOpExpr)) return false; expr = (ScalarArrayOpExpr *) clause; if (!expr->useOr || list_length(expr->args) != 2 || get_oprrest(expr->opno) != F_EQSEL) return false; scalar = linitial(expr->args); arrayexpr = lsecond(expr->args); var = get_multicolumn_eq_var(scalar); if (var == NULL) return false; if (varRelid != 0 && var->varno != varRelid) return false; if (rinfo != NULL) { if (rinfo->num_base_rels != 1) return false; ok = is_pseudo_constant_clause_relids(arrayexpr, rinfo->right_relids); } else { ok = (NumRelids(root, clause) == 1) && is_pseudo_constant_clause(arrayexpr); } if (!ok) return false; folded = estimate_expression_value(root, arrayexpr); if (!IsA(folded, Const) || ((Const *) folded)->constisnull) return false; elemtype = get_base_element_type(((Const *) folded)->consttype); if (!OidIsValid(elemtype)) return false; saopclause->var = var; saopclause->arrayconst = (Const *) folded; saopclause->opno = expr->opno; saopclause->inputcollid = expr->inputcollid; saopclause->elemtype = elemtype; return true; } static int find_usable_multicolumn_eq_prefix(PlannerInfo *root, RelOptInfo *rel, int varRelid, IndexOptInfo *index, MulticolumnEqClause *eqclauses, int neqclauses, MulticolumnEqCandidate *candidate) { int maxprefix = 0; Relation indexrel; Oid reltype; TupleDesc indexdesc; TypeCacheEntry *typentry; int pos; if (index->relam != BTREE_AM_OID || index->nkeycolumns <= 1 || index->indexprs != NIL || index->indpred != NIL || index->hypothetical) return 0; for (pos = 0; pos < index->nkeycolumns; pos++) { int attno = index->indexkeys[pos]; int match = -1; int i; if (attno <= 0) break; for (i = 0; i < neqclauses; i++) { bool already_used = false; int j; if (eqclauses[i].var->varno != rel->relid || eqclauses[i].var->varattno != attno) continue; for (j = 0; j < pos; j++) { if (candidate->matches[j] == i) { already_used = true; break; } } if (already_used) continue; if (match >= 0) goto done_matching; match = i; } if (match < 0) break; candidate->matches[pos] = match; maxprefix++; } done_matching: if (maxprefix < 2) return 0; indexrel = index_open(index->indexoid, AccessShareLock); reltype = indexrel->rd_rel->reltype; indexdesc = RelationGetDescr(indexrel); if (!OidIsValid(reltype)) { index_close(indexrel, AccessShareLock); return 0; } typentry = lookup_type_cache(reltype, TYPECACHE_EQ_OPR); if (!OidIsValid(typentry->eq_opr)) { index_close(indexrel, AccessShareLock); return 0; } for (pos = maxprefix; pos >= 2; pos--) { HeapTuple statsTuple; bool ok = true; int i; statsTuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(index->indexoid), Int16GetDatum(pos), BoolGetDatum(false)); if (!HeapTupleIsValid(statsTuple)) continue; for (i = 0; i < pos; i++) { VariableStatData vardata; Form_pg_attribute attr; examine_variable(root, (Node *) eqclauses[candidate->matches[i]].var, varRelid, &vardata); if (!vardata.acl_ok) ok = false; ReleaseVariableStats(vardata); if (!ok) break; attr = TupleDescAttr(indexdesc, i); if (eqclauses[candidate->matches[i]].constval->consttype != attr->atttypid) { ok = false; break; } } ReleaseSysCache(statsTuple); if (ok) { index_close(indexrel, AccessShareLock); return pos; } } index_close(indexrel, AccessShareLock); return 0; } static int find_usable_multicolumn_saop_prefix(PlannerInfo *root, RelOptInfo *rel, int varRelid, IndexOptInfo *index, MulticolumnEqClause *eqclauses, int neqclauses, MulticolumnSaopClause *saopclauses, int nsaopclauses, MulticolumnSaopCandidate *candidate) { int maxprefix = 0; Relation indexrel; Oid reltype; TupleDesc indexdesc; TypeCacheEntry *typentry; int pos; if (index->relam != BTREE_AM_OID || index->nkeycolumns <= 1 || index->indexprs != NIL || index->indpred != NIL || index->hypothetical) return 0; candidate->nsaops = 0; for (pos = 0; pos < index->nkeycolumns; pos++) { int attno = index->indexkeys[pos]; int neqmatches = 0; int nsaopmatches = 0; int eqmatch = -1; int saopmatch = -1; int i; if (attno <= 0) break; for (i = 0; i < neqclauses; i++) { if (eqclauses[i].var->varno != rel->relid || eqclauses[i].var->varattno != attno) continue; neqmatches++; eqmatch = i; } for (i = 0; i < nsaopclauses; i++) { if (saopclauses[i].var->varno != rel->relid || saopclauses[i].var->varattno != attno) continue; nsaopmatches++; saopmatch = i; } if (neqmatches > 1 || nsaopmatches > 1 || (neqmatches == 1 && nsaopmatches == 1)) return 0; if (eqmatch < 0 && saopmatch < 0) break; if (saopmatch >= 0) { candidate->eqmatches[pos] = -1; candidate->saopmatches[pos] = saopmatch; candidate->nsaops++; } else { candidate->eqmatches[pos] = eqmatch; candidate->saopmatches[pos] = -1; } maxprefix++; } if (maxprefix < 2 || candidate->nsaops < 1) return 0; indexrel = index_open(index->indexoid, AccessShareLock); reltype = indexrel->rd_rel->reltype; indexdesc = RelationGetDescr(indexrel); if (!OidIsValid(reltype)) { index_close(indexrel, AccessShareLock); return 0; } typentry = lookup_type_cache(reltype, TYPECACHE_EQ_OPR); if (!OidIsValid(typentry->eq_opr)) { index_close(indexrel, AccessShareLock); return 0; } for (pos = maxprefix; pos >= 2; pos--) { HeapTuple statsTuple; bool ok = true; bool saw_saop = false; int i; statsTuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(index->indexoid), Int16GetDatum(pos), BoolGetDatum(false)); if (!HeapTupleIsValid(statsTuple)) continue; for (i = 0; i < pos; i++) { VariableStatData vardata; Var *var; Oid consttype; Form_pg_attribute attr; if (candidate->saopmatches[i] >= 0) { var = saopclauses[candidate->saopmatches[i]].var; consttype = saopclauses[candidate->saopmatches[i]].elemtype; saw_saop = true; } else { var = eqclauses[candidate->eqmatches[i]].var; consttype = eqclauses[candidate->eqmatches[i]].constval->consttype; } examine_variable(root, (Node *) var, varRelid, &vardata); if (!vardata.acl_ok) ok = false; ReleaseVariableStats(vardata); if (!ok) break; attr = TupleDescAttr(indexdesc, i); if (consttype != attr->atttypid) { ok = false; break; } } ReleaseSysCache(statsTuple); if (ok && saw_saop) { index_close(indexrel, AccessShareLock); return pos; } } index_close(indexrel, AccessShareLock); return 0; } static bool find_best_multicolumn_eq_candidate(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset *estimatedclauses, MulticolumnEqCandidate *candidate) { MulticolumnEqClause *eqclauses; int neqclauses = 0; ListCell *lc; int listidx = -1; ListCell *ilist; eqclauses = palloc_array(MulticolumnEqClause, list_length(clauses)); foreach(lc, clauses) { MulticolumnEqClause eqclause; listidx++; if (bms_is_member(listidx, estimatedclauses)) continue; if (!extract_multicolumn_eq_clause(root, (Node *) lfirst(lc), varRelid, &eqclause)) continue; eqclause.clauseindex = listidx; eqclauses[neqclauses++] = eqclause; } if (neqclauses < 2) { pfree(eqclauses); return false; } candidate->index = NULL; candidate->prefixlen = 0; foreach(ilist, rel->indexlist) { MulticolumnEqCandidate this_candidate; int prefixlen; MemSet(&this_candidate, -1, sizeof(this_candidate)); this_candidate.index = (IndexOptInfo *) lfirst(ilist); prefixlen = find_usable_multicolumn_eq_prefix(root, rel, varRelid, this_candidate.index, eqclauses, neqclauses, &this_candidate); if (prefixlen < 2) continue; this_candidate.prefixlen = prefixlen; if (candidate->index == NULL || prefixlen > candidate->prefixlen || (prefixlen == candidate->prefixlen && this_candidate.index->nkeycolumns < candidate->index->nkeycolumns)) *candidate = this_candidate; } if (candidate->index == NULL) { pfree(eqclauses); return false; } { int i; for (i = 0; i < candidate->prefixlen; i++) candidate->matches[i] = eqclauses[candidate->matches[i]].clauseindex; } pfree(eqclauses); return true; } static bool find_best_multicolumn_saop_candidate(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset *estimatedclauses, MulticolumnSaopCandidate *candidate) { MulticolumnEqClause *eqclauses; MulticolumnSaopClause *saopclauses; int neqclauses = 0; int nsaopclauses = 0; ListCell *lc; int listidx = -1; ListCell *ilist; eqclauses = palloc_array(MulticolumnEqClause, list_length(clauses)); saopclauses = palloc_array(MulticolumnSaopClause, list_length(clauses)); foreach(lc, clauses) { MulticolumnEqClause eqclause; MulticolumnSaopClause saopclause; listidx++; if (bms_is_member(listidx, estimatedclauses)) continue; if (extract_multicolumn_eq_clause(root, (Node *) lfirst(lc), varRelid, &eqclause)) { eqclause.clauseindex = listidx; eqclauses[neqclauses++] = eqclause; continue; } if (extract_multicolumn_saop_clause(root, (Node *) lfirst(lc), varRelid, &saopclause)) { saopclause.clauseindex = listidx; saopclauses[nsaopclauses++] = saopclause; } } if (nsaopclauses < 1) { pfree(eqclauses); pfree(saopclauses); return false; } candidate->index = NULL; candidate->prefixlen = 0; foreach(ilist, rel->indexlist) { MulticolumnSaopCandidate this_candidate; int prefixlen; MemSet(&this_candidate, -1, sizeof(this_candidate)); this_candidate.index = (IndexOptInfo *) lfirst(ilist); prefixlen = find_usable_multicolumn_saop_prefix(root, rel, varRelid, this_candidate.index, eqclauses, neqclauses, saopclauses, nsaopclauses, &this_candidate); if (prefixlen < 2) continue; this_candidate.prefixlen = prefixlen; if (candidate->index == NULL || prefixlen > candidate->prefixlen || (prefixlen == candidate->prefixlen && this_candidate.index->nkeycolumns < candidate->index->nkeycolumns)) *candidate = this_candidate; } if (candidate->index == NULL) { pfree(eqclauses); pfree(saopclauses); return false; } { int i; for (i = 0; i < candidate->prefixlen; i++) { if (candidate->eqmatches[i] >= 0) candidate->eqmatches[i] = eqclauses[candidate->eqmatches[i]].clauseindex; if (candidate->saopmatches[i] >= 0) candidate->saopmatches[i] = saopclauses[candidate->saopmatches[i]].clauseindex; } } pfree(eqclauses); pfree(saopclauses); return true; } static Selectivity estimate_multicolumn_eq_candidate(RelOptInfo *rel, MulticolumnEqClause *eqclauses, MulticolumnEqCandidate *candidate) { IndexOptInfo *index = candidate->index; Relation indexrel; HeapTuple statsTuple; TupleDesc tupdesc; HeapTuple consttuple; Datum values[INDEX_MAX_KEYS]; bool isnull[INDEX_MAX_KEYS]; VariableStatData vardata; TypeCacheEntry *typentry; Datum constdatum; Selectivity selec; int i; indexrel = index_open(index->indexoid, AccessShareLock); statsTuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(index->indexoid), Int16GetDatum(candidate->prefixlen), BoolGetDatum(false)); if (!HeapTupleIsValid(statsTuple)) elog(ERROR, "missing multicolumn statistics for index %u prefix %d", index->indexoid, candidate->prefixlen); tupdesc = CreateTupleDescTruncatedCopy(RelationGetDescr(indexrel), candidate->prefixlen); for (i = 0; i < candidate->prefixlen; i++) { values[i] = eqclauses[candidate->matches[i]].constval->constvalue; isnull[i] = false; } consttuple = heap_form_tuple(tupdesc, values, isnull); constdatum = HeapTupleGetDatum(consttuple); typentry = lookup_type_cache(indexrel->rd_rel->reltype, TYPECACHE_EQ_OPR); MemSet(&vardata, 0, sizeof(vardata)); vardata.rel = rel; vardata.statsTuple = statsTuple; vardata.freefunc = ReleaseSysCache; vardata.vartype = indexrel->rd_rel->reltype; vardata.atttype = indexrel->rd_rel->reltype; vardata.atttypmod = -1; vardata.isunique = index->unique && (candidate->prefixlen == index->nkeycolumns); vardata.acl_ok = true; selec = var_eq_const(&vardata, typentry->eq_opr, InvalidOid, constdatum, false, true, false); ReleaseVariableStats(vardata); heap_freetuple(consttuple); pfree(tupdesc); index_close(indexrel, AccessShareLock); return selec; } static Selectivity estimate_multicolumn_saop_variant(VariableStatData *vardata, TypeCacheEntry *typentry, TupleDesc tupdesc, Datum *values, bool *isnull) { HeapTuple consttuple; Datum constdatum; Selectivity selec; consttuple = heap_form_tuple(tupdesc, values, isnull); constdatum = HeapTupleGetDatum(consttuple); selec = var_eq_const(vardata, typentry->eq_opr, InvalidOid, constdatum, false, true, false); heap_freetuple(consttuple); return selec; } static Selectivity estimate_multicolumn_saop_exact(VariableStatData *vardata, TypeCacheEntry *typentry, TupleDesc tupdesc, Datum *values, bool *isnull, MulticolumnSaopValues *saopvalues, int *saoppositions, int nsaops, int depth) { Selectivity selec = 0.0; int i; if (depth >= nsaops) return estimate_multicolumn_saop_variant(vardata, typentry, tupdesc, values, isnull); for (i = 0; i < saopvalues[depth].nvalues; i++) { values[saoppositions[depth]] = saopvalues[depth].values[i]; selec += estimate_multicolumn_saop_exact(vardata, typentry, tupdesc, values, isnull, saopvalues, saoppositions, nsaops, depth + 1); } return selec; } static void prepare_multicolumn_saop_values(MulticolumnSaopClause *saopclause, MulticolumnSaopValues *saopvalues) { ArrayType *arrayval; int16 elmlen; bool elmbyval; char elmalign; Datum *elements; bool *nulls; int nelems; Datum *values; FmgrInfo eqproc; int i; saopvalues->values = NULL; saopvalues->nvalues = 0; arrayval = DatumGetArrayTypeP(saopclause->arrayconst->constvalue); get_typlenbyvalalign(saopclause->elemtype, &elmlen, &elmbyval, &elmalign); deconstruct_array(arrayval, saopclause->elemtype, elmlen, elmbyval, elmalign, &elements, &nulls, &nelems); values = palloc_array(Datum, Max(nelems, 1)); fmgr_info(get_opcode(saopclause->opno), &eqproc); for (i = 0; i < nelems; i++) { int j; bool duplicate = false; if (nulls[i]) continue; for (j = 0; j < saopvalues->nvalues; j++) { if (DatumGetBool(FunctionCall2Coll(&eqproc, saopclause->inputcollid, elements[i], values[j]))) { duplicate = true; break; } } if (!duplicate) values[saopvalues->nvalues++] = elements[i]; } pfree(elements); pfree(nulls); if (saopvalues->nvalues == 0) { pfree(values); return; } saopvalues->values = values; } static Selectivity estimate_multicolumn_saop_candidate(RelOptInfo *rel, MulticolumnEqClause *eqclauses, MulticolumnSaopClause *saopclauses, MulticolumnSaopCandidate *candidate) { IndexOptInfo *index = candidate->index; Relation indexrel; HeapTuple statsTuple; TupleDesc tupdesc; VariableStatData vardata; TypeCacheEntry *typentry; Datum values[INDEX_MAX_KEYS]; bool isnull[INDEX_MAX_KEYS]; MulticolumnSaopValues saopvalues[INDEX_MAX_KEYS]; int saoppositions[INDEX_MAX_KEYS]; Selectivity selec = 0.0; long double total_variants = 1.0; int nsaops = 0; int sample_limit; int i; indexrel = index_open(index->indexoid, AccessShareLock); statsTuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(index->indexoid), Int16GetDatum(candidate->prefixlen), BoolGetDatum(false)); if (!HeapTupleIsValid(statsTuple)) elog(ERROR, "missing multicolumn statistics for index %u prefix %d", index->indexoid, candidate->prefixlen); tupdesc = CreateTupleDescTruncatedCopy(RelationGetDescr(indexrel), candidate->prefixlen); for (i = 0; i < candidate->prefixlen; i++) { isnull[i] = false; if (candidate->eqmatches[i] >= 0) values[i] = eqclauses[candidate->eqmatches[i]].constval->constvalue; } typentry = lookup_type_cache(indexrel->rd_rel->reltype, TYPECACHE_EQ_OPR); MemSet(&vardata, 0, sizeof(vardata)); vardata.rel = rel; vardata.statsTuple = statsTuple; vardata.freefunc = ReleaseSysCache; vardata.vartype = indexrel->rd_rel->reltype; vardata.atttype = indexrel->rd_rel->reltype; vardata.atttypmod = -1; vardata.isunique = index->unique && (candidate->prefixlen == index->nkeycolumns); vardata.acl_ok = true; for (i = 0; i < candidate->prefixlen; i++) { if (candidate->saopmatches[i] < 0) continue; saoppositions[nsaops] = i; prepare_multicolumn_saop_values(&saopclauses[candidate->saopmatches[i]], &saopvalues[nsaops]); if (saopvalues[nsaops].nvalues == 0) { int j; for (j = 0; j < nsaops; j++) pfree(saopvalues[j].values); ReleaseVariableStats(vardata); pfree(tupdesc); index_close(indexrel, AccessShareLock); return 0.0; } total_variants *= saopvalues[nsaops].nvalues; nsaops++; } sample_limit = Max(1, default_statistics_target / 4); if (total_variants <= sample_limit) selec = estimate_multicolumn_saop_exact(&vardata, typentry, tupdesc, values, isnull, saopvalues, saoppositions, nsaops, 0); else { for (i = 0; i < sample_limit; i++) { int j; for (j = 0; j < nsaops; j++) { int valueidx; valueidx = (int) pg_prng_uint64_range(&pg_global_prng_state, 0, saopvalues[j].nvalues - 1); values[saoppositions[j]] = saopvalues[j].values[valueidx]; } selec += estimate_multicolumn_saop_variant(&vardata, typentry, tupdesc, values, isnull); } selec = selec * total_variants / sample_limit; } ReleaseVariableStats(vardata); for (i = 0; i < nsaops; i++) pfree(saopvalues[i].values); pfree(tupdesc); index_close(indexrel, AccessShareLock); CLAMP_PROBABILITY(selec); return selec; } static bool apply_multicolumn_eq_selectivity(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset **estimatedclauses, Selectivity *s1) { MulticolumnEqCandidate candidate; MulticolumnEqClause *eqclauses; int neqclauses = 0; ListCell *lc; int listidx = -1; int i; if (!find_best_multicolumn_eq_candidate(root, rel, clauses, varRelid, *estimatedclauses, &candidate)) return false; eqclauses = palloc_array(MulticolumnEqClause, list_length(clauses)); foreach(lc, clauses) { MulticolumnEqClause eqclause; listidx++; if (bms_is_member(listidx, *estimatedclauses)) continue; if (!extract_multicolumn_eq_clause(root, (Node *) lfirst(lc), varRelid, &eqclause)) continue; eqclause.clauseindex = listidx; eqclauses[neqclauses++] = eqclause; } for (i = 0; i < candidate.prefixlen; i++) { int j; for (j = 0; j < neqclauses; j++) { if (eqclauses[j].clauseindex == candidate.matches[i]) { candidate.matches[i] = j; break; } } Assert(j < neqclauses); } *s1 *= estimate_multicolumn_eq_candidate(rel, eqclauses, &candidate); for (i = 0; i < candidate.prefixlen; i++) *estimatedclauses = bms_add_member(*estimatedclauses, eqclauses[candidate.matches[i]].clauseindex); pfree(eqclauses); return true; } static bool apply_multicolumn_saop_selectivity(PlannerInfo *root, RelOptInfo *rel, List *clauses, int varRelid, Bitmapset **estimatedclauses, Selectivity *s1) { MulticolumnSaopCandidate candidate; MulticolumnEqClause *eqclauses; MulticolumnSaopClause *saopclauses; int neqclauses = 0; int nsaopclauses = 0; ListCell *lc; int listidx = -1; int i; MemSet(&candidate, 0, sizeof(candidate)); if (!find_best_multicolumn_saop_candidate(root, rel, clauses, varRelid, *estimatedclauses, &candidate)) return false; eqclauses = palloc_array(MulticolumnEqClause, list_length(clauses)); saopclauses = palloc_array(MulticolumnSaopClause, list_length(clauses)); foreach(lc, clauses) { MulticolumnEqClause eqclause; MulticolumnSaopClause saopclause; listidx++; if (bms_is_member(listidx, *estimatedclauses)) continue; if (extract_multicolumn_eq_clause(root, (Node *) lfirst(lc), varRelid, &eqclause)) { eqclause.clauseindex = listidx; eqclauses[neqclauses++] = eqclause; continue; } if (extract_multicolumn_saop_clause(root, (Node *) lfirst(lc), varRelid, &saopclause)) { saopclause.clauseindex = listidx; saopclauses[nsaopclauses++] = saopclause; } } for (i = 0; i < candidate.prefixlen; i++) { int j; if (candidate.saopmatches[i] >= 0) { for (j = 0; j < nsaopclauses; j++) { if (saopclauses[j].clauseindex == candidate.saopmatches[i]) { candidate.saopmatches[i] = j; break; } } Assert(j < nsaopclauses); } else { for (j = 0; j < neqclauses; j++) { if (eqclauses[j].clauseindex == candidate.eqmatches[i]) { candidate.eqmatches[i] = j; break; } } Assert(j < neqclauses); } } *s1 *= estimate_multicolumn_saop_candidate(rel, eqclauses, saopclauses, &candidate); for (i = 0; i < candidate.prefixlen; i++) { if (candidate.saopmatches[i] >= 0) *estimatedclauses = bms_add_member(*estimatedclauses, saopclauses[candidate.saopmatches[i]].clauseindex); else *estimatedclauses = bms_add_member(*estimatedclauses, eqclauses[candidate.eqmatches[i]].clauseindex); } pfree(eqclauses); pfree(saopclauses); return true; } static bool extract_multicolumn_join_clause(PlannerInfo *root, Node *clause, int varRelid, SpecialJoinInfo *sjinfo, MulticolumnJoinClause *joinclause) { RestrictInfo *rinfo = NULL; OpExpr *expr; Var *leftvar; Var *rightvar; RelOptInfo *leftrel; RelOptInfo *rightrel; Var *side0; Var *side1; if (IsA(clause, RestrictInfo)) { rinfo = (RestrictInfo *) clause; if (rinfo->pseudoconstant || rinfo->orclause) return false; clause = (Node *) rinfo->clause; } if (!IsA(clause, OpExpr)) return false; expr = (OpExpr *) clause; if (list_length(expr->args) != 2 || get_oprjoin(expr->opno) != F_EQJOINSEL || !treat_as_join_clause(root, clause, rinfo, varRelid, sjinfo)) return false; leftvar = get_multicolumn_eq_var(linitial(expr->args)); rightvar = get_multicolumn_eq_var(lsecond(expr->args)); if (leftvar == NULL || rightvar == NULL) return false; if (leftvar->varno == rightvar->varno || leftvar->vartype != rightvar->vartype) return false; leftrel = find_base_rel(root, leftvar->varno); rightrel = find_base_rel(root, rightvar->varno); if (leftrel == NULL || rightrel == NULL || leftrel->rtekind != RTE_RELATION || rightrel->rtekind != RTE_RELATION) return false; if (leftvar->varno < rightvar->varno) { side0 = leftvar; side1 = rightvar; } else { side0 = rightvar; side1 = leftvar; } joinclause->vars[0] = side0; joinclause->vars[1] = side1; return true; } static int find_multicolumn_join_prefix_for_indexes(PlannerInfo *root, MulticolumnJoinClause *joinclauses, int njoinclauses, IndexOptInfo *index0, IndexOptInfo *index1, int matches[INDEX_MAX_KEYS], Oid *eqopno) { int maxprefix = 0; Relation indexrel0; Relation indexrel1; Oid reltype0; Oid reltype1; TupleDesc indexdesc0; TupleDesc indexdesc1; TypeCacheEntry *typentry0; TypeCacheEntry *typentry1; Oid common_eqop; int pos; if (index0->relam != BTREE_AM_OID || index1->relam != BTREE_AM_OID || index0->nkeycolumns <= 1 || index1->nkeycolumns <= 1 || index0->indexprs != NIL || index1->indexprs != NIL || index0->indpred != NIL || index1->indpred != NIL || index0->hypothetical || index1->hypothetical) return 0; for (pos = 0; pos < Min(index0->nkeycolumns, index1->nkeycolumns); pos++) { int attno0 = index0->indexkeys[pos]; int attno1 = index1->indexkeys[pos]; int match = -1; int i; if (attno0 <= 0 || attno1 <= 0) break; for (i = 0; i < njoinclauses; i++) { if (joinclauses[i].vars[0]->varattno != attno0 || joinclauses[i].vars[1]->varattno != attno1) continue; if (match >= 0) return 0; match = i; } if (match < 0) break; matches[pos] = match; maxprefix++; } if (maxprefix < 2) return 0; indexrel0 = index_open(index0->indexoid, AccessShareLock); indexrel1 = index_open(index1->indexoid, AccessShareLock); reltype0 = indexrel0->rd_rel->reltype; reltype1 = indexrel1->rd_rel->reltype; indexdesc0 = RelationGetDescr(indexrel0); indexdesc1 = RelationGetDescr(indexrel1); if (!OidIsValid(reltype0) || !OidIsValid(reltype1)) { index_close(indexrel0, AccessShareLock); index_close(indexrel1, AccessShareLock); return 0; } typentry0 = lookup_type_cache(reltype0, TYPECACHE_EQ_OPR); typentry1 = lookup_type_cache(reltype1, TYPECACHE_EQ_OPR); if (!OidIsValid(typentry0->eq_opr) || !OidIsValid(typentry1->eq_opr) || typentry0->eq_opr != typentry1->eq_opr) { index_close(indexrel0, AccessShareLock); index_close(indexrel1, AccessShareLock); return 0; } common_eqop = typentry0->eq_opr; for (pos = maxprefix; pos >= 2; pos--) { HeapTuple statsTuple0; HeapTuple statsTuple1; bool ok = true; int i; statsTuple0 = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(index0->indexoid), Int16GetDatum(pos), BoolGetDatum(false)); if (!HeapTupleIsValid(statsTuple0)) continue; statsTuple1 = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(index1->indexoid), Int16GetDatum(pos), BoolGetDatum(false)); if (!HeapTupleIsValid(statsTuple1)) { ReleaseSysCache(statsTuple0); continue; } for (i = 0; i < pos; i++) { VariableStatData vardata; Form_pg_attribute attr0; Form_pg_attribute attr1; Oid jointype; examine_variable(root, (Node *) joinclauses[matches[i]].vars[0], 0, &vardata); if (!vardata.acl_ok) ok = false; ReleaseVariableStats(vardata); if (!ok) break; examine_variable(root, (Node *) joinclauses[matches[i]].vars[1], 0, &vardata); if (!vardata.acl_ok) ok = false; ReleaseVariableStats(vardata); if (!ok) break; attr0 = TupleDescAttr(indexdesc0, i); attr1 = TupleDescAttr(indexdesc1, i); jointype = joinclauses[matches[i]].vars[0]->vartype; if (attr0->atttypid != attr1->atttypid || attr0->atttypid != jointype || attr1->atttypid != joinclauses[matches[i]].vars[1]->vartype) { ok = false; break; } } ReleaseSysCache(statsTuple0); ReleaseSysCache(statsTuple1); if (ok) { *eqopno = common_eqop; index_close(indexrel0, AccessShareLock); index_close(indexrel1, AccessShareLock); return pos; } } index_close(indexrel0, AccessShareLock); index_close(indexrel1, AccessShareLock); return 0; } static bool multicolumn_join_candidate_better(MulticolumnJoinCandidate *candidate, MulticolumnJoinCandidate *bestcandidate) { if (bestcandidate->indexes[0] == NULL) return true; if (candidate->prefixlen != bestcandidate->prefixlen) return (candidate->prefixlen > bestcandidate->prefixlen); if (candidate->indexes[0]->nkeycolumns + candidate->indexes[1]->nkeycolumns != bestcandidate->indexes[0]->nkeycolumns + bestcandidate->indexes[1]->nkeycolumns) { return (candidate->indexes[0]->nkeycolumns + candidate->indexes[1]->nkeycolumns < bestcandidate->indexes[0]->nkeycolumns + bestcandidate->indexes[1]->nkeycolumns); } if (candidate->indexes[0]->indexoid != bestcandidate->indexes[0]->indexoid) return (candidate->indexes[0]->indexoid < bestcandidate->indexes[0]->indexoid); return (candidate->indexes[1]->indexoid < bestcandidate->indexes[1]->indexoid); } static bool find_best_multicolumn_join_candidate_for_rels(PlannerInfo *root, RelOptInfo *rel0, RelOptInfo *rel1, MulticolumnJoinClause *joinclauses, int njoinclauses, MulticolumnJoinCandidate *candidate) { ListCell *ilc0; MemSet(candidate, 0, sizeof(*candidate)); candidate->rels[0] = rel0; candidate->rels[1] = rel1; foreach(ilc0, rel0->indexlist) { IndexOptInfo *index0 = (IndexOptInfo *) lfirst(ilc0); ListCell *ilc1; foreach(ilc1, rel1->indexlist) { IndexOptInfo *index1 = (IndexOptInfo *) lfirst(ilc1); int matches[INDEX_MAX_KEYS]; Oid eqopno = InvalidOid; int prefixlen; MemSet(matches, -1, sizeof(matches)); prefixlen = find_multicolumn_join_prefix_for_indexes(root, joinclauses, njoinclauses, index0, index1, matches, &eqopno); if (prefixlen < 2) continue; if (candidate->indexes[0] == NULL) { int i; candidate->indexes[0] = index0; candidate->indexes[1] = index1; candidate->eqopno = eqopno; candidate->prefixlen = prefixlen; for (i = 0; i < prefixlen; i++) candidate->matches[i] = joinclauses[matches[i]].clauseindex; } else { MulticolumnJoinCandidate newcandidate; int i; MemSet(&newcandidate, 0, sizeof(newcandidate)); newcandidate.rels[0] = rel0; newcandidate.rels[1] = rel1; newcandidate.indexes[0] = index0; newcandidate.indexes[1] = index1; newcandidate.eqopno = eqopno; newcandidate.prefixlen = prefixlen; for (i = 0; i < prefixlen; i++) newcandidate.matches[i] = joinclauses[matches[i]].clauseindex; if (multicolumn_join_candidate_better(&newcandidate, candidate)) *candidate = newcandidate; } } } return (candidate->indexes[0] != NULL); } static Selectivity estimate_multicolumn_join_candidate(MulticolumnJoinCandidate *candidate) { Relation indexrel0; Relation indexrel1; HeapTuple statsTuple0; HeapTuple statsTuple1; VariableStatData vardata0; VariableStatData vardata1; Selectivity selec; indexrel0 = index_open(candidate->indexes[0]->indexoid, AccessShareLock); indexrel1 = index_open(candidate->indexes[1]->indexoid, AccessShareLock); statsTuple0 = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(candidate->indexes[0]->indexoid), Int16GetDatum(candidate->prefixlen), BoolGetDatum(false)); statsTuple1 = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(candidate->indexes[1]->indexoid), Int16GetDatum(candidate->prefixlen), BoolGetDatum(false)); if (!HeapTupleIsValid(statsTuple0) || !HeapTupleIsValid(statsTuple1)) elog(ERROR, "missing multicolumn join statistics for prefix %d", candidate->prefixlen); MemSet(&vardata0, 0, sizeof(vardata0)); vardata0.rel = candidate->rels[0]; vardata0.statsTuple = statsTuple0; vardata0.freefunc = ReleaseSysCache; vardata0.vartype = indexrel0->rd_rel->reltype; vardata0.atttype = indexrel0->rd_rel->reltype; vardata0.atttypmod = -1; vardata0.isunique = candidate->indexes[0]->unique && (candidate->prefixlen == candidate->indexes[0]->nkeycolumns); vardata0.acl_ok = true; MemSet(&vardata1, 0, sizeof(vardata1)); vardata1.rel = candidate->rels[1]; vardata1.statsTuple = statsTuple1; vardata1.freefunc = ReleaseSysCache; vardata1.vartype = indexrel1->rd_rel->reltype; vardata1.atttype = indexrel1->rd_rel->reltype; vardata1.atttypmod = -1; vardata1.isunique = candidate->indexes[1]->unique && (candidate->prefixlen == candidate->indexes[1]->nkeycolumns); vardata1.acl_ok = true; selec = eqjoin_selectivity_from_stats(candidate->eqopno, InvalidOid, &vardata0, &vardata1); ReleaseVariableStats(vardata0); ReleaseVariableStats(vardata1); index_close(indexrel0, AccessShareLock); index_close(indexrel1, AccessShareLock); return selec; } static bool find_best_multicolumn_join_candidate(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, Bitmapset *estimatedclauses, MulticolumnJoinCandidate *candidate) { MulticolumnJoinClause *joinclauses; MulticolumnJoinClause *pairclauses; int njoinclauses = 0; ListCell *lc; int listidx = -1; int i; if (varRelid != 0 || sjinfo == NULL || jointype != JOIN_INNER) return false; joinclauses = palloc_array(MulticolumnJoinClause, list_length(clauses)); pairclauses = palloc_array(MulticolumnJoinClause, list_length(clauses)); foreach(lc, clauses) { MulticolumnJoinClause joinclause; listidx++; if (bms_is_member(listidx, estimatedclauses)) continue; if (!extract_multicolumn_join_clause(root, (Node *) lfirst(lc), varRelid, sjinfo, &joinclause)) continue; joinclause.clauseindex = listidx; joinclauses[njoinclauses++] = joinclause; } MemSet(candidate, 0, sizeof(*candidate)); for (i = 0; i < njoinclauses; i++) { int side0varno = joinclauses[i].vars[0]->varno; int side1varno = joinclauses[i].vars[1]->varno; RelOptInfo *rel0; RelOptInfo *rel1; MulticolumnJoinCandidate paircandidate; int npairclauses = 0; int j; bool seenpair = false; for (j = 0; j < i; j++) { if (joinclauses[j].vars[0]->varno == side0varno && joinclauses[j].vars[1]->varno == side1varno) { seenpair = true; break; } } if (seenpair) continue; for (j = i; j < njoinclauses; j++) { if (joinclauses[j].vars[0]->varno != side0varno || joinclauses[j].vars[1]->varno != side1varno) continue; pairclauses[npairclauses++] = joinclauses[j]; } if (npairclauses < 2) continue; rel0 = find_base_rel(root, side0varno); rel1 = find_base_rel(root, side1varno); if (rel0 == NULL || rel1 == NULL || rel0->rtekind != RTE_RELATION || rel1->rtekind != RTE_RELATION) continue; if (!find_best_multicolumn_join_candidate_for_rels(root, rel0, rel1, pairclauses, npairclauses, &paircandidate)) continue; if (multicolumn_join_candidate_better(&paircandidate, candidate)) *candidate = paircandidate; } pfree(pairclauses); pfree(joinclauses); return (candidate->indexes[0] != NULL); } static bool apply_multicolumn_join_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, Bitmapset **estimatedclauses, Selectivity *s1) { MulticolumnJoinCandidate candidate; int i; if (!find_best_multicolumn_join_candidate(root, clauses, varRelid, jointype, sjinfo, *estimatedclauses, &candidate)) return false; *s1 *= estimate_multicolumn_join_candidate(&candidate); for (i = 0; i < candidate.prefixlen; i++) *estimatedclauses = bms_add_member(*estimatedclauses, candidate.matches[i]); return true; } static bool extract_exact_self_join_clause(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, ExactSelfJoinClause *joinclause) { RestrictInfo *rinfo = NULL; OpExpr *expr; Var *leftvar; Var *rightvar; RangeTblEntry *leftrte; RangeTblEntry *rightrte; if (varRelid != 0 || jointype != JOIN_INNER || sjinfo == NULL) return false; if (IsA(clause, RestrictInfo)) { rinfo = (RestrictInfo *) clause; if (rinfo->pseudoconstant || rinfo->orclause) return false; clause = (Node *) rinfo->clause; } if (!IsA(clause, OpExpr)) return false; expr = (OpExpr *) clause; if (list_length(expr->args) != 2 || get_oprjoin(expr->opno) != F_EQJOINSEL || get_oprrest(expr->opno) != F_EQSEL) return false; leftvar = get_multicolumn_eq_var(linitial(expr->args)); rightvar = get_multicolumn_eq_var(lsecond(expr->args)); if (leftvar == NULL || rightvar == NULL || leftvar->varno == rightvar->varno || leftvar->vartype != rightvar->vartype || leftvar->varattno != rightvar->varattno) return false; leftrte = planner_rt_fetch(leftvar->varno, root); rightrte = planner_rt_fetch(rightvar->varno, root); if (leftrte->rtekind != RTE_RELATION || rightrte->rtekind != RTE_RELATION || leftrte->relid != rightrte->relid) return false; joinclause->clause = clause; if (leftvar->varno < rightvar->varno) { joinclause->vars[0] = leftvar; joinclause->vars[1] = rightvar; } else { joinclause->vars[0] = rightvar; joinclause->vars[1] = leftvar; } return true; } static bool apply_exact_self_join_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, Bitmapset **estimatedclauses, Selectivity *s1, bool use_extended_stats) { ExactSelfJoinClause *joinclauses; int njoinclauses = 0; ListCell *lc; int listidx = -1; int i; bool applied = false; if (!use_extended_stats || varRelid != 0 || jointype != JOIN_INNER || sjinfo == NULL) return false; joinclauses = palloc_array(ExactSelfJoinClause, list_length(clauses)); foreach(lc, clauses) { ExactSelfJoinClause joinclause; listidx++; if (bms_is_member(listidx, *estimatedclauses)) continue; if (!extract_exact_self_join_clause(root, (Node *) lfirst(lc), varRelid, jointype, sjinfo, &joinclause)) continue; joinclause.clauseindex = listidx; joinclauses[njoinclauses++] = joinclause; } for (i = 0; i < njoinclauses; i++) { Selectivity group_sel = 1.0; int groupcount = 0; int j; if (bms_is_member(joinclauses[i].clauseindex, *estimatedclauses)) continue; for (j = i; j < njoinclauses; j++) { Selectivity clause_sel; if (joinclauses[i].vars[0]->varno != joinclauses[j].vars[0]->varno || joinclauses[i].vars[1]->varno != joinclauses[j].vars[1]->varno) continue; clause_sel = clause_selectivity_ext(root, joinclauses[j].clause, varRelid, jointype, sjinfo, use_extended_stats); group_sel = Min(group_sel, clause_sel); groupcount++; } if (groupcount < 2) continue; *s1 *= group_sel; for (j = i; j < njoinclauses; j++) { if (joinclauses[i].vars[0]->varno != joinclauses[j].vars[0]->varno || joinclauses[i].vars[1]->varno != joinclauses[j].vars[1]->varno) continue; *estimatedclauses = bms_add_member(*estimatedclauses, joinclauses[j].clauseindex); } applied = true; } pfree(joinclauses); return applied; } /* [PG_CUSTOM: 1C_PLANNER] END */ /* * clauselist_selectivity - * Compute the selectivity of an implicitly-ANDed list of boolean * expression clauses. The list can be empty, in which case 1.0 * must be returned. List elements may be either RestrictInfos * or bare expression clauses --- the former is preferred since * it allows caching of results. * * See clause_selectivity() for the meaning of the additional parameters. * * The basic approach is to apply extended statistics first, on as many * clauses as possible, in order to capture cross-column dependencies etc. * The remaining clauses are then estimated by taking the product of their * selectivities, but that's only right if they have independent * probabilities, and in reality they are often NOT independent even if they * only refer to a single column. So, we want to be smarter where we can. * * We also recognize "range queries", such as "x > 34 AND x < 42". Clauses * are recognized as possible range query components if they are restriction * opclauses whose operators have scalarltsel or a related function as their * restriction selectivity estimator. We pair up clauses of this form that * refer to the same variable. An unpairable clause of this kind is simply * multiplied into the selectivity product in the normal way. But when we * find a pair, we know that the selectivities represent the relative * positions of the low and high bounds within the column's range, so instead * of figuring the selectivity as hisel * losel, we can figure it as hisel + * losel - 1. (To visualize this, see that hisel is the fraction of the range * below the high bound, while losel is the fraction above the low bound; so * hisel can be interpreted directly as a 0..1 value but we need to convert * losel to 1-losel before interpreting it as a value. Then the available * range is 1-losel to hisel. However, this calculation double-excludes * nulls, so really we need hisel + losel + null_frac - 1.) * * If either selectivity is exactly DEFAULT_INEQ_SEL, we forget this equation * and instead use DEFAULT_RANGE_INEQ_SEL. The same applies if the equation * yields an impossible (negative) result. * * A free side-effect is that we can recognize redundant inequalities such * as "x < 4 AND x < 5"; only the tighter constraint will be counted. * * Of course this is all very dependent on the behavior of the inequality * selectivity functions; perhaps some day we can generalize the approach. */ Selectivity clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo) { return clauselist_selectivity_ext(root, clauses, varRelid, jointype, sjinfo, true); } /* * clauselist_selectivity_ext - * Extended version of clauselist_selectivity(). If "use_extended_stats" * is false, all extended statistics will be ignored, and only per-column * statistics will be used. */ Selectivity clauselist_selectivity_ext(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats) { Selectivity s1 = 1.0; RelOptInfo *rel; Bitmapset *estimatedclauses = NULL; RangeQueryClause *rqlist = NULL; ListCell *l; int listidx; /* * If there's exactly one clause, just go directly to * clause_selectivity_ext(). None of what we might do below is relevant. */ if (list_length(clauses) == 1) return clause_selectivity_ext(root, (Node *) linitial(clauses), varRelid, jointype, sjinfo, use_extended_stats); /* * Determine if these clauses reference a single relation. If so, and if * it has extended statistics, try to apply those. */ rel = find_single_rel_for_clauses(root, clauses); if (use_extended_stats && rel && rel->rtekind == RTE_RELATION && rel->statlist != NIL) { /* * Estimate as many clauses as possible using extended statistics. * * 'estimatedclauses' is populated with the 0-based list position * index of clauses estimated here, and that should be ignored below. */ s1 = statext_clauselist_selectivity(root, clauses, varRelid, jointype, sjinfo, rel, &estimatedclauses, false); } /* [PG_CUSTOM: 1C_PLANNER] BEGIN: Применяется 1С-оценка многоколоночной equality/SAOP/join selectivity. */ if (use_extended_stats && rel && rel->rtekind == RTE_RELATION) { while (apply_multicolumn_saop_selectivity(root, rel, clauses, varRelid, &estimatedclauses, &s1)) /* keep consuming disjoint multicolumn equality/SAOP groups */ ; while (apply_multicolumn_eq_selectivity(root, rel, clauses, varRelid, &estimatedclauses, &s1)) /* keep consuming disjoint multicolumn equality groups */ ; } if (use_extended_stats && varRelid == 0 && sjinfo != NULL && jointype == JOIN_INNER) while (apply_multicolumn_join_selectivity(root, clauses, varRelid, jointype, sjinfo, &estimatedclauses, &s1)) /* keep consuming disjoint multicolumn join groups */ ; (void) apply_exact_self_join_selectivity(root, clauses, varRelid, jointype, sjinfo, &estimatedclauses, &s1, use_extended_stats); /* [PG_CUSTOM: 1C_PLANNER] END */ /* * Apply normal selectivity estimates for remaining clauses. We'll be * careful to skip any clauses which were already estimated above. * * Anything that doesn't look like a potential rangequery clause gets * multiplied into s1 and forgotten. Anything that does gets inserted into * an rqlist entry. */ listidx = -1; foreach(l, clauses) { Node *clause = (Node *) lfirst(l); RestrictInfo *rinfo; Selectivity s2; listidx++; /* * Skip this clause if it's already been estimated by some other * statistics above. */ if (bms_is_member(listidx, estimatedclauses)) continue; /* Compute the selectivity of this clause in isolation */ s2 = clause_selectivity_ext(root, clause, varRelid, jointype, sjinfo, use_extended_stats); /* * Check for being passed a RestrictInfo. * * If it's a pseudoconstant RestrictInfo, then s2 is either 1.0 or * 0.0; just use that rather than looking for range pairs. */ if (IsA(clause, RestrictInfo)) { rinfo = (RestrictInfo *) clause; if (rinfo->pseudoconstant) { s1 = s1 * s2; continue; } clause = (Node *) rinfo->clause; } else rinfo = NULL; /* * See if it looks like a restriction clause with a pseudoconstant on * one side. (Anything more complicated than that might not behave in * the simple way we are expecting.) Most of the tests here can be * done more efficiently with rinfo than without. */ if (is_opclause(clause) && list_length(((OpExpr *) clause)->args) == 2) { OpExpr *expr = (OpExpr *) clause; bool varonleft = true; bool ok; if (rinfo) { ok = (rinfo->num_base_rels == 1) && (is_pseudo_constant_clause_relids(lsecond(expr->args), rinfo->right_relids) || (varonleft = false, is_pseudo_constant_clause_relids(linitial(expr->args), rinfo->left_relids))); } else { ok = (NumRelids(root, clause) == 1) && (is_pseudo_constant_clause(lsecond(expr->args)) || (varonleft = false, is_pseudo_constant_clause(linitial(expr->args)))); } if (ok) { /* * If it's not a "<"/"<="/">"/">=" operator, just merge the * selectivity in generically. But if it's the right oprrest, * add the clause to rqlist for later processing. */ switch (get_oprrest(expr->opno)) { case F_SCALARLTSEL: case F_SCALARLESEL: addRangeClause(&rqlist, clause, varonleft, true, s2); break; case F_SCALARGTSEL: case F_SCALARGESEL: addRangeClause(&rqlist, clause, varonleft, false, s2); break; default: /* Just merge the selectivity in generically */ s1 = s1 * s2; break; } continue; /* drop to loop bottom */ } } /* Not the right form, so treat it generically. */ s1 = s1 * s2; } /* * Now scan the rangequery pair list. */ while (rqlist != NULL) { RangeQueryClause *rqnext; if (rqlist->have_lobound && rqlist->have_hibound) { /* Successfully matched a pair of range clauses */ Selectivity s2; /* * Exact equality to the default value probably means the * selectivity function punted. This is not airtight but should * be good enough. */ if (rqlist->hibound == DEFAULT_INEQ_SEL || rqlist->lobound == DEFAULT_INEQ_SEL) { s2 = DEFAULT_RANGE_INEQ_SEL; } else { s2 = rqlist->hibound + rqlist->lobound - 1.0; /* Adjust for double-exclusion of NULLs */ s2 += nulltestsel(root, IS_NULL, rqlist->var, varRelid, jointype, sjinfo); /* * A zero or slightly negative s2 should be converted into a * small positive value; we probably are dealing with a very * tight range and got a bogus result due to roundoff errors. * However, if s2 is very negative, then we probably have * default selectivity estimates on one or both sides of the * range that we failed to recognize above for some reason. */ if (s2 <= 0.0) { if (s2 < -0.01) { /* * No data available --- use a default estimate that * is small, but not real small. */ s2 = DEFAULT_RANGE_INEQ_SEL; } else { /* * It's just roundoff error; use a small positive * value */ s2 = 1.0e-10; } } } /* Merge in the selectivity of the pair of clauses */ s1 *= s2; } else { /* Only found one of a pair, merge it in generically */ if (rqlist->have_lobound) s1 *= rqlist->lobound; else s1 *= rqlist->hibound; } /* release storage and advance */ rqnext = rqlist->next; pfree(rqlist); rqlist = rqnext; } return s1; } /* * clauselist_selectivity_or - * Compute the selectivity of an implicitly-ORed list of boolean * expression clauses. The list can be empty, in which case 0.0 * must be returned. List elements may be either RestrictInfos * or bare expression clauses --- the former is preferred since * it allows caching of results. * * See clause_selectivity() for the meaning of the additional parameters. * * The basic approach is to apply extended statistics first, on as many * clauses as possible, in order to capture cross-column dependencies etc. * The remaining clauses are then estimated as if they were independent. */ static Selectivity clauselist_selectivity_or(PlannerInfo *root, List *clauses, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats) { Selectivity s1 = 0.0; RelOptInfo *rel; Bitmapset *estimatedclauses = NULL; ListCell *lc; int listidx; /* * Determine if these clauses reference a single relation. If so, and if * it has extended statistics, try to apply those. */ rel = find_single_rel_for_clauses(root, clauses); if (use_extended_stats && rel && rel->rtekind == RTE_RELATION && rel->statlist != NIL) { /* * Estimate as many clauses as possible using extended statistics. * * 'estimatedclauses' is populated with the 0-based list position * index of clauses estimated here, and that should be ignored below. */ s1 = statext_clauselist_selectivity(root, clauses, varRelid, jointype, sjinfo, rel, &estimatedclauses, true); } /* * Estimate the remaining clauses as if they were independent. * * Selectivities for an OR clause are computed as s1+s2 - s1*s2 to account * for the probable overlap of selected tuple sets. * * XXX is this too conservative? */ listidx = -1; foreach(lc, clauses) { Selectivity s2; listidx++; /* * Skip this clause if it's already been estimated by some other * statistics above. */ if (bms_is_member(listidx, estimatedclauses)) continue; s2 = clause_selectivity_ext(root, (Node *) lfirst(lc), varRelid, jointype, sjinfo, use_extended_stats); s1 = s1 + s2 - s1 * s2; } return s1; } /* * addRangeClause --- add a new range clause for clauselist_selectivity * * Here is where we try to match up pairs of range-query clauses */ static void addRangeClause(RangeQueryClause **rqlist, Node *clause, bool varonleft, bool isLTsel, Selectivity s2) { RangeQueryClause *rqelem; Node *var; bool is_lobound; if (varonleft) { var = get_leftop((Expr *) clause); is_lobound = !isLTsel; /* x < something is high bound */ } else { var = get_rightop((Expr *) clause); is_lobound = isLTsel; /* something < x is low bound */ } for (rqelem = *rqlist; rqelem; rqelem = rqelem->next) { /* * We use full equal() here because the "var" might be a function of * one or more attributes of the same relation... */ if (!equal(var, rqelem->var)) continue; /* Found the right group to put this clause in */ if (is_lobound) { if (!rqelem->have_lobound) { rqelem->have_lobound = true; rqelem->lobound = s2; } else { /*------ * We have found two similar clauses, such as * x < y AND x <= z. * Keep only the more restrictive one. *------ */ if (rqelem->lobound > s2) rqelem->lobound = s2; } } else { if (!rqelem->have_hibound) { rqelem->have_hibound = true; rqelem->hibound = s2; } else { /*------ * We have found two similar clauses, such as * x > y AND x >= z. * Keep only the more restrictive one. *------ */ if (rqelem->hibound > s2) rqelem->hibound = s2; } } return; } /* No matching var found, so make a new clause-pair data structure */ rqelem = palloc_object(RangeQueryClause); rqelem->var = var; if (is_lobound) { rqelem->have_lobound = true; rqelem->have_hibound = false; rqelem->lobound = s2; } else { rqelem->have_lobound = false; rqelem->have_hibound = true; rqelem->hibound = s2; } rqelem->next = *rqlist; *rqlist = rqelem; } /* * find_single_rel_for_clauses * Examine each clause in 'clauses' and determine if all clauses * reference only a single relation. If so return that relation, * otherwise return NULL. */ static RelOptInfo * find_single_rel_for_clauses(PlannerInfo *root, List *clauses) { int lastrelid = 0; ListCell *l; foreach(l, clauses) { RestrictInfo *rinfo = (RestrictInfo *) lfirst(l); int relid; /* * If we have a list of bare clauses rather than RestrictInfos, we * could pull out their relids the hard way with pull_varnos(). * However, currently the extended-stats machinery won't do anything * with non-RestrictInfo clauses anyway, so there's no point in * spending extra cycles; just fail if that's what we have. * * An exception to that rule is if we have a bare BoolExpr AND clause. * We treat this as a special case because the restrictinfo machinery * doesn't build RestrictInfos on top of AND clauses. */ if (is_andclause(rinfo)) { RelOptInfo *rel; rel = find_single_rel_for_clauses(root, ((BoolExpr *) rinfo)->args); if (rel == NULL) return NULL; if (lastrelid == 0) lastrelid = rel->relid; else if (rel->relid != lastrelid) return NULL; continue; } if (!IsA(rinfo, RestrictInfo)) return NULL; if (bms_is_empty(rinfo->clause_relids)) continue; /* we can ignore variable-free clauses */ if (!bms_get_singleton_member(rinfo->clause_relids, &relid)) return NULL; /* multiple relations in this clause */ if (lastrelid == 0) lastrelid = relid; /* first clause referencing a relation */ else if (relid != lastrelid) return NULL; /* relation not same as last one */ } if (lastrelid != 0) return find_base_rel(root, lastrelid); return NULL; /* no clauses */ } /* * treat_as_join_clause - * Decide whether an operator clause is to be handled by the * restriction or join estimator. Subroutine for clause_selectivity(). */ static inline bool treat_as_join_clause(PlannerInfo *root, Node *clause, RestrictInfo *rinfo, int varRelid, SpecialJoinInfo *sjinfo) { if (varRelid != 0) { /* * Caller is forcing restriction mode (eg, because we are examining an * inner indexscan qual). */ return false; } else if (sjinfo == NULL) { /* * It must be a restriction clause, since it's being evaluated at a * scan node. */ return false; } else { /* * Otherwise, it's a join if there's more than one base relation used. * We can optimize this calculation if an rinfo was passed. * * XXX Since we know the clause is being evaluated at a join, the * only way it could be single-relation is if it was delayed by outer * joins. We intentionally count only baserels here, not OJs that * might be present in rinfo->clause_relids, so that we direct such * cases to the restriction qual estimators not join estimators. * Eventually some notice should be taken of the possibility of * injected nulls, but we'll likely want to do that in the restriction * estimators rather than starting to treat such cases as join quals. */ if (rinfo) return (rinfo->num_base_rels > 1); else return (NumRelids(root, clause) > 1); } } /* * clause_selectivity - * Compute the selectivity of a general boolean expression clause. * * The clause can be either a RestrictInfo or a plain expression. If it's * a RestrictInfo, we try to cache the selectivity for possible re-use, * so passing RestrictInfos is preferred. * * varRelid is either 0 or a rangetable index. * * When varRelid is not 0, only variables belonging to that relation are * considered in computing selectivity; other vars are treated as constants * of unknown values. This is appropriate for estimating the selectivity of * a join clause that is being used as a restriction clause in a scan of a * nestloop join's inner relation --- varRelid should then be the ID of the * inner relation. * * When varRelid is 0, all variables are treated as variables. This * is appropriate for ordinary join clauses and restriction clauses. * * jointype is the join type, if the clause is a join clause. Pass JOIN_INNER * if the clause isn't a join clause. * * sjinfo is NULL for a non-join clause, otherwise it provides additional * context information about the join being performed. There are some * special cases: * 1. For a special (not INNER) join, sjinfo is always a member of * root->join_info_list. * 2. For an INNER join, sjinfo is just a transient struct, and only the * relids and jointype fields in it can be trusted. * It is possible for jointype to be different from sjinfo->jointype. * This indicates we are considering a variant join: either with * the LHS and RHS switched, or with one input unique-ified. * * Note: when passing nonzero varRelid, it's normally appropriate to set * jointype == JOIN_INNER, sjinfo == NULL, even if the clause is really a * join clause; because we aren't treating it as a join clause. */ Selectivity clause_selectivity(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo) { return clause_selectivity_ext(root, clause, varRelid, jointype, sjinfo, true); } /* * clause_selectivity_ext - * Extended version of clause_selectivity(). If "use_extended_stats" is * false, all extended statistics will be ignored, and only per-column * statistics will be used. */ Selectivity clause_selectivity_ext(PlannerInfo *root, Node *clause, int varRelid, JoinType jointype, SpecialJoinInfo *sjinfo, bool use_extended_stats) { Selectivity s1 = 0.5; /* default for any unhandled clause type */ RestrictInfo *rinfo = NULL; bool cacheable = false; if (clause == NULL) /* can this still happen? */ return s1; if (IsA(clause, RestrictInfo)) { rinfo = (RestrictInfo *) clause; /* * If the clause is marked pseudoconstant, then it will be used as a * gating qual and should not affect selectivity estimates; hence * return 1.0. The only exception is that a constant FALSE may be * taken as having selectivity 0.0, since it will surely mean no rows * out of the plan. This case is simple enough that we need not * bother caching the result. */ if (rinfo->pseudoconstant) { if (!IsA(rinfo->clause, Const)) return (Selectivity) 1.0; } /* * If the clause is marked redundant, always return 1.0. */ if (rinfo->norm_selec > 1) return (Selectivity) 1.0; /* * If possible, cache the result of the selectivity calculation for * the clause. We can cache if varRelid is zero or the clause * contains only vars of that relid --- otherwise varRelid will affect * the result, so mustn't cache. Outer join quals might be examined * with either their join's actual jointype or JOIN_INNER, so we need * two cache variables to remember both cases. Note: we assume the * result won't change if we are switching the input relations or * considering a unique-ified case, so we only need one cache variable * for all non-JOIN_INNER cases. */ if (varRelid == 0 || rinfo->num_base_rels == 0 || (rinfo->num_base_rels == 1 && bms_is_member(varRelid, rinfo->clause_relids))) { /* Cacheable --- do we already have the result? */ if (jointype == JOIN_INNER) { if (rinfo->norm_selec >= 0) return rinfo->norm_selec; } else { if (rinfo->outer_selec >= 0) return rinfo->outer_selec; } cacheable = true; } /* * Proceed with examination of contained clause. If the clause is an * OR-clause, we want to look at the variant with sub-RestrictInfos, * so that per-subclause selectivities can be cached. */ if (rinfo->orclause) clause = (Node *) rinfo->orclause; else clause = (Node *) rinfo->clause; } if (IsA(clause, Var)) { Var *var = (Var *) clause; /* * We probably shouldn't ever see an uplevel Var here, but if we do, * return the default selectivity... */ if (var->varlevelsup == 0 && (varRelid == 0 || varRelid == (int) var->varno)) { /* Use the restriction selectivity function for a bool Var */ s1 = boolvarsel(root, (Node *) var, varRelid); } } else if (IsA(clause, Const)) { /* bool constant is pretty easy... */ Const *con = (Const *) clause; s1 = con->constisnull ? 0.0 : DatumGetBool(con->constvalue) ? 1.0 : 0.0; } else if (IsA(clause, Param)) { /* see if we can replace the Param */ Node *subst = estimate_expression_value(root, clause); if (IsA(subst, Const)) { /* bool constant is pretty easy... */ Const *con = (Const *) subst; s1 = con->constisnull ? 0.0 : DatumGetBool(con->constvalue) ? 1.0 : 0.0; } else { /* XXX any way to do better than default? */ } } else if (is_notclause(clause)) { /* inverse of the selectivity of the underlying clause */ s1 = 1.0 - clause_selectivity_ext(root, (Node *) get_notclausearg((Expr *) clause), varRelid, jointype, sjinfo, use_extended_stats); } else if (is_andclause(clause)) { /* share code with clauselist_selectivity() */ s1 = clauselist_selectivity_ext(root, ((BoolExpr *) clause)->args, varRelid, jointype, sjinfo, use_extended_stats); } else if (is_orclause(clause)) { /* * Almost the same thing as clauselist_selectivity, but with the * clauses connected by OR. */ s1 = clauselist_selectivity_or(root, ((BoolExpr *) clause)->args, varRelid, jointype, sjinfo, use_extended_stats); } else if (is_opclause(clause) || IsA(clause, DistinctExpr)) { OpExpr *opclause = (OpExpr *) clause; Oid opno = opclause->opno; if (treat_as_join_clause(root, clause, rinfo, varRelid, sjinfo)) { /* Estimate selectivity for a join clause. */ s1 = join_selectivity(root, opno, opclause->args, opclause->inputcollid, jointype, sjinfo); } else { /* Estimate selectivity for a restriction clause. */ s1 = restriction_selectivity(root, opno, opclause->args, opclause->inputcollid, varRelid); } /* * DistinctExpr has the same representation as OpExpr, but the * contained operator is "=" not "<>", so we must negate the result. * This estimation method doesn't give the right behavior for nulls, * but it's better than doing nothing. */ if (IsA(clause, DistinctExpr)) s1 = 1.0 - s1; } else if (is_funcclause(clause)) { FuncExpr *funcclause = (FuncExpr *) clause; /* Try to get an estimate from the support function, if any */ s1 = function_selectivity(root, funcclause->funcid, funcclause->args, funcclause->inputcollid, treat_as_join_clause(root, clause, rinfo, varRelid, sjinfo), varRelid, jointype, sjinfo); /* If no support, fall back on boolvarsel */ if (s1 < 0) s1 = boolvarsel(root, clause, varRelid); } else if (IsA(clause, ScalarArrayOpExpr)) { /* Use node specific selectivity calculation function */ s1 = scalararraysel(root, (ScalarArrayOpExpr *) clause, treat_as_join_clause(root, clause, rinfo, varRelid, sjinfo), varRelid, jointype, sjinfo); } else if (IsA(clause, RowCompareExpr)) { /* Use node specific selectivity calculation function */ s1 = rowcomparesel(root, (RowCompareExpr *) clause, varRelid, jointype, sjinfo); } else if (IsA(clause, NullTest)) { /* Use node specific selectivity calculation function */ s1 = nulltestsel(root, ((NullTest *) clause)->nulltesttype, (Node *) ((NullTest *) clause)->arg, varRelid, jointype, sjinfo); } else if (IsA(clause, BooleanTest)) { /* Use node specific selectivity calculation function */ s1 = booltestsel(root, ((BooleanTest *) clause)->booltesttype, (Node *) ((BooleanTest *) clause)->arg, varRelid, jointype, sjinfo); } else if (IsA(clause, CurrentOfExpr)) { /* CURRENT OF selects at most one row of its table */ CurrentOfExpr *cexpr = (CurrentOfExpr *) clause; RelOptInfo *crel = find_base_rel(root, cexpr->cvarno); if (crel->tuples > 0) s1 = 1.0 / crel->tuples; } else if (IsA(clause, RelabelType)) { /* Not sure this case is needed, but it can't hurt */ s1 = clause_selectivity_ext(root, (Node *) ((RelabelType *) clause)->arg, varRelid, jointype, sjinfo, use_extended_stats); } else if (IsA(clause, CoerceToDomain)) { /* Not sure this case is needed, but it can't hurt */ s1 = clause_selectivity_ext(root, (Node *) ((CoerceToDomain *) clause)->arg, varRelid, jointype, sjinfo, use_extended_stats); } else { /* * For anything else, see if we can consider it as a boolean variable. * This only works if it's an immutable expression in Vars of a single * relation; but there's no point in us checking that here because * boolvarsel() will do it internally, and return a suitable default * selectivity if not. */ s1 = boolvarsel(root, clause, varRelid); } /* Cache the result if possible */ if (cacheable) { if (jointype == JOIN_INNER) rinfo->norm_selec = s1; else rinfo->outer_selec = s1; } #ifdef SELECTIVITY_DEBUG elog(DEBUG4, "clause_selectivity: s1 %f", s1); #endif /* SELECTIVITY_DEBUG */ return s1; }