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.216 2007/01/20 20:45:39 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/pg_locale.h"
36 #include "utils/selfuncs.h"
40 * DoneMatchingIndexKeys() - MACRO
42 #define DoneMatchingIndexKeys(families) (families[0] == InvalidOid)
44 #define IsBooleanOpfamily(opfamily) \
45 ((opfamily) == BOOL_BTREE_FAM_OID || (opfamily) == BOOL_HASH_FAM_OID)
48 static List *find_usable_indexes(PlannerInfo *root, RelOptInfo *rel,
49 List *clauses, List *outer_clauses,
50 bool istoplevel, RelOptInfo *outer_rel,
51 SaOpControl saop_control);
52 static List *find_saop_paths(PlannerInfo *root, RelOptInfo *rel,
53 List *clauses, List *outer_clauses,
54 bool istoplevel, RelOptInfo *outer_rel);
55 static Path *choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel,
56 List *paths, RelOptInfo *outer_rel);
57 static int bitmap_path_comparator(const void *a, const void *b);
58 static Cost bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel,
59 List *paths, RelOptInfo *outer_rel);
60 static List *pull_indexpath_quals(Path *bitmapqual);
61 static bool lists_intersect_ptr(List *list1, List *list2);
62 static bool match_clause_to_indexcol(IndexOptInfo *index,
63 int indexcol, Oid opfamily,
66 SaOpControl saop_control);
67 static bool is_indexable_operator(Oid expr_op, Oid opfamily,
68 bool indexkey_on_left);
69 static bool match_rowcompare_to_indexcol(IndexOptInfo *index,
72 RowCompareExpr *clause,
74 static Relids indexable_outerrelids(PlannerInfo *root, RelOptInfo *rel);
75 static bool matches_any_index(RestrictInfo *rinfo, RelOptInfo *rel,
77 static List *find_clauses_for_join(PlannerInfo *root, RelOptInfo *rel,
78 Relids outer_relids, bool isouterjoin);
79 static bool match_boolean_index_clause(Node *clause, int indexcol,
81 static bool match_special_index_operator(Expr *clause, Oid opfamily,
82 bool indexkey_on_left);
83 static Expr *expand_boolean_index_clause(Node *clause, int indexcol,
85 static List *expand_indexqual_opclause(RestrictInfo *rinfo, Oid opfamily);
86 static RestrictInfo *expand_indexqual_rowcompare(RestrictInfo *rinfo,
89 static List *prefix_quals(Node *leftop, Oid opfamily,
90 Const *prefix, Pattern_Prefix_Status pstatus);
91 static List *network_prefix_quals(Node *leftop, Oid expr_op, Oid opfamily,
93 static Datum string_to_datum(const char *str, Oid datatype);
94 static Const *string_to_const(const char *str, Oid datatype);
98 * create_index_paths()
99 * Generate all interesting index paths for the given relation.
100 * Candidate paths are added to the rel's pathlist (using add_path).
102 * To be considered for an index scan, an index must match one or more
103 * restriction clauses or join clauses from the query's qual condition,
104 * or match the query's ORDER BY condition, or have a predicate that
105 * matches the query's qual condition.
107 * There are two basic kinds of index scans. A "plain" index scan uses
108 * only restriction clauses (possibly none at all) in its indexqual,
109 * so it can be applied in any context. An "innerjoin" index scan uses
110 * join clauses (plus restriction clauses, if available) in its indexqual.
111 * Therefore it can only be used as the inner relation of a nestloop
112 * join against an outer rel that includes all the other rels mentioned
113 * in its join clauses. In that context, values for the other rels'
114 * attributes are available and fixed during any one scan of the indexpath.
116 * An IndexPath is generated and submitted to add_path() for each plain index
117 * scan this routine deems potentially interesting for the current query.
119 * We also determine the set of other relids that participate in join
120 * clauses that could be used with each index. The actually best innerjoin
121 * path will be generated for each outer relation later on, but knowing the
122 * set of potential otherrels allows us to identify equivalent outer relations
123 * and avoid repeated computation.
125 * 'rel' is the relation for which we want to generate index paths
127 * Note: check_partial_indexes() must have been run previously for this rel.
130 create_index_paths(PlannerInfo *root, RelOptInfo *rel)
136 /* Skip the whole mess if no indexes */
137 if (rel->indexlist == NIL)
139 rel->index_outer_relids = NULL;
144 * Examine join clauses to see which ones are potentially usable with
145 * indexes of this rel, and generate the set of all other relids that
146 * participate in such join clauses. We'll use this set later to
147 * recognize outer rels that are equivalent for joining purposes.
149 rel->index_outer_relids = indexable_outerrelids(root, rel);
152 * Find all the index paths that are directly usable for this relation
153 * (ie, are valid without considering OR or JOIN clauses).
155 indexpaths = find_usable_indexes(root, rel,
156 rel->baserestrictinfo, NIL,
157 true, NULL, SAOP_FORBID);
160 * We can submit them all to add_path. (This generates access paths for
161 * plain IndexScan plans.) However, for the next step we will only want
162 * the ones that have some selectivity; we must discard anything that was
163 * generated solely for ordering purposes.
166 foreach(l, indexpaths)
168 IndexPath *ipath = (IndexPath *) lfirst(l);
170 add_path(rel, (Path *) ipath);
172 if (ipath->indexselectivity < 1.0 &&
173 !ScanDirectionIsBackward(ipath->indexscandir))
174 bitindexpaths = lappend(bitindexpaths, ipath);
178 * Generate BitmapOrPaths for any suitable OR-clauses present in the
179 * restriction list. Add these to bitindexpaths.
181 indexpaths = generate_bitmap_or_paths(root, rel,
182 rel->baserestrictinfo, NIL,
184 bitindexpaths = list_concat(bitindexpaths, indexpaths);
187 * Likewise, generate paths using ScalarArrayOpExpr clauses; these can't
188 * be simple indexscans but they can be used in bitmap scans.
190 indexpaths = find_saop_paths(root, rel,
191 rel->baserestrictinfo, NIL,
193 bitindexpaths = list_concat(bitindexpaths, indexpaths);
196 * If we found anything usable, generate a BitmapHeapPath for the most
197 * promising combination of bitmap index paths.
199 if (bitindexpaths != NIL)
202 BitmapHeapPath *bpath;
204 bitmapqual = choose_bitmap_and(root, rel, bitindexpaths, NULL);
205 bpath = create_bitmap_heap_path(root, rel, bitmapqual, NULL);
206 add_path(rel, (Path *) bpath);
212 * find_usable_indexes
213 * Given a list of restriction clauses, find all the potentially usable
214 * indexes for the given relation, and return a list of IndexPaths.
216 * The caller actually supplies two lists of restriction clauses: some
217 * "current" ones and some "outer" ones. Both lists can be used freely
218 * to match keys of the index, but an index must use at least one of the
219 * "current" clauses to be considered usable. The motivation for this is
221 * WHERE (x = 42) AND (... OR (y = 52 AND z = 77) OR ....)
222 * While we are considering the y/z subclause of the OR, we can use "x = 42"
223 * as one of the available index conditions; but we shouldn't match the
224 * subclause to any index on x alone, because such a Path would already have
225 * been generated at the upper level. So we could use an index on x,y,z
226 * or an index on x,y for the OR subclause, but not an index on just x.
227 * When dealing with a partial index, a match of the index predicate to
228 * one of the "current" clauses also makes the index usable.
230 * If istoplevel is true (indicating we are considering the top level of a
231 * rel's restriction clauses), we will include indexes in the result that
232 * have an interesting sort order, even if they have no matching restriction
235 * 'rel' is the relation for which we want to generate index paths
236 * 'clauses' is the current list of clauses (RestrictInfo nodes)
237 * 'outer_clauses' is the list of additional upper-level clauses
238 * 'istoplevel' is true if clauses are the rel's top-level restriction list
239 * (outer_clauses must be NIL when this is true)
240 * 'outer_rel' is the outer side of the join if forming an inner indexscan
241 * (so some of the given clauses are join clauses); NULL if not
242 * 'saop_control' indicates whether ScalarArrayOpExpr clauses can be used
244 * Note: check_partial_indexes() must have been run previously.
248 find_usable_indexes(PlannerInfo *root, RelOptInfo *rel,
249 List *clauses, List *outer_clauses,
250 bool istoplevel, RelOptInfo *outer_rel,
251 SaOpControl saop_control)
253 Relids outer_relids = outer_rel ? outer_rel->relids : NULL;
255 List *all_clauses = NIL; /* not computed till needed */
258 foreach(ilist, rel->indexlist)
260 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
262 List *restrictclauses;
263 List *index_pathkeys;
264 List *useful_pathkeys;
265 bool useful_predicate;
267 bool index_is_ordered;
270 * Ignore partial indexes that do not match the query. If a partial
271 * index is marked predOK then we know it's OK; otherwise, if we are
272 * at top level we know it's not OK (since predOK is exactly whether
273 * its predicate could be proven from the toplevel clauses).
274 * Otherwise, we have to test whether the added clauses are sufficient
275 * to imply the predicate. If so, we could use the index in the
278 * We set useful_predicate to true iff the predicate was proven using
279 * the current set of clauses. This is needed to prevent matching a
280 * predOK index to an arm of an OR, which would be a legal but
281 * pointlessly inefficient plan. (A better plan will be generated by
282 * just scanning the predOK index alone, no OR.)
284 useful_predicate = false;
285 if (index->indpred != NIL)
291 /* we know predicate was proven from these clauses */
292 useful_predicate = true;
298 continue; /* no point in trying to prove it */
300 /* Form all_clauses if not done already */
301 if (all_clauses == NIL)
302 all_clauses = list_concat(list_copy(clauses),
305 if (!predicate_implied_by(index->indpred, all_clauses))
306 continue; /* can't use it at all */
308 if (!predicate_implied_by(index->indpred, outer_clauses))
309 useful_predicate = true;
314 * 1. Match the index against the available restriction clauses.
315 * found_clause is set true only if at least one of the current
316 * clauses was used (and, if saop_control is SAOP_REQUIRE, it has to
317 * have been a ScalarArrayOpExpr clause).
319 restrictclauses = group_clauses_by_indexkey(index,
327 * Not all index AMs support scans with no restriction clauses. We
328 * can't generate a scan over an index with amoptionalkey = false
329 * unless there's at least one restriction clause.
331 if (restrictclauses == NIL && !index->amoptionalkey)
335 * 2. Compute pathkeys describing index's ordering, if any, then see
336 * how many of them are actually useful for this query. This is not
337 * relevant unless we are at top level.
339 index_is_ordered = OidIsValid(index->fwdsortop[0]);
340 if (index_is_ordered && istoplevel && outer_rel == NULL)
342 index_pathkeys = build_index_pathkeys(root, index,
343 ForwardScanDirection);
344 useful_pathkeys = truncate_useless_pathkeys(root, rel,
348 useful_pathkeys = NIL;
351 * 3. Generate an indexscan path if there are relevant restriction
352 * clauses in the current clauses, OR the index ordering is
353 * potentially useful for later merging or final output ordering, OR
354 * the index has a predicate that was proven by the current clauses.
356 if (found_clause || useful_pathkeys != NIL || useful_predicate)
358 ipath = create_index_path(root, index,
362 ForwardScanDirection :
363 NoMovementScanDirection,
365 result = lappend(result, ipath);
369 * 4. If the index is ordered, a backwards scan might be
370 * interesting. Again, this is only interesting at top level.
372 if (index_is_ordered && istoplevel && outer_rel == NULL)
374 index_pathkeys = build_index_pathkeys(root, index,
375 BackwardScanDirection);
376 useful_pathkeys = truncate_useless_pathkeys(root, rel,
378 if (useful_pathkeys != NIL)
380 ipath = create_index_path(root, index,
383 BackwardScanDirection,
385 result = lappend(result, ipath);
396 * Find all the potential indexpaths that make use of ScalarArrayOpExpr
397 * clauses. The executor only supports these in bitmap scans, not
398 * plain indexscans, so we need to segregate them from the normal case.
399 * Otherwise, same API as find_usable_indexes().
400 * Returns a list of IndexPaths.
403 find_saop_paths(PlannerInfo *root, RelOptInfo *rel,
404 List *clauses, List *outer_clauses,
405 bool istoplevel, RelOptInfo *outer_rel)
407 bool have_saop = false;
411 * Since find_usable_indexes is relatively expensive, don't bother to run
412 * it unless there are some top-level ScalarArrayOpExpr clauses.
416 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
418 Assert(IsA(rinfo, RestrictInfo));
419 if (IsA(rinfo->clause, ScalarArrayOpExpr))
428 return find_usable_indexes(root, rel,
429 clauses, outer_clauses,
430 istoplevel, outer_rel,
436 * generate_bitmap_or_paths
437 * Look through the list of clauses to find OR clauses, and generate
438 * a BitmapOrPath for each one we can handle that way. Return a list
439 * of the generated BitmapOrPaths.
441 * outer_clauses is a list of additional clauses that can be assumed true
442 * for the purpose of generating indexquals, but are not to be searched for
443 * ORs. (See find_usable_indexes() for motivation.) outer_rel is the outer
444 * side when we are considering a nestloop inner indexpath.
447 generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
448 List *clauses, List *outer_clauses,
449 RelOptInfo *outer_rel)
456 * We can use both the current and outer clauses as context for
457 * find_usable_indexes
459 all_clauses = list_concat(list_copy(clauses), outer_clauses);
463 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
468 Assert(IsA(rinfo, RestrictInfo));
469 /* Ignore RestrictInfos that aren't ORs */
470 if (!restriction_is_or_clause(rinfo))
474 * We must be able to match at least one index to each of the arms of
475 * the OR, else we can't use it.
478 foreach(j, ((BoolExpr *) rinfo->orclause)->args)
480 Node *orarg = (Node *) lfirst(j);
483 /* OR arguments should be ANDs or sub-RestrictInfos */
484 if (and_clause(orarg))
486 List *andargs = ((BoolExpr *) orarg)->args;
488 indlist = find_usable_indexes(root, rel,
494 /* Recurse in case there are sub-ORs */
495 indlist = list_concat(indlist,
496 generate_bitmap_or_paths(root, rel,
503 Assert(IsA(orarg, RestrictInfo));
504 Assert(!restriction_is_or_clause((RestrictInfo *) orarg));
505 indlist = find_usable_indexes(root, rel,
514 * If nothing matched this arm, we can't do anything with this OR
524 * OK, pick the most promising AND combination, and add it to
527 bitmapqual = choose_bitmap_and(root, rel, indlist, outer_rel);
528 pathlist = lappend(pathlist, bitmapqual);
532 * If we have a match for every arm, then turn them into a
533 * BitmapOrPath, and add to result list.
537 bitmapqual = (Path *) create_bitmap_or_path(root, rel, pathlist);
538 result = lappend(result, bitmapqual);
548 * Given a nonempty list of bitmap paths, AND them into one path.
550 * This is a nontrivial decision since we can legally use any subset of the
551 * given path set. We want to choose a good tradeoff between selectivity
552 * and cost of computing the bitmap.
554 * The result is either a single one of the inputs, or a BitmapAndPath
555 * combining multiple inputs.
558 choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel,
559 List *paths, RelOptInfo *outer_rel)
561 int npaths = list_length(paths);
569 Assert(npaths > 0); /* else caller error */
571 return (Path *) linitial(paths); /* easy case */
574 * In theory we should consider every nonempty subset of the given paths.
575 * In practice that seems like overkill, given the crude nature of the
576 * estimates, not to mention the possible effects of higher-level AND and
577 * OR clauses. As a compromise, we sort the paths by selectivity. We
578 * always take the first, and sequentially add on paths that result in a
579 * lower estimated cost.
581 * We also make some effort to detect directly redundant input paths, as
582 * can happen if there are multiple possibly usable indexes. (Another way
583 * it can happen is that best_inner_indexscan will find the same OR join
584 * clauses that create_or_index_quals has pulled OR restriction clauses
585 * out of, and then both versions show up as duplicate paths.) We
586 * consider an index redundant if any of its index conditions were already
587 * used by earlier indexes. (We could use predicate_implied_by to have a
588 * more intelligent, but much more expensive, check --- but in most cases
589 * simple pointer equality should suffice, since after all the index
590 * conditions are all coming from the same RestrictInfo lists.)
592 * You might think the condition for redundancy should be "all index
593 * conditions already used", not "any", but this turns out to be wrong.
594 * For example, if we use an index on A, and then come to an index with
595 * conditions on A and B, the only way that the second index can be later
596 * in the selectivity-order sort is if the condition on B is completely
597 * non-selective. In any case, we'd surely be drastically misestimating
598 * the selectivity if we count the same condition twice.
600 * We include index predicate conditions in the redundancy test. Because
601 * the test is just for pointer equality and not equal(), the effect is
602 * that use of the same partial index in two different AND elements is
603 * considered redundant. (XXX is this too strong?)
605 * Note: outputting the selected sub-paths in selectivity order is a good
606 * thing even if we weren't using that as part of the selection method,
607 * because it makes the short-circuit case in MultiExecBitmapAnd() more
611 /* Convert list to array so we can apply qsort */
612 patharray = (Path **) palloc(npaths * sizeof(Path *));
616 patharray[i++] = (Path *) lfirst(l);
618 qsort(patharray, npaths, sizeof(Path *), bitmap_path_comparator);
620 paths = list_make1(patharray[0]);
621 costsofar = bitmap_and_cost_est(root, rel, paths, outer_rel);
622 qualsofar = pull_indexpath_quals(patharray[0]);
623 lastcell = list_head(paths); /* for quick deletions */
625 for (i = 1; i < npaths; i++)
627 Path *newpath = patharray[i];
631 newqual = pull_indexpath_quals(newpath);
632 if (lists_intersect_ptr(newqual, qualsofar))
633 continue; /* consider it redundant */
634 /* tentatively add newpath to paths, so we can estimate cost */
635 paths = lappend(paths, newpath);
636 newcost = bitmap_and_cost_est(root, rel, paths, outer_rel);
637 if (newcost < costsofar)
639 /* keep newpath in paths, update subsidiary variables */
641 qualsofar = list_concat(qualsofar, newqual);
642 lastcell = lnext(lastcell);
646 /* reject newpath, remove it from paths list */
647 paths = list_delete_cell(paths, lnext(lastcell), lastcell);
649 Assert(lnext(lastcell) == NULL);
652 if (list_length(paths) == 1)
653 return (Path *) linitial(paths); /* no need for AND */
654 return (Path *) create_bitmap_and_path(root, rel, paths);
657 /* qsort comparator to sort in increasing selectivity order */
659 bitmap_path_comparator(const void *a, const void *b)
661 Path *pa = *(Path *const *) a;
662 Path *pb = *(Path *const *) b;
668 cost_bitmap_tree_node(pa, &acost, &aselec);
669 cost_bitmap_tree_node(pb, &bcost, &bselec);
672 * If selectivities are the same, sort by cost. (Note: there used to be
673 * logic here to do "fuzzy comparison", but that's a bad idea because it
674 * fails to be transitive, which will confuse qsort terribly.)
690 * Estimate the cost of actually executing a BitmapAnd with the given
694 bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel,
695 List *paths, RelOptInfo *outer_rel)
700 /* Set up a dummy BitmapAndPath */
701 apath.path.type = T_BitmapAndPath;
702 apath.path.parent = rel;
703 apath.bitmapquals = paths;
704 cost_bitmap_and_node(&apath, root);
706 /* Now we can do cost_bitmap_heap_scan */
707 cost_bitmap_heap_scan(&bpath, root, rel, (Path *) &apath, outer_rel);
709 return bpath.total_cost;
713 * pull_indexpath_quals
715 * Given the Path structure for a plain or bitmap indexscan, extract a list
716 * of all the indexquals and index predicate conditions used in the Path.
718 * This is sort of a simplified version of make_restrictinfo_from_bitmapqual;
719 * here, we are not trying to produce an accurate representation of the AND/OR
720 * semantics of the Path, but just find out all the base conditions used.
722 * The result list contains pointers to the expressions used in the Path,
723 * but all the list cells are freshly built, so it's safe to destructively
724 * modify the list (eg, by concat'ing it with other lists).
727 pull_indexpath_quals(Path *bitmapqual)
732 if (IsA(bitmapqual, BitmapAndPath))
734 BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
736 foreach(l, apath->bitmapquals)
740 sublist = pull_indexpath_quals((Path *) lfirst(l));
741 result = list_concat(result, sublist);
744 else if (IsA(bitmapqual, BitmapOrPath))
746 BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
748 foreach(l, opath->bitmapquals)
752 sublist = pull_indexpath_quals((Path *) lfirst(l));
753 result = list_concat(result, sublist);
756 else if (IsA(bitmapqual, IndexPath))
758 IndexPath *ipath = (IndexPath *) bitmapqual;
760 result = get_actual_clauses(ipath->indexclauses);
761 result = list_concat(result, list_copy(ipath->indexinfo->indpred));
764 elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
771 * lists_intersect_ptr
772 * Detect whether two lists have a nonempty intersection,
773 * using pointer equality to compare members.
775 * This possibly should go into list.c, but it doesn't yet have any use
776 * except in choose_bitmap_and.
779 lists_intersect_ptr(List *list1, List *list2)
783 foreach(cell1, list1)
785 void *datum1 = lfirst(cell1);
788 foreach(cell2, list2)
790 if (lfirst(cell2) == datum1)
799 /****************************************************************************
800 * ---- ROUTINES TO CHECK RESTRICTIONS ----
801 ****************************************************************************/
805 * group_clauses_by_indexkey
806 * Find restriction clauses that can be used with an index.
808 * Returns a list of sublists of RestrictInfo nodes for clauses that can be
809 * used with this index. Each sublist contains clauses that can be used
810 * with one index key (in no particular order); the top list is ordered by
811 * index key. (This is depended on by expand_indexqual_conditions().)
813 * We can use clauses from either the current clauses or outer_clauses lists,
814 * but *found_clause is set TRUE only if we used at least one clause from
815 * the "current clauses" list. See find_usable_indexes() for motivation.
817 * outer_relids determines what Vars will be allowed on the other side
818 * of a possible index qual; see match_clause_to_indexcol().
820 * 'saop_control' indicates whether ScalarArrayOpExpr clauses can be used.
821 * When it's SAOP_REQUIRE, *found_clause is set TRUE only if we used at least
822 * one ScalarArrayOpExpr from the current clauses list.
824 * If the index has amoptionalkey = false, we give up and return NIL when
825 * there are no restriction clauses matching the first index key. Otherwise,
826 * we return NIL if there are no restriction clauses matching any index key.
827 * A non-NIL result will have one (possibly empty) sublist for each index key.
829 * Example: given an index on (A,B,C), we would return ((C1 C2) () (C3 C4))
830 * if we find that clauses C1 and C2 use column A, clauses C3 and C4 use
831 * column C, and no clauses use column B.
833 * Note: in some circumstances we may find the same RestrictInfos coming
834 * from multiple places. Defend against redundant outputs by using
835 * list_append_unique_ptr (pointer equality should be good enough).
838 group_clauses_by_indexkey(IndexOptInfo *index,
839 List *clauses, List *outer_clauses,
841 SaOpControl saop_control,
844 List *clausegroup_list = NIL;
845 bool found_outer_clause = false;
847 Oid *families = index->opfamily;
849 *found_clause = false; /* default result */
851 if (clauses == NIL && outer_clauses == NIL)
852 return NIL; /* cannot succeed */
856 Oid curFamily = families[0];
857 List *clausegroup = NIL;
860 /* check the current clauses */
863 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
865 Assert(IsA(rinfo, RestrictInfo));
866 if (match_clause_to_indexcol(index,
873 clausegroup = list_append_unique_ptr(clausegroup, rinfo);
874 if (saop_control != SAOP_REQUIRE ||
875 IsA(rinfo->clause, ScalarArrayOpExpr))
876 *found_clause = true;
880 /* check the outer clauses */
881 foreach(l, outer_clauses)
883 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
885 Assert(IsA(rinfo, RestrictInfo));
886 if (match_clause_to_indexcol(index,
893 clausegroup = list_append_unique_ptr(clausegroup, rinfo);
894 found_outer_clause = true;
899 * If no clauses match this key, check for amoptionalkey restriction.
901 if (clausegroup == NIL && !index->amoptionalkey && indexcol == 0)
904 clausegroup_list = lappend(clausegroup_list, clausegroup);
909 } while (!DoneMatchingIndexKeys(families));
911 if (!*found_clause && !found_outer_clause)
912 return NIL; /* no indexable clauses anywhere */
914 return clausegroup_list;
919 * match_clause_to_indexcol()
920 * Determines whether a restriction clause matches a column of an index.
922 * To match a normal index, the clause:
924 * (1) must be in the form (indexkey op const) or (const op indexkey);
926 * (2) must contain an operator which is in the same family as the index
927 * operator for this column, or is a "special" operator as recognized
928 * by match_special_index_operator().
930 * Our definition of "const" is pretty liberal: we allow Vars belonging
931 * to the caller-specified outer_relids relations (which had better not
932 * include the relation whose index is being tested). outer_relids should
933 * be NULL when checking simple restriction clauses, and the outer side
934 * of the join when building a join inner scan. Other than that, the
935 * only thing we don't like is volatile functions.
937 * Note: in most cases we already know that the clause as a whole uses
938 * vars from the interesting set of relations. The reason for the
939 * outer_relids test is to reject clauses like (a.f1 OP (b.f2 OP a.f3));
940 * that's not processable by an indexscan nestloop join on A, whereas
941 * (a.f1 OP (b.f2 OP c.f3)) is.
943 * Presently, the executor can only deal with indexquals that have the
944 * indexkey on the left, so we can only use clauses that have the indexkey
945 * on the right if we can commute the clause to put the key on the left.
946 * We do not actually do the commuting here, but we check whether a
947 * suitable commutator operator is available.
949 * It is also possible to match RowCompareExpr clauses to indexes (but
950 * currently, only btree indexes handle this). In this routine we will
951 * report a match if the first column of the row comparison matches the
952 * target index column. This is sufficient to guarantee that some index
953 * condition can be constructed from the RowCompareExpr --- whether the
954 * remaining columns match the index too is considered in
955 * expand_indexqual_rowcompare().
957 * It is also possible to match ScalarArrayOpExpr clauses to indexes, when
958 * the clause is of the form "indexkey op ANY (arrayconst)". Since the
959 * executor can only handle these in the context of bitmap index scans,
960 * our caller specifies whether to allow these or not.
962 * For boolean indexes, it is also possible to match the clause directly
963 * to the indexkey; or perhaps the clause is (NOT indexkey).
965 * 'index' is the index of interest.
966 * 'indexcol' is a column number of 'index' (counting from 0).
967 * 'opfamily' is the corresponding operator family.
968 * 'rinfo' is the clause to be tested (as a RestrictInfo node).
969 * 'saop_control' indicates whether ScalarArrayOpExpr clauses can be used.
971 * Returns true if the clause can be used with this index key.
973 * NOTE: returns false if clause is an OR or AND clause; it is the
974 * responsibility of higher-level routines to cope with those.
977 match_clause_to_indexcol(IndexOptInfo *index,
982 SaOpControl saop_control)
984 Expr *clause = rinfo->clause;
993 * Never match pseudoconstants to indexes. (Normally this could not
994 * happen anyway, since a pseudoconstant clause couldn't contain a Var,
995 * but what if someone builds an expression index on a constant? It's not
996 * totally unreasonable to do so with a partial index, either.)
998 if (rinfo->pseudoconstant)
1001 /* First check for boolean-index cases. */
1002 if (IsBooleanOpfamily(opfamily))
1004 if (match_boolean_index_clause((Node *) clause, indexcol, index))
1009 * Clause must be a binary opclause, or possibly a ScalarArrayOpExpr
1010 * (which is always binary, by definition). Or it could be a
1011 * RowCompareExpr, which we pass off to match_rowcompare_to_indexcol().
1013 if (is_opclause(clause))
1015 leftop = get_leftop(clause);
1016 rightop = get_rightop(clause);
1017 if (!leftop || !rightop)
1019 left_relids = rinfo->left_relids;
1020 right_relids = rinfo->right_relids;
1021 expr_op = ((OpExpr *) clause)->opno;
1024 else if (saop_control != SAOP_FORBID &&
1025 clause && IsA(clause, ScalarArrayOpExpr))
1027 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) clause;
1029 /* We only accept ANY clauses, not ALL */
1032 leftop = (Node *) linitial(saop->args);
1033 rightop = (Node *) lsecond(saop->args);
1034 left_relids = NULL; /* not actually needed */
1035 right_relids = pull_varnos(rightop);
1036 expr_op = saop->opno;
1039 else if (clause && IsA(clause, RowCompareExpr))
1041 return match_rowcompare_to_indexcol(index, indexcol, opfamily,
1042 (RowCompareExpr *) clause,
1049 * Check for clauses of the form: (indexkey operator constant) or
1050 * (constant operator indexkey). See above notes about const-ness.
1052 if (match_index_to_operand(leftop, indexcol, index) &&
1053 bms_is_subset(right_relids, outer_relids) &&
1054 !contain_volatile_functions(rightop))
1056 if (is_indexable_operator(expr_op, opfamily, true))
1060 * If we didn't find a member of the index's opfamily, see whether it
1061 * is a "special" indexable operator.
1064 match_special_index_operator(clause, opfamily, true))
1070 match_index_to_operand(rightop, indexcol, index) &&
1071 bms_is_subset(left_relids, outer_relids) &&
1072 !contain_volatile_functions(leftop))
1074 if (is_indexable_operator(expr_op, opfamily, false))
1078 * If we didn't find a member of the index's opfamily, see whether it
1079 * is a "special" indexable operator.
1081 if (match_special_index_operator(clause, opfamily, false))
1090 * is_indexable_operator
1091 * Does the operator match the specified index opfamily?
1093 * If the indexkey is on the right, what we actually want to know
1094 * is whether the operator has a commutator operator that matches
1098 is_indexable_operator(Oid expr_op, Oid opfamily, bool indexkey_on_left)
1100 /* Get the commuted operator if necessary */
1101 if (!indexkey_on_left)
1103 expr_op = get_commutator(expr_op);
1104 if (expr_op == InvalidOid)
1108 /* OK if the (commuted) operator is a member of the index's opfamily */
1109 return op_in_opfamily(expr_op, opfamily);
1113 * match_rowcompare_to_indexcol()
1114 * Handles the RowCompareExpr case for match_clause_to_indexcol(),
1115 * which see for comments.
1118 match_rowcompare_to_indexcol(IndexOptInfo *index,
1121 RowCompareExpr *clause,
1122 Relids outer_relids)
1128 /* Forget it if we're not dealing with a btree index */
1129 if (index->relam != BTREE_AM_OID)
1133 * We could do the matching on the basis of insisting that the opfamily
1134 * shown in the RowCompareExpr be the same as the index column's opfamily,
1135 * but that could fail in the presence of reverse-sort opfamilies: it'd
1136 * be a matter of chance whether RowCompareExpr had picked the forward
1137 * or reverse-sort family. So look only at the operator, and match
1138 * if it is a member of the index's opfamily (after commutation, if the
1139 * indexkey is on the right). We'll worry later about whether any
1140 * additional operators are matchable to the index.
1142 leftop = (Node *) linitial(clause->largs);
1143 rightop = (Node *) linitial(clause->rargs);
1144 expr_op = linitial_oid(clause->opnos);
1147 * These syntactic tests are the same as in match_clause_to_indexcol()
1149 if (match_index_to_operand(leftop, indexcol, index) &&
1150 bms_is_subset(pull_varnos(rightop), outer_relids) &&
1151 !contain_volatile_functions(rightop))
1153 /* OK, indexkey is on left */
1155 else if (match_index_to_operand(rightop, indexcol, index) &&
1156 bms_is_subset(pull_varnos(leftop), outer_relids) &&
1157 !contain_volatile_functions(leftop))
1159 /* indexkey is on right, so commute the operator */
1160 expr_op = get_commutator(expr_op);
1161 if (expr_op == InvalidOid)
1167 /* We're good if the operator is the right type of opfamily member */
1168 switch (get_op_opfamily_strategy(expr_op, opfamily))
1170 case BTLessStrategyNumber:
1171 case BTLessEqualStrategyNumber:
1172 case BTGreaterEqualStrategyNumber:
1173 case BTGreaterStrategyNumber:
1181 /****************************************************************************
1182 * ---- ROUTINES TO DO PARTIAL INDEX PREDICATE TESTS ----
1183 ****************************************************************************/
1186 * check_partial_indexes
1187 * Check each partial index of the relation, and mark it predOK or not
1188 * depending on whether the predicate is satisfied for this query.
1191 check_partial_indexes(PlannerInfo *root, RelOptInfo *rel)
1193 List *restrictinfo_list = rel->baserestrictinfo;
1196 foreach(ilist, rel->indexlist)
1198 IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
1200 if (index->indpred == NIL)
1201 continue; /* ignore non-partial indexes */
1203 index->predOK = predicate_implied_by(index->indpred,
1208 /****************************************************************************
1209 * ---- ROUTINES TO CHECK JOIN CLAUSES ----
1210 ****************************************************************************/
1213 * indexable_outerrelids
1214 * Finds all other relids that participate in any indexable join clause
1215 * for the specified table. Returns a set of relids.
1218 indexable_outerrelids(PlannerInfo *root, RelOptInfo *rel)
1220 Relids outer_relids = NULL;
1221 bool is_child_rel = (rel->reloptkind == RELOPT_OTHER_MEMBER_REL);
1225 * Examine each joinclause in the joininfo list to see if it matches any
1226 * key of any index. If so, add the clause's other rels to the result.
1228 foreach(lc1, rel->joininfo)
1230 RestrictInfo *joininfo = (RestrictInfo *) lfirst(lc1);
1233 other_rels = bms_difference(joininfo->required_relids, rel->relids);
1234 if (matches_any_index(joininfo, rel, other_rels))
1235 outer_relids = bms_join(outer_relids, other_rels);
1237 bms_free(other_rels);
1241 * We also have to look through the query's EquivalenceClasses to see
1242 * if any of them could generate indexable join conditions for this rel.
1244 if (rel->has_eclass_joins)
1246 foreach(lc1, root->eq_classes)
1248 EquivalenceClass *cur_ec = (EquivalenceClass *) lfirst(lc1);
1249 Relids other_rels = NULL;
1250 bool found_index = false;
1254 * Won't generate joinclauses if const or single-member (the latter
1255 * test covers the volatile case too)
1257 if (cur_ec->ec_has_const || list_length(cur_ec->ec_members) <= 1)
1261 * Note we don't test ec_broken; if we did, we'd need a separate
1262 * code path to look through ec_sources. Checking the members
1263 * anyway is OK as a possibly-overoptimistic heuristic.
1267 * No point in searching if rel not mentioned in eclass (but we
1268 * can't tell that for a child rel).
1270 if (!is_child_rel &&
1271 !bms_is_subset(rel->relids, cur_ec->ec_relids))
1275 * Scan members, looking for both an index match and join
1278 foreach(lc2, cur_ec->ec_members)
1280 EquivalenceMember *cur_em = (EquivalenceMember *) lfirst(lc2);
1282 /* Join candidate? */
1283 if (!cur_em->em_is_child &&
1284 !bms_overlap(cur_em->em_relids, rel->relids))
1286 other_rels = bms_add_members(other_rels,
1291 /* Check for index match (only need one) */
1293 bms_equal(cur_em->em_relids, rel->relids) &&
1294 eclass_matches_any_index(cur_ec, cur_em, rel))
1299 outer_relids = bms_join(outer_relids, other_rels);
1301 bms_free(other_rels);
1305 return outer_relids;
1310 * Workhorse for indexable_outerrelids: see if a joinclause can be
1311 * matched to any index of the given rel.
1314 matches_any_index(RestrictInfo *rinfo, RelOptInfo *rel, Relids outer_relids)
1318 Assert(IsA(rinfo, RestrictInfo));
1320 if (restriction_is_or_clause(rinfo))
1322 foreach(l, ((BoolExpr *) rinfo->orclause)->args)
1324 Node *orarg = (Node *) lfirst(l);
1326 /* OR arguments should be ANDs or sub-RestrictInfos */
1327 if (and_clause(orarg))
1331 /* Recurse to examine AND items and sub-ORs */
1332 foreach(j, ((BoolExpr *) orarg)->args)
1334 RestrictInfo *arinfo = (RestrictInfo *) lfirst(j);
1336 if (matches_any_index(arinfo, rel, outer_relids))
1342 /* Recurse to examine simple clause */
1343 Assert(IsA(orarg, RestrictInfo));
1344 Assert(!restriction_is_or_clause((RestrictInfo *) orarg));
1345 if (matches_any_index((RestrictInfo *) orarg, rel,
1354 /* Normal case for a simple restriction clause */
1355 foreach(l, rel->indexlist)
1357 IndexOptInfo *index = (IndexOptInfo *) lfirst(l);
1359 Oid *families = index->opfamily;
1363 Oid curFamily = families[0];
1365 if (match_clause_to_indexcol(index,
1375 } while (!DoneMatchingIndexKeys(families));
1382 * eclass_matches_any_index
1383 * Workhorse for indexable_outerrelids: see if an EquivalenceClass member
1384 * can be matched to any index column of the given rel.
1386 * This is also exported for use by find_eclass_clauses_for_index_join.
1389 eclass_matches_any_index(EquivalenceClass *ec, EquivalenceMember *em,
1394 foreach(l, rel->indexlist)
1396 IndexOptInfo *index = (IndexOptInfo *) lfirst(l);
1398 Oid *families = index->opfamily;
1402 Oid curFamily = families[0];
1404 if (list_member_oid(ec->ec_opfamilies, curFamily) &&
1405 match_index_to_operand((Node *) em->em_expr, indexcol, index))
1410 } while (!DoneMatchingIndexKeys(families));
1418 * best_inner_indexscan
1419 * Finds the best available inner indexscan for a nestloop join
1420 * with the given rel on the inside and the given outer_rel outside.
1421 * May return NULL if there are no possible inner indexscans.
1423 * We ignore ordering considerations (since a nestloop's inner scan's order
1424 * is uninteresting). Also, we consider only total cost when deciding which
1425 * of two possible paths is better --- this assumes that all indexpaths have
1426 * negligible startup cost. (True today, but someday we might have to think
1427 * harder.) Therefore, there is only one dimension of comparison and so it's
1428 * sufficient to return a single "best" path.
1430 * Note: create_index_paths() must have been run previously for this rel,
1431 * else the result will always be NULL.
1434 best_inner_indexscan(PlannerInfo *root, RelOptInfo *rel,
1435 RelOptInfo *outer_rel, JoinType jointype)
1437 Relids outer_relids;
1442 List *bitindexpaths;
1444 InnerIndexscanInfo *info;
1445 MemoryContext oldcontext;
1448 * Nestloop only supports inner, left, and IN joins.
1454 case JOIN_UNIQUE_OUTER:
1455 isouterjoin = false;
1465 * If there are no indexable joinclauses for this rel, exit quickly.
1467 if (bms_is_empty(rel->index_outer_relids))
1471 * Otherwise, we have to do path selection in the main planning context,
1472 * so that any created path can be safely attached to the rel's cache of
1473 * best inner paths. (This is not currently an issue for normal planning,
1474 * but it is an issue for GEQO planning.)
1476 oldcontext = MemoryContextSwitchTo(root->planner_cxt);
1479 * Intersect the given outer relids with index_outer_relids to find the
1480 * set of outer relids actually relevant for this rel. If there are none,
1481 * again we can fail immediately.
1483 outer_relids = bms_intersect(rel->index_outer_relids, outer_rel->relids);
1484 if (bms_is_empty(outer_relids))
1486 bms_free(outer_relids);
1487 MemoryContextSwitchTo(oldcontext);
1492 * Look to see if we already computed the result for this set of relevant
1493 * outerrels. (We include the isouterjoin status in the cache lookup key
1494 * for safety. In practice I suspect this is not necessary because it
1495 * should always be the same for a given innerrel.)
1497 * NOTE: because we cache on outer_relids rather than outer_rel->relids,
1498 * we will report the same path and hence path cost for joins with
1499 * different sets of irrelevant rels on the outside. Now that cost_index
1500 * is sensitive to outer_rel->rows, this is not really right. However the
1501 * error is probably not large. Is it worth establishing a separate cache
1502 * entry for each distinct outer_rel->relids set to get this right?
1504 foreach(l, rel->index_inner_paths)
1506 info = (InnerIndexscanInfo *) lfirst(l);
1507 if (bms_equal(info->other_relids, outer_relids) &&
1508 info->isouterjoin == isouterjoin)
1510 bms_free(outer_relids);
1511 MemoryContextSwitchTo(oldcontext);
1512 return info->best_innerpath;
1517 * Find all the relevant restriction and join clauses.
1519 * Note: because we include restriction clauses, we will find indexscans
1520 * that could be plain indexscans, ie, they don't require the join context
1521 * at all. This may seem redundant, but we need to include those scans in
1522 * the input given to choose_bitmap_and() to be sure we find optimal AND
1523 * combinations of join and non-join scans. Also, even if the "best inner
1524 * indexscan" is just a plain indexscan, it will have a different cost
1525 * estimate because of cache effects.
1527 clause_list = find_clauses_for_join(root, rel, outer_relids, isouterjoin);
1530 * Find all the index paths that are usable for this join, except for
1531 * stuff involving OR and ScalarArrayOpExpr clauses.
1533 indexpaths = find_usable_indexes(root, rel,
1539 * Generate BitmapOrPaths for any suitable OR-clauses present in the
1542 bitindexpaths = generate_bitmap_or_paths(root, rel,
1547 * Likewise, generate paths using ScalarArrayOpExpr clauses; these can't
1548 * be simple indexscans but they can be used in bitmap scans.
1550 bitindexpaths = list_concat(bitindexpaths,
1551 find_saop_paths(root, rel,
1556 * Include the regular index paths in bitindexpaths.
1558 bitindexpaths = list_concat(bitindexpaths, list_copy(indexpaths));
1561 * If we found anything usable, generate a BitmapHeapPath for the most
1562 * promising combination of bitmap index paths.
1564 if (bitindexpaths != NIL)
1567 BitmapHeapPath *bpath;
1569 bitmapqual = choose_bitmap_and(root, rel, bitindexpaths, outer_rel);
1570 bpath = create_bitmap_heap_path(root, rel, bitmapqual, outer_rel);
1571 indexpaths = lappend(indexpaths, bpath);
1575 * Now choose the cheapest member of indexpaths.
1578 foreach(l, indexpaths)
1580 Path *path = (Path *) lfirst(l);
1582 if (cheapest == NULL ||
1583 compare_path_costs(path, cheapest, TOTAL_COST) < 0)
1587 /* Cache the result --- whether positive or negative */
1588 info = makeNode(InnerIndexscanInfo);
1589 info->other_relids = outer_relids;
1590 info->isouterjoin = isouterjoin;
1591 info->best_innerpath = cheapest;
1592 rel->index_inner_paths = lcons(info, rel->index_inner_paths);
1594 MemoryContextSwitchTo(oldcontext);
1600 * find_clauses_for_join
1601 * Generate a list of clauses that are potentially useful for
1602 * scanning rel as the inner side of a nestloop join.
1604 * We consider both join and restriction clauses. Any joinclause that uses
1605 * only otherrels in the specified outer_relids is fair game. But there must
1606 * be at least one such joinclause in the final list, otherwise we return NIL
1607 * indicating that there isn't any potential win here.
1610 find_clauses_for_join(PlannerInfo *root, RelOptInfo *rel,
1611 Relids outer_relids, bool isouterjoin)
1613 List *clause_list = NIL;
1618 * Look for joinclauses that are usable with given outer_relids. Note
1619 * we'll take anything that's applicable to the join whether it has
1620 * anything to do with an index or not; since we're only building a list,
1621 * it's not worth filtering more finely here.
1623 join_relids = bms_union(rel->relids, outer_relids);
1625 foreach(l, rel->joininfo)
1627 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
1629 /* Can't use pushed-down join clauses in outer join */
1630 if (isouterjoin && rinfo->is_pushed_down)
1632 if (!bms_is_subset(rinfo->required_relids, join_relids))
1635 clause_list = lappend(clause_list, rinfo);
1638 bms_free(join_relids);
1641 * Also check to see if any EquivalenceClasses can produce a relevant
1642 * joinclause. Since all such clauses are effectively pushed-down,
1643 * this doesn't apply to outer joins.
1645 if (!isouterjoin && rel->has_eclass_joins)
1646 clause_list = list_concat(clause_list,
1647 find_eclass_clauses_for_index_join(root,
1651 /* If no join clause was matched then forget it, per comments above */
1652 if (clause_list == NIL)
1655 /* We can also use any plain restriction clauses for the rel */
1656 clause_list = list_concat(list_copy(rel->baserestrictinfo), clause_list);
1662 /****************************************************************************
1663 * ---- PATH CREATION UTILITIES ----
1664 ****************************************************************************/
1667 * flatten_clausegroups_list
1668 * Given a list of lists of RestrictInfos, flatten it to a list
1671 * This is used to flatten out the result of group_clauses_by_indexkey()
1672 * to produce an indexclauses list. The original list structure mustn't
1673 * be altered, but it's OK to share copies of the underlying RestrictInfos.
1676 flatten_clausegroups_list(List *clausegroups)
1678 List *allclauses = NIL;
1681 foreach(l, clausegroups)
1682 allclauses = list_concat(allclauses, list_copy((List *) lfirst(l)));
1687 /****************************************************************************
1688 * ---- ROUTINES TO CHECK OPERANDS ----
1689 ****************************************************************************/
1692 * match_index_to_operand()
1693 * Generalized test for a match between an index's key
1694 * and the operand on one side of a restriction or join clause.
1696 * operand: the nodetree to be compared to the index
1697 * indexcol: the column number of the index (counting from 0)
1698 * index: the index of interest
1701 match_index_to_operand(Node *operand,
1703 IndexOptInfo *index)
1708 * Ignore any RelabelType node above the operand. This is needed to be
1709 * able to apply indexscanning in binary-compatible-operator cases. Note:
1710 * we can assume there is at most one RelabelType node;
1711 * eval_const_expressions() will have simplified if more than one.
1713 if (operand && IsA(operand, RelabelType))
1714 operand = (Node *) ((RelabelType *) operand)->arg;
1716 indkey = index->indexkeys[indexcol];
1720 * Simple index column; operand must be a matching Var.
1722 if (operand && IsA(operand, Var) &&
1723 index->rel->relid == ((Var *) operand)->varno &&
1724 indkey == ((Var *) operand)->varattno)
1730 * Index expression; find the correct expression. (This search could
1731 * be avoided, at the cost of complicating all the callers of this
1732 * routine; doesn't seem worth it.)
1734 ListCell *indexpr_item;
1738 indexpr_item = list_head(index->indexprs);
1739 for (i = 0; i < indexcol; i++)
1741 if (index->indexkeys[i] == 0)
1743 if (indexpr_item == NULL)
1744 elog(ERROR, "wrong number of index expressions");
1745 indexpr_item = lnext(indexpr_item);
1748 if (indexpr_item == NULL)
1749 elog(ERROR, "wrong number of index expressions");
1750 indexkey = (Node *) lfirst(indexpr_item);
1753 * Does it match the operand? Again, strip any relabeling.
1755 if (indexkey && IsA(indexkey, RelabelType))
1756 indexkey = (Node *) ((RelabelType *) indexkey)->arg;
1758 if (equal(indexkey, operand))
1765 /****************************************************************************
1766 * ---- ROUTINES FOR "SPECIAL" INDEXABLE OPERATORS ----
1767 ****************************************************************************/
1770 * These routines handle special optimization of operators that can be
1771 * used with index scans even though they are not known to the executor's
1772 * indexscan machinery. The key idea is that these operators allow us
1773 * to derive approximate indexscan qual clauses, such that any tuples
1774 * that pass the operator clause itself must also satisfy the simpler
1775 * indexscan condition(s). Then we can use the indexscan machinery
1776 * to avoid scanning as much of the table as we'd otherwise have to,
1777 * while applying the original operator as a qpqual condition to ensure
1778 * we deliver only the tuples we want. (In essence, we're using a regular
1779 * index as if it were a lossy index.)
1781 * An example of what we're doing is
1782 * textfield LIKE 'abc%'
1783 * from which we can generate the indexscanable conditions
1784 * textfield >= 'abc' AND textfield < 'abd'
1785 * which allow efficient scanning of an index on textfield.
1786 * (In reality, character set and collation issues make the transformation
1787 * from LIKE to indexscan limits rather harder than one might think ...
1788 * but that's the basic idea.)
1790 * Another thing that we do with this machinery is to provide special
1791 * smarts for "boolean" indexes (that is, indexes on boolean columns
1792 * that support boolean equality). We can transform a plain reference
1793 * to the indexkey into "indexkey = true", or "NOT indexkey" into
1794 * "indexkey = false", so as to make the expression indexable using the
1795 * regular index operators. (As of Postgres 8.1, we must do this here
1796 * because constant simplification does the reverse transformation;
1797 * without this code there'd be no way to use such an index at all.)
1799 * Three routines are provided here:
1801 * match_special_index_operator() is just an auxiliary function for
1802 * match_clause_to_indexcol(); after the latter fails to recognize a
1803 * restriction opclause's operator as a member of an index's opfamily,
1804 * it asks match_special_index_operator() whether the clause should be
1805 * considered an indexqual anyway.
1807 * match_boolean_index_clause() similarly detects clauses that can be
1808 * converted into boolean equality operators.
1810 * expand_indexqual_conditions() converts a list of lists of RestrictInfo
1811 * nodes (with implicit AND semantics across list elements) into
1812 * a list of clauses that the executor can actually handle. For operators
1813 * that are members of the index's opfamily this transformation is a no-op,
1814 * but clauses recognized by match_special_index_operator() or
1815 * match_boolean_index_clause() must be converted into one or more "regular"
1816 * indexqual conditions.
1821 * match_boolean_index_clause
1822 * Recognize restriction clauses that can be matched to a boolean index.
1824 * This should be called only when IsBooleanOpfamily() recognizes the
1825 * index's operator family. We check to see if the clause matches the
1829 match_boolean_index_clause(Node *clause,
1831 IndexOptInfo *index)
1834 if (match_index_to_operand(clause, indexcol, index))
1837 if (not_clause(clause))
1839 if (match_index_to_operand((Node *) get_notclausearg((Expr *) clause),
1845 * Since we only consider clauses at top level of WHERE, we can convert
1846 * indexkey IS TRUE and indexkey IS FALSE to index searches as well. The
1847 * different meaning for NULL isn't important.
1849 else if (clause && IsA(clause, BooleanTest))
1851 BooleanTest *btest = (BooleanTest *) clause;
1853 if (btest->booltesttype == IS_TRUE ||
1854 btest->booltesttype == IS_FALSE)
1855 if (match_index_to_operand((Node *) btest->arg,
1863 * match_special_index_operator
1864 * Recognize restriction clauses that can be used to generate
1865 * additional indexscanable qualifications.
1867 * The given clause is already known to be a binary opclause having
1868 * the form (indexkey OP pseudoconst) or (pseudoconst OP indexkey),
1869 * but the OP proved not to be one of the index's opfamily operators.
1870 * Return 'true' if we can do something with it anyway.
1873 match_special_index_operator(Expr *clause, Oid opfamily,
1874 bool indexkey_on_left)
1876 bool isIndexable = false;
1880 Const *prefix = NULL;
1884 * Currently, all known special operators require the indexkey on the
1885 * left, but this test could be pushed into the switch statement if some
1886 * are added that do not...
1888 if (!indexkey_on_left)
1891 /* we know these will succeed */
1892 rightop = get_rightop(clause);
1893 expr_op = ((OpExpr *) clause)->opno;
1895 /* again, required for all current special ops: */
1896 if (!IsA(rightop, Const) ||
1897 ((Const *) rightop)->constisnull)
1899 patt = (Const *) rightop;
1903 case OID_TEXT_LIKE_OP:
1904 case OID_BPCHAR_LIKE_OP:
1905 case OID_NAME_LIKE_OP:
1906 /* the right-hand const is type text for all of these */
1907 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like,
1908 &prefix, &rest) != Pattern_Prefix_None;
1911 case OID_BYTEA_LIKE_OP:
1912 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like,
1913 &prefix, &rest) != Pattern_Prefix_None;
1916 case OID_TEXT_ICLIKE_OP:
1917 case OID_BPCHAR_ICLIKE_OP:
1918 case OID_NAME_ICLIKE_OP:
1919 /* the right-hand const is type text for all of these */
1920 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Like_IC,
1921 &prefix, &rest) != Pattern_Prefix_None;
1924 case OID_TEXT_REGEXEQ_OP:
1925 case OID_BPCHAR_REGEXEQ_OP:
1926 case OID_NAME_REGEXEQ_OP:
1927 /* the right-hand const is type text for all of these */
1928 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Regex,
1929 &prefix, &rest) != Pattern_Prefix_None;
1932 case OID_TEXT_ICREGEXEQ_OP:
1933 case OID_BPCHAR_ICREGEXEQ_OP:
1934 case OID_NAME_ICREGEXEQ_OP:
1935 /* the right-hand const is type text for all of these */
1936 isIndexable = pattern_fixed_prefix(patt, Pattern_Type_Regex_IC,
1937 &prefix, &rest) != Pattern_Prefix_None;
1940 case OID_INET_SUB_OP:
1941 case OID_INET_SUBEQ_OP:
1948 pfree(DatumGetPointer(prefix->constvalue));
1952 /* done if the expression doesn't look indexable */
1957 * Must also check that index's opfamily supports the operators we will
1958 * want to apply. (A hash index, for example, will not support ">=".)
1959 * Currently, only btree supports the operators we need.
1961 * We insist on the opfamily being the specific one we expect, else we'd do
1962 * the wrong thing if someone were to make a reverse-sort opfamily with the
1967 case OID_TEXT_LIKE_OP:
1968 case OID_TEXT_ICLIKE_OP:
1969 case OID_TEXT_REGEXEQ_OP:
1970 case OID_TEXT_ICREGEXEQ_OP:
1972 (opfamily == TEXT_PATTERN_BTREE_FAM_OID) ||
1973 (opfamily == TEXT_BTREE_FAM_OID && lc_collate_is_c());
1976 case OID_BPCHAR_LIKE_OP:
1977 case OID_BPCHAR_ICLIKE_OP:
1978 case OID_BPCHAR_REGEXEQ_OP:
1979 case OID_BPCHAR_ICREGEXEQ_OP:
1981 (opfamily == BPCHAR_PATTERN_BTREE_FAM_OID) ||
1982 (opfamily == BPCHAR_BTREE_FAM_OID && lc_collate_is_c());
1985 case OID_NAME_LIKE_OP:
1986 case OID_NAME_ICLIKE_OP:
1987 case OID_NAME_REGEXEQ_OP:
1988 case OID_NAME_ICREGEXEQ_OP:
1990 (opfamily == NAME_PATTERN_BTREE_FAM_OID) ||
1991 (opfamily == NAME_BTREE_FAM_OID && lc_collate_is_c());
1994 case OID_BYTEA_LIKE_OP:
1995 isIndexable = (opfamily == BYTEA_BTREE_FAM_OID);
1998 case OID_INET_SUB_OP:
1999 case OID_INET_SUBEQ_OP:
2000 isIndexable = (opfamily == NETWORK_BTREE_FAM_OID);
2008 * expand_indexqual_conditions
2009 * Given a list of sublists of RestrictInfo nodes, produce a flat list
2010 * of index qual clauses. Standard qual clauses (those in the index's
2011 * opfamily) are passed through unchanged. Boolean clauses and "special"
2012 * index operators are expanded into clauses that the indexscan machinery
2013 * will know what to do with. RowCompare clauses are simplified if
2014 * necessary to create a clause that is fully checkable by the index.
2016 * The input list is ordered by index key, and so the output list is too.
2017 * (The latter is not depended on by any part of the core planner, I believe,
2018 * but parts of the executor require it, and so do the amcostestimate
2022 expand_indexqual_conditions(IndexOptInfo *index, List *clausegroups)
2024 List *resultquals = NIL;
2025 ListCell *clausegroup_item;
2027 Oid *families = index->opfamily;
2029 if (clausegroups == NIL)
2032 clausegroup_item = list_head(clausegroups);
2035 Oid curFamily = families[0];
2038 foreach(l, (List *) lfirst(clausegroup_item))
2040 RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
2041 Expr *clause = rinfo->clause;
2043 /* First check for boolean cases */
2044 if (IsBooleanOpfamily(curFamily))
2048 boolqual = expand_boolean_index_clause((Node *) clause,
2053 resultquals = lappend(resultquals,
2054 make_restrictinfo(boolqual,
2064 * Else it must be an opclause (usual case), ScalarArrayOp, or
2067 if (is_opclause(clause))
2069 resultquals = list_concat(resultquals,
2070 expand_indexqual_opclause(rinfo,
2073 else if (IsA(clause, ScalarArrayOpExpr))
2075 /* no extra work at this time */
2076 resultquals = lappend(resultquals, rinfo);
2078 else if (IsA(clause, RowCompareExpr))
2080 resultquals = lappend(resultquals,
2081 expand_indexqual_rowcompare(rinfo,
2086 elog(ERROR, "unsupported indexqual type: %d",
2087 (int) nodeTag(clause));
2090 clausegroup_item = lnext(clausegroup_item);
2094 } while (clausegroup_item != NULL && !DoneMatchingIndexKeys(families));
2096 Assert(clausegroup_item == NULL); /* else more groups than indexkeys */
2102 * expand_boolean_index_clause
2103 * Convert a clause recognized by match_boolean_index_clause into
2104 * a boolean equality operator clause.
2106 * Returns NULL if the clause isn't a boolean index qual.
2109 expand_boolean_index_clause(Node *clause,
2111 IndexOptInfo *index)
2114 if (match_index_to_operand(clause, indexcol, index))
2116 /* convert to indexkey = TRUE */
2117 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2119 (Expr *) makeBoolConst(true, false));
2122 if (not_clause(clause))
2124 Node *arg = (Node *) get_notclausearg((Expr *) clause);
2126 /* It must have matched the indexkey */
2127 Assert(match_index_to_operand(arg, indexcol, index));
2128 /* convert to indexkey = FALSE */
2129 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2131 (Expr *) makeBoolConst(false, false));
2133 if (clause && IsA(clause, BooleanTest))
2135 BooleanTest *btest = (BooleanTest *) clause;
2136 Node *arg = (Node *) btest->arg;
2138 /* It must have matched the indexkey */
2139 Assert(match_index_to_operand(arg, indexcol, index));
2140 if (btest->booltesttype == IS_TRUE)
2142 /* convert to indexkey = TRUE */
2143 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2145 (Expr *) makeBoolConst(true, false));
2147 if (btest->booltesttype == IS_FALSE)
2149 /* convert to indexkey = FALSE */
2150 return make_opclause(BooleanEqualOperator, BOOLOID, false,
2152 (Expr *) makeBoolConst(false, false));
2162 * expand_indexqual_opclause --- expand a single indexqual condition
2163 * that is an operator clause
2165 * The input is a single RestrictInfo, the output a list of RestrictInfos
2168 expand_indexqual_opclause(RestrictInfo *rinfo, Oid opfamily)
2170 Expr *clause = rinfo->clause;
2172 /* we know these will succeed */
2173 Node *leftop = get_leftop(clause);
2174 Node *rightop = get_rightop(clause);
2175 Oid expr_op = ((OpExpr *) clause)->opno;
2176 Const *patt = (Const *) rightop;
2177 Const *prefix = NULL;
2179 Pattern_Prefix_Status pstatus;
2185 * LIKE and regex operators are not members of any index opfamily,
2186 * so if we find one in an indexqual list we can assume that it
2187 * was accepted by match_special_index_operator().
2189 case OID_TEXT_LIKE_OP:
2190 case OID_BPCHAR_LIKE_OP:
2191 case OID_NAME_LIKE_OP:
2192 case OID_BYTEA_LIKE_OP:
2193 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Like,
2195 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2198 case OID_TEXT_ICLIKE_OP:
2199 case OID_BPCHAR_ICLIKE_OP:
2200 case OID_NAME_ICLIKE_OP:
2201 /* the right-hand const is type text for all of these */
2202 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Like_IC,
2204 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2207 case OID_TEXT_REGEXEQ_OP:
2208 case OID_BPCHAR_REGEXEQ_OP:
2209 case OID_NAME_REGEXEQ_OP:
2210 /* the right-hand const is type text for all of these */
2211 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Regex,
2213 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2216 case OID_TEXT_ICREGEXEQ_OP:
2217 case OID_BPCHAR_ICREGEXEQ_OP:
2218 case OID_NAME_ICREGEXEQ_OP:
2219 /* the right-hand const is type text for all of these */
2220 pstatus = pattern_fixed_prefix(patt, Pattern_Type_Regex_IC,
2222 result = prefix_quals(leftop, opfamily, prefix, pstatus);
2225 case OID_INET_SUB_OP:
2226 case OID_INET_SUBEQ_OP:
2227 result = network_prefix_quals(leftop, expr_op, opfamily,
2232 result = list_make1(rinfo);
2240 * expand_indexqual_rowcompare --- expand a single indexqual condition
2241 * that is a RowCompareExpr
2243 * It's already known that the first column of the row comparison matches
2244 * the specified column of the index. We can use additional columns of the
2245 * row comparison as index qualifications, so long as they match the index
2246 * in the "same direction", ie, the indexkeys are all on the same side of the
2247 * clause and the operators are all the same-type members of the opfamilies.
2248 * If all the columns of the RowCompareExpr match in this way, we just use it
2249 * as-is. Otherwise, we build a shortened RowCompareExpr (if more than one
2250 * column matches) or a simple OpExpr (if the first-column match is all
2251 * there is). In these cases the modified clause is always "<=" or ">="
2252 * even when the original was "<" or ">" --- this is necessary to match all
2253 * the rows that could match the original. (We are essentially building a
2254 * lossy version of the row comparison when we do this.)
2256 static RestrictInfo *
2257 expand_indexqual_rowcompare(RestrictInfo *rinfo,
2258 IndexOptInfo *index,
2261 RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
2273 ListCell *largs_cell;
2274 ListCell *rargs_cell;
2275 ListCell *opnos_cell;
2277 /* We have to figure out (again) how the first col matches */
2278 var_on_left = match_index_to_operand((Node *) linitial(clause->largs),
2280 Assert(var_on_left ||
2281 match_index_to_operand((Node *) linitial(clause->rargs),
2283 expr_op = linitial_oid(clause->opnos);
2285 expr_op = get_commutator(expr_op);
2286 get_op_opfamily_properties(expr_op, index->opfamily[indexcol],
2291 /* Build lists of the opfamilies and operator datatypes in case needed */
2292 opfamilies = list_make1_oid(index->opfamily[indexcol]);
2293 lefttypes = list_make1_oid(op_lefttype);
2294 righttypes = list_make1_oid(op_righttype);
2297 * See how many of the remaining columns match some index column in the
2298 * same way. A note about rel membership tests: we assume that the clause
2299 * as a whole is already known to use only Vars from the indexed relation
2300 * and possibly some acceptable outer relations. So the "other" side of
2301 * any potential index condition is OK as long as it doesn't use Vars from
2302 * the indexed relation.
2305 largs_cell = lnext(list_head(clause->largs));
2306 rargs_cell = lnext(list_head(clause->rargs));
2307 opnos_cell = lnext(list_head(clause->opnos));
2309 while (largs_cell != NULL)
2315 expr_op = lfirst_oid(opnos_cell);
2318 varop = (Node *) lfirst(largs_cell);
2319 constop = (Node *) lfirst(rargs_cell);
2323 varop = (Node *) lfirst(rargs_cell);
2324 constop = (Node *) lfirst(largs_cell);
2325 /* indexkey is on right, so commute the operator */
2326 expr_op = get_commutator(expr_op);
2327 if (expr_op == InvalidOid)
2328 break; /* operator is not usable */
2330 if (bms_is_member(index->rel->relid, pull_varnos(constop)))
2331 break; /* no good, Var on wrong side */
2332 if (contain_volatile_functions(constop))
2333 break; /* no good, volatile comparison value */
2336 * The Var side can match any column of the index. If the user does
2337 * something weird like having multiple identical index columns, we
2338 * insist the match be on the first such column, to avoid confusing
2341 for (i = 0; i < index->ncolumns; i++)
2343 if (match_index_to_operand(varop, i, index))
2346 if (i >= index->ncolumns)
2347 break; /* no match found */
2349 /* Now, do we have the right operator for this column? */
2350 if (get_op_opfamily_strategy(expr_op, index->opfamily[i])
2354 /* Add opfamily and datatypes to lists */
2355 get_op_opfamily_properties(expr_op, index->opfamily[i],
2360 opfamilies = lappend_oid(opfamilies, index->opfamily[i]);
2361 lefttypes = lappend_oid(lefttypes, op_lefttype);
2362 righttypes = lappend_oid(righttypes, op_righttype);
2364 /* This column matches, keep scanning */
2366 largs_cell = lnext(largs_cell);
2367 rargs_cell = lnext(rargs_cell);
2368 opnos_cell = lnext(opnos_cell);
2371 /* Return clause as-is if it's all usable as index quals */
2372 if (matching_cols == list_length(clause->opnos))
2376 * We have to generate a subset rowcompare (possibly just one OpExpr). The
2377 * painful part of this is changing < to <= or > to >=, so deal with that
2380 if (op_strategy == BTLessEqualStrategyNumber ||
2381 op_strategy == BTGreaterEqualStrategyNumber)
2383 /* easy, just use the same operators */
2384 new_ops = list_truncate(list_copy(clause->opnos), matching_cols);
2388 ListCell *opfamilies_cell;
2389 ListCell *lefttypes_cell;
2390 ListCell *righttypes_cell;
2392 if (op_strategy == BTLessStrategyNumber)
2393 op_strategy = BTLessEqualStrategyNumber;
2394 else if (op_strategy == BTGreaterStrategyNumber)
2395 op_strategy = BTGreaterEqualStrategyNumber;
2397 elog(ERROR, "unexpected strategy number %d", op_strategy);
2399 lefttypes_cell = list_head(lefttypes);
2400 righttypes_cell = list_head(righttypes);
2401 foreach(opfamilies_cell, opfamilies)
2403 Oid opfam = lfirst_oid(opfamilies_cell);
2404 Oid lefttype = lfirst_oid(lefttypes_cell);
2405 Oid righttype = lfirst_oid(righttypes_cell);
2407 expr_op = get_opfamily_member(opfam, lefttype, righttype,
2409 if (!OidIsValid(expr_op)) /* should not happen */
2410 elog(ERROR, "could not find member %d(%u,%u) of opfamily %u",
2411 op_strategy, lefttype, righttype, opfam);
2414 expr_op = get_commutator(expr_op);
2415 if (!OidIsValid(expr_op)) /* should not happen */
2416 elog(ERROR, "could not find commutator of member %d(%u,%u) of opfamily %u",
2417 op_strategy, lefttype, righttype, opfam);
2419 new_ops = lappend_oid(new_ops, expr_op);
2421 lefttypes_cell = lnext(lefttypes_cell);
2422 righttypes_cell = lnext(righttypes_cell);
2425 /* If we have more than one matching col, create a subset rowcompare */
2426 if (matching_cols > 1)
2428 RowCompareExpr *rc = makeNode(RowCompareExpr);
2431 rc->rctype = (RowCompareType) op_strategy;
2433 rc->rctype = (op_strategy == BTLessEqualStrategyNumber) ?
2434 ROWCOMPARE_GE : ROWCOMPARE_LE;
2435 rc->opnos = new_ops;
2436 rc->opfamilies = list_truncate(list_copy(clause->opfamilies),
2438 rc->largs = list_truncate((List *) copyObject(clause->largs),
2440 rc->rargs = list_truncate((List *) copyObject(clause->rargs),
2442 return make_restrictinfo((Expr *) rc, true, false, false, NULL);
2448 opexpr = make_opclause(linitial_oid(new_ops), BOOLOID, false,
2449 copyObject(linitial(clause->largs)),
2450 copyObject(linitial(clause->rargs)));
2451 return make_restrictinfo(opexpr, true, false, false, NULL);
2456 * Given a fixed prefix that all the "leftop" values must have,
2457 * generate suitable indexqual condition(s). opfamily is the index
2458 * operator family; we use it to deduce the appropriate comparison
2459 * operators and operand datatypes.
2462 prefix_quals(Node *leftop, Oid opfamily,
2463 Const *prefix_const, Pattern_Prefix_Status pstatus)
2471 Assert(pstatus != Pattern_Prefix_None);
2475 case TEXT_BTREE_FAM_OID:
2476 case TEXT_PATTERN_BTREE_FAM_OID:
2480 case BPCHAR_BTREE_FAM_OID:
2481 case BPCHAR_PATTERN_BTREE_FAM_OID:
2482 datatype = BPCHAROID;
2485 case NAME_BTREE_FAM_OID:
2486 case NAME_PATTERN_BTREE_FAM_OID:
2490 case BYTEA_BTREE_FAM_OID:
2491 datatype = BYTEAOID;
2495 /* shouldn't get here */
2496 elog(ERROR, "unexpected opfamily: %u", opfamily);
2501 * If necessary, coerce the prefix constant to the right type. The given
2502 * prefix constant is either text or bytea type.
2504 if (prefix_const->consttype != datatype)
2508 switch (prefix_const->consttype)
2511 prefix = DatumGetCString(DirectFunctionCall1(textout,
2512 prefix_const->constvalue));
2515 prefix = DatumGetCString(DirectFunctionCall1(byteaout,
2516 prefix_const->constvalue));
2519 elog(ERROR, "unexpected const type: %u",
2520 prefix_const->consttype);
2523 prefix_const = string_to_const(prefix, datatype);
2528 * If we found an exact-match pattern, generate an "=" indexqual.
2530 if (pstatus == Pattern_Prefix_Exact)
2532 oproid = get_opfamily_member(opfamily, datatype, datatype,
2533 BTEqualStrategyNumber);
2534 if (oproid == InvalidOid)
2535 elog(ERROR, "no = operator for opfamily %u", opfamily);
2536 expr = make_opclause(oproid, BOOLOID, false,
2537 (Expr *) leftop, (Expr *) prefix_const);
2538 result = list_make1(make_restrictinfo(expr, true, false, false, NULL));
2543 * Otherwise, we have a nonempty required prefix of the values.
2545 * We can always say "x >= prefix".
2547 oproid = get_opfamily_member(opfamily, datatype, datatype,
2548 BTGreaterEqualStrategyNumber);
2549 if (oproid == InvalidOid)
2550 elog(ERROR, "no >= operator for opfamily %u", opfamily);
2551 expr = make_opclause(oproid, BOOLOID, false,
2552 (Expr *) leftop, (Expr *) prefix_const);
2553 result = list_make1(make_restrictinfo(expr, true, false, false, NULL));
2556 * If we can create a string larger than the prefix, we can say
2560 greaterstr = make_greater_string(prefix_const);
2563 oproid = get_opfamily_member(opfamily, datatype, datatype,
2564 BTLessStrategyNumber);
2565 if (oproid == InvalidOid)
2566 elog(ERROR, "no < operator for opfamily %u", opfamily);
2567 expr = make_opclause(oproid, BOOLOID, false,
2568 (Expr *) leftop, (Expr *) greaterstr);
2569 result = lappend(result,
2570 make_restrictinfo(expr, true, false, false, NULL));
2577 * Given a leftop and a rightop, and a inet-family sup/sub operator,
2578 * generate suitable indexqual condition(s). expr_op is the original
2579 * operator, and opfamily is the index opfamily.
2582 network_prefix_quals(Node *leftop, Oid expr_op, Oid opfamily, Datum rightop)
2595 case OID_INET_SUB_OP:
2599 case OID_INET_SUBEQ_OP:
2604 elog(ERROR, "unexpected operator: %u", expr_op);
2609 * create clause "key >= network_scan_first( rightop )", or ">" if the
2610 * operator disallows equality.
2614 opr1oid = get_opfamily_member(opfamily, datatype, datatype,
2615 BTGreaterEqualStrategyNumber);
2616 if (opr1oid == InvalidOid)
2617 elog(ERROR, "no >= operator for opfamily %u", opfamily);
2621 opr1oid = get_opfamily_member(opfamily, datatype, datatype,
2622 BTGreaterStrategyNumber);
2623 if (opr1oid == InvalidOid)
2624 elog(ERROR, "no > operator for opfamily %u", opfamily);
2627 opr1right = network_scan_first(rightop);
2629 expr = make_opclause(opr1oid, BOOLOID, false,
2631 (Expr *) makeConst(datatype, -1, opr1right,
2633 result = list_make1(make_restrictinfo(expr, true, false, false, NULL));
2635 /* create clause "key <= network_scan_last( rightop )" */
2637 opr2oid = get_opfamily_member(opfamily, datatype, datatype,
2638 BTLessEqualStrategyNumber);
2639 if (opr2oid == InvalidOid)
2640 elog(ERROR, "no <= operator for opfamily %u", opfamily);
2642 opr2right = network_scan_last(rightop);
2644 expr = make_opclause(opr2oid, BOOLOID, false,
2646 (Expr *) makeConst(datatype, -1, opr2right,
2648 result = lappend(result,
2649 make_restrictinfo(expr, true, false, false, NULL));
2655 * Handy subroutines for match_special_index_operator() and friends.
2659 * Generate a Datum of the appropriate type from a C string.
2660 * Note that all of the supported types are pass-by-ref, so the
2661 * returned value should be pfree'd if no longer needed.
2664 string_to_datum(const char *str, Oid datatype)
2667 * We cheat a little by assuming that textin() will do for bpchar and
2668 * varchar constants too...
2670 if (datatype == NAMEOID)
2671 return DirectFunctionCall1(namein, CStringGetDatum(str));
2672 else if (datatype == BYTEAOID)
2673 return DirectFunctionCall1(byteain, CStringGetDatum(str));
2675 return DirectFunctionCall1(textin, CStringGetDatum(str));
2679 * Generate a Const node of the appropriate type from a C string.
2682 string_to_const(const char *str, Oid datatype)
2684 Datum conval = string_to_datum(str, datatype);
2686 return makeConst(datatype, ((datatype == NAMEOID) ? NAMEDATALEN : -1),
2687 conval, false, false);