Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * indxpath.c
4 : * Routines to determine which indexes are usable for scanning a
5 : * given relation, and create Paths accordingly.
6 : *
7 : * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
8 : * Portions Copyright (c) 1994, Regents of the University of California
9 : *
10 : *
11 : * IDENTIFICATION
12 : * src/backend/optimizer/path/indxpath.c
13 : *
14 : *-------------------------------------------------------------------------
15 : */
16 : #include "postgres.h"
17 :
18 : #include <math.h>
19 :
20 : #include "access/stratnum.h"
21 : #include "access/sysattr.h"
22 : #include "catalog/pg_am.h"
23 : #include "catalog/pg_operator.h"
24 : #include "catalog/pg_opfamily.h"
25 : #include "catalog/pg_type.h"
26 : #include "nodes/makefuncs.h"
27 : #include "nodes/nodeFuncs.h"
28 : #include "nodes/supportnodes.h"
29 : #include "optimizer/cost.h"
30 : #include "optimizer/optimizer.h"
31 : #include "optimizer/pathnode.h"
32 : #include "optimizer/paths.h"
33 : #include "optimizer/prep.h"
34 : #include "optimizer/restrictinfo.h"
35 : #include "utils/lsyscache.h"
36 : #include "utils/selfuncs.h"
37 :
38 :
39 : /* XXX see PartCollMatchesExprColl */
40 : #define IndexCollMatchesExprColl(idxcollation, exprcollation) \
41 : ((idxcollation) == InvalidOid || (idxcollation) == (exprcollation))
42 :
43 : /* Whether we are looking for plain indexscan, bitmap scan, or either */
44 : typedef enum
45 : {
46 : ST_INDEXSCAN, /* must support amgettuple */
47 : ST_BITMAPSCAN, /* must support amgetbitmap */
48 : ST_ANYSCAN /* either is okay */
49 : } ScanTypeControl;
50 :
51 : /* Data structure for collecting qual clauses that match an index */
52 : typedef struct
53 : {
54 : bool nonempty; /* True if lists are not all empty */
55 : /* Lists of IndexClause nodes, one list per index column */
56 : List *indexclauses[INDEX_MAX_KEYS];
57 : } IndexClauseSet;
58 :
59 : /* Per-path data used within choose_bitmap_and() */
60 : typedef struct
61 : {
62 : Path *path; /* IndexPath, BitmapAndPath, or BitmapOrPath */
63 : List *quals; /* the WHERE clauses it uses */
64 : List *preds; /* predicates of its partial index(es) */
65 : Bitmapset *clauseids; /* quals+preds represented as a bitmapset */
66 : bool unclassifiable; /* has too many quals+preds to process? */
67 : } PathClauseUsage;
68 :
69 : /* Callback argument for ec_member_matches_indexcol */
70 : typedef struct
71 : {
72 : IndexOptInfo *index; /* index we're considering */
73 : int indexcol; /* index column we want to match to */
74 : } ec_member_matches_arg;
75 :
76 :
77 : static void consider_index_join_clauses(PlannerInfo *root, RelOptInfo *rel,
78 : IndexOptInfo *index,
79 : IndexClauseSet *rclauseset,
80 : IndexClauseSet *jclauseset,
81 : IndexClauseSet *eclauseset,
82 : List **bitindexpaths);
83 : static void consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
84 : IndexOptInfo *index,
85 : IndexClauseSet *rclauseset,
86 : IndexClauseSet *jclauseset,
87 : IndexClauseSet *eclauseset,
88 : List **bitindexpaths,
89 : List *indexjoinclauses,
90 : int considered_clauses,
91 : List **considered_relids);
92 : static void get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
93 : IndexOptInfo *index,
94 : IndexClauseSet *rclauseset,
95 : IndexClauseSet *jclauseset,
96 : IndexClauseSet *eclauseset,
97 : List **bitindexpaths,
98 : Relids relids,
99 : List **considered_relids);
100 : static bool eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
101 : List *indexjoinclauses);
102 : static bool bms_equal_any(Relids relids, List *relids_list);
103 : static void get_index_paths(PlannerInfo *root, RelOptInfo *rel,
104 : IndexOptInfo *index, IndexClauseSet *clauses,
105 : List **bitindexpaths);
106 : static List *build_index_paths(PlannerInfo *root, RelOptInfo *rel,
107 : IndexOptInfo *index, IndexClauseSet *clauses,
108 : bool useful_predicate,
109 : ScanTypeControl scantype,
110 : bool *skip_nonnative_saop,
111 : bool *skip_lower_saop);
112 : static List *build_paths_for_OR(PlannerInfo *root, RelOptInfo *rel,
113 : List *clauses, List *other_clauses);
114 : static List *generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
115 : List *clauses, List *other_clauses);
116 : static Path *choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel,
117 : List *paths);
118 : static int path_usage_comparator(const void *a, const void *b);
119 : static Cost bitmap_scan_cost_est(PlannerInfo *root, RelOptInfo *rel,
120 : Path *ipath);
121 : static Cost bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel,
122 : List *paths);
123 : static PathClauseUsage *classify_index_clause_usage(Path *path,
124 : List **clauselist);
125 : static void find_indexpath_quals(Path *bitmapqual, List **quals, List **preds);
126 : static int find_list_position(Node *node, List **nodelist);
127 : static bool check_index_only(RelOptInfo *rel, IndexOptInfo *index);
128 : static double get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids);
129 : static double adjust_rowcount_for_semijoins(PlannerInfo *root,
130 : Index cur_relid,
131 : Index outer_relid,
132 : double rowcount);
133 : static double approximate_joinrel_size(PlannerInfo *root, Relids relids);
134 : static void match_restriction_clauses_to_index(PlannerInfo *root,
135 : IndexOptInfo *index,
136 : IndexClauseSet *clauseset);
137 : static void match_join_clauses_to_index(PlannerInfo *root,
138 : RelOptInfo *rel, IndexOptInfo *index,
139 : IndexClauseSet *clauseset,
140 : List **joinorclauses);
141 : static void match_eclass_clauses_to_index(PlannerInfo *root,
142 : IndexOptInfo *index,
143 : IndexClauseSet *clauseset);
144 : static void match_clauses_to_index(PlannerInfo *root,
145 : List *clauses,
146 : IndexOptInfo *index,
147 : IndexClauseSet *clauseset);
148 : static void match_clause_to_index(PlannerInfo *root,
149 : RestrictInfo *rinfo,
150 : IndexOptInfo *index,
151 : IndexClauseSet *clauseset);
152 : static IndexClause *match_clause_to_indexcol(PlannerInfo *root,
153 : RestrictInfo *rinfo,
154 : int indexcol,
155 : IndexOptInfo *index);
156 : static IndexClause *match_boolean_index_clause(PlannerInfo *root,
157 : RestrictInfo *rinfo,
158 : int indexcol, IndexOptInfo *index);
159 : static IndexClause *match_opclause_to_indexcol(PlannerInfo *root,
160 : RestrictInfo *rinfo,
161 : int indexcol,
162 : IndexOptInfo *index);
163 : static IndexClause *match_funcclause_to_indexcol(PlannerInfo *root,
164 : RestrictInfo *rinfo,
165 : int indexcol,
166 : IndexOptInfo *index);
167 : static IndexClause *get_index_clause_from_support(PlannerInfo *root,
168 : RestrictInfo *rinfo,
169 : Oid funcid,
170 : int indexarg,
171 : int indexcol,
172 : IndexOptInfo *index);
173 : static IndexClause *match_saopclause_to_indexcol(PlannerInfo *root,
174 : RestrictInfo *rinfo,
175 : int indexcol,
176 : IndexOptInfo *index);
177 : static IndexClause *match_rowcompare_to_indexcol(PlannerInfo *root,
178 : RestrictInfo *rinfo,
179 : int indexcol,
180 : IndexOptInfo *index);
181 : static IndexClause *expand_indexqual_rowcompare(PlannerInfo *root,
182 : RestrictInfo *rinfo,
183 : int indexcol,
184 : IndexOptInfo *index,
185 : Oid expr_op,
186 : bool var_on_left);
187 : static void match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
188 : List **orderby_clauses_p,
189 : List **clause_columns_p);
190 : static Expr *match_clause_to_ordering_op(IndexOptInfo *index,
191 : int indexcol, Expr *clause, Oid pk_opfamily);
192 : static bool ec_member_matches_indexcol(PlannerInfo *root, RelOptInfo *rel,
193 : EquivalenceClass *ec, EquivalenceMember *em,
194 : void *arg);
195 :
196 :
197 : /*
198 : * create_index_paths()
199 : * Generate all interesting index paths for the given relation.
200 : * Candidate paths are added to the rel's pathlist (using add_path).
201 : *
202 : * To be considered for an index scan, an index must match one or more
203 : * restriction clauses or join clauses from the query's qual condition,
204 : * or match the query's ORDER BY condition, or have a predicate that
205 : * matches the query's qual condition.
206 : *
207 : * There are two basic kinds of index scans. A "plain" index scan uses
208 : * only restriction clauses (possibly none at all) in its indexqual,
209 : * so it can be applied in any context. A "parameterized" index scan uses
210 : * join clauses (plus restriction clauses, if available) in its indexqual.
211 : * When joining such a scan to one of the relations supplying the other
212 : * variables used in its indexqual, the parameterized scan must appear as
213 : * the inner relation of a nestloop join; it can't be used on the outer side,
214 : * nor in a merge or hash join. In that context, values for the other rels'
215 : * attributes are available and fixed during any one scan of the indexpath.
216 : *
217 : * An IndexPath is generated and submitted to add_path() for each plain or
218 : * parameterized index scan this routine deems potentially interesting for
219 : * the current query.
220 : *
221 : * 'rel' is the relation for which we want to generate index paths
222 : *
223 : * Note: check_index_predicates() must have been run previously for this rel.
224 : *
225 : * Note: in cases involving LATERAL references in the relation's tlist, it's
226 : * possible that rel->lateral_relids is nonempty. Currently, we include
227 : * lateral_relids into the parameterization reported for each path, but don't
228 : * take it into account otherwise. The fact that any such rels *must* be
229 : * available as parameter sources perhaps should influence our choices of
230 : * index quals ... but for now, it doesn't seem worth troubling over.
231 : * In particular, comments below about "unparameterized" paths should be read
232 : * as meaning "unparameterized so far as the indexquals are concerned".
233 : */
234 : void
235 237388 : create_index_paths(PlannerInfo *root, RelOptInfo *rel)
236 : {
237 : List *indexpaths;
238 : List *bitindexpaths;
239 : List *bitjoinpaths;
240 : List *joinorclauses;
241 : IndexClauseSet rclauseset;
242 : IndexClauseSet jclauseset;
243 : IndexClauseSet eclauseset;
244 : ListCell *lc;
245 :
246 : /* Skip the whole mess if no indexes */
247 237388 : if (rel->indexlist == NIL)
248 39922 : return;
249 :
250 : /* Bitmap paths are collected and then dealt with at the end */
251 197466 : bitindexpaths = bitjoinpaths = joinorclauses = NIL;
252 :
253 : /* Examine each index in turn */
254 606596 : foreach(lc, rel->indexlist)
255 : {
256 409130 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
257 :
258 : /* Protect limited-size array in IndexClauseSets */
259 : Assert(index->nkeycolumns <= INDEX_MAX_KEYS);
260 :
261 : /*
262 : * Ignore partial indexes that do not match the query.
263 : * (generate_bitmap_or_paths() might be able to do something with
264 : * them, but that's of no concern here.)
265 : */
266 409130 : if (index->indpred != NIL && !index->predOK)
267 330 : continue;
268 :
269 : /*
270 : * Identify the restriction clauses that can match the index.
271 : */
272 13899200 : MemSet(&rclauseset, 0, sizeof(rclauseset));
273 408800 : match_restriction_clauses_to_index(root, index, &rclauseset);
274 :
275 : /*
276 : * Build index paths from the restriction clauses. These will be
277 : * non-parameterized paths. Plain paths go directly to add_path(),
278 : * bitmap paths are added to bitindexpaths to be handled below.
279 : */
280 408800 : get_index_paths(root, rel, index, &rclauseset,
281 : &bitindexpaths);
282 :
283 : /*
284 : * Identify the join clauses that can match the index. For the moment
285 : * we keep them separate from the restriction clauses. Note that this
286 : * step finds only "loose" join clauses that have not been merged into
287 : * EquivalenceClasses. Also, collect join OR clauses for later.
288 : */
289 13899200 : MemSet(&jclauseset, 0, sizeof(jclauseset));
290 408800 : match_join_clauses_to_index(root, rel, index,
291 : &jclauseset, &joinorclauses);
292 :
293 : /*
294 : * Look for EquivalenceClasses that can generate joinclauses matching
295 : * the index.
296 : */
297 13899200 : MemSet(&eclauseset, 0, sizeof(eclauseset));
298 408800 : match_eclass_clauses_to_index(root, index,
299 : &eclauseset);
300 :
301 : /*
302 : * If we found any plain or eclass join clauses, build parameterized
303 : * index paths using them.
304 : */
305 408800 : if (jclauseset.nonempty || eclauseset.nonempty)
306 62002 : consider_index_join_clauses(root, rel, index,
307 : &rclauseset,
308 : &jclauseset,
309 : &eclauseset,
310 : &bitjoinpaths);
311 : }
312 :
313 : /*
314 : * Generate BitmapOrPaths for any suitable OR-clauses present in the
315 : * restriction list. Add these to bitindexpaths.
316 : */
317 197466 : indexpaths = generate_bitmap_or_paths(root, rel,
318 : rel->baserestrictinfo, NIL);
319 197466 : bitindexpaths = list_concat(bitindexpaths, indexpaths);
320 :
321 : /*
322 : * Likewise, generate BitmapOrPaths for any suitable OR-clauses present in
323 : * the joinclause list. Add these to bitjoinpaths.
324 : */
325 197466 : indexpaths = generate_bitmap_or_paths(root, rel,
326 : joinorclauses, rel->baserestrictinfo);
327 197466 : bitjoinpaths = list_concat(bitjoinpaths, indexpaths);
328 :
329 : /*
330 : * If we found anything usable, generate a BitmapHeapPath for the most
331 : * promising combination of restriction bitmap index paths. Note there
332 : * will be only one such path no matter how many indexes exist. This
333 : * should be sufficient since there's basically only one figure of merit
334 : * (total cost) for such a path.
335 : */
336 197466 : if (bitindexpaths != NIL)
337 : {
338 : Path *bitmapqual;
339 : BitmapHeapPath *bpath;
340 :
341 125592 : bitmapqual = choose_bitmap_and(root, rel, bitindexpaths);
342 125592 : bpath = create_bitmap_heap_path(root, rel, bitmapqual,
343 : rel->lateral_relids, 1.0, 0);
344 125592 : add_path(rel, (Path *) bpath);
345 :
346 : /* create a partial bitmap heap path */
347 125592 : if (rel->consider_parallel && rel->lateral_relids == NULL)
348 76034 : create_partial_bitmap_paths(root, rel, bitmapqual);
349 : }
350 :
351 : /*
352 : * Likewise, if we found anything usable, generate BitmapHeapPaths for the
353 : * most promising combinations of join bitmap index paths. Our strategy
354 : * is to generate one such path for each distinct parameterization seen
355 : * among the available bitmap index paths. This may look pretty
356 : * expensive, but usually there won't be very many distinct
357 : * parameterizations. (This logic is quite similar to that in
358 : * consider_index_join_clauses, but we're working with whole paths not
359 : * individual clauses.)
360 : */
361 197466 : if (bitjoinpaths != NIL)
362 : {
363 : List *all_path_outers;
364 : ListCell *lc;
365 :
366 : /* Identify each distinct parameterization seen in bitjoinpaths */
367 57500 : all_path_outers = NIL;
368 121472 : foreach(lc, bitjoinpaths)
369 : {
370 63972 : Path *path = (Path *) lfirst(lc);
371 63972 : Relids required_outer = PATH_REQ_OUTER(path);
372 :
373 63972 : if (!bms_equal_any(required_outer, all_path_outers))
374 62272 : all_path_outers = lappend(all_path_outers, required_outer);
375 : }
376 :
377 : /* Now, for each distinct parameterization set ... */
378 119772 : foreach(lc, all_path_outers)
379 : {
380 62272 : Relids max_outers = (Relids) lfirst(lc);
381 : List *this_path_set;
382 : Path *bitmapqual;
383 : Relids required_outer;
384 : double loop_count;
385 : BitmapHeapPath *bpath;
386 : ListCell *lcp;
387 :
388 : /* Identify all the bitmap join paths needing no more than that */
389 62272 : this_path_set = NIL;
390 137440 : foreach(lcp, bitjoinpaths)
391 : {
392 75168 : Path *path = (Path *) lfirst(lcp);
393 :
394 75168 : if (bms_is_subset(PATH_REQ_OUTER(path), max_outers))
395 64388 : this_path_set = lappend(this_path_set, path);
396 : }
397 :
398 : /*
399 : * Add in restriction bitmap paths, since they can be used
400 : * together with any join paths.
401 : */
402 62272 : this_path_set = list_concat(this_path_set, bitindexpaths);
403 :
404 : /* Select best AND combination for this parameterization */
405 62272 : bitmapqual = choose_bitmap_and(root, rel, this_path_set);
406 :
407 : /* And push that path into the mix */
408 62272 : required_outer = PATH_REQ_OUTER(bitmapqual);
409 62272 : loop_count = get_loop_count(root, rel->relid, required_outer);
410 62272 : bpath = create_bitmap_heap_path(root, rel, bitmapqual,
411 : required_outer, loop_count, 0);
412 62272 : add_path(rel, (Path *) bpath);
413 : }
414 : }
415 : }
416 :
417 : /*
418 : * consider_index_join_clauses
419 : * Given sets of join clauses for an index, decide which parameterized
420 : * index paths to build.
421 : *
422 : * Plain indexpaths are sent directly to add_path, while potential
423 : * bitmap indexpaths are added to *bitindexpaths for later processing.
424 : *
425 : * 'rel' is the index's heap relation
426 : * 'index' is the index for which we want to generate paths
427 : * 'rclauseset' is the collection of indexable restriction clauses
428 : * 'jclauseset' is the collection of indexable simple join clauses
429 : * 'eclauseset' is the collection of indexable clauses from EquivalenceClasses
430 : * '*bitindexpaths' is the list to add bitmap paths to
431 : */
432 : static void
433 62002 : consider_index_join_clauses(PlannerInfo *root, RelOptInfo *rel,
434 : IndexOptInfo *index,
435 : IndexClauseSet *rclauseset,
436 : IndexClauseSet *jclauseset,
437 : IndexClauseSet *eclauseset,
438 : List **bitindexpaths)
439 : {
440 62002 : int considered_clauses = 0;
441 62002 : List *considered_relids = NIL;
442 : int indexcol;
443 :
444 : /*
445 : * The strategy here is to identify every potentially useful set of outer
446 : * rels that can provide indexable join clauses. For each such set,
447 : * select all the join clauses available from those outer rels, add on all
448 : * the indexable restriction clauses, and generate plain and/or bitmap
449 : * index paths for that set of clauses. This is based on the assumption
450 : * that it's always better to apply a clause as an indexqual than as a
451 : * filter (qpqual); which is where an available clause would end up being
452 : * applied if we omit it from the indexquals.
453 : *
454 : * This looks expensive, but in most practical cases there won't be very
455 : * many distinct sets of outer rels to consider. As a safety valve when
456 : * that's not true, we use a heuristic: limit the number of outer rel sets
457 : * considered to a multiple of the number of clauses considered. (We'll
458 : * always consider using each individual join clause, though.)
459 : *
460 : * For simplicity in selecting relevant clauses, we represent each set of
461 : * outer rels as a maximum set of clause_relids --- that is, the indexed
462 : * relation itself is also included in the relids set. considered_relids
463 : * lists all relids sets we've already tried.
464 : */
465 157746 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
466 : {
467 : /* Consider each applicable simple join clause */
468 95744 : considered_clauses += list_length(jclauseset->indexclauses[indexcol]);
469 95744 : consider_index_join_outer_rels(root, rel, index,
470 : rclauseset, jclauseset, eclauseset,
471 : bitindexpaths,
472 : jclauseset->indexclauses[indexcol],
473 : considered_clauses,
474 : &considered_relids);
475 : /* Consider each applicable eclass join clause */
476 95744 : considered_clauses += list_length(eclauseset->indexclauses[indexcol]);
477 95744 : consider_index_join_outer_rels(root, rel, index,
478 : rclauseset, jclauseset, eclauseset,
479 : bitindexpaths,
480 : eclauseset->indexclauses[indexcol],
481 : considered_clauses,
482 : &considered_relids);
483 : }
484 62002 : }
485 :
486 : /*
487 : * consider_index_join_outer_rels
488 : * Generate parameterized paths based on clause relids in the clause list.
489 : *
490 : * Workhorse for consider_index_join_clauses; see notes therein for rationale.
491 : *
492 : * 'rel', 'index', 'rclauseset', 'jclauseset', 'eclauseset', and
493 : * 'bitindexpaths' as above
494 : * 'indexjoinclauses' is a list of IndexClauses for join clauses
495 : * 'considered_clauses' is the total number of clauses considered (so far)
496 : * '*considered_relids' is a list of all relids sets already considered
497 : */
498 : static void
499 191488 : consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
500 : IndexOptInfo *index,
501 : IndexClauseSet *rclauseset,
502 : IndexClauseSet *jclauseset,
503 : IndexClauseSet *eclauseset,
504 : List **bitindexpaths,
505 : List *indexjoinclauses,
506 : int considered_clauses,
507 : List **considered_relids)
508 : {
509 : ListCell *lc;
510 :
511 : /* Examine relids of each joinclause in the given list */
512 256658 : foreach(lc, indexjoinclauses)
513 : {
514 65170 : IndexClause *iclause = (IndexClause *) lfirst(lc);
515 65170 : Relids clause_relids = iclause->rinfo->clause_relids;
516 65170 : EquivalenceClass *parent_ec = iclause->rinfo->parent_ec;
517 : int num_considered_relids;
518 :
519 : /* If we already tried its relids set, no need to do so again */
520 65170 : if (bms_equal_any(clause_relids, *considered_relids))
521 1446 : continue;
522 :
523 : /*
524 : * Generate the union of this clause's relids set with each
525 : * previously-tried set. This ensures we try this clause along with
526 : * every interesting subset of previous clauses. However, to avoid
527 : * exponential growth of planning time when there are many clauses,
528 : * limit the number of relid sets accepted to 10 * considered_clauses.
529 : *
530 : * Note: get_join_index_paths appends entries to *considered_relids,
531 : * but we do not need to visit such newly-added entries within this
532 : * loop, so we don't use foreach() here. No real harm would be done
533 : * if we did visit them, since the subset check would reject them; but
534 : * it would waste some cycles.
535 : */
536 63724 : num_considered_relids = list_length(*considered_relids);
537 65486 : for (int pos = 0; pos < num_considered_relids; pos++)
538 : {
539 1762 : Relids oldrelids = (Relids) list_nth(*considered_relids, pos);
540 :
541 : /*
542 : * If either is a subset of the other, no new set is possible.
543 : * This isn't a complete test for redundancy, but it's easy and
544 : * cheap. get_join_index_paths will check more carefully if we
545 : * already generated the same relids set.
546 : */
547 1762 : if (bms_subset_compare(clause_relids, oldrelids) != BMS_DIFFERENT)
548 16 : continue;
549 :
550 : /*
551 : * If this clause was derived from an equivalence class, the
552 : * clause list may contain other clauses derived from the same
553 : * eclass. We should not consider that combining this clause with
554 : * one of those clauses generates a usefully different
555 : * parameterization; so skip if any clause derived from the same
556 : * eclass would already have been included when using oldrelids.
557 : */
558 3386 : if (parent_ec &&
559 1640 : eclass_already_used(parent_ec, oldrelids,
560 : indexjoinclauses))
561 1574 : continue;
562 :
563 : /*
564 : * If the number of relid sets considered exceeds our heuristic
565 : * limit, stop considering combinations of clauses. We'll still
566 : * consider the current clause alone, though (below this loop).
567 : */
568 172 : if (list_length(*considered_relids) >= 10 * considered_clauses)
569 0 : break;
570 :
571 : /* OK, try the union set */
572 172 : get_join_index_paths(root, rel, index,
573 : rclauseset, jclauseset, eclauseset,
574 : bitindexpaths,
575 : bms_union(clause_relids, oldrelids),
576 : considered_relids);
577 : }
578 :
579 : /* Also try this set of relids by itself */
580 63724 : get_join_index_paths(root, rel, index,
581 : rclauseset, jclauseset, eclauseset,
582 : bitindexpaths,
583 : clause_relids,
584 : considered_relids);
585 : }
586 191488 : }
587 :
588 : /*
589 : * get_join_index_paths
590 : * Generate index paths using clauses from the specified outer relations.
591 : * In addition to generating paths, relids is added to *considered_relids
592 : * if not already present.
593 : *
594 : * Workhorse for consider_index_join_clauses; see notes therein for rationale.
595 : *
596 : * 'rel', 'index', 'rclauseset', 'jclauseset', 'eclauseset',
597 : * 'bitindexpaths', 'considered_relids' as above
598 : * 'relids' is the current set of relids to consider (the target rel plus
599 : * one or more outer rels)
600 : */
601 : static void
602 63896 : get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
603 : IndexOptInfo *index,
604 : IndexClauseSet *rclauseset,
605 : IndexClauseSet *jclauseset,
606 : IndexClauseSet *eclauseset,
607 : List **bitindexpaths,
608 : Relids relids,
609 : List **considered_relids)
610 : {
611 : IndexClauseSet clauseset;
612 : int indexcol;
613 :
614 : /* If we already considered this relids set, don't repeat the work */
615 63896 : if (bms_equal_any(relids, *considered_relids))
616 0 : return;
617 :
618 : /* Identify indexclauses usable with this relids set */
619 2172464 : MemSet(&clauseset, 0, sizeof(clauseset));
620 :
621 163096 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
622 : {
623 : ListCell *lc;
624 :
625 : /* First find applicable simple join clauses */
626 124464 : foreach(lc, jclauseset->indexclauses[indexcol])
627 : {
628 25264 : IndexClause *iclause = (IndexClause *) lfirst(lc);
629 :
630 25264 : if (bms_is_subset(iclause->rinfo->clause_relids, relids))
631 25030 : clauseset.indexclauses[indexcol] =
632 25030 : lappend(clauseset.indexclauses[indexcol], iclause);
633 : }
634 :
635 : /*
636 : * Add applicable eclass join clauses. The clauses generated for each
637 : * column are redundant (cf generate_implied_equalities_for_column),
638 : * so we need at most one. This is the only exception to the general
639 : * rule of using all available index clauses.
640 : */
641 101194 : foreach(lc, eclauseset->indexclauses[indexcol])
642 : {
643 42466 : IndexClause *iclause = (IndexClause *) lfirst(lc);
644 :
645 42466 : if (bms_is_subset(iclause->rinfo->clause_relids, relids))
646 : {
647 40472 : clauseset.indexclauses[indexcol] =
648 40472 : lappend(clauseset.indexclauses[indexcol], iclause);
649 40472 : break;
650 : }
651 : }
652 :
653 : /* Add restriction clauses */
654 99200 : clauseset.indexclauses[indexcol] =
655 99200 : list_concat(clauseset.indexclauses[indexcol],
656 99200 : rclauseset->indexclauses[indexcol]);
657 :
658 99200 : if (clauseset.indexclauses[indexcol] != NIL)
659 78252 : clauseset.nonempty = true;
660 : }
661 :
662 : /* We should have found something, else caller passed silly relids */
663 : Assert(clauseset.nonempty);
664 :
665 : /* Build index path(s) using the collected set of clauses */
666 63896 : get_index_paths(root, rel, index, &clauseset, bitindexpaths);
667 :
668 : /*
669 : * Remember we considered paths for this set of relids.
670 : */
671 63896 : *considered_relids = lappend(*considered_relids, relids);
672 : }
673 :
674 : /*
675 : * eclass_already_used
676 : * True if any join clause usable with oldrelids was generated from
677 : * the specified equivalence class.
678 : */
679 : static bool
680 1640 : eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
681 : List *indexjoinclauses)
682 : {
683 : ListCell *lc;
684 :
685 1738 : foreach(lc, indexjoinclauses)
686 : {
687 1672 : IndexClause *iclause = (IndexClause *) lfirst(lc);
688 1672 : RestrictInfo *rinfo = iclause->rinfo;
689 :
690 3344 : if (rinfo->parent_ec == parent_ec &&
691 1672 : bms_is_subset(rinfo->clause_relids, oldrelids))
692 1574 : return true;
693 : }
694 66 : return false;
695 : }
696 :
697 : /*
698 : * bms_equal_any
699 : * True if relids is bms_equal to any member of relids_list
700 : *
701 : * Perhaps this should be in bitmapset.c someday.
702 : */
703 : static bool
704 193038 : bms_equal_any(Relids relids, List *relids_list)
705 : {
706 : ListCell *lc;
707 :
708 202864 : foreach(lc, relids_list)
709 : {
710 12972 : if (bms_equal(relids, (Relids) lfirst(lc)))
711 3146 : return true;
712 : }
713 189892 : return false;
714 : }
715 :
716 :
717 : /*
718 : * get_index_paths
719 : * Given an index and a set of index clauses for it, construct IndexPaths.
720 : *
721 : * Plain indexpaths are sent directly to add_path, while potential
722 : * bitmap indexpaths are added to *bitindexpaths for later processing.
723 : *
724 : * This is a fairly simple frontend to build_index_paths(). Its reason for
725 : * existence is mainly to handle ScalarArrayOpExpr quals properly. If the
726 : * index AM supports them natively, we should just include them in simple
727 : * index paths. If not, we should exclude them while building simple index
728 : * paths, and then make a separate attempt to include them in bitmap paths.
729 : * Furthermore, we should consider excluding lower-order ScalarArrayOpExpr
730 : * quals so as to create ordered paths.
731 : */
732 : static void
733 472696 : get_index_paths(PlannerInfo *root, RelOptInfo *rel,
734 : IndexOptInfo *index, IndexClauseSet *clauses,
735 : List **bitindexpaths)
736 : {
737 : List *indexpaths;
738 472696 : bool skip_nonnative_saop = false;
739 472696 : bool skip_lower_saop = false;
740 : ListCell *lc;
741 :
742 : /*
743 : * Build simple index paths using the clauses. Allow ScalarArrayOpExpr
744 : * clauses only if the index AM supports them natively, and skip any such
745 : * clauses for index columns after the first (so that we produce ordered
746 : * paths if possible).
747 : */
748 472696 : indexpaths = build_index_paths(root, rel,
749 : index, clauses,
750 472696 : index->predOK,
751 : ST_ANYSCAN,
752 : &skip_nonnative_saop,
753 : &skip_lower_saop);
754 :
755 : /*
756 : * If we skipped any lower-order ScalarArrayOpExprs on an index with an AM
757 : * that supports them, then try again including those clauses. This will
758 : * produce paths with more selectivity but no ordering.
759 : */
760 472696 : if (skip_lower_saop)
761 : {
762 252 : indexpaths = list_concat(indexpaths,
763 252 : build_index_paths(root, rel,
764 : index, clauses,
765 252 : index->predOK,
766 : ST_ANYSCAN,
767 : &skip_nonnative_saop,
768 : NULL));
769 : }
770 :
771 : /*
772 : * Submit all the ones that can form plain IndexScan plans to add_path. (A
773 : * plain IndexPath can represent either a plain IndexScan or an
774 : * IndexOnlyScan, but for our purposes here that distinction does not
775 : * matter. However, some of the indexes might support only bitmap scans,
776 : * and those we mustn't submit to add_path here.)
777 : *
778 : * Also, pick out the ones that are usable as bitmap scans. For that, we
779 : * must discard indexes that don't support bitmap scans, and we also are
780 : * only interested in paths that have some selectivity; we should discard
781 : * anything that was generated solely for ordering purposes.
782 : */
783 743576 : foreach(lc, indexpaths)
784 : {
785 270880 : IndexPath *ipath = (IndexPath *) lfirst(lc);
786 :
787 270880 : if (index->amhasgettuple)
788 265414 : add_path(rel, (Path *) ipath);
789 :
790 270880 : if (index->amhasgetbitmap &&
791 270880 : (ipath->path.pathkeys == NIL ||
792 144758 : ipath->indexselectivity < 1.0))
793 210004 : *bitindexpaths = lappend(*bitindexpaths, ipath);
794 : }
795 :
796 : /*
797 : * If there were ScalarArrayOpExpr clauses that the index can't handle
798 : * natively, generate bitmap scan paths relying on executor-managed
799 : * ScalarArrayOpExpr.
800 : */
801 472696 : if (skip_nonnative_saop)
802 : {
803 20 : indexpaths = build_index_paths(root, rel,
804 : index, clauses,
805 : false,
806 : ST_BITMAPSCAN,
807 : NULL,
808 : NULL);
809 20 : *bitindexpaths = list_concat(*bitindexpaths, indexpaths);
810 : }
811 472696 : }
812 :
813 : /*
814 : * build_index_paths
815 : * Given an index and a set of index clauses for it, construct zero
816 : * or more IndexPaths. It also constructs zero or more partial IndexPaths.
817 : *
818 : * We return a list of paths because (1) this routine checks some cases
819 : * that should cause us to not generate any IndexPath, and (2) in some
820 : * cases we want to consider both a forward and a backward scan, so as
821 : * to obtain both sort orders. Note that the paths are just returned
822 : * to the caller and not immediately fed to add_path().
823 : *
824 : * At top level, useful_predicate should be exactly the index's predOK flag
825 : * (ie, true if it has a predicate that was proven from the restriction
826 : * clauses). When working on an arm of an OR clause, useful_predicate
827 : * should be true if the predicate required the current OR list to be proven.
828 : * Note that this routine should never be called at all if the index has an
829 : * unprovable predicate.
830 : *
831 : * scantype indicates whether we want to create plain indexscans, bitmap
832 : * indexscans, or both. When it's ST_BITMAPSCAN, we will not consider
833 : * index ordering while deciding if a Path is worth generating.
834 : *
835 : * If skip_nonnative_saop is non-NULL, we ignore ScalarArrayOpExpr clauses
836 : * unless the index AM supports them directly, and we set *skip_nonnative_saop
837 : * to true if we found any such clauses (caller must initialize the variable
838 : * to false). If it's NULL, we do not ignore ScalarArrayOpExpr clauses.
839 : *
840 : * If skip_lower_saop is non-NULL, we ignore ScalarArrayOpExpr clauses for
841 : * non-first index columns, and we set *skip_lower_saop to true if we found
842 : * any such clauses (caller must initialize the variable to false). If it's
843 : * NULL, we do not ignore non-first ScalarArrayOpExpr clauses, but they will
844 : * result in considering the scan's output to be unordered.
845 : *
846 : * 'rel' is the index's heap relation
847 : * 'index' is the index for which we want to generate paths
848 : * 'clauses' is the collection of indexable clauses (IndexClause nodes)
849 : * 'useful_predicate' indicates whether the index has a useful predicate
850 : * 'scantype' indicates whether we need plain or bitmap scan support
851 : * 'skip_nonnative_saop' indicates whether to accept SAOP if index AM doesn't
852 : * 'skip_lower_saop' indicates whether to accept non-first-column SAOP
853 : */
854 : static List *
855 474128 : build_index_paths(PlannerInfo *root, RelOptInfo *rel,
856 : IndexOptInfo *index, IndexClauseSet *clauses,
857 : bool useful_predicate,
858 : ScanTypeControl scantype,
859 : bool *skip_nonnative_saop,
860 : bool *skip_lower_saop)
861 : {
862 474128 : List *result = NIL;
863 : IndexPath *ipath;
864 : List *index_clauses;
865 : Relids outer_relids;
866 : double loop_count;
867 : List *orderbyclauses;
868 : List *orderbyclausecols;
869 : List *index_pathkeys;
870 : List *useful_pathkeys;
871 : bool found_lower_saop_clause;
872 : bool pathkeys_possibly_useful;
873 : bool index_is_ordered;
874 : bool index_only_scan;
875 : int indexcol;
876 :
877 : /*
878 : * Check that index supports the desired scan type(s)
879 : */
880 474128 : switch (scantype)
881 : {
882 0 : case ST_INDEXSCAN:
883 0 : if (!index->amhasgettuple)
884 0 : return NIL;
885 0 : break;
886 1180 : case ST_BITMAPSCAN:
887 1180 : if (!index->amhasgetbitmap)
888 0 : return NIL;
889 1180 : break;
890 472948 : case ST_ANYSCAN:
891 : /* either or both are OK */
892 472948 : break;
893 : }
894 :
895 : /*
896 : * 1. Combine the per-column IndexClause lists into an overall list.
897 : *
898 : * In the resulting list, clauses are ordered by index key, so that the
899 : * column numbers form a nondecreasing sequence. (This order is depended
900 : * on by btree and possibly other places.) The list can be empty, if the
901 : * index AM allows that.
902 : *
903 : * found_lower_saop_clause is set true if we accept a ScalarArrayOpExpr
904 : * index clause for a non-first index column. This prevents us from
905 : * assuming that the scan result is ordered. (Actually, the result is
906 : * still ordered if there are equality constraints for all earlier
907 : * columns, but it seems too expensive and non-modular for this code to be
908 : * aware of that refinement.)
909 : *
910 : * We also build a Relids set showing which outer rels are required by the
911 : * selected clauses. Any lateral_relids are included in that, but not
912 : * otherwise accounted for.
913 : */
914 474128 : index_clauses = NIL;
915 474128 : found_lower_saop_clause = false;
916 474128 : outer_relids = bms_copy(rel->lateral_relids);
917 1322770 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
918 : {
919 : ListCell *lc;
920 :
921 1100460 : foreach(lc, clauses->indexclauses[indexcol])
922 : {
923 251630 : IndexClause *iclause = (IndexClause *) lfirst(lc);
924 251630 : RestrictInfo *rinfo = iclause->rinfo;
925 :
926 : /* We might need to omit ScalarArrayOpExpr clauses */
927 251630 : if (IsA(rinfo->clause, ScalarArrayOpExpr))
928 : {
929 8492 : if (!index->amsearcharray)
930 : {
931 40 : if (skip_nonnative_saop)
932 : {
933 : /* Ignore because not supported by index */
934 20 : *skip_nonnative_saop = true;
935 20 : continue;
936 : }
937 : /* Caller had better intend this only for bitmap scan */
938 : Assert(scantype == ST_BITMAPSCAN);
939 : }
940 8472 : if (indexcol > 0)
941 : {
942 552 : if (skip_lower_saop)
943 : {
944 : /* Caller doesn't want to lose index ordering */
945 276 : *skip_lower_saop = true;
946 276 : continue;
947 : }
948 276 : found_lower_saop_clause = true;
949 : }
950 : }
951 :
952 : /* OK to include this clause */
953 251334 : index_clauses = lappend(index_clauses, iclause);
954 251334 : outer_relids = bms_add_members(outer_relids,
955 251334 : rinfo->clause_relids);
956 : }
957 :
958 : /*
959 : * If no clauses match the first index column, check for amoptionalkey
960 : * restriction. We can't generate a scan over an index with
961 : * amoptionalkey = false unless there's at least one index clause.
962 : * (When working on columns after the first, this test cannot fail. It
963 : * is always okay for columns after the first to not have any
964 : * clauses.)
965 : */
966 848830 : if (index_clauses == NIL && !index->amoptionalkey)
967 188 : return NIL;
968 : }
969 :
970 : /* We do not want the index's rel itself listed in outer_relids */
971 473940 : outer_relids = bms_del_member(outer_relids, rel->relid);
972 : /* Enforce convention that outer_relids is exactly NULL if empty */
973 473940 : if (bms_is_empty(outer_relids))
974 409904 : outer_relids = NULL;
975 :
976 : /* Compute loop_count for cost estimation purposes */
977 473940 : loop_count = get_loop_count(root, rel->relid, outer_relids);
978 :
979 : /*
980 : * 2. Compute pathkeys describing index's ordering, if any, then see how
981 : * many of them are actually useful for this query. This is not relevant
982 : * if we are only trying to build bitmap indexscans, nor if we have to
983 : * assume the scan is unordered.
984 : */
985 946700 : pathkeys_possibly_useful = (scantype != ST_BITMAPSCAN &&
986 946448 : !found_lower_saop_clause &&
987 472508 : has_useful_pathkeys(root, rel));
988 473940 : index_is_ordered = (index->sortopfamily != NULL);
989 473940 : if (index_is_ordered && pathkeys_possibly_useful)
990 : {
991 271978 : index_pathkeys = build_index_pathkeys(root, index,
992 : ForwardScanDirection);
993 271978 : useful_pathkeys = truncate_useless_pathkeys(root, rel,
994 : index_pathkeys);
995 271978 : orderbyclauses = NIL;
996 271978 : orderbyclausecols = NIL;
997 : }
998 201962 : else if (index->amcanorderbyop && pathkeys_possibly_useful)
999 : {
1000 : /* see if we can generate ordering operators for query_pathkeys */
1001 552 : match_pathkeys_to_index(index, root->query_pathkeys,
1002 : &orderbyclauses,
1003 : &orderbyclausecols);
1004 1104 : if (orderbyclauses)
1005 316 : useful_pathkeys = root->query_pathkeys;
1006 : else
1007 236 : useful_pathkeys = NIL;
1008 : }
1009 : else
1010 : {
1011 201410 : useful_pathkeys = NIL;
1012 201410 : orderbyclauses = NIL;
1013 201410 : orderbyclausecols = NIL;
1014 : }
1015 :
1016 : /*
1017 : * 3. Check if an index-only scan is possible. If we're not building
1018 : * plain indexscans, this isn't relevant since bitmap scans don't support
1019 : * index data retrieval anyway.
1020 : */
1021 946700 : index_only_scan = (scantype != ST_BITMAPSCAN &&
1022 472760 : check_index_only(rel, index));
1023 :
1024 : /*
1025 : * 4. Generate an indexscan path if there are relevant restriction clauses
1026 : * in the current clauses, OR the index ordering is potentially useful for
1027 : * later merging or final output ordering, OR the index has a useful
1028 : * predicate, OR an index-only scan is possible.
1029 : */
1030 473940 : if (index_clauses != NIL || useful_pathkeys != NIL || useful_predicate ||
1031 : index_only_scan)
1032 : {
1033 271788 : ipath = create_index_path(root, index,
1034 : index_clauses,
1035 : orderbyclauses,
1036 : orderbyclausecols,
1037 : useful_pathkeys,
1038 : index_is_ordered ?
1039 : ForwardScanDirection :
1040 : NoMovementScanDirection,
1041 : index_only_scan,
1042 : outer_relids,
1043 : loop_count,
1044 : false);
1045 271788 : result = lappend(result, ipath);
1046 :
1047 : /*
1048 : * If appropriate, consider parallel index scan. We don't allow
1049 : * parallel index scan for bitmap index scans.
1050 : */
1051 271788 : if (index->amcanparallel &&
1052 262572 : rel->consider_parallel && outer_relids == NULL &&
1053 : scantype != ST_BITMAPSCAN)
1054 : {
1055 132556 : ipath = create_index_path(root, index,
1056 : index_clauses,
1057 : orderbyclauses,
1058 : orderbyclausecols,
1059 : useful_pathkeys,
1060 : index_is_ordered ?
1061 : ForwardScanDirection :
1062 : NoMovementScanDirection,
1063 : index_only_scan,
1064 : outer_relids,
1065 : loop_count,
1066 : true);
1067 :
1068 : /*
1069 : * if, after costing the path, we find that it's not worth using
1070 : * parallel workers, just free it.
1071 : */
1072 132556 : if (ipath->path.parallel_workers > 0)
1073 6742 : add_partial_path(rel, (Path *) ipath);
1074 : else
1075 125814 : pfree(ipath);
1076 : }
1077 : }
1078 :
1079 : /*
1080 : * 5. If the index is ordered, a backwards scan might be interesting.
1081 : */
1082 473940 : if (index_is_ordered && pathkeys_possibly_useful)
1083 : {
1084 271978 : index_pathkeys = build_index_pathkeys(root, index,
1085 : BackwardScanDirection);
1086 271978 : useful_pathkeys = truncate_useless_pathkeys(root, rel,
1087 : index_pathkeys);
1088 271978 : if (useful_pathkeys != NIL)
1089 : {
1090 272 : ipath = create_index_path(root, index,
1091 : index_clauses,
1092 : NIL,
1093 : NIL,
1094 : useful_pathkeys,
1095 : BackwardScanDirection,
1096 : index_only_scan,
1097 : outer_relids,
1098 : loop_count,
1099 : false);
1100 272 : result = lappend(result, ipath);
1101 :
1102 : /* If appropriate, consider parallel index scan */
1103 272 : if (index->amcanparallel &&
1104 272 : rel->consider_parallel && outer_relids == NULL &&
1105 : scantype != ST_BITMAPSCAN)
1106 : {
1107 236 : ipath = create_index_path(root, index,
1108 : index_clauses,
1109 : NIL,
1110 : NIL,
1111 : useful_pathkeys,
1112 : BackwardScanDirection,
1113 : index_only_scan,
1114 : outer_relids,
1115 : loop_count,
1116 : true);
1117 :
1118 : /*
1119 : * if, after costing the path, we find that it's not worth
1120 : * using parallel workers, just free it.
1121 : */
1122 236 : if (ipath->path.parallel_workers > 0)
1123 112 : add_partial_path(rel, (Path *) ipath);
1124 : else
1125 124 : pfree(ipath);
1126 : }
1127 : }
1128 : }
1129 :
1130 473940 : return result;
1131 : }
1132 :
1133 : /*
1134 : * build_paths_for_OR
1135 : * Given a list of restriction clauses from one arm of an OR clause,
1136 : * construct all matching IndexPaths for the relation.
1137 : *
1138 : * Here we must scan all indexes of the relation, since a bitmap OR tree
1139 : * can use multiple indexes.
1140 : *
1141 : * The caller actually supplies two lists of restriction clauses: some
1142 : * "current" ones and some "other" ones. Both lists can be used freely
1143 : * to match keys of the index, but an index must use at least one of the
1144 : * "current" clauses to be considered usable. The motivation for this is
1145 : * examples like
1146 : * WHERE (x = 42) AND (... OR (y = 52 AND z = 77) OR ....)
1147 : * While we are considering the y/z subclause of the OR, we can use "x = 42"
1148 : * as one of the available index conditions; but we shouldn't match the
1149 : * subclause to any index on x alone, because such a Path would already have
1150 : * been generated at the upper level. So we could use an index on x,y,z
1151 : * or an index on x,y for the OR subclause, but not an index on just x.
1152 : * When dealing with a partial index, a match of the index predicate to
1153 : * one of the "current" clauses also makes the index usable.
1154 : *
1155 : * 'rel' is the relation for which we want to generate index paths
1156 : * 'clauses' is the current list of clauses (RestrictInfo nodes)
1157 : * 'other_clauses' is the list of additional upper-level clauses
1158 : */
1159 : static List *
1160 15828 : build_paths_for_OR(PlannerInfo *root, RelOptInfo *rel,
1161 : List *clauses, List *other_clauses)
1162 : {
1163 15828 : List *result = NIL;
1164 15828 : List *all_clauses = NIL; /* not computed till needed */
1165 : ListCell *lc;
1166 :
1167 55446 : foreach(lc, rel->indexlist)
1168 : {
1169 39618 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
1170 : IndexClauseSet clauseset;
1171 : List *indexpaths;
1172 : bool useful_predicate;
1173 :
1174 : /* Ignore index if it doesn't support bitmap scans */
1175 39618 : if (!index->amhasgetbitmap)
1176 38458 : continue;
1177 :
1178 : /*
1179 : * Ignore partial indexes that do not match the query. If a partial
1180 : * index is marked predOK then we know it's OK. Otherwise, we have to
1181 : * test whether the added clauses are sufficient to imply the
1182 : * predicate. If so, we can use the index in the current context.
1183 : *
1184 : * We set useful_predicate to true iff the predicate was proven using
1185 : * the current set of clauses. This is needed to prevent matching a
1186 : * predOK index to an arm of an OR, which would be a legal but
1187 : * pointlessly inefficient plan. (A better plan will be generated by
1188 : * just scanning the predOK index alone, no OR.)
1189 : */
1190 39618 : useful_predicate = false;
1191 39618 : if (index->indpred != NIL)
1192 : {
1193 96 : if (index->predOK)
1194 : {
1195 : /* Usable, but don't set useful_predicate */
1196 : }
1197 : else
1198 : {
1199 : /* Form all_clauses if not done already */
1200 80 : if (all_clauses == NIL)
1201 32 : all_clauses = list_concat_copy(clauses, other_clauses);
1202 :
1203 80 : if (!predicate_implied_by(index->indpred, all_clauses, false))
1204 56 : continue; /* can't use it at all */
1205 :
1206 24 : if (!predicate_implied_by(index->indpred, other_clauses, false))
1207 24 : useful_predicate = true;
1208 : }
1209 : }
1210 :
1211 : /*
1212 : * Identify the restriction clauses that can match the index.
1213 : */
1214 1345108 : MemSet(&clauseset, 0, sizeof(clauseset));
1215 39562 : match_clauses_to_index(root, clauses, index, &clauseset);
1216 :
1217 : /*
1218 : * If no matches so far, and the index predicate isn't useful, we
1219 : * don't want it.
1220 : */
1221 39562 : if (!clauseset.nonempty && !useful_predicate)
1222 38402 : continue;
1223 :
1224 : /*
1225 : * Add "other" restriction clauses to the clauseset.
1226 : */
1227 1160 : match_clauses_to_index(root, other_clauses, index, &clauseset);
1228 :
1229 : /*
1230 : * Construct paths if possible.
1231 : */
1232 1160 : indexpaths = build_index_paths(root, rel,
1233 : index, &clauseset,
1234 : useful_predicate,
1235 : ST_BITMAPSCAN,
1236 : NULL,
1237 : NULL);
1238 1160 : result = list_concat(result, indexpaths);
1239 : }
1240 :
1241 15828 : return result;
1242 : }
1243 :
1244 : /*
1245 : * generate_bitmap_or_paths
1246 : * Look through the list of clauses to find OR clauses, and generate
1247 : * a BitmapOrPath for each one we can handle that way. Return a list
1248 : * of the generated BitmapOrPaths.
1249 : *
1250 : * other_clauses is a list of additional clauses that can be assumed true
1251 : * for the purpose of generating indexquals, but are not to be searched for
1252 : * ORs. (See build_paths_for_OR() for motivation.)
1253 : */
1254 : static List *
1255 395436 : generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
1256 : List *clauses, List *other_clauses)
1257 : {
1258 395436 : List *result = NIL;
1259 : List *all_clauses;
1260 : ListCell *lc;
1261 :
1262 : /*
1263 : * We can use both the current and other clauses as context for
1264 : * build_paths_for_OR; no need to remove ORs from the lists.
1265 : */
1266 395436 : all_clauses = list_concat_copy(clauses, other_clauses);
1267 :
1268 616858 : foreach(lc, clauses)
1269 : {
1270 221422 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1271 : List *pathlist;
1272 : Path *bitmapqual;
1273 : ListCell *j;
1274 :
1275 : /* Ignore RestrictInfos that aren't ORs */
1276 221422 : if (!restriction_is_or_clause(rinfo))
1277 206208 : continue;
1278 :
1279 : /*
1280 : * We must be able to match at least one index to each of the arms of
1281 : * the OR, else we can't use it.
1282 : */
1283 15214 : pathlist = NIL;
1284 16250 : foreach(j, ((BoolExpr *) rinfo->orclause)->args)
1285 : {
1286 15828 : Node *orarg = (Node *) lfirst(j);
1287 : List *indlist;
1288 :
1289 : /* OR arguments should be ANDs or sub-RestrictInfos */
1290 15828 : if (is_andclause(orarg))
1291 : {
1292 504 : List *andargs = ((BoolExpr *) orarg)->args;
1293 :
1294 504 : indlist = build_paths_for_OR(root, rel,
1295 : andargs,
1296 : all_clauses);
1297 :
1298 : /* Recurse in case there are sub-ORs */
1299 504 : indlist = list_concat(indlist,
1300 504 : generate_bitmap_or_paths(root, rel,
1301 : andargs,
1302 : all_clauses));
1303 : }
1304 : else
1305 : {
1306 15324 : RestrictInfo *rinfo = castNode(RestrictInfo, orarg);
1307 : List *orargs;
1308 :
1309 : Assert(!restriction_is_or_clause(rinfo));
1310 15324 : orargs = list_make1(rinfo);
1311 :
1312 15324 : indlist = build_paths_for_OR(root, rel,
1313 : orargs,
1314 : all_clauses);
1315 : }
1316 :
1317 : /*
1318 : * If nothing matched this arm, we can't do anything with this OR
1319 : * clause.
1320 : */
1321 15828 : if (indlist == NIL)
1322 : {
1323 14792 : pathlist = NIL;
1324 14792 : break;
1325 : }
1326 :
1327 : /*
1328 : * OK, pick the most promising AND combination, and add it to
1329 : * pathlist.
1330 : */
1331 1036 : bitmapqual = choose_bitmap_and(root, rel, indlist);
1332 1036 : pathlist = lappend(pathlist, bitmapqual);
1333 : }
1334 :
1335 : /*
1336 : * If we have a match for every arm, then turn them into a
1337 : * BitmapOrPath, and add to result list.
1338 : */
1339 15214 : if (pathlist != NIL)
1340 : {
1341 422 : bitmapqual = (Path *) create_bitmap_or_path(root, rel, pathlist);
1342 422 : result = lappend(result, bitmapqual);
1343 : }
1344 : }
1345 :
1346 395436 : return result;
1347 : }
1348 :
1349 :
1350 : /*
1351 : * choose_bitmap_and
1352 : * Given a nonempty list of bitmap paths, AND them into one path.
1353 : *
1354 : * This is a nontrivial decision since we can legally use any subset of the
1355 : * given path set. We want to choose a good tradeoff between selectivity
1356 : * and cost of computing the bitmap.
1357 : *
1358 : * The result is either a single one of the inputs, or a BitmapAndPath
1359 : * combining multiple inputs.
1360 : */
1361 : static Path *
1362 188900 : choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel, List *paths)
1363 : {
1364 188900 : int npaths = list_length(paths);
1365 : PathClauseUsage **pathinfoarray;
1366 : PathClauseUsage *pathinfo;
1367 : List *clauselist;
1368 188900 : List *bestpaths = NIL;
1369 188900 : Cost bestcost = 0;
1370 : int i,
1371 : j;
1372 : ListCell *l;
1373 :
1374 : Assert(npaths > 0); /* else caller error */
1375 188900 : if (npaths == 1)
1376 146784 : return (Path *) linitial(paths); /* easy case */
1377 :
1378 : /*
1379 : * In theory we should consider every nonempty subset of the given paths.
1380 : * In practice that seems like overkill, given the crude nature of the
1381 : * estimates, not to mention the possible effects of higher-level AND and
1382 : * OR clauses. Moreover, it's completely impractical if there are a large
1383 : * number of paths, since the work would grow as O(2^N).
1384 : *
1385 : * As a heuristic, we first check for paths using exactly the same sets of
1386 : * WHERE clauses + index predicate conditions, and reject all but the
1387 : * cheapest-to-scan in any such group. This primarily gets rid of indexes
1388 : * that include the interesting columns but also irrelevant columns. (In
1389 : * situations where the DBA has gone overboard on creating variant
1390 : * indexes, this can make for a very large reduction in the number of
1391 : * paths considered further.)
1392 : *
1393 : * We then sort the surviving paths with the cheapest-to-scan first, and
1394 : * for each path, consider using that path alone as the basis for a bitmap
1395 : * scan. Then we consider bitmap AND scans formed from that path plus
1396 : * each subsequent (higher-cost) path, adding on a subsequent path if it
1397 : * results in a reduction in the estimated total scan cost. This means we
1398 : * consider about O(N^2) rather than O(2^N) path combinations, which is
1399 : * quite tolerable, especially given than N is usually reasonably small
1400 : * because of the prefiltering step. The cheapest of these is returned.
1401 : *
1402 : * We will only consider AND combinations in which no two indexes use the
1403 : * same WHERE clause. This is a bit of a kluge: it's needed because
1404 : * costsize.c and clausesel.c aren't very smart about redundant clauses.
1405 : * They will usually double-count the redundant clauses, producing a
1406 : * too-small selectivity that makes a redundant AND step look like it
1407 : * reduces the total cost. Perhaps someday that code will be smarter and
1408 : * we can remove this limitation. (But note that this also defends
1409 : * against flat-out duplicate input paths, which can happen because
1410 : * match_join_clauses_to_index will find the same OR join clauses that
1411 : * extract_restriction_or_clauses has pulled OR restriction clauses out
1412 : * of.)
1413 : *
1414 : * For the same reason, we reject AND combinations in which an index
1415 : * predicate clause duplicates another clause. Here we find it necessary
1416 : * to be even stricter: we'll reject a partial index if any of its
1417 : * predicate clauses are implied by the set of WHERE clauses and predicate
1418 : * clauses used so far. This covers cases such as a condition "x = 42"
1419 : * used with a plain index, followed by a clauseless scan of a partial
1420 : * index "WHERE x >= 40 AND x < 50". The partial index has been accepted
1421 : * only because "x = 42" was present, and so allowing it would partially
1422 : * double-count selectivity. (We could use predicate_implied_by on
1423 : * regular qual clauses too, to have a more intelligent, but much more
1424 : * expensive, check for redundancy --- but in most cases simple equality
1425 : * seems to suffice.)
1426 : */
1427 :
1428 : /*
1429 : * Extract clause usage info and detect any paths that use exactly the
1430 : * same set of clauses; keep only the cheapest-to-scan of any such groups.
1431 : * The surviving paths are put into an array for qsort'ing.
1432 : */
1433 : pathinfoarray = (PathClauseUsage **)
1434 42116 : palloc(npaths * sizeof(PathClauseUsage *));
1435 42116 : clauselist = NIL;
1436 42116 : npaths = 0;
1437 131898 : foreach(l, paths)
1438 : {
1439 89782 : Path *ipath = (Path *) lfirst(l);
1440 :
1441 89782 : pathinfo = classify_index_clause_usage(ipath, &clauselist);
1442 :
1443 : /* If it's unclassifiable, treat it as distinct from all others */
1444 89782 : if (pathinfo->unclassifiable)
1445 : {
1446 0 : pathinfoarray[npaths++] = pathinfo;
1447 0 : continue;
1448 : }
1449 :
1450 133788 : for (i = 0; i < npaths; i++)
1451 : {
1452 106248 : if (!pathinfoarray[i]->unclassifiable &&
1453 53124 : bms_equal(pathinfo->clauseids, pathinfoarray[i]->clauseids))
1454 9118 : break;
1455 : }
1456 89782 : if (i < npaths)
1457 : {
1458 : /* duplicate clauseids, keep the cheaper one */
1459 : Cost ncost;
1460 : Cost ocost;
1461 : Selectivity nselec;
1462 : Selectivity oselec;
1463 :
1464 9118 : cost_bitmap_tree_node(pathinfo->path, &ncost, &nselec);
1465 9118 : cost_bitmap_tree_node(pathinfoarray[i]->path, &ocost, &oselec);
1466 9118 : if (ncost < ocost)
1467 670 : pathinfoarray[i] = pathinfo;
1468 : }
1469 : else
1470 : {
1471 : /* not duplicate clauseids, add to array */
1472 80664 : pathinfoarray[npaths++] = pathinfo;
1473 : }
1474 : }
1475 :
1476 : /* If only one surviving path, we're done */
1477 42116 : if (npaths == 1)
1478 7070 : return pathinfoarray[0]->path;
1479 :
1480 : /* Sort the surviving paths by index access cost */
1481 35046 : qsort(pathinfoarray, npaths, sizeof(PathClauseUsage *),
1482 : path_usage_comparator);
1483 :
1484 : /*
1485 : * For each surviving index, consider it as an "AND group leader", and see
1486 : * whether adding on any of the later indexes results in an AND path with
1487 : * cheaper total cost than before. Then take the cheapest AND group.
1488 : *
1489 : * Note: paths that are either clauseless or unclassifiable will have
1490 : * empty clauseids, so that they will not be rejected by the clauseids
1491 : * filter here, nor will they cause later paths to be rejected by it.
1492 : */
1493 108640 : for (i = 0; i < npaths; i++)
1494 : {
1495 : Cost costsofar;
1496 : List *qualsofar;
1497 : Bitmapset *clauseidsofar;
1498 :
1499 73594 : pathinfo = pathinfoarray[i];
1500 73594 : paths = list_make1(pathinfo->path);
1501 73594 : costsofar = bitmap_scan_cost_est(root, rel, pathinfo->path);
1502 73594 : qualsofar = list_concat_copy(pathinfo->quals, pathinfo->preds);
1503 73594 : clauseidsofar = bms_copy(pathinfo->clauseids);
1504 :
1505 115928 : for (j = i + 1; j < npaths; j++)
1506 : {
1507 : Cost newcost;
1508 :
1509 42334 : pathinfo = pathinfoarray[j];
1510 : /* Check for redundancy */
1511 42334 : if (bms_overlap(pathinfo->clauseids, clauseidsofar))
1512 22736 : continue; /* consider it redundant */
1513 19598 : if (pathinfo->preds)
1514 : {
1515 8 : bool redundant = false;
1516 :
1517 : /* we check each predicate clause separately */
1518 8 : foreach(l, pathinfo->preds)
1519 : {
1520 8 : Node *np = (Node *) lfirst(l);
1521 :
1522 8 : if (predicate_implied_by(list_make1(np), qualsofar, false))
1523 : {
1524 8 : redundant = true;
1525 8 : break; /* out of inner foreach loop */
1526 : }
1527 : }
1528 8 : if (redundant)
1529 8 : continue;
1530 : }
1531 : /* tentatively add new path to paths, so we can estimate cost */
1532 19590 : paths = lappend(paths, pathinfo->path);
1533 19590 : newcost = bitmap_and_cost_est(root, rel, paths);
1534 19590 : if (newcost < costsofar)
1535 : {
1536 : /* keep new path in paths, update subsidiary variables */
1537 364 : costsofar = newcost;
1538 364 : qualsofar = list_concat(qualsofar, pathinfo->quals);
1539 364 : qualsofar = list_concat(qualsofar, pathinfo->preds);
1540 364 : clauseidsofar = bms_add_members(clauseidsofar,
1541 364 : pathinfo->clauseids);
1542 : }
1543 : else
1544 : {
1545 : /* reject new path, remove it from paths list */
1546 19226 : paths = list_truncate(paths, list_length(paths) - 1);
1547 : }
1548 : }
1549 :
1550 : /* Keep the cheapest AND-group (or singleton) */
1551 73594 : if (i == 0 || costsofar < bestcost)
1552 : {
1553 36548 : bestpaths = paths;
1554 36548 : bestcost = costsofar;
1555 : }
1556 :
1557 : /* some easy cleanup (we don't try real hard though) */
1558 73594 : list_free(qualsofar);
1559 : }
1560 :
1561 35046 : if (list_length(bestpaths) == 1)
1562 34978 : return (Path *) linitial(bestpaths); /* no need for AND */
1563 68 : return (Path *) create_bitmap_and_path(root, rel, bestpaths);
1564 : }
1565 :
1566 : /* qsort comparator to sort in increasing index access cost order */
1567 : static int
1568 41296 : path_usage_comparator(const void *a, const void *b)
1569 : {
1570 41296 : PathClauseUsage *pa = *(PathClauseUsage *const *) a;
1571 41296 : PathClauseUsage *pb = *(PathClauseUsage *const *) b;
1572 : Cost acost;
1573 : Cost bcost;
1574 : Selectivity aselec;
1575 : Selectivity bselec;
1576 :
1577 41296 : cost_bitmap_tree_node(pa->path, &acost, &aselec);
1578 41296 : cost_bitmap_tree_node(pb->path, &bcost, &bselec);
1579 :
1580 : /*
1581 : * If costs are the same, sort by selectivity.
1582 : */
1583 41296 : if (acost < bcost)
1584 23874 : return -1;
1585 17422 : if (acost > bcost)
1586 13870 : return 1;
1587 :
1588 3552 : if (aselec < bselec)
1589 2768 : return -1;
1590 784 : if (aselec > bselec)
1591 18 : return 1;
1592 :
1593 766 : return 0;
1594 : }
1595 :
1596 : /*
1597 : * Estimate the cost of actually executing a bitmap scan with a single
1598 : * index path (which could be a BitmapAnd or BitmapOr node).
1599 : */
1600 : static Cost
1601 93184 : bitmap_scan_cost_est(PlannerInfo *root, RelOptInfo *rel, Path *ipath)
1602 : {
1603 : BitmapHeapPath bpath;
1604 :
1605 : /* Set up a dummy BitmapHeapPath */
1606 93184 : bpath.path.type = T_BitmapHeapPath;
1607 93184 : bpath.path.pathtype = T_BitmapHeapScan;
1608 93184 : bpath.path.parent = rel;
1609 93184 : bpath.path.pathtarget = rel->reltarget;
1610 93184 : bpath.path.param_info = ipath->param_info;
1611 93184 : bpath.path.pathkeys = NIL;
1612 93184 : bpath.bitmapqual = ipath;
1613 :
1614 : /*
1615 : * Check the cost of temporary path without considering parallelism.
1616 : * Parallel bitmap heap path will be considered at later stage.
1617 : */
1618 93184 : bpath.path.parallel_workers = 0;
1619 :
1620 : /* Now we can do cost_bitmap_heap_scan */
1621 93184 : cost_bitmap_heap_scan(&bpath.path, root, rel,
1622 : bpath.path.param_info,
1623 : ipath,
1624 : get_loop_count(root, rel->relid,
1625 93184 : PATH_REQ_OUTER(ipath)));
1626 :
1627 93184 : return bpath.path.total_cost;
1628 : }
1629 :
1630 : /*
1631 : * Estimate the cost of actually executing a BitmapAnd scan with the given
1632 : * inputs.
1633 : */
1634 : static Cost
1635 19590 : bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel, List *paths)
1636 : {
1637 : BitmapAndPath *apath;
1638 :
1639 : /*
1640 : * Might as well build a real BitmapAndPath here, as the work is slightly
1641 : * too complicated to be worth repeating just to save one palloc.
1642 : */
1643 19590 : apath = create_bitmap_and_path(root, rel, paths);
1644 :
1645 19590 : return bitmap_scan_cost_est(root, rel, (Path *) apath);
1646 : }
1647 :
1648 :
1649 : /*
1650 : * classify_index_clause_usage
1651 : * Construct a PathClauseUsage struct describing the WHERE clauses and
1652 : * index predicate clauses used by the given indexscan path.
1653 : * We consider two clauses the same if they are equal().
1654 : *
1655 : * At some point we might want to migrate this info into the Path data
1656 : * structure proper, but for the moment it's only needed within
1657 : * choose_bitmap_and().
1658 : *
1659 : * *clauselist is used and expanded as needed to identify all the distinct
1660 : * clauses seen across successive calls. Caller must initialize it to NIL
1661 : * before first call of a set.
1662 : */
1663 : static PathClauseUsage *
1664 89782 : classify_index_clause_usage(Path *path, List **clauselist)
1665 : {
1666 : PathClauseUsage *result;
1667 : Bitmapset *clauseids;
1668 : ListCell *lc;
1669 :
1670 89782 : result = (PathClauseUsage *) palloc(sizeof(PathClauseUsage));
1671 89782 : result->path = path;
1672 :
1673 : /* Recursively find the quals and preds used by the path */
1674 89782 : result->quals = NIL;
1675 89782 : result->preds = NIL;
1676 89782 : find_indexpath_quals(path, &result->quals, &result->preds);
1677 :
1678 : /*
1679 : * Some machine-generated queries have outlandish numbers of qual clauses.
1680 : * To avoid getting into O(N^2) behavior even in this preliminary
1681 : * classification step, we want to limit the number of entries we can
1682 : * accumulate in *clauselist. Treat any path with more than 100 quals +
1683 : * preds as unclassifiable, which will cause calling code to consider it
1684 : * distinct from all other paths.
1685 : */
1686 89782 : if (list_length(result->quals) + list_length(result->preds) > 100)
1687 : {
1688 0 : result->clauseids = NULL;
1689 0 : result->unclassifiable = true;
1690 0 : return result;
1691 : }
1692 :
1693 : /* Build up a bitmapset representing the quals and preds */
1694 89782 : clauseids = NULL;
1695 218848 : foreach(lc, result->quals)
1696 : {
1697 129066 : Node *node = (Node *) lfirst(lc);
1698 :
1699 129066 : clauseids = bms_add_member(clauseids,
1700 : find_list_position(node, clauselist));
1701 : }
1702 89958 : foreach(lc, result->preds)
1703 : {
1704 176 : Node *node = (Node *) lfirst(lc);
1705 :
1706 176 : clauseids = bms_add_member(clauseids,
1707 : find_list_position(node, clauselist));
1708 : }
1709 89782 : result->clauseids = clauseids;
1710 89782 : result->unclassifiable = false;
1711 :
1712 89782 : return result;
1713 : }
1714 :
1715 :
1716 : /*
1717 : * find_indexpath_quals
1718 : *
1719 : * Given the Path structure for a plain or bitmap indexscan, extract lists
1720 : * of all the index clauses and index predicate conditions used in the Path.
1721 : * These are appended to the initial contents of *quals and *preds (hence
1722 : * caller should initialize those to NIL).
1723 : *
1724 : * Note we are not trying to produce an accurate representation of the AND/OR
1725 : * semantics of the Path, but just find out all the base conditions used.
1726 : *
1727 : * The result lists contain pointers to the expressions used in the Path,
1728 : * but all the list cells are freshly built, so it's safe to destructively
1729 : * modify the lists (eg, by concat'ing with other lists).
1730 : */
1731 : static void
1732 90846 : find_indexpath_quals(Path *bitmapqual, List **quals, List **preds)
1733 : {
1734 90846 : if (IsA(bitmapqual, BitmapAndPath))
1735 : {
1736 0 : BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
1737 : ListCell *l;
1738 :
1739 0 : foreach(l, apath->bitmapquals)
1740 : {
1741 0 : find_indexpath_quals((Path *) lfirst(l), quals, preds);
1742 : }
1743 : }
1744 90846 : else if (IsA(bitmapqual, BitmapOrPath))
1745 : {
1746 510 : BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
1747 : ListCell *l;
1748 :
1749 1574 : foreach(l, opath->bitmapquals)
1750 : {
1751 1064 : find_indexpath_quals((Path *) lfirst(l), quals, preds);
1752 : }
1753 : }
1754 90336 : else if (IsA(bitmapqual, IndexPath))
1755 : {
1756 90336 : IndexPath *ipath = (IndexPath *) bitmapqual;
1757 : ListCell *l;
1758 :
1759 219402 : foreach(l, ipath->indexclauses)
1760 : {
1761 129066 : IndexClause *iclause = (IndexClause *) lfirst(l);
1762 :
1763 129066 : *quals = lappend(*quals, iclause->rinfo->clause);
1764 : }
1765 90336 : *preds = list_concat(*preds, ipath->indexinfo->indpred);
1766 : }
1767 : else
1768 0 : elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
1769 90846 : }
1770 :
1771 :
1772 : /*
1773 : * find_list_position
1774 : * Return the given node's position (counting from 0) in the given
1775 : * list of nodes. If it's not equal() to any existing list member,
1776 : * add it at the end, and return that position.
1777 : */
1778 : static int
1779 129242 : find_list_position(Node *node, List **nodelist)
1780 : {
1781 : int i;
1782 : ListCell *lc;
1783 :
1784 129242 : i = 0;
1785 221518 : foreach(lc, *nodelist)
1786 : {
1787 126808 : Node *oldnode = (Node *) lfirst(lc);
1788 :
1789 126808 : if (equal(node, oldnode))
1790 34532 : return i;
1791 92276 : i++;
1792 : }
1793 :
1794 94710 : *nodelist = lappend(*nodelist, node);
1795 :
1796 94710 : return i;
1797 : }
1798 :
1799 :
1800 : /*
1801 : * check_index_only
1802 : * Determine whether an index-only scan is possible for this index.
1803 : */
1804 : static bool
1805 472760 : check_index_only(RelOptInfo *rel, IndexOptInfo *index)
1806 : {
1807 : bool result;
1808 472760 : Bitmapset *attrs_used = NULL;
1809 472760 : Bitmapset *index_canreturn_attrs = NULL;
1810 472760 : Bitmapset *index_cannotreturn_attrs = NULL;
1811 : ListCell *lc;
1812 : int i;
1813 :
1814 : /* Index-only scans must be enabled */
1815 472760 : if (!enable_indexonlyscan)
1816 2008 : return false;
1817 :
1818 : /*
1819 : * Check that all needed attributes of the relation are available from the
1820 : * index.
1821 : */
1822 :
1823 : /*
1824 : * First, identify all the attributes needed for joins or final output.
1825 : * Note: we must look at rel's targetlist, not the attr_needed data,
1826 : * because attr_needed isn't computed for inheritance child rels.
1827 : */
1828 470752 : pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
1829 :
1830 : /*
1831 : * Add all the attributes used by restriction clauses; but consider only
1832 : * those clauses not implied by the index predicate, since ones that are
1833 : * so implied don't need to be checked explicitly in the plan.
1834 : *
1835 : * Note: attributes used only in index quals would not be needed at
1836 : * runtime either, if we are certain that the index is not lossy. However
1837 : * it'd be complicated to account for that accurately, and it doesn't
1838 : * matter in most cases, since we'd conclude that such attributes are
1839 : * available from the index anyway.
1840 : */
1841 960106 : foreach(lc, index->indrestrictinfo)
1842 : {
1843 489354 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
1844 :
1845 489354 : pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
1846 : }
1847 :
1848 : /*
1849 : * Construct a bitmapset of columns that the index can return back in an
1850 : * index-only scan. If there are multiple index columns containing the
1851 : * same attribute, all of them must be capable of returning the value,
1852 : * since we might recheck operators on any of them. (Potentially we could
1853 : * be smarter about that, but it's such a weird situation that it doesn't
1854 : * seem worth spending a lot of sweat on.)
1855 : */
1856 1315578 : for (i = 0; i < index->ncolumns; i++)
1857 : {
1858 844826 : int attno = index->indexkeys[i];
1859 :
1860 : /*
1861 : * For the moment, we just ignore index expressions. It might be nice
1862 : * to do something with them, later.
1863 : */
1864 844826 : if (attno == 0)
1865 1860 : continue;
1866 :
1867 842966 : if (index->canreturn[i])
1868 : index_canreturn_attrs =
1869 720250 : bms_add_member(index_canreturn_attrs,
1870 : attno - FirstLowInvalidHeapAttributeNumber);
1871 : else
1872 : index_cannotreturn_attrs =
1873 122716 : bms_add_member(index_cannotreturn_attrs,
1874 : attno - FirstLowInvalidHeapAttributeNumber);
1875 : }
1876 :
1877 470752 : index_canreturn_attrs = bms_del_members(index_canreturn_attrs,
1878 : index_cannotreturn_attrs);
1879 :
1880 : /* Do we have all the necessary attributes? */
1881 470752 : result = bms_is_subset(attrs_used, index_canreturn_attrs);
1882 :
1883 470752 : bms_free(attrs_used);
1884 470752 : bms_free(index_canreturn_attrs);
1885 470752 : bms_free(index_cannotreturn_attrs);
1886 :
1887 470752 : return result;
1888 : }
1889 :
1890 : /*
1891 : * get_loop_count
1892 : * Choose the loop count estimate to use for costing a parameterized path
1893 : * with the given set of outer relids.
1894 : *
1895 : * Since we produce parameterized paths before we've begun to generate join
1896 : * relations, it's impossible to predict exactly how many times a parameterized
1897 : * path will be iterated; we don't know the size of the relation that will be
1898 : * on the outside of the nestloop. However, we should try to account for
1899 : * multiple iterations somehow in costing the path. The heuristic embodied
1900 : * here is to use the rowcount of the smallest other base relation needed in
1901 : * the join clauses used by the path. (We could alternatively consider the
1902 : * largest one, but that seems too optimistic.) This is of course the right
1903 : * answer for single-other-relation cases, and it seems like a reasonable
1904 : * zero-order approximation for multiway-join cases.
1905 : *
1906 : * In addition, we check to see if the other side of each join clause is on
1907 : * the inside of some semijoin that the current relation is on the outside of.
1908 : * If so, the only way that a parameterized path could be used is if the
1909 : * semijoin RHS has been unique-ified, so we should use the number of unique
1910 : * RHS rows rather than using the relation's raw rowcount.
1911 : *
1912 : * Note: for this to work, allpaths.c must establish all baserel size
1913 : * estimates before it begins to compute paths, or at least before it
1914 : * calls create_index_paths().
1915 : */
1916 : static double
1917 629396 : get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids)
1918 : {
1919 : double result;
1920 : int outer_relid;
1921 :
1922 : /* For a non-parameterized path, just return 1.0 quickly */
1923 629396 : if (outer_relids == NULL)
1924 474726 : return 1.0;
1925 :
1926 154670 : result = 0.0;
1927 154670 : outer_relid = -1;
1928 310108 : while ((outer_relid = bms_next_member(outer_relids, outer_relid)) >= 0)
1929 : {
1930 : RelOptInfo *outer_rel;
1931 : double rowcount;
1932 :
1933 : /* Paranoia: ignore bogus relid indexes */
1934 155438 : if (outer_relid >= root->simple_rel_array_size)
1935 0 : continue;
1936 155438 : outer_rel = root->simple_rel_array[outer_relid];
1937 155438 : if (outer_rel == NULL)
1938 0 : continue;
1939 : Assert(outer_rel->relid == outer_relid); /* sanity check on array */
1940 :
1941 : /* Other relation could be proven empty, if so ignore */
1942 155438 : if (IS_DUMMY_REL(outer_rel))
1943 16 : continue;
1944 :
1945 : /* Otherwise, rel's rows estimate should be valid by now */
1946 : Assert(outer_rel->rows > 0);
1947 :
1948 : /* Check to see if rel is on the inside of any semijoins */
1949 155422 : rowcount = adjust_rowcount_for_semijoins(root,
1950 : cur_relid,
1951 : outer_relid,
1952 : outer_rel->rows);
1953 :
1954 : /* Remember smallest row count estimate among the outer rels */
1955 155422 : if (result == 0.0 || result > rowcount)
1956 154962 : result = rowcount;
1957 : }
1958 : /* Return 1.0 if we found no valid relations (shouldn't happen) */
1959 154670 : return (result > 0.0) ? result : 1.0;
1960 : }
1961 :
1962 : /*
1963 : * Check to see if outer_relid is on the inside of any semijoin that cur_relid
1964 : * is on the outside of. If so, replace rowcount with the estimated number of
1965 : * unique rows from the semijoin RHS (assuming that's smaller, which it might
1966 : * not be). The estimate is crude but it's the best we can do at this stage
1967 : * of the proceedings.
1968 : */
1969 : static double
1970 155422 : adjust_rowcount_for_semijoins(PlannerInfo *root,
1971 : Index cur_relid,
1972 : Index outer_relid,
1973 : double rowcount)
1974 : {
1975 : ListCell *lc;
1976 :
1977 278766 : foreach(lc, root->join_info_list)
1978 : {
1979 123344 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
1980 :
1981 125800 : if (sjinfo->jointype == JOIN_SEMI &&
1982 2832 : bms_is_member(cur_relid, sjinfo->syn_lefthand) &&
1983 376 : bms_is_member(outer_relid, sjinfo->syn_righthand))
1984 : {
1985 : /* Estimate number of unique-ified rows */
1986 : double nraw;
1987 : double nunique;
1988 :
1989 288 : nraw = approximate_joinrel_size(root, sjinfo->syn_righthand);
1990 288 : nunique = estimate_num_groups(root,
1991 : sjinfo->semi_rhs_exprs,
1992 : nraw,
1993 : NULL);
1994 288 : if (rowcount > nunique)
1995 148 : rowcount = nunique;
1996 : }
1997 : }
1998 155422 : return rowcount;
1999 : }
2000 :
2001 : /*
2002 : * Make an approximate estimate of the size of a joinrel.
2003 : *
2004 : * We don't have enough info at this point to get a good estimate, so we
2005 : * just multiply the base relation sizes together. Fortunately, this is
2006 : * the right answer anyway for the most common case with a single relation
2007 : * on the RHS of a semijoin. Also, estimate_num_groups() has only a weak
2008 : * dependency on its input_rows argument (it basically uses it as a clamp).
2009 : * So we might be able to get a fairly decent end result even with a severe
2010 : * overestimate of the RHS's raw size.
2011 : */
2012 : static double
2013 288 : approximate_joinrel_size(PlannerInfo *root, Relids relids)
2014 : {
2015 288 : double rowcount = 1.0;
2016 : int relid;
2017 :
2018 288 : relid = -1;
2019 632 : while ((relid = bms_next_member(relids, relid)) >= 0)
2020 : {
2021 : RelOptInfo *rel;
2022 :
2023 : /* Paranoia: ignore bogus relid indexes */
2024 344 : if (relid >= root->simple_rel_array_size)
2025 0 : continue;
2026 344 : rel = root->simple_rel_array[relid];
2027 344 : if (rel == NULL)
2028 0 : continue;
2029 : Assert(rel->relid == relid); /* sanity check on array */
2030 :
2031 : /* Relation could be proven empty, if so ignore */
2032 344 : if (IS_DUMMY_REL(rel))
2033 0 : continue;
2034 :
2035 : /* Otherwise, rel's rows estimate should be valid by now */
2036 : Assert(rel->rows > 0);
2037 :
2038 : /* Accumulate product */
2039 344 : rowcount *= rel->rows;
2040 : }
2041 288 : return rowcount;
2042 : }
2043 :
2044 :
2045 : /****************************************************************************
2046 : * ---- ROUTINES TO CHECK QUERY CLAUSES ----
2047 : ****************************************************************************/
2048 :
2049 : /*
2050 : * match_restriction_clauses_to_index
2051 : * Identify restriction clauses for the rel that match the index.
2052 : * Matching clauses are added to *clauseset.
2053 : */
2054 : static void
2055 408800 : match_restriction_clauses_to_index(PlannerInfo *root,
2056 : IndexOptInfo *index,
2057 : IndexClauseSet *clauseset)
2058 : {
2059 : /* We can ignore clauses that are implied by the index predicate */
2060 408800 : match_clauses_to_index(root, index->indrestrictinfo, index, clauseset);
2061 408800 : }
2062 :
2063 : /*
2064 : * match_join_clauses_to_index
2065 : * Identify join clauses for the rel that match the index.
2066 : * Matching clauses are added to *clauseset.
2067 : * Also, add any potentially usable join OR clauses to *joinorclauses.
2068 : */
2069 : static void
2070 408800 : match_join_clauses_to_index(PlannerInfo *root,
2071 : RelOptInfo *rel, IndexOptInfo *index,
2072 : IndexClauseSet *clauseset,
2073 : List **joinorclauses)
2074 : {
2075 : ListCell *lc;
2076 :
2077 : /* Scan the rel's join clauses */
2078 556666 : foreach(lc, rel->joininfo)
2079 : {
2080 147866 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2081 :
2082 : /* Check if clause can be moved to this rel */
2083 147866 : if (!join_clause_is_movable_to(rinfo, rel))
2084 69086 : continue;
2085 :
2086 : /* Potentially usable, so see if it matches the index or is an OR */
2087 78780 : if (restriction_is_or_clause(rinfo))
2088 14072 : *joinorclauses = lappend(*joinorclauses, rinfo);
2089 : else
2090 64708 : match_clause_to_index(root, rinfo, index, clauseset);
2091 : }
2092 408800 : }
2093 :
2094 : /*
2095 : * match_eclass_clauses_to_index
2096 : * Identify EquivalenceClass join clauses for the rel that match the index.
2097 : * Matching clauses are added to *clauseset.
2098 : */
2099 : static void
2100 408800 : match_eclass_clauses_to_index(PlannerInfo *root, IndexOptInfo *index,
2101 : IndexClauseSet *clauseset)
2102 : {
2103 : int indexcol;
2104 :
2105 : /* No work if rel is not in any such ECs */
2106 408800 : if (!index->rel->has_eclass_joins)
2107 313664 : return;
2108 :
2109 251138 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2110 : {
2111 : ec_member_matches_arg arg;
2112 : List *clauses;
2113 :
2114 : /* Generate clauses, skipping any that join to lateral_referencers */
2115 156002 : arg.index = index;
2116 156002 : arg.indexcol = indexcol;
2117 156002 : clauses = generate_implied_equalities_for_column(root,
2118 : index->rel,
2119 : ec_member_matches_indexcol,
2120 : (void *) &arg,
2121 156002 : index->rel->lateral_referencers);
2122 :
2123 : /*
2124 : * We have to check whether the results actually do match the index,
2125 : * since for non-btree indexes the EC's equality operators might not
2126 : * be in the index opclass (cf ec_member_matches_indexcol).
2127 : */
2128 156002 : match_clauses_to_index(root, clauses, index, clauseset);
2129 : }
2130 : }
2131 :
2132 : /*
2133 : * match_clauses_to_index
2134 : * Perform match_clause_to_index() for each clause in a list.
2135 : * Matching clauses are added to *clauseset.
2136 : */
2137 : static void
2138 605524 : match_clauses_to_index(PlannerInfo *root,
2139 : List *clauses,
2140 : IndexOptInfo *index,
2141 : IndexClauseSet *clauseset)
2142 : {
2143 : ListCell *lc;
2144 :
2145 1133334 : foreach(lc, clauses)
2146 : {
2147 527810 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
2148 :
2149 527810 : match_clause_to_index(root, rinfo, index, clauseset);
2150 : }
2151 605524 : }
2152 :
2153 : /*
2154 : * match_clause_to_index
2155 : * Test whether a qual clause can be used with an index.
2156 : *
2157 : * If the clause is usable, add an IndexClause entry for it to the appropriate
2158 : * list in *clauseset. (*clauseset must be initialized to zeroes before first
2159 : * call.)
2160 : *
2161 : * Note: in some circumstances we may find the same RestrictInfos coming from
2162 : * multiple places. Defend against redundant outputs by refusing to add a
2163 : * clause twice (pointer equality should be a good enough check for this).
2164 : *
2165 : * Note: it's possible that a badly-defined index could have multiple matching
2166 : * columns. We always select the first match if so; this avoids scenarios
2167 : * wherein we get an inflated idea of the index's selectivity by using the
2168 : * same clause multiple times with different index columns.
2169 : */
2170 : static void
2171 592518 : match_clause_to_index(PlannerInfo *root,
2172 : RestrictInfo *rinfo,
2173 : IndexOptInfo *index,
2174 : IndexClauseSet *clauseset)
2175 : {
2176 : int indexcol;
2177 :
2178 : /*
2179 : * Never match pseudoconstants to indexes. (Normally a match could not
2180 : * happen anyway, since a pseudoconstant clause couldn't contain a Var,
2181 : * but what if someone builds an expression index on a constant? It's not
2182 : * totally unreasonable to do so with a partial index, either.)
2183 : */
2184 592518 : if (rinfo->pseudoconstant)
2185 5564 : return;
2186 :
2187 : /*
2188 : * If clause can't be used as an indexqual because it must wait till after
2189 : * some lower-security-level restriction clause, reject it.
2190 : */
2191 586954 : if (!restriction_is_securely_promotable(rinfo, index->rel))
2192 524 : return;
2193 :
2194 : /* OK, check each index key column for a match */
2195 1280516 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2196 : {
2197 : IndexClause *iclause;
2198 : ListCell *lc;
2199 :
2200 : /* Ignore duplicates */
2201 983234 : foreach(lc, clauseset->indexclauses[indexcol])
2202 : {
2203 54064 : IndexClause *iclause = (IndexClause *) lfirst(lc);
2204 :
2205 54064 : if (iclause->rinfo == rinfo)
2206 0 : return;
2207 : }
2208 :
2209 : /* OK, try to match the clause to the index column */
2210 929170 : iclause = match_clause_to_indexcol(root,
2211 : rinfo,
2212 : indexcol,
2213 : index);
2214 929170 : if (iclause)
2215 : {
2216 : /* Success, so record it */
2217 235084 : clauseset->indexclauses[indexcol] =
2218 235084 : lappend(clauseset->indexclauses[indexcol], iclause);
2219 235084 : clauseset->nonempty = true;
2220 235084 : return;
2221 : }
2222 : }
2223 : }
2224 :
2225 : /*
2226 : * match_clause_to_indexcol()
2227 : * Determine whether a restriction clause matches a column of an index,
2228 : * and if so, build an IndexClause node describing the details.
2229 : *
2230 : * To match an index normally, an operator clause:
2231 : *
2232 : * (1) must be in the form (indexkey op const) or (const op indexkey);
2233 : * and
2234 : * (2) must contain an operator which is in the index's operator family
2235 : * for this column; and
2236 : * (3) must match the collation of the index, if collation is relevant.
2237 : *
2238 : * Our definition of "const" is exceedingly liberal: we allow anything that
2239 : * doesn't involve a volatile function or a Var of the index's relation.
2240 : * In particular, Vars belonging to other relations of the query are
2241 : * accepted here, since a clause of that form can be used in a
2242 : * parameterized indexscan. It's the responsibility of higher code levels
2243 : * to manage restriction and join clauses appropriately.
2244 : *
2245 : * Note: we do need to check for Vars of the index's relation on the
2246 : * "const" side of the clause, since clauses like (a.f1 OP (b.f2 OP a.f3))
2247 : * are not processable by a parameterized indexscan on a.f1, whereas
2248 : * something like (a.f1 OP (b.f2 OP c.f3)) is.
2249 : *
2250 : * Presently, the executor can only deal with indexquals that have the
2251 : * indexkey on the left, so we can only use clauses that have the indexkey
2252 : * on the right if we can commute the clause to put the key on the left.
2253 : * We handle that by generating an IndexClause with the correctly-commuted
2254 : * opclause as a derived indexqual.
2255 : *
2256 : * If the index has a collation, the clause must have the same collation.
2257 : * For collation-less indexes, we assume it doesn't matter; this is
2258 : * necessary for cases like "hstore ? text", wherein hstore's operators
2259 : * don't care about collation but the clause will get marked with a
2260 : * collation anyway because of the text argument. (This logic is
2261 : * embodied in the macro IndexCollMatchesExprColl.)
2262 : *
2263 : * It is also possible to match RowCompareExpr clauses to indexes (but
2264 : * currently, only btree indexes handle this).
2265 : *
2266 : * It is also possible to match ScalarArrayOpExpr clauses to indexes, when
2267 : * the clause is of the form "indexkey op ANY (arrayconst)".
2268 : *
2269 : * For boolean indexes, it is also possible to match the clause directly
2270 : * to the indexkey; or perhaps the clause is (NOT indexkey).
2271 : *
2272 : * And, last but not least, some operators and functions can be processed
2273 : * to derive (typically lossy) indexquals from a clause that isn't in
2274 : * itself indexable. If we see that any operand of an OpExpr or FuncExpr
2275 : * matches the index key, and the function has a planner support function
2276 : * attached to it, we'll invoke the support function to see if such an
2277 : * indexqual can be built.
2278 : *
2279 : * 'rinfo' is the clause to be tested (as a RestrictInfo node).
2280 : * 'indexcol' is a column number of 'index' (counting from 0).
2281 : * 'index' is the index of interest.
2282 : *
2283 : * Returns an IndexClause if the clause can be used with this index key,
2284 : * or NULL if not.
2285 : *
2286 : * NOTE: returns NULL if clause is an OR or AND clause; it is the
2287 : * responsibility of higher-level routines to cope with those.
2288 : */
2289 : static IndexClause *
2290 929170 : match_clause_to_indexcol(PlannerInfo *root,
2291 : RestrictInfo *rinfo,
2292 : int indexcol,
2293 : IndexOptInfo *index)
2294 : {
2295 : IndexClause *iclause;
2296 929170 : Expr *clause = rinfo->clause;
2297 : Oid opfamily;
2298 :
2299 : Assert(indexcol < index->nkeycolumns);
2300 :
2301 : /*
2302 : * Historically this code has coped with NULL clauses. That's probably
2303 : * not possible anymore, but we might as well continue to cope.
2304 : */
2305 929170 : if (clause == NULL)
2306 0 : return NULL;
2307 :
2308 : /* First check for boolean-index cases. */
2309 929170 : opfamily = index->opfamily[indexcol];
2310 929170 : if (IsBooleanOpfamily(opfamily))
2311 : {
2312 100 : iclause = match_boolean_index_clause(root, rinfo, indexcol, index);
2313 100 : if (iclause)
2314 52 : return iclause;
2315 : }
2316 :
2317 : /*
2318 : * Clause must be an opclause, funcclause, ScalarArrayOpExpr, or
2319 : * RowCompareExpr. Or, if the index supports it, we can handle IS
2320 : * NULL/NOT NULL clauses.
2321 : */
2322 929118 : if (IsA(clause, OpExpr))
2323 : {
2324 737630 : return match_opclause_to_indexcol(root, rinfo, indexcol, index);
2325 : }
2326 191488 : else if (IsA(clause, FuncExpr))
2327 : {
2328 12824 : return match_funcclause_to_indexcol(root, rinfo, indexcol, index);
2329 : }
2330 178664 : else if (IsA(clause, ScalarArrayOpExpr))
2331 : {
2332 56530 : return match_saopclause_to_indexcol(root, rinfo, indexcol, index);
2333 : }
2334 122134 : else if (IsA(clause, RowCompareExpr))
2335 : {
2336 192 : return match_rowcompare_to_indexcol(root, rinfo, indexcol, index);
2337 : }
2338 121942 : else if (index->amsearchnulls && IsA(clause, NullTest))
2339 : {
2340 47024 : NullTest *nt = (NullTest *) clause;
2341 :
2342 94048 : if (!nt->argisrow &&
2343 47024 : match_index_to_operand((Node *) nt->arg, indexcol, index))
2344 : {
2345 922 : iclause = makeNode(IndexClause);
2346 922 : iclause->rinfo = rinfo;
2347 922 : iclause->indexquals = list_make1(rinfo);
2348 922 : iclause->lossy = false;
2349 922 : iclause->indexcol = indexcol;
2350 922 : iclause->indexcols = NIL;
2351 922 : return iclause;
2352 : }
2353 : }
2354 :
2355 121020 : return NULL;
2356 : }
2357 :
2358 : /*
2359 : * match_boolean_index_clause
2360 : * Recognize restriction clauses that can be matched to a boolean index.
2361 : *
2362 : * The idea here is that, for an index on a boolean column that supports the
2363 : * BooleanEqualOperator, we can transform a plain reference to the indexkey
2364 : * into "indexkey = true", or "NOT indexkey" into "indexkey = false", etc,
2365 : * so as to make the expression indexable using the index's "=" operator.
2366 : * Since Postgres 8.1, we must do this because constant simplification does
2367 : * the reverse transformation; without this code there'd be no way to use
2368 : * such an index at all.
2369 : *
2370 : * This should be called only when IsBooleanOpfamily() recognizes the
2371 : * index's operator family. We check to see if the clause matches the
2372 : * index's key, and if so, build a suitable IndexClause.
2373 : */
2374 : static IndexClause *
2375 196 : match_boolean_index_clause(PlannerInfo *root,
2376 : RestrictInfo *rinfo,
2377 : int indexcol,
2378 : IndexOptInfo *index)
2379 : {
2380 196 : Node *clause = (Node *) rinfo->clause;
2381 196 : Expr *op = NULL;
2382 :
2383 : /* Direct match? */
2384 196 : if (match_index_to_operand(clause, indexcol, index))
2385 : {
2386 : /* convert to indexkey = TRUE */
2387 56 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2388 : (Expr *) clause,
2389 56 : (Expr *) makeBoolConst(true, false),
2390 : InvalidOid, InvalidOid);
2391 : }
2392 : /* NOT clause? */
2393 140 : else if (is_notclause(clause))
2394 : {
2395 44 : Node *arg = (Node *) get_notclausearg((Expr *) clause);
2396 :
2397 44 : if (match_index_to_operand(arg, indexcol, index))
2398 : {
2399 : /* convert to indexkey = FALSE */
2400 44 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2401 : (Expr *) arg,
2402 44 : (Expr *) makeBoolConst(false, false),
2403 : InvalidOid, InvalidOid);
2404 : }
2405 : }
2406 :
2407 : /*
2408 : * Since we only consider clauses at top level of WHERE, we can convert
2409 : * indexkey IS TRUE and indexkey IS FALSE to index searches as well. The
2410 : * different meaning for NULL isn't important.
2411 : */
2412 96 : else if (clause && IsA(clause, BooleanTest))
2413 : {
2414 24 : BooleanTest *btest = (BooleanTest *) clause;
2415 24 : Node *arg = (Node *) btest->arg;
2416 :
2417 36 : if (btest->booltesttype == IS_TRUE &&
2418 12 : match_index_to_operand(arg, indexcol, index))
2419 : {
2420 : /* convert to indexkey = TRUE */
2421 12 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2422 : (Expr *) arg,
2423 12 : (Expr *) makeBoolConst(true, false),
2424 : InvalidOid, InvalidOid);
2425 : }
2426 24 : else if (btest->booltesttype == IS_FALSE &&
2427 12 : match_index_to_operand(arg, indexcol, index))
2428 : {
2429 : /* convert to indexkey = FALSE */
2430 12 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2431 : (Expr *) arg,
2432 12 : (Expr *) makeBoolConst(false, false),
2433 : InvalidOid, InvalidOid);
2434 : }
2435 : }
2436 :
2437 : /*
2438 : * If we successfully made an operator clause from the given qual, we must
2439 : * wrap it in an IndexClause. It's not lossy.
2440 : */
2441 196 : if (op)
2442 : {
2443 124 : IndexClause *iclause = makeNode(IndexClause);
2444 :
2445 124 : iclause->rinfo = rinfo;
2446 124 : iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
2447 124 : iclause->lossy = false;
2448 124 : iclause->indexcol = indexcol;
2449 124 : iclause->indexcols = NIL;
2450 124 : return iclause;
2451 : }
2452 :
2453 72 : return NULL;
2454 : }
2455 :
2456 : /*
2457 : * match_opclause_to_indexcol()
2458 : * Handles the OpExpr case for match_clause_to_indexcol(),
2459 : * which see for comments.
2460 : */
2461 : static IndexClause *
2462 737630 : match_opclause_to_indexcol(PlannerInfo *root,
2463 : RestrictInfo *rinfo,
2464 : int indexcol,
2465 : IndexOptInfo *index)
2466 : {
2467 : IndexClause *iclause;
2468 737630 : OpExpr *clause = (OpExpr *) rinfo->clause;
2469 : Node *leftop,
2470 : *rightop;
2471 : Oid expr_op;
2472 : Oid expr_coll;
2473 : Index index_relid;
2474 : Oid opfamily;
2475 : Oid idxcollation;
2476 :
2477 : /*
2478 : * Only binary operators need apply. (In theory, a planner support
2479 : * function could do something with a unary operator, but it seems
2480 : * unlikely to be worth the cycles to check.)
2481 : */
2482 737630 : if (list_length(clause->args) != 2)
2483 0 : return NULL;
2484 :
2485 737630 : leftop = (Node *) linitial(clause->args);
2486 737630 : rightop = (Node *) lsecond(clause->args);
2487 737630 : expr_op = clause->opno;
2488 737630 : expr_coll = clause->inputcollid;
2489 :
2490 737630 : index_relid = index->rel->relid;
2491 737630 : opfamily = index->opfamily[indexcol];
2492 737630 : idxcollation = index->indexcollations[indexcol];
2493 :
2494 : /*
2495 : * Check for clauses of the form: (indexkey operator constant) or
2496 : * (constant operator indexkey). See match_clause_to_indexcol's notes
2497 : * about const-ness.
2498 : *
2499 : * Note that we don't ask the support function about clauses that don't
2500 : * have one of these forms. Again, in principle it might be possible to
2501 : * do something, but it seems unlikely to be worth the cycles to check.
2502 : */
2503 737630 : if (match_index_to_operand(leftop, indexcol, index) &&
2504 211038 : !bms_is_member(index_relid, rinfo->right_relids) &&
2505 210974 : !contain_volatile_functions(rightop))
2506 : {
2507 419478 : if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
2508 208504 : op_in_opfamily(expr_op, opfamily))
2509 : {
2510 203890 : iclause = makeNode(IndexClause);
2511 203890 : iclause->rinfo = rinfo;
2512 203890 : iclause->indexquals = list_make1(rinfo);
2513 203890 : iclause->lossy = false;
2514 203890 : iclause->indexcol = indexcol;
2515 203890 : iclause->indexcols = NIL;
2516 203890 : return iclause;
2517 : }
2518 :
2519 : /*
2520 : * If we didn't find a member of the index's opfamily, try the support
2521 : * function for the operator's underlying function.
2522 : */
2523 7084 : set_opfuncid(clause); /* make sure we have opfuncid */
2524 7084 : return get_index_clause_from_support(root,
2525 : rinfo,
2526 : clause->opfuncid,
2527 : 0, /* indexarg on left */
2528 : indexcol,
2529 : index);
2530 : }
2531 :
2532 526656 : if (match_index_to_operand(rightop, indexcol, index) &&
2533 19044 : !bms_is_member(index_relid, rinfo->left_relids) &&
2534 19008 : !contain_volatile_functions(leftop))
2535 : {
2536 19008 : if (IndexCollMatchesExprColl(idxcollation, expr_coll))
2537 : {
2538 19008 : Oid comm_op = get_commutator(expr_op);
2539 :
2540 38016 : if (OidIsValid(comm_op) &&
2541 19008 : op_in_opfamily(comm_op, opfamily))
2542 : {
2543 : RestrictInfo *commrinfo;
2544 :
2545 : /* Build a commuted OpExpr and RestrictInfo */
2546 18752 : commrinfo = commute_restrictinfo(rinfo, comm_op);
2547 :
2548 : /* Make an IndexClause showing that as a derived qual */
2549 18752 : iclause = makeNode(IndexClause);
2550 18752 : iclause->rinfo = rinfo;
2551 18752 : iclause->indexquals = list_make1(commrinfo);
2552 18752 : iclause->lossy = false;
2553 18752 : iclause->indexcol = indexcol;
2554 18752 : iclause->indexcols = NIL;
2555 18752 : return iclause;
2556 : }
2557 : }
2558 :
2559 : /*
2560 : * If we didn't find a member of the index's opfamily, try the support
2561 : * function for the operator's underlying function.
2562 : */
2563 256 : set_opfuncid(clause); /* make sure we have opfuncid */
2564 256 : return get_index_clause_from_support(root,
2565 : rinfo,
2566 : clause->opfuncid,
2567 : 1, /* indexarg on right */
2568 : indexcol,
2569 : index);
2570 : }
2571 :
2572 507648 : return NULL;
2573 : }
2574 :
2575 : /*
2576 : * match_funcclause_to_indexcol()
2577 : * Handles the FuncExpr case for match_clause_to_indexcol(),
2578 : * which see for comments.
2579 : */
2580 : static IndexClause *
2581 12824 : match_funcclause_to_indexcol(PlannerInfo *root,
2582 : RestrictInfo *rinfo,
2583 : int indexcol,
2584 : IndexOptInfo *index)
2585 : {
2586 12824 : FuncExpr *clause = (FuncExpr *) rinfo->clause;
2587 : int indexarg;
2588 : ListCell *lc;
2589 :
2590 : /*
2591 : * We have no built-in intelligence about function clauses, but if there's
2592 : * a planner support function, it might be able to do something. But, to
2593 : * cut down on wasted planning cycles, only call the support function if
2594 : * at least one argument matches the target index column.
2595 : *
2596 : * Note that we don't insist on the other arguments being pseudoconstants;
2597 : * the support function has to check that. This is to allow cases where
2598 : * only some of the other arguments need to be included in the indexqual.
2599 : */
2600 12824 : indexarg = 0;
2601 27562 : foreach(lc, clause->args)
2602 : {
2603 17036 : Node *op = (Node *) lfirst(lc);
2604 :
2605 17036 : if (match_index_to_operand(op, indexcol, index))
2606 : {
2607 2298 : return get_index_clause_from_support(root,
2608 : rinfo,
2609 : clause->funcid,
2610 : indexarg,
2611 : indexcol,
2612 : index);
2613 : }
2614 :
2615 14738 : indexarg++;
2616 : }
2617 :
2618 10526 : return NULL;
2619 : }
2620 :
2621 : /*
2622 : * get_index_clause_from_support()
2623 : * If the function has a planner support function, try to construct
2624 : * an IndexClause using indexquals created by the support function.
2625 : */
2626 : static IndexClause *
2627 9638 : get_index_clause_from_support(PlannerInfo *root,
2628 : RestrictInfo *rinfo,
2629 : Oid funcid,
2630 : int indexarg,
2631 : int indexcol,
2632 : IndexOptInfo *index)
2633 : {
2634 9638 : Oid prosupport = get_func_support(funcid);
2635 : SupportRequestIndexCondition req;
2636 : List *sresult;
2637 :
2638 9638 : if (!OidIsValid(prosupport))
2639 6046 : return NULL;
2640 :
2641 3592 : req.type = T_SupportRequestIndexCondition;
2642 3592 : req.root = root;
2643 3592 : req.funcid = funcid;
2644 3592 : req.node = (Node *) rinfo->clause;
2645 3592 : req.indexarg = indexarg;
2646 3592 : req.index = index;
2647 3592 : req.indexcol = indexcol;
2648 3592 : req.opfamily = index->opfamily[indexcol];
2649 3592 : req.indexcollation = index->indexcollations[indexcol];
2650 :
2651 3592 : req.lossy = true; /* default assumption */
2652 :
2653 3592 : sresult = (List *)
2654 3592 : DatumGetPointer(OidFunctionCall1(prosupport,
2655 : PointerGetDatum(&req)));
2656 :
2657 3592 : if (sresult != NIL)
2658 : {
2659 3462 : IndexClause *iclause = makeNode(IndexClause);
2660 3462 : List *indexquals = NIL;
2661 : ListCell *lc;
2662 :
2663 : /*
2664 : * The support function API says it should just give back bare
2665 : * clauses, so here we must wrap each one in a RestrictInfo.
2666 : */
2667 7982 : foreach(lc, sresult)
2668 : {
2669 4520 : Expr *clause = (Expr *) lfirst(lc);
2670 :
2671 4520 : indexquals = lappend(indexquals,
2672 4520 : make_simple_restrictinfo(root, clause));
2673 : }
2674 :
2675 3462 : iclause->rinfo = rinfo;
2676 3462 : iclause->indexquals = indexquals;
2677 3462 : iclause->lossy = req.lossy;
2678 3462 : iclause->indexcol = indexcol;
2679 3462 : iclause->indexcols = NIL;
2680 :
2681 3462 : return iclause;
2682 : }
2683 :
2684 130 : return NULL;
2685 : }
2686 :
2687 : /*
2688 : * match_saopclause_to_indexcol()
2689 : * Handles the ScalarArrayOpExpr case for match_clause_to_indexcol(),
2690 : * which see for comments.
2691 : */
2692 : static IndexClause *
2693 56530 : match_saopclause_to_indexcol(PlannerInfo *root,
2694 : RestrictInfo *rinfo,
2695 : int indexcol,
2696 : IndexOptInfo *index)
2697 : {
2698 56530 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
2699 : Node *leftop,
2700 : *rightop;
2701 : Relids right_relids;
2702 : Oid expr_op;
2703 : Oid expr_coll;
2704 : Index index_relid;
2705 : Oid opfamily;
2706 : Oid idxcollation;
2707 :
2708 : /* We only accept ANY clauses, not ALL */
2709 56530 : if (!saop->useOr)
2710 3590 : return NULL;
2711 52940 : leftop = (Node *) linitial(saop->args);
2712 52940 : rightop = (Node *) lsecond(saop->args);
2713 52940 : right_relids = pull_varnos(root, rightop);
2714 52940 : expr_op = saop->opno;
2715 52940 : expr_coll = saop->inputcollid;
2716 :
2717 52940 : index_relid = index->rel->relid;
2718 52940 : opfamily = index->opfamily[indexcol];
2719 52940 : idxcollation = index->indexcollations[indexcol];
2720 :
2721 : /*
2722 : * We must have indexkey on the left and a pseudo-constant array argument.
2723 : */
2724 52940 : if (match_index_to_operand(leftop, indexcol, index) &&
2725 7958 : !bms_is_member(index_relid, right_relids) &&
2726 7958 : !contain_volatile_functions(rightop))
2727 : {
2728 15912 : if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
2729 7954 : op_in_opfamily(expr_op, opfamily))
2730 : {
2731 7946 : IndexClause *iclause = makeNode(IndexClause);
2732 :
2733 7946 : iclause->rinfo = rinfo;
2734 7946 : iclause->indexquals = list_make1(rinfo);
2735 7946 : iclause->lossy = false;
2736 7946 : iclause->indexcol = indexcol;
2737 7946 : iclause->indexcols = NIL;
2738 7946 : return iclause;
2739 : }
2740 :
2741 : /*
2742 : * We do not currently ask support functions about ScalarArrayOpExprs,
2743 : * though in principle we could.
2744 : */
2745 : }
2746 :
2747 44994 : return NULL;
2748 : }
2749 :
2750 : /*
2751 : * match_rowcompare_to_indexcol()
2752 : * Handles the RowCompareExpr case for match_clause_to_indexcol(),
2753 : * which see for comments.
2754 : *
2755 : * In this routine we check whether the first column of the row comparison
2756 : * matches the target index column. This is sufficient to guarantee that some
2757 : * index condition can be constructed from the RowCompareExpr --- the rest
2758 : * is handled by expand_indexqual_rowcompare().
2759 : */
2760 : static IndexClause *
2761 192 : match_rowcompare_to_indexcol(PlannerInfo *root,
2762 : RestrictInfo *rinfo,
2763 : int indexcol,
2764 : IndexOptInfo *index)
2765 : {
2766 192 : RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
2767 : Index index_relid;
2768 : Oid opfamily;
2769 : Oid idxcollation;
2770 : Node *leftop,
2771 : *rightop;
2772 : bool var_on_left;
2773 : Oid expr_op;
2774 : Oid expr_coll;
2775 :
2776 : /* Forget it if we're not dealing with a btree index */
2777 192 : if (index->relam != BTREE_AM_OID)
2778 0 : return NULL;
2779 :
2780 192 : index_relid = index->rel->relid;
2781 192 : opfamily = index->opfamily[indexcol];
2782 192 : idxcollation = index->indexcollations[indexcol];
2783 :
2784 : /*
2785 : * We could do the matching on the basis of insisting that the opfamily
2786 : * shown in the RowCompareExpr be the same as the index column's opfamily,
2787 : * but that could fail in the presence of reverse-sort opfamilies: it'd be
2788 : * a matter of chance whether RowCompareExpr had picked the forward or
2789 : * reverse-sort family. So look only at the operator, and match if it is
2790 : * a member of the index's opfamily (after commutation, if the indexkey is
2791 : * on the right). We'll worry later about whether any additional
2792 : * operators are matchable to the index.
2793 : */
2794 192 : leftop = (Node *) linitial(clause->largs);
2795 192 : rightop = (Node *) linitial(clause->rargs);
2796 192 : expr_op = linitial_oid(clause->opnos);
2797 192 : expr_coll = linitial_oid(clause->inputcollids);
2798 :
2799 : /* Collations must match, if relevant */
2800 192 : if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
2801 0 : return NULL;
2802 :
2803 : /*
2804 : * These syntactic tests are the same as in match_opclause_to_indexcol()
2805 : */
2806 192 : if (match_index_to_operand(leftop, indexcol, index) &&
2807 44 : !bms_is_member(index_relid, pull_varnos(root, rightop)) &&
2808 44 : !contain_volatile_functions(rightop))
2809 : {
2810 : /* OK, indexkey is on left */
2811 44 : var_on_left = true;
2812 : }
2813 148 : else if (match_index_to_operand(rightop, indexcol, index) &&
2814 16 : !bms_is_member(index_relid, pull_varnos(root, leftop)) &&
2815 16 : !contain_volatile_functions(leftop))
2816 : {
2817 : /* indexkey is on right, so commute the operator */
2818 16 : expr_op = get_commutator(expr_op);
2819 16 : if (expr_op == InvalidOid)
2820 0 : return NULL;
2821 16 : var_on_left = false;
2822 : }
2823 : else
2824 132 : return NULL;
2825 :
2826 : /* We're good if the operator is the right type of opfamily member */
2827 60 : switch (get_op_opfamily_strategy(expr_op, opfamily))
2828 : {
2829 60 : case BTLessStrategyNumber:
2830 : case BTLessEqualStrategyNumber:
2831 : case BTGreaterEqualStrategyNumber:
2832 : case BTGreaterStrategyNumber:
2833 60 : return expand_indexqual_rowcompare(root,
2834 : rinfo,
2835 : indexcol,
2836 : index,
2837 : expr_op,
2838 : var_on_left);
2839 : }
2840 :
2841 0 : return NULL;
2842 : }
2843 :
2844 : /*
2845 : * expand_indexqual_rowcompare --- expand a single indexqual condition
2846 : * that is a RowCompareExpr
2847 : *
2848 : * It's already known that the first column of the row comparison matches
2849 : * the specified column of the index. We can use additional columns of the
2850 : * row comparison as index qualifications, so long as they match the index
2851 : * in the "same direction", ie, the indexkeys are all on the same side of the
2852 : * clause and the operators are all the same-type members of the opfamilies.
2853 : *
2854 : * If all the columns of the RowCompareExpr match in this way, we just use it
2855 : * as-is, except for possibly commuting it to put the indexkeys on the left.
2856 : *
2857 : * Otherwise, we build a shortened RowCompareExpr (if more than one
2858 : * column matches) or a simple OpExpr (if the first-column match is all
2859 : * there is). In these cases the modified clause is always "<=" or ">="
2860 : * even when the original was "<" or ">" --- this is necessary to match all
2861 : * the rows that could match the original. (We are building a lossy version
2862 : * of the row comparison when we do this, so we set lossy = true.)
2863 : *
2864 : * Note: this is really just the last half of match_rowcompare_to_indexcol,
2865 : * but we split it out for comprehensibility.
2866 : */
2867 : static IndexClause *
2868 60 : expand_indexqual_rowcompare(PlannerInfo *root,
2869 : RestrictInfo *rinfo,
2870 : int indexcol,
2871 : IndexOptInfo *index,
2872 : Oid expr_op,
2873 : bool var_on_left)
2874 : {
2875 60 : IndexClause *iclause = makeNode(IndexClause);
2876 60 : RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
2877 : int op_strategy;
2878 : Oid op_lefttype;
2879 : Oid op_righttype;
2880 : int matching_cols;
2881 : List *expr_ops;
2882 : List *opfamilies;
2883 : List *lefttypes;
2884 : List *righttypes;
2885 : List *new_ops;
2886 : List *var_args;
2887 : List *non_var_args;
2888 :
2889 60 : iclause->rinfo = rinfo;
2890 60 : iclause->indexcol = indexcol;
2891 :
2892 60 : if (var_on_left)
2893 : {
2894 44 : var_args = clause->largs;
2895 44 : non_var_args = clause->rargs;
2896 : }
2897 : else
2898 : {
2899 16 : var_args = clause->rargs;
2900 16 : non_var_args = clause->largs;
2901 : }
2902 :
2903 60 : get_op_opfamily_properties(expr_op, index->opfamily[indexcol], false,
2904 : &op_strategy,
2905 : &op_lefttype,
2906 : &op_righttype);
2907 :
2908 : /* Initialize returned list of which index columns are used */
2909 60 : iclause->indexcols = list_make1_int(indexcol);
2910 :
2911 : /* Build lists of ops, opfamilies and operator datatypes in case needed */
2912 60 : expr_ops = list_make1_oid(expr_op);
2913 60 : opfamilies = list_make1_oid(index->opfamily[indexcol]);
2914 60 : lefttypes = list_make1_oid(op_lefttype);
2915 60 : righttypes = list_make1_oid(op_righttype);
2916 :
2917 : /*
2918 : * See how many of the remaining columns match some index column in the
2919 : * same way. As in match_clause_to_indexcol(), the "other" side of any
2920 : * potential index condition is OK as long as it doesn't use Vars from the
2921 : * indexed relation.
2922 : */
2923 60 : matching_cols = 1;
2924 :
2925 108 : while (matching_cols < list_length(var_args))
2926 : {
2927 84 : Node *varop = (Node *) list_nth(var_args, matching_cols);
2928 84 : Node *constop = (Node *) list_nth(non_var_args, matching_cols);
2929 : int i;
2930 :
2931 84 : expr_op = list_nth_oid(clause->opnos, matching_cols);
2932 84 : if (!var_on_left)
2933 : {
2934 : /* indexkey is on right, so commute the operator */
2935 16 : expr_op = get_commutator(expr_op);
2936 16 : if (expr_op == InvalidOid)
2937 0 : break; /* operator is not usable */
2938 : }
2939 84 : if (bms_is_member(index->rel->relid, pull_varnos(root, constop)))
2940 0 : break; /* no good, Var on wrong side */
2941 84 : if (contain_volatile_functions(constop))
2942 0 : break; /* no good, volatile comparison value */
2943 :
2944 : /*
2945 : * The Var side can match any key column of the index.
2946 : */
2947 200 : for (i = 0; i < index->nkeycolumns; i++)
2948 : {
2949 164 : if (match_index_to_operand(varop, i, index) &&
2950 48 : get_op_opfamily_strategy(expr_op,
2951 48 : index->opfamily[i]) == op_strategy &&
2952 48 : IndexCollMatchesExprColl(index->indexcollations[i],
2953 : list_nth_oid(clause->inputcollids,
2954 : matching_cols)))
2955 : break;
2956 : }
2957 84 : if (i >= index->nkeycolumns)
2958 36 : break; /* no match found */
2959 :
2960 : /* Add column number to returned list */
2961 48 : iclause->indexcols = lappend_int(iclause->indexcols, i);
2962 :
2963 : /* Add operator info to lists */
2964 48 : get_op_opfamily_properties(expr_op, index->opfamily[i], false,
2965 : &op_strategy,
2966 : &op_lefttype,
2967 : &op_righttype);
2968 48 : expr_ops = lappend_oid(expr_ops, expr_op);
2969 48 : opfamilies = lappend_oid(opfamilies, index->opfamily[i]);
2970 48 : lefttypes = lappend_oid(lefttypes, op_lefttype);
2971 48 : righttypes = lappend_oid(righttypes, op_righttype);
2972 :
2973 : /* This column matches, keep scanning */
2974 48 : matching_cols++;
2975 : }
2976 :
2977 : /* Result is non-lossy if all columns are usable as index quals */
2978 60 : iclause->lossy = (matching_cols != list_length(clause->opnos));
2979 :
2980 : /*
2981 : * We can use rinfo->clause as-is if we have var on left and it's all
2982 : * usable as index quals.
2983 : */
2984 60 : if (var_on_left && !iclause->lossy)
2985 16 : iclause->indexquals = list_make1(rinfo);
2986 : else
2987 : {
2988 : /*
2989 : * We have to generate a modified rowcompare (possibly just one
2990 : * OpExpr). The painful part of this is changing < to <= or > to >=,
2991 : * so deal with that first.
2992 : */
2993 44 : if (!iclause->lossy)
2994 : {
2995 : /* very easy, just use the commuted operators */
2996 8 : new_ops = expr_ops;
2997 : }
2998 36 : else if (op_strategy == BTLessEqualStrategyNumber ||
2999 36 : op_strategy == BTGreaterEqualStrategyNumber)
3000 : {
3001 : /* easy, just use the same (possibly commuted) operators */
3002 0 : new_ops = list_truncate(expr_ops, matching_cols);
3003 : }
3004 : else
3005 : {
3006 : ListCell *opfamilies_cell;
3007 : ListCell *lefttypes_cell;
3008 : ListCell *righttypes_cell;
3009 :
3010 36 : if (op_strategy == BTLessStrategyNumber)
3011 20 : op_strategy = BTLessEqualStrategyNumber;
3012 16 : else if (op_strategy == BTGreaterStrategyNumber)
3013 16 : op_strategy = BTGreaterEqualStrategyNumber;
3014 : else
3015 0 : elog(ERROR, "unexpected strategy number %d", op_strategy);
3016 36 : new_ops = NIL;
3017 96 : forthree(opfamilies_cell, opfamilies,
3018 : lefttypes_cell, lefttypes,
3019 : righttypes_cell, righttypes)
3020 : {
3021 60 : Oid opfam = lfirst_oid(opfamilies_cell);
3022 60 : Oid lefttype = lfirst_oid(lefttypes_cell);
3023 60 : Oid righttype = lfirst_oid(righttypes_cell);
3024 :
3025 60 : expr_op = get_opfamily_member(opfam, lefttype, righttype,
3026 : op_strategy);
3027 60 : if (!OidIsValid(expr_op)) /* should not happen */
3028 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3029 : op_strategy, lefttype, righttype, opfam);
3030 60 : new_ops = lappend_oid(new_ops, expr_op);
3031 : }
3032 : }
3033 :
3034 : /* If we have more than one matching col, create a subset rowcompare */
3035 44 : if (matching_cols > 1)
3036 : {
3037 32 : RowCompareExpr *rc = makeNode(RowCompareExpr);
3038 :
3039 32 : rc->rctype = (RowCompareType) op_strategy;
3040 32 : rc->opnos = new_ops;
3041 32 : rc->opfamilies = list_truncate(list_copy(clause->opfamilies),
3042 : matching_cols);
3043 32 : rc->inputcollids = list_truncate(list_copy(clause->inputcollids),
3044 : matching_cols);
3045 32 : rc->largs = list_truncate(copyObject(var_args),
3046 : matching_cols);
3047 32 : rc->rargs = list_truncate(copyObject(non_var_args),
3048 : matching_cols);
3049 32 : iclause->indexquals = list_make1(make_simple_restrictinfo(root,
3050 : (Expr *) rc));
3051 : }
3052 : else
3053 : {
3054 : Expr *op;
3055 :
3056 : /* We don't report an index column list in this case */
3057 12 : iclause->indexcols = NIL;
3058 :
3059 12 : op = make_opclause(linitial_oid(new_ops), BOOLOID, false,
3060 12 : copyObject(linitial(var_args)),
3061 12 : copyObject(linitial(non_var_args)),
3062 : InvalidOid,
3063 12 : linitial_oid(clause->inputcollids));
3064 12 : iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
3065 : }
3066 : }
3067 :
3068 60 : return iclause;
3069 : }
3070 :
3071 :
3072 : /****************************************************************************
3073 : * ---- ROUTINES TO CHECK ORDERING OPERATORS ----
3074 : ****************************************************************************/
3075 :
3076 : /*
3077 : * match_pathkeys_to_index
3078 : * Test whether an index can produce output ordered according to the
3079 : * given pathkeys using "ordering operators".
3080 : *
3081 : * If it can, return a list of suitable ORDER BY expressions, each of the form
3082 : * "indexedcol operator pseudoconstant", along with an integer list of the
3083 : * index column numbers (zero based) that each clause would be used with.
3084 : * NIL lists are returned if the ordering is not achievable this way.
3085 : *
3086 : * On success, the result list is ordered by pathkeys, and in fact is
3087 : * one-to-one with the requested pathkeys.
3088 : */
3089 : static void
3090 552 : match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
3091 : List **orderby_clauses_p,
3092 : List **clause_columns_p)
3093 : {
3094 552 : List *orderby_clauses = NIL;
3095 552 : List *clause_columns = NIL;
3096 : ListCell *lc1;
3097 :
3098 552 : *orderby_clauses_p = NIL; /* set default results */
3099 552 : *clause_columns_p = NIL;
3100 :
3101 : /* Only indexes with the amcanorderbyop property are interesting here */
3102 552 : if (!index->amcanorderbyop)
3103 0 : return;
3104 :
3105 872 : foreach(lc1, pathkeys)
3106 : {
3107 544 : PathKey *pathkey = (PathKey *) lfirst(lc1);
3108 544 : bool found = false;
3109 : ListCell *lc2;
3110 :
3111 : /*
3112 : * Note: for any failure to match, we just return NIL immediately.
3113 : * There is no value in matching just some of the pathkeys.
3114 : */
3115 :
3116 : /* Pathkey must request default sort order for the target opfamily */
3117 544 : if (pathkey->pk_strategy != BTLessStrategyNumber ||
3118 516 : pathkey->pk_nulls_first)
3119 224 : return;
3120 :
3121 : /* If eclass is volatile, no hope of using an indexscan */
3122 516 : if (pathkey->pk_eclass->ec_has_volatile)
3123 0 : return;
3124 :
3125 : /*
3126 : * Try to match eclass member expression(s) to index. Note that child
3127 : * EC members are considered, but only when they belong to the target
3128 : * relation. (Unlike regular members, the same expression could be a
3129 : * child member of more than one EC. Therefore, the same index could
3130 : * be considered to match more than one pathkey list, which is OK
3131 : * here. See also get_eclass_for_sort_expr.)
3132 : */
3133 712 : foreach(lc2, pathkey->pk_eclass->ec_members)
3134 : {
3135 516 : EquivalenceMember *member = (EquivalenceMember *) lfirst(lc2);
3136 : int indexcol;
3137 :
3138 : /* No possibility of match if it references other relations */
3139 516 : if (!bms_equal(member->em_relids, index->rel->relids))
3140 0 : continue;
3141 :
3142 : /*
3143 : * We allow any column of the index to match each pathkey; they
3144 : * don't have to match left-to-right as you might expect. This is
3145 : * correct for GiST, and it doesn't matter for SP-GiST because
3146 : * that doesn't handle multiple columns anyway, and no other
3147 : * existing AMs support amcanorderbyop. We might need different
3148 : * logic in future for other implementations.
3149 : */
3150 712 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
3151 : {
3152 : Expr *expr;
3153 :
3154 516 : expr = match_clause_to_ordering_op(index,
3155 : indexcol,
3156 : member->em_expr,
3157 : pathkey->pk_opfamily);
3158 516 : if (expr)
3159 : {
3160 320 : orderby_clauses = lappend(orderby_clauses, expr);
3161 320 : clause_columns = lappend_int(clause_columns, indexcol);
3162 320 : found = true;
3163 320 : break;
3164 : }
3165 : }
3166 :
3167 516 : if (found) /* don't want to look at remaining members */
3168 320 : break;
3169 : }
3170 :
3171 516 : if (!found) /* fail if no match for this pathkey */
3172 196 : return;
3173 : }
3174 :
3175 328 : *orderby_clauses_p = orderby_clauses; /* success! */
3176 328 : *clause_columns_p = clause_columns;
3177 : }
3178 :
3179 : /*
3180 : * match_clause_to_ordering_op
3181 : * Determines whether an ordering operator expression matches an
3182 : * index column.
3183 : *
3184 : * This is similar to, but simpler than, match_clause_to_indexcol.
3185 : * We only care about simple OpExpr cases. The input is a bare
3186 : * expression that is being ordered by, which must be of the form
3187 : * (indexkey op const) or (const op indexkey) where op is an ordering
3188 : * operator for the column's opfamily.
3189 : *
3190 : * 'index' is the index of interest.
3191 : * 'indexcol' is a column number of 'index' (counting from 0).
3192 : * 'clause' is the ordering expression to be tested.
3193 : * 'pk_opfamily' is the btree opfamily describing the required sort order.
3194 : *
3195 : * Note that we currently do not consider the collation of the ordering
3196 : * operator's result. In practical cases the result type will be numeric
3197 : * and thus have no collation, and it's not very clear what to match to
3198 : * if it did have a collation. The index's collation should match the
3199 : * ordering operator's input collation, not its result.
3200 : *
3201 : * If successful, return 'clause' as-is if the indexkey is on the left,
3202 : * otherwise a commuted copy of 'clause'. If no match, return NULL.
3203 : */
3204 : static Expr *
3205 516 : match_clause_to_ordering_op(IndexOptInfo *index,
3206 : int indexcol,
3207 : Expr *clause,
3208 : Oid pk_opfamily)
3209 : {
3210 : Oid opfamily;
3211 : Oid idxcollation;
3212 : Node *leftop,
3213 : *rightop;
3214 : Oid expr_op;
3215 : Oid expr_coll;
3216 : Oid sortfamily;
3217 : bool commuted;
3218 :
3219 : Assert(indexcol < index->nkeycolumns);
3220 :
3221 516 : opfamily = index->opfamily[indexcol];
3222 516 : idxcollation = index->indexcollations[indexcol];
3223 :
3224 : /*
3225 : * Clause must be a binary opclause.
3226 : */
3227 516 : if (!is_opclause(clause))
3228 196 : return NULL;
3229 320 : leftop = get_leftop(clause);
3230 320 : rightop = get_rightop(clause);
3231 320 : if (!leftop || !rightop)
3232 0 : return NULL;
3233 320 : expr_op = ((OpExpr *) clause)->opno;
3234 320 : expr_coll = ((OpExpr *) clause)->inputcollid;
3235 :
3236 : /*
3237 : * We can forget the whole thing right away if wrong collation.
3238 : */
3239 320 : if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
3240 0 : return NULL;
3241 :
3242 : /*
3243 : * Check for clauses of the form: (indexkey operator constant) or
3244 : * (constant operator indexkey).
3245 : */
3246 320 : if (match_index_to_operand(leftop, indexcol, index) &&
3247 304 : !contain_var_clause(rightop) &&
3248 304 : !contain_volatile_functions(rightop))
3249 : {
3250 304 : commuted = false;
3251 : }
3252 16 : else if (match_index_to_operand(rightop, indexcol, index) &&
3253 16 : !contain_var_clause(leftop) &&
3254 16 : !contain_volatile_functions(leftop))
3255 : {
3256 : /* Might match, but we need a commuted operator */
3257 16 : expr_op = get_commutator(expr_op);
3258 16 : if (expr_op == InvalidOid)
3259 0 : return NULL;
3260 16 : commuted = true;
3261 : }
3262 : else
3263 0 : return NULL;
3264 :
3265 : /*
3266 : * Is the (commuted) operator an ordering operator for the opfamily? And
3267 : * if so, does it yield the right sorting semantics?
3268 : */
3269 320 : sortfamily = get_op_opfamily_sortfamily(expr_op, opfamily);
3270 320 : if (sortfamily != pk_opfamily)
3271 0 : return NULL;
3272 :
3273 : /* We have a match. Return clause or a commuted version thereof. */
3274 320 : if (commuted)
3275 : {
3276 16 : OpExpr *newclause = makeNode(OpExpr);
3277 :
3278 : /* flat-copy all the fields of clause */
3279 16 : memcpy(newclause, clause, sizeof(OpExpr));
3280 :
3281 : /* commute it */
3282 16 : newclause->opno = expr_op;
3283 16 : newclause->opfuncid = InvalidOid;
3284 16 : newclause->args = list_make2(rightop, leftop);
3285 :
3286 16 : clause = (Expr *) newclause;
3287 : }
3288 :
3289 320 : return clause;
3290 : }
3291 :
3292 :
3293 : /****************************************************************************
3294 : * ---- ROUTINES TO DO PARTIAL INDEX PREDICATE TESTS ----
3295 : ****************************************************************************/
3296 :
3297 : /*
3298 : * check_index_predicates
3299 : * Set the predicate-derived IndexOptInfo fields for each index
3300 : * of the specified relation.
3301 : *
3302 : * predOK is set true if the index is partial and its predicate is satisfied
3303 : * for this query, ie the query's WHERE clauses imply the predicate.
3304 : *
3305 : * indrestrictinfo is set to the relation's baserestrictinfo list less any
3306 : * conditions that are implied by the index's predicate. (Obviously, for a
3307 : * non-partial index, this is the same as baserestrictinfo.) Such conditions
3308 : * can be dropped from the plan when using the index, in certain cases.
3309 : *
3310 : * At one time it was possible for this to get re-run after adding more
3311 : * restrictions to the rel, thus possibly letting us prove more indexes OK.
3312 : * That doesn't happen any more (at least not in the core code's usage),
3313 : * but this code still supports it in case extensions want to mess with the
3314 : * baserestrictinfo list. We assume that adding more restrictions can't make
3315 : * an index not predOK. We must recompute indrestrictinfo each time, though,
3316 : * to make sure any newly-added restrictions get into it if needed.
3317 : */
3318 : void
3319 237568 : check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
3320 : {
3321 : List *clauselist;
3322 : bool have_partial;
3323 : bool is_target_rel;
3324 : Relids otherrels;
3325 : ListCell *lc;
3326 :
3327 : /* Indexes are available only on base or "other" member relations. */
3328 : Assert(IS_SIMPLE_REL(rel));
3329 :
3330 : /*
3331 : * Initialize the indrestrictinfo lists to be identical to
3332 : * baserestrictinfo, and check whether there are any partial indexes. If
3333 : * not, this is all we need to do.
3334 : */
3335 237568 : have_partial = false;
3336 646786 : foreach(lc, rel->indexlist)
3337 : {
3338 409218 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
3339 :
3340 409218 : index->indrestrictinfo = rel->baserestrictinfo;
3341 409218 : if (index->indpred)
3342 678 : have_partial = true;
3343 : }
3344 237568 : if (!have_partial)
3345 237118 : return;
3346 :
3347 : /*
3348 : * Construct a list of clauses that we can assume true for the purpose of
3349 : * proving the index(es) usable. Restriction clauses for the rel are
3350 : * always usable, and so are any join clauses that are "movable to" this
3351 : * rel. Also, we can consider any EC-derivable join clauses (which must
3352 : * be "movable to" this rel, by definition).
3353 : */
3354 450 : clauselist = list_copy(rel->baserestrictinfo);
3355 :
3356 : /* Scan the rel's join clauses */
3357 450 : foreach(lc, rel->joininfo)
3358 : {
3359 0 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3360 :
3361 : /* Check if clause can be moved to this rel */
3362 0 : if (!join_clause_is_movable_to(rinfo, rel))
3363 0 : continue;
3364 :
3365 0 : clauselist = lappend(clauselist, rinfo);
3366 : }
3367 :
3368 : /*
3369 : * Add on any equivalence-derivable join clauses. Computing the correct
3370 : * relid sets for generate_join_implied_equalities is slightly tricky
3371 : * because the rel could be a child rel rather than a true baserel, and in
3372 : * that case we must remove its parents' relid(s) from all_baserels.
3373 : */
3374 450 : if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
3375 48 : otherrels = bms_difference(root->all_baserels,
3376 48 : find_childrel_parents(root, rel));
3377 : else
3378 402 : otherrels = bms_difference(root->all_baserels, rel->relids);
3379 :
3380 450 : if (!bms_is_empty(otherrels))
3381 : clauselist =
3382 56 : list_concat(clauselist,
3383 56 : generate_join_implied_equalities(root,
3384 56 : bms_union(rel->relids,
3385 : otherrels),
3386 : otherrels,
3387 : rel));
3388 :
3389 : /*
3390 : * Normally we remove quals that are implied by a partial index's
3391 : * predicate from indrestrictinfo, indicating that they need not be
3392 : * checked explicitly by an indexscan plan using this index. However, if
3393 : * the rel is a target relation of UPDATE/DELETE/SELECT FOR UPDATE, we
3394 : * cannot remove such quals from the plan, because they need to be in the
3395 : * plan so that they will be properly rechecked by EvalPlanQual testing.
3396 : * Some day we might want to remove such quals from the main plan anyway
3397 : * and pass them through to EvalPlanQual via a side channel; but for now,
3398 : * we just don't remove implied quals at all for target relations.
3399 : */
3400 796 : is_target_rel = (rel->relid == root->parse->resultRelation ||
3401 346 : get_plan_rowmark(root->rowMarks, rel->relid) != NULL);
3402 :
3403 : /*
3404 : * Now try to prove each index predicate true, and compute the
3405 : * indrestrictinfo lists for partial indexes. Note that we compute the
3406 : * indrestrictinfo list even for non-predOK indexes; this might seem
3407 : * wasteful, but we may be able to use such indexes in OR clauses, cf
3408 : * generate_bitmap_or_paths().
3409 : */
3410 1328 : foreach(lc, rel->indexlist)
3411 : {
3412 878 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
3413 : ListCell *lcr;
3414 :
3415 878 : if (index->indpred == NIL)
3416 200 : continue; /* ignore non-partial indexes here */
3417 :
3418 678 : if (!index->predOK) /* don't repeat work if already proven OK */
3419 678 : index->predOK = predicate_implied_by(index->indpred, clauselist,
3420 : false);
3421 :
3422 : /* If rel is an update target, leave indrestrictinfo as set above */
3423 678 : if (is_target_rel)
3424 152 : continue;
3425 :
3426 : /* Else compute indrestrictinfo as the non-implied quals */
3427 526 : index->indrestrictinfo = NIL;
3428 1222 : foreach(lcr, rel->baserestrictinfo)
3429 : {
3430 696 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcr);
3431 :
3432 : /* predicate_implied_by() assumes first arg is immutable */
3433 696 : if (contain_mutable_functions((Node *) rinfo->clause) ||
3434 696 : !predicate_implied_by(list_make1(rinfo->clause),
3435 : index->indpred, false))
3436 488 : index->indrestrictinfo = lappend(index->indrestrictinfo, rinfo);
3437 : }
3438 : }
3439 : }
3440 :
3441 : /****************************************************************************
3442 : * ---- ROUTINES TO CHECK EXTERNALLY-VISIBLE CONDITIONS ----
3443 : ****************************************************************************/
3444 :
3445 : /*
3446 : * ec_member_matches_indexcol
3447 : * Test whether an EquivalenceClass member matches an index column.
3448 : *
3449 : * This is a callback for use by generate_implied_equalities_for_column.
3450 : */
3451 : static bool
3452 147332 : ec_member_matches_indexcol(PlannerInfo *root, RelOptInfo *rel,
3453 : EquivalenceClass *ec, EquivalenceMember *em,
3454 : void *arg)
3455 : {
3456 147332 : IndexOptInfo *index = ((ec_member_matches_arg *) arg)->index;
3457 147332 : int indexcol = ((ec_member_matches_arg *) arg)->indexcol;
3458 : Oid curFamily;
3459 : Oid curCollation;
3460 :
3461 : Assert(indexcol < index->nkeycolumns);
3462 :
3463 147332 : curFamily = index->opfamily[indexcol];
3464 147332 : curCollation = index->indexcollations[indexcol];
3465 :
3466 : /*
3467 : * If it's a btree index, we can reject it if its opfamily isn't
3468 : * compatible with the EC, since no clause generated from the EC could be
3469 : * used with the index. For non-btree indexes, we can't easily tell
3470 : * whether clauses generated from the EC could be used with the index, so
3471 : * don't check the opfamily. This might mean we return "true" for a
3472 : * useless EC, so we have to recheck the results of
3473 : * generate_implied_equalities_for_column; see
3474 : * match_eclass_clauses_to_index.
3475 : */
3476 147332 : if (index->relam == BTREE_AM_OID &&
3477 147304 : !list_member_oid(ec->ec_opfamilies, curFamily))
3478 46058 : return false;
3479 :
3480 : /* We insist on collation match for all index types, though */
3481 101274 : if (!IndexCollMatchesExprColl(curCollation, ec->ec_collation))
3482 6 : return false;
3483 :
3484 101268 : return match_index_to_operand((Node *) em->em_expr, indexcol, index);
3485 : }
3486 :
3487 : /*
3488 : * relation_has_unique_index_for
3489 : * Determine whether the relation provably has at most one row satisfying
3490 : * a set of equality conditions, because the conditions constrain all
3491 : * columns of some unique index.
3492 : *
3493 : * The conditions can be represented in either or both of two ways:
3494 : * 1. A list of RestrictInfo nodes, where the caller has already determined
3495 : * that each condition is a mergejoinable equality with an expression in
3496 : * this relation on one side, and an expression not involving this relation
3497 : * on the other. The transient outer_is_left flag is used to identify which
3498 : * side we should look at: left side if outer_is_left is false, right side
3499 : * if it is true.
3500 : * 2. A list of expressions in this relation, and a corresponding list of
3501 : * equality operators. The caller must have already checked that the operators
3502 : * represent equality. (Note: the operators could be cross-type; the
3503 : * expressions should correspond to their RHS inputs.)
3504 : *
3505 : * The caller need only supply equality conditions arising from joins;
3506 : * this routine automatically adds in any usable baserestrictinfo clauses.
3507 : * (Note that the passed-in restrictlist will be destructively modified!)
3508 : */
3509 : bool
3510 116814 : relation_has_unique_index_for(PlannerInfo *root, RelOptInfo *rel,
3511 : List *restrictlist,
3512 : List *exprlist, List *oprlist)
3513 : {
3514 : ListCell *ic;
3515 :
3516 : Assert(list_length(exprlist) == list_length(oprlist));
3517 :
3518 : /* Short-circuit if no indexes... */
3519 116814 : if (rel->indexlist == NIL)
3520 284 : return false;
3521 :
3522 : /*
3523 : * Examine the rel's restriction clauses for usable var = const clauses
3524 : * that we can add to the restrictlist.
3525 : */
3526 221916 : foreach(ic, rel->baserestrictinfo)
3527 : {
3528 105386 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(ic);
3529 :
3530 : /*
3531 : * Note: can_join won't be set for a restriction clause, but
3532 : * mergeopfamilies will be if it has a mergejoinable operator and
3533 : * doesn't contain volatile functions.
3534 : */
3535 105386 : if (restrictinfo->mergeopfamilies == NIL)
3536 42362 : continue; /* not mergejoinable */
3537 :
3538 : /*
3539 : * The clause certainly doesn't refer to anything but the given rel.
3540 : * If either side is pseudoconstant then we can use it.
3541 : */
3542 63024 : if (bms_is_empty(restrictinfo->left_relids))
3543 : {
3544 : /* righthand side is inner */
3545 1458 : restrictinfo->outer_is_left = true;
3546 : }
3547 61566 : else if (bms_is_empty(restrictinfo->right_relids))
3548 : {
3549 : /* lefthand side is inner */
3550 61536 : restrictinfo->outer_is_left = false;
3551 : }
3552 : else
3553 30 : continue;
3554 :
3555 : /* OK, add to list */
3556 62994 : restrictlist = lappend(restrictlist, restrictinfo);
3557 : }
3558 :
3559 : /* Short-circuit the easy case */
3560 116530 : if (restrictlist == NIL && exprlist == NIL)
3561 148 : return false;
3562 :
3563 : /* Examine each index of the relation ... */
3564 307794 : foreach(ic, rel->indexlist)
3565 : {
3566 257602 : IndexOptInfo *ind = (IndexOptInfo *) lfirst(ic);
3567 : int c;
3568 :
3569 : /*
3570 : * If the index is not unique, or not immediately enforced, or if it's
3571 : * a partial index that doesn't match the query, it's useless here.
3572 : */
3573 257602 : if (!ind->unique || !ind->immediate ||
3574 176392 : (ind->indpred != NIL && !ind->predOK))
3575 81210 : continue;
3576 :
3577 : /*
3578 : * Try to find each index column in the lists of conditions. This is
3579 : * O(N^2) or worse, but we expect all the lists to be short.
3580 : */
3581 306162 : for (c = 0; c < ind->nkeycolumns; c++)
3582 : {
3583 239972 : bool matched = false;
3584 : ListCell *lc;
3585 : ListCell *lc2;
3586 :
3587 478266 : foreach(lc, restrictlist)
3588 : {
3589 368064 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3590 : Node *rexpr;
3591 :
3592 : /*
3593 : * The condition's equality operator must be a member of the
3594 : * index opfamily, else it is not asserting the right kind of
3595 : * equality behavior for this index. We check this first
3596 : * since it's probably cheaper than match_index_to_operand().
3597 : */
3598 368064 : if (!list_member_oid(rinfo->mergeopfamilies, ind->opfamily[c]))
3599 93608 : continue;
3600 :
3601 : /*
3602 : * XXX at some point we may need to check collations here too.
3603 : * For the moment we assume all collations reduce to the same
3604 : * notion of equality.
3605 : */
3606 :
3607 : /* OK, see if the condition operand matches the index key */
3608 274456 : if (rinfo->outer_is_left)
3609 135844 : rexpr = get_rightop(rinfo->clause);
3610 : else
3611 138612 : rexpr = get_leftop(rinfo->clause);
3612 :
3613 274456 : if (match_index_to_operand(rexpr, c, ind))
3614 : {
3615 129770 : matched = true; /* column is unique */
3616 129770 : break;
3617 : }
3618 : }
3619 :
3620 239972 : if (matched)
3621 129770 : continue;
3622 :
3623 110202 : forboth(lc, exprlist, lc2, oprlist)
3624 : {
3625 0 : Node *expr = (Node *) lfirst(lc);
3626 0 : Oid opr = lfirst_oid(lc2);
3627 :
3628 : /* See if the expression matches the index key */
3629 0 : if (!match_index_to_operand(expr, c, ind))
3630 0 : continue;
3631 :
3632 : /*
3633 : * The equality operator must be a member of the index
3634 : * opfamily, else it is not asserting the right kind of
3635 : * equality behavior for this index. We assume the caller
3636 : * determined it is an equality operator, so we don't need to
3637 : * check any more tightly than this.
3638 : */
3639 0 : if (!op_in_opfamily(opr, ind->opfamily[c]))
3640 0 : continue;
3641 :
3642 : /*
3643 : * XXX at some point we may need to check collations here too.
3644 : * For the moment we assume all collations reduce to the same
3645 : * notion of equality.
3646 : */
3647 :
3648 0 : matched = true; /* column is unique */
3649 0 : break;
3650 : }
3651 :
3652 110202 : if (!matched)
3653 110202 : break; /* no match; this index doesn't help us */
3654 : }
3655 :
3656 : /* Matched all key columns of this index? */
3657 176392 : if (c == ind->nkeycolumns)
3658 66190 : return true;
3659 : }
3660 :
3661 50192 : return false;
3662 : }
3663 :
3664 : /*
3665 : * indexcol_is_bool_constant_for_query
3666 : *
3667 : * If an index column is constrained to have a constant value by the query's
3668 : * WHERE conditions, then it's irrelevant for sort-order considerations.
3669 : * Usually that means we have a restriction clause WHERE indexcol = constant,
3670 : * which gets turned into an EquivalenceClass containing a constant, which
3671 : * is recognized as redundant by build_index_pathkeys(). But if the index
3672 : * column is a boolean variable (or expression), then we are not going to
3673 : * see WHERE indexcol = constant, because expression preprocessing will have
3674 : * simplified that to "WHERE indexcol" or "WHERE NOT indexcol". So we are not
3675 : * going to have a matching EquivalenceClass (unless the query also contains
3676 : * "ORDER BY indexcol"). To allow such cases to work the same as they would
3677 : * for non-boolean values, this function is provided to detect whether the
3678 : * specified index column matches a boolean restriction clause.
3679 : */
3680 : bool
3681 264204 : indexcol_is_bool_constant_for_query(PlannerInfo *root,
3682 : IndexOptInfo *index,
3683 : int indexcol)
3684 : {
3685 : ListCell *lc;
3686 :
3687 : /* If the index isn't boolean, we can't possibly get a match */
3688 264204 : if (!IsBooleanOpfamily(index->opfamily[indexcol]))
3689 263988 : return false;
3690 :
3691 : /* Check each restriction clause for the index's rel */
3692 240 : foreach(lc, index->rel->baserestrictinfo)
3693 : {
3694 96 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3695 :
3696 : /*
3697 : * As in match_clause_to_indexcol, never match pseudoconstants to
3698 : * indexes. (It might be semantically okay to do so here, but the
3699 : * odds of getting a match are negligible, so don't waste the cycles.)
3700 : */
3701 96 : if (rinfo->pseudoconstant)
3702 0 : continue;
3703 :
3704 : /* See if we can match the clause's expression to the index column */
3705 96 : if (match_boolean_index_clause(root, rinfo, indexcol, index))
3706 72 : return true;
3707 : }
3708 :
3709 144 : return false;
3710 : }
3711 :
3712 :
3713 : /****************************************************************************
3714 : * ---- ROUTINES TO CHECK OPERANDS ----
3715 : ****************************************************************************/
3716 :
3717 : /*
3718 : * match_index_to_operand()
3719 : * Generalized test for a match between an index's key
3720 : * and the operand on one side of a restriction or join clause.
3721 : *
3722 : * operand: the nodetree to be compared to the index
3723 : * indexcol: the column number of the index (counting from 0)
3724 : * index: the index of interest
3725 : *
3726 : * Note that we aren't interested in collations here; the caller must check
3727 : * for a collation match, if it's dealing with an operator where that matters.
3728 : *
3729 : * This is exported for use in selfuncs.c.
3730 : */
3731 : bool
3732 1932602 : match_index_to_operand(Node *operand,
3733 : int indexcol,
3734 : IndexOptInfo *index)
3735 : {
3736 : int indkey;
3737 :
3738 : /*
3739 : * Ignore any RelabelType node above the operand. This is needed to be
3740 : * able to apply indexscanning in binary-compatible-operator cases. Note:
3741 : * we can assume there is at most one RelabelType node;
3742 : * eval_const_expressions() will have simplified if more than one.
3743 : */
3744 1932602 : if (operand && IsA(operand, RelabelType))
3745 13340 : operand = (Node *) ((RelabelType *) operand)->arg;
3746 :
3747 1932602 : indkey = index->indexkeys[indexcol];
3748 1932602 : if (indkey != 0)
3749 : {
3750 : /*
3751 : * Simple index column; operand must be a matching Var.
3752 : */
3753 1929428 : if (operand && IsA(operand, Var) &&
3754 1476118 : index->rel->relid == ((Var *) operand)->varno &&
3755 1372676 : indkey == ((Var *) operand)->varattno)
3756 487316 : return true;
3757 : }
3758 : else
3759 : {
3760 : /*
3761 : * Index expression; find the correct expression. (This search could
3762 : * be avoided, at the cost of complicating all the callers of this
3763 : * routine; doesn't seem worth it.)
3764 : */
3765 : ListCell *indexpr_item;
3766 : int i;
3767 : Node *indexkey;
3768 :
3769 3174 : indexpr_item = list_head(index->indexprs);
3770 3174 : for (i = 0; i < indexcol; i++)
3771 : {
3772 0 : if (index->indexkeys[i] == 0)
3773 : {
3774 0 : if (indexpr_item == NULL)
3775 0 : elog(ERROR, "wrong number of index expressions");
3776 0 : indexpr_item = lnext(index->indexprs, indexpr_item);
3777 : }
3778 : }
3779 3174 : if (indexpr_item == NULL)
3780 0 : elog(ERROR, "wrong number of index expressions");
3781 3174 : indexkey = (Node *) lfirst(indexpr_item);
3782 :
3783 : /*
3784 : * Does it match the operand? Again, strip any relabeling.
3785 : */
3786 3174 : if (indexkey && IsA(indexkey, RelabelType))
3787 10 : indexkey = (Node *) ((RelabelType *) indexkey)->arg;
3788 :
3789 3174 : if (equal(indexkey, operand))
3790 1346 : return true;
3791 : }
3792 :
3793 1443940 : return false;
3794 : }
3795 :
3796 : /*
3797 : * is_pseudo_constant_for_index()
3798 : * Test whether the given expression can be used as an indexscan
3799 : * comparison value.
3800 : *
3801 : * An indexscan comparison value must not contain any volatile functions,
3802 : * and it can't contain any Vars of the index's own table. Vars of
3803 : * other tables are okay, though; in that case we'd be producing an
3804 : * indexqual usable in a parameterized indexscan. This is, therefore,
3805 : * a weaker condition than is_pseudo_constant_clause().
3806 : *
3807 : * This function is exported for use by planner support functions,
3808 : * which will have available the IndexOptInfo, but not any RestrictInfo
3809 : * infrastructure. It is making the same test made by functions above
3810 : * such as match_opclause_to_indexcol(), but those rely where possible
3811 : * on RestrictInfo information about variable membership.
3812 : *
3813 : * expr: the nodetree to be checked
3814 : * index: the index of interest
3815 : */
3816 : bool
3817 0 : is_pseudo_constant_for_index(PlannerInfo *root, Node *expr, IndexOptInfo *index)
3818 : {
3819 : /* pull_varnos is cheaper than volatility check, so do that first */
3820 0 : if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
3821 0 : return false; /* no good, contains Var of table */
3822 0 : if (contain_volatile_functions(expr))
3823 0 : return false; /* no good, volatile comparison value */
3824 0 : return true;
3825 : }
|