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-2025, 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_amop.h"
24 : #include "catalog/pg_operator.h"
25 : #include "catalog/pg_opfamily.h"
26 : #include "catalog/pg_type.h"
27 : #include "nodes/makefuncs.h"
28 : #include "nodes/nodeFuncs.h"
29 : #include "nodes/supportnodes.h"
30 : #include "optimizer/cost.h"
31 : #include "optimizer/optimizer.h"
32 : #include "optimizer/pathnode.h"
33 : #include "optimizer/paths.h"
34 : #include "optimizer/prep.h"
35 : #include "optimizer/restrictinfo.h"
36 : #include "utils/array.h"
37 : #include "utils/lsyscache.h"
38 : #include "utils/selfuncs.h"
39 : #include "utils/syscache.h"
40 :
41 :
42 : /* XXX see PartCollMatchesExprColl */
43 : #define IndexCollMatchesExprColl(idxcollation, exprcollation) \
44 : ((idxcollation) == InvalidOid || (idxcollation) == (exprcollation))
45 :
46 : /* Whether we are looking for plain indexscan, bitmap scan, or either */
47 : typedef enum
48 : {
49 : ST_INDEXSCAN, /* must support amgettuple */
50 : ST_BITMAPSCAN, /* must support amgetbitmap */
51 : ST_ANYSCAN, /* either is okay */
52 : } ScanTypeControl;
53 :
54 : /* Data structure for collecting qual clauses that match an index */
55 : typedef struct
56 : {
57 : bool nonempty; /* True if lists are not all empty */
58 : /* Lists of IndexClause nodes, one list per index column */
59 : List *indexclauses[INDEX_MAX_KEYS];
60 : } IndexClauseSet;
61 :
62 : /* Per-path data used within choose_bitmap_and() */
63 : typedef struct
64 : {
65 : Path *path; /* IndexPath, BitmapAndPath, or BitmapOrPath */
66 : List *quals; /* the WHERE clauses it uses */
67 : List *preds; /* predicates of its partial index(es) */
68 : Bitmapset *clauseids; /* quals+preds represented as a bitmapset */
69 : bool unclassifiable; /* has too many quals+preds to process? */
70 : } PathClauseUsage;
71 :
72 : /* Callback argument for ec_member_matches_indexcol */
73 : typedef struct
74 : {
75 : IndexOptInfo *index; /* index we're considering */
76 : int indexcol; /* index column we want to match to */
77 : } ec_member_matches_arg;
78 :
79 :
80 : static void consider_index_join_clauses(PlannerInfo *root, RelOptInfo *rel,
81 : IndexOptInfo *index,
82 : IndexClauseSet *rclauseset,
83 : IndexClauseSet *jclauseset,
84 : IndexClauseSet *eclauseset,
85 : List **bitindexpaths);
86 : static void consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
87 : IndexOptInfo *index,
88 : IndexClauseSet *rclauseset,
89 : IndexClauseSet *jclauseset,
90 : IndexClauseSet *eclauseset,
91 : List **bitindexpaths,
92 : List *indexjoinclauses,
93 : int considered_clauses,
94 : List **considered_relids);
95 : static void get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
96 : IndexOptInfo *index,
97 : IndexClauseSet *rclauseset,
98 : IndexClauseSet *jclauseset,
99 : IndexClauseSet *eclauseset,
100 : List **bitindexpaths,
101 : Relids relids,
102 : List **considered_relids);
103 : static bool eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
104 : List *indexjoinclauses);
105 : static void get_index_paths(PlannerInfo *root, RelOptInfo *rel,
106 : IndexOptInfo *index, IndexClauseSet *clauses,
107 : List **bitindexpaths);
108 : static List *build_index_paths(PlannerInfo *root, RelOptInfo *rel,
109 : IndexOptInfo *index, IndexClauseSet *clauses,
110 : bool useful_predicate,
111 : ScanTypeControl scantype,
112 : bool *skip_nonnative_saop);
113 : static List *build_paths_for_OR(PlannerInfo *root, RelOptInfo *rel,
114 : List *clauses, List *other_clauses);
115 : static List *generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
116 : List *clauses, List *other_clauses);
117 : static Path *choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel,
118 : List *paths);
119 : static int path_usage_comparator(const void *a, const void *b);
120 : static Cost bitmap_scan_cost_est(PlannerInfo *root, RelOptInfo *rel,
121 : Path *ipath);
122 : static Cost bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel,
123 : List *paths);
124 : static PathClauseUsage *classify_index_clause_usage(Path *path,
125 : List **clauselist);
126 : static void find_indexpath_quals(Path *bitmapqual, List **quals, List **preds);
127 : static int find_list_position(Node *node, List **nodelist);
128 : static bool check_index_only(RelOptInfo *rel, IndexOptInfo *index);
129 : static double get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids);
130 : static double adjust_rowcount_for_semijoins(PlannerInfo *root,
131 : Index cur_relid,
132 : Index outer_relid,
133 : double rowcount);
134 : static double approximate_joinrel_size(PlannerInfo *root, Relids relids);
135 : static void match_restriction_clauses_to_index(PlannerInfo *root,
136 : IndexOptInfo *index,
137 : IndexClauseSet *clauseset);
138 : static void match_join_clauses_to_index(PlannerInfo *root,
139 : RelOptInfo *rel, IndexOptInfo *index,
140 : IndexClauseSet *clauseset,
141 : List **joinorclauses);
142 : static void match_eclass_clauses_to_index(PlannerInfo *root,
143 : IndexOptInfo *index,
144 : IndexClauseSet *clauseset);
145 : static void match_clauses_to_index(PlannerInfo *root,
146 : List *clauses,
147 : IndexOptInfo *index,
148 : IndexClauseSet *clauseset);
149 : static void match_clause_to_index(PlannerInfo *root,
150 : RestrictInfo *rinfo,
151 : IndexOptInfo *index,
152 : IndexClauseSet *clauseset);
153 : static IndexClause *match_clause_to_indexcol(PlannerInfo *root,
154 : RestrictInfo *rinfo,
155 : int indexcol,
156 : IndexOptInfo *index);
157 : static bool IsBooleanOpfamily(Oid opfamily);
158 : static IndexClause *match_boolean_index_clause(PlannerInfo *root,
159 : RestrictInfo *rinfo,
160 : int indexcol, IndexOptInfo *index);
161 : static IndexClause *match_opclause_to_indexcol(PlannerInfo *root,
162 : RestrictInfo *rinfo,
163 : int indexcol,
164 : IndexOptInfo *index);
165 : static IndexClause *match_funcclause_to_indexcol(PlannerInfo *root,
166 : RestrictInfo *rinfo,
167 : int indexcol,
168 : IndexOptInfo *index);
169 : static IndexClause *get_index_clause_from_support(PlannerInfo *root,
170 : RestrictInfo *rinfo,
171 : Oid funcid,
172 : int indexarg,
173 : int indexcol,
174 : IndexOptInfo *index);
175 : static IndexClause *match_saopclause_to_indexcol(PlannerInfo *root,
176 : RestrictInfo *rinfo,
177 : int indexcol,
178 : IndexOptInfo *index);
179 : static IndexClause *match_rowcompare_to_indexcol(PlannerInfo *root,
180 : RestrictInfo *rinfo,
181 : int indexcol,
182 : IndexOptInfo *index);
183 : static IndexClause *match_orclause_to_indexcol(PlannerInfo *root,
184 : RestrictInfo *rinfo,
185 : int indexcol,
186 : IndexOptInfo *index);
187 : static IndexClause *expand_indexqual_rowcompare(PlannerInfo *root,
188 : RestrictInfo *rinfo,
189 : int indexcol,
190 : IndexOptInfo *index,
191 : Oid expr_op,
192 : bool var_on_left);
193 : static void match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
194 : List **orderby_clauses_p,
195 : List **clause_columns_p);
196 : static Expr *match_clause_to_ordering_op(IndexOptInfo *index,
197 : int indexcol, Expr *clause, Oid pk_opfamily);
198 : static bool ec_member_matches_indexcol(PlannerInfo *root, RelOptInfo *rel,
199 : EquivalenceClass *ec, EquivalenceMember *em,
200 : void *arg);
201 :
202 :
203 : /*
204 : * create_index_paths()
205 : * Generate all interesting index paths for the given relation.
206 : * Candidate paths are added to the rel's pathlist (using add_path).
207 : *
208 : * To be considered for an index scan, an index must match one or more
209 : * restriction clauses or join clauses from the query's qual condition,
210 : * or match the query's ORDER BY condition, or have a predicate that
211 : * matches the query's qual condition.
212 : *
213 : * There are two basic kinds of index scans. A "plain" index scan uses
214 : * only restriction clauses (possibly none at all) in its indexqual,
215 : * so it can be applied in any context. A "parameterized" index scan uses
216 : * join clauses (plus restriction clauses, if available) in its indexqual.
217 : * When joining such a scan to one of the relations supplying the other
218 : * variables used in its indexqual, the parameterized scan must appear as
219 : * the inner relation of a nestloop join; it can't be used on the outer side,
220 : * nor in a merge or hash join. In that context, values for the other rels'
221 : * attributes are available and fixed during any one scan of the indexpath.
222 : *
223 : * An IndexPath is generated and submitted to add_path() for each plain or
224 : * parameterized index scan this routine deems potentially interesting for
225 : * the current query.
226 : *
227 : * 'rel' is the relation for which we want to generate index paths
228 : *
229 : * Note: check_index_predicates() must have been run previously for this rel.
230 : *
231 : * Note: in cases involving LATERAL references in the relation's tlist, it's
232 : * possible that rel->lateral_relids is nonempty. Currently, we include
233 : * lateral_relids into the parameterization reported for each path, but don't
234 : * take it into account otherwise. The fact that any such rels *must* be
235 : * available as parameter sources perhaps should influence our choices of
236 : * index quals ... but for now, it doesn't seem worth troubling over.
237 : * In particular, comments below about "unparameterized" paths should be read
238 : * as meaning "unparameterized so far as the indexquals are concerned".
239 : */
240 : void
241 361884 : create_index_paths(PlannerInfo *root, RelOptInfo *rel)
242 : {
243 : List *indexpaths;
244 : List *bitindexpaths;
245 : List *bitjoinpaths;
246 : List *joinorclauses;
247 : IndexClauseSet rclauseset;
248 : IndexClauseSet jclauseset;
249 : IndexClauseSet eclauseset;
250 : ListCell *lc;
251 :
252 : /* Skip the whole mess if no indexes */
253 361884 : if (rel->indexlist == NIL)
254 67326 : return;
255 :
256 : /* Bitmap paths are collected and then dealt with at the end */
257 294558 : bitindexpaths = bitjoinpaths = joinorclauses = NIL;
258 :
259 : /* Examine each index in turn */
260 915320 : foreach(lc, rel->indexlist)
261 : {
262 620762 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
263 :
264 : /* Protect limited-size array in IndexClauseSets */
265 : Assert(index->nkeycolumns <= INDEX_MAX_KEYS);
266 :
267 : /*
268 : * Ignore partial indexes that do not match the query.
269 : * (generate_bitmap_or_paths() might be able to do something with
270 : * them, but that's of no concern here.)
271 : */
272 620762 : if (index->indpred != NIL && !index->predOK)
273 496 : continue;
274 :
275 : /*
276 : * Identify the restriction clauses that can match the index.
277 : */
278 21089044 : MemSet(&rclauseset, 0, sizeof(rclauseset));
279 620266 : match_restriction_clauses_to_index(root, index, &rclauseset);
280 :
281 : /*
282 : * Build index paths from the restriction clauses. These will be
283 : * non-parameterized paths. Plain paths go directly to add_path(),
284 : * bitmap paths are added to bitindexpaths to be handled below.
285 : */
286 620266 : get_index_paths(root, rel, index, &rclauseset,
287 : &bitindexpaths);
288 :
289 : /*
290 : * Identify the join clauses that can match the index. For the moment
291 : * we keep them separate from the restriction clauses. Note that this
292 : * step finds only "loose" join clauses that have not been merged into
293 : * EquivalenceClasses. Also, collect join OR clauses for later.
294 : */
295 21089044 : MemSet(&jclauseset, 0, sizeof(jclauseset));
296 620266 : match_join_clauses_to_index(root, rel, index,
297 : &jclauseset, &joinorclauses);
298 :
299 : /*
300 : * Look for EquivalenceClasses that can generate joinclauses matching
301 : * the index.
302 : */
303 21089044 : MemSet(&eclauseset, 0, sizeof(eclauseset));
304 620266 : match_eclass_clauses_to_index(root, index,
305 : &eclauseset);
306 :
307 : /*
308 : * If we found any plain or eclass join clauses, build parameterized
309 : * index paths using them.
310 : */
311 620266 : if (jclauseset.nonempty || eclauseset.nonempty)
312 114116 : consider_index_join_clauses(root, rel, index,
313 : &rclauseset,
314 : &jclauseset,
315 : &eclauseset,
316 : &bitjoinpaths);
317 : }
318 :
319 : /*
320 : * Generate BitmapOrPaths for any suitable OR-clauses present in the
321 : * restriction list. Add these to bitindexpaths.
322 : */
323 294558 : indexpaths = generate_bitmap_or_paths(root, rel,
324 : rel->baserestrictinfo, NIL);
325 294558 : bitindexpaths = list_concat(bitindexpaths, indexpaths);
326 :
327 : /*
328 : * Likewise, generate BitmapOrPaths for any suitable OR-clauses present in
329 : * the joinclause list. Add these to bitjoinpaths.
330 : */
331 294558 : indexpaths = generate_bitmap_or_paths(root, rel,
332 : joinorclauses, rel->baserestrictinfo);
333 294558 : bitjoinpaths = list_concat(bitjoinpaths, indexpaths);
334 :
335 : /*
336 : * If we found anything usable, generate a BitmapHeapPath for the most
337 : * promising combination of restriction bitmap index paths. Note there
338 : * will be only one such path no matter how many indexes exist. This
339 : * should be sufficient since there's basically only one figure of merit
340 : * (total cost) for such a path.
341 : */
342 294558 : if (bitindexpaths != NIL)
343 : {
344 : Path *bitmapqual;
345 : BitmapHeapPath *bpath;
346 :
347 180870 : bitmapqual = choose_bitmap_and(root, rel, bitindexpaths);
348 180870 : bpath = create_bitmap_heap_path(root, rel, bitmapqual,
349 : rel->lateral_relids, 1.0, 0);
350 180870 : add_path(rel, (Path *) bpath);
351 :
352 : /* create a partial bitmap heap path */
353 180870 : if (rel->consider_parallel && rel->lateral_relids == NULL)
354 128818 : create_partial_bitmap_paths(root, rel, bitmapqual);
355 : }
356 :
357 : /*
358 : * Likewise, if we found anything usable, generate BitmapHeapPaths for the
359 : * most promising combinations of join bitmap index paths. Our strategy
360 : * is to generate one such path for each distinct parameterization seen
361 : * among the available bitmap index paths. This may look pretty
362 : * expensive, but usually there won't be very many distinct
363 : * parameterizations. (This logic is quite similar to that in
364 : * consider_index_join_clauses, but we're working with whole paths not
365 : * individual clauses.)
366 : */
367 294558 : if (bitjoinpaths != NIL)
368 : {
369 : List *all_path_outers;
370 :
371 : /* Identify each distinct parameterization seen in bitjoinpaths */
372 105010 : all_path_outers = NIL;
373 229958 : foreach(lc, bitjoinpaths)
374 : {
375 124948 : Path *path = (Path *) lfirst(lc);
376 124948 : Relids required_outer = PATH_REQ_OUTER(path);
377 :
378 124948 : all_path_outers = list_append_unique(all_path_outers,
379 : required_outer);
380 : }
381 :
382 : /* Now, for each distinct parameterization set ... */
383 224214 : foreach(lc, all_path_outers)
384 : {
385 119204 : Relids max_outers = (Relids) lfirst(lc);
386 : List *this_path_set;
387 : Path *bitmapqual;
388 : Relids required_outer;
389 : double loop_count;
390 : BitmapHeapPath *bpath;
391 : ListCell *lcp;
392 :
393 : /* Identify all the bitmap join paths needing no more than that */
394 119204 : this_path_set = NIL;
395 282834 : foreach(lcp, bitjoinpaths)
396 : {
397 163630 : Path *path = (Path *) lfirst(lcp);
398 :
399 163630 : if (bms_is_subset(PATH_REQ_OUTER(path), max_outers))
400 131484 : this_path_set = lappend(this_path_set, path);
401 : }
402 :
403 : /*
404 : * Add in restriction bitmap paths, since they can be used
405 : * together with any join paths.
406 : */
407 119204 : this_path_set = list_concat(this_path_set, bitindexpaths);
408 :
409 : /* Select best AND combination for this parameterization */
410 119204 : bitmapqual = choose_bitmap_and(root, rel, this_path_set);
411 :
412 : /* And push that path into the mix */
413 119204 : required_outer = PATH_REQ_OUTER(bitmapqual);
414 119204 : loop_count = get_loop_count(root, rel->relid, required_outer);
415 119204 : bpath = create_bitmap_heap_path(root, rel, bitmapqual,
416 : required_outer, loop_count, 0);
417 119204 : add_path(rel, (Path *) bpath);
418 : }
419 : }
420 : }
421 :
422 : /*
423 : * consider_index_join_clauses
424 : * Given sets of join clauses for an index, decide which parameterized
425 : * index paths to build.
426 : *
427 : * Plain indexpaths are sent directly to add_path, while potential
428 : * bitmap indexpaths are added to *bitindexpaths for later processing.
429 : *
430 : * 'rel' is the index's heap relation
431 : * 'index' is the index for which we want to generate paths
432 : * 'rclauseset' is the collection of indexable restriction clauses
433 : * 'jclauseset' is the collection of indexable simple join clauses
434 : * 'eclauseset' is the collection of indexable clauses from EquivalenceClasses
435 : * '*bitindexpaths' is the list to add bitmap paths to
436 : */
437 : static void
438 114116 : consider_index_join_clauses(PlannerInfo *root, RelOptInfo *rel,
439 : IndexOptInfo *index,
440 : IndexClauseSet *rclauseset,
441 : IndexClauseSet *jclauseset,
442 : IndexClauseSet *eclauseset,
443 : List **bitindexpaths)
444 : {
445 114116 : int considered_clauses = 0;
446 114116 : List *considered_relids = NIL;
447 : int indexcol;
448 :
449 : /*
450 : * The strategy here is to identify every potentially useful set of outer
451 : * rels that can provide indexable join clauses. For each such set,
452 : * select all the join clauses available from those outer rels, add on all
453 : * the indexable restriction clauses, and generate plain and/or bitmap
454 : * index paths for that set of clauses. This is based on the assumption
455 : * that it's always better to apply a clause as an indexqual than as a
456 : * filter (qpqual); which is where an available clause would end up being
457 : * applied if we omit it from the indexquals.
458 : *
459 : * This looks expensive, but in most practical cases there won't be very
460 : * many distinct sets of outer rels to consider. As a safety valve when
461 : * that's not true, we use a heuristic: limit the number of outer rel sets
462 : * considered to a multiple of the number of clauses considered. (We'll
463 : * always consider using each individual join clause, though.)
464 : *
465 : * For simplicity in selecting relevant clauses, we represent each set of
466 : * outer rels as a maximum set of clause_relids --- that is, the indexed
467 : * relation itself is also included in the relids set. considered_relids
468 : * lists all relids sets we've already tried.
469 : */
470 281782 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
471 : {
472 : /* Consider each applicable simple join clause */
473 167666 : considered_clauses += list_length(jclauseset->indexclauses[indexcol]);
474 167666 : consider_index_join_outer_rels(root, rel, index,
475 : rclauseset, jclauseset, eclauseset,
476 : bitindexpaths,
477 : jclauseset->indexclauses[indexcol],
478 : considered_clauses,
479 : &considered_relids);
480 : /* Consider each applicable eclass join clause */
481 167666 : considered_clauses += list_length(eclauseset->indexclauses[indexcol]);
482 167666 : consider_index_join_outer_rels(root, rel, index,
483 : rclauseset, jclauseset, eclauseset,
484 : bitindexpaths,
485 : eclauseset->indexclauses[indexcol],
486 : considered_clauses,
487 : &considered_relids);
488 : }
489 114116 : }
490 :
491 : /*
492 : * consider_index_join_outer_rels
493 : * Generate parameterized paths based on clause relids in the clause list.
494 : *
495 : * Workhorse for consider_index_join_clauses; see notes therein for rationale.
496 : *
497 : * 'rel', 'index', 'rclauseset', 'jclauseset', 'eclauseset', and
498 : * 'bitindexpaths' as above
499 : * 'indexjoinclauses' is a list of IndexClauses for join clauses
500 : * 'considered_clauses' is the total number of clauses considered (so far)
501 : * '*considered_relids' is a list of all relids sets already considered
502 : */
503 : static void
504 335332 : consider_index_join_outer_rels(PlannerInfo *root, RelOptInfo *rel,
505 : IndexOptInfo *index,
506 : IndexClauseSet *rclauseset,
507 : IndexClauseSet *jclauseset,
508 : IndexClauseSet *eclauseset,
509 : List **bitindexpaths,
510 : List *indexjoinclauses,
511 : int considered_clauses,
512 : List **considered_relids)
513 : {
514 : ListCell *lc;
515 :
516 : /* Examine relids of each joinclause in the given list */
517 458656 : foreach(lc, indexjoinclauses)
518 : {
519 123324 : IndexClause *iclause = (IndexClause *) lfirst(lc);
520 123324 : Relids clause_relids = iclause->rinfo->clause_relids;
521 123324 : EquivalenceClass *parent_ec = iclause->rinfo->parent_ec;
522 : int num_considered_relids;
523 :
524 : /* If we already tried its relids set, no need to do so again */
525 123324 : if (list_member(*considered_relids, clause_relids))
526 1812 : continue;
527 :
528 : /*
529 : * Generate the union of this clause's relids set with each
530 : * previously-tried set. This ensures we try this clause along with
531 : * every interesting subset of previous clauses. However, to avoid
532 : * exponential growth of planning time when there are many clauses,
533 : * limit the number of relid sets accepted to 10 * considered_clauses.
534 : *
535 : * Note: get_join_index_paths appends entries to *considered_relids,
536 : * but we do not need to visit such newly-added entries within this
537 : * loop, so we don't use foreach() here. No real harm would be done
538 : * if we did visit them, since the subset check would reject them; but
539 : * it would waste some cycles.
540 : */
541 121512 : num_considered_relids = list_length(*considered_relids);
542 129076 : for (int pos = 0; pos < num_considered_relids; pos++)
543 : {
544 7564 : Relids oldrelids = (Relids) list_nth(*considered_relids, pos);
545 :
546 : /*
547 : * If either is a subset of the other, no new set is possible.
548 : * This isn't a complete test for redundancy, but it's easy and
549 : * cheap. get_join_index_paths will check more carefully if we
550 : * already generated the same relids set.
551 : */
552 7564 : if (bms_subset_compare(clause_relids, oldrelids) != BMS_DIFFERENT)
553 24 : continue;
554 :
555 : /*
556 : * If this clause was derived from an equivalence class, the
557 : * clause list may contain other clauses derived from the same
558 : * eclass. We should not consider that combining this clause with
559 : * one of those clauses generates a usefully different
560 : * parameterization; so skip if any clause derived from the same
561 : * eclass would already have been included when using oldrelids.
562 : */
563 14924 : if (parent_ec &&
564 7384 : eclass_already_used(parent_ec, oldrelids,
565 : indexjoinclauses))
566 4392 : continue;
567 :
568 : /*
569 : * If the number of relid sets considered exceeds our heuristic
570 : * limit, stop considering combinations of clauses. We'll still
571 : * consider the current clause alone, though (below this loop).
572 : */
573 3148 : if (list_length(*considered_relids) >= 10 * considered_clauses)
574 0 : break;
575 :
576 : /* OK, try the union set */
577 3148 : get_join_index_paths(root, rel, index,
578 : rclauseset, jclauseset, eclauseset,
579 : bitindexpaths,
580 : bms_union(clause_relids, oldrelids),
581 : considered_relids);
582 : }
583 :
584 : /* Also try this set of relids by itself */
585 121512 : get_join_index_paths(root, rel, index,
586 : rclauseset, jclauseset, eclauseset,
587 : bitindexpaths,
588 : clause_relids,
589 : considered_relids);
590 : }
591 335332 : }
592 :
593 : /*
594 : * get_join_index_paths
595 : * Generate index paths using clauses from the specified outer relations.
596 : * In addition to generating paths, relids is added to *considered_relids
597 : * if not already present.
598 : *
599 : * Workhorse for consider_index_join_clauses; see notes therein for rationale.
600 : *
601 : * 'rel', 'index', 'rclauseset', 'jclauseset', 'eclauseset',
602 : * 'bitindexpaths', 'considered_relids' as above
603 : * 'relids' is the current set of relids to consider (the target rel plus
604 : * one or more outer rels)
605 : */
606 : static void
607 124660 : get_join_index_paths(PlannerInfo *root, RelOptInfo *rel,
608 : IndexOptInfo *index,
609 : IndexClauseSet *rclauseset,
610 : IndexClauseSet *jclauseset,
611 : IndexClauseSet *eclauseset,
612 : List **bitindexpaths,
613 : Relids relids,
614 : List **considered_relids)
615 : {
616 : IndexClauseSet clauseset;
617 : int indexcol;
618 :
619 : /* If we already considered this relids set, don't repeat the work */
620 124660 : if (list_member(*considered_relids, relids))
621 0 : return;
622 :
623 : /* Identify indexclauses usable with this relids set */
624 4238440 : MemSet(&clauseset, 0, sizeof(clauseset));
625 :
626 312116 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
627 : {
628 : ListCell *lc;
629 :
630 : /* First find applicable simple join clauses */
631 218850 : foreach(lc, jclauseset->indexclauses[indexcol])
632 : {
633 31394 : IndexClause *iclause = (IndexClause *) lfirst(lc);
634 :
635 31394 : if (bms_is_subset(iclause->rinfo->clause_relids, relids))
636 31000 : clauseset.indexclauses[indexcol] =
637 31000 : lappend(clauseset.indexclauses[indexcol], iclause);
638 : }
639 :
640 : /*
641 : * Add applicable eclass join clauses. The clauses generated for each
642 : * column are redundant (cf generate_implied_equalities_for_column),
643 : * so we need at most one. This is the only exception to the general
644 : * rule of using all available index clauses.
645 : */
646 198668 : foreach(lc, eclauseset->indexclauses[indexcol])
647 : {
648 109808 : IndexClause *iclause = (IndexClause *) lfirst(lc);
649 :
650 109808 : if (bms_is_subset(iclause->rinfo->clause_relids, relids))
651 : {
652 98596 : clauseset.indexclauses[indexcol] =
653 98596 : lappend(clauseset.indexclauses[indexcol], iclause);
654 98596 : break;
655 : }
656 : }
657 :
658 : /* Add restriction clauses */
659 187456 : clauseset.indexclauses[indexcol] =
660 187456 : list_concat(clauseset.indexclauses[indexcol],
661 187456 : rclauseset->indexclauses[indexcol]);
662 :
663 187456 : if (clauseset.indexclauses[indexcol] != NIL)
664 152548 : clauseset.nonempty = true;
665 : }
666 :
667 : /* We should have found something, else caller passed silly relids */
668 : Assert(clauseset.nonempty);
669 :
670 : /* Build index path(s) using the collected set of clauses */
671 124660 : get_index_paths(root, rel, index, &clauseset, bitindexpaths);
672 :
673 : /*
674 : * Remember we considered paths for this set of relids.
675 : */
676 124660 : *considered_relids = lappend(*considered_relids, relids);
677 : }
678 :
679 : /*
680 : * eclass_already_used
681 : * True if any join clause usable with oldrelids was generated from
682 : * the specified equivalence class.
683 : */
684 : static bool
685 7384 : eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
686 : List *indexjoinclauses)
687 : {
688 : ListCell *lc;
689 :
690 10574 : foreach(lc, indexjoinclauses)
691 : {
692 7582 : IndexClause *iclause = (IndexClause *) lfirst(lc);
693 7582 : RestrictInfo *rinfo = iclause->rinfo;
694 :
695 15164 : if (rinfo->parent_ec == parent_ec &&
696 7582 : bms_is_subset(rinfo->clause_relids, oldrelids))
697 4392 : return true;
698 : }
699 2992 : return false;
700 : }
701 :
702 :
703 : /*
704 : * get_index_paths
705 : * Given an index and a set of index clauses for it, construct IndexPaths.
706 : *
707 : * Plain indexpaths are sent directly to add_path, while potential
708 : * bitmap indexpaths are added to *bitindexpaths for later processing.
709 : *
710 : * This is a fairly simple frontend to build_index_paths(). Its reason for
711 : * existence is mainly to handle ScalarArrayOpExpr quals properly. If the
712 : * index AM supports them natively, we should just include them in simple
713 : * index paths. If not, we should exclude them while building simple index
714 : * paths, and then make a separate attempt to include them in bitmap paths.
715 : */
716 : static void
717 744926 : get_index_paths(PlannerInfo *root, RelOptInfo *rel,
718 : IndexOptInfo *index, IndexClauseSet *clauses,
719 : List **bitindexpaths)
720 : {
721 : List *indexpaths;
722 744926 : bool skip_nonnative_saop = false;
723 : ListCell *lc;
724 :
725 : /*
726 : * Build simple index paths using the clauses. Allow ScalarArrayOpExpr
727 : * clauses only if the index AM supports them natively.
728 : */
729 744926 : indexpaths = build_index_paths(root, rel,
730 : index, clauses,
731 744926 : index->predOK,
732 : ST_ANYSCAN,
733 : &skip_nonnative_saop);
734 :
735 : /*
736 : * Submit all the ones that can form plain IndexScan plans to add_path. (A
737 : * plain IndexPath can represent either a plain IndexScan or an
738 : * IndexOnlyScan, but for our purposes here that distinction does not
739 : * matter. However, some of the indexes might support only bitmap scans,
740 : * and those we mustn't submit to add_path here.)
741 : *
742 : * Also, pick out the ones that are usable as bitmap scans. For that, we
743 : * must discard indexes that don't support bitmap scans, and we also are
744 : * only interested in paths that have some selectivity; we should discard
745 : * anything that was generated solely for ordering purposes.
746 : */
747 1187276 : foreach(lc, indexpaths)
748 : {
749 442350 : IndexPath *ipath = (IndexPath *) lfirst(lc);
750 :
751 442350 : if (index->amhasgettuple)
752 428950 : add_path(rel, (Path *) ipath);
753 :
754 442350 : if (index->amhasgetbitmap &&
755 442350 : (ipath->path.pathkeys == NIL ||
756 266960 : ipath->indexselectivity < 1.0))
757 327654 : *bitindexpaths = lappend(*bitindexpaths, ipath);
758 : }
759 :
760 : /*
761 : * If there were ScalarArrayOpExpr clauses that the index can't handle
762 : * natively, generate bitmap scan paths relying on executor-managed
763 : * ScalarArrayOpExpr.
764 : */
765 744926 : if (skip_nonnative_saop)
766 : {
767 32 : indexpaths = build_index_paths(root, rel,
768 : index, clauses,
769 : false,
770 : ST_BITMAPSCAN,
771 : NULL);
772 32 : *bitindexpaths = list_concat(*bitindexpaths, indexpaths);
773 : }
774 744926 : }
775 :
776 : /*
777 : * build_index_paths
778 : * Given an index and a set of index clauses for it, construct zero
779 : * or more IndexPaths. It also constructs zero or more partial IndexPaths.
780 : *
781 : * We return a list of paths because (1) this routine checks some cases
782 : * that should cause us to not generate any IndexPath, and (2) in some
783 : * cases we want to consider both a forward and a backward scan, so as
784 : * to obtain both sort orders. Note that the paths are just returned
785 : * to the caller and not immediately fed to add_path().
786 : *
787 : * At top level, useful_predicate should be exactly the index's predOK flag
788 : * (ie, true if it has a predicate that was proven from the restriction
789 : * clauses). When working on an arm of an OR clause, useful_predicate
790 : * should be true if the predicate required the current OR list to be proven.
791 : * Note that this routine should never be called at all if the index has an
792 : * unprovable predicate.
793 : *
794 : * scantype indicates whether we want to create plain indexscans, bitmap
795 : * indexscans, or both. When it's ST_BITMAPSCAN, we will not consider
796 : * index ordering while deciding if a Path is worth generating.
797 : *
798 : * If skip_nonnative_saop is non-NULL, we ignore ScalarArrayOpExpr clauses
799 : * unless the index AM supports them directly, and we set *skip_nonnative_saop
800 : * to true if we found any such clauses (caller must initialize the variable
801 : * to false). If it's NULL, we do not ignore ScalarArrayOpExpr clauses.
802 : *
803 : * 'rel' is the index's heap relation
804 : * 'index' is the index for which we want to generate paths
805 : * 'clauses' is the collection of indexable clauses (IndexClause nodes)
806 : * 'useful_predicate' indicates whether the index has a useful predicate
807 : * 'scantype' indicates whether we need plain or bitmap scan support
808 : * 'skip_nonnative_saop' indicates whether to accept SAOP if index AM doesn't
809 : */
810 : static List *
811 748138 : build_index_paths(PlannerInfo *root, RelOptInfo *rel,
812 : IndexOptInfo *index, IndexClauseSet *clauses,
813 : bool useful_predicate,
814 : ScanTypeControl scantype,
815 : bool *skip_nonnative_saop)
816 : {
817 748138 : List *result = NIL;
818 : IndexPath *ipath;
819 : List *index_clauses;
820 : Relids outer_relids;
821 : double loop_count;
822 : List *orderbyclauses;
823 : List *orderbyclausecols;
824 : List *index_pathkeys;
825 : List *useful_pathkeys;
826 : bool pathkeys_possibly_useful;
827 : bool index_is_ordered;
828 : bool index_only_scan;
829 : int indexcol;
830 :
831 : Assert(skip_nonnative_saop != NULL || scantype == ST_BITMAPSCAN);
832 :
833 : /*
834 : * Check that index supports the desired scan type(s)
835 : */
836 748138 : switch (scantype)
837 : {
838 0 : case ST_INDEXSCAN:
839 0 : if (!index->amhasgettuple)
840 0 : return NIL;
841 0 : break;
842 3212 : case ST_BITMAPSCAN:
843 3212 : if (!index->amhasgetbitmap)
844 0 : return NIL;
845 3212 : break;
846 744926 : case ST_ANYSCAN:
847 : /* either or both are OK */
848 744926 : break;
849 : }
850 :
851 : /*
852 : * 1. Combine the per-column IndexClause lists into an overall list.
853 : *
854 : * In the resulting list, clauses are ordered by index key, so that the
855 : * column numbers form a nondecreasing sequence. (This order is depended
856 : * on by btree and possibly other places.) The list can be empty, if the
857 : * index AM allows that.
858 : *
859 : * We also build a Relids set showing which outer rels are required by the
860 : * selected clauses. Any lateral_relids are included in that, but not
861 : * otherwise accounted for.
862 : */
863 748138 : index_clauses = NIL;
864 748138 : outer_relids = bms_copy(rel->lateral_relids);
865 2153680 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
866 : {
867 : ListCell *lc;
868 :
869 1788498 : foreach(lc, clauses->indexclauses[indexcol])
870 : {
871 382626 : IndexClause *iclause = (IndexClause *) lfirst(lc);
872 382626 : RestrictInfo *rinfo = iclause->rinfo;
873 :
874 382626 : if (skip_nonnative_saop && !index->amsearcharray &&
875 21822 : IsA(rinfo->clause, ScalarArrayOpExpr))
876 : {
877 : /*
878 : * Caller asked us to generate IndexPaths that omit any
879 : * ScalarArrayOpExpr clauses when the underlying index AM
880 : * lacks native support.
881 : *
882 : * We must omit this clause (and tell caller about it).
883 : */
884 32 : *skip_nonnative_saop = true;
885 32 : continue;
886 : }
887 :
888 : /* OK to include this clause */
889 382594 : index_clauses = lappend(index_clauses, iclause);
890 382594 : outer_relids = bms_add_members(outer_relids,
891 382594 : rinfo->clause_relids);
892 : }
893 :
894 : /*
895 : * If no clauses match the first index column, check for amoptionalkey
896 : * restriction. We can't generate a scan over an index with
897 : * amoptionalkey = false unless there's at least one index clause.
898 : * (When working on columns after the first, this test cannot fail. It
899 : * is always okay for columns after the first to not have any
900 : * clauses.)
901 : */
902 1405872 : if (index_clauses == NIL && !index->amoptionalkey)
903 330 : return NIL;
904 : }
905 :
906 : /* We do not want the index's rel itself listed in outer_relids */
907 747808 : outer_relids = bms_del_member(outer_relids, rel->relid);
908 :
909 : /* Compute loop_count for cost estimation purposes */
910 747808 : loop_count = get_loop_count(root, rel->relid, outer_relids);
911 :
912 : /*
913 : * 2. Compute pathkeys describing index's ordering, if any, then see how
914 : * many of them are actually useful for this query. This is not relevant
915 : * if we are only trying to build bitmap indexscans.
916 : */
917 1492404 : pathkeys_possibly_useful = (scantype != ST_BITMAPSCAN &&
918 744596 : has_useful_pathkeys(root, rel));
919 747808 : index_is_ordered = (index->sortopfamily != NULL);
920 747808 : if (index_is_ordered && pathkeys_possibly_useful)
921 : {
922 545974 : index_pathkeys = build_index_pathkeys(root, index,
923 : ForwardScanDirection);
924 545974 : useful_pathkeys = truncate_useless_pathkeys(root, rel,
925 : index_pathkeys);
926 545974 : orderbyclauses = NIL;
927 545974 : orderbyclausecols = NIL;
928 : }
929 201834 : else if (index->amcanorderbyop && pathkeys_possibly_useful)
930 : {
931 : /*
932 : * See if we can generate ordering operators for query_pathkeys or at
933 : * least some prefix thereof. Matching to just a prefix of the
934 : * query_pathkeys will allow an incremental sort to be considered on
935 : * the index's partially sorted results.
936 : */
937 1074 : match_pathkeys_to_index(index, root->query_pathkeys,
938 : &orderbyclauses,
939 : &orderbyclausecols);
940 1074 : if (list_length(root->query_pathkeys) == list_length(orderbyclauses))
941 468 : useful_pathkeys = root->query_pathkeys;
942 : else
943 606 : useful_pathkeys = list_copy_head(root->query_pathkeys,
944 : list_length(orderbyclauses));
945 : }
946 : else
947 : {
948 200760 : useful_pathkeys = NIL;
949 200760 : orderbyclauses = NIL;
950 200760 : orderbyclausecols = NIL;
951 : }
952 :
953 : /*
954 : * 3. Check if an index-only scan is possible. If we're not building
955 : * plain indexscans, this isn't relevant since bitmap scans don't support
956 : * index data retrieval anyway.
957 : */
958 1492404 : index_only_scan = (scantype != ST_BITMAPSCAN &&
959 744596 : check_index_only(rel, index));
960 :
961 : /*
962 : * 4. Generate an indexscan path if there are relevant restriction clauses
963 : * in the current clauses, OR the index ordering is potentially useful for
964 : * later merging or final output ordering, OR the index has a useful
965 : * predicate, OR an index-only scan is possible.
966 : */
967 747808 : if (index_clauses != NIL || useful_pathkeys != NIL || useful_predicate ||
968 : index_only_scan)
969 : {
970 445002 : ipath = create_index_path(root, index,
971 : index_clauses,
972 : orderbyclauses,
973 : orderbyclausecols,
974 : useful_pathkeys,
975 : ForwardScanDirection,
976 : index_only_scan,
977 : outer_relids,
978 : loop_count,
979 : false);
980 445002 : result = lappend(result, ipath);
981 :
982 : /*
983 : * If appropriate, consider parallel index scan. We don't allow
984 : * parallel index scan for bitmap index scans.
985 : */
986 445002 : if (index->amcanparallel &&
987 424214 : rel->consider_parallel && outer_relids == NULL &&
988 : scantype != ST_BITMAPSCAN)
989 : {
990 231802 : ipath = create_index_path(root, index,
991 : index_clauses,
992 : orderbyclauses,
993 : orderbyclausecols,
994 : useful_pathkeys,
995 : ForwardScanDirection,
996 : index_only_scan,
997 : outer_relids,
998 : loop_count,
999 : true);
1000 :
1001 : /*
1002 : * if, after costing the path, we find that it's not worth using
1003 : * parallel workers, just free it.
1004 : */
1005 231802 : if (ipath->path.parallel_workers > 0)
1006 9712 : add_partial_path(rel, (Path *) ipath);
1007 : else
1008 222090 : pfree(ipath);
1009 : }
1010 : }
1011 :
1012 : /*
1013 : * 5. If the index is ordered, a backwards scan might be interesting.
1014 : */
1015 747808 : if (index_is_ordered && pathkeys_possibly_useful)
1016 : {
1017 545974 : index_pathkeys = build_index_pathkeys(root, index,
1018 : BackwardScanDirection);
1019 545974 : useful_pathkeys = truncate_useless_pathkeys(root, rel,
1020 : index_pathkeys);
1021 545974 : if (useful_pathkeys != NIL)
1022 : {
1023 560 : ipath = create_index_path(root, index,
1024 : index_clauses,
1025 : NIL,
1026 : NIL,
1027 : useful_pathkeys,
1028 : BackwardScanDirection,
1029 : index_only_scan,
1030 : outer_relids,
1031 : loop_count,
1032 : false);
1033 560 : result = lappend(result, ipath);
1034 :
1035 : /* If appropriate, consider parallel index scan */
1036 560 : if (index->amcanparallel &&
1037 560 : rel->consider_parallel && outer_relids == NULL &&
1038 : scantype != ST_BITMAPSCAN)
1039 : {
1040 470 : ipath = create_index_path(root, index,
1041 : index_clauses,
1042 : NIL,
1043 : NIL,
1044 : useful_pathkeys,
1045 : BackwardScanDirection,
1046 : index_only_scan,
1047 : outer_relids,
1048 : loop_count,
1049 : true);
1050 :
1051 : /*
1052 : * if, after costing the path, we find that it's not worth
1053 : * using parallel workers, just free it.
1054 : */
1055 470 : if (ipath->path.parallel_workers > 0)
1056 168 : add_partial_path(rel, (Path *) ipath);
1057 : else
1058 302 : pfree(ipath);
1059 : }
1060 : }
1061 : }
1062 :
1063 747808 : return result;
1064 : }
1065 :
1066 : /*
1067 : * build_paths_for_OR
1068 : * Given a list of restriction clauses from one arm of an OR clause,
1069 : * construct all matching IndexPaths for the relation.
1070 : *
1071 : * Here we must scan all indexes of the relation, since a bitmap OR tree
1072 : * can use multiple indexes.
1073 : *
1074 : * The caller actually supplies two lists of restriction clauses: some
1075 : * "current" ones and some "other" ones. Both lists can be used freely
1076 : * to match keys of the index, but an index must use at least one of the
1077 : * "current" clauses to be considered usable. The motivation for this is
1078 : * examples like
1079 : * WHERE (x = 42) AND (... OR (y = 52 AND z = 77) OR ....)
1080 : * While we are considering the y/z subclause of the OR, we can use "x = 42"
1081 : * as one of the available index conditions; but we shouldn't match the
1082 : * subclause to any index on x alone, because such a Path would already have
1083 : * been generated at the upper level. So we could use an index on x,y,z
1084 : * or an index on x,y for the OR subclause, but not an index on just x.
1085 : * When dealing with a partial index, a match of the index predicate to
1086 : * one of the "current" clauses also makes the index usable.
1087 : *
1088 : * 'rel' is the relation for which we want to generate index paths
1089 : * 'clauses' is the current list of clauses (RestrictInfo nodes)
1090 : * 'other_clauses' is the list of additional upper-level clauses
1091 : */
1092 : static List *
1093 15262 : build_paths_for_OR(PlannerInfo *root, RelOptInfo *rel,
1094 : List *clauses, List *other_clauses)
1095 : {
1096 15262 : List *result = NIL;
1097 15262 : List *all_clauses = NIL; /* not computed till needed */
1098 : ListCell *lc;
1099 :
1100 53774 : foreach(lc, rel->indexlist)
1101 : {
1102 38512 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
1103 : IndexClauseSet clauseset;
1104 : List *indexpaths;
1105 : bool useful_predicate;
1106 :
1107 : /* Ignore index if it doesn't support bitmap scans */
1108 38512 : if (!index->amhasgetbitmap)
1109 35332 : continue;
1110 :
1111 : /*
1112 : * Ignore partial indexes that do not match the query. If a partial
1113 : * index is marked predOK then we know it's OK. Otherwise, we have to
1114 : * test whether the added clauses are sufficient to imply the
1115 : * predicate. If so, we can use the index in the current context.
1116 : *
1117 : * We set useful_predicate to true iff the predicate was proven using
1118 : * the current set of clauses. This is needed to prevent matching a
1119 : * predOK index to an arm of an OR, which would be a legal but
1120 : * pointlessly inefficient plan. (A better plan will be generated by
1121 : * just scanning the predOK index alone, no OR.)
1122 : */
1123 38512 : useful_predicate = false;
1124 38512 : if (index->indpred != NIL)
1125 : {
1126 168 : if (index->predOK)
1127 : {
1128 : /* Usable, but don't set useful_predicate */
1129 : }
1130 : else
1131 : {
1132 : /* Form all_clauses if not done already */
1133 144 : if (all_clauses == NIL)
1134 60 : all_clauses = list_concat_copy(clauses, other_clauses);
1135 :
1136 144 : if (!predicate_implied_by(index->indpred, all_clauses, false))
1137 96 : continue; /* can't use it at all */
1138 :
1139 48 : if (!predicate_implied_by(index->indpred, other_clauses, false))
1140 48 : useful_predicate = true;
1141 : }
1142 : }
1143 :
1144 : /*
1145 : * Identify the restriction clauses that can match the index.
1146 : */
1147 1306144 : MemSet(&clauseset, 0, sizeof(clauseset));
1148 38416 : match_clauses_to_index(root, clauses, index, &clauseset);
1149 :
1150 : /*
1151 : * If no matches so far, and the index predicate isn't useful, we
1152 : * don't want it.
1153 : */
1154 38416 : if (!clauseset.nonempty && !useful_predicate)
1155 35236 : continue;
1156 :
1157 : /*
1158 : * Add "other" restriction clauses to the clauseset.
1159 : */
1160 3180 : match_clauses_to_index(root, other_clauses, index, &clauseset);
1161 :
1162 : /*
1163 : * Construct paths if possible.
1164 : */
1165 3180 : indexpaths = build_index_paths(root, rel,
1166 : index, &clauseset,
1167 : useful_predicate,
1168 : ST_BITMAPSCAN,
1169 : NULL);
1170 3180 : result = list_concat(result, indexpaths);
1171 : }
1172 :
1173 15262 : return result;
1174 : }
1175 :
1176 : /*
1177 : * Utility structure used to group similar OR-clause arguments in
1178 : * group_similar_or_args(). It represents information about the OR-clause
1179 : * argument and its matching index key.
1180 : */
1181 : typedef struct
1182 : {
1183 : int indexnum; /* index of the matching index, or -1 if no
1184 : * matching index */
1185 : int colnum; /* index of the matching column, or -1 if no
1186 : * matching index */
1187 : Oid opno; /* OID of the OpClause operator, or InvalidOid
1188 : * if not an OpExpr */
1189 : Oid inputcollid; /* OID of the OpClause input collation */
1190 : int argindex; /* index of the clause in the list of
1191 : * arguments */
1192 : } OrArgIndexMatch;
1193 :
1194 : /*
1195 : * Comparison function for OrArgIndexMatch which provides sort order placing
1196 : * similar OR-clause arguments together.
1197 : */
1198 : static int
1199 8072 : or_arg_index_match_cmp(const void *a, const void *b)
1200 : {
1201 8072 : const OrArgIndexMatch *match_a = (const OrArgIndexMatch *) a;
1202 8072 : const OrArgIndexMatch *match_b = (const OrArgIndexMatch *) b;
1203 :
1204 8072 : if (match_a->indexnum < match_b->indexnum)
1205 662 : return -1;
1206 7410 : else if (match_a->indexnum > match_b->indexnum)
1207 4994 : return 1;
1208 :
1209 2416 : if (match_a->colnum < match_b->colnum)
1210 102 : return -1;
1211 2314 : else if (match_a->colnum > match_b->colnum)
1212 6 : return 1;
1213 :
1214 2308 : if (match_a->opno < match_b->opno)
1215 18 : return -1;
1216 2290 : else if (match_a->opno > match_b->opno)
1217 54 : return 1;
1218 :
1219 2236 : if (match_a->inputcollid < match_b->inputcollid)
1220 0 : return -1;
1221 2236 : else if (match_a->inputcollid > match_b->inputcollid)
1222 0 : return 1;
1223 :
1224 2236 : if (match_a->argindex < match_b->argindex)
1225 2176 : return -1;
1226 60 : else if (match_a->argindex > match_b->argindex)
1227 60 : return 1;
1228 :
1229 0 : return 0;
1230 : }
1231 :
1232 : /*
1233 : * group_similar_or_args
1234 : * Transform incoming OR-restrictinfo into a list of sub-restrictinfos,
1235 : * each of them containing a subset of similar OR-clause arguments from
1236 : * the source rinfo.
1237 : *
1238 : * Similar OR-clause arguments are of the form "indexkey op constant" having
1239 : * the same indexkey, operator, and collation. Constant may comprise either
1240 : * Const or Param. It may be employed later, during the
1241 : * match_clause_to_indexcol() to transform the whole OR-sub-rinfo to an SAOP
1242 : * clause.
1243 : *
1244 : * Returns the processed list of OR-clause arguments.
1245 : */
1246 : static List *
1247 13570 : group_similar_or_args(PlannerInfo *root, RelOptInfo *rel, RestrictInfo *rinfo)
1248 : {
1249 : int n;
1250 : int i;
1251 : int group_start;
1252 : OrArgIndexMatch *matches;
1253 13570 : bool matched = false;
1254 : ListCell *lc;
1255 : ListCell *lc2;
1256 : List *orargs;
1257 13570 : List *result = NIL;
1258 :
1259 : Assert(IsA(rinfo->orclause, BoolExpr));
1260 13570 : orargs = ((BoolExpr *) rinfo->orclause)->args;
1261 13570 : n = list_length(orargs);
1262 :
1263 : /*
1264 : * To avoid N^2 behavior, take utility pass along the list of OR-clause
1265 : * arguments. For each argument, fill the OrArgIndexMatch structure,
1266 : * which will be used to sort these arguments at the next step.
1267 : */
1268 13570 : i = -1;
1269 13570 : matches = (OrArgIndexMatch *) palloc(sizeof(OrArgIndexMatch) * n);
1270 45480 : foreach(lc, orargs)
1271 : {
1272 31910 : Node *arg = lfirst(lc);
1273 : RestrictInfo *argrinfo;
1274 : OpExpr *clause;
1275 : Oid opno;
1276 : Node *leftop,
1277 : *rightop;
1278 : Node *nonConstExpr;
1279 : int indexnum;
1280 : int colnum;
1281 :
1282 31910 : i++;
1283 31910 : matches[i].argindex = i;
1284 31910 : matches[i].indexnum = -1;
1285 31910 : matches[i].colnum = -1;
1286 31910 : matches[i].opno = InvalidOid;
1287 31910 : matches[i].inputcollid = InvalidOid;
1288 :
1289 31910 : if (!IsA(arg, RestrictInfo))
1290 3538 : continue;
1291 :
1292 28372 : argrinfo = castNode(RestrictInfo, arg);
1293 :
1294 : /* Only operator clauses can match */
1295 28372 : if (!IsA(argrinfo->clause, OpExpr))
1296 11016 : continue;
1297 :
1298 17356 : clause = (OpExpr *) argrinfo->clause;
1299 17356 : opno = clause->opno;
1300 :
1301 : /* Only binary operators can match */
1302 17356 : if (list_length(clause->args) != 2)
1303 0 : continue;
1304 :
1305 : /*
1306 : * Ignore any RelabelType node above the operands. This is needed to
1307 : * be able to apply indexscanning in binary-compatible-operator cases.
1308 : * Note: we can assume there is at most one RelabelType node;
1309 : * eval_const_expressions() will have simplified if more than one.
1310 : */
1311 17356 : leftop = get_leftop(clause);
1312 17356 : if (IsA(leftop, RelabelType))
1313 228 : leftop = (Node *) ((RelabelType *) leftop)->arg;
1314 :
1315 17356 : rightop = get_rightop(clause);
1316 17356 : if (IsA(rightop, RelabelType))
1317 696 : rightop = (Node *) ((RelabelType *) rightop)->arg;
1318 :
1319 : /*
1320 : * Check for clauses of the form: (indexkey operator constant) or
1321 : * (constant operator indexkey). But we don't know a particular index
1322 : * yet. First check for a constant, which must be Const or Param.
1323 : * That's cheaper than search for an index key among all indexes.
1324 : */
1325 17356 : if (IsA(leftop, Const) || IsA(leftop, Param))
1326 : {
1327 636 : opno = get_commutator(opno);
1328 :
1329 636 : if (!OidIsValid(opno))
1330 : {
1331 : /* commutator doesn't exist, we can't reverse the order */
1332 0 : continue;
1333 : }
1334 636 : nonConstExpr = rightop;
1335 : }
1336 16720 : else if (IsA(rightop, Const) || IsA(rightop, Param))
1337 : {
1338 11536 : nonConstExpr = leftop;
1339 : }
1340 : else
1341 : {
1342 5184 : continue;
1343 : }
1344 :
1345 : /*
1346 : * Match non-constant part to the index key. It's possible that a
1347 : * single non-constant part matches multiple index keys. It's OK, we
1348 : * just stop with first matching index key. Given that this choice is
1349 : * determined the same for every clause, we will group similar clauses
1350 : * together anyway.
1351 : */
1352 12172 : indexnum = 0;
1353 31012 : foreach(lc2, rel->indexlist)
1354 : {
1355 23798 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc2);
1356 :
1357 : /*
1358 : * Ignore index if it doesn't support bitmap scans or SAOP
1359 : * clauses.
1360 : */
1361 23798 : if (!index->amhasgetbitmap || !index->amsearcharray)
1362 54 : continue;
1363 :
1364 60518 : for (colnum = 0; colnum < index->nkeycolumns; colnum++)
1365 : {
1366 41732 : if (match_index_to_operand(nonConstExpr, colnum, index))
1367 : {
1368 4958 : matches[i].indexnum = indexnum;
1369 4958 : matches[i].colnum = colnum;
1370 4958 : matches[i].opno = opno;
1371 4958 : matches[i].inputcollid = clause->inputcollid;
1372 4958 : matched = true;
1373 4958 : break;
1374 : }
1375 : }
1376 :
1377 : /*
1378 : * Stop looping through the indexes, if we managed to match
1379 : * nonConstExpr to any index column.
1380 : */
1381 23744 : if (matches[i].indexnum >= 0)
1382 4958 : break;
1383 18786 : indexnum++;
1384 : }
1385 : }
1386 :
1387 : /*
1388 : * Fast-path check: if no clause is matching to the index column, we can
1389 : * just give up at this stage and return the clause list as-is.
1390 : */
1391 13570 : if (!matched)
1392 : {
1393 9400 : pfree(matches);
1394 9400 : return orargs;
1395 : }
1396 :
1397 : /* Sort clauses to make similar clauses go together */
1398 4170 : qsort(matches, n, sizeof(OrArgIndexMatch), or_arg_index_match_cmp);
1399 :
1400 : /*
1401 : * Group similar clauses into single sub-restrictinfo. Side effect: the
1402 : * resulting list of restrictions will be sorted by indexnum and colnum.
1403 : */
1404 4170 : group_start = 0;
1405 14500 : for (i = 1; i <= n; i++)
1406 : {
1407 : /* Check if it's a group boundary */
1408 10330 : if (group_start >= 0 &&
1409 6160 : (i == n ||
1410 6160 : matches[i].indexnum != matches[group_start].indexnum ||
1411 2272 : matches[i].colnum != matches[group_start].colnum ||
1412 2164 : matches[i].opno != matches[group_start].opno ||
1413 2104 : matches[i].inputcollid != matches[group_start].inputcollid ||
1414 2104 : matches[i].indexnum == -1))
1415 : {
1416 : /*
1417 : * One clause in group: add it "as is" to the upper-level OR.
1418 : */
1419 9892 : if (i - group_start == 1)
1420 : {
1421 9574 : result = lappend(result,
1422 : list_nth(orargs,
1423 9574 : matches[group_start].argindex));
1424 : }
1425 : else
1426 : {
1427 : /*
1428 : * Two or more clauses in a group: create a nested OR.
1429 : */
1430 318 : List *args = NIL;
1431 318 : List *rargs = NIL;
1432 : RestrictInfo *subrinfo;
1433 : int j;
1434 :
1435 : Assert(i - group_start >= 2);
1436 :
1437 : /* Construct the list of nested OR arguments */
1438 1074 : for (j = group_start; j < i; j++)
1439 : {
1440 756 : Node *arg = list_nth(orargs, matches[j].argindex);
1441 :
1442 756 : rargs = lappend(rargs, arg);
1443 756 : if (IsA(arg, RestrictInfo))
1444 756 : args = lappend(args, ((RestrictInfo *) arg)->clause);
1445 : else
1446 0 : args = lappend(args, arg);
1447 : }
1448 :
1449 : /* Construct the nested OR and wrap it with RestrictInfo */
1450 318 : subrinfo = make_plain_restrictinfo(root,
1451 : make_orclause(args),
1452 : make_orclause(rargs),
1453 318 : rinfo->is_pushed_down,
1454 318 : rinfo->has_clone,
1455 318 : rinfo->is_clone,
1456 318 : rinfo->pseudoconstant,
1457 : rinfo->security_level,
1458 : rinfo->required_relids,
1459 : rinfo->incompatible_relids,
1460 : rinfo->outer_relids);
1461 318 : result = lappend(result, subrinfo);
1462 : }
1463 :
1464 9892 : group_start = i;
1465 : }
1466 : }
1467 4170 : pfree(matches);
1468 4170 : return result;
1469 : }
1470 :
1471 : /*
1472 : * make_bitmap_paths_for_or_group
1473 : * Generate bitmap paths for a group of similar OR-clause arguments
1474 : * produced by group_similar_or_args().
1475 : *
1476 : * This function considers two cases: (1) matching a group of clauses to
1477 : * the index as a whole, and (2) matching the individual clauses one-by-one.
1478 : * (1) typically comprises an optimal solution. If not, (2) typically
1479 : * comprises fair alternative.
1480 : *
1481 : * Ideally, we could consider all arbitrary splits of arguments into
1482 : * subgroups, but that could lead to unacceptable computational complexity.
1483 : * This is why we only consider two cases of above.
1484 : */
1485 : static List *
1486 318 : make_bitmap_paths_for_or_group(PlannerInfo *root, RelOptInfo *rel,
1487 : RestrictInfo *ri, List *other_clauses)
1488 : {
1489 318 : List *jointlist = NIL;
1490 318 : List *splitlist = NIL;
1491 : ListCell *lc;
1492 : List *orargs;
1493 318 : List *args = ((BoolExpr *) ri->orclause)->args;
1494 318 : Cost jointcost = 0.0,
1495 318 : splitcost = 0.0;
1496 : Path *bitmapqual;
1497 : List *indlist;
1498 :
1499 : /*
1500 : * First, try to match the whole group to the one index.
1501 : */
1502 318 : orargs = list_make1(ri);
1503 318 : indlist = build_paths_for_OR(root, rel,
1504 : orargs,
1505 : other_clauses);
1506 318 : if (indlist != NIL)
1507 : {
1508 312 : bitmapqual = choose_bitmap_and(root, rel, indlist);
1509 312 : jointcost = bitmapqual->total_cost;
1510 312 : jointlist = list_make1(bitmapqual);
1511 : }
1512 :
1513 : /*
1514 : * If we manage to find a bitmap scan, which uses the group of OR-clause
1515 : * arguments as a whole, we can skip matching OR-clause arguments
1516 : * one-by-one as long as there are no other clauses, which can bring more
1517 : * efficiency to one-by-one case.
1518 : */
1519 318 : if (jointlist != NIL && other_clauses == NIL)
1520 42 : return jointlist;
1521 :
1522 : /*
1523 : * Also try to match all containing clauses one-by-one.
1524 : */
1525 930 : foreach(lc, args)
1526 : {
1527 660 : orargs = list_make1(lfirst(lc));
1528 :
1529 660 : indlist = build_paths_for_OR(root, rel,
1530 : orargs,
1531 : other_clauses);
1532 :
1533 660 : if (indlist == NIL)
1534 : {
1535 6 : splitlist = NIL;
1536 6 : break;
1537 : }
1538 :
1539 654 : bitmapqual = choose_bitmap_and(root, rel, indlist);
1540 654 : splitcost += bitmapqual->total_cost;
1541 654 : splitlist = lappend(splitlist, bitmapqual);
1542 : }
1543 :
1544 : /*
1545 : * Pick the best option.
1546 : */
1547 276 : if (splitlist == NIL)
1548 6 : return jointlist;
1549 270 : else if (jointlist == NIL)
1550 0 : return splitlist;
1551 : else
1552 270 : return (jointcost < splitcost) ? jointlist : splitlist;
1553 : }
1554 :
1555 :
1556 : /*
1557 : * generate_bitmap_or_paths
1558 : * Look through the list of clauses to find OR clauses, and generate
1559 : * a BitmapOrPath for each one we can handle that way. Return a list
1560 : * of the generated BitmapOrPaths.
1561 : *
1562 : * other_clauses is a list of additional clauses that can be assumed true
1563 : * for the purpose of generating indexquals, but are not to be searched for
1564 : * ORs. (See build_paths_for_OR() for motivation.)
1565 : */
1566 : static List *
1567 591472 : generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
1568 : List *clauses, List *other_clauses)
1569 : {
1570 591472 : List *result = NIL;
1571 : List *all_clauses;
1572 : ListCell *lc;
1573 :
1574 : /*
1575 : * We can use both the current and other clauses as context for
1576 : * build_paths_for_OR; no need to remove ORs from the lists.
1577 : */
1578 591472 : all_clauses = list_concat_copy(clauses, other_clauses);
1579 :
1580 932300 : foreach(lc, clauses)
1581 : {
1582 340828 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1583 : List *pathlist;
1584 : Path *bitmapqual;
1585 : ListCell *j;
1586 : List *groupedArgs;
1587 340828 : List *inner_other_clauses = NIL;
1588 :
1589 : /* Ignore RestrictInfos that aren't ORs */
1590 340828 : if (!restriction_is_or_clause(rinfo))
1591 327258 : continue;
1592 :
1593 : /*
1594 : * We must be able to match at least one index to each of the arms of
1595 : * the OR, else we can't use it.
1596 : */
1597 13570 : pathlist = NIL;
1598 :
1599 : /*
1600 : * Group the similar OR-clause arguments into dedicated RestrictInfos,
1601 : * because each of those RestrictInfos has a chance to match the index
1602 : * as a whole.
1603 : */
1604 13570 : groupedArgs = group_similar_or_args(root, rel, rinfo);
1605 :
1606 13570 : if (groupedArgs != ((BoolExpr *) rinfo->orclause)->args)
1607 : {
1608 : /*
1609 : * Some parts of the rinfo were probably grouped. In this case,
1610 : * we have a set of sub-rinfos that together are an exact
1611 : * duplicate of rinfo. Thus, we need to remove the rinfo from
1612 : * other clauses. match_clauses_to_index detects duplicated
1613 : * iclauses by comparing pointers to original rinfos that would be
1614 : * different. So, we must delete rinfo to avoid de-facto
1615 : * duplicated clauses in the index clauses list.
1616 : */
1617 4170 : inner_other_clauses = list_delete(list_copy(all_clauses), rinfo);
1618 : }
1619 :
1620 15796 : foreach(j, groupedArgs)
1621 : {
1622 14602 : Node *orarg = (Node *) lfirst(j);
1623 : List *indlist;
1624 :
1625 : /* OR arguments should be ANDs or sub-RestrictInfos */
1626 14602 : if (is_andclause(orarg))
1627 : {
1628 2356 : List *andargs = ((BoolExpr *) orarg)->args;
1629 :
1630 2356 : indlist = build_paths_for_OR(root, rel,
1631 : andargs,
1632 : all_clauses);
1633 :
1634 : /* Recurse in case there are sub-ORs */
1635 2356 : indlist = list_concat(indlist,
1636 2356 : generate_bitmap_or_paths(root, rel,
1637 : andargs,
1638 : all_clauses));
1639 : }
1640 12246 : else if (restriction_is_or_clause(castNode(RestrictInfo, orarg)))
1641 : {
1642 318 : RestrictInfo *ri = castNode(RestrictInfo, orarg);
1643 :
1644 : /*
1645 : * Generate bitmap paths for the group of similar OR-clause
1646 : * arguments.
1647 : */
1648 318 : indlist = make_bitmap_paths_for_or_group(root,
1649 : rel, ri,
1650 : inner_other_clauses);
1651 :
1652 318 : if (indlist == NIL)
1653 : {
1654 6 : pathlist = NIL;
1655 6 : break;
1656 : }
1657 : else
1658 : {
1659 312 : pathlist = list_concat(pathlist, indlist);
1660 312 : continue;
1661 : }
1662 : }
1663 : else
1664 : {
1665 11928 : RestrictInfo *ri = castNode(RestrictInfo, orarg);
1666 : List *orargs;
1667 :
1668 11928 : orargs = list_make1(ri);
1669 :
1670 11928 : indlist = build_paths_for_OR(root, rel,
1671 : orargs,
1672 : all_clauses);
1673 : }
1674 :
1675 : /*
1676 : * If nothing matched this arm, we can't do anything with this OR
1677 : * clause.
1678 : */
1679 14284 : if (indlist == NIL)
1680 : {
1681 12370 : pathlist = NIL;
1682 12370 : break;
1683 : }
1684 :
1685 : /*
1686 : * OK, pick the most promising AND combination, and add it to
1687 : * pathlist.
1688 : */
1689 1914 : bitmapqual = choose_bitmap_and(root, rel, indlist);
1690 1914 : pathlist = lappend(pathlist, bitmapqual);
1691 : }
1692 :
1693 13570 : if (inner_other_clauses != NIL)
1694 3802 : list_free(inner_other_clauses);
1695 :
1696 : /*
1697 : * If we have a match for every arm, then turn them into a
1698 : * BitmapOrPath, and add to result list.
1699 : */
1700 13570 : if (pathlist != NIL)
1701 : {
1702 1194 : bitmapqual = (Path *) create_bitmap_or_path(root, rel, pathlist);
1703 1194 : result = lappend(result, bitmapqual);
1704 : }
1705 : }
1706 :
1707 591472 : return result;
1708 : }
1709 :
1710 :
1711 : /*
1712 : * choose_bitmap_and
1713 : * Given a nonempty list of bitmap paths, AND them into one path.
1714 : *
1715 : * This is a nontrivial decision since we can legally use any subset of the
1716 : * given path set. We want to choose a good tradeoff between selectivity
1717 : * and cost of computing the bitmap.
1718 : *
1719 : * The result is either a single one of the inputs, or a BitmapAndPath
1720 : * combining multiple inputs.
1721 : */
1722 : static Path *
1723 302954 : choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel, List *paths)
1724 : {
1725 302954 : int npaths = list_length(paths);
1726 : PathClauseUsage **pathinfoarray;
1727 : PathClauseUsage *pathinfo;
1728 : List *clauselist;
1729 302954 : List *bestpaths = NIL;
1730 302954 : Cost bestcost = 0;
1731 : int i,
1732 : j;
1733 : ListCell *l;
1734 :
1735 : Assert(npaths > 0); /* else caller error */
1736 302954 : if (npaths == 1)
1737 236398 : return (Path *) linitial(paths); /* easy case */
1738 :
1739 : /*
1740 : * In theory we should consider every nonempty subset of the given paths.
1741 : * In practice that seems like overkill, given the crude nature of the
1742 : * estimates, not to mention the possible effects of higher-level AND and
1743 : * OR clauses. Moreover, it's completely impractical if there are a large
1744 : * number of paths, since the work would grow as O(2^N).
1745 : *
1746 : * As a heuristic, we first check for paths using exactly the same sets of
1747 : * WHERE clauses + index predicate conditions, and reject all but the
1748 : * cheapest-to-scan in any such group. This primarily gets rid of indexes
1749 : * that include the interesting columns but also irrelevant columns. (In
1750 : * situations where the DBA has gone overboard on creating variant
1751 : * indexes, this can make for a very large reduction in the number of
1752 : * paths considered further.)
1753 : *
1754 : * We then sort the surviving paths with the cheapest-to-scan first, and
1755 : * for each path, consider using that path alone as the basis for a bitmap
1756 : * scan. Then we consider bitmap AND scans formed from that path plus
1757 : * each subsequent (higher-cost) path, adding on a subsequent path if it
1758 : * results in a reduction in the estimated total scan cost. This means we
1759 : * consider about O(N^2) rather than O(2^N) path combinations, which is
1760 : * quite tolerable, especially given than N is usually reasonably small
1761 : * because of the prefiltering step. The cheapest of these is returned.
1762 : *
1763 : * We will only consider AND combinations in which no two indexes use the
1764 : * same WHERE clause. This is a bit of a kluge: it's needed because
1765 : * costsize.c and clausesel.c aren't very smart about redundant clauses.
1766 : * They will usually double-count the redundant clauses, producing a
1767 : * too-small selectivity that makes a redundant AND step look like it
1768 : * reduces the total cost. Perhaps someday that code will be smarter and
1769 : * we can remove this limitation. (But note that this also defends
1770 : * against flat-out duplicate input paths, which can happen because
1771 : * match_join_clauses_to_index will find the same OR join clauses that
1772 : * extract_restriction_or_clauses has pulled OR restriction clauses out
1773 : * of.)
1774 : *
1775 : * For the same reason, we reject AND combinations in which an index
1776 : * predicate clause duplicates another clause. Here we find it necessary
1777 : * to be even stricter: we'll reject a partial index if any of its
1778 : * predicate clauses are implied by the set of WHERE clauses and predicate
1779 : * clauses used so far. This covers cases such as a condition "x = 42"
1780 : * used with a plain index, followed by a clauseless scan of a partial
1781 : * index "WHERE x >= 40 AND x < 50". The partial index has been accepted
1782 : * only because "x = 42" was present, and so allowing it would partially
1783 : * double-count selectivity. (We could use predicate_implied_by on
1784 : * regular qual clauses too, to have a more intelligent, but much more
1785 : * expensive, check for redundancy --- but in most cases simple equality
1786 : * seems to suffice.)
1787 : */
1788 :
1789 : /*
1790 : * Extract clause usage info and detect any paths that use exactly the
1791 : * same set of clauses; keep only the cheapest-to-scan of any such groups.
1792 : * The surviving paths are put into an array for qsort'ing.
1793 : */
1794 : pathinfoarray = (PathClauseUsage **)
1795 66556 : palloc(npaths * sizeof(PathClauseUsage *));
1796 66556 : clauselist = NIL;
1797 66556 : npaths = 0;
1798 221592 : foreach(l, paths)
1799 : {
1800 155036 : Path *ipath = (Path *) lfirst(l);
1801 :
1802 155036 : pathinfo = classify_index_clause_usage(ipath, &clauselist);
1803 :
1804 : /* If it's unclassifiable, treat it as distinct from all others */
1805 155036 : if (pathinfo->unclassifiable)
1806 : {
1807 0 : pathinfoarray[npaths++] = pathinfo;
1808 0 : continue;
1809 : }
1810 :
1811 244060 : for (i = 0; i < npaths; i++)
1812 : {
1813 220152 : if (!pathinfoarray[i]->unclassifiable &&
1814 110076 : bms_equal(pathinfo->clauseids, pathinfoarray[i]->clauseids))
1815 21052 : break;
1816 : }
1817 155036 : if (i < npaths)
1818 : {
1819 : /* duplicate clauseids, keep the cheaper one */
1820 : Cost ncost;
1821 : Cost ocost;
1822 : Selectivity nselec;
1823 : Selectivity oselec;
1824 :
1825 21052 : cost_bitmap_tree_node(pathinfo->path, &ncost, &nselec);
1826 21052 : cost_bitmap_tree_node(pathinfoarray[i]->path, &ocost, &oselec);
1827 21052 : if (ncost < ocost)
1828 5106 : pathinfoarray[i] = pathinfo;
1829 : }
1830 : else
1831 : {
1832 : /* not duplicate clauseids, add to array */
1833 133984 : pathinfoarray[npaths++] = pathinfo;
1834 : }
1835 : }
1836 :
1837 : /* If only one surviving path, we're done */
1838 66556 : if (npaths == 1)
1839 12510 : return pathinfoarray[0]->path;
1840 :
1841 : /* Sort the surviving paths by index access cost */
1842 54046 : qsort(pathinfoarray, npaths, sizeof(PathClauseUsage *),
1843 : path_usage_comparator);
1844 :
1845 : /*
1846 : * For each surviving index, consider it as an "AND group leader", and see
1847 : * whether adding on any of the later indexes results in an AND path with
1848 : * cheaper total cost than before. Then take the cheapest AND group.
1849 : *
1850 : * Note: paths that are either clauseless or unclassifiable will have
1851 : * empty clauseids, so that they will not be rejected by the clauseids
1852 : * filter here, nor will they cause later paths to be rejected by it.
1853 : */
1854 175520 : for (i = 0; i < npaths; i++)
1855 : {
1856 : Cost costsofar;
1857 : List *qualsofar;
1858 : Bitmapset *clauseidsofar;
1859 :
1860 121474 : pathinfo = pathinfoarray[i];
1861 121474 : paths = list_make1(pathinfo->path);
1862 121474 : costsofar = bitmap_scan_cost_est(root, rel, pathinfo->path);
1863 121474 : qualsofar = list_concat_copy(pathinfo->quals, pathinfo->preds);
1864 121474 : clauseidsofar = bms_copy(pathinfo->clauseids);
1865 :
1866 202686 : for (j = i + 1; j < npaths; j++)
1867 : {
1868 : Cost newcost;
1869 :
1870 81212 : pathinfo = pathinfoarray[j];
1871 : /* Check for redundancy */
1872 81212 : if (bms_overlap(pathinfo->clauseids, clauseidsofar))
1873 37336 : continue; /* consider it redundant */
1874 43876 : if (pathinfo->preds)
1875 : {
1876 24 : bool redundant = false;
1877 :
1878 : /* we check each predicate clause separately */
1879 24 : foreach(l, pathinfo->preds)
1880 : {
1881 24 : Node *np = (Node *) lfirst(l);
1882 :
1883 24 : if (predicate_implied_by(list_make1(np), qualsofar, false))
1884 : {
1885 24 : redundant = true;
1886 24 : break; /* out of inner foreach loop */
1887 : }
1888 : }
1889 24 : if (redundant)
1890 24 : continue;
1891 : }
1892 : /* tentatively add new path to paths, so we can estimate cost */
1893 43852 : paths = lappend(paths, pathinfo->path);
1894 43852 : newcost = bitmap_and_cost_est(root, rel, paths);
1895 43852 : if (newcost < costsofar)
1896 : {
1897 : /* keep new path in paths, update subsidiary variables */
1898 190 : costsofar = newcost;
1899 190 : qualsofar = list_concat(qualsofar, pathinfo->quals);
1900 190 : qualsofar = list_concat(qualsofar, pathinfo->preds);
1901 190 : clauseidsofar = bms_add_members(clauseidsofar,
1902 190 : pathinfo->clauseids);
1903 : }
1904 : else
1905 : {
1906 : /* reject new path, remove it from paths list */
1907 43662 : paths = list_truncate(paths, list_length(paths) - 1);
1908 : }
1909 : }
1910 :
1911 : /* Keep the cheapest AND-group (or singleton) */
1912 121474 : if (i == 0 || costsofar < bestcost)
1913 : {
1914 56962 : bestpaths = paths;
1915 56962 : bestcost = costsofar;
1916 : }
1917 :
1918 : /* some easy cleanup (we don't try real hard though) */
1919 121474 : list_free(qualsofar);
1920 : }
1921 :
1922 54046 : if (list_length(bestpaths) == 1)
1923 53880 : return (Path *) linitial(bestpaths); /* no need for AND */
1924 166 : return (Path *) create_bitmap_and_path(root, rel, bestpaths);
1925 : }
1926 :
1927 : /* qsort comparator to sort in increasing index access cost order */
1928 : static int
1929 76766 : path_usage_comparator(const void *a, const void *b)
1930 : {
1931 76766 : PathClauseUsage *pa = *(PathClauseUsage *const *) a;
1932 76766 : PathClauseUsage *pb = *(PathClauseUsage *const *) b;
1933 : Cost acost;
1934 : Cost bcost;
1935 : Selectivity aselec;
1936 : Selectivity bselec;
1937 :
1938 76766 : cost_bitmap_tree_node(pa->path, &acost, &aselec);
1939 76766 : cost_bitmap_tree_node(pb->path, &bcost, &bselec);
1940 :
1941 : /*
1942 : * If costs are the same, sort by selectivity.
1943 : */
1944 76766 : if (acost < bcost)
1945 43318 : return -1;
1946 33448 : if (acost > bcost)
1947 22952 : return 1;
1948 :
1949 10496 : if (aselec < bselec)
1950 5540 : return -1;
1951 4956 : if (aselec > bselec)
1952 1086 : return 1;
1953 :
1954 3870 : return 0;
1955 : }
1956 :
1957 : /*
1958 : * Estimate the cost of actually executing a bitmap scan with a single
1959 : * index path (which could be a BitmapAnd or BitmapOr node).
1960 : */
1961 : static Cost
1962 165326 : bitmap_scan_cost_est(PlannerInfo *root, RelOptInfo *rel, Path *ipath)
1963 : {
1964 : BitmapHeapPath bpath;
1965 :
1966 : /* Set up a dummy BitmapHeapPath */
1967 165326 : bpath.path.type = T_BitmapHeapPath;
1968 165326 : bpath.path.pathtype = T_BitmapHeapScan;
1969 165326 : bpath.path.parent = rel;
1970 165326 : bpath.path.pathtarget = rel->reltarget;
1971 165326 : bpath.path.param_info = ipath->param_info;
1972 165326 : bpath.path.pathkeys = NIL;
1973 165326 : bpath.bitmapqual = ipath;
1974 :
1975 : /*
1976 : * Check the cost of temporary path without considering parallelism.
1977 : * Parallel bitmap heap path will be considered at later stage.
1978 : */
1979 165326 : bpath.path.parallel_workers = 0;
1980 :
1981 : /* Now we can do cost_bitmap_heap_scan */
1982 165326 : cost_bitmap_heap_scan(&bpath.path, root, rel,
1983 : bpath.path.param_info,
1984 : ipath,
1985 : get_loop_count(root, rel->relid,
1986 165326 : PATH_REQ_OUTER(ipath)));
1987 :
1988 165326 : return bpath.path.total_cost;
1989 : }
1990 :
1991 : /*
1992 : * Estimate the cost of actually executing a BitmapAnd scan with the given
1993 : * inputs.
1994 : */
1995 : static Cost
1996 43852 : bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel, List *paths)
1997 : {
1998 : BitmapAndPath *apath;
1999 :
2000 : /*
2001 : * Might as well build a real BitmapAndPath here, as the work is slightly
2002 : * too complicated to be worth repeating just to save one palloc.
2003 : */
2004 43852 : apath = create_bitmap_and_path(root, rel, paths);
2005 :
2006 43852 : return bitmap_scan_cost_est(root, rel, (Path *) apath);
2007 : }
2008 :
2009 :
2010 : /*
2011 : * classify_index_clause_usage
2012 : * Construct a PathClauseUsage struct describing the WHERE clauses and
2013 : * index predicate clauses used by the given indexscan path.
2014 : * We consider two clauses the same if they are equal().
2015 : *
2016 : * At some point we might want to migrate this info into the Path data
2017 : * structure proper, but for the moment it's only needed within
2018 : * choose_bitmap_and().
2019 : *
2020 : * *clauselist is used and expanded as needed to identify all the distinct
2021 : * clauses seen across successive calls. Caller must initialize it to NIL
2022 : * before first call of a set.
2023 : */
2024 : static PathClauseUsage *
2025 155036 : classify_index_clause_usage(Path *path, List **clauselist)
2026 : {
2027 : PathClauseUsage *result;
2028 : Bitmapset *clauseids;
2029 : ListCell *lc;
2030 :
2031 155036 : result = (PathClauseUsage *) palloc(sizeof(PathClauseUsage));
2032 155036 : result->path = path;
2033 :
2034 : /* Recursively find the quals and preds used by the path */
2035 155036 : result->quals = NIL;
2036 155036 : result->preds = NIL;
2037 155036 : find_indexpath_quals(path, &result->quals, &result->preds);
2038 :
2039 : /*
2040 : * Some machine-generated queries have outlandish numbers of qual clauses.
2041 : * To avoid getting into O(N^2) behavior even in this preliminary
2042 : * classification step, we want to limit the number of entries we can
2043 : * accumulate in *clauselist. Treat any path with more than 100 quals +
2044 : * preds as unclassifiable, which will cause calling code to consider it
2045 : * distinct from all other paths.
2046 : */
2047 155036 : if (list_length(result->quals) + list_length(result->preds) > 100)
2048 : {
2049 0 : result->clauseids = NULL;
2050 0 : result->unclassifiable = true;
2051 0 : return result;
2052 : }
2053 :
2054 : /* Build up a bitmapset representing the quals and preds */
2055 155036 : clauseids = NULL;
2056 356872 : foreach(lc, result->quals)
2057 : {
2058 201836 : Node *node = (Node *) lfirst(lc);
2059 :
2060 201836 : clauseids = bms_add_member(clauseids,
2061 : find_list_position(node, clauselist));
2062 : }
2063 155330 : foreach(lc, result->preds)
2064 : {
2065 294 : Node *node = (Node *) lfirst(lc);
2066 :
2067 294 : clauseids = bms_add_member(clauseids,
2068 : find_list_position(node, clauselist));
2069 : }
2070 155036 : result->clauseids = clauseids;
2071 155036 : result->unclassifiable = false;
2072 :
2073 155036 : return result;
2074 : }
2075 :
2076 :
2077 : /*
2078 : * find_indexpath_quals
2079 : *
2080 : * Given the Path structure for a plain or bitmap indexscan, extract lists
2081 : * of all the index clauses and index predicate conditions used in the Path.
2082 : * These are appended to the initial contents of *quals and *preds (hence
2083 : * caller should initialize those to NIL).
2084 : *
2085 : * Note we are not trying to produce an accurate representation of the AND/OR
2086 : * semantics of the Path, but just find out all the base conditions used.
2087 : *
2088 : * The result lists contain pointers to the expressions used in the Path,
2089 : * but all the list cells are freshly built, so it's safe to destructively
2090 : * modify the lists (eg, by concat'ing with other lists).
2091 : */
2092 : static void
2093 157772 : find_indexpath_quals(Path *bitmapqual, List **quals, List **preds)
2094 : {
2095 157772 : if (IsA(bitmapqual, BitmapAndPath))
2096 : {
2097 0 : BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
2098 : ListCell *l;
2099 :
2100 0 : foreach(l, apath->bitmapquals)
2101 : {
2102 0 : find_indexpath_quals((Path *) lfirst(l), quals, preds);
2103 : }
2104 : }
2105 157772 : else if (IsA(bitmapqual, BitmapOrPath))
2106 : {
2107 1458 : BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
2108 : ListCell *l;
2109 :
2110 4194 : foreach(l, opath->bitmapquals)
2111 : {
2112 2736 : find_indexpath_quals((Path *) lfirst(l), quals, preds);
2113 : }
2114 : }
2115 156314 : else if (IsA(bitmapqual, IndexPath))
2116 : {
2117 156314 : IndexPath *ipath = (IndexPath *) bitmapqual;
2118 : ListCell *l;
2119 :
2120 358150 : foreach(l, ipath->indexclauses)
2121 : {
2122 201836 : IndexClause *iclause = (IndexClause *) lfirst(l);
2123 :
2124 201836 : *quals = lappend(*quals, iclause->rinfo->clause);
2125 : }
2126 156314 : *preds = list_concat(*preds, ipath->indexinfo->indpred);
2127 : }
2128 : else
2129 0 : elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
2130 157772 : }
2131 :
2132 :
2133 : /*
2134 : * find_list_position
2135 : * Return the given node's position (counting from 0) in the given
2136 : * list of nodes. If it's not equal() to any existing list member,
2137 : * add it at the end, and return that position.
2138 : */
2139 : static int
2140 202130 : find_list_position(Node *node, List **nodelist)
2141 : {
2142 : int i;
2143 : ListCell *lc;
2144 :
2145 202130 : i = 0;
2146 321226 : foreach(lc, *nodelist)
2147 : {
2148 180484 : Node *oldnode = (Node *) lfirst(lc);
2149 :
2150 180484 : if (equal(node, oldnode))
2151 61388 : return i;
2152 119096 : i++;
2153 : }
2154 :
2155 140742 : *nodelist = lappend(*nodelist, node);
2156 :
2157 140742 : return i;
2158 : }
2159 :
2160 :
2161 : /*
2162 : * check_index_only
2163 : * Determine whether an index-only scan is possible for this index.
2164 : */
2165 : static bool
2166 744596 : check_index_only(RelOptInfo *rel, IndexOptInfo *index)
2167 : {
2168 : bool result;
2169 744596 : Bitmapset *attrs_used = NULL;
2170 744596 : Bitmapset *index_canreturn_attrs = NULL;
2171 : ListCell *lc;
2172 : int i;
2173 :
2174 : /* Index-only scans must be enabled */
2175 744596 : if (!enable_indexonlyscan)
2176 3686 : return false;
2177 :
2178 : /*
2179 : * Check that all needed attributes of the relation are available from the
2180 : * index.
2181 : */
2182 :
2183 : /*
2184 : * First, identify all the attributes needed for joins or final output.
2185 : * Note: we must look at rel's targetlist, not the attr_needed data,
2186 : * because attr_needed isn't computed for inheritance child rels.
2187 : */
2188 740910 : pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
2189 :
2190 : /*
2191 : * Add all the attributes used by restriction clauses; but consider only
2192 : * those clauses not implied by the index predicate, since ones that are
2193 : * so implied don't need to be checked explicitly in the plan.
2194 : *
2195 : * Note: attributes used only in index quals would not be needed at
2196 : * runtime either, if we are certain that the index is not lossy. However
2197 : * it'd be complicated to account for that accurately, and it doesn't
2198 : * matter in most cases, since we'd conclude that such attributes are
2199 : * available from the index anyway.
2200 : */
2201 1534332 : foreach(lc, index->indrestrictinfo)
2202 : {
2203 793422 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2204 :
2205 793422 : pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
2206 : }
2207 :
2208 : /*
2209 : * Construct a bitmapset of columns that the index can return back in an
2210 : * index-only scan.
2211 : */
2212 2137718 : for (i = 0; i < index->ncolumns; i++)
2213 : {
2214 1396808 : int attno = index->indexkeys[i];
2215 :
2216 : /*
2217 : * For the moment, we just ignore index expressions. It might be nice
2218 : * to do something with them, later.
2219 : */
2220 1396808 : if (attno == 0)
2221 2958 : continue;
2222 :
2223 1393850 : if (index->canreturn[i])
2224 : index_canreturn_attrs =
2225 1118602 : bms_add_member(index_canreturn_attrs,
2226 : attno - FirstLowInvalidHeapAttributeNumber);
2227 : }
2228 :
2229 : /* Do we have all the necessary attributes? */
2230 740910 : result = bms_is_subset(attrs_used, index_canreturn_attrs);
2231 :
2232 740910 : bms_free(attrs_used);
2233 740910 : bms_free(index_canreturn_attrs);
2234 :
2235 740910 : return result;
2236 : }
2237 :
2238 : /*
2239 : * get_loop_count
2240 : * Choose the loop count estimate to use for costing a parameterized path
2241 : * with the given set of outer relids.
2242 : *
2243 : * Since we produce parameterized paths before we've begun to generate join
2244 : * relations, it's impossible to predict exactly how many times a parameterized
2245 : * path will be iterated; we don't know the size of the relation that will be
2246 : * on the outside of the nestloop. However, we should try to account for
2247 : * multiple iterations somehow in costing the path. The heuristic embodied
2248 : * here is to use the rowcount of the smallest other base relation needed in
2249 : * the join clauses used by the path. (We could alternatively consider the
2250 : * largest one, but that seems too optimistic.) This is of course the right
2251 : * answer for single-other-relation cases, and it seems like a reasonable
2252 : * zero-order approximation for multiway-join cases.
2253 : *
2254 : * In addition, we check to see if the other side of each join clause is on
2255 : * the inside of some semijoin that the current relation is on the outside of.
2256 : * If so, the only way that a parameterized path could be used is if the
2257 : * semijoin RHS has been unique-ified, so we should use the number of unique
2258 : * RHS rows rather than using the relation's raw rowcount.
2259 : *
2260 : * Note: for this to work, allpaths.c must establish all baserel size
2261 : * estimates before it begins to compute paths, or at least before it
2262 : * calls create_index_paths().
2263 : */
2264 : static double
2265 1032338 : get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids)
2266 : {
2267 : double result;
2268 : int outer_relid;
2269 :
2270 : /* For a non-parameterized path, just return 1.0 quickly */
2271 1032338 : if (outer_relids == NULL)
2272 713148 : return 1.0;
2273 :
2274 319190 : result = 0.0;
2275 319190 : outer_relid = -1;
2276 648510 : while ((outer_relid = bms_next_member(outer_relids, outer_relid)) >= 0)
2277 : {
2278 : RelOptInfo *outer_rel;
2279 : double rowcount;
2280 :
2281 : /* Paranoia: ignore bogus relid indexes */
2282 329320 : if (outer_relid >= root->simple_rel_array_size)
2283 0 : continue;
2284 329320 : outer_rel = root->simple_rel_array[outer_relid];
2285 329320 : if (outer_rel == NULL)
2286 290 : continue;
2287 : Assert(outer_rel->relid == outer_relid); /* sanity check on array */
2288 :
2289 : /* Other relation could be proven empty, if so ignore */
2290 329030 : if (IS_DUMMY_REL(outer_rel))
2291 24 : continue;
2292 :
2293 : /* Otherwise, rel's rows estimate should be valid by now */
2294 : Assert(outer_rel->rows > 0);
2295 :
2296 : /* Check to see if rel is on the inside of any semijoins */
2297 329006 : rowcount = adjust_rowcount_for_semijoins(root,
2298 : cur_relid,
2299 : outer_relid,
2300 : outer_rel->rows);
2301 :
2302 : /* Remember smallest row count estimate among the outer rels */
2303 329006 : if (result == 0.0 || result > rowcount)
2304 324926 : result = rowcount;
2305 : }
2306 : /* Return 1.0 if we found no valid relations (shouldn't happen) */
2307 319190 : return (result > 0.0) ? result : 1.0;
2308 : }
2309 :
2310 : /*
2311 : * Check to see if outer_relid is on the inside of any semijoin that cur_relid
2312 : * is on the outside of. If so, replace rowcount with the estimated number of
2313 : * unique rows from the semijoin RHS (assuming that's smaller, which it might
2314 : * not be). The estimate is crude but it's the best we can do at this stage
2315 : * of the proceedings.
2316 : */
2317 : static double
2318 329006 : adjust_rowcount_for_semijoins(PlannerInfo *root,
2319 : Index cur_relid,
2320 : Index outer_relid,
2321 : double rowcount)
2322 : {
2323 : ListCell *lc;
2324 :
2325 520494 : foreach(lc, root->join_info_list)
2326 : {
2327 191488 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
2328 :
2329 197164 : if (sjinfo->jointype == JOIN_SEMI &&
2330 7786 : bms_is_member(cur_relid, sjinfo->syn_lefthand) &&
2331 2110 : bms_is_member(outer_relid, sjinfo->syn_righthand))
2332 : {
2333 : /* Estimate number of unique-ified rows */
2334 : double nraw;
2335 : double nunique;
2336 :
2337 824 : nraw = approximate_joinrel_size(root, sjinfo->syn_righthand);
2338 824 : nunique = estimate_num_groups(root,
2339 : sjinfo->semi_rhs_exprs,
2340 : nraw,
2341 : NULL,
2342 : NULL);
2343 824 : if (rowcount > nunique)
2344 350 : rowcount = nunique;
2345 : }
2346 : }
2347 329006 : return rowcount;
2348 : }
2349 :
2350 : /*
2351 : * Make an approximate estimate of the size of a joinrel.
2352 : *
2353 : * We don't have enough info at this point to get a good estimate, so we
2354 : * just multiply the base relation sizes together. Fortunately, this is
2355 : * the right answer anyway for the most common case with a single relation
2356 : * on the RHS of a semijoin. Also, estimate_num_groups() has only a weak
2357 : * dependency on its input_rows argument (it basically uses it as a clamp).
2358 : * So we might be able to get a fairly decent end result even with a severe
2359 : * overestimate of the RHS's raw size.
2360 : */
2361 : static double
2362 824 : approximate_joinrel_size(PlannerInfo *root, Relids relids)
2363 : {
2364 824 : double rowcount = 1.0;
2365 : int relid;
2366 :
2367 824 : relid = -1;
2368 1780 : while ((relid = bms_next_member(relids, relid)) >= 0)
2369 : {
2370 : RelOptInfo *rel;
2371 :
2372 : /* Paranoia: ignore bogus relid indexes */
2373 956 : if (relid >= root->simple_rel_array_size)
2374 0 : continue;
2375 956 : rel = root->simple_rel_array[relid];
2376 956 : if (rel == NULL)
2377 0 : continue;
2378 : Assert(rel->relid == relid); /* sanity check on array */
2379 :
2380 : /* Relation could be proven empty, if so ignore */
2381 956 : if (IS_DUMMY_REL(rel))
2382 0 : continue;
2383 :
2384 : /* Otherwise, rel's rows estimate should be valid by now */
2385 : Assert(rel->rows > 0);
2386 :
2387 : /* Accumulate product */
2388 956 : rowcount *= rel->rows;
2389 : }
2390 824 : return rowcount;
2391 : }
2392 :
2393 :
2394 : /****************************************************************************
2395 : * ---- ROUTINES TO CHECK QUERY CLAUSES ----
2396 : ****************************************************************************/
2397 :
2398 : /*
2399 : * match_restriction_clauses_to_index
2400 : * Identify restriction clauses for the rel that match the index.
2401 : * Matching clauses are added to *clauseset.
2402 : */
2403 : static void
2404 620266 : match_restriction_clauses_to_index(PlannerInfo *root,
2405 : IndexOptInfo *index,
2406 : IndexClauseSet *clauseset)
2407 : {
2408 : /* We can ignore clauses that are implied by the index predicate */
2409 620266 : match_clauses_to_index(root, index->indrestrictinfo, index, clauseset);
2410 620266 : }
2411 :
2412 : /*
2413 : * match_join_clauses_to_index
2414 : * Identify join clauses for the rel that match the index.
2415 : * Matching clauses are added to *clauseset.
2416 : * Also, add any potentially usable join OR clauses to *joinorclauses.
2417 : */
2418 : static void
2419 620266 : match_join_clauses_to_index(PlannerInfo *root,
2420 : RelOptInfo *rel, IndexOptInfo *index,
2421 : IndexClauseSet *clauseset,
2422 : List **joinorclauses)
2423 : {
2424 : ListCell *lc;
2425 :
2426 : /* Scan the rel's join clauses */
2427 838540 : foreach(lc, rel->joininfo)
2428 : {
2429 218274 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2430 :
2431 : /* Check if clause can be moved to this rel */
2432 218274 : if (!join_clause_is_movable_to(rinfo, rel))
2433 132612 : continue;
2434 :
2435 : /* Potentially usable, so see if it matches the index or is an OR */
2436 85662 : if (restriction_is_or_clause(rinfo))
2437 10782 : *joinorclauses = lappend(*joinorclauses, rinfo);
2438 : else
2439 74880 : match_clause_to_index(root, rinfo, index, clauseset);
2440 : }
2441 620266 : }
2442 :
2443 : /*
2444 : * match_eclass_clauses_to_index
2445 : * Identify EquivalenceClass join clauses for the rel that match the index.
2446 : * Matching clauses are added to *clauseset.
2447 : */
2448 : static void
2449 620266 : match_eclass_clauses_to_index(PlannerInfo *root, IndexOptInfo *index,
2450 : IndexClauseSet *clauseset)
2451 : {
2452 : int indexcol;
2453 :
2454 : /* No work if rel is not in any such ECs */
2455 620266 : if (!index->rel->has_eclass_joins)
2456 368958 : return;
2457 :
2458 658360 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2459 : {
2460 : ec_member_matches_arg arg;
2461 : List *clauses;
2462 :
2463 : /* Generate clauses, skipping any that join to lateral_referencers */
2464 407052 : arg.index = index;
2465 407052 : arg.indexcol = indexcol;
2466 407052 : clauses = generate_implied_equalities_for_column(root,
2467 : index->rel,
2468 : ec_member_matches_indexcol,
2469 : &arg,
2470 407052 : index->rel->lateral_referencers);
2471 :
2472 : /*
2473 : * We have to check whether the results actually do match the index,
2474 : * since for non-btree indexes the EC's equality operators might not
2475 : * be in the index opclass (cf ec_member_matches_indexcol).
2476 : */
2477 407052 : match_clauses_to_index(root, clauses, index, clauseset);
2478 : }
2479 : }
2480 :
2481 : /*
2482 : * match_clauses_to_index
2483 : * Perform match_clause_to_index() for each clause in a list.
2484 : * Matching clauses are added to *clauseset.
2485 : */
2486 : static void
2487 1068914 : match_clauses_to_index(PlannerInfo *root,
2488 : List *clauses,
2489 : IndexOptInfo *index,
2490 : IndexClauseSet *clauseset)
2491 : {
2492 : ListCell *lc;
2493 :
2494 1934770 : foreach(lc, clauses)
2495 : {
2496 865856 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
2497 :
2498 865856 : match_clause_to_index(root, rinfo, index, clauseset);
2499 : }
2500 1068914 : }
2501 :
2502 : /*
2503 : * match_clause_to_index
2504 : * Test whether a qual clause can be used with an index.
2505 : *
2506 : * If the clause is usable, add an IndexClause entry for it to the appropriate
2507 : * list in *clauseset. (*clauseset must be initialized to zeroes before first
2508 : * call.)
2509 : *
2510 : * Note: in some circumstances we may find the same RestrictInfos coming from
2511 : * multiple places. Defend against redundant outputs by refusing to add a
2512 : * clause twice (pointer equality should be a good enough check for this).
2513 : *
2514 : * Note: it's possible that a badly-defined index could have multiple matching
2515 : * columns. We always select the first match if so; this avoids scenarios
2516 : * wherein we get an inflated idea of the index's selectivity by using the
2517 : * same clause multiple times with different index columns.
2518 : */
2519 : static void
2520 940736 : match_clause_to_index(PlannerInfo *root,
2521 : RestrictInfo *rinfo,
2522 : IndexOptInfo *index,
2523 : IndexClauseSet *clauseset)
2524 : {
2525 : int indexcol;
2526 :
2527 : /*
2528 : * Never match pseudoconstants to indexes. (Normally a match could not
2529 : * happen anyway, since a pseudoconstant clause couldn't contain a Var,
2530 : * but what if someone builds an expression index on a constant? It's not
2531 : * totally unreasonable to do so with a partial index, either.)
2532 : */
2533 940736 : if (rinfo->pseudoconstant)
2534 12168 : return;
2535 :
2536 : /*
2537 : * If clause can't be used as an indexqual because it must wait till after
2538 : * some lower-security-level restriction clause, reject it.
2539 : */
2540 928568 : if (!restriction_is_securely_promotable(rinfo, index->rel))
2541 474 : return;
2542 :
2543 : /* OK, check each index key column for a match */
2544 2061660 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2545 : {
2546 : IndexClause *iclause;
2547 : ListCell *lc;
2548 :
2549 : /* Ignore duplicates */
2550 1553046 : foreach(lc, clauseset->indexclauses[indexcol])
2551 : {
2552 66838 : iclause = (IndexClause *) lfirst(lc);
2553 :
2554 66838 : if (iclause->rinfo == rinfo)
2555 0 : return;
2556 : }
2557 :
2558 : /* OK, try to match the clause to the index column */
2559 1486208 : iclause = match_clause_to_indexcol(root,
2560 : rinfo,
2561 : indexcol,
2562 : index);
2563 1486208 : if (iclause)
2564 : {
2565 : /* Success, so record it */
2566 352642 : clauseset->indexclauses[indexcol] =
2567 352642 : lappend(clauseset->indexclauses[indexcol], iclause);
2568 352642 : clauseset->nonempty = true;
2569 352642 : return;
2570 : }
2571 : }
2572 : }
2573 :
2574 : /*
2575 : * match_clause_to_indexcol()
2576 : * Determine whether a restriction clause matches a column of an index,
2577 : * and if so, build an IndexClause node describing the details.
2578 : *
2579 : * To match an index normally, an operator clause:
2580 : *
2581 : * (1) must be in the form (indexkey op const) or (const op indexkey);
2582 : * and
2583 : * (2) must contain an operator which is in the index's operator family
2584 : * for this column; and
2585 : * (3) must match the collation of the index, if collation is relevant.
2586 : *
2587 : * Our definition of "const" is exceedingly liberal: we allow anything that
2588 : * doesn't involve a volatile function or a Var of the index's relation
2589 : * except for a boolean OR expression input: due to a trade-off between the
2590 : * expected execution speedup and planning complexity, we limit or->saop
2591 : * transformation by obvious cases when an index scan can get a profit.
2592 : * In particular, Vars belonging to other relations of the query are
2593 : * accepted here, since a clause of that form can be used in a
2594 : * parameterized indexscan. It's the responsibility of higher code levels
2595 : * to manage restriction and join clauses appropriately.
2596 : *
2597 : * Note: we do need to check for Vars of the index's relation on the
2598 : * "const" side of the clause, since clauses like (a.f1 OP (b.f2 OP a.f3))
2599 : * are not processable by a parameterized indexscan on a.f1, whereas
2600 : * something like (a.f1 OP (b.f2 OP c.f3)) is.
2601 : *
2602 : * Presently, the executor can only deal with indexquals that have the
2603 : * indexkey on the left, so we can only use clauses that have the indexkey
2604 : * on the right if we can commute the clause to put the key on the left.
2605 : * We handle that by generating an IndexClause with the correctly-commuted
2606 : * opclause as a derived indexqual.
2607 : *
2608 : * If the index has a collation, the clause must have the same collation.
2609 : * For collation-less indexes, we assume it doesn't matter; this is
2610 : * necessary for cases like "hstore ? text", wherein hstore's operators
2611 : * don't care about collation but the clause will get marked with a
2612 : * collation anyway because of the text argument. (This logic is
2613 : * embodied in the macro IndexCollMatchesExprColl.)
2614 : *
2615 : * It is also possible to match RowCompareExpr clauses to indexes (but
2616 : * currently, only btree indexes handle this).
2617 : *
2618 : * It is also possible to match ScalarArrayOpExpr clauses to indexes, when
2619 : * the clause is of the form "indexkey op ANY (arrayconst)".
2620 : *
2621 : * It is also possible to match a list of OR clauses if it might be
2622 : * transformed into a single ScalarArrayOpExpr clause. On success,
2623 : * the returning index clause will contain a transformed clause.
2624 : *
2625 : * For boolean indexes, it is also possible to match the clause directly
2626 : * to the indexkey; or perhaps the clause is (NOT indexkey).
2627 : *
2628 : * And, last but not least, some operators and functions can be processed
2629 : * to derive (typically lossy) indexquals from a clause that isn't in
2630 : * itself indexable. If we see that any operand of an OpExpr or FuncExpr
2631 : * matches the index key, and the function has a planner support function
2632 : * attached to it, we'll invoke the support function to see if such an
2633 : * indexqual can be built.
2634 : *
2635 : * 'rinfo' is the clause to be tested (as a RestrictInfo node).
2636 : * 'indexcol' is a column number of 'index' (counting from 0).
2637 : * 'index' is the index of interest.
2638 : *
2639 : * Returns an IndexClause if the clause can be used with this index key,
2640 : * or NULL if not.
2641 : *
2642 : * NOTE: returns NULL if clause is an OR or AND clause; it is the
2643 : * responsibility of higher-level routines to cope with those.
2644 : */
2645 : static IndexClause *
2646 1486208 : match_clause_to_indexcol(PlannerInfo *root,
2647 : RestrictInfo *rinfo,
2648 : int indexcol,
2649 : IndexOptInfo *index)
2650 : {
2651 : IndexClause *iclause;
2652 1486208 : Expr *clause = rinfo->clause;
2653 : Oid opfamily;
2654 :
2655 : Assert(indexcol < index->nkeycolumns);
2656 :
2657 : /*
2658 : * Historically this code has coped with NULL clauses. That's probably
2659 : * not possible anymore, but we might as well continue to cope.
2660 : */
2661 1486208 : if (clause == NULL)
2662 0 : return NULL;
2663 :
2664 : /* First check for boolean-index cases. */
2665 1486208 : opfamily = index->opfamily[indexcol];
2666 1486208 : if (IsBooleanOpfamily(opfamily))
2667 : {
2668 338 : iclause = match_boolean_index_clause(root, rinfo, indexcol, index);
2669 338 : if (iclause)
2670 240 : return iclause;
2671 : }
2672 :
2673 : /*
2674 : * Clause must be an opclause, funcclause, ScalarArrayOpExpr,
2675 : * RowCompareExpr, or OR-clause that could be converted to SAOP. Or, if
2676 : * the index supports it, we can handle IS NULL/NOT NULL clauses.
2677 : */
2678 1485968 : if (IsA(clause, OpExpr))
2679 : {
2680 1241872 : return match_opclause_to_indexcol(root, rinfo, indexcol, index);
2681 : }
2682 244096 : else if (IsA(clause, FuncExpr))
2683 : {
2684 28044 : return match_funcclause_to_indexcol(root, rinfo, indexcol, index);
2685 : }
2686 216052 : else if (IsA(clause, ScalarArrayOpExpr))
2687 : {
2688 70100 : return match_saopclause_to_indexcol(root, rinfo, indexcol, index);
2689 : }
2690 145952 : else if (IsA(clause, RowCompareExpr))
2691 : {
2692 432 : return match_rowcompare_to_indexcol(root, rinfo, indexcol, index);
2693 : }
2694 145520 : else if (restriction_is_or_clause(rinfo))
2695 : {
2696 21296 : return match_orclause_to_indexcol(root, rinfo, indexcol, index);
2697 : }
2698 124224 : else if (index->amsearchnulls && IsA(clause, NullTest))
2699 : {
2700 15588 : NullTest *nt = (NullTest *) clause;
2701 :
2702 31176 : if (!nt->argisrow &&
2703 15588 : match_index_to_operand((Node *) nt->arg, indexcol, index))
2704 : {
2705 1202 : iclause = makeNode(IndexClause);
2706 1202 : iclause->rinfo = rinfo;
2707 1202 : iclause->indexquals = list_make1(rinfo);
2708 1202 : iclause->lossy = false;
2709 1202 : iclause->indexcol = indexcol;
2710 1202 : iclause->indexcols = NIL;
2711 1202 : return iclause;
2712 : }
2713 : }
2714 :
2715 123022 : return NULL;
2716 : }
2717 :
2718 : /*
2719 : * IsBooleanOpfamily
2720 : * Detect whether an opfamily supports boolean equality as an operator.
2721 : *
2722 : * If the opfamily OID is in the range of built-in objects, we can rely
2723 : * on hard-wired knowledge of which built-in opfamilies support this.
2724 : * For extension opfamilies, there's no choice but to do a catcache lookup.
2725 : */
2726 : static bool
2727 2011440 : IsBooleanOpfamily(Oid opfamily)
2728 : {
2729 2011440 : if (opfamily < FirstNormalObjectId)
2730 2008234 : return IsBuiltinBooleanOpfamily(opfamily);
2731 : else
2732 3206 : return op_in_opfamily(BooleanEqualOperator, opfamily);
2733 : }
2734 :
2735 : /*
2736 : * match_boolean_index_clause
2737 : * Recognize restriction clauses that can be matched to a boolean index.
2738 : *
2739 : * The idea here is that, for an index on a boolean column that supports the
2740 : * BooleanEqualOperator, we can transform a plain reference to the indexkey
2741 : * into "indexkey = true", or "NOT indexkey" into "indexkey = false", etc,
2742 : * so as to make the expression indexable using the index's "=" operator.
2743 : * Since Postgres 8.1, we must do this because constant simplification does
2744 : * the reverse transformation; without this code there'd be no way to use
2745 : * such an index at all.
2746 : *
2747 : * This should be called only when IsBooleanOpfamily() recognizes the
2748 : * index's operator family. We check to see if the clause matches the
2749 : * index's key, and if so, build a suitable IndexClause.
2750 : */
2751 : static IndexClause *
2752 1346 : match_boolean_index_clause(PlannerInfo *root,
2753 : RestrictInfo *rinfo,
2754 : int indexcol,
2755 : IndexOptInfo *index)
2756 : {
2757 1346 : Node *clause = (Node *) rinfo->clause;
2758 1346 : Expr *op = NULL;
2759 :
2760 : /* Direct match? */
2761 1346 : if (match_index_to_operand(clause, indexcol, index))
2762 : {
2763 : /* convert to indexkey = TRUE */
2764 94 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2765 : (Expr *) clause,
2766 94 : (Expr *) makeBoolConst(true, false),
2767 : InvalidOid, InvalidOid);
2768 : }
2769 : /* NOT clause? */
2770 1252 : else if (is_notclause(clause))
2771 : {
2772 1082 : Node *arg = (Node *) get_notclausearg((Expr *) clause);
2773 :
2774 1082 : if (match_index_to_operand(arg, indexcol, index))
2775 : {
2776 : /* convert to indexkey = FALSE */
2777 1082 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2778 : (Expr *) arg,
2779 1082 : (Expr *) makeBoolConst(false, false),
2780 : InvalidOid, InvalidOid);
2781 : }
2782 : }
2783 :
2784 : /*
2785 : * Since we only consider clauses at top level of WHERE, we can convert
2786 : * indexkey IS TRUE and indexkey IS FALSE to index searches as well. The
2787 : * different meaning for NULL isn't important.
2788 : */
2789 170 : else if (clause && IsA(clause, BooleanTest))
2790 : {
2791 36 : BooleanTest *btest = (BooleanTest *) clause;
2792 36 : Node *arg = (Node *) btest->arg;
2793 :
2794 54 : if (btest->booltesttype == IS_TRUE &&
2795 18 : match_index_to_operand(arg, indexcol, index))
2796 : {
2797 : /* convert to indexkey = TRUE */
2798 18 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2799 : (Expr *) arg,
2800 18 : (Expr *) makeBoolConst(true, false),
2801 : InvalidOid, InvalidOid);
2802 : }
2803 36 : else if (btest->booltesttype == IS_FALSE &&
2804 18 : match_index_to_operand(arg, indexcol, index))
2805 : {
2806 : /* convert to indexkey = FALSE */
2807 18 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2808 : (Expr *) arg,
2809 18 : (Expr *) makeBoolConst(false, false),
2810 : InvalidOid, InvalidOid);
2811 : }
2812 : }
2813 :
2814 : /*
2815 : * If we successfully made an operator clause from the given qual, we must
2816 : * wrap it in an IndexClause. It's not lossy.
2817 : */
2818 1346 : if (op)
2819 : {
2820 1212 : IndexClause *iclause = makeNode(IndexClause);
2821 :
2822 1212 : iclause->rinfo = rinfo;
2823 1212 : iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
2824 1212 : iclause->lossy = false;
2825 1212 : iclause->indexcol = indexcol;
2826 1212 : iclause->indexcols = NIL;
2827 1212 : return iclause;
2828 : }
2829 :
2830 134 : return NULL;
2831 : }
2832 :
2833 : /*
2834 : * match_opclause_to_indexcol()
2835 : * Handles the OpExpr case for match_clause_to_indexcol(),
2836 : * which see for comments.
2837 : */
2838 : static IndexClause *
2839 1241872 : match_opclause_to_indexcol(PlannerInfo *root,
2840 : RestrictInfo *rinfo,
2841 : int indexcol,
2842 : IndexOptInfo *index)
2843 : {
2844 : IndexClause *iclause;
2845 1241872 : OpExpr *clause = (OpExpr *) rinfo->clause;
2846 : Node *leftop,
2847 : *rightop;
2848 : Oid expr_op;
2849 : Oid expr_coll;
2850 : Index index_relid;
2851 : Oid opfamily;
2852 : Oid idxcollation;
2853 :
2854 : /*
2855 : * Only binary operators need apply. (In theory, a planner support
2856 : * function could do something with a unary operator, but it seems
2857 : * unlikely to be worth the cycles to check.)
2858 : */
2859 1241872 : if (list_length(clause->args) != 2)
2860 0 : return NULL;
2861 :
2862 1241872 : leftop = (Node *) linitial(clause->args);
2863 1241872 : rightop = (Node *) lsecond(clause->args);
2864 1241872 : expr_op = clause->opno;
2865 1241872 : expr_coll = clause->inputcollid;
2866 :
2867 1241872 : index_relid = index->rel->relid;
2868 1241872 : opfamily = index->opfamily[indexcol];
2869 1241872 : idxcollation = index->indexcollations[indexcol];
2870 :
2871 : /*
2872 : * Check for clauses of the form: (indexkey operator constant) or
2873 : * (constant operator indexkey). See match_clause_to_indexcol's notes
2874 : * about const-ness.
2875 : *
2876 : * Note that we don't ask the support function about clauses that don't
2877 : * have one of these forms. Again, in principle it might be possible to
2878 : * do something, but it seems unlikely to be worth the cycles to check.
2879 : */
2880 1241872 : if (match_index_to_operand(leftop, indexcol, index) &&
2881 301772 : !bms_is_member(index_relid, rinfo->right_relids) &&
2882 301622 : !contain_volatile_functions(rightop))
2883 : {
2884 596998 : if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
2885 295376 : op_in_opfamily(expr_op, opfamily))
2886 : {
2887 290424 : iclause = makeNode(IndexClause);
2888 290424 : iclause->rinfo = rinfo;
2889 290424 : iclause->indexquals = list_make1(rinfo);
2890 290424 : iclause->lossy = false;
2891 290424 : iclause->indexcol = indexcol;
2892 290424 : iclause->indexcols = NIL;
2893 290424 : return iclause;
2894 : }
2895 :
2896 : /*
2897 : * If we didn't find a member of the index's opfamily, try the support
2898 : * function for the operator's underlying function.
2899 : */
2900 11198 : set_opfuncid(clause); /* make sure we have opfuncid */
2901 11198 : return get_index_clause_from_support(root,
2902 : rinfo,
2903 : clause->opfuncid,
2904 : 0, /* indexarg on left */
2905 : indexcol,
2906 : index);
2907 : }
2908 :
2909 940250 : if (match_index_to_operand(rightop, indexcol, index) &&
2910 54116 : !bms_is_member(index_relid, rinfo->left_relids) &&
2911 54008 : !contain_volatile_functions(leftop))
2912 : {
2913 54008 : if (IndexCollMatchesExprColl(idxcollation, expr_coll))
2914 : {
2915 53996 : Oid comm_op = get_commutator(expr_op);
2916 :
2917 107992 : if (OidIsValid(comm_op) &&
2918 53996 : op_in_opfamily(comm_op, opfamily))
2919 : {
2920 : RestrictInfo *commrinfo;
2921 :
2922 : /* Build a commuted OpExpr and RestrictInfo */
2923 52318 : commrinfo = commute_restrictinfo(rinfo, comm_op);
2924 :
2925 : /* Make an IndexClause showing that as a derived qual */
2926 52318 : iclause = makeNode(IndexClause);
2927 52318 : iclause->rinfo = rinfo;
2928 52318 : iclause->indexquals = list_make1(commrinfo);
2929 52318 : iclause->lossy = false;
2930 52318 : iclause->indexcol = indexcol;
2931 52318 : iclause->indexcols = NIL;
2932 52318 : return iclause;
2933 : }
2934 : }
2935 :
2936 : /*
2937 : * If we didn't find a member of the index's opfamily, try the support
2938 : * function for the operator's underlying function.
2939 : */
2940 1690 : set_opfuncid(clause); /* make sure we have opfuncid */
2941 1690 : return get_index_clause_from_support(root,
2942 : rinfo,
2943 : clause->opfuncid,
2944 : 1, /* indexarg on right */
2945 : indexcol,
2946 : index);
2947 : }
2948 :
2949 886242 : return NULL;
2950 : }
2951 :
2952 : /*
2953 : * match_funcclause_to_indexcol()
2954 : * Handles the FuncExpr case for match_clause_to_indexcol(),
2955 : * which see for comments.
2956 : */
2957 : static IndexClause *
2958 28044 : match_funcclause_to_indexcol(PlannerInfo *root,
2959 : RestrictInfo *rinfo,
2960 : int indexcol,
2961 : IndexOptInfo *index)
2962 : {
2963 28044 : FuncExpr *clause = (FuncExpr *) rinfo->clause;
2964 : int indexarg;
2965 : ListCell *lc;
2966 :
2967 : /*
2968 : * We have no built-in intelligence about function clauses, but if there's
2969 : * a planner support function, it might be able to do something. But, to
2970 : * cut down on wasted planning cycles, only call the support function if
2971 : * at least one argument matches the target index column.
2972 : *
2973 : * Note that we don't insist on the other arguments being pseudoconstants;
2974 : * the support function has to check that. This is to allow cases where
2975 : * only some of the other arguments need to be included in the indexqual.
2976 : */
2977 28044 : indexarg = 0;
2978 59944 : foreach(lc, clause->args)
2979 : {
2980 37036 : Node *op = (Node *) lfirst(lc);
2981 :
2982 37036 : if (match_index_to_operand(op, indexcol, index))
2983 : {
2984 5136 : return get_index_clause_from_support(root,
2985 : rinfo,
2986 : clause->funcid,
2987 : indexarg,
2988 : indexcol,
2989 : index);
2990 : }
2991 :
2992 31900 : indexarg++;
2993 : }
2994 :
2995 22908 : return NULL;
2996 : }
2997 :
2998 : /*
2999 : * get_index_clause_from_support()
3000 : * If the function has a planner support function, try to construct
3001 : * an IndexClause using indexquals created by the support function.
3002 : */
3003 : static IndexClause *
3004 18024 : get_index_clause_from_support(PlannerInfo *root,
3005 : RestrictInfo *rinfo,
3006 : Oid funcid,
3007 : int indexarg,
3008 : int indexcol,
3009 : IndexOptInfo *index)
3010 : {
3011 18024 : Oid prosupport = get_func_support(funcid);
3012 : SupportRequestIndexCondition req;
3013 : List *sresult;
3014 :
3015 18024 : if (!OidIsValid(prosupport))
3016 10238 : return NULL;
3017 :
3018 7786 : req.type = T_SupportRequestIndexCondition;
3019 7786 : req.root = root;
3020 7786 : req.funcid = funcid;
3021 7786 : req.node = (Node *) rinfo->clause;
3022 7786 : req.indexarg = indexarg;
3023 7786 : req.index = index;
3024 7786 : req.indexcol = indexcol;
3025 7786 : req.opfamily = index->opfamily[indexcol];
3026 7786 : req.indexcollation = index->indexcollations[indexcol];
3027 :
3028 7786 : req.lossy = true; /* default assumption */
3029 :
3030 : sresult = (List *)
3031 7786 : DatumGetPointer(OidFunctionCall1(prosupport,
3032 : PointerGetDatum(&req)));
3033 :
3034 7786 : if (sresult != NIL)
3035 : {
3036 1360 : IndexClause *iclause = makeNode(IndexClause);
3037 1360 : List *indexquals = NIL;
3038 : ListCell *lc;
3039 :
3040 : /*
3041 : * The support function API says it should just give back bare
3042 : * clauses, so here we must wrap each one in a RestrictInfo.
3043 : */
3044 4002 : foreach(lc, sresult)
3045 : {
3046 2642 : Expr *clause = (Expr *) lfirst(lc);
3047 :
3048 2642 : indexquals = lappend(indexquals,
3049 2642 : make_simple_restrictinfo(root, clause));
3050 : }
3051 :
3052 1360 : iclause->rinfo = rinfo;
3053 1360 : iclause->indexquals = indexquals;
3054 1360 : iclause->lossy = req.lossy;
3055 1360 : iclause->indexcol = indexcol;
3056 1360 : iclause->indexcols = NIL;
3057 :
3058 1360 : return iclause;
3059 : }
3060 :
3061 6426 : return NULL;
3062 : }
3063 :
3064 : /*
3065 : * match_saopclause_to_indexcol()
3066 : * Handles the ScalarArrayOpExpr case for match_clause_to_indexcol(),
3067 : * which see for comments.
3068 : */
3069 : static IndexClause *
3070 70100 : match_saopclause_to_indexcol(PlannerInfo *root,
3071 : RestrictInfo *rinfo,
3072 : int indexcol,
3073 : IndexOptInfo *index)
3074 : {
3075 70100 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
3076 : Node *leftop,
3077 : *rightop;
3078 : Relids right_relids;
3079 : Oid expr_op;
3080 : Oid expr_coll;
3081 : Index index_relid;
3082 : Oid opfamily;
3083 : Oid idxcollation;
3084 :
3085 : /* We only accept ANY clauses, not ALL */
3086 70100 : if (!saop->useOr)
3087 13402 : return NULL;
3088 56698 : leftop = (Node *) linitial(saop->args);
3089 56698 : rightop = (Node *) lsecond(saop->args);
3090 56698 : right_relids = pull_varnos(root, rightop);
3091 56698 : expr_op = saop->opno;
3092 56698 : expr_coll = saop->inputcollid;
3093 :
3094 56698 : index_relid = index->rel->relid;
3095 56698 : opfamily = index->opfamily[indexcol];
3096 56698 : idxcollation = index->indexcollations[indexcol];
3097 :
3098 : /*
3099 : * We must have indexkey on the left and a pseudo-constant array argument.
3100 : */
3101 56698 : if (match_index_to_operand(leftop, indexcol, index) &&
3102 5886 : !bms_is_member(index_relid, right_relids) &&
3103 5886 : !contain_volatile_functions(rightop))
3104 : {
3105 11766 : if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
3106 5880 : op_in_opfamily(expr_op, opfamily))
3107 : {
3108 5868 : IndexClause *iclause = makeNode(IndexClause);
3109 :
3110 5868 : iclause->rinfo = rinfo;
3111 5868 : iclause->indexquals = list_make1(rinfo);
3112 5868 : iclause->lossy = false;
3113 5868 : iclause->indexcol = indexcol;
3114 5868 : iclause->indexcols = NIL;
3115 5868 : return iclause;
3116 : }
3117 :
3118 : /*
3119 : * We do not currently ask support functions about ScalarArrayOpExprs,
3120 : * though in principle we could.
3121 : */
3122 : }
3123 :
3124 50830 : return NULL;
3125 : }
3126 :
3127 : /*
3128 : * match_rowcompare_to_indexcol()
3129 : * Handles the RowCompareExpr case for match_clause_to_indexcol(),
3130 : * which see for comments.
3131 : *
3132 : * In this routine we check whether the first column of the row comparison
3133 : * matches the target index column. This is sufficient to guarantee that some
3134 : * index condition can be constructed from the RowCompareExpr --- the rest
3135 : * is handled by expand_indexqual_rowcompare().
3136 : */
3137 : static IndexClause *
3138 432 : match_rowcompare_to_indexcol(PlannerInfo *root,
3139 : RestrictInfo *rinfo,
3140 : int indexcol,
3141 : IndexOptInfo *index)
3142 : {
3143 432 : RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
3144 : Index index_relid;
3145 : Oid opfamily;
3146 : Oid idxcollation;
3147 : Node *leftop,
3148 : *rightop;
3149 : bool var_on_left;
3150 : Oid expr_op;
3151 : Oid expr_coll;
3152 :
3153 : /* Forget it if we're not dealing with a btree index */
3154 432 : if (index->relam != BTREE_AM_OID)
3155 0 : return NULL;
3156 :
3157 432 : index_relid = index->rel->relid;
3158 432 : opfamily = index->opfamily[indexcol];
3159 432 : idxcollation = index->indexcollations[indexcol];
3160 :
3161 : /*
3162 : * We could do the matching on the basis of insisting that the opfamily
3163 : * shown in the RowCompareExpr be the same as the index column's opfamily,
3164 : * but that could fail in the presence of reverse-sort opfamilies: it'd be
3165 : * a matter of chance whether RowCompareExpr had picked the forward or
3166 : * reverse-sort family. So look only at the operator, and match if it is
3167 : * a member of the index's opfamily (after commutation, if the indexkey is
3168 : * on the right). We'll worry later about whether any additional
3169 : * operators are matchable to the index.
3170 : */
3171 432 : leftop = (Node *) linitial(clause->largs);
3172 432 : rightop = (Node *) linitial(clause->rargs);
3173 432 : expr_op = linitial_oid(clause->opnos);
3174 432 : expr_coll = linitial_oid(clause->inputcollids);
3175 :
3176 : /* Collations must match, if relevant */
3177 432 : if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
3178 0 : return NULL;
3179 :
3180 : /*
3181 : * These syntactic tests are the same as in match_opclause_to_indexcol()
3182 : */
3183 432 : if (match_index_to_operand(leftop, indexcol, index) &&
3184 126 : !bms_is_member(index_relid, pull_varnos(root, rightop)) &&
3185 126 : !contain_volatile_functions(rightop))
3186 : {
3187 : /* OK, indexkey is on left */
3188 126 : var_on_left = true;
3189 : }
3190 306 : else if (match_index_to_operand(rightop, indexcol, index) &&
3191 24 : !bms_is_member(index_relid, pull_varnos(root, leftop)) &&
3192 24 : !contain_volatile_functions(leftop))
3193 : {
3194 : /* indexkey is on right, so commute the operator */
3195 24 : expr_op = get_commutator(expr_op);
3196 24 : if (expr_op == InvalidOid)
3197 0 : return NULL;
3198 24 : var_on_left = false;
3199 : }
3200 : else
3201 282 : return NULL;
3202 :
3203 : /* We're good if the operator is the right type of opfamily member */
3204 150 : switch (get_op_opfamily_strategy(expr_op, opfamily))
3205 : {
3206 150 : case BTLessStrategyNumber:
3207 : case BTLessEqualStrategyNumber:
3208 : case BTGreaterEqualStrategyNumber:
3209 : case BTGreaterStrategyNumber:
3210 150 : return expand_indexqual_rowcompare(root,
3211 : rinfo,
3212 : indexcol,
3213 : index,
3214 : expr_op,
3215 : var_on_left);
3216 : }
3217 :
3218 0 : return NULL;
3219 : }
3220 :
3221 : /*
3222 : * match_orclause_to_indexcol()
3223 : * Handles the OR-expr case for match_clause_to_indexcol() in the case
3224 : * when it could be transformed to ScalarArrayOpExpr.
3225 : *
3226 : * In this routine, we attempt to transform a list of OR-clause args into a
3227 : * single SAOP expression matching the target index column. On success,
3228 : * return an IndexClause, containing the transformed expression or NULL,
3229 : * if failed.
3230 : */
3231 : static IndexClause *
3232 21296 : match_orclause_to_indexcol(PlannerInfo *root,
3233 : RestrictInfo *rinfo,
3234 : int indexcol,
3235 : IndexOptInfo *index)
3236 : {
3237 : ListCell *lc;
3238 21296 : BoolExpr *orclause = (BoolExpr *) rinfo->orclause;
3239 21296 : Node *indexExpr = NULL;
3240 21296 : List *consts = NIL;
3241 21296 : Node *arrayNode = NULL;
3242 21296 : ScalarArrayOpExpr *saopexpr = NULL;
3243 21296 : Oid matchOpno = InvalidOid;
3244 : IndexClause *iclause;
3245 21296 : Oid consttype = InvalidOid;
3246 21296 : Oid arraytype = InvalidOid;
3247 21296 : Oid inputcollid = InvalidOid;
3248 21296 : bool firstTime = true;
3249 21296 : bool haveParam = false;
3250 :
3251 : Assert(IsA(orclause, BoolExpr));
3252 : Assert(orclause->boolop == OR_EXPR);
3253 :
3254 : /* Ignore index if it doesn't support SAOP clauses */
3255 21296 : if (!index->amsearcharray)
3256 106 : return NULL;
3257 :
3258 : /*
3259 : * Try to convert a list of OR-clauses to a single SAOP expression. Each
3260 : * OR entry must be in the form: (indexkey operator constant) or (constant
3261 : * operator indexkey). Operators of all the entries must match. Constant
3262 : * might be either Const or Param. To be effective, give up on the first
3263 : * non-matching entry. Exit is implemented as a break from the loop,
3264 : * which is catched afterwards.
3265 : */
3266 25394 : foreach(lc, orclause->args)
3267 : {
3268 : RestrictInfo *subRinfo;
3269 : OpExpr *subClause;
3270 : Oid opno;
3271 : Node *leftop,
3272 : *rightop;
3273 : Node *constExpr;
3274 :
3275 24314 : if (!IsA(lfirst(lc), RestrictInfo))
3276 5488 : break;
3277 :
3278 18826 : subRinfo = (RestrictInfo *) lfirst(lc);
3279 :
3280 : /* Only operator clauses can match */
3281 18826 : if (!IsA(subRinfo->clause, OpExpr))
3282 4620 : break;
3283 :
3284 14206 : subClause = (OpExpr *) subRinfo->clause;
3285 14206 : opno = subClause->opno;
3286 :
3287 : /* Only binary operators can match */
3288 14206 : if (list_length(subClause->args) != 2)
3289 0 : break;
3290 :
3291 : /*
3292 : * The parameters below must match between sub-rinfo and its parent as
3293 : * make_restrictinfo() fills them with the same values, and further
3294 : * modifications are also the same for the whole subtree. However,
3295 : * still make a sanity check.
3296 : */
3297 : Assert(subRinfo->is_pushed_down == rinfo->is_pushed_down);
3298 : Assert(subRinfo->is_clone == rinfo->is_clone);
3299 : Assert(subRinfo->security_level == rinfo->security_level);
3300 : Assert(bms_equal(subRinfo->incompatible_relids, rinfo->incompatible_relids));
3301 : Assert(bms_equal(subRinfo->outer_relids, rinfo->outer_relids));
3302 :
3303 : /*
3304 : * Also, check that required_relids in sub-rinfo is subset of parent's
3305 : * required_relids.
3306 : */
3307 : Assert(bms_is_subset(subRinfo->required_relids, rinfo->required_relids));
3308 :
3309 : /* Only the operator returning a boolean suit the transformation. */
3310 14206 : if (get_op_rettype(opno) != BOOLOID)
3311 0 : break;
3312 :
3313 : /*
3314 : * Check for clauses of the form: (indexkey operator constant) or
3315 : * (constant operator indexkey). Determine indexkey side first, check
3316 : * the constant later.
3317 : */
3318 14206 : leftop = (Node *) linitial(subClause->args);
3319 14206 : rightop = (Node *) lsecond(subClause->args);
3320 14206 : if (match_index_to_operand(leftop, indexcol, index))
3321 : {
3322 4990 : indexExpr = leftop;
3323 4990 : constExpr = rightop;
3324 : }
3325 9216 : else if (match_index_to_operand(rightop, indexcol, index))
3326 : {
3327 240 : opno = get_commutator(opno);
3328 240 : if (!OidIsValid(opno))
3329 : {
3330 : /* commutator doesn't exist, we can't reverse the order */
3331 0 : break;
3332 : }
3333 240 : indexExpr = rightop;
3334 240 : constExpr = leftop;
3335 : }
3336 : else
3337 : {
3338 8976 : break;
3339 : }
3340 :
3341 : /*
3342 : * Ignore any RelabelType node above the operands. This is needed to
3343 : * be able to apply indexscanning in binary-compatible-operator cases.
3344 : * Note: we can assume there is at most one RelabelType node;
3345 : * eval_const_expressions() will have simplified if more than one.
3346 : */
3347 5230 : if (IsA(constExpr, RelabelType))
3348 0 : constExpr = (Node *) ((RelabelType *) constExpr)->arg;
3349 5230 : if (IsA(indexExpr, RelabelType))
3350 6 : indexExpr = (Node *) ((RelabelType *) indexExpr)->arg;
3351 :
3352 : /* We allow constant to be Const or Param */
3353 5230 : if (!IsA(constExpr, Const) && !IsA(constExpr, Param))
3354 438 : break;
3355 :
3356 : /* Forbid transformation for composite types, records. */
3357 9584 : if (type_is_rowtype(exprType(constExpr)) ||
3358 4792 : type_is_rowtype(exprType(indexExpr)))
3359 : break;
3360 :
3361 : /*
3362 : * Save information about the operator, type, and collation for the
3363 : * first matching qual. Then, check that subsequent quals match the
3364 : * first.
3365 : */
3366 4792 : if (firstTime)
3367 : {
3368 2734 : matchOpno = opno;
3369 2734 : consttype = exprType(constExpr);
3370 2734 : arraytype = get_array_type(consttype);
3371 2734 : inputcollid = subClause->inputcollid;
3372 :
3373 : /*
3374 : * Check that the operator is presented in the opfamily and that
3375 : * the expression collation matches the index collation. Also,
3376 : * there must be an array type to construct an array later.
3377 : */
3378 2734 : if (!IndexCollMatchesExprColl(index->indexcollations[indexcol], inputcollid) ||
3379 2626 : !op_in_opfamily(matchOpno, index->opfamily[indexcol]) ||
3380 : !OidIsValid(arraytype))
3381 : break;
3382 2590 : firstTime = false;
3383 : }
3384 : else
3385 : {
3386 2058 : if (opno != matchOpno ||
3387 3228 : inputcollid != subClause->inputcollid ||
3388 1614 : consttype != exprType(constExpr))
3389 : break;
3390 : }
3391 :
3392 4204 : if (IsA(constExpr, Param))
3393 24 : haveParam = true;
3394 4204 : consts = lappend(consts, constExpr);
3395 : }
3396 :
3397 : /*
3398 : * Catch the break from the loop above. Normally, a foreach() loop ends
3399 : * up with a NULL list cell. A non-NULL list cell indicates a break from
3400 : * the foreach() loop. Free the consts list and return NULL then.
3401 : */
3402 21190 : if (lc != NULL)
3403 : {
3404 20110 : list_free(consts);
3405 20110 : return NULL;
3406 : }
3407 :
3408 : /*
3409 : * Assemble an array from the list of constants. It seems more profitable
3410 : * to build a const array. But in the presence of parameters, we don't
3411 : * have a specific value here and must employ an ArrayExpr instead.
3412 : */
3413 1080 : if (haveParam)
3414 : {
3415 24 : ArrayExpr *arrayExpr = makeNode(ArrayExpr);
3416 :
3417 : /* array_collid will be set by parse_collate.c */
3418 24 : arrayExpr->element_typeid = consttype;
3419 24 : arrayExpr->array_typeid = arraytype;
3420 24 : arrayExpr->multidims = false;
3421 24 : arrayExpr->elements = consts;
3422 24 : arrayExpr->location = -1;
3423 :
3424 24 : arrayNode = (Node *) arrayExpr;
3425 : }
3426 : else
3427 : {
3428 : int16 typlen;
3429 : bool typbyval;
3430 : char typalign;
3431 : Datum *elems;
3432 1056 : int i = 0;
3433 : ArrayType *arrayConst;
3434 :
3435 1056 : get_typlenbyvalalign(consttype, &typlen, &typbyval, &typalign);
3436 :
3437 1056 : elems = (Datum *) palloc(sizeof(Datum) * list_length(consts));
3438 4662 : foreach_node(Const, value, consts)
3439 : {
3440 : Assert(!value->constisnull);
3441 :
3442 2550 : elems[i++] = value->constvalue;
3443 : }
3444 :
3445 1056 : arrayConst = construct_array(elems, i, consttype,
3446 : typlen, typbyval, typalign);
3447 1056 : arrayNode = (Node *) makeConst(arraytype, -1, inputcollid,
3448 : -1, PointerGetDatum(arrayConst),
3449 : false, false);
3450 :
3451 1056 : pfree(elems);
3452 1056 : list_free(consts);
3453 : }
3454 :
3455 : /* Build the SAOP expression node */
3456 1080 : saopexpr = makeNode(ScalarArrayOpExpr);
3457 1080 : saopexpr->opno = matchOpno;
3458 1080 : saopexpr->opfuncid = get_opcode(matchOpno);
3459 1080 : saopexpr->hashfuncid = InvalidOid;
3460 1080 : saopexpr->negfuncid = InvalidOid;
3461 1080 : saopexpr->useOr = true;
3462 1080 : saopexpr->inputcollid = inputcollid;
3463 1080 : saopexpr->args = list_make2(indexExpr, arrayNode);
3464 1080 : saopexpr->location = -1;
3465 :
3466 : /*
3467 : * Finally, build an IndexClause based on the SAOP node. Use
3468 : * make_simple_restrictinfo() to get RestrictInfo with clean selectivity
3469 : * estimations, because they may differ from the estimation made for an OR
3470 : * clause. Although it is not a lossy expression, keep the original rinfo
3471 : * in iclause->rinfo as prescribed.
3472 : */
3473 1080 : iclause = makeNode(IndexClause);
3474 1080 : iclause->rinfo = rinfo;
3475 1080 : iclause->indexquals = list_make1(make_simple_restrictinfo(root,
3476 : &saopexpr->xpr));
3477 1080 : iclause->lossy = false;
3478 1080 : iclause->indexcol = indexcol;
3479 1080 : iclause->indexcols = NIL;
3480 1080 : return iclause;
3481 : }
3482 :
3483 : /*
3484 : * expand_indexqual_rowcompare --- expand a single indexqual condition
3485 : * that is a RowCompareExpr
3486 : *
3487 : * It's already known that the first column of the row comparison matches
3488 : * the specified column of the index. We can use additional columns of the
3489 : * row comparison as index qualifications, so long as they match the index
3490 : * in the "same direction", ie, the indexkeys are all on the same side of the
3491 : * clause and the operators are all the same-type members of the opfamilies.
3492 : *
3493 : * If all the columns of the RowCompareExpr match in this way, we just use it
3494 : * as-is, except for possibly commuting it to put the indexkeys on the left.
3495 : *
3496 : * Otherwise, we build a shortened RowCompareExpr (if more than one
3497 : * column matches) or a simple OpExpr (if the first-column match is all
3498 : * there is). In these cases the modified clause is always "<=" or ">="
3499 : * even when the original was "<" or ">" --- this is necessary to match all
3500 : * the rows that could match the original. (We are building a lossy version
3501 : * of the row comparison when we do this, so we set lossy = true.)
3502 : *
3503 : * Note: this is really just the last half of match_rowcompare_to_indexcol,
3504 : * but we split it out for comprehensibility.
3505 : */
3506 : static IndexClause *
3507 150 : expand_indexqual_rowcompare(PlannerInfo *root,
3508 : RestrictInfo *rinfo,
3509 : int indexcol,
3510 : IndexOptInfo *index,
3511 : Oid expr_op,
3512 : bool var_on_left)
3513 : {
3514 150 : IndexClause *iclause = makeNode(IndexClause);
3515 150 : RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
3516 : int op_strategy;
3517 : Oid op_lefttype;
3518 : Oid op_righttype;
3519 : int matching_cols;
3520 : List *expr_ops;
3521 : List *opfamilies;
3522 : List *lefttypes;
3523 : List *righttypes;
3524 : List *new_ops;
3525 : List *var_args;
3526 : List *non_var_args;
3527 :
3528 150 : iclause->rinfo = rinfo;
3529 150 : iclause->indexcol = indexcol;
3530 :
3531 150 : if (var_on_left)
3532 : {
3533 126 : var_args = clause->largs;
3534 126 : non_var_args = clause->rargs;
3535 : }
3536 : else
3537 : {
3538 24 : var_args = clause->rargs;
3539 24 : non_var_args = clause->largs;
3540 : }
3541 :
3542 150 : get_op_opfamily_properties(expr_op, index->opfamily[indexcol], false,
3543 : &op_strategy,
3544 : &op_lefttype,
3545 : &op_righttype);
3546 :
3547 : /* Initialize returned list of which index columns are used */
3548 150 : iclause->indexcols = list_make1_int(indexcol);
3549 :
3550 : /* Build lists of ops, opfamilies and operator datatypes in case needed */
3551 150 : expr_ops = list_make1_oid(expr_op);
3552 150 : opfamilies = list_make1_oid(index->opfamily[indexcol]);
3553 150 : lefttypes = list_make1_oid(op_lefttype);
3554 150 : righttypes = list_make1_oid(op_righttype);
3555 :
3556 : /*
3557 : * See how many of the remaining columns match some index column in the
3558 : * same way. As in match_clause_to_indexcol(), the "other" side of any
3559 : * potential index condition is OK as long as it doesn't use Vars from the
3560 : * indexed relation.
3561 : */
3562 150 : matching_cols = 1;
3563 :
3564 282 : while (matching_cols < list_length(var_args))
3565 : {
3566 186 : Node *varop = (Node *) list_nth(var_args, matching_cols);
3567 186 : Node *constop = (Node *) list_nth(non_var_args, matching_cols);
3568 : int i;
3569 :
3570 186 : expr_op = list_nth_oid(clause->opnos, matching_cols);
3571 186 : if (!var_on_left)
3572 : {
3573 : /* indexkey is on right, so commute the operator */
3574 24 : expr_op = get_commutator(expr_op);
3575 24 : if (expr_op == InvalidOid)
3576 0 : break; /* operator is not usable */
3577 : }
3578 186 : if (bms_is_member(index->rel->relid, pull_varnos(root, constop)))
3579 0 : break; /* no good, Var on wrong side */
3580 186 : if (contain_volatile_functions(constop))
3581 0 : break; /* no good, volatile comparison value */
3582 :
3583 : /*
3584 : * The Var side can match any key column of the index.
3585 : */
3586 444 : for (i = 0; i < index->nkeycolumns; i++)
3587 : {
3588 390 : if (match_index_to_operand(varop, i, index) &&
3589 132 : get_op_opfamily_strategy(expr_op,
3590 132 : index->opfamily[i]) == op_strategy &&
3591 132 : IndexCollMatchesExprColl(index->indexcollations[i],
3592 : list_nth_oid(clause->inputcollids,
3593 : matching_cols)))
3594 : break;
3595 : }
3596 186 : if (i >= index->nkeycolumns)
3597 54 : break; /* no match found */
3598 :
3599 : /* Add column number to returned list */
3600 132 : iclause->indexcols = lappend_int(iclause->indexcols, i);
3601 :
3602 : /* Add operator info to lists */
3603 132 : get_op_opfamily_properties(expr_op, index->opfamily[i], false,
3604 : &op_strategy,
3605 : &op_lefttype,
3606 : &op_righttype);
3607 132 : expr_ops = lappend_oid(expr_ops, expr_op);
3608 132 : opfamilies = lappend_oid(opfamilies, index->opfamily[i]);
3609 132 : lefttypes = lappend_oid(lefttypes, op_lefttype);
3610 132 : righttypes = lappend_oid(righttypes, op_righttype);
3611 :
3612 : /* This column matches, keep scanning */
3613 132 : matching_cols++;
3614 : }
3615 :
3616 : /* Result is non-lossy if all columns are usable as index quals */
3617 150 : iclause->lossy = (matching_cols != list_length(clause->opnos));
3618 :
3619 : /*
3620 : * We can use rinfo->clause as-is if we have var on left and it's all
3621 : * usable as index quals.
3622 : */
3623 150 : if (var_on_left && !iclause->lossy)
3624 84 : iclause->indexquals = list_make1(rinfo);
3625 : else
3626 : {
3627 : /*
3628 : * We have to generate a modified rowcompare (possibly just one
3629 : * OpExpr). The painful part of this is changing < to <= or > to >=,
3630 : * so deal with that first.
3631 : */
3632 66 : if (!iclause->lossy)
3633 : {
3634 : /* very easy, just use the commuted operators */
3635 12 : new_ops = expr_ops;
3636 : }
3637 54 : else if (op_strategy == BTLessEqualStrategyNumber ||
3638 54 : op_strategy == BTGreaterEqualStrategyNumber)
3639 : {
3640 : /* easy, just use the same (possibly commuted) operators */
3641 0 : new_ops = list_truncate(expr_ops, matching_cols);
3642 : }
3643 : else
3644 : {
3645 : ListCell *opfamilies_cell;
3646 : ListCell *lefttypes_cell;
3647 : ListCell *righttypes_cell;
3648 :
3649 54 : if (op_strategy == BTLessStrategyNumber)
3650 30 : op_strategy = BTLessEqualStrategyNumber;
3651 24 : else if (op_strategy == BTGreaterStrategyNumber)
3652 24 : op_strategy = BTGreaterEqualStrategyNumber;
3653 : else
3654 0 : elog(ERROR, "unexpected strategy number %d", op_strategy);
3655 54 : new_ops = NIL;
3656 144 : forthree(opfamilies_cell, opfamilies,
3657 : lefttypes_cell, lefttypes,
3658 : righttypes_cell, righttypes)
3659 : {
3660 90 : Oid opfam = lfirst_oid(opfamilies_cell);
3661 90 : Oid lefttype = lfirst_oid(lefttypes_cell);
3662 90 : Oid righttype = lfirst_oid(righttypes_cell);
3663 :
3664 90 : expr_op = get_opfamily_member(opfam, lefttype, righttype,
3665 : op_strategy);
3666 90 : if (!OidIsValid(expr_op)) /* should not happen */
3667 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3668 : op_strategy, lefttype, righttype, opfam);
3669 90 : new_ops = lappend_oid(new_ops, expr_op);
3670 : }
3671 : }
3672 :
3673 : /* If we have more than one matching col, create a subset rowcompare */
3674 66 : if (matching_cols > 1)
3675 : {
3676 48 : RowCompareExpr *rc = makeNode(RowCompareExpr);
3677 :
3678 48 : rc->cmptype = (CompareType) op_strategy;
3679 48 : rc->opnos = new_ops;
3680 48 : rc->opfamilies = list_copy_head(clause->opfamilies,
3681 : matching_cols);
3682 48 : rc->inputcollids = list_copy_head(clause->inputcollids,
3683 : matching_cols);
3684 48 : rc->largs = list_copy_head(var_args, matching_cols);
3685 48 : rc->rargs = list_copy_head(non_var_args, matching_cols);
3686 48 : iclause->indexquals = list_make1(make_simple_restrictinfo(root,
3687 : (Expr *) rc));
3688 : }
3689 : else
3690 : {
3691 : Expr *op;
3692 :
3693 : /* We don't report an index column list in this case */
3694 18 : iclause->indexcols = NIL;
3695 :
3696 18 : op = make_opclause(linitial_oid(new_ops), BOOLOID, false,
3697 18 : copyObject(linitial(var_args)),
3698 18 : copyObject(linitial(non_var_args)),
3699 : InvalidOid,
3700 18 : linitial_oid(clause->inputcollids));
3701 18 : iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
3702 : }
3703 : }
3704 :
3705 150 : return iclause;
3706 : }
3707 :
3708 :
3709 : /****************************************************************************
3710 : * ---- ROUTINES TO CHECK ORDERING OPERATORS ----
3711 : ****************************************************************************/
3712 :
3713 : /*
3714 : * match_pathkeys_to_index
3715 : * For the given 'index' and 'pathkeys', output a list of suitable ORDER
3716 : * BY expressions, each of the form "indexedcol operator pseudoconstant",
3717 : * along with an integer list of the index column numbers (zero based)
3718 : * that each clause would be used with.
3719 : *
3720 : * This attempts to find an ORDER BY and index column number for all items in
3721 : * the pathkey list, however, if we're unable to match any given pathkey to an
3722 : * index column, we return just the ones matched by the function so far. This
3723 : * allows callers who are interested in partial matches to get them. Callers
3724 : * can determine a partial match vs a full match by checking the outputted
3725 : * list lengths. A full match will have one item in the output lists for each
3726 : * item in the given 'pathkeys' list.
3727 : */
3728 : static void
3729 1074 : match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
3730 : List **orderby_clauses_p,
3731 : List **clause_columns_p)
3732 : {
3733 : ListCell *lc1;
3734 :
3735 1074 : *orderby_clauses_p = NIL; /* set default results */
3736 1074 : *clause_columns_p = NIL;
3737 :
3738 : /* Only indexes with the amcanorderbyop property are interesting here */
3739 1074 : if (!index->amcanorderbyop)
3740 0 : return;
3741 :
3742 1548 : foreach(lc1, pathkeys)
3743 : {
3744 1080 : PathKey *pathkey = (PathKey *) lfirst(lc1);
3745 1080 : bool found = false;
3746 : ListCell *lc2;
3747 :
3748 :
3749 : /* Pathkey must request default sort order for the target opfamily */
3750 1080 : if (pathkey->pk_strategy != BTLessStrategyNumber ||
3751 1046 : pathkey->pk_nulls_first)
3752 606 : return;
3753 :
3754 : /* If eclass is volatile, no hope of using an indexscan */
3755 1046 : if (pathkey->pk_eclass->ec_has_volatile)
3756 0 : return;
3757 :
3758 : /*
3759 : * Try to match eclass member expression(s) to index. Note that child
3760 : * EC members are considered, but only when they belong to the target
3761 : * relation. (Unlike regular members, the same expression could be a
3762 : * child member of more than one EC. Therefore, the same index could
3763 : * be considered to match more than one pathkey list, which is OK
3764 : * here. See also get_eclass_for_sort_expr.)
3765 : */
3766 1682 : foreach(lc2, pathkey->pk_eclass->ec_members)
3767 : {
3768 1110 : EquivalenceMember *member = (EquivalenceMember *) lfirst(lc2);
3769 : int indexcol;
3770 :
3771 : /* No possibility of match if it references other relations */
3772 1110 : if (!bms_equal(member->em_relids, index->rel->relids))
3773 64 : continue;
3774 :
3775 : /*
3776 : * We allow any column of the index to match each pathkey; they
3777 : * don't have to match left-to-right as you might expect. This is
3778 : * correct for GiST, and it doesn't matter for SP-GiST because
3779 : * that doesn't handle multiple columns anyway, and no other
3780 : * existing AMs support amcanorderbyop. We might need different
3781 : * logic in future for other implementations.
3782 : */
3783 1906 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
3784 : {
3785 : Expr *expr;
3786 :
3787 1334 : expr = match_clause_to_ordering_op(index,
3788 : indexcol,
3789 : member->em_expr,
3790 : pathkey->pk_opfamily);
3791 1334 : if (expr)
3792 : {
3793 474 : *orderby_clauses_p = lappend(*orderby_clauses_p, expr);
3794 474 : *clause_columns_p = lappend_int(*clause_columns_p, indexcol);
3795 474 : found = true;
3796 474 : break;
3797 : }
3798 : }
3799 :
3800 1046 : if (found) /* don't want to look at remaining members */
3801 474 : break;
3802 : }
3803 :
3804 : /*
3805 : * Return the matches found so far when this pathkey couldn't be
3806 : * matched to the index.
3807 : */
3808 1046 : if (!found)
3809 572 : return;
3810 : }
3811 : }
3812 :
3813 : /*
3814 : * match_clause_to_ordering_op
3815 : * Determines whether an ordering operator expression matches an
3816 : * index column.
3817 : *
3818 : * This is similar to, but simpler than, match_clause_to_indexcol.
3819 : * We only care about simple OpExpr cases. The input is a bare
3820 : * expression that is being ordered by, which must be of the form
3821 : * (indexkey op const) or (const op indexkey) where op is an ordering
3822 : * operator for the column's opfamily.
3823 : *
3824 : * 'index' is the index of interest.
3825 : * 'indexcol' is a column number of 'index' (counting from 0).
3826 : * 'clause' is the ordering expression to be tested.
3827 : * 'pk_opfamily' is the btree opfamily describing the required sort order.
3828 : *
3829 : * Note that we currently do not consider the collation of the ordering
3830 : * operator's result. In practical cases the result type will be numeric
3831 : * and thus have no collation, and it's not very clear what to match to
3832 : * if it did have a collation. The index's collation should match the
3833 : * ordering operator's input collation, not its result.
3834 : *
3835 : * If successful, return 'clause' as-is if the indexkey is on the left,
3836 : * otherwise a commuted copy of 'clause'. If no match, return NULL.
3837 : */
3838 : static Expr *
3839 1334 : match_clause_to_ordering_op(IndexOptInfo *index,
3840 : int indexcol,
3841 : Expr *clause,
3842 : Oid pk_opfamily)
3843 : {
3844 : Oid opfamily;
3845 : Oid idxcollation;
3846 : Node *leftop,
3847 : *rightop;
3848 : Oid expr_op;
3849 : Oid expr_coll;
3850 : Oid sortfamily;
3851 : bool commuted;
3852 :
3853 : Assert(indexcol < index->nkeycolumns);
3854 :
3855 1334 : opfamily = index->opfamily[indexcol];
3856 1334 : idxcollation = index->indexcollations[indexcol];
3857 :
3858 : /*
3859 : * Clause must be a binary opclause.
3860 : */
3861 1334 : if (!is_opclause(clause))
3862 860 : return NULL;
3863 474 : leftop = get_leftop(clause);
3864 474 : rightop = get_rightop(clause);
3865 474 : if (!leftop || !rightop)
3866 0 : return NULL;
3867 474 : expr_op = ((OpExpr *) clause)->opno;
3868 474 : expr_coll = ((OpExpr *) clause)->inputcollid;
3869 :
3870 : /*
3871 : * We can forget the whole thing right away if wrong collation.
3872 : */
3873 474 : if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
3874 0 : return NULL;
3875 :
3876 : /*
3877 : * Check for clauses of the form: (indexkey operator constant) or
3878 : * (constant operator indexkey).
3879 : */
3880 474 : if (match_index_to_operand(leftop, indexcol, index) &&
3881 450 : !contain_var_clause(rightop) &&
3882 450 : !contain_volatile_functions(rightop))
3883 : {
3884 450 : commuted = false;
3885 : }
3886 24 : else if (match_index_to_operand(rightop, indexcol, index) &&
3887 24 : !contain_var_clause(leftop) &&
3888 24 : !contain_volatile_functions(leftop))
3889 : {
3890 : /* Might match, but we need a commuted operator */
3891 24 : expr_op = get_commutator(expr_op);
3892 24 : if (expr_op == InvalidOid)
3893 0 : return NULL;
3894 24 : commuted = true;
3895 : }
3896 : else
3897 0 : return NULL;
3898 :
3899 : /*
3900 : * Is the (commuted) operator an ordering operator for the opfamily? And
3901 : * if so, does it yield the right sorting semantics?
3902 : */
3903 474 : sortfamily = get_op_opfamily_sortfamily(expr_op, opfamily);
3904 474 : if (sortfamily != pk_opfamily)
3905 0 : return NULL;
3906 :
3907 : /* We have a match. Return clause or a commuted version thereof. */
3908 474 : if (commuted)
3909 : {
3910 24 : OpExpr *newclause = makeNode(OpExpr);
3911 :
3912 : /* flat-copy all the fields of clause */
3913 24 : memcpy(newclause, clause, sizeof(OpExpr));
3914 :
3915 : /* commute it */
3916 24 : newclause->opno = expr_op;
3917 24 : newclause->opfuncid = InvalidOid;
3918 24 : newclause->args = list_make2(rightop, leftop);
3919 :
3920 24 : clause = (Expr *) newclause;
3921 : }
3922 :
3923 474 : return clause;
3924 : }
3925 :
3926 :
3927 : /****************************************************************************
3928 : * ---- ROUTINES TO DO PARTIAL INDEX PREDICATE TESTS ----
3929 : ****************************************************************************/
3930 :
3931 : /*
3932 : * check_index_predicates
3933 : * Set the predicate-derived IndexOptInfo fields for each index
3934 : * of the specified relation.
3935 : *
3936 : * predOK is set true if the index is partial and its predicate is satisfied
3937 : * for this query, ie the query's WHERE clauses imply the predicate.
3938 : *
3939 : * indrestrictinfo is set to the relation's baserestrictinfo list less any
3940 : * conditions that are implied by the index's predicate. (Obviously, for a
3941 : * non-partial index, this is the same as baserestrictinfo.) Such conditions
3942 : * can be dropped from the plan when using the index, in certain cases.
3943 : *
3944 : * At one time it was possible for this to get re-run after adding more
3945 : * restrictions to the rel, thus possibly letting us prove more indexes OK.
3946 : * That doesn't happen any more (at least not in the core code's usage),
3947 : * but this code still supports it in case extensions want to mess with the
3948 : * baserestrictinfo list. We assume that adding more restrictions can't make
3949 : * an index not predOK. We must recompute indrestrictinfo each time, though,
3950 : * to make sure any newly-added restrictions get into it if needed.
3951 : */
3952 : void
3953 362612 : check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
3954 : {
3955 : List *clauselist;
3956 : bool have_partial;
3957 : bool is_target_rel;
3958 : Relids otherrels;
3959 : ListCell *lc;
3960 :
3961 : /* Indexes are available only on base or "other" member relations. */
3962 : Assert(IS_SIMPLE_REL(rel));
3963 :
3964 : /*
3965 : * Initialize the indrestrictinfo lists to be identical to
3966 : * baserestrictinfo, and check whether there are any partial indexes. If
3967 : * not, this is all we need to do.
3968 : */
3969 362612 : have_partial = false;
3970 983572 : foreach(lc, rel->indexlist)
3971 : {
3972 620960 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
3973 :
3974 620960 : index->indrestrictinfo = rel->baserestrictinfo;
3975 620960 : if (index->indpred)
3976 984 : have_partial = true;
3977 : }
3978 362612 : if (!have_partial)
3979 361952 : return;
3980 :
3981 : /*
3982 : * Construct a list of clauses that we can assume true for the purpose of
3983 : * proving the index(es) usable. Restriction clauses for the rel are
3984 : * always usable, and so are any join clauses that are "movable to" this
3985 : * rel. Also, we can consider any EC-derivable join clauses (which must
3986 : * be "movable to" this rel, by definition).
3987 : */
3988 660 : clauselist = list_copy(rel->baserestrictinfo);
3989 :
3990 : /* Scan the rel's join clauses */
3991 660 : foreach(lc, rel->joininfo)
3992 : {
3993 0 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3994 :
3995 : /* Check if clause can be moved to this rel */
3996 0 : if (!join_clause_is_movable_to(rinfo, rel))
3997 0 : continue;
3998 :
3999 0 : clauselist = lappend(clauselist, rinfo);
4000 : }
4001 :
4002 : /*
4003 : * Add on any equivalence-derivable join clauses. Computing the correct
4004 : * relid sets for generate_join_implied_equalities is slightly tricky
4005 : * because the rel could be a child rel rather than a true baserel, and in
4006 : * that case we must subtract its parents' relid(s) from all_query_rels.
4007 : * Additionally, we mustn't consider clauses that are only computable
4008 : * after outer joins that can null the rel.
4009 : */
4010 660 : if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
4011 72 : otherrels = bms_difference(root->all_query_rels,
4012 72 : find_childrel_parents(root, rel));
4013 : else
4014 588 : otherrels = bms_difference(root->all_query_rels, rel->relids);
4015 660 : otherrels = bms_del_members(otherrels, rel->nulling_relids);
4016 :
4017 660 : if (!bms_is_empty(otherrels))
4018 : clauselist =
4019 88 : list_concat(clauselist,
4020 88 : generate_join_implied_equalities(root,
4021 88 : bms_union(rel->relids,
4022 : otherrels),
4023 : otherrels,
4024 : rel,
4025 : NULL));
4026 :
4027 : /*
4028 : * Normally we remove quals that are implied by a partial index's
4029 : * predicate from indrestrictinfo, indicating that they need not be
4030 : * checked explicitly by an indexscan plan using this index. However, if
4031 : * the rel is a target relation of UPDATE/DELETE/MERGE/SELECT FOR UPDATE,
4032 : * we cannot remove such quals from the plan, because they need to be in
4033 : * the plan so that they will be properly rechecked by EvalPlanQual
4034 : * testing. Some day we might want to remove such quals from the main
4035 : * plan anyway and pass them through to EvalPlanQual via a side channel;
4036 : * but for now, we just don't remove implied quals at all for target
4037 : * relations.
4038 : */
4039 1208 : is_target_rel = (bms_is_member(rel->relid, root->all_result_relids) ||
4040 548 : get_plan_rowmark(root->rowMarks, rel->relid) != NULL);
4041 :
4042 : /*
4043 : * Now try to prove each index predicate true, and compute the
4044 : * indrestrictinfo lists for partial indexes. Note that we compute the
4045 : * indrestrictinfo list even for non-predOK indexes; this might seem
4046 : * wasteful, but we may be able to use such indexes in OR clauses, cf
4047 : * generate_bitmap_or_paths().
4048 : */
4049 2030 : foreach(lc, rel->indexlist)
4050 : {
4051 1370 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
4052 : ListCell *lcr;
4053 :
4054 1370 : if (index->indpred == NIL)
4055 386 : continue; /* ignore non-partial indexes here */
4056 :
4057 984 : if (!index->predOK) /* don't repeat work if already proven OK */
4058 984 : index->predOK = predicate_implied_by(index->indpred, clauselist,
4059 : false);
4060 :
4061 : /* If rel is an update target, leave indrestrictinfo as set above */
4062 984 : if (is_target_rel)
4063 172 : continue;
4064 :
4065 : /* Else compute indrestrictinfo as the non-implied quals */
4066 812 : index->indrestrictinfo = NIL;
4067 1914 : foreach(lcr, rel->baserestrictinfo)
4068 : {
4069 1102 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcr);
4070 :
4071 : /* predicate_implied_by() assumes first arg is immutable */
4072 1102 : if (contain_mutable_functions((Node *) rinfo->clause) ||
4073 1102 : !predicate_implied_by(list_make1(rinfo->clause),
4074 : index->indpred, false))
4075 782 : index->indrestrictinfo = lappend(index->indrestrictinfo, rinfo);
4076 : }
4077 : }
4078 : }
4079 :
4080 : /****************************************************************************
4081 : * ---- ROUTINES TO CHECK EXTERNALLY-VISIBLE CONDITIONS ----
4082 : ****************************************************************************/
4083 :
4084 : /*
4085 : * ec_member_matches_indexcol
4086 : * Test whether an EquivalenceClass member matches an index column.
4087 : *
4088 : * This is a callback for use by generate_implied_equalities_for_column.
4089 : */
4090 : static bool
4091 348964 : ec_member_matches_indexcol(PlannerInfo *root, RelOptInfo *rel,
4092 : EquivalenceClass *ec, EquivalenceMember *em,
4093 : void *arg)
4094 : {
4095 348964 : IndexOptInfo *index = ((ec_member_matches_arg *) arg)->index;
4096 348964 : int indexcol = ((ec_member_matches_arg *) arg)->indexcol;
4097 : Oid curFamily;
4098 : Oid curCollation;
4099 :
4100 : Assert(indexcol < index->nkeycolumns);
4101 :
4102 348964 : curFamily = index->opfamily[indexcol];
4103 348964 : curCollation = index->indexcollations[indexcol];
4104 :
4105 : /*
4106 : * If it's a btree index, we can reject it if its opfamily isn't
4107 : * compatible with the EC, since no clause generated from the EC could be
4108 : * used with the index. For non-btree indexes, we can't easily tell
4109 : * whether clauses generated from the EC could be used with the index, so
4110 : * don't check the opfamily. This might mean we return "true" for a
4111 : * useless EC, so we have to recheck the results of
4112 : * generate_implied_equalities_for_column; see
4113 : * match_eclass_clauses_to_index.
4114 : */
4115 348964 : if (index->relam == BTREE_AM_OID &&
4116 348922 : !list_member_oid(ec->ec_opfamilies, curFamily))
4117 107242 : return false;
4118 :
4119 : /* We insist on collation match for all index types, though */
4120 241722 : if (!IndexCollMatchesExprColl(curCollation, ec->ec_collation))
4121 14 : return false;
4122 :
4123 241708 : return match_index_to_operand((Node *) em->em_expr, indexcol, index);
4124 : }
4125 :
4126 : /*
4127 : * relation_has_unique_index_for
4128 : * Determine whether the relation provably has at most one row satisfying
4129 : * a set of equality conditions, because the conditions constrain all
4130 : * columns of some unique index.
4131 : *
4132 : * The conditions can be represented in either or both of two ways:
4133 : * 1. A list of RestrictInfo nodes, where the caller has already determined
4134 : * that each condition is a mergejoinable equality with an expression in
4135 : * this relation on one side, and an expression not involving this relation
4136 : * on the other. The transient outer_is_left flag is used to identify which
4137 : * side we should look at: left side if outer_is_left is false, right side
4138 : * if it is true.
4139 : * 2. A list of expressions in this relation, and a corresponding list of
4140 : * equality operators. The caller must have already checked that the operators
4141 : * represent equality. (Note: the operators could be cross-type; the
4142 : * expressions should correspond to their RHS inputs.)
4143 : *
4144 : * The caller need only supply equality conditions arising from joins;
4145 : * this routine automatically adds in any usable baserestrictinfo clauses.
4146 : * (Note that the passed-in restrictlist will be destructively modified!)
4147 : */
4148 : bool
4149 169354 : relation_has_unique_index_for(PlannerInfo *root, RelOptInfo *rel,
4150 : List *restrictlist,
4151 : List *exprlist, List *oprlist)
4152 : {
4153 : ListCell *ic;
4154 :
4155 : Assert(list_length(exprlist) == list_length(oprlist));
4156 :
4157 : /* Short-circuit if no indexes... */
4158 169354 : if (rel->indexlist == NIL)
4159 452 : return false;
4160 :
4161 : /*
4162 : * Examine the rel's restriction clauses for usable var = const clauses
4163 : * that we can add to the restrictlist.
4164 : */
4165 277778 : foreach(ic, rel->baserestrictinfo)
4166 : {
4167 108876 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(ic);
4168 :
4169 : /*
4170 : * Note: can_join won't be set for a restriction clause, but
4171 : * mergeopfamilies will be if it has a mergejoinable operator and
4172 : * doesn't contain volatile functions.
4173 : */
4174 108876 : if (restrictinfo->mergeopfamilies == NIL)
4175 46040 : continue; /* not mergejoinable */
4176 :
4177 : /*
4178 : * The clause certainly doesn't refer to anything but the given rel.
4179 : * If either side is pseudoconstant then we can use it.
4180 : */
4181 62836 : if (bms_is_empty(restrictinfo->left_relids))
4182 : {
4183 : /* righthand side is inner */
4184 28 : restrictinfo->outer_is_left = true;
4185 : }
4186 62808 : else if (bms_is_empty(restrictinfo->right_relids))
4187 : {
4188 : /* lefthand side is inner */
4189 62778 : restrictinfo->outer_is_left = false;
4190 : }
4191 : else
4192 30 : continue;
4193 :
4194 : /* OK, add to list */
4195 62806 : restrictlist = lappend(restrictlist, restrictinfo);
4196 : }
4197 :
4198 : /* Short-circuit the easy case */
4199 168902 : if (restrictlist == NIL && exprlist == NIL)
4200 814 : return false;
4201 :
4202 : /* Examine each index of the relation ... */
4203 421998 : foreach(ic, rel->indexlist)
4204 : {
4205 356196 : IndexOptInfo *ind = (IndexOptInfo *) lfirst(ic);
4206 : int c;
4207 :
4208 : /*
4209 : * If the index is not unique, or not immediately enforced, or if it's
4210 : * a partial index, it's useless here. We're unable to make use of
4211 : * predOK partial unique indexes due to the fact that
4212 : * check_index_predicates() also makes use of join predicates to
4213 : * determine if the partial index is usable. Here we need proofs that
4214 : * hold true before any joins are evaluated.
4215 : */
4216 356196 : if (!ind->unique || !ind->immediate || ind->indpred != NIL)
4217 95096 : continue;
4218 :
4219 : /*
4220 : * Try to find each index column in the lists of conditions. This is
4221 : * O(N^2) or worse, but we expect all the lists to be short.
4222 : */
4223 427116 : for (c = 0; c < ind->nkeycolumns; c++)
4224 : {
4225 324830 : bool matched = false;
4226 : ListCell *lc;
4227 : ListCell *lc2;
4228 :
4229 609530 : foreach(lc, restrictlist)
4230 : {
4231 450716 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4232 : Node *rexpr;
4233 :
4234 : /*
4235 : * The condition's equality operator must be a member of the
4236 : * index opfamily, else it is not asserting the right kind of
4237 : * equality behavior for this index. We check this first
4238 : * since it's probably cheaper than match_index_to_operand().
4239 : */
4240 450716 : if (!list_member_oid(rinfo->mergeopfamilies, ind->opfamily[c]))
4241 121246 : continue;
4242 :
4243 : /*
4244 : * XXX at some point we may need to check collations here too.
4245 : * For the moment we assume all collations reduce to the same
4246 : * notion of equality.
4247 : */
4248 :
4249 : /* OK, see if the condition operand matches the index key */
4250 329470 : if (rinfo->outer_is_left)
4251 144660 : rexpr = get_rightop(rinfo->clause);
4252 : else
4253 184810 : rexpr = get_leftop(rinfo->clause);
4254 :
4255 329470 : if (match_index_to_operand(rexpr, c, ind))
4256 : {
4257 166016 : matched = true; /* column is unique */
4258 166016 : break;
4259 : }
4260 : }
4261 :
4262 324830 : if (matched)
4263 166016 : continue;
4264 :
4265 158960 : forboth(lc, exprlist, lc2, oprlist)
4266 : {
4267 146 : Node *expr = (Node *) lfirst(lc);
4268 146 : Oid opr = lfirst_oid(lc2);
4269 :
4270 : /* See if the expression matches the index key */
4271 146 : if (!match_index_to_operand(expr, c, ind))
4272 146 : continue;
4273 :
4274 : /*
4275 : * The equality operator must be a member of the index
4276 : * opfamily, else it is not asserting the right kind of
4277 : * equality behavior for this index. We assume the caller
4278 : * determined it is an equality operator, so we don't need to
4279 : * check any more tightly than this.
4280 : */
4281 0 : if (!op_in_opfamily(opr, ind->opfamily[c]))
4282 0 : continue;
4283 :
4284 : /*
4285 : * XXX at some point we may need to check collations here too.
4286 : * For the moment we assume all collations reduce to the same
4287 : * notion of equality.
4288 : */
4289 :
4290 0 : matched = true; /* column is unique */
4291 0 : break;
4292 : }
4293 :
4294 158814 : if (!matched)
4295 158814 : break; /* no match; this index doesn't help us */
4296 : }
4297 :
4298 : /* Matched all key columns of this index? */
4299 261100 : if (c == ind->nkeycolumns)
4300 102286 : return true;
4301 : }
4302 :
4303 65802 : return false;
4304 : }
4305 :
4306 : /*
4307 : * indexcol_is_bool_constant_for_query
4308 : *
4309 : * If an index column is constrained to have a constant value by the query's
4310 : * WHERE conditions, then it's irrelevant for sort-order considerations.
4311 : * Usually that means we have a restriction clause WHERE indexcol = constant,
4312 : * which gets turned into an EquivalenceClass containing a constant, which
4313 : * is recognized as redundant by build_index_pathkeys(). But if the index
4314 : * column is a boolean variable (or expression), then we are not going to
4315 : * see WHERE indexcol = constant, because expression preprocessing will have
4316 : * simplified that to "WHERE indexcol" or "WHERE NOT indexcol". So we are not
4317 : * going to have a matching EquivalenceClass (unless the query also contains
4318 : * "ORDER BY indexcol"). To allow such cases to work the same as they would
4319 : * for non-boolean values, this function is provided to detect whether the
4320 : * specified index column matches a boolean restriction clause.
4321 : */
4322 : bool
4323 525232 : indexcol_is_bool_constant_for_query(PlannerInfo *root,
4324 : IndexOptInfo *index,
4325 : int indexcol)
4326 : {
4327 : ListCell *lc;
4328 :
4329 : /* If the index isn't boolean, we can't possibly get a match */
4330 525232 : if (!IsBooleanOpfamily(index->opfamily[indexcol]))
4331 523516 : return false;
4332 :
4333 : /* Check each restriction clause for the index's rel */
4334 1752 : foreach(lc, index->rel->baserestrictinfo)
4335 : {
4336 1008 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4337 :
4338 : /*
4339 : * As in match_clause_to_indexcol, never match pseudoconstants to
4340 : * indexes. (It might be semantically okay to do so here, but the
4341 : * odds of getting a match are negligible, so don't waste the cycles.)
4342 : */
4343 1008 : if (rinfo->pseudoconstant)
4344 0 : continue;
4345 :
4346 : /* See if we can match the clause's expression to the index column */
4347 1008 : if (match_boolean_index_clause(root, rinfo, indexcol, index))
4348 972 : return true;
4349 : }
4350 :
4351 744 : return false;
4352 : }
4353 :
4354 :
4355 : /****************************************************************************
4356 : * ---- ROUTINES TO CHECK OPERANDS ----
4357 : ****************************************************************************/
4358 :
4359 : /*
4360 : * match_index_to_operand()
4361 : * Generalized test for a match between an index's key
4362 : * and the operand on one side of a restriction or join clause.
4363 : *
4364 : * operand: the nodetree to be compared to the index
4365 : * indexcol: the column number of the index (counting from 0)
4366 : * index: the index of interest
4367 : *
4368 : * Note that we aren't interested in collations here; the caller must check
4369 : * for a collation match, if it's dealing with an operator where that matters.
4370 : *
4371 : * This is exported for use in selfuncs.c.
4372 : */
4373 : bool
4374 3147306 : match_index_to_operand(Node *operand,
4375 : int indexcol,
4376 : IndexOptInfo *index)
4377 : {
4378 : int indkey;
4379 :
4380 : /*
4381 : * Ignore any RelabelType node above the operand. This is needed to be
4382 : * able to apply indexscanning in binary-compatible-operator cases. Note:
4383 : * we can assume there is at most one RelabelType node;
4384 : * eval_const_expressions() will have simplified if more than one.
4385 : */
4386 3147306 : if (operand && IsA(operand, RelabelType))
4387 22616 : operand = (Node *) ((RelabelType *) operand)->arg;
4388 :
4389 3147306 : indkey = index->indexkeys[indexcol];
4390 3147306 : if (indkey != 0)
4391 : {
4392 : /*
4393 : * Simple index column; operand must be a matching Var.
4394 : */
4395 3142238 : if (operand && IsA(operand, Var) &&
4396 2323638 : index->rel->relid == ((Var *) operand)->varno &&
4397 2131052 : indkey == ((Var *) operand)->varattno &&
4398 740800 : ((Var *) operand)->varnullingrels == NULL)
4399 740062 : return true;
4400 : }
4401 : else
4402 : {
4403 : /*
4404 : * Index expression; find the correct expression. (This search could
4405 : * be avoided, at the cost of complicating all the callers of this
4406 : * routine; doesn't seem worth it.)
4407 : */
4408 : ListCell *indexpr_item;
4409 : int i;
4410 : Node *indexkey;
4411 :
4412 5068 : indexpr_item = list_head(index->indexprs);
4413 5068 : for (i = 0; i < indexcol; i++)
4414 : {
4415 0 : if (index->indexkeys[i] == 0)
4416 : {
4417 0 : if (indexpr_item == NULL)
4418 0 : elog(ERROR, "wrong number of index expressions");
4419 0 : indexpr_item = lnext(index->indexprs, indexpr_item);
4420 : }
4421 : }
4422 5068 : if (indexpr_item == NULL)
4423 0 : elog(ERROR, "wrong number of index expressions");
4424 5068 : indexkey = (Node *) lfirst(indexpr_item);
4425 :
4426 : /*
4427 : * Does it match the operand? Again, strip any relabeling.
4428 : */
4429 5068 : if (indexkey && IsA(indexkey, RelabelType))
4430 10 : indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4431 :
4432 5068 : if (equal(indexkey, operand))
4433 2062 : return true;
4434 : }
4435 :
4436 2405182 : return false;
4437 : }
4438 :
4439 : /*
4440 : * is_pseudo_constant_for_index()
4441 : * Test whether the given expression can be used as an indexscan
4442 : * comparison value.
4443 : *
4444 : * An indexscan comparison value must not contain any volatile functions,
4445 : * and it can't contain any Vars of the index's own table. Vars of
4446 : * other tables are okay, though; in that case we'd be producing an
4447 : * indexqual usable in a parameterized indexscan. This is, therefore,
4448 : * a weaker condition than is_pseudo_constant_clause().
4449 : *
4450 : * This function is exported for use by planner support functions,
4451 : * which will have available the IndexOptInfo, but not any RestrictInfo
4452 : * infrastructure. It is making the same test made by functions above
4453 : * such as match_opclause_to_indexcol(), but those rely where possible
4454 : * on RestrictInfo information about variable membership.
4455 : *
4456 : * expr: the nodetree to be checked
4457 : * index: the index of interest
4458 : */
4459 : bool
4460 0 : is_pseudo_constant_for_index(PlannerInfo *root, Node *expr, IndexOptInfo *index)
4461 : {
4462 : /* pull_varnos is cheaper than volatility check, so do that first */
4463 0 : if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
4464 0 : return false; /* no good, contains Var of table */
4465 0 : if (contain_volatile_functions(expr))
4466 0 : return false; /* no good, volatile comparison value */
4467 0 : return true;
4468 : }
|