/*------------------------------------------------------------------------- * * appendorpath.c * Support ordered Append paths for selected OR clauses. * * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/backend/optimizer/path/appendorpath.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/skey.h" #include "catalog/pg_am.h" #include "optimizer/clauses.h" #include "optimizer/cost.h" #include "optimizer/optimizer.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" #include "optimizer/planmain.h" #include "optimizer/restrictinfo.h" #include "utils/lsyscache.h" typedef struct CKey { RestrictInfo *rinfo; int n; OpExpr *normalizedexpr; Var *var; Node *value; Oid opfamily; int strategy; uint8 strategy_mask; } CKey; typedef struct ExExpr { OpExpr *expr; Oid opfamily; Oid lefttype; Oid righttype; int strategy; int attno; } ExExpr; typedef struct OrderedIndexPath { IndexPath *path; List *prepared_quals; } OrderedIndexPath; #define BTMASK(x) (1 << (x)) #define IS_LESS(a) \ ((a) == BTLessStrategyNumber || (a) == BTLessEqualStrategyNumber) #define IS_GREATER(a) \ ((a) == BTGreaterStrategyNumber || (a) == BTGreaterEqualStrategyNumber) #define IS_ONE_DIRECTION(a,b) \ ((IS_LESS(a) && IS_LESS(b)) || (IS_GREATER(a) && IS_GREATER(b))) static List *extract_index_clause_exprs(List *indexclauses); static bool check_same_index(Path *path, Oid *indexoid); static CKey *transform_to_ckey(IndexOptInfo *index, RestrictInfo *rinfo, int indexcol); static List *get_index_quals(IndexPath *path, int branchno); static List *find_all_quals(BitmapOrPath *path, int *branchcount); static bool equal_ckey_args(CKey *a, CKey *b); static int count_matching_entries(List *all_quals, CKey *candidate); static List *find_common_quals(BitmapOrPath *path); static RestrictInfo *union_operation(PlannerInfo *root, CKey *key); static bool derived_qual_already_implied(RelOptInfo *rel, RestrictInfo *derived); static List *optimizable_indexclauses(List *indexclauses); static Path *cleanup_nested_quals(BitmapOrPath *path); static bool paths_overlap(List *paths, ListCell *check); static List *contained_quals(List *nested, List *paths, ListCell *check); static List *prepare_quals(IndexOptInfo *index, List *indexclauses); static int simple_cmp_expr(ExExpr *a, ExExpr *b); static int cmp_eq_expr(ExExpr *a, ExExpr *b); static int cmp_neg_cmp(ExExpr *a, ExExpr *b); static int cmp_expr(ExExpr *a, ExExpr *b); static int cmp_column_quals(List *a, List *b, int attno); static int cmp_index_path_ex(const void *a, const void *b); static List *sort_index_scans(List *ipaths); static double estimate_branch_rows(PlannerInfo *root, RelOptInfo *rel, List *indexclauses); static IndexPath *create_or_branch_index_path(PlannerInfo *root, RelOptInfo *rel, IndexPath *source, List *pathkeys, ScanDirection scandir); static List *build_or_branch_index_paths(PlannerInfo *root, RelOptInfo *rel, List *source_paths, List *pathkeys, ScanDirection scandir); static void add_append_path_candidate(PlannerInfo *root, RelOptInfo *rel, List *index_paths, List *pathkeys); static IndexOptInfo *sorting_index = NULL; static bool ordering_unknown = false; static List * extract_index_clause_exprs(List *indexclauses) { List *exprs = NIL; ListCell *lc; foreach(lc, indexclauses) { IndexClause *iclause = lfirst_node(IndexClause, lc); ListCell *qc; foreach(qc, iclause->indexquals) exprs = lappend(exprs, lfirst_node(RestrictInfo, qc)->clause); } return exprs; } static bool check_same_index(Path *path, Oid *indexoid) { List *subpaths; ListCell *lc; if (IsA(path, IndexPath)) { IndexPath *ipath = castNode(IndexPath, path); if (ipath->indexinfo->relam != BTREE_AM_OID) return false; if (!OidIsValid(*indexoid)) *indexoid = ipath->indexinfo->indexoid; else if (*indexoid != ipath->indexinfo->indexoid) return false; return true; } else if (IsA(path, BitmapOrPath)) subpaths = castNode(BitmapOrPath, path)->bitmapquals; else if (IsA(path, BitmapAndPath)) subpaths = castNode(BitmapAndPath, path)->bitmapquals; else return false; foreach(lc, subpaths) { if (!check_same_index((Path *) lfirst(lc), indexoid)) return false; } return true; } static CKey * transform_to_ckey(IndexOptInfo *index, RestrictInfo *rinfo, int indexcol) { CKey *key; OpExpr *expr; if (!IsA(rinfo->clause, OpExpr)) return NULL; expr = castNode(OpExpr, rinfo->clause); if (contain_mutable_functions((Node *) expr) || list_length(expr->args) != 2) return NULL; key = palloc(sizeof(CKey)); key->rinfo = rinfo; key->normalizedexpr = copyObject(expr); if (!bms_equal(rinfo->left_relids, index->rel->relids)) CommuteOpExpr(key->normalizedexpr); key->var = castNode(Var, fix_indexqual_operand(linitial(key->normalizedexpr->args), index, indexcol)); key->opfamily = index->opfamily[key->var->varattno - 1]; key->var->varattno = key->var->varattnosyn; key->value = lsecond(key->normalizedexpr->args); key->strategy = get_op_opfamily_strategy(key->normalizedexpr->opno, key->opfamily); if (key->strategy == InvalidStrategy) return NULL; key->strategy_mask = BTMASK(key->strategy); return key; } static List * get_index_quals(IndexPath *path, int branchno) { List *quals = NIL; ListCell *lc; foreach(lc, path->indexclauses) { IndexClause *iclause = lfirst_node(IndexClause, lc); ListCell *qc; foreach(qc, iclause->indexquals) { CKey *key; key = transform_to_ckey(path->indexinfo, lfirst_node(RestrictInfo, qc), iclause->indexcol); if (key != NULL) { key->n = branchno; quals = lappend(quals, key); } } } return quals; } static List * find_all_quals(BitmapOrPath *path, int *branchcount) { List *all_quals = NIL; ListCell *lc; *branchcount = 0; foreach(lc, path->bitmapquals) { Path *subpath = (Path *) lfirst(lc); if (!IsA(subpath, IndexPath)) return NIL; all_quals = list_concat(all_quals, get_index_quals(castNode(IndexPath, subpath), *branchcount)); (*branchcount)++; } return all_quals; } static bool equal_ckey_args(CKey *a, CKey *b) { return a->opfamily == b->opfamily && equal(a->value, b->value) && equal(a->var, b->var); } static int count_matching_entries(List *all_quals, CKey *candidate) { int current_branch = 0; ListCell *lc; foreach(lc, all_quals) { CKey *key = (CKey *) lfirst(lc); if (key->n == current_branch) continue; if (key->n == current_branch + 1) { if (equal_ckey_args(key, candidate)) { candidate->strategy_mask |= key->strategy_mask; current_branch++; } } else return -1; } return current_branch + 1; } static List * find_common_quals(BitmapOrPath *path) { List *all_quals; List *common_quals = NIL; int branchcount; ListCell *lc; all_quals = find_all_quals(path, &branchcount); if (all_quals == NIL) return NIL; foreach(lc, all_quals) { CKey *key = (CKey *) lfirst(lc); if (key->n != 0) break; if (count_matching_entries(all_quals, key) == branchcount) common_quals = lappend(common_quals, key); } return common_quals; } static RestrictInfo * union_operation(PlannerInfo *root, CKey *key) { Oid lefttype; Oid righttype; int strategy; switch (key->strategy_mask) { case BTMASK(BTLessStrategyNumber): case BTMASK(BTLessEqualStrategyNumber): case BTMASK(BTEqualStrategyNumber): case BTMASK(BTGreaterEqualStrategyNumber): case BTMASK(BTGreaterStrategyNumber): break; case BTMASK(BTLessStrategyNumber) | BTMASK(BTLessEqualStrategyNumber): case BTMASK(BTLessStrategyNumber) | BTMASK(BTLessEqualStrategyNumber) | BTMASK(BTEqualStrategyNumber): case BTMASK(BTLessStrategyNumber) | BTMASK(BTEqualStrategyNumber): case BTMASK(BTLessEqualStrategyNumber) | BTMASK(BTEqualStrategyNumber): key->strategy = BTLessEqualStrategyNumber; break; case BTMASK(BTGreaterEqualStrategyNumber) | BTMASK(BTGreaterStrategyNumber): case BTMASK(BTEqualStrategyNumber) | BTMASK(BTGreaterEqualStrategyNumber) | BTMASK(BTGreaterStrategyNumber): case BTMASK(BTEqualStrategyNumber) | BTMASK(BTGreaterStrategyNumber): case BTMASK(BTEqualStrategyNumber) | BTMASK(BTGreaterEqualStrategyNumber): key->strategy = BTGreaterEqualStrategyNumber; break; default: return NULL; } get_op_opfamily_properties(key->normalizedexpr->opno, key->opfamily, false, &strategy, &lefttype, &righttype); if (strategy != key->strategy) { key->normalizedexpr->opno = get_opfamily_member(key->opfamily, lefttype, righttype, key->strategy); if (!OidIsValid(key->normalizedexpr->opno)) return NULL; key->normalizedexpr->opfuncid = get_opcode(key->normalizedexpr->opno); } return make_simple_restrictinfo(root, (Expr *) key->normalizedexpr); } static bool derived_qual_already_implied(RelOptInfo *rel, RestrictInfo *derived) { ListCell *lc; foreach(lc, rel->baserestrictinfo) { RestrictInfo *existing = lfirst_node(RestrictInfo, lc); if (restriction_is_or_clause(existing) || existing->pseudoconstant) continue; if (equal(existing->clause, derived->clause)) return true; if (predicate_implied_by(list_make1(derived->clause), list_make1(existing->clause), false)) return true; } return false; } static List * optimizable_indexclauses(List *indexclauses) { List *result = NIL; ListCell *lc; foreach(lc, indexclauses) { IndexClause *iclause = lfirst_node(IndexClause, lc); bool ok = true; ListCell *qc; foreach(qc, iclause->indexquals) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, qc); if (!IsA(rinfo->clause, OpExpr) || list_length(castNode(OpExpr, rinfo->clause)->args) != 2) { ok = false; break; } } if (ok) result = lappend(result, iclause); } return result; } static List * contained_quals(List *nested, List *paths, ListCell *check) { List *checkpred; ListCell *lc; if (list_member_ptr(nested, lfirst(check))) return nested; checkpred = extract_index_clause_exprs( castNode(IndexPath, lfirst(check))->indexclauses); if (contain_mutable_functions((Node *) checkpred)) return nested; foreach(lc, paths) { if (lc == check || list_member_ptr(nested, lfirst(lc))) continue; if (predicate_implied_by(checkpred, extract_index_clause_exprs( castNode(IndexPath, lfirst(lc))->indexclauses), false)) nested = lappend(nested, lfirst(lc)); } return nested; } static bool paths_overlap(List *paths, ListCell *check) { List *checkpred; ListCell *lc; checkpred = extract_index_clause_exprs( castNode(IndexPath, lfirst(check))->indexclauses); for_each_cell(lc, paths, check) { if (lc == check) continue; if (!predicate_refuted_by(checkpred, extract_index_clause_exprs( castNode(IndexPath, lfirst(lc))->indexclauses), false)) return true; } return false; } static Path * cleanup_nested_quals(BitmapOrPath *path) { List *nested = NIL; ListCell *lc; foreach(lc, path->bitmapquals) { IndexPath *ipath; List *preds; if (!IsA(lfirst(lc), IndexPath)) return NULL; ipath = castNode(IndexPath, lfirst(lc)); if (ipath->indexinfo->relam != BTREE_AM_OID) return NULL; preds = optimizable_indexclauses(ipath->indexclauses); if (preds == NIL) return NULL; ipath->indexclauses = preds; } foreach(lc, path->bitmapquals) nested = contained_quals(nested, path->bitmapquals, lc); if (nested != NIL) { path->bitmapquals = list_difference_ptr(path->bitmapquals, nested); if (list_length(path->bitmapquals) == 1) return linitial(path->bitmapquals); } foreach(lc, path->bitmapquals) { if (paths_overlap(path->bitmapquals, lc)) return NULL; } return &path->path; } static List * prepare_quals(IndexOptInfo *index, List *indexclauses) { List *result = NIL; ListCell *lc; foreach(lc, indexclauses) { IndexClause *iclause = lfirst_node(IndexClause, lc); ListCell *qc; foreach(qc, iclause->indexquals) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, qc); OpExpr *expr; ExExpr *prepared; if (!IsA(rinfo->clause, OpExpr)) return NIL; expr = castNode(OpExpr, rinfo->clause); if (list_length(expr->args) != 2 || contain_mutable_functions((Node *) expr)) return NIL; prepared = palloc(sizeof(ExExpr)); prepared->expr = copyObject(expr); if (!bms_equal(rinfo->left_relids, index->rel->relids)) CommuteOpExpr(prepared->expr); linitial(prepared->expr->args) = fix_indexqual_operand(linitial(prepared->expr->args), index, iclause->indexcol); prepared->attno = castNode(Var, linitial(prepared->expr->args))->varattno; prepared->opfamily = index->opfamily[prepared->attno - 1]; get_op_opfamily_properties(prepared->expr->opno, prepared->opfamily, false, &prepared->strategy, &prepared->lefttype, &prepared->righttype); result = lappend(result, prepared); } } return result; } static int simple_cmp_expr(ExExpr *a, ExExpr *b) { List *a_clauses = list_make1(a->expr); List *b_clauses = list_make1(b->expr); if (predicate_implied_by(a_clauses, b_clauses, false)) return 1; if (predicate_implied_by(b_clauses, a_clauses, false)) return -1; return 0; } static int cmp_eq_expr(ExExpr *a, ExExpr *b) { Oid oldop = b->expr->opno; int result = 0; b->expr->opno = get_opfamily_member(b->opfamily, b->lefttype, b->righttype, BTLessStrategyNumber); if (OidIsValid(b->expr->opno)) { b->expr->opfuncid = get_opcode(b->expr->opno); result = simple_cmp_expr(a, b); } if (result == 0) { b->expr->opno = get_opfamily_member(b->opfamily, b->lefttype, b->righttype, BTGreaterStrategyNumber); if (OidIsValid(b->expr->opno)) { b->expr->opfuncid = get_opcode(b->expr->opno); result = -simple_cmp_expr(a, b); } } b->expr->opno = oldop; b->expr->opfuncid = get_opcode(b->expr->opno); return result; } static int cmp_neg_cmp(ExExpr *a, ExExpr *b) { Oid oldop = b->expr->opno; int result = 0; b->expr->opno = get_negator(b->expr->opno); if (OidIsValid(b->expr->opno)) { b->expr->opfuncid = get_opcode(b->expr->opno); result = simple_cmp_expr(a, b); } b->expr->opno = oldop; b->expr->opfuncid = get_opcode(b->expr->opno); return IS_LESS(a->strategy) ? -result : result; } static int cmp_expr(ExExpr *a, ExExpr *b) { int result; List *a_clauses = list_make1(a->expr); List *b_clauses = list_make1(b->expr); if (IS_ONE_DIRECTION(a->strategy, b->strategy) || !predicate_refuted_by(a_clauses, b_clauses, false)) return 0; if (a->strategy == BTEqualStrategyNumber && b->strategy == BTEqualStrategyNumber) return cmp_eq_expr(a, b); if (b->strategy == BTEqualStrategyNumber) return -cmp_eq_expr(a, b); if (a->strategy == BTEqualStrategyNumber) return cmp_eq_expr(b, a); result = cmp_neg_cmp(a, b); if (result == 0) result = -cmp_neg_cmp(b, a); return result; } static int cmp_column_quals(List *a, List *b, int attno) { ListCell *la; foreach(la, a) { ExExpr *ea = (ExExpr *) lfirst(la); ListCell *lb; if (ea->attno != attno) continue; foreach(lb, b) { ExExpr *eb = (ExExpr *) lfirst(lb); int result; if (eb->attno != attno) continue; result = cmp_expr(ea, eb); if (result != 0) return result; if (ea->strategy == eb->strategy && eb->strategy != BTEqualStrategyNumber && equal(ea->expr, eb->expr)) { ordering_unknown = true; return 0; } } } return 0; } static int cmp_index_path_ex(const void *a, const void *b) { const OrderedIndexPath *pa = a; const OrderedIndexPath *pb = b; int attno; for (attno = 1; attno <= sorting_index->nkeycolumns; attno++) { int result; result = cmp_column_quals(pa->prepared_quals, pb->prepared_quals, attno); if (result != 0) return -result; } ordering_unknown = true; return 0; } static List * sort_index_scans(List *ipaths) { OrderedIndexPath *items; IndexOptInfo *index; List *ordered_paths = NIL; ListCell *lc; int count; int i; index = castNode(IndexPath, linitial(ipaths))->indexinfo; count = list_length(ipaths); items = palloc(sizeof(OrderedIndexPath) * count); i = 0; foreach(lc, ipaths) { items[i].path = castNode(IndexPath, lfirst(lc)); items[i].prepared_quals = prepare_quals(index, items[i].path->indexclauses); if (items[i].prepared_quals == NIL) return NIL; i++; } sorting_index = index; ordering_unknown = false; qsort(items, count, sizeof(OrderedIndexPath), cmp_index_path_ex); if (ordering_unknown) return NIL; for (i = 0; i < count; i++) ordered_paths = lappend(ordered_paths, items[i].path); return ordered_paths; } static double estimate_branch_rows(PlannerInfo *root, RelOptInfo *rel, List *indexclauses) { List *clauses; double branch_rows; clauses = extract_index_clause_exprs(indexclauses); branch_rows = rel->tuples * clauselist_selectivity(root, clauses, rel->relid, JOIN_INNER, NULL); return clamp_row_est(branch_rows); } static IndexPath * create_or_branch_index_path(PlannerInfo *root, RelOptInfo *rel, IndexPath *source, List *pathkeys, ScanDirection scandir) { IndexPath *path; double branch_rows; double costed_rows; if (PATH_REQ_OUTER(&source->path) != NULL) return NULL; branch_rows = estimate_branch_rows(root, rel, source->indexclauses); path = create_index_path(root, source->indexinfo, source->indexclauses, NIL, NIL, pathkeys, scandir, false, NULL, 1.0, false); costed_rows = path->path.rows; path->path.total_cost += path->path.pathtarget->cost.per_tuple * (branch_rows - costed_rows); path->path.rows = branch_rows; return path; } static List * build_or_branch_index_paths(PlannerInfo *root, RelOptInfo *rel, List *source_paths, List *pathkeys, ScanDirection scandir) { List *result = NIL; ListCell *lc; foreach(lc, source_paths) { IndexPath *src = lfirst_node(IndexPath, lc); IndexPath *path; path = create_or_branch_index_path(root, rel, src, pathkeys, scandir); if (path == NULL) return NIL; result = lappend(result, path); } return result; } static void add_append_path_candidate(PlannerInfo *root, RelOptInfo *rel, List *index_paths, List *pathkeys) { AppendPathInput input; memset(&input, 0, sizeof(input)); input.subpaths = index_paths; add_path(rel, (Path *) create_append_path(root, rel, input, pathkeys, NULL, 0, false, -1.0)); } void keybased_rewrite_index_paths(PlannerInfo *root, RelOptInfo *rel) { BitmapOrPath *bestpath = NULL; ListCell *lc; List *common_quals; Oid indexoid = InvalidOid; Path *cleaned; foreach(lc, rel->baserestrictinfo) { RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc); if (restriction_is_or_clause(rinfo)) { List *orpaths; ListCell *pc; orpaths = generate_bitmap_or_paths(root, rel, list_make1(rinfo), rel->baserestrictinfo); foreach(pc, orpaths) { BitmapOrPath *path = lfirst_node(BitmapOrPath, pc); Oid candidate_indexoid = InvalidOid; if (!check_same_index(&path->path, &candidate_indexoid)) continue; if (bestpath == NULL || path->path.total_cost < bestpath->path.total_cost) { bestpath = path; indexoid = candidate_indexoid; } } } } if (bestpath == NULL || !OidIsValid(indexoid)) return; common_quals = find_common_quals(bestpath); if (common_quals != NIL) { List *orig_baserestrictinfo = NIL; ListCell *qc; foreach(qc, common_quals) { RestrictInfo *rinfo; rinfo = union_operation(root, (CKey *) lfirst(qc)); if (rinfo == NULL) continue; if (derived_qual_already_implied(rel, rinfo)) continue; if (orig_baserestrictinfo == NIL) orig_baserestrictinfo = list_copy(rel->baserestrictinfo); rel->baserestrictinfo = lappend(rel->baserestrictinfo, rinfo); } if (orig_baserestrictinfo != NIL) { create_index_paths(root, rel); rel->baserestrictinfo = orig_baserestrictinfo; } } cleaned = cleanup_nested_quals(bestpath); if (cleaned == NULL) return; if (IsA(cleaned, IndexPath)) { IndexPath *source = castNode(IndexPath, cleaned); IndexOptInfo *index = source->indexinfo; IndexPath *ipath; List *pathkeys = NIL; ScanDirection scandir = ForwardScanDirection; if (root->query_pathkeys != NIL && index->sortopfamily != NULL && OidIsValid(index->sortopfamily[0])) { pathkeys = build_index_pathkeys(root, index, ForwardScanDirection); pathkeys = truncate_useless_pathkeys(root, rel, pathkeys); if (pathkeys == NIL) { pathkeys = build_index_pathkeys(root, index, BackwardScanDirection); pathkeys = truncate_useless_pathkeys(root, rel, pathkeys); if (pathkeys != NIL) scandir = BackwardScanDirection; } } ipath = create_or_branch_index_path(root, rel, source, pathkeys, scandir); if (ipath == NULL) return; add_path(rel, &ipath->path); return; } if (IsA(cleaned, BitmapOrPath)) { BitmapOrPath *orpath = castNode(BitmapOrPath, cleaned); IndexOptInfo *index = castNode(IndexPath, linitial(orpath->bitmapquals))->indexinfo; List *ordered_paths; List *forward_pathkeys = NIL; List *backward_pathkeys = NIL; bool added_ordered = false; if (root->query_pathkeys != NIL && index->sortopfamily != NULL && OidIsValid(index->sortopfamily[0])) { forward_pathkeys = build_index_pathkeys(root, index, ForwardScanDirection); forward_pathkeys = truncate_useless_pathkeys(root, rel, forward_pathkeys); if (forward_pathkeys != NIL) { ordered_paths = build_or_branch_index_paths(root, rel, orpath->bitmapquals, forward_pathkeys, ForwardScanDirection); if (ordered_paths != NIL) { ordered_paths = sort_index_scans(ordered_paths); if (ordered_paths != NIL) { add_append_path_candidate(root, rel, ordered_paths, forward_pathkeys); added_ordered = true; } } } backward_pathkeys = build_index_pathkeys(root, index, BackwardScanDirection); backward_pathkeys = truncate_useless_pathkeys(root, rel, backward_pathkeys); if (backward_pathkeys != NIL) { ordered_paths = build_or_branch_index_paths(root, rel, orpath->bitmapquals, backward_pathkeys, BackwardScanDirection); if (ordered_paths != NIL) { ordered_paths = sort_index_scans(ordered_paths); if (ordered_paths != NIL) { List *reversed_paths = NIL; ListCell *pc; foreach(pc, ordered_paths) reversed_paths = lcons(lfirst(pc), reversed_paths); add_append_path_candidate(root, rel, reversed_paths, backward_pathkeys); added_ordered = true; } } } } if (!added_ordered) { List *unordered_paths; unordered_paths = build_or_branch_index_paths(root, rel, orpath->bitmapquals, NIL, ForwardScanDirection); if (unordered_paths != NIL) add_append_path_candidate(root, rel, unordered_paths, NIL); } } }