1 /*-------------------------------------------------------------------------
4 * Routines to determine which indexes are usable for scanning a
5 * given relation, and create Paths accordingly.
7 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * $PostgreSQL: pgsql/src/backend/optimizer/path/indxpath.c,v 1.215 2007/01/09 02:14:12 tgl Exp $
14 *-------------------------------------------------------------------------
20 #include "access/skey.h"
21 #include "catalog/pg_am.h"
22 #include "catalog/pg_operator.h"
23 #include "catalog/pg_opfamily.h"
24 #include "catalog/pg_type.h"
25 #include "nodes/makefuncs.h"
26 #include "optimizer/clauses.h"
27 #include "optimizer/cost.h"
28 #include "optimizer/pathnode.h"
29 #include "optimizer/paths.h"
30 #include "optimizer/predtest.h"
31 #include "optimizer/restrictinfo.h"
32 #include "optimizer/var.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/pg_locale.h"
37 #include "utils/selfuncs.h"
41 * DoneMatchingIndexKeys() - MACRO
43 #define DoneMatchingIndexKeys(families) (families[0] == InvalidOid)
45 #define IsBooleanOpfamily(opfamily) \
46 ((opfamily) == BOOL_BTREE_FAM_OID || (opfamily) == BOOL_HASH_FAM_OID)
49 static List *find_usable_indexes(PlannerInfo *root, RelOptInfo *rel,
50 List *clauses, List *outer_clauses,
51 bool istoplevel, RelOptInfo *outer_rel,
52 SaOpControl saop_control);
53 static List *find_saop_paths(PlannerInfo *root, RelOptInfo *rel,
54 List *clauses, List *outer_clauses,
55 bool istoplevel, RelOptInfo *outer_rel);
56 static Path *choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel,
57 List *paths, RelOptInfo *outer_rel);
58 static int bitmap_path_comparator(const void *a, const void *b);
59 static Cost bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel,
60 List *paths, RelOptInfo *outer_rel);
61 static List *pull_indexpath_quals(Path *bitmapqual);
62 static bool lists_intersect_ptr(List *list1, List *list2);
63 static bool match_clause_to_indexcol(IndexOptInfo *index,
64 int indexcol, Oid opfamily,
67 SaOpControl saop_control);
68 static bool is_indexable_operator(Oid expr_op, Oid opfamily,
69 bool indexkey_on_left);
70 static bool match_rowcompare_to_indexcol(IndexOptInfo *index,
73 RowCompareExpr *clause,
75 static Relids indexable_outerrelids(RelOptInfo *rel);
76 static bool matches_any_index(RestrictInfo *rinfo, RelOptInfo *rel,
78 static List *find_clauses_for_join(PlannerInfo *root, RelOptInfo *rel,
79 Relids outer_relids, bool isouterjoin);
80 static ScanDirection match_variant_ordering(PlannerInfo *root,
82 List *restrictclauses);
83 static List *identify_ignorable_ordering_cols(PlannerInfo *root,
85 List *restrictclauses);
86 static bool match_index_to_query_keys(PlannerInfo *root,
88 ScanDirection indexscandir,
90 static bool match_boolean_index_clause(Node *clause, int indexcol,
92 static bool match_special_index_operator(Expr *clause, Oid opfamily,
93 bool indexkey_on_left);
94 static Expr *expand_boolean_index_clause(Node *clause, int indexcol,
96 static List *expand_indexqual_opclause(RestrictInfo *rinfo, Oid opfamily);
97 static RestrictInfo *expand_indexqual_rowcompare(RestrictInfo *rinfo,
100 static List *prefix_quals(Node *leftop, Oid opfamily,
101 Const *prefix, Pattern_Prefix_Status pstatus);
102 static List *network_prefix_quals(Node *leftop, Oid expr_op, Oid opfamily,
104 static Datum string_to_datum(const char *str, Oid datatype);
105 static Const *string_to_const(const char *str, Oid datatype);
109 * create_index_paths()
110 * Generate all interesting index paths for the given relation.
111 * Candidate paths are added to the rel's pathlist (using add_path).
113 * To be considered for an index scan, an index must match one or more
114 * restriction clauses or join clauses from the query's qual condition,
115 * or match the query's ORDER BY condition, or have a predicate that
116 * matches the query's qual condition.
118 * There are two basic kinds of index scans. A "plain" index scan uses
119 * only restriction clauses (possibly none at all) in its indexqual,
120 * so it can be applied in any context. An "innerjoin" index scan uses
121 * join clauses (plus restriction clauses, if available) in its indexqual.
122 * Therefore it can only be used as the inner relation of a nestloop
123 * join against an outer rel that includes all the other rels mentioned
124 * in its join clauses. In that context, values for the other rels'
125 * attributes are available and fixed during any one scan of the indexpath.
127 * An IndexPath is generated and submitted to add_path() for each plain index
128 * scan this routine deems potentially interesting for the current query.
130 * We also determine the set of other relids that participate in join
131 * clauses that could be used with each index. The actually best innerjoin
132 * path will be generated for each outer relation later on, but knowing the
133 * set of potential otherrels allows us to identify equivalent outer relations
134 * and avoid repeated computation.
136 * 'rel' is the relation for which we want to generate index paths
138 * Note: check_partial_indexes() must have been run previously for this rel.
141 create_index_paths(PlannerInfo *root, RelOptInfo *rel)
147 /* Skip the whole mess if no indexes */
148 if (rel->indexlist == NIL)
150 rel->index_outer_relids = NULL;
155 * Examine join clauses to see which ones are potentially usable with
156 * indexes of this rel, and generate the set of all other relids that
157 * participate in such join clauses. We'll use this set later to
158 * recognize outer rels that are equivalent for joining purposes.
160 rel->index_outer_relids = indexable_outerrelids(rel);
163 * Find all the index paths that are directly usable for this relation
164 * (ie, are valid without considering OR or JOIN clauses).
166 indexpaths = find_usable_indexes(root, rel,
167 rel->baserestrictinfo, NIL,
168 true, NULL, SAOP_FORBID);
171 * We can submit them all to add_path. (This generates access paths for
172 * plain IndexScan plans.) However, for the next step we will only want
173 * the ones that have some selectivity; we must discard anything that was
174 * generated solely for ordering purposes.
177 foreach(l, indexpaths)
179 IndexPath *ipath = (IndexPath *) lfirst(l);
181 add_path(rel, (Path *) ipath);
183 if (ipath->indexselectivity < 1.0 &&
184 !ScanDirectionIsBackward(ipath->indexscandir))
185 bitindexpaths = lappend(bitindexpaths, ipath);
189 * Generate BitmapOrPaths for any suitable OR-clauses present in the
190 * restriction list. Add these to bitindexpaths.
192 indexpaths = generate_bitmap_or_paths(root, rel,
193 rel->baserestrictinfo, NIL,
195 bitindexpaths = list_concat(bitindexpaths, indexpaths);
198 * Likewise, generate paths using ScalarArrayOpExpr clauses; these can't
199 * be simple indexscans but they can be used in bitmap scans.
201 indexpaths = find_saop_paths(root, rel,
202 rel->baserestrictinfo, NIL,
204 bitindexpaths = list_concat(bitindexpaths, indexpaths);
207 * If we found anything usable, generate a BitmapHeapPath for the most
208 * promising combination of bitmap index paths.
210 if (bitindexpaths != NIL)
213 BitmapHeapPath *bpath;
215 bitmapqual = choose_bitmap_and(root, rel, bitindexpaths, NULL);
216 bpath = create_bitmap_heap_path(root, rel, bitmapqual, NULL);
217 add_path(rel, (Path *) bpath);
223 * find_usable_indexes
224 * Given a list of restriction clauses, find all the potentially usable
225 * indexes for the given relation, and return a list of IndexPaths.
227 * The caller actually supplies two lists of restriction clauses: some
228 * "current" ones and some "outer" ones. Both lists can be used freely
229 * to match keys of the index, but an index must use at least one of the
230 * "current" clauses to be considered usable. The motivation for this is
232 * WHERE (x = 42) AND (... OR (y = 52 AND z = 77) OR ....)
233 * While we are considering the y/z subclause of the OR, we can use "x = 42"
234 * as one of the available index conditions; but we shouldn't match the
235 * subclause to any index on x alone, because such a Path would already have
236 * been generated at the upper level. So we could use an index on x,y,z
237 * or an index on x,y for the OR subclause, but not an index on just x.
238 * When dealing with a partial index, a match of the index predicate to
239 * one of the "current" clauses also makes the index usable.
241 * If istoplevel is true (indicating we are considering the top level of a
242 * rel's restriction clauses), we will include indexes in the result that
243 * have an interesting sort order, even if they have no matching restriction
246 * 'rel' is the relation for which we want to generate index paths
247 * 'clauses' is the current list of clauses (RestrictInfo nodes)
248 * 'outer_clauses' is the list of additional upper-level clauses
249 * 'istoplevel' is true if clauses are the rel's top-level restriction list
250 * (outer_clauses must be NIL when this is true)
251 * 'outer_rel' is the outer side of the join if forming an inner indexscan
252 * (so some of the given clauses are join clauses); NULL if not
253 * 'saop_control' indicates whether ScalarArrayOpExpr clauses can be used
255 * Note: check_partial_indexes() must have been run previously.
259 find_usable_indexes(PlannerInfo *root, RelOptInfo *rel,
260 List *clauses, List *outer_clauses,
261 bool istoplevel, RelOptInfo *outer_rel,
262 SaOpControl saop_control)
264 Relids outer_relids = outer_rel ? outer_rel->relids : NULL;
266 List *all_clauses = NIL; /* not computed till needed */
269 foreach(ilist, rel->indexlist)
271 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
273 List *restrictclauses;
274 List *index_pathkeys;
275 List *useful_pathkeys;
276 bool useful_predicate;
278 bool index_is_ordered;
281 * Ignore partial indexes that do not match the query. If a partial
282 * index is marked predOK then we know it's OK; otherwise, if we are
283 * at top level we know it's not OK (since predOK is exactly whether
284 * its predicate could be proven from the toplevel clauses).
285 * Otherwise, we have to test whether the added clauses are sufficient
286 * to imply the predicate. If so, we could use the index in the
289 * We set useful_predicate to true iff the predicate was proven using
290 * the current set of clauses. This is needed to prevent matching a
291 * predOK index to an arm of an OR, which would be a legal but
292 * pointlessly inefficient plan. (A better plan will be generated by
293 * just scanning the predOK index alone, no OR.)
295 useful_predicate = false;
296 if (index->indpred != NIL)
302 /* we know predicate was proven from these clauses */
303 useful_predicate = true;
309 continue; /* no point in trying to prove it */
311 /* Form all_clauses if not done already */
312 if (all_clauses == NIL)
313 all_clauses = list_concat(list_copy(clauses),
316 if (!predicate_implied_by(index->indpred, all_clauses))
317 continue; /* can't use it at all */
319 if (!predicate_implied_by(index->indpred, outer_clauses))
320 useful_predicate = true;
325 * 1. Match the index against the available restriction clauses.
326 * found_clause is set true only if at least one of the current
327 * clauses was used (and, if saop_control is SAOP_REQUIRE, it has to
328 * have been a ScalarArrayOpExpr clause).
330 restrictclauses = group_clauses_by_indexkey(index,
338 * Not all index AMs support scans with no restriction clauses. We
339 * can't generate a scan over an index with amoptionalkey = false
340 * unless there's at least one restriction clause.
342 if (restrictclauses == NIL && !index->amoptionalkey)
346 * 2. Compute pathkeys describing index's ordering, if any, then see
347 * how many of them are actually useful for this query. This is not
348 * relevant unless we are at top level.
350 index_is_ordered = OidIsValid(index->fwdsortop[0]);
351 if (index_is_ordered && istoplevel && outer_rel == NULL)
353 index_pathkeys = build_index_pathkeys(root, index,
354 ForwardScanDirection,
356 useful_pathkeys = truncate_useless_pathkeys(root, rel,
360 useful_pathkeys = NIL;
363 * 3. Generate an indexscan path if there are relevant restriction
364 * clauses in the current clauses, OR the index ordering is
365 * potentially useful for later merging or final output ordering, OR
366 * the index has a predicate that was proven by the current clauses.
368 if (found_clause || useful_pathkeys != NIL || useful_predicate)
370 ipath = create_index_path(root, index,
374 ForwardScanDirection :
375 NoMovementScanDirection,
377 result = lappend(result, ipath);
381 * 4. If the index is ordered, and there is a requested query ordering
382 * that we failed to match, consider variant ways of achieving the
383 * ordering. Again, this is only interesting at top level.
385 if (index_is_ordered && istoplevel && outer_rel == NULL &&
386 root->query_pathkeys != NIL &&
387 pathkeys_useful_for_ordering(root, useful_pathkeys) == 0)
389 ScanDirection scandir;
391 scandir = match_variant_ordering(root, index, restrictclauses);
392 if (!ScanDirectionIsNoMovement(scandir))
394 ipath = create_index_path(root, index,
396 root->query_pathkeys,
399 result = lappend(result, ipath);
410 * Find all the potential indexpaths that make use of ScalarArrayOpExpr
411 * clauses. The executor only supports these in bitmap scans, not
412 * plain indexscans, so we need to segregate them from the normal case.
413 * Otherwise, same API as find_usable_indexes().
414 * Returns a list of IndexPaths.
417 find_saop_paths(PlannerInfo *root, RelOptInfo *rel,
418 List *clauses, List *outer_clauses,
419 bool istoplevel, RelOptInfo *outer_rel)
421 bool have_saop = false;
425 * Since find_usable_indexes is relatively expensive, don't bother to run
426 * it unless there are some top-level ScalarArrayOpExpr clauses.
430 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
432 Assert(IsA(rinfo, RestrictInfo));
433 if (IsA(rinfo->clause, ScalarArrayOpExpr))
442 return find_usable_indexes(root, rel,
443 clauses, outer_clauses,
444 istoplevel, outer_rel,
450 * generate_bitmap_or_paths
451 * Look through the list of clauses to find OR clauses, and generate
452 * a BitmapOrPath for each one we can handle that way. Return a list
453 * of the generated BitmapOrPaths.
455 * outer_clauses is a list of additional clauses that can be assumed true
456 * for the purpose of generating indexquals, but are not to be searched for
457 * ORs. (See find_usable_indexes() for motivation.) outer_rel is the outer
458 * side when we are considering a nestloop inner indexpath.
461 generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
462 List *clauses, List *outer_clauses,
463 RelOptInfo *outer_rel)
470 * We can use both the current and outer clauses as context for
471 * find_usable_indexes
473 all_clauses = list_concat(list_copy(clauses), outer_clauses);
477 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
482 Assert(IsA(rinfo, RestrictInfo));
483 /* Ignore RestrictInfos that aren't ORs */
484 if (!restriction_is_or_clause(rinfo))
488 * We must be able to match at least one index to each of the arms of
489 * the OR, else we can't use it.
492 foreach(j, ((BoolExpr *) rinfo->orclause)->args)
494 Node *orarg = (Node *) lfirst(j);
497 /* OR arguments should be ANDs or sub-RestrictInfos */
498 if (and_clause(orarg))
500 List *andargs = ((BoolExpr *) orarg)->args;
502 indlist = find_usable_indexes(root, rel,
508 /* Recurse in case there are sub-ORs */
509 indlist = list_concat(indlist,
510 generate_bitmap_or_paths(root, rel,
517 Assert(IsA(orarg, RestrictInfo));
518 Assert(!restriction_is_or_clause((RestrictInfo *) orarg));
519 indlist = find_usable_indexes(root, rel,
528 * If nothing matched this arm, we can't do anything with this OR
538 * OK, pick the most promising AND combination, and add it to
541 bitmapqual = choose_bitmap_and(root, rel, indlist, outer_rel);
542 pathlist = lappend(pathlist, bitmapqual);
546 * If we have a match for every arm, then turn them into a
547 * BitmapOrPath, and add to result list.
551 bitmapqual = (Path *) create_bitmap_or_path(root, rel, pathlist);
552 result = lappend(result, bitmapqual);
562 * Given a nonempty list of bitmap paths, AND them into one path.
564 * This is a nontrivial decision since we can legally use any subset of the
565 * given path set. We want to choose a good tradeoff between selectivity
566 * and cost of computing the bitmap.
568 * The result is either a single one of the inputs, or a BitmapAndPath
569 * combining multiple inputs.
572 choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel,
573 List *paths, RelOptInfo *outer_rel)
575 int npaths = list_length(paths);
583 Assert(npaths > 0); /* else caller error */
585 return (Path *) linitial(paths); /* easy case */
588 * In theory we should consider every nonempty subset of the given paths.
589 * In practice that seems like overkill, given the crude nature of the
590 * estimates, not to mention the possible effects of higher-level AND and
591 * OR clauses. As a compromise, we sort the paths by selectivity. We
592 * always take the first, and sequentially add on paths that result in a
593 * lower estimated cost.
595 * We also make some effort to detect directly redundant input paths, as
596 * can happen if there are multiple possibly usable indexes. (Another way
597 * it can happen is that best_inner_indexscan will find the same OR join
598 * clauses that create_or_index_quals has pulled OR restriction clauses
599 * out of, and then both versions show up as duplicate paths.) We
600 * consider an index redundant if any of its index conditions were already
601 * used by earlier indexes. (We could use predicate_implied_by to have a
602 * more intelligent, but much more expensive, check --- but in most cases
603 * simple pointer equality should suffice, since after all the index
604 * conditions are all coming from the same RestrictInfo lists.)
606 * You might think the condition for redundancy should be "all index
607 * conditions already used", not "any", but this turns out to be wrong.
608 * For example, if we use an index on A, and then come to an index with
609 * conditions on A and B, the only way that the second index can be later
610 * in the selectivity-order sort is if the condition on B is completely
611 * non-selective. In any case, we'd surely be drastically misestimating
612 * the selectivity if we count the same condition twice.
614 * We include index predicate conditions in the redundancy test. Because
615 * the test is just for pointer equality and not equal(), the effect is
616 * that use of the same partial index in two different AND elements is
617 * considered redundant. (XXX is this too strong?)
619 * Note: outputting the selected sub-paths in selectivity order is a good
620 * thing even if we weren't using that as part of the selection method,
621 * because it makes the short-circuit case in MultiExecBitmapAnd() more
625 /* Convert list to array so we can apply qsort */
626 patharray = (Path **) palloc(npaths * sizeof(Path *));
630 patharray[i++] = (Path *) lfirst(l);
632 qsort(patharray, npaths, sizeof(Path *), bitmap_path_comparator);
634 paths = list_make1(patharray[0]);
635 costsofar = bitmap_and_cost_est(root, rel, paths, outer_rel);
636 qualsofar = pull_indexpath_quals(patharray[0]);
637 lastcell = list_head(paths); /* for quick deletions */
639 for (i = 1; i < npaths; i++)
641 Path *newpath = patharray[i];
645 newqual = pull_indexpath_quals(newpath);
646 if (lists_intersect_ptr(newqual, qualsofar))
647 continue; /* consider it redundant */
648 /* tentatively add newpath to paths, so we can estimate cost */
649 paths = lappend(paths, newpath);
650 newcost = bitmap_and_cost_est(root, rel, paths, outer_rel);
651 if (newcost < costsofar)
653 /* keep newpath in paths, update subsidiary variables */
655 qualsofar = list_concat(qualsofar, newqual);
656 lastcell = lnext(lastcell);
660 /* reject newpath, remove it from paths list */
661 paths = list_delete_cell(paths, lnext(lastcell), lastcell);
663 Assert(lnext(lastcell) == NULL);
666 if (list_length(paths) == 1)
667 return (Path *) linitial(paths); /* no need for AND */
668 return (Path *) create_bitmap_and_path(root, rel, paths);
671 /* qsort comparator to sort in increasing selectivity order */
673 bitmap_path_comparator(const void *a, const void *b)
675 Path *pa = *(Path *const *) a;
676 Path *pb = *(Path *const *) b;
682 cost_bitmap_tree_node(pa, &acost, &aselec);
683 cost_bitmap_tree_node(pb, &bcost, &bselec);
686 * If selectivities are the same, sort by cost. (Note: there used to be
687 * logic here to do "fuzzy comparison", but that's a bad idea because it
688 * fails to be transitive, which will confuse qsort terribly.)
704 * Estimate the cost of actually executing a BitmapAnd with the given
708 bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel,
709 List *paths, RelOptInfo *outer_rel)
714 /* Set up a dummy BitmapAndPath */
715 apath.path.type = T_BitmapAndPath;
716 apath.path.parent = rel;
717 apath.bitmapquals = paths;
718 cost_bitmap_and_node(&apath, root);
720 /* Now we can do cost_bitmap_heap_scan */
721 cost_bitmap_heap_scan(&bpath, root, rel, (Path *) &apath, outer_rel);
723 return bpath.total_cost;
727 * pull_indexpath_quals
729 * Given the Path structure for a plain or bitmap indexscan, extract a list
730 * of all the indexquals and index predicate conditions used in the Path.
732 * This is sort of a simplified version of make_restrictinfo_from_bitmapqual;
733 * here, we are not trying to produce an accurate representation of the AND/OR
734 * semantics of the Path, but just find out all the base conditions used.
736 * The result list contains pointers to the expressions used in the Path,
737 * but all the list cells are freshly built, so it's safe to destructively
738 * modify the list (eg, by concat'ing it with other lists).
741 pull_indexpath_quals(Path *bitmapqual)
746 if (IsA(bitmapqual, BitmapAndPath))
748 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
750 foreach(l, apath->bitmapquals)
754 sublist = pull_indexpath_quals((Path *) lfirst(l));
755 result = list_concat(result, sublist);
758 else if (IsA(bitmapqual, BitmapOrPath))
760 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
762 foreach(l, opath->bitmapquals)
766 sublist = pull_indexpath_quals((Path *) lfirst(l));
767 result = list_concat(result, sublist);
770 else if (IsA(bitmapqual, IndexPath))
772 IndexPath *ipath = (IndexPath *) bitmapqual;
774 result = get_actual_clauses(ipath->indexclauses);
775 result = list_concat(result, list_copy(ipath->indexinfo->indpred));
778 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
785 * lists_intersect_ptr
786 * Detect whether two lists have a nonempty intersection,
787 * using pointer equality to compare members.
789 * This possibly should go into list.c, but it doesn't yet have any use
790 * except in choose_bitmap_and.
793 lists_intersect_ptr(List *list1, List *list2)
797 foreach(cell1, list1)
799 void *datum1 = lfirst(cell1);
802 foreach(cell2, list2)
804 if (lfirst(cell2) == datum1)
813 /****************************************************************************
814 * ---- ROUTINES TO CHECK RESTRICTIONS ----
815 ****************************************************************************/
819 * group_clauses_by_indexkey
820 * Find restriction clauses that can be used with an index.
822 * Returns a list of sublists of RestrictInfo nodes for clauses that can be
823 * used with this index. Each sublist contains clauses that can be used
824 * with one index key (in no particular order); the top list is ordered by
825 * index key. (This is depended on by expand_indexqual_conditions().)
827 * We can use clauses from either the current clauses or outer_clauses lists,
828 * but *found_clause is set TRUE only if we used at least one clause from
829 * the "current clauses" list. See find_usable_indexes() for motivation.
831 * outer_relids determines what Vars will be allowed on the other side
832 * of a possible index qual; see match_clause_to_indexcol().
834 * 'saop_control' indicates whether ScalarArrayOpExpr clauses can be used.
835 * When it's SAOP_REQUIRE, *found_clause is set TRUE only if we used at least
836 * one ScalarArrayOpExpr from the current clauses list.
838 * If the index has amoptionalkey = false, we give up and return NIL when
839 * there are no restriction clauses matching the first index key. Otherwise,
840 * we return NIL if there are no restriction clauses matching any index key.
841 * A non-NIL result will have one (possibly empty) sublist for each index key.
843 * Example: given an index on (A,B,C), we would return ((C1 C2) () (C3 C4))
844 * if we find that clauses C1 and C2 use column A, clauses C3 and C4 use
845 * column C, and no clauses use column B.
847 * Note: in some circumstances we may find the same RestrictInfos coming
848 * from multiple places. Defend against redundant outputs by using
849 * list_append_unique_ptr (pointer equality should be good enough).
852 group_clauses_by_indexkey(IndexOptInfo *index,
853 List *clauses, List *outer_clauses,
855 SaOpControl saop_control,
858 List *clausegroup_list = NIL;
859 bool found_outer_clause = false;
861 Oid *families = index->opfamily;
863 *found_clause = false; /* default result */
865 if (clauses == NIL && outer_clauses == NIL)
866 return NIL; /* cannot succeed */
870 Oid curFamily = families[0];
871 List *clausegroup = NIL;
874 /* check the current clauses */
877 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
879 Assert(IsA(rinfo, RestrictInfo));
880 if (match_clause_to_indexcol(index,
887 clausegroup = list_append_unique_ptr(clausegroup, rinfo);
888 if (saop_control != SAOP_REQUIRE ||
889 IsA(rinfo->clause, ScalarArrayOpExpr))
890 *found_clause = true;
894 /* check the outer clauses */
895 foreach(l, outer_clauses)
897 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
899 Assert(IsA(rinfo, RestrictInfo));
900 if (match_clause_to_indexcol(index,
907 clausegroup = list_append_unique_ptr(clausegroup, rinfo);
908 found_outer_clause = true;
913 * If no clauses match this key, check for amoptionalkey restriction.
915 if (clausegroup == NIL && !index->amoptionalkey && indexcol == 0)
918 clausegroup_list = lappend(clausegroup_list, clausegroup);
923 } while (!DoneMatchingIndexKeys(families));
925 if (!*found_clause && !found_outer_clause)
926 return NIL; /* no indexable clauses anywhere */
928 return clausegroup_list;
933 * match_clause_to_indexcol()
934 * Determines whether a restriction clause matches a column of an index.
936 * To match a normal index, the clause:
938 * (1) must be in the form (indexkey op const) or (const op indexkey);
940 * (2) must contain an operator which is in the same family as the index
941 * operator for this column, or is a "special" operator as recognized
942 * by match_special_index_operator().
944 * Our definition of "const" is pretty liberal: we allow Vars belonging
945 * to the caller-specified outer_relids relations (which had better not
946 * include the relation whose index is being tested). outer_relids should
947 * be NULL when checking simple restriction clauses, and the outer side
948 * of the join when building a join inner scan. Other than that, the
949 * only thing we don't like is volatile functions.
951 * Note: in most cases we already know that the clause as a whole uses
952 * vars from the interesting set of relations. The reason for the
953 * outer_relids test is to reject clauses like (a.f1 OP (b.f2 OP a.f3));
954 * that's not processable by an indexscan nestloop join on A, whereas
955 * (a.f1 OP (b.f2 OP c.f3)) is.
957 * Presently, the executor can only deal with indexquals that have the
958 * indexkey on the left, so we can only use clauses that have the indexkey
959 * on the right if we can commute the clause to put the key on the left.
960 * We do not actually do the commuting here, but we check whether a
961 * suitable commutator operator is available.
963 * It is also possible to match RowCompareExpr clauses to indexes (but
964 * currently, only btree indexes handle this). In this routine we will
965 * report a match if the first column of the row comparison matches the
966 * target index column. This is sufficient to guarantee that some index
967 * condition can be constructed from the RowCompareExpr --- whether the
968 * remaining columns match the index too is considered in
969 * expand_indexqual_rowcompare().
971 * It is also possible to match ScalarArrayOpExpr clauses to indexes, when
972 * the clause is of the form "indexkey op ANY (arrayconst)". Since the
973 * executor can only handle these in the context of bitmap index scans,
974 * our caller specifies whether to allow these or not.
976 * For boolean indexes, it is also possible to match the clause directly
977 * to the indexkey; or perhaps the clause is (NOT indexkey).
979 * 'index' is the index of interest.
980 * 'indexcol' is a column number of 'index' (counting from 0).
981 * 'opfamily' is the corresponding operator family.
982 * 'rinfo' is the clause to be tested (as a RestrictInfo node).
983 * 'saop_control' indicates whether ScalarArrayOpExpr clauses can be used.
985 * Returns true if the clause can be used with this index key.
987 * NOTE: returns false if clause is an OR or AND clause; it is the
988 * responsibility of higher-level routines to cope with those.
991 match_clause_to_indexcol(IndexOptInfo *index,
996 SaOpControl saop_control)
998 Expr *clause = rinfo->clause;
1002 Relids right_relids;
1007 * Never match pseudoconstants to indexes. (Normally this could not
1008 * happen anyway, since a pseudoconstant clause couldn't contain a Var,
1009 * but what if someone builds an expression index on a constant? It's not
1010 * totally unreasonable to do so with a partial index, either.)
1012 if (rinfo->pseudoconstant)
1015 /* First check for boolean-index cases. */
1016 if (IsBooleanOpfamily(opfamily))
1018 if (match_boolean_index_clause((Node *) clause, indexcol, index))
1023 * Clause must be a binary opclause, or possibly a ScalarArrayOpExpr
1024 * (which is always binary, by definition). Or it could be a
1025 * RowCompareExpr, which we pass off to match_rowcompare_to_indexcol().
1027 if (is_opclause(clause))
1029 leftop = get_leftop(clause);
1030 rightop = get_rightop(clause);
1031 if (!leftop || !rightop)
1033 left_relids = rinfo->left_relids;
1034 right_relids = rinfo->right_relids;
1035 expr_op = ((OpExpr *) clause)->opno;
1038 else if (saop_control != SAOP_FORBID &&
1039 clause && IsA(clause, ScalarArrayOpExpr))
1041 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
1043 /* We only accept ANY clauses, not ALL */
1046 leftop = (Node *) linitial(saop->args);
1047 rightop = (Node *) lsecond(saop->args);
1048 left_relids = NULL; /* not actually needed */
1049 right_relids = pull_varnos(rightop);
1050 expr_op = saop->opno;
1053 else if (clause && IsA(clause, RowCompareExpr))
1055 return match_rowcompare_to_indexcol(index, indexcol, opfamily,
1056 (RowCompareExpr *) clause,
1063 * Check for clauses of the form: (indexkey operator constant) or
1064 * (constant operator indexkey). See above notes about const-ness.
1066 if (match_index_to_operand(leftop, indexcol, index) &&
1067 bms_is_subset(right_relids, outer_relids) &&
1068 !contain_volatile_functions(rightop))
1070 if (is_indexable_operator(expr_op, opfamily, true))
1074 * If we didn't find a member of the index's opfamily, see whether it
1075 * is a "special" indexable operator.
1078 match_special_index_operator(clause, opfamily, true))
1084 match_index_to_operand(rightop, indexcol, index) &&
1085 bms_is_subset(left_relids, outer_relids) &&
1086 !contain_volatile_functions(leftop))
1088 if (is_indexable_operator(expr_op, opfamily, false))
1092 * If we didn't find a member of the index's opfamily, see whether it
1093 * is a "special" indexable operator.
1095 if (match_special_index_operator(clause, opfamily, false))
1104 * is_indexable_operator
1105 * Does the operator match the specified index opfamily?
1107 * If the indexkey is on the right, what we actually want to know
1108 * is whether the operator has a commutator operator that matches
1112 is_indexable_operator(Oid expr_op, Oid opfamily, bool indexkey_on_left)
1114 /* Get the commuted operator if necessary */
1115 if (!indexkey_on_left)
1117 expr_op = get_commutator(expr_op);
1118 if (expr_op == InvalidOid)
1122 /* OK if the (commuted) operator is a member of the index's opfamily */
1123 return op_in_opfamily(expr_op, opfamily);
1127 * match_rowcompare_to_indexcol()
1128 * Handles the RowCompareExpr case for match_clause_to_indexcol(),
1129 * which see for comments.
1132 match_rowcompare_to_indexcol(IndexOptInfo *index,
1135 RowCompareExpr *clause,
1136 Relids outer_relids)
1142 /* Forget it if we're not dealing with a btree index */
1143 if (index->relam != BTREE_AM_OID)
1147 * We could do the matching on the basis of insisting that the opfamily
1148 * shown in the RowCompareExpr be the same as the index column's opfamily,
1149 * but that could fail in the presence of reverse-sort opfamilies: it'd
1150 * be a matter of chance whether RowCompareExpr had picked the forward
1151 * or reverse-sort family. So look only at the operator, and match
1152 * if it is a member of the index's opfamily (after commutation, if the
1153 * indexkey is on the right). We'll worry later about whether any
1154 * additional operators are matchable to the index.
1156 leftop = (Node *) linitial(clause->largs);
1157 rightop = (Node *) linitial(clause->rargs);
1158 expr_op = linitial_oid(clause->opnos);
1161 * These syntactic tests are the same as in match_clause_to_indexcol()
1163 if (match_index_to_operand(leftop, indexcol, index) &&
1164 bms_is_subset(pull_varnos(rightop), outer_relids) &&
1165 !contain_volatile_functions(rightop))
1167 /* OK, indexkey is on left */
1169 else if (match_index_to_operand(rightop, indexcol, index) &&
1170 bms_is_subset(pull_varnos(leftop), outer_relids) &&
1171 !contain_volatile_functions(leftop))
1173 /* indexkey is on right, so commute the operator */
1174 expr_op = get_commutator(expr_op);
1175 if (expr_op == InvalidOid)
1181 /* We're good if the operator is the right type of opfamily member */
1182 switch (get_op_opfamily_strategy(expr_op, opfamily))
1184 case BTLessStrategyNumber:
1185 case BTLessEqualStrategyNumber:
1186 case BTGreaterEqualStrategyNumber:
1187 case BTGreaterStrategyNumber:
1195 /****************************************************************************
1196 * ---- ROUTINES TO DO PARTIAL INDEX PREDICATE TESTS ----
1197 ****************************************************************************/
1200 * check_partial_indexes
1201 * Check each partial index of the relation, and mark it predOK or not
1202 * depending on whether the predicate is satisfied for this query.
1205 check_partial_indexes(PlannerInfo *root, RelOptInfo *rel)
1207 List *restrictinfo_list = rel->baserestrictinfo;
1211 * Note: if Postgres tried to optimize queries by forming equivalence
1212 * classes over equi-joined attributes (i.e., if it recognized that a
1213 * qualification such as "where a.b=c.d and a.b=5" could make use of an
1214 * index on c.d), then we could use that equivalence class info here with
1215 * joininfo lists to do more complete tests for the usability of a partial
1216 * index. For now, the test only uses restriction clauses (those in
1217 * baserestrictinfo). --Nels, Dec '92
1219 * XXX as of 7.1, equivalence class info *is* available. Consider
1220 * improving this code as foreseen by Nels.
1223 foreach(ilist, rel->indexlist)
1225 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1227 if (index->indpred == NIL)
1228 continue; /* ignore non-partial indexes */
1230 index->predOK = predicate_implied_by(index->indpred,
1235 /****************************************************************************
1236 * ---- ROUTINES TO CHECK JOIN CLAUSES ----
1237 ****************************************************************************/
1240 * indexable_outerrelids
1241 * Finds all other relids that participate in any indexable join clause
1242 * for the specified table. Returns a set of relids.
1245 indexable_outerrelids(RelOptInfo *rel)
1247 Relids outer_relids = NULL;
1251 * Examine each joinclause in the joininfo list to see if it matches any
1252 * key of any index. If so, add the clause's other rels to the result.
1254 foreach(l, rel->joininfo)
1256 RestrictInfo *joininfo = (RestrictInfo *) lfirst(l);
1259 other_rels = bms_difference(joininfo->required_relids, rel->relids);
1260 if (matches_any_index(joininfo, rel, other_rels))
1261 outer_relids = bms_join(outer_relids, other_rels);
1263 bms_free(other_rels);
1266 return outer_relids;
1271 * Workhorse for indexable_outerrelids: see if a joinclause can be
1272 * matched to any index of the given rel.
1275 matches_any_index(RestrictInfo *rinfo, RelOptInfo *rel, Relids outer_relids)
1279 Assert(IsA(rinfo, RestrictInfo));
1281 if (restriction_is_or_clause(rinfo))
1283 foreach(l, ((BoolExpr *) rinfo->orclause)->args)
1285 Node *orarg = (Node *) lfirst(l);
1287 /* OR arguments should be ANDs or sub-RestrictInfos */
1288 if (and_clause(orarg))
1292 /* Recurse to examine AND items and sub-ORs */
1293 foreach(j, ((BoolExpr *) orarg)->args)
1295 RestrictInfo *arinfo = (RestrictInfo *) lfirst(j);
1297 if (matches_any_index(arinfo, rel, outer_relids))
1303 /* Recurse to examine simple clause */
1304 Assert(IsA(orarg, RestrictInfo));
1305 Assert(!restriction_is_or_clause((RestrictInfo *) orarg));
1306 if (matches_any_index((RestrictInfo *) orarg, rel,
1315 /* Normal case for a simple restriction clause */
1316 foreach(l, rel->indexlist)
1318 IndexOptInfo *index = (IndexOptInfo *) lfirst(l);
1320 Oid *families = index->opfamily;
1324 Oid curFamily = families[0];
1326 if (match_clause_to_indexcol(index,
1336 } while (!DoneMatchingIndexKeys(families));
1343 * best_inner_indexscan
1344 * Finds the best available inner indexscan for a nestloop join
1345 * with the given rel on the inside and the given outer_rel outside.
1346 * May return NULL if there are no possible inner indexscans.
1348 * We ignore ordering considerations (since a nestloop's inner scan's order
1349 * is uninteresting). Also, we consider only total cost when deciding which
1350 * of two possible paths is better --- this assumes that all indexpaths have
1351 * negligible startup cost. (True today, but someday we might have to think
1352 * harder.) Therefore, there is only one dimension of comparison and so it's
1353 * sufficient to return a single "best" path.
1355 * Note: create_index_paths() must have been run previously for this rel,
1356 * else the result will always be NULL.
1359 best_inner_indexscan(PlannerInfo *root, RelOptInfo *rel,
1360 RelOptInfo *outer_rel, JoinType jointype)
1362 Relids outer_relids;
1367 List *bitindexpaths;
1369 InnerIndexscanInfo *info;
1370 MemoryContext oldcontext;
1373 * Nestloop only supports inner, left, and IN joins.
1379 case JOIN_UNIQUE_OUTER:
1380 isouterjoin = false;
1390 * If there are no indexable joinclauses for this rel, exit quickly.
1392 if (bms_is_empty(rel->index_outer_relids))
1396 * Otherwise, we have to do path selection in the memory context of the
1397 * given rel, so that any created path can be safely attached to the rel's
1398 * cache of best inner paths. (This is not currently an issue for normal
1399 * planning, but it is an issue for GEQO planning.)
1401 oldcontext = MemoryContextSwitchTo(GetMemoryChunkContext(rel));
1404 * Intersect the given outer relids with index_outer_relids to find the
1405 * set of outer relids actually relevant for this rel. If there are none,
1406 * again we can fail immediately.
1408 outer_relids = bms_intersect(rel->index_outer_relids, outer_rel->relids);
1409 if (bms_is_empty(outer_relids))
1411 bms_free(outer_relids);
1412 MemoryContextSwitchTo(oldcontext);
1417 * Look to see if we already computed the result for this set of relevant
1418 * outerrels. (We include the isouterjoin status in the cache lookup key
1419 * for safety. In practice I suspect this is not necessary because it
1420 * should always be the same for a given innerrel.)
1422 * NOTE: because we cache on outer_relids rather than outer_rel->relids,
1423 * we will report the same path and hence path cost for joins with
1424 * different sets of irrelevant rels on the outside. Now that cost_index
1425 * is sensitive to outer_rel->rows, this is not really right. However the
1426 * error is probably not large. Is it worth establishing a separate cache
1427 * entry for each distinct outer_rel->relids set to get this right?
1429 foreach(l, rel->index_inner_paths)
1431 info = (InnerIndexscanInfo *) lfirst(l);
1432 if (bms_equal(info->other_relids, outer_relids) &&
1433 info->isouterjoin == isouterjoin)
1435 bms_free(outer_relids);
1436 MemoryContextSwitchTo(oldcontext);
1437 return info->best_innerpath;
1442 * Find all the relevant restriction and join clauses.
1444 * Note: because we include restriction clauses, we will find indexscans
1445 * that could be plain indexscans, ie, they don't require the join context
1446 * at all. This may seem redundant, but we need to include those scans in
1447 * the input given to choose_bitmap_and() to be sure we find optimal AND
1448 * combinations of join and non-join scans. Also, even if the "best inner
1449 * indexscan" is just a plain indexscan, it will have a different cost
1450 * estimate because of cache effects.
1452 clause_list = find_clauses_for_join(root, rel, outer_relids, isouterjoin);
1455 * Find all the index paths that are usable for this join, except for
1456 * stuff involving OR and ScalarArrayOpExpr clauses.
1458 indexpaths = find_usable_indexes(root, rel,
1464 * Generate BitmapOrPaths for any suitable OR-clauses present in the
1467 bitindexpaths = generate_bitmap_or_paths(root, rel,
1472 * Likewise, generate paths using ScalarArrayOpExpr clauses; these can't
1473 * be simple indexscans but they can be used in bitmap scans.
1475 bitindexpaths = list_concat(bitindexpaths,
1476 find_saop_paths(root, rel,
1481 * Include the regular index paths in bitindexpaths.
1483 bitindexpaths = list_concat(bitindexpaths, list_copy(indexpaths));
1486 * If we found anything usable, generate a BitmapHeapPath for the most
1487 * promising combination of bitmap index paths.
1489 if (bitindexpaths != NIL)
1492 BitmapHeapPath *bpath;
1494 bitmapqual = choose_bitmap_and(root, rel, bitindexpaths, outer_rel);
1495 bpath = create_bitmap_heap_path(root, rel, bitmapqual, outer_rel);
1496 indexpaths = lappend(indexpaths, bpath);
1500 * Now choose the cheapest member of indexpaths.
1503 foreach(l, indexpaths)
1505 Path *path = (Path *) lfirst(l);
1507 if (cheapest == NULL ||
1508 compare_path_costs(path, cheapest, TOTAL_COST) < 0)
1512 /* Cache the result --- whether positive or negative */
1513 info = makeNode(InnerIndexscanInfo);
1514 info->other_relids = outer_relids;
1515 info->isouterjoin = isouterjoin;
1516 info->best_innerpath = cheapest;
1517 rel->index_inner_paths = lcons(info, rel->index_inner_paths);
1519 MemoryContextSwitchTo(oldcontext);
1525 * find_clauses_for_join
1526 * Generate a list of clauses that are potentially useful for
1527 * scanning rel as the inner side of a nestloop join.
1529 * We consider both join and restriction clauses. Any joinclause that uses
1530 * only otherrels in the specified outer_relids is fair game. But there must
1531 * be at least one such joinclause in the final list, otherwise we return NIL
1532 * indicating that there isn't any potential win here.
1535 find_clauses_for_join(PlannerInfo *root, RelOptInfo *rel,
1536 Relids outer_relids, bool isouterjoin)
1538 List *clause_list = NIL;
1542 /* Look for joinclauses that are usable with given outer_relids */
1543 join_relids = bms_union(rel->relids, outer_relids);
1545 foreach(l, rel->joininfo)
1547 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1549 /* Can't use pushed-down join clauses in outer join */
1550 if (isouterjoin && rinfo->is_pushed_down)
1552 if (!bms_is_subset(rinfo->required_relids, join_relids))
1555 clause_list = lappend(clause_list, rinfo);
1558 bms_free(join_relids);
1560 /* if no join clause was matched then forget it, per comments above */
1561 if (clause_list == NIL)
1565 * We can also use any plain restriction clauses for the rel. We put
1566 * these at the front of the clause list for the convenience of
1567 * remove_redundant_join_clauses, which can never remove non-join clauses
1568 * and hence won't be able to get rid of a non-join clause if it appears
1569 * after a join clause it is redundant with.
1571 clause_list = list_concat(list_copy(rel->baserestrictinfo), clause_list);
1574 * We may now have clauses that are known redundant. Get rid of 'em.
1576 if (list_length(clause_list) > 1)
1578 clause_list = remove_redundant_join_clauses(root,
1586 /****************************************************************************
1587 * ---- ROUTINES TO HANDLE PATHKEYS ----
1588 ****************************************************************************/
1591 * match_variant_ordering
1592 * Try to match an index's ordering to the query's requested ordering
1594 * This is used when the index is ordered but a naive comparison fails to
1595 * match its ordering (pathkeys) to root->query_pathkeys. It may be that
1596 * we need to scan the index backwards. Also, a less naive comparison can
1597 * help for both forward and backward indexscans. Columns of the index
1598 * that have an equality restriction clause can be ignored in the match;
1599 * that is, an index on (x,y) can be considered to match the ordering of
1600 * ... WHERE x = 42 ORDER BY y;
1602 * Note: it would be possible to similarly ignore useless ORDER BY items;
1603 * that is, an index on just y could be considered to match the ordering of
1604 * ... WHERE x = 42 ORDER BY x, y;
1605 * But proving that this is safe would require finding a btree opfamily
1606 * containing both the = operator and the < or > operator in the ORDER BY
1607 * item. That's significantly more expensive than what we do here, since
1608 * we'd have to look at restriction clauses unrelated to the current index
1609 * and search for opfamilies without any hint from the index. The practical
1610 * use-cases seem to be mostly covered by ignoring index columns, so that's
1611 * all we do for now.
1614 * 'index' is the index of interest.
1615 * 'restrictclauses' is the list of sublists of restriction clauses
1616 * matching the columns of the index (NIL if none)
1618 * If able to match the requested query pathkeys, returns either
1619 * ForwardScanDirection or BackwardScanDirection to indicate the proper index
1620 * scan direction. If no match, returns NoMovementScanDirection.
1622 static ScanDirection
1623 match_variant_ordering(PlannerInfo *root,
1624 IndexOptInfo *index,
1625 List *restrictclauses)
1630 * Forget the whole thing if not a btree index; our check for ignorable
1631 * columns assumes we are dealing with btree opfamilies. (It'd be possible
1632 * to factor out just the try for backwards indexscan, but considering
1633 * that we presently have no orderable indexes except btrees anyway, it's
1634 * hardly worth contorting this code for that case.)
1636 * Note: if you remove this, you probably need to put in a check on
1637 * amoptionalkey to prevent possible clauseless scan on an index that
1640 if (index->relam != BTREE_AM_OID)
1641 return NoMovementScanDirection;
1644 * Figure out which index columns can be optionally ignored because they
1645 * have an equality constraint. This is the same set for either forward
1646 * or backward scan, so we do it just once.
1648 ignorables = identify_ignorable_ordering_cols(root, index,
1652 * Try to match to forward scan, then backward scan. However, we can skip
1653 * the forward-scan case if there are no ignorable columns, because
1654 * find_usable_indexes() would have found the match already.
1657 match_index_to_query_keys(root, index, ForwardScanDirection,
1659 return ForwardScanDirection;
1661 if (match_index_to_query_keys(root, index, BackwardScanDirection,
1663 return BackwardScanDirection;
1665 return NoMovementScanDirection;
1669 * identify_ignorable_ordering_cols
1670 * Determine which index columns can be ignored for ordering purposes
1672 * Returns an integer List of column numbers (1-based) of ignorable
1673 * columns. The ignorable columns are those that have equality constraints
1674 * against pseudoconstants.
1677 identify_ignorable_ordering_cols(PlannerInfo *root,
1678 IndexOptInfo *index,
1679 List *restrictclauses)
1682 int indexcol = 0; /* note this is 0-based */
1685 /* restrictclauses is either NIL or has a sublist per column */
1686 foreach(l, restrictclauses)
1688 List *sublist = (List *) lfirst(l);
1689 Oid opfamily = index->opfamily[indexcol];
1692 foreach(l2, sublist)
1694 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l2);
1695 OpExpr *clause = (OpExpr *) rinfo->clause;
1701 /* First check for boolean-index cases. */
1702 if (IsBooleanOpfamily(opfamily))
1704 if (match_boolean_index_clause((Node *) clause, indexcol,
1708 * The clause means either col = TRUE or col = FALSE; we
1709 * do not care which, it's an equality constraint either
1712 result = lappend_int(result, indexcol + 1);
1717 /* Otherwise, ignore if not a binary opclause */
1718 if (!is_opclause(clause) || list_length(clause->args) != 2)
1721 /* Determine left/right sides and check the operator */
1722 clause_op = clause->opno;
1723 if (match_index_to_operand(linitial(clause->args), indexcol,
1726 /* clause_op is correct */
1731 Assert(match_index_to_operand(lsecond(clause->args), indexcol,
1733 /* Must flip operator to get the opfamily member */
1734 clause_op = get_commutator(clause_op);
1737 if (!OidIsValid(clause_op))
1738 continue; /* ignore non match, per next comment */
1739 op_strategy = get_op_opfamily_strategy(clause_op, opfamily);
1742 * You might expect to see Assert(op_strategy != 0) here, but you
1743 * won't: the clause might contain a special indexable operator
1744 * rather than an ordinary opfamily member. Currently none of the
1745 * special operators are very likely to expand to an equality
1746 * operator; we do not bother to check, but just assume no match.
1748 if (op_strategy != BTEqualStrategyNumber)
1751 /* Now check that other side is pseudoconstant */
1753 ispc = is_pseudo_constant_clause_relids(lsecond(clause->args),
1754 rinfo->right_relids);
1756 ispc = is_pseudo_constant_clause_relids(linitial(clause->args),
1757 rinfo->left_relids);
1760 result = lappend_int(result, indexcol + 1);
1770 * match_index_to_query_keys
1771 * Check a single scan direction for "intelligent" match to query keys
1773 * 'index' is the index of interest.
1774 * 'indexscandir' is the scan direction to consider
1775 * 'ignorables' is an integer list of indexes of ignorable index columns
1777 * Returns TRUE on successful match (ie, the query_pathkeys can be considered
1778 * to match this index).
1781 match_index_to_query_keys(PlannerInfo *root,
1782 IndexOptInfo *index,
1783 ScanDirection indexscandir,
1786 List *index_pathkeys;
1787 ListCell *index_cell;
1791 /* Get the pathkeys that exactly describe the index */
1792 index_pathkeys = build_index_pathkeys(root, index, indexscandir, false);
1795 * Can we match to the query's requested pathkeys? The inner loop skips
1796 * over ignorable index columns while trying to match.
1798 index_cell = list_head(index_pathkeys);
1801 foreach(r, root->query_pathkeys)
1803 List *rsubkey = (List *) lfirst(r);
1809 if (index_cell == NULL)
1811 isubkey = (List *) lfirst(index_cell);
1812 index_cell = lnext(index_cell);
1813 index_col++; /* index_col is now 1-based */
1816 * Since we are dealing with canonicalized pathkeys, pointer
1817 * comparison is sufficient to determine a match.
1819 if (rsubkey == isubkey)
1820 break; /* matched current query pathkey */
1822 if (!list_member_int(ignorables, index_col))
1823 return false; /* definite failure to match */
1824 /* otherwise loop around and try to match to next index col */
1831 /****************************************************************************
1832 * ---- PATH CREATION UTILITIES ----
1833 ****************************************************************************/
1836 * flatten_clausegroups_list
1837 * Given a list of lists of RestrictInfos, flatten it to a list
1840 * This is used to flatten out the result of group_clauses_by_indexkey()
1841 * to produce an indexclauses list. The original list structure mustn't
1842 * be altered, but it's OK to share copies of the underlying RestrictInfos.
1845 flatten_clausegroups_list(List *clausegroups)
1847 List *allclauses = NIL;
1850 foreach(l, clausegroups)
1851 allclauses = list_concat(allclauses, list_copy((List *) lfirst(l)));
1856 /****************************************************************************
1857 * ---- ROUTINES TO CHECK OPERANDS ----
1858 ****************************************************************************/
1861 * match_index_to_operand()
1862 * Generalized test for a match between an index's key
1863 * and the operand on one side of a restriction or join clause.
1865 * operand: the nodetree to be compared to the index
1866 * indexcol: the column number of the index (counting from 0)
1867 * index: the index of interest
1870 match_index_to_operand(Node *operand,
1872 IndexOptInfo *index)
1877 * Ignore any RelabelType node above the operand. This is needed to be
1878 * able to apply indexscanning in binary-compatible-operator cases. Note:
1879 * we can assume there is at most one RelabelType node;
1880 * eval_const_expressions() will have simplified if more than one.
1882 if (operand && IsA(operand, RelabelType))
1883 operand = (Node *) ((RelabelType *) operand)->arg;
1885 indkey = index->indexkeys[indexcol];
1889 * Simple index column; operand must be a matching Var.
1891 if (operand && IsA(operand, Var) &&
1892 index->rel->relid == ((Var *) operand)->varno &&
1893 indkey == ((Var *) operand)->varattno)
1899 * Index expression; find the correct expression. (This search could
1900 * be avoided, at the cost of complicating all the callers of this
1901 * routine; doesn't seem worth it.)
1903 ListCell *indexpr_item;
1907 indexpr_item = list_head(index->indexprs);
1908 for (i = 0; i < indexcol; i++)
1910 if (index->indexkeys[i] == 0)
1912 if (indexpr_item == NULL)
1913 elog(ERROR, "wrong number of index expressions");
1914 indexpr_item = lnext(indexpr_item);
1917 if (indexpr_item == NULL)
1918 elog(ERROR, "wrong number of index expressions");
1919 indexkey = (Node *) lfirst(indexpr_item);
1922 * Does it match the operand? Again, strip any relabeling.
1924 if (indexkey && IsA(indexkey, RelabelType))
1925 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
1927 if (equal(indexkey, operand))
1934 /****************************************************************************
1935 * ---- ROUTINES FOR "SPECIAL" INDEXABLE OPERATORS ----
1936 ****************************************************************************/
1939 * These routines handle special optimization of operators that can be
1940 * used with index scans even though they are not known to the executor's
1941 * indexscan machinery. The key idea is that these operators allow us
1942 * to derive approximate indexscan qual clauses, such that any tuples
1943 * that pass the operator clause itself must also satisfy the simpler
1944 * indexscan condition(s). Then we can use the indexscan machinery
1945 * to avoid scanning as much of the table as we'd otherwise have to,
1946 * while applying the original operator as a qpqual condition to ensure
1947 * we deliver only the tuples we want. (In essence, we're using a regular
1948 * index as if it were a lossy index.)
1950 * An example of what we're doing is
1951 * textfield LIKE 'abc%'
1952 * from which we can generate the indexscanable conditions
1953 * textfield >= 'abc' AND textfield < 'abd'
1954 * which allow efficient scanning of an index on textfield.
1955 * (In reality, character set and collation issues make the transformation
1956 * from LIKE to indexscan limits rather harder than one might think ...
1957 * but that's the basic idea.)
1959 * Another thing that we do with this machinery is to provide special
1960 * smarts for "boolean" indexes (that is, indexes on boolean columns
1961 * that support boolean equality). We can transform a plain reference
1962 * to the indexkey into "indexkey = true", or "NOT indexkey" into
1963 * "indexkey = false", so as to make the expression indexable using the
1964 * regular index operators. (As of Postgres 8.1, we must do this here
1965 * because constant simplification does the reverse transformation;
1966 * without this code there'd be no way to use such an index at all.)
1968 * Three routines are provided here:
1970 * match_special_index_operator() is just an auxiliary function for
1971 * match_clause_to_indexcol(); after the latter fails to recognize a
1972 * restriction opclause's operator as a member of an index's opfamily,
1973 * it asks match_special_index_operator() whether the clause should be
1974 * considered an indexqual anyway.
1976 * match_boolean_index_clause() similarly detects clauses that can be
1977 * converted into boolean equality operators.
1979 * expand_indexqual_conditions() converts a list of lists of RestrictInfo
1980 * nodes (with implicit AND semantics across list elements) into
1981 * a list of clauses that the executor can actually handle. For operators
1982 * that are members of the index's opfamily this transformation is a no-op,
1983 * but clauses recognized by match_special_index_operator() or
1984 * match_boolean_index_clause() must be converted into one or more "regular"
1985 * indexqual conditions.
1990 * match_boolean_index_clause
1991 * Recognize restriction clauses that can be matched to a boolean index.
1993 * This should be called only when IsBooleanOpfamily() recognizes the
1994 * index's operator family. We check to see if the clause matches the
1998 match_boolean_index_clause(Node *clause,
2000 IndexOptInfo *index)
2003 if (match_index_to_operand(clause, indexcol, index))
2006 if (not_clause(clause))
2008 if (match_index_to_operand((Node *) get_notclausearg((Expr *) clause),
2014 * Since we only consider clauses at top level of WHERE, we can convert
2015 * indexkey IS TRUE and indexkey IS FALSE to index searches as well. The
2016 * different meaning for NULL isn't important.
2018 else if (clause && IsA(clause, BooleanTest))
2020 BooleanTest *btest = (BooleanTest *) clause;
2022 if (btest->booltesttype == IS_TRUE ||
2023 btest->booltesttype == IS_FALSE)
2024 if (match_index_to_operand((Node *) btest->arg,
2032 * match_special_index_operator
2033 * Recognize restriction clauses that can be used to generate
2034 * additional indexscanable qualifications.
2036 * The given clause is already known to be a binary opclause having
2037 * the form (indexkey OP pseudoconst) or (pseudoconst OP indexkey),
2038 * but the OP proved not to be one of the index's opfamily operators.
2039 * Return 'true' if we can do something with it anyway.
2042 match_special_index_operator(Expr *clause, Oid opfamily,
2043 bool indexkey_on_left)
2045 bool isIndexable = false;
2049 Const *prefix = NULL;
2053 * Currently, all known special operators require the indexkey on the
2054 * left, but this test could be pushed into the switch statement if some
2055 * are added that do not...
2057 if (!indexkey_on_left)
2060 /* we know these will succeed */
2061 rightop = get_rightop(clause);
2062 expr_op = ((OpExpr *) clause)->opno;
2064 /* again, required for all current special ops: */
2065 if (!IsA(rightop, Const) ||
2066 ((Const *) rightop)->constisnull)
2068 patt = (Const *) rightop;
2072 case OID_TEXT_LIKE_OP:
2073 case OID_BPCHAR_LIKE_OP:
2074 case OID_NAME_LIKE_OP:
2075 /* the right-hand const is type text for all of these */
2076 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like,
2077 &prefix, &rest) != Pattern_Prefix_None;
2080 case OID_BYTEA_LIKE_OP:
2081 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like,
2082 &prefix, &rest) != Pattern_Prefix_None;
2085 case OID_TEXT_ICLIKE_OP:
2086 case OID_BPCHAR_ICLIKE_OP:
2087 case OID_NAME_ICLIKE_OP:
2088 /* the right-hand const is type text for all of these */
2089 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like_IC,
2090 &prefix, &rest) != Pattern_Prefix_None;
2093 case OID_TEXT_REGEXEQ_OP:
2094 case OID_BPCHAR_REGEXEQ_OP:
2095 case OID_NAME_REGEXEQ_OP:
2096 /* the right-hand const is type text for all of these */
2097 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Regex,
2098 &prefix, &rest) != Pattern_Prefix_None;
2101 case OID_TEXT_ICREGEXEQ_OP:
2102 case OID_BPCHAR_ICREGEXEQ_OP:
2103 case OID_NAME_ICREGEXEQ_OP:
2104 /* the right-hand const is type text for all of these */
2105 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Regex_IC,
2106 &prefix, &rest) != Pattern_Prefix_None;
2109 case OID_INET_SUB_OP:
2110 case OID_INET_SUBEQ_OP:
2117 pfree(DatumGetPointer(prefix->constvalue));
2121 /* done if the expression doesn't look indexable */
2126 * Must also check that index's opfamily supports the operators we will
2127 * want to apply. (A hash index, for example, will not support ">=".)
2128 * Currently, only btree supports the operators we need.
2130 * We insist on the opfamily being the specific one we expect, else we'd do
2131 * the wrong thing if someone were to make a reverse-sort opfamily with the
2136 case OID_TEXT_LIKE_OP:
2137 case OID_TEXT_ICLIKE_OP:
2138 case OID_TEXT_REGEXEQ_OP:
2139 case OID_TEXT_ICREGEXEQ_OP:
2141 (opfamily == TEXT_PATTERN_BTREE_FAM_OID) ||
2142 (opfamily == TEXT_BTREE_FAM_OID && lc_collate_is_c());
2145 case OID_BPCHAR_LIKE_OP:
2146 case OID_BPCHAR_ICLIKE_OP:
2147 case OID_BPCHAR_REGEXEQ_OP:
2148 case OID_BPCHAR_ICREGEXEQ_OP:
2150 (opfamily == BPCHAR_PATTERN_BTREE_FAM_OID) ||
2151 (opfamily == BPCHAR_BTREE_FAM_OID && lc_collate_is_c());
2154 case OID_NAME_LIKE_OP:
2155 case OID_NAME_ICLIKE_OP:
2156 case OID_NAME_REGEXEQ_OP:
2157 case OID_NAME_ICREGEXEQ_OP:
2159 (opfamily == NAME_PATTERN_BTREE_FAM_OID) ||
2160 (opfamily == NAME_BTREE_FAM_OID && lc_collate_is_c());
2163 case OID_BYTEA_LIKE_OP:
2164 isIndexable = (opfamily == BYTEA_BTREE_FAM_OID);
2167 case OID_INET_SUB_OP:
2168 case OID_INET_SUBEQ_OP:
2169 isIndexable = (opfamily == NETWORK_BTREE_FAM_OID);
2177 * expand_indexqual_conditions
2178 * Given a list of sublists of RestrictInfo nodes, produce a flat list
2179 * of index qual clauses. Standard qual clauses (those in the index's
2180 * opfamily) are passed through unchanged. Boolean clauses and "special"
2181 * index operators are expanded into clauses that the indexscan machinery
2182 * will know what to do with. RowCompare clauses are simplified if
2183 * necessary to create a clause that is fully checkable by the index.
2185 * The input list is ordered by index key, and so the output list is too.
2186 * (The latter is not depended on by any part of the core planner, I believe,
2187 * but parts of the executor require it, and so do the amcostestimate
2191 expand_indexqual_conditions(IndexOptInfo *index, List *clausegroups)
2193 List *resultquals = NIL;
2194 ListCell *clausegroup_item;
2196 Oid *families = index->opfamily;
2198 if (clausegroups == NIL)
2201 clausegroup_item = list_head(clausegroups);
2204 Oid curFamily = families[0];
2207 foreach(l, (List *) lfirst(clausegroup_item))
2209 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2210 Expr *clause = rinfo->clause;
2212 /* First check for boolean cases */
2213 if (IsBooleanOpfamily(curFamily))
2217 boolqual = expand_boolean_index_clause((Node *) clause,
2222 resultquals = lappend(resultquals,
2223 make_restrictinfo(boolqual,
2233 * Else it must be an opclause (usual case), ScalarArrayOp, or
2236 if (is_opclause(clause))
2238 resultquals = list_concat(resultquals,
2239 expand_indexqual_opclause(rinfo,
2242 else if (IsA(clause, ScalarArrayOpExpr))
2244 /* no extra work at this time */
2245 resultquals = lappend(resultquals, rinfo);
2247 else if (IsA(clause, RowCompareExpr))
2249 resultquals = lappend(resultquals,
2250 expand_indexqual_rowcompare(rinfo,
2255 elog(ERROR, "unsupported indexqual type: %d",
2256 (int) nodeTag(clause));
2259 clausegroup_item = lnext(clausegroup_item);
2263 } while (clausegroup_item != NULL && !DoneMatchingIndexKeys(families));
2265 Assert(clausegroup_item == NULL); /* else more groups than indexkeys */
2271 * expand_boolean_index_clause
2272 * Convert a clause recognized by match_boolean_index_clause into
2273 * a boolean equality operator clause.
2275 * Returns NULL if the clause isn't a boolean index qual.
2278 expand_boolean_index_clause(Node *clause,
2280 IndexOptInfo *index)
2283 if (match_index_to_operand(clause, indexcol, index))
2285 /* convert to indexkey = TRUE */
2286 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2288 (Expr *) makeBoolConst(true, false));
2291 if (not_clause(clause))
2293 Node *arg = (Node *) get_notclausearg((Expr *) clause);
2295 /* It must have matched the indexkey */
2296 Assert(match_index_to_operand(arg, indexcol, index));
2297 /* convert to indexkey = FALSE */
2298 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2300 (Expr *) makeBoolConst(false, false));
2302 if (clause && IsA(clause, BooleanTest))
2304 BooleanTest *btest = (BooleanTest *) clause;
2305 Node *arg = (Node *) btest->arg;
2307 /* It must have matched the indexkey */
2308 Assert(match_index_to_operand(arg, indexcol, index));
2309 if (btest->booltesttype == IS_TRUE)
2311 /* convert to indexkey = TRUE */
2312 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2314 (Expr *) makeBoolConst(true, false));
2316 if (btest->booltesttype == IS_FALSE)
2318 /* convert to indexkey = FALSE */
2319 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2321 (Expr *) makeBoolConst(false, false));
2331 * expand_indexqual_opclause --- expand a single indexqual condition
2332 * that is an operator clause
2334 * The input is a single RestrictInfo, the output a list of RestrictInfos
2337 expand_indexqual_opclause(RestrictInfo *rinfo, Oid opfamily)
2339 Expr *clause = rinfo->clause;
2341 /* we know these will succeed */
2342 Node *leftop = get_leftop(clause);
2343 Node *rightop = get_rightop(clause);
2344 Oid expr_op = ((OpExpr *) clause)->opno;
2345 Const *patt = (Const *) rightop;
2346 Const *prefix = NULL;
2348 Pattern_Prefix_Status pstatus;
2354 * LIKE and regex operators are not members of any index opfamily,
2355 * so if we find one in an indexqual list we can assume that it
2356 * was accepted by match_special_index_operator().
2358 case OID_TEXT_LIKE_OP:
2359 case OID_BPCHAR_LIKE_OP:
2360 case OID_NAME_LIKE_OP:
2361 case OID_BYTEA_LIKE_OP:
2362 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Like,
2364 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2367 case OID_TEXT_ICLIKE_OP:
2368 case OID_BPCHAR_ICLIKE_OP:
2369 case OID_NAME_ICLIKE_OP:
2370 /* the right-hand const is type text for all of these */
2371 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Like_IC,
2373 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2376 case OID_TEXT_REGEXEQ_OP:
2377 case OID_BPCHAR_REGEXEQ_OP:
2378 case OID_NAME_REGEXEQ_OP:
2379 /* the right-hand const is type text for all of these */
2380 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Regex,
2382 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2385 case OID_TEXT_ICREGEXEQ_OP:
2386 case OID_BPCHAR_ICREGEXEQ_OP:
2387 case OID_NAME_ICREGEXEQ_OP:
2388 /* the right-hand const is type text for all of these */
2389 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Regex_IC,
2391 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2394 case OID_INET_SUB_OP:
2395 case OID_INET_SUBEQ_OP:
2396 result = network_prefix_quals(leftop, expr_op, opfamily,
2401 result = list_make1(rinfo);
2409 * expand_indexqual_rowcompare --- expand a single indexqual condition
2410 * that is a RowCompareExpr
2412 * It's already known that the first column of the row comparison matches
2413 * the specified column of the index. We can use additional columns of the
2414 * row comparison as index qualifications, so long as they match the index
2415 * in the "same direction", ie, the indexkeys are all on the same side of the
2416 * clause and the operators are all the same-type members of the opfamilies.
2417 * If all the columns of the RowCompareExpr match in this way, we just use it
2418 * as-is. Otherwise, we build a shortened RowCompareExpr (if more than one
2419 * column matches) or a simple OpExpr (if the first-column match is all
2420 * there is). In these cases the modified clause is always "<=" or ">="
2421 * even when the original was "<" or ">" --- this is necessary to match all
2422 * the rows that could match the original. (We are essentially building a
2423 * lossy version of the row comparison when we do this.)
2425 static RestrictInfo *
2426 expand_indexqual_rowcompare(RestrictInfo *rinfo,
2427 IndexOptInfo *index,
2430 RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
2442 ListCell *largs_cell;
2443 ListCell *rargs_cell;
2444 ListCell *opnos_cell;
2446 /* We have to figure out (again) how the first col matches */
2447 var_on_left = match_index_to_operand((Node *) linitial(clause->largs),
2449 Assert(var_on_left ||
2450 match_index_to_operand((Node *) linitial(clause->rargs),
2452 expr_op = linitial_oid(clause->opnos);
2454 expr_op = get_commutator(expr_op);
2455 get_op_opfamily_properties(expr_op, index->opfamily[indexcol],
2460 /* Build lists of the opfamilies and operator datatypes in case needed */
2461 opfamilies = list_make1_oid(index->opfamily[indexcol]);
2462 lefttypes = list_make1_oid(op_lefttype);
2463 righttypes = list_make1_oid(op_righttype);
2466 * See how many of the remaining columns match some index column in the
2467 * same way. A note about rel membership tests: we assume that the clause
2468 * as a whole is already known to use only Vars from the indexed relation
2469 * and possibly some acceptable outer relations. So the "other" side of
2470 * any potential index condition is OK as long as it doesn't use Vars from
2471 * the indexed relation.
2474 largs_cell = lnext(list_head(clause->largs));
2475 rargs_cell = lnext(list_head(clause->rargs));
2476 opnos_cell = lnext(list_head(clause->opnos));
2478 while (largs_cell != NULL)
2484 expr_op = lfirst_oid(opnos_cell);
2487 varop = (Node *) lfirst(largs_cell);
2488 constop = (Node *) lfirst(rargs_cell);
2492 varop = (Node *) lfirst(rargs_cell);
2493 constop = (Node *) lfirst(largs_cell);
2494 /* indexkey is on right, so commute the operator */
2495 expr_op = get_commutator(expr_op);
2496 if (expr_op == InvalidOid)
2497 break; /* operator is not usable */
2499 if (bms_is_member(index->rel->relid, pull_varnos(constop)))
2500 break; /* no good, Var on wrong side */
2501 if (contain_volatile_functions(constop))
2502 break; /* no good, volatile comparison value */
2505 * The Var side can match any column of the index. If the user does
2506 * something weird like having multiple identical index columns, we
2507 * insist the match be on the first such column, to avoid confusing
2510 for (i = 0; i < index->ncolumns; i++)
2512 if (match_index_to_operand(varop, i, index))
2515 if (i >= index->ncolumns)
2516 break; /* no match found */
2518 /* Now, do we have the right operator for this column? */
2519 if (get_op_opfamily_strategy(expr_op, index->opfamily[i])
2523 /* Add opfamily and datatypes to lists */
2524 get_op_opfamily_properties(expr_op, index->opfamily[i],
2529 opfamilies = lappend_oid(opfamilies, index->opfamily[i]);
2530 lefttypes = lappend_oid(lefttypes, op_lefttype);
2531 righttypes = lappend_oid(righttypes, op_righttype);
2533 /* This column matches, keep scanning */
2535 largs_cell = lnext(largs_cell);
2536 rargs_cell = lnext(rargs_cell);
2537 opnos_cell = lnext(opnos_cell);
2540 /* Return clause as-is if it's all usable as index quals */
2541 if (matching_cols == list_length(clause->opnos))
2545 * We have to generate a subset rowcompare (possibly just one OpExpr). The
2546 * painful part of this is changing < to <= or > to >=, so deal with that
2549 if (op_strategy == BTLessEqualStrategyNumber ||
2550 op_strategy == BTGreaterEqualStrategyNumber)
2552 /* easy, just use the same operators */
2553 new_ops = list_truncate(list_copy(clause->opnos), matching_cols);
2557 ListCell *opfamilies_cell;
2558 ListCell *lefttypes_cell;
2559 ListCell *righttypes_cell;
2561 if (op_strategy == BTLessStrategyNumber)
2562 op_strategy = BTLessEqualStrategyNumber;
2563 else if (op_strategy == BTGreaterStrategyNumber)
2564 op_strategy = BTGreaterEqualStrategyNumber;
2566 elog(ERROR, "unexpected strategy number %d", op_strategy);
2568 lefttypes_cell = list_head(lefttypes);
2569 righttypes_cell = list_head(righttypes);
2570 foreach(opfamilies_cell, opfamilies)
2572 Oid opfam = lfirst_oid(opfamilies_cell);
2573 Oid lefttype = lfirst_oid(lefttypes_cell);
2574 Oid righttype = lfirst_oid(righttypes_cell);
2576 expr_op = get_opfamily_member(opfam, lefttype, righttype,
2578 if (!OidIsValid(expr_op)) /* should not happen */
2579 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
2580 op_strategy, lefttype, righttype, opfam);
2583 expr_op = get_commutator(expr_op);
2584 if (!OidIsValid(expr_op)) /* should not happen */
2585 elog(ERROR, "could not find commutator of member %d(%u,%u) of opfamily %u",
2586 op_strategy, lefttype, righttype, opfam);
2588 new_ops = lappend_oid(new_ops, expr_op);
2590 lefttypes_cell = lnext(lefttypes_cell);
2591 righttypes_cell = lnext(righttypes_cell);
2594 /* If we have more than one matching col, create a subset rowcompare */
2595 if (matching_cols > 1)
2597 RowCompareExpr *rc = makeNode(RowCompareExpr);
2600 rc->rctype = (RowCompareType) op_strategy;
2602 rc->rctype = (op_strategy == BTLessEqualStrategyNumber) ?
2603 ROWCOMPARE_GE : ROWCOMPARE_LE;
2604 rc->opnos = new_ops;
2605 rc->opfamilies = list_truncate(list_copy(clause->opfamilies),
2607 rc->largs = list_truncate((List *) copyObject(clause->largs),
2609 rc->rargs = list_truncate((List *) copyObject(clause->rargs),
2611 return make_restrictinfo((Expr *) rc, true, false, false, NULL);
2617 opexpr = make_opclause(linitial_oid(new_ops), BOOLOID, false,
2618 copyObject(linitial(clause->largs)),
2619 copyObject(linitial(clause->rargs)));
2620 return make_restrictinfo(opexpr, true, false, false, NULL);
2625 * Given a fixed prefix that all the "leftop" values must have,
2626 * generate suitable indexqual condition(s). opfamily is the index
2627 * operator family; we use it to deduce the appropriate comparison
2628 * operators and operand datatypes.
2631 prefix_quals(Node *leftop, Oid opfamily,
2632 Const *prefix_const, Pattern_Prefix_Status pstatus)
2640 Assert(pstatus != Pattern_Prefix_None);
2644 case TEXT_BTREE_FAM_OID:
2645 case TEXT_PATTERN_BTREE_FAM_OID:
2649 case BPCHAR_BTREE_FAM_OID:
2650 case BPCHAR_PATTERN_BTREE_FAM_OID:
2651 datatype = BPCHAROID;
2654 case NAME_BTREE_FAM_OID:
2655 case NAME_PATTERN_BTREE_FAM_OID:
2659 case BYTEA_BTREE_FAM_OID:
2660 datatype = BYTEAOID;
2664 /* shouldn't get here */
2665 elog(ERROR, "unexpected opfamily: %u", opfamily);
2670 * If necessary, coerce the prefix constant to the right type. The given
2671 * prefix constant is either text or bytea type.
2673 if (prefix_const->consttype != datatype)
2677 switch (prefix_const->consttype)
2680 prefix = DatumGetCString(DirectFunctionCall1(textout,
2681 prefix_const->constvalue));
2684 prefix = DatumGetCString(DirectFunctionCall1(byteaout,
2685 prefix_const->constvalue));
2688 elog(ERROR, "unexpected const type: %u",
2689 prefix_const->consttype);
2692 prefix_const = string_to_const(prefix, datatype);
2697 * If we found an exact-match pattern, generate an "=" indexqual.
2699 if (pstatus == Pattern_Prefix_Exact)
2701 oproid = get_opfamily_member(opfamily, datatype, datatype,
2702 BTEqualStrategyNumber);
2703 if (oproid == InvalidOid)
2704 elog(ERROR, "no = operator for opfamily %u", opfamily);
2705 expr = make_opclause(oproid, BOOLOID, false,
2706 (Expr *) leftop, (Expr *) prefix_const);
2707 result = list_make1(make_restrictinfo(expr, true, false, false, NULL));
2712 * Otherwise, we have a nonempty required prefix of the values.
2714 * We can always say "x >= prefix".
2716 oproid = get_opfamily_member(opfamily, datatype, datatype,
2717 BTGreaterEqualStrategyNumber);
2718 if (oproid == InvalidOid)
2719 elog(ERROR, "no >= operator for opfamily %u", opfamily);
2720 expr = make_opclause(oproid, BOOLOID, false,
2721 (Expr *) leftop, (Expr *) prefix_const);
2722 result = list_make1(make_restrictinfo(expr, true, false, false, NULL));
2725 * If we can create a string larger than the prefix, we can say
2729 greaterstr = make_greater_string(prefix_const);
2732 oproid = get_opfamily_member(opfamily, datatype, datatype,
2733 BTLessStrategyNumber);
2734 if (oproid == InvalidOid)
2735 elog(ERROR, "no < operator for opfamily %u", opfamily);
2736 expr = make_opclause(oproid, BOOLOID, false,
2737 (Expr *) leftop, (Expr *) greaterstr);
2738 result = lappend(result,
2739 make_restrictinfo(expr, true, false, false, NULL));
2746 * Given a leftop and a rightop, and a inet-family sup/sub operator,
2747 * generate suitable indexqual condition(s). expr_op is the original
2748 * operator, and opfamily is the index opfamily.
2751 network_prefix_quals(Node *leftop, Oid expr_op, Oid opfamily, Datum rightop)
2764 case OID_INET_SUB_OP:
2768 case OID_INET_SUBEQ_OP:
2773 elog(ERROR, "unexpected operator: %u", expr_op);
2778 * create clause "key >= network_scan_first( rightop )", or ">" if the
2779 * operator disallows equality.
2783 opr1oid = get_opfamily_member(opfamily, datatype, datatype,
2784 BTGreaterEqualStrategyNumber);
2785 if (opr1oid == InvalidOid)
2786 elog(ERROR, "no >= operator for opfamily %u", opfamily);
2790 opr1oid = get_opfamily_member(opfamily, datatype, datatype,
2791 BTGreaterStrategyNumber);
2792 if (opr1oid == InvalidOid)
2793 elog(ERROR, "no > operator for opfamily %u", opfamily);
2796 opr1right = network_scan_first(rightop);
2798 expr = make_opclause(opr1oid, BOOLOID, false,
2800 (Expr *) makeConst(datatype, -1, opr1right,
2802 result = list_make1(make_restrictinfo(expr, true, false, false, NULL));
2804 /* create clause "key <= network_scan_last( rightop )" */
2806 opr2oid = get_opfamily_member(opfamily, datatype, datatype,
2807 BTLessEqualStrategyNumber);
2808 if (opr2oid == InvalidOid)
2809 elog(ERROR, "no <= operator for opfamily %u", opfamily);
2811 opr2right = network_scan_last(rightop);
2813 expr = make_opclause(opr2oid, BOOLOID, false,
2815 (Expr *) makeConst(datatype, -1, opr2right,
2817 result = lappend(result,
2818 make_restrictinfo(expr, true, false, false, NULL));
2824 * Handy subroutines for match_special_index_operator() and friends.
2828 * Generate a Datum of the appropriate type from a C string.
2829 * Note that all of the supported types are pass-by-ref, so the
2830 * returned value should be pfree'd if no longer needed.
2833 string_to_datum(const char *str, Oid datatype)
2836 * We cheat a little by assuming that textin() will do for bpchar and
2837 * varchar constants too...
2839 if (datatype == NAMEOID)
2840 return DirectFunctionCall1(namein, CStringGetDatum(str));
2841 else if (datatype == BYTEAOID)
2842 return DirectFunctionCall1(byteain, CStringGetDatum(str));
2844 return DirectFunctionCall1(textin, CStringGetDatum(str));
2848 * Generate a Const node of the appropriate type from a C string.
2851 string_to_const(const char *str, Oid datatype)
2853 Datum conval = string_to_datum(str, datatype);
2855 return makeConst(datatype, ((datatype == NAMEOID) ? NAMEDATALEN : -1),
2856 conval, false, false);