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