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