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 464654 : 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 464654 : if (rel->indexlist == NIL)
254 68092 : return;
255 :
256 : /* Bitmap paths are collected and then dealt with at the end */
257 396562 : bitindexpaths = bitjoinpaths = joinorclauses = NIL;
258 :
259 : /* Examine each index in turn */
260 1251000 : foreach(lc, rel->indexlist)
261 : {
262 854438 : 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 854438 : if (index->indpred != NIL && !index->predOK)
273 496 : continue;
274 :
275 : /*
276 : * Identify the restriction clauses that can match the index.
277 : */
278 29034028 : MemSet(&rclauseset, 0, sizeof(rclauseset));
279 853942 : 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 853942 : 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 29034028 : MemSet(&jclauseset, 0, sizeof(jclauseset));
296 853942 : 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 29034028 : MemSet(&eclauseset, 0, sizeof(eclauseset));
304 853942 : 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 853942 : if (jclauseset.nonempty || eclauseset.nonempty)
312 236792 : 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 396562 : indexpaths = generate_bitmap_or_paths(root, rel,
324 : rel->baserestrictinfo, NIL);
325 396562 : 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 396562 : indexpaths = generate_bitmap_or_paths(root, rel,
332 : joinorclauses, rel->baserestrictinfo);
333 396562 : 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 396562 : if (bitindexpaths != NIL)
343 : {
344 : Path *bitmapqual;
345 : BitmapHeapPath *bpath;
346 :
347 258328 : bitmapqual = choose_bitmap_and(root, rel, bitindexpaths);
348 258328 : bpath = create_bitmap_heap_path(root, rel, bitmapqual,
349 : rel->lateral_relids, 1.0, 0);
350 258328 : add_path(rel, (Path *) bpath);
351 :
352 : /* create a partial bitmap heap path */
353 258328 : if (rel->consider_parallel && rel->lateral_relids == NULL)
354 204400 : 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 396562 : if (bitjoinpaths != NIL)
368 : {
369 : List *all_path_outers;
370 :
371 : /* Identify each distinct parameterization seen in bitjoinpaths */
372 203506 : all_path_outers = NIL;
373 498996 : foreach(lc, bitjoinpaths)
374 : {
375 295490 : Path *path = (Path *) lfirst(lc);
376 295490 : Relids required_outer = PATH_REQ_OUTER(path);
377 :
378 295490 : all_path_outers = list_append_unique(all_path_outers,
379 : required_outer);
380 : }
381 :
382 : /* Now, for each distinct parameterization set ... */
383 469496 : foreach(lc, all_path_outers)
384 : {
385 265990 : 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 265990 : this_path_set = NIL;
395 745106 : foreach(lcp, bitjoinpaths)
396 : {
397 479116 : Path *path = (Path *) lfirst(lcp);
398 :
399 479116 : if (bms_is_subset(PATH_REQ_OUTER(path), max_outers))
400 302238 : 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 265990 : this_path_set = list_concat(this_path_set, bitindexpaths);
408 :
409 : /* Select best AND combination for this parameterization */
410 265990 : bitmapqual = choose_bitmap_and(root, rel, this_path_set);
411 :
412 : /* And push that path into the mix */
413 265990 : required_outer = PATH_REQ_OUTER(bitmapqual);
414 265990 : loop_count = get_loop_count(root, rel->relid, required_outer);
415 265990 : bpath = create_bitmap_heap_path(root, rel, bitmapqual,
416 : required_outer, loop_count, 0);
417 265990 : 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 236792 : 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 236792 : int considered_clauses = 0;
446 236792 : 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 612340 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
471 : {
472 : /* Consider each applicable simple join clause */
473 375548 : considered_clauses += list_length(jclauseset->indexclauses[indexcol]);
474 375548 : 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 375548 : considered_clauses += list_length(eclauseset->indexclauses[indexcol]);
482 375548 : 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 236792 : }
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 751096 : 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 1069030 : foreach(lc, indexjoinclauses)
518 : {
519 317934 : IndexClause *iclause = (IndexClause *) lfirst(lc);
520 317934 : Relids clause_relids = iclause->rinfo->clause_relids;
521 317934 : 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 317934 : if (list_member(*considered_relids, clause_relids))
526 25722 : 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 292212 : num_considered_relids = list_length(*considered_relids);
542 347998 : for (int pos = 0; pos < num_considered_relids; pos++)
543 : {
544 55786 : 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 55786 : 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 111362 : if (parent_ec &&
564 55600 : eclass_already_used(parent_ec, oldrelids,
565 : indexjoinclauses))
566 52422 : 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 3340 : if (list_length(*considered_relids) >= 10 * considered_clauses)
574 0 : break;
575 :
576 : /* OK, try the union set */
577 3340 : 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 292212 : get_join_index_paths(root, rel, index,
586 : rclauseset, jclauseset, eclauseset,
587 : bitindexpaths,
588 : clause_relids,
589 : considered_relids);
590 : }
591 751096 : }
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 295552 : 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 295552 : if (list_member(*considered_relids, relids))
621 0 : return;
622 :
623 : /* Identify indexclauses usable with this relids set */
624 10048768 : MemSet(&clauseset, 0, sizeof(clauseset));
625 :
626 787268 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
627 : {
628 : ListCell *lc;
629 :
630 : /* First find applicable simple join clauses */
631 524002 : foreach(lc, jclauseset->indexclauses[indexcol])
632 : {
633 32286 : IndexClause *iclause = (IndexClause *) lfirst(lc);
634 :
635 32286 : if (bms_is_subset(iclause->rinfo->clause_relids, relids))
636 31886 : clauseset.indexclauses[indexcol] =
637 31886 : 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 575222 : foreach(lc, eclauseset->indexclauses[indexcol])
647 : {
648 376162 : IndexClause *iclause = (IndexClause *) lfirst(lc);
649 :
650 376162 : if (bms_is_subset(iclause->rinfo->clause_relids, relids))
651 : {
652 292656 : clauseset.indexclauses[indexcol] =
653 292656 : lappend(clauseset.indexclauses[indexcol], iclause);
654 292656 : break;
655 : }
656 : }
657 :
658 : /* Add restriction clauses */
659 491716 : clauseset.indexclauses[indexcol] =
660 491716 : list_concat(clauseset.indexclauses[indexcol],
661 491716 : rclauseset->indexclauses[indexcol]);
662 :
663 491716 : if (clauseset.indexclauses[indexcol] != NIL)
664 384000 : 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 295552 : get_index_paths(root, rel, index, &clauseset, bitindexpaths);
672 :
673 : /*
674 : * Remember we considered paths for this set of relids.
675 : */
676 295552 : *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 55600 : eclass_already_used(EquivalenceClass *parent_ec, Relids oldrelids,
686 : List *indexjoinclauses)
687 : {
688 : ListCell *lc;
689 :
690 59240 : foreach(lc, indexjoinclauses)
691 : {
692 56062 : IndexClause *iclause = (IndexClause *) lfirst(lc);
693 56062 : RestrictInfo *rinfo = iclause->rinfo;
694 :
695 112124 : if (rinfo->parent_ec == parent_ec &&
696 56062 : bms_is_subset(rinfo->clause_relids, oldrelids))
697 52422 : return true;
698 : }
699 3178 : 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 1149494 : get_index_paths(PlannerInfo *root, RelOptInfo *rel,
718 : IndexOptInfo *index, IndexClauseSet *clauses,
719 : List **bitindexpaths)
720 : {
721 : List *indexpaths;
722 1149494 : 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 1149494 : indexpaths = build_index_paths(root, rel,
730 : index, clauses,
731 1149494 : 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 1928156 : foreach(lc, indexpaths)
748 : {
749 778662 : IndexPath *ipath = (IndexPath *) lfirst(lc);
750 :
751 778662 : if (index->amhasgettuple)
752 765262 : add_path(rel, (Path *) ipath);
753 :
754 778662 : if (index->amhasgetbitmap &&
755 778662 : (ipath->path.pathkeys == NIL ||
756 561668 : ipath->indexselectivity < 1.0))
757 576736 : *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 1149494 : 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 1149494 : }
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 1151810 : 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 1151810 : 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 1151810 : switch (scantype)
837 : {
838 0 : case ST_INDEXSCAN:
839 0 : if (!index->amhasgettuple)
840 0 : return NIL;
841 0 : break;
842 2316 : case ST_BITMAPSCAN:
843 2316 : if (!index->amhasgetbitmap)
844 0 : return NIL;
845 2316 : break;
846 1149494 : case ST_ANYSCAN:
847 : /* either or both are OK */
848 1149494 : 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 1151810 : index_clauses = NIL;
864 1151810 : outer_relids = bms_copy(rel->lateral_relids);
865 3221462 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
866 : {
867 : ListCell *lc;
868 :
869 2761740 : foreach(lc, clauses->indexclauses[indexcol])
870 : {
871 691758 : IndexClause *iclause = (IndexClause *) lfirst(lc);
872 691758 : RestrictInfo *rinfo = iclause->rinfo;
873 :
874 691758 : if (skip_nonnative_saop && !index->amsearcharray &&
875 22026 : 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 691726 : index_clauses = lappend(index_clauses, iclause);
890 691726 : outer_relids = bms_add_members(outer_relids,
891 691726 : 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 2069982 : 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 1151480 : outer_relids = bms_del_member(outer_relids, rel->relid);
908 :
909 : /* Compute loop_count for cost estimation purposes */
910 1151480 : 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 2300644 : pathkeys_possibly_useful = (scantype != ST_BITMAPSCAN &&
918 1149164 : has_useful_pathkeys(root, rel));
919 1151480 : index_is_ordered = (index->sortopfamily != NULL);
920 1151480 : if (index_is_ordered && pathkeys_possibly_useful)
921 : {
922 948428 : index_pathkeys = build_index_pathkeys(root, index,
923 : ForwardScanDirection);
924 948428 : useful_pathkeys = truncate_useless_pathkeys(root, rel,
925 : index_pathkeys);
926 948428 : orderbyclauses = NIL;
927 948428 : orderbyclausecols = NIL;
928 : }
929 203052 : 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 201978 : useful_pathkeys = NIL;
949 201978 : orderbyclauses = NIL;
950 201978 : 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 2300644 : index_only_scan = (scantype != ST_BITMAPSCAN &&
959 1149164 : 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 1151480 : if (index_clauses != NIL || useful_pathkeys != NIL || useful_predicate ||
968 : index_only_scan)
969 : {
970 780418 : 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 780418 : 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 780418 : if (index->amcanparallel &&
987 759510 : rel->consider_parallel && outer_relids == NULL &&
988 : scantype != ST_BITMAPSCAN)
989 : {
990 394846 : 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 394846 : if (ipath->path.parallel_workers > 0)
1006 9808 : add_partial_path(rel, (Path *) ipath);
1007 : else
1008 385038 : pfree(ipath);
1009 : }
1010 : }
1011 :
1012 : /*
1013 : * 5. If the index is ordered, a backwards scan might be interesting.
1014 : */
1015 1151480 : if (index_is_ordered && pathkeys_possibly_useful)
1016 : {
1017 948428 : index_pathkeys = build_index_pathkeys(root, index,
1018 : BackwardScanDirection);
1019 948428 : useful_pathkeys = truncate_useless_pathkeys(root, rel,
1020 : index_pathkeys);
1021 948428 : 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 1151480 : 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 20796 : build_paths_for_OR(PlannerInfo *root, RelOptInfo *rel,
1094 : List *clauses, List *other_clauses)
1095 : {
1096 20796 : List *result = NIL;
1097 20796 : List *all_clauses = NIL; /* not computed till needed */
1098 : ListCell *lc;
1099 :
1100 78548 : foreach(lc, rel->indexlist)
1101 : {
1102 57752 : 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 57752 : if (!index->amhasgetbitmap)
1109 55468 : 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 57752 : useful_predicate = false;
1124 57752 : 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 1960304 : MemSet(&clauseset, 0, sizeof(clauseset));
1148 57656 : 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 57656 : if (!clauseset.nonempty && !useful_predicate)
1155 55372 : continue;
1156 :
1157 : /*
1158 : * Add "other" restriction clauses to the clauseset.
1159 : */
1160 2284 : match_clauses_to_index(root, other_clauses, index, &clauseset);
1161 :
1162 : /*
1163 : * Construct paths if possible.
1164 : */
1165 2284 : indexpaths = build_index_paths(root, rel,
1166 : index, &clauseset,
1167 : useful_predicate,
1168 : ST_BITMAPSCAN,
1169 : NULL);
1170 2284 : result = list_concat(result, indexpaths);
1171 : }
1172 :
1173 20796 : 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 6146 : or_arg_index_match_cmp(const void *a, const void *b)
1200 : {
1201 6146 : const OrArgIndexMatch *match_a = (const OrArgIndexMatch *) a;
1202 6146 : const OrArgIndexMatch *match_b = (const OrArgIndexMatch *) b;
1203 :
1204 6146 : if (match_a->indexnum < match_b->indexnum)
1205 1138 : return -1;
1206 5008 : else if (match_a->indexnum > match_b->indexnum)
1207 2598 : return 1;
1208 :
1209 2410 : if (match_a->colnum < match_b->colnum)
1210 762 : return -1;
1211 1648 : else if (match_a->colnum > match_b->colnum)
1212 24 : return 1;
1213 :
1214 1624 : if (match_a->opno < match_b->opno)
1215 18 : return -1;
1216 1606 : else if (match_a->opno > match_b->opno)
1217 42 : return 1;
1218 :
1219 1564 : if (match_a->inputcollid < match_b->inputcollid)
1220 0 : return -1;
1221 1564 : else if (match_a->inputcollid > match_b->inputcollid)
1222 0 : return 1;
1223 :
1224 1564 : if (match_a->argindex < match_b->argindex)
1225 1486 : return -1;
1226 78 : else if (match_a->argindex > match_b->argindex)
1227 78 : 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 19618 : 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 19618 : bool matched = false;
1254 : ListCell *lc;
1255 : ListCell *lc2;
1256 : List *orargs;
1257 19618 : List *result = NIL;
1258 19618 : Index relid = rel->relid;
1259 :
1260 : Assert(IsA(rinfo->orclause, BoolExpr));
1261 19618 : orargs = ((BoolExpr *) rinfo->orclause)->args;
1262 19618 : n = list_length(orargs);
1263 :
1264 : /*
1265 : * To avoid N^2 behavior, take utility pass along the list of OR-clause
1266 : * arguments. For each argument, fill the OrArgIndexMatch structure,
1267 : * which will be used to sort these arguments at the next step.
1268 : */
1269 19618 : i = -1;
1270 19618 : matches = (OrArgIndexMatch *) palloc(sizeof(OrArgIndexMatch) * n);
1271 61932 : foreach(lc, orargs)
1272 : {
1273 42314 : Node *arg = lfirst(lc);
1274 : RestrictInfo *argrinfo;
1275 : OpExpr *clause;
1276 : Oid opno;
1277 : Node *leftop,
1278 : *rightop;
1279 : Node *nonConstExpr;
1280 : int indexnum;
1281 : int colnum;
1282 :
1283 42314 : i++;
1284 42314 : matches[i].argindex = i;
1285 42314 : matches[i].indexnum = -1;
1286 42314 : matches[i].colnum = -1;
1287 42314 : matches[i].opno = InvalidOid;
1288 42314 : matches[i].inputcollid = InvalidOid;
1289 :
1290 42314 : if (!IsA(arg, RestrictInfo))
1291 1812 : continue;
1292 :
1293 40502 : argrinfo = castNode(RestrictInfo, arg);
1294 :
1295 : /* Only operator clauses can match */
1296 40502 : if (!IsA(argrinfo->clause, OpExpr))
1297 30340 : continue;
1298 :
1299 10162 : clause = (OpExpr *) argrinfo->clause;
1300 10162 : opno = clause->opno;
1301 :
1302 : /* Only binary operators can match */
1303 10162 : if (list_length(clause->args) != 2)
1304 0 : continue;
1305 :
1306 : /*
1307 : * Ignore any RelabelType node above the operands. This is needed to
1308 : * be able to apply indexscanning in binary-compatible-operator cases.
1309 : * Note: we can assume there is at most one RelabelType node;
1310 : * eval_const_expressions() will have simplified if more than one.
1311 : */
1312 10162 : leftop = get_leftop(clause);
1313 10162 : if (IsA(leftop, RelabelType))
1314 204 : leftop = (Node *) ((RelabelType *) leftop)->arg;
1315 :
1316 10162 : rightop = get_rightop(clause);
1317 10162 : if (IsA(rightop, RelabelType))
1318 696 : rightop = (Node *) ((RelabelType *) rightop)->arg;
1319 :
1320 : /*
1321 : * Check for clauses of the form: (indexkey operator constant) or
1322 : * (constant operator indexkey). But we don't know a particular index
1323 : * yet. Therefore, we try to distinguish the potential index key and
1324 : * constant first, then search for a matching index key among all
1325 : * indexes.
1326 : */
1327 10162 : if (bms_is_member(relid, argrinfo->right_relids) &&
1328 1744 : !bms_is_member(relid, argrinfo->left_relids) &&
1329 1672 : !contain_volatile_functions(leftop))
1330 : {
1331 1672 : opno = get_commutator(opno);
1332 :
1333 1672 : if (!OidIsValid(opno))
1334 : {
1335 : /* commutator doesn't exist, we can't reverse the order */
1336 0 : continue;
1337 : }
1338 1672 : nonConstExpr = rightop;
1339 : }
1340 8490 : else if (bms_is_member(relid, argrinfo->left_relids) &&
1341 6790 : !bms_is_member(relid, argrinfo->right_relids) &&
1342 6718 : !contain_volatile_functions(rightop))
1343 : {
1344 6718 : nonConstExpr = leftop;
1345 : }
1346 : else
1347 : {
1348 1772 : continue;
1349 : }
1350 :
1351 : /*
1352 : * Match non-constant part to the index key. It's possible that a
1353 : * single non-constant part matches multiple index keys. It's OK, we
1354 : * just stop with first matching index key. Given that this choice is
1355 : * determined the same for every clause, we will group similar clauses
1356 : * together anyway.
1357 : */
1358 8390 : indexnum = 0;
1359 18288 : foreach(lc2, rel->indexlist)
1360 : {
1361 14820 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc2);
1362 :
1363 : /*
1364 : * Ignore index if it doesn't support bitmap scans or SAOP
1365 : * clauses.
1366 : */
1367 14820 : if (!index->amhasgetbitmap || !index->amsearcharray)
1368 54 : continue;
1369 :
1370 33722 : for (colnum = 0; colnum < index->nkeycolumns; colnum++)
1371 : {
1372 23878 : if (match_index_to_operand(nonConstExpr, colnum, index))
1373 : {
1374 4922 : matches[i].indexnum = indexnum;
1375 4922 : matches[i].colnum = colnum;
1376 4922 : matches[i].opno = opno;
1377 4922 : matches[i].inputcollid = clause->inputcollid;
1378 4922 : matched = true;
1379 4922 : break;
1380 : }
1381 : }
1382 :
1383 : /*
1384 : * Stop looping through the indexes, if we managed to match
1385 : * nonConstExpr to any index column.
1386 : */
1387 14766 : if (matches[i].indexnum >= 0)
1388 4922 : break;
1389 9844 : indexnum++;
1390 : }
1391 : }
1392 :
1393 : /*
1394 : * Fast-path check: if no clause is matching to the index column, we can
1395 : * just give up at this stage and return the clause list as-is.
1396 : */
1397 19618 : if (!matched)
1398 : {
1399 16234 : pfree(matches);
1400 16234 : return orargs;
1401 : }
1402 :
1403 : /* Sort clauses to make similar clauses go together */
1404 3384 : qsort(matches, n, sizeof(OrArgIndexMatch), or_arg_index_match_cmp);
1405 :
1406 : /*
1407 : * Group similar clauses into single sub-restrictinfo. Side effect: the
1408 : * resulting list of restrictions will be sorted by indexnum and colnum.
1409 : */
1410 3384 : group_start = 0;
1411 11530 : for (i = 1; i <= n; i++)
1412 : {
1413 : /* Check if it's a group boundary */
1414 8146 : if (group_start >= 0 &&
1415 4762 : (i == n ||
1416 4762 : matches[i].indexnum != matches[group_start].indexnum ||
1417 2248 : matches[i].colnum != matches[group_start].colnum ||
1418 1474 : matches[i].opno != matches[group_start].opno ||
1419 1426 : matches[i].inputcollid != matches[group_start].inputcollid ||
1420 1426 : matches[i].indexnum == -1))
1421 : {
1422 : /*
1423 : * One clause in group: add it "as is" to the upper-level OR.
1424 : */
1425 7708 : if (i - group_start == 1)
1426 : {
1427 7402 : result = lappend(result,
1428 : list_nth(orargs,
1429 7402 : matches[group_start].argindex));
1430 : }
1431 : else
1432 : {
1433 : /*
1434 : * Two or more clauses in a group: create a nested OR.
1435 : */
1436 306 : List *args = NIL;
1437 306 : List *rargs = NIL;
1438 : RestrictInfo *subrinfo;
1439 : int j;
1440 :
1441 : Assert(i - group_start >= 2);
1442 :
1443 : /* Construct the list of nested OR arguments */
1444 1050 : for (j = group_start; j < i; j++)
1445 : {
1446 744 : Node *arg = list_nth(orargs, matches[j].argindex);
1447 :
1448 744 : rargs = lappend(rargs, arg);
1449 744 : if (IsA(arg, RestrictInfo))
1450 744 : args = lappend(args, ((RestrictInfo *) arg)->clause);
1451 : else
1452 0 : args = lappend(args, arg);
1453 : }
1454 :
1455 : /* Construct the nested OR and wrap it with RestrictInfo */
1456 306 : subrinfo = make_plain_restrictinfo(root,
1457 : make_orclause(args),
1458 : make_orclause(rargs),
1459 306 : rinfo->is_pushed_down,
1460 306 : rinfo->has_clone,
1461 306 : rinfo->is_clone,
1462 306 : rinfo->pseudoconstant,
1463 : rinfo->security_level,
1464 : rinfo->required_relids,
1465 : rinfo->incompatible_relids,
1466 : rinfo->outer_relids);
1467 306 : result = lappend(result, subrinfo);
1468 : }
1469 :
1470 7708 : group_start = i;
1471 : }
1472 : }
1473 3384 : pfree(matches);
1474 3384 : return result;
1475 : }
1476 :
1477 : /*
1478 : * make_bitmap_paths_for_or_group
1479 : * Generate bitmap paths for a group of similar OR-clause arguments
1480 : * produced by group_similar_or_args().
1481 : *
1482 : * This function considers two cases: (1) matching a group of clauses to
1483 : * the index as a whole, and (2) matching the individual clauses one-by-one.
1484 : * (1) typically comprises an optimal solution. If not, (2) typically
1485 : * comprises fair alternative.
1486 : *
1487 : * Ideally, we could consider all arbitrary splits of arguments into
1488 : * subgroups, but that could lead to unacceptable computational complexity.
1489 : * This is why we only consider two cases of above.
1490 : */
1491 : static List *
1492 300 : make_bitmap_paths_for_or_group(PlannerInfo *root, RelOptInfo *rel,
1493 : RestrictInfo *ri, List *other_clauses)
1494 : {
1495 300 : List *jointlist = NIL;
1496 300 : List *splitlist = NIL;
1497 : ListCell *lc;
1498 : List *orargs;
1499 300 : List *args = ((BoolExpr *) ri->orclause)->args;
1500 300 : Cost jointcost = 0.0,
1501 300 : splitcost = 0.0;
1502 : Path *bitmapqual;
1503 : List *indlist;
1504 :
1505 : /*
1506 : * First, try to match the whole group to the one index.
1507 : */
1508 300 : orargs = list_make1(ri);
1509 300 : indlist = build_paths_for_OR(root, rel,
1510 : orargs,
1511 : other_clauses);
1512 300 : if (indlist != NIL)
1513 : {
1514 294 : bitmapqual = choose_bitmap_and(root, rel, indlist);
1515 294 : jointcost = bitmapqual->total_cost;
1516 294 : jointlist = list_make1(bitmapqual);
1517 : }
1518 :
1519 : /*
1520 : * If we manage to find a bitmap scan, which uses the group of OR-clause
1521 : * arguments as a whole, we can skip matching OR-clause arguments
1522 : * one-by-one as long as there are no other clauses, which can bring more
1523 : * efficiency to one-by-one case.
1524 : */
1525 300 : if (jointlist != NIL && other_clauses == NIL)
1526 78 : return jointlist;
1527 :
1528 : /*
1529 : * Also try to match all containing clauses one-by-one.
1530 : */
1531 768 : foreach(lc, args)
1532 : {
1533 552 : orargs = list_make1(lfirst(lc));
1534 :
1535 552 : indlist = build_paths_for_OR(root, rel,
1536 : orargs,
1537 : other_clauses);
1538 :
1539 552 : if (indlist == NIL)
1540 : {
1541 6 : splitlist = NIL;
1542 6 : break;
1543 : }
1544 :
1545 546 : bitmapqual = choose_bitmap_and(root, rel, indlist);
1546 546 : splitcost += bitmapqual->total_cost;
1547 546 : splitlist = lappend(splitlist, bitmapqual);
1548 : }
1549 :
1550 : /*
1551 : * Pick the best option.
1552 : */
1553 222 : if (splitlist == NIL)
1554 6 : return jointlist;
1555 216 : else if (jointlist == NIL)
1556 0 : return splitlist;
1557 : else
1558 216 : return (jointcost < splitcost) ? jointlist : splitlist;
1559 : }
1560 :
1561 :
1562 : /*
1563 : * generate_bitmap_or_paths
1564 : * Look through the list of clauses to find OR clauses, and generate
1565 : * a BitmapOrPath for each one we can handle that way. Return a list
1566 : * of the generated BitmapOrPaths.
1567 : *
1568 : * other_clauses is a list of additional clauses that can be assumed true
1569 : * for the purpose of generating indexquals, but are not to be searched for
1570 : * ORs. (See build_paths_for_OR() for motivation.)
1571 : */
1572 : static List *
1573 794116 : generate_bitmap_or_paths(PlannerInfo *root, RelOptInfo *rel,
1574 : List *clauses, List *other_clauses)
1575 : {
1576 794116 : List *result = NIL;
1577 : List *all_clauses;
1578 : ListCell *lc;
1579 :
1580 : /*
1581 : * We can use both the current and other clauses as context for
1582 : * build_paths_for_OR; no need to remove ORs from the lists.
1583 : */
1584 794116 : all_clauses = list_concat_copy(clauses, other_clauses);
1585 :
1586 1230234 : foreach(lc, clauses)
1587 : {
1588 436118 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
1589 : List *pathlist;
1590 : Path *bitmapqual;
1591 : ListCell *j;
1592 : List *groupedArgs;
1593 436118 : List *inner_other_clauses = NIL;
1594 :
1595 : /* Ignore RestrictInfos that aren't ORs */
1596 436118 : if (!restriction_is_or_clause(rinfo))
1597 416500 : continue;
1598 :
1599 : /*
1600 : * We must be able to match at least one index to each of the arms of
1601 : * the OR, else we can't use it.
1602 : */
1603 19618 : pathlist = NIL;
1604 :
1605 : /*
1606 : * Group the similar OR-clause arguments into dedicated RestrictInfos,
1607 : * because each of those RestrictInfos has a chance to match the index
1608 : * as a whole.
1609 : */
1610 19618 : groupedArgs = group_similar_or_args(root, rel, rinfo);
1611 :
1612 19618 : if (groupedArgs != ((BoolExpr *) rinfo->orclause)->args)
1613 : {
1614 : /*
1615 : * Some parts of the rinfo were probably grouped. In this case,
1616 : * we have a set of sub-rinfos that together are an exact
1617 : * duplicate of rinfo. Thus, we need to remove the rinfo from
1618 : * other clauses. match_clauses_to_index detects duplicated
1619 : * iclauses by comparing pointers to original rinfos that would be
1620 : * different. So, we must delete rinfo to avoid de-facto
1621 : * duplicated clauses in the index clauses list.
1622 : */
1623 3384 : inner_other_clauses = list_delete(list_copy(all_clauses), rinfo);
1624 : }
1625 :
1626 21056 : foreach(j, groupedArgs)
1627 : {
1628 20244 : Node *orarg = (Node *) lfirst(j);
1629 : List *indlist;
1630 :
1631 : /* OR arguments should be ANDs or sub-RestrictInfos */
1632 20244 : if (is_andclause(orarg))
1633 : {
1634 992 : List *andargs = ((BoolExpr *) orarg)->args;
1635 :
1636 992 : indlist = build_paths_for_OR(root, rel,
1637 : andargs,
1638 : all_clauses);
1639 :
1640 : /* Recurse in case there are sub-ORs */
1641 992 : indlist = list_concat(indlist,
1642 992 : generate_bitmap_or_paths(root, rel,
1643 : andargs,
1644 : all_clauses));
1645 : }
1646 19252 : else if (restriction_is_or_clause(castNode(RestrictInfo, orarg)))
1647 : {
1648 300 : RestrictInfo *ri = castNode(RestrictInfo, orarg);
1649 :
1650 : /*
1651 : * Generate bitmap paths for the group of similar OR-clause
1652 : * arguments.
1653 : */
1654 300 : indlist = make_bitmap_paths_for_or_group(root,
1655 : rel, ri,
1656 : inner_other_clauses);
1657 :
1658 300 : if (indlist == NIL)
1659 : {
1660 6 : pathlist = NIL;
1661 6 : break;
1662 : }
1663 : else
1664 : {
1665 294 : pathlist = list_concat(pathlist, indlist);
1666 294 : continue;
1667 : }
1668 : }
1669 : else
1670 : {
1671 18952 : RestrictInfo *ri = castNode(RestrictInfo, orarg);
1672 : List *orargs;
1673 :
1674 18952 : orargs = list_make1(ri);
1675 :
1676 18952 : indlist = build_paths_for_OR(root, rel,
1677 : orargs,
1678 : all_clauses);
1679 : }
1680 :
1681 : /*
1682 : * If nothing matched this arm, we can't do anything with this OR
1683 : * clause.
1684 : */
1685 19944 : if (indlist == NIL)
1686 : {
1687 18800 : pathlist = NIL;
1688 18800 : break;
1689 : }
1690 :
1691 : /*
1692 : * OK, pick the most promising AND combination, and add it to
1693 : * pathlist.
1694 : */
1695 1144 : bitmapqual = choose_bitmap_and(root, rel, indlist);
1696 1144 : pathlist = lappend(pathlist, bitmapqual);
1697 : }
1698 :
1699 19618 : if (inner_other_clauses != NIL)
1700 1858 : list_free(inner_other_clauses);
1701 :
1702 : /*
1703 : * If we have a match for every arm, then turn them into a
1704 : * BitmapOrPath, and add to result list.
1705 : */
1706 19618 : if (pathlist != NIL)
1707 : {
1708 812 : bitmapqual = (Path *) create_bitmap_or_path(root, rel, pathlist);
1709 812 : result = lappend(result, bitmapqual);
1710 : }
1711 : }
1712 :
1713 794116 : return result;
1714 : }
1715 :
1716 :
1717 : /*
1718 : * choose_bitmap_and
1719 : * Given a nonempty list of bitmap paths, AND them into one path.
1720 : *
1721 : * This is a nontrivial decision since we can legally use any subset of the
1722 : * given path set. We want to choose a good tradeoff between selectivity
1723 : * and cost of computing the bitmap.
1724 : *
1725 : * The result is either a single one of the inputs, or a BitmapAndPath
1726 : * combining multiple inputs.
1727 : */
1728 : static Path *
1729 526302 : choose_bitmap_and(PlannerInfo *root, RelOptInfo *rel, List *paths)
1730 : {
1731 526302 : int npaths = list_length(paths);
1732 : PathClauseUsage **pathinfoarray;
1733 : PathClauseUsage *pathinfo;
1734 : List *clauselist;
1735 526302 : List *bestpaths = NIL;
1736 526302 : Cost bestcost = 0;
1737 : int i,
1738 : j;
1739 : ListCell *l;
1740 :
1741 : Assert(npaths > 0); /* else caller error */
1742 526302 : if (npaths == 1)
1743 338470 : return (Path *) linitial(paths); /* easy case */
1744 :
1745 : /*
1746 : * In theory we should consider every nonempty subset of the given paths.
1747 : * In practice that seems like overkill, given the crude nature of the
1748 : * estimates, not to mention the possible effects of higher-level AND and
1749 : * OR clauses. Moreover, it's completely impractical if there are a large
1750 : * number of paths, since the work would grow as O(2^N).
1751 : *
1752 : * As a heuristic, we first check for paths using exactly the same sets of
1753 : * WHERE clauses + index predicate conditions, and reject all but the
1754 : * cheapest-to-scan in any such group. This primarily gets rid of indexes
1755 : * that include the interesting columns but also irrelevant columns. (In
1756 : * situations where the DBA has gone overboard on creating variant
1757 : * indexes, this can make for a very large reduction in the number of
1758 : * paths considered further.)
1759 : *
1760 : * We then sort the surviving paths with the cheapest-to-scan first, and
1761 : * for each path, consider using that path alone as the basis for a bitmap
1762 : * scan. Then we consider bitmap AND scans formed from that path plus
1763 : * each subsequent (higher-cost) path, adding on a subsequent path if it
1764 : * results in a reduction in the estimated total scan cost. This means we
1765 : * consider about O(N^2) rather than O(2^N) path combinations, which is
1766 : * quite tolerable, especially given than N is usually reasonably small
1767 : * because of the prefiltering step. The cheapest of these is returned.
1768 : *
1769 : * We will only consider AND combinations in which no two indexes use the
1770 : * same WHERE clause. This is a bit of a kluge: it's needed because
1771 : * costsize.c and clausesel.c aren't very smart about redundant clauses.
1772 : * They will usually double-count the redundant clauses, producing a
1773 : * too-small selectivity that makes a redundant AND step look like it
1774 : * reduces the total cost. Perhaps someday that code will be smarter and
1775 : * we can remove this limitation. (But note that this also defends
1776 : * against flat-out duplicate input paths, which can happen because
1777 : * match_join_clauses_to_index will find the same OR join clauses that
1778 : * extract_restriction_or_clauses has pulled OR restriction clauses out
1779 : * of.)
1780 : *
1781 : * For the same reason, we reject AND combinations in which an index
1782 : * predicate clause duplicates another clause. Here we find it necessary
1783 : * to be even stricter: we'll reject a partial index if any of its
1784 : * predicate clauses are implied by the set of WHERE clauses and predicate
1785 : * clauses used so far. This covers cases such as a condition "x = 42"
1786 : * used with a plain index, followed by a clauseless scan of a partial
1787 : * index "WHERE x >= 40 AND x < 50". The partial index has been accepted
1788 : * only because "x = 42" was present, and so allowing it would partially
1789 : * double-count selectivity. (We could use predicate_implied_by on
1790 : * regular qual clauses too, to have a more intelligent, but much more
1791 : * expensive, check for redundancy --- but in most cases simple equality
1792 : * seems to suffice.)
1793 : */
1794 :
1795 : /*
1796 : * Extract clause usage info and detect any paths that use exactly the
1797 : * same set of clauses; keep only the cheapest-to-scan of any such groups.
1798 : * The surviving paths are put into an array for qsort'ing.
1799 : */
1800 : pathinfoarray = (PathClauseUsage **)
1801 187832 : palloc(npaths * sizeof(PathClauseUsage *));
1802 187832 : clauselist = NIL;
1803 187832 : npaths = 0;
1804 585780 : foreach(l, paths)
1805 : {
1806 397948 : Path *ipath = (Path *) lfirst(l);
1807 :
1808 397948 : pathinfo = classify_index_clause_usage(ipath, &clauselist);
1809 :
1810 : /* If it's unclassifiable, treat it as distinct from all others */
1811 397948 : if (pathinfo->unclassifiable)
1812 : {
1813 0 : pathinfoarray[npaths++] = pathinfo;
1814 0 : continue;
1815 : }
1816 :
1817 597232 : for (i = 0; i < npaths; i++)
1818 : {
1819 464776 : if (!pathinfoarray[i]->unclassifiable &&
1820 232388 : bms_equal(pathinfo->clauseids, pathinfoarray[i]->clauseids))
1821 33104 : break;
1822 : }
1823 397948 : if (i < npaths)
1824 : {
1825 : /* duplicate clauseids, keep the cheaper one */
1826 : Cost ncost;
1827 : Cost ocost;
1828 : Selectivity nselec;
1829 : Selectivity oselec;
1830 :
1831 33104 : cost_bitmap_tree_node(pathinfo->path, &ncost, &nselec);
1832 33104 : cost_bitmap_tree_node(pathinfoarray[i]->path, &ocost, &oselec);
1833 33104 : if (ncost < ocost)
1834 5144 : pathinfoarray[i] = pathinfo;
1835 : }
1836 : else
1837 : {
1838 : /* not duplicate clauseids, add to array */
1839 364844 : pathinfoarray[npaths++] = pathinfo;
1840 : }
1841 : }
1842 :
1843 : /* If only one surviving path, we're done */
1844 187832 : if (npaths == 1)
1845 24750 : return pathinfoarray[0]->path;
1846 :
1847 : /* Sort the surviving paths by index access cost */
1848 163082 : qsort(pathinfoarray, npaths, sizeof(PathClauseUsage *),
1849 : path_usage_comparator);
1850 :
1851 : /*
1852 : * For each surviving index, consider it as an "AND group leader", and see
1853 : * whether adding on any of the later indexes results in an AND path with
1854 : * cheaper total cost than before. Then take the cheapest AND group.
1855 : *
1856 : * Note: paths that are either clauseless or unclassifiable will have
1857 : * empty clauseids, so that they will not be rejected by the clauseids
1858 : * filter here, nor will they cause later paths to be rejected by it.
1859 : */
1860 503176 : for (i = 0; i < npaths; i++)
1861 : {
1862 : Cost costsofar;
1863 : List *qualsofar;
1864 : Bitmapset *clauseidsofar;
1865 :
1866 340094 : pathinfo = pathinfoarray[i];
1867 340094 : paths = list_make1(pathinfo->path);
1868 340094 : costsofar = bitmap_scan_cost_est(root, rel, pathinfo->path);
1869 340094 : qualsofar = list_concat_copy(pathinfo->quals, pathinfo->preds);
1870 340094 : clauseidsofar = bms_copy(pathinfo->clauseids);
1871 :
1872 531474 : for (j = i + 1; j < npaths; j++)
1873 : {
1874 : Cost newcost;
1875 :
1876 191380 : pathinfo = pathinfoarray[j];
1877 : /* Check for redundancy */
1878 191380 : if (bms_overlap(pathinfo->clauseids, clauseidsofar))
1879 86522 : continue; /* consider it redundant */
1880 104858 : if (pathinfo->preds)
1881 : {
1882 24 : bool redundant = false;
1883 :
1884 : /* we check each predicate clause separately */
1885 24 : foreach(l, pathinfo->preds)
1886 : {
1887 24 : Node *np = (Node *) lfirst(l);
1888 :
1889 24 : if (predicate_implied_by(list_make1(np), qualsofar, false))
1890 : {
1891 24 : redundant = true;
1892 24 : break; /* out of inner foreach loop */
1893 : }
1894 : }
1895 24 : if (redundant)
1896 24 : continue;
1897 : }
1898 : /* tentatively add new path to paths, so we can estimate cost */
1899 104834 : paths = lappend(paths, pathinfo->path);
1900 104834 : newcost = bitmap_and_cost_est(root, rel, paths);
1901 104834 : if (newcost < costsofar)
1902 : {
1903 : /* keep new path in paths, update subsidiary variables */
1904 206 : costsofar = newcost;
1905 206 : qualsofar = list_concat(qualsofar, pathinfo->quals);
1906 206 : qualsofar = list_concat(qualsofar, pathinfo->preds);
1907 206 : clauseidsofar = bms_add_members(clauseidsofar,
1908 206 : pathinfo->clauseids);
1909 : }
1910 : else
1911 : {
1912 : /* reject new path, remove it from paths list */
1913 104628 : paths = list_truncate(paths, list_length(paths) - 1);
1914 : }
1915 : }
1916 :
1917 : /* Keep the cheapest AND-group (or singleton) */
1918 340094 : if (i == 0 || costsofar < bestcost)
1919 : {
1920 201648 : bestpaths = paths;
1921 201648 : bestcost = costsofar;
1922 : }
1923 :
1924 : /* some easy cleanup (we don't try real hard though) */
1925 340094 : list_free(qualsofar);
1926 : }
1927 :
1928 163082 : if (list_length(bestpaths) == 1)
1929 162900 : return (Path *) linitial(bestpaths); /* no need for AND */
1930 182 : return (Path *) create_bitmap_and_path(root, rel, bestpaths);
1931 : }
1932 :
1933 : /* qsort comparator to sort in increasing index access cost order */
1934 : static int
1935 186276 : path_usage_comparator(const void *a, const void *b)
1936 : {
1937 186276 : PathClauseUsage *pa = *(PathClauseUsage *const *) a;
1938 186276 : PathClauseUsage *pb = *(PathClauseUsage *const *) b;
1939 : Cost acost;
1940 : Cost bcost;
1941 : Selectivity aselec;
1942 : Selectivity bselec;
1943 :
1944 186276 : cost_bitmap_tree_node(pa->path, &acost, &aselec);
1945 186276 : cost_bitmap_tree_node(pb->path, &bcost, &bselec);
1946 :
1947 : /*
1948 : * If costs are the same, sort by selectivity.
1949 : */
1950 186276 : if (acost < bcost)
1951 80566 : return -1;
1952 105710 : if (acost > bcost)
1953 59116 : return 1;
1954 :
1955 46594 : if (aselec < bselec)
1956 4472 : return -1;
1957 42122 : if (aselec > bselec)
1958 1146 : return 1;
1959 :
1960 40976 : return 0;
1961 : }
1962 :
1963 : /*
1964 : * Estimate the cost of actually executing a bitmap scan with a single
1965 : * index path (which could be a BitmapAnd or BitmapOr node).
1966 : */
1967 : static Cost
1968 444928 : bitmap_scan_cost_est(PlannerInfo *root, RelOptInfo *rel, Path *ipath)
1969 : {
1970 : BitmapHeapPath bpath;
1971 :
1972 : /* Set up a dummy BitmapHeapPath */
1973 444928 : bpath.path.type = T_BitmapHeapPath;
1974 444928 : bpath.path.pathtype = T_BitmapHeapScan;
1975 444928 : bpath.path.parent = rel;
1976 444928 : bpath.path.pathtarget = rel->reltarget;
1977 444928 : bpath.path.param_info = ipath->param_info;
1978 444928 : bpath.path.pathkeys = NIL;
1979 444928 : bpath.bitmapqual = ipath;
1980 :
1981 : /*
1982 : * Check the cost of temporary path without considering parallelism.
1983 : * Parallel bitmap heap path will be considered at later stage.
1984 : */
1985 444928 : bpath.path.parallel_workers = 0;
1986 :
1987 : /* Now we can do cost_bitmap_heap_scan */
1988 444928 : cost_bitmap_heap_scan(&bpath.path, root, rel,
1989 : bpath.path.param_info,
1990 : ipath,
1991 : get_loop_count(root, rel->relid,
1992 444928 : PATH_REQ_OUTER(ipath)));
1993 :
1994 444928 : return bpath.path.total_cost;
1995 : }
1996 :
1997 : /*
1998 : * Estimate the cost of actually executing a BitmapAnd scan with the given
1999 : * inputs.
2000 : */
2001 : static Cost
2002 104834 : bitmap_and_cost_est(PlannerInfo *root, RelOptInfo *rel, List *paths)
2003 : {
2004 : BitmapAndPath *apath;
2005 :
2006 : /*
2007 : * Might as well build a real BitmapAndPath here, as the work is slightly
2008 : * too complicated to be worth repeating just to save one palloc.
2009 : */
2010 104834 : apath = create_bitmap_and_path(root, rel, paths);
2011 :
2012 104834 : return bitmap_scan_cost_est(root, rel, (Path *) apath);
2013 : }
2014 :
2015 :
2016 : /*
2017 : * classify_index_clause_usage
2018 : * Construct a PathClauseUsage struct describing the WHERE clauses and
2019 : * index predicate clauses used by the given indexscan path.
2020 : * We consider two clauses the same if they are equal().
2021 : *
2022 : * At some point we might want to migrate this info into the Path data
2023 : * structure proper, but for the moment it's only needed within
2024 : * choose_bitmap_and().
2025 : *
2026 : * *clauselist is used and expanded as needed to identify all the distinct
2027 : * clauses seen across successive calls. Caller must initialize it to NIL
2028 : * before first call of a set.
2029 : */
2030 : static PathClauseUsage *
2031 397948 : classify_index_clause_usage(Path *path, List **clauselist)
2032 : {
2033 : PathClauseUsage *result;
2034 : Bitmapset *clauseids;
2035 : ListCell *lc;
2036 :
2037 397948 : result = (PathClauseUsage *) palloc(sizeof(PathClauseUsage));
2038 397948 : result->path = path;
2039 :
2040 : /* Recursively find the quals and preds used by the path */
2041 397948 : result->quals = NIL;
2042 397948 : result->preds = NIL;
2043 397948 : find_indexpath_quals(path, &result->quals, &result->preds);
2044 :
2045 : /*
2046 : * Some machine-generated queries have outlandish numbers of qual clauses.
2047 : * To avoid getting into O(N^2) behavior even in this preliminary
2048 : * classification step, we want to limit the number of entries we can
2049 : * accumulate in *clauselist. Treat any path with more than 100 quals +
2050 : * preds as unclassifiable, which will cause calling code to consider it
2051 : * distinct from all other paths.
2052 : */
2053 397948 : if (list_length(result->quals) + list_length(result->preds) > 100)
2054 : {
2055 0 : result->clauseids = NULL;
2056 0 : result->unclassifiable = true;
2057 0 : return result;
2058 : }
2059 :
2060 : /* Build up a bitmapset representing the quals and preds */
2061 397948 : clauseids = NULL;
2062 890912 : foreach(lc, result->quals)
2063 : {
2064 492964 : Node *node = (Node *) lfirst(lc);
2065 :
2066 492964 : clauseids = bms_add_member(clauseids,
2067 : find_list_position(node, clauselist));
2068 : }
2069 398242 : foreach(lc, result->preds)
2070 : {
2071 294 : Node *node = (Node *) lfirst(lc);
2072 :
2073 294 : clauseids = bms_add_member(clauseids,
2074 : find_list_position(node, clauselist));
2075 : }
2076 397948 : result->clauseids = clauseids;
2077 397948 : result->unclassifiable = false;
2078 :
2079 397948 : return result;
2080 : }
2081 :
2082 :
2083 : /*
2084 : * find_indexpath_quals
2085 : *
2086 : * Given the Path structure for a plain or bitmap indexscan, extract lists
2087 : * of all the index clauses and index predicate conditions used in the Path.
2088 : * These are appended to the initial contents of *quals and *preds (hence
2089 : * caller should initialize those to NIL).
2090 : *
2091 : * Note we are not trying to produce an accurate representation of the AND/OR
2092 : * semantics of the Path, but just find out all the base conditions used.
2093 : *
2094 : * The result lists contain pointers to the expressions used in the Path,
2095 : * but all the list cells are freshly built, so it's safe to destructively
2096 : * modify the lists (eg, by concat'ing with other lists).
2097 : */
2098 : static void
2099 399474 : find_indexpath_quals(Path *bitmapqual, List **quals, List **preds)
2100 : {
2101 399474 : if (IsA(bitmapqual, BitmapAndPath))
2102 : {
2103 0 : BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
2104 : ListCell *l;
2105 :
2106 0 : foreach(l, apath->bitmapquals)
2107 : {
2108 0 : find_indexpath_quals((Path *) lfirst(l), quals, preds);
2109 : }
2110 : }
2111 399474 : else if (IsA(bitmapqual, BitmapOrPath))
2112 : {
2113 862 : BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
2114 : ListCell *l;
2115 :
2116 2388 : foreach(l, opath->bitmapquals)
2117 : {
2118 1526 : find_indexpath_quals((Path *) lfirst(l), quals, preds);
2119 : }
2120 : }
2121 398612 : else if (IsA(bitmapqual, IndexPath))
2122 : {
2123 398612 : IndexPath *ipath = (IndexPath *) bitmapqual;
2124 : ListCell *l;
2125 :
2126 891576 : foreach(l, ipath->indexclauses)
2127 : {
2128 492964 : IndexClause *iclause = (IndexClause *) lfirst(l);
2129 :
2130 492964 : *quals = lappend(*quals, iclause->rinfo->clause);
2131 : }
2132 398612 : *preds = list_concat(*preds, ipath->indexinfo->indpred);
2133 : }
2134 : else
2135 0 : elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
2136 399474 : }
2137 :
2138 :
2139 : /*
2140 : * find_list_position
2141 : * Return the given node's position (counting from 0) in the given
2142 : * list of nodes. If it's not equal() to any existing list member,
2143 : * add it at the end, and return that position.
2144 : */
2145 : static int
2146 493258 : find_list_position(Node *node, List **nodelist)
2147 : {
2148 : int i;
2149 : ListCell *lc;
2150 :
2151 493258 : i = 0;
2152 721572 : foreach(lc, *nodelist)
2153 : {
2154 350376 : Node *oldnode = (Node *) lfirst(lc);
2155 :
2156 350376 : if (equal(node, oldnode))
2157 122062 : return i;
2158 228314 : i++;
2159 : }
2160 :
2161 371196 : *nodelist = lappend(*nodelist, node);
2162 :
2163 371196 : return i;
2164 : }
2165 :
2166 :
2167 : /*
2168 : * check_index_only
2169 : * Determine whether an index-only scan is possible for this index.
2170 : */
2171 : static bool
2172 1149164 : check_index_only(RelOptInfo *rel, IndexOptInfo *index)
2173 : {
2174 : bool result;
2175 1149164 : Bitmapset *attrs_used = NULL;
2176 1149164 : Bitmapset *index_canreturn_attrs = NULL;
2177 : ListCell *lc;
2178 : int i;
2179 :
2180 : /* Index-only scans must be enabled */
2181 1149164 : if (!enable_indexonlyscan)
2182 3688 : return false;
2183 :
2184 : /*
2185 : * Check that all needed attributes of the relation are available from the
2186 : * index.
2187 : */
2188 :
2189 : /*
2190 : * First, identify all the attributes needed for joins or final output.
2191 : * Note: we must look at rel's targetlist, not the attr_needed data,
2192 : * because attr_needed isn't computed for inheritance child rels.
2193 : */
2194 1145476 : pull_varattnos((Node *) rel->reltarget->exprs, rel->relid, &attrs_used);
2195 :
2196 : /*
2197 : * Add all the attributes used by restriction clauses; but consider only
2198 : * those clauses not implied by the index predicate, since ones that are
2199 : * so implied don't need to be checked explicitly in the plan.
2200 : *
2201 : * Note: attributes used only in index quals would not be needed at
2202 : * runtime either, if we are certain that the index is not lossy. However
2203 : * it'd be complicated to account for that accurately, and it doesn't
2204 : * matter in most cases, since we'd conclude that such attributes are
2205 : * available from the index anyway.
2206 : */
2207 2382874 : foreach(lc, index->indrestrictinfo)
2208 : {
2209 1237398 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2210 :
2211 1237398 : pull_varattnos((Node *) rinfo->clause, rel->relid, &attrs_used);
2212 : }
2213 :
2214 : /*
2215 : * Construct a bitmapset of columns that the index can return back in an
2216 : * index-only scan.
2217 : */
2218 3207448 : for (i = 0; i < index->ncolumns; i++)
2219 : {
2220 2061972 : int attno = index->indexkeys[i];
2221 :
2222 : /*
2223 : * For the moment, we just ignore index expressions. It might be nice
2224 : * to do something with them, later.
2225 : */
2226 2061972 : if (attno == 0)
2227 3274 : continue;
2228 :
2229 2058698 : if (index->canreturn[i])
2230 : index_canreturn_attrs =
2231 1783324 : bms_add_member(index_canreturn_attrs,
2232 : attno - FirstLowInvalidHeapAttributeNumber);
2233 : }
2234 :
2235 : /* Do we have all the necessary attributes? */
2236 1145476 : result = bms_is_subset(attrs_used, index_canreturn_attrs);
2237 :
2238 1145476 : bms_free(attrs_used);
2239 1145476 : bms_free(index_canreturn_attrs);
2240 :
2241 1145476 : return result;
2242 : }
2243 :
2244 : /*
2245 : * get_loop_count
2246 : * Choose the loop count estimate to use for costing a parameterized path
2247 : * with the given set of outer relids.
2248 : *
2249 : * Since we produce parameterized paths before we've begun to generate join
2250 : * relations, it's impossible to predict exactly how many times a parameterized
2251 : * path will be iterated; we don't know the size of the relation that will be
2252 : * on the outside of the nestloop. However, we should try to account for
2253 : * multiple iterations somehow in costing the path. The heuristic embodied
2254 : * here is to use the rowcount of the smallest other base relation needed in
2255 : * the join clauses used by the path. (We could alternatively consider the
2256 : * largest one, but that seems too optimistic.) This is of course the right
2257 : * answer for single-other-relation cases, and it seems like a reasonable
2258 : * zero-order approximation for multiway-join cases.
2259 : *
2260 : * In addition, we check to see if the other side of each join clause is on
2261 : * the inside of some semijoin that the current relation is on the outside of.
2262 : * If so, the only way that a parameterized path could be used is if the
2263 : * semijoin RHS has been unique-ified, so we should use the number of unique
2264 : * RHS rows rather than using the relation's raw rowcount.
2265 : *
2266 : * Note: for this to work, allpaths.c must establish all baserel size
2267 : * estimates before it begins to compute paths, or at least before it
2268 : * calls create_index_paths().
2269 : */
2270 : static double
2271 1862398 : get_loop_count(PlannerInfo *root, Index cur_relid, Relids outer_relids)
2272 : {
2273 : double result;
2274 : int outer_relid;
2275 :
2276 : /* For a non-parameterized path, just return 1.0 quickly */
2277 1862398 : if (outer_relids == NULL)
2278 1115168 : return 1.0;
2279 :
2280 747230 : result = 0.0;
2281 747230 : outer_relid = -1;
2282 1505148 : while ((outer_relid = bms_next_member(outer_relids, outer_relid)) >= 0)
2283 : {
2284 : RelOptInfo *outer_rel;
2285 : double rowcount;
2286 :
2287 : /* Paranoia: ignore bogus relid indexes */
2288 757918 : if (outer_relid >= root->simple_rel_array_size)
2289 0 : continue;
2290 757918 : outer_rel = root->simple_rel_array[outer_relid];
2291 757918 : if (outer_rel == NULL)
2292 254 : continue;
2293 : Assert(outer_rel->relid == outer_relid); /* sanity check on array */
2294 :
2295 : /* Other relation could be proven empty, if so ignore */
2296 757664 : if (IS_DUMMY_REL(outer_rel))
2297 24 : continue;
2298 :
2299 : /* Otherwise, rel's rows estimate should be valid by now */
2300 : Assert(outer_rel->rows > 0);
2301 :
2302 : /* Check to see if rel is on the inside of any semijoins */
2303 757640 : rowcount = adjust_rowcount_for_semijoins(root,
2304 : cur_relid,
2305 : outer_relid,
2306 : outer_rel->rows);
2307 :
2308 : /* Remember smallest row count estimate among the outer rels */
2309 757640 : if (result == 0.0 || result > rowcount)
2310 753980 : result = rowcount;
2311 : }
2312 : /* Return 1.0 if we found no valid relations (shouldn't happen) */
2313 747230 : return (result > 0.0) ? result : 1.0;
2314 : }
2315 :
2316 : /*
2317 : * Check to see if outer_relid is on the inside of any semijoin that cur_relid
2318 : * is on the outside of. If so, replace rowcount with the estimated number of
2319 : * unique rows from the semijoin RHS (assuming that's smaller, which it might
2320 : * not be). The estimate is crude but it's the best we can do at this stage
2321 : * of the proceedings.
2322 : */
2323 : static double
2324 757640 : adjust_rowcount_for_semijoins(PlannerInfo *root,
2325 : Index cur_relid,
2326 : Index outer_relid,
2327 : double rowcount)
2328 : {
2329 : ListCell *lc;
2330 :
2331 954536 : foreach(lc, root->join_info_list)
2332 : {
2333 196896 : SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
2334 :
2335 203364 : if (sjinfo->jointype == JOIN_SEMI &&
2336 8770 : bms_is_member(cur_relid, sjinfo->syn_lefthand) &&
2337 2302 : bms_is_member(outer_relid, sjinfo->syn_righthand))
2338 : {
2339 : /* Estimate number of unique-ified rows */
2340 : double nraw;
2341 : double nunique;
2342 :
2343 872 : nraw = approximate_joinrel_size(root, sjinfo->syn_righthand);
2344 872 : nunique = estimate_num_groups(root,
2345 : sjinfo->semi_rhs_exprs,
2346 : nraw,
2347 : NULL,
2348 : NULL);
2349 872 : if (rowcount > nunique)
2350 354 : rowcount = nunique;
2351 : }
2352 : }
2353 757640 : return rowcount;
2354 : }
2355 :
2356 : /*
2357 : * Make an approximate estimate of the size of a joinrel.
2358 : *
2359 : * We don't have enough info at this point to get a good estimate, so we
2360 : * just multiply the base relation sizes together. Fortunately, this is
2361 : * the right answer anyway for the most common case with a single relation
2362 : * on the RHS of a semijoin. Also, estimate_num_groups() has only a weak
2363 : * dependency on its input_rows argument (it basically uses it as a clamp).
2364 : * So we might be able to get a fairly decent end result even with a severe
2365 : * overestimate of the RHS's raw size.
2366 : */
2367 : static double
2368 872 : approximate_joinrel_size(PlannerInfo *root, Relids relids)
2369 : {
2370 872 : double rowcount = 1.0;
2371 : int relid;
2372 :
2373 872 : relid = -1;
2374 1900 : while ((relid = bms_next_member(relids, relid)) >= 0)
2375 : {
2376 : RelOptInfo *rel;
2377 :
2378 : /* Paranoia: ignore bogus relid indexes */
2379 1028 : if (relid >= root->simple_rel_array_size)
2380 0 : continue;
2381 1028 : rel = root->simple_rel_array[relid];
2382 1028 : if (rel == NULL)
2383 0 : continue;
2384 : Assert(rel->relid == relid); /* sanity check on array */
2385 :
2386 : /* Relation could be proven empty, if so ignore */
2387 1028 : if (IS_DUMMY_REL(rel))
2388 0 : continue;
2389 :
2390 : /* Otherwise, rel's rows estimate should be valid by now */
2391 : Assert(rel->rows > 0);
2392 :
2393 : /* Accumulate product */
2394 1028 : rowcount *= rel->rows;
2395 : }
2396 872 : return rowcount;
2397 : }
2398 :
2399 :
2400 : /****************************************************************************
2401 : * ---- ROUTINES TO CHECK QUERY CLAUSES ----
2402 : ****************************************************************************/
2403 :
2404 : /*
2405 : * match_restriction_clauses_to_index
2406 : * Identify restriction clauses for the rel that match the index.
2407 : * Matching clauses are added to *clauseset.
2408 : */
2409 : static void
2410 853942 : match_restriction_clauses_to_index(PlannerInfo *root,
2411 : IndexOptInfo *index,
2412 : IndexClauseSet *clauseset)
2413 : {
2414 : /* We can ignore clauses that are implied by the index predicate */
2415 853942 : match_clauses_to_index(root, index->indrestrictinfo, index, clauseset);
2416 853942 : }
2417 :
2418 : /*
2419 : * match_join_clauses_to_index
2420 : * Identify join clauses for the rel that match the index.
2421 : * Matching clauses are added to *clauseset.
2422 : * Also, add any potentially usable join OR clauses to *joinorclauses.
2423 : * They also might be processed by match_clause_to_index() as a whole.
2424 : */
2425 : static void
2426 853942 : match_join_clauses_to_index(PlannerInfo *root,
2427 : RelOptInfo *rel, IndexOptInfo *index,
2428 : IndexClauseSet *clauseset,
2429 : List **joinorclauses)
2430 : {
2431 : ListCell *lc;
2432 :
2433 : /* Scan the rel's join clauses */
2434 1138622 : foreach(lc, rel->joininfo)
2435 : {
2436 284680 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
2437 :
2438 : /* Check if clause can be moved to this rel */
2439 284680 : if (!join_clause_is_movable_to(rinfo, rel))
2440 136874 : continue;
2441 :
2442 : /*
2443 : * Potentially usable, so see if it matches the index or is an OR. Use
2444 : * list_append_unique_ptr() here to avoid possible duplicates when
2445 : * processing the same clauses with different indexes.
2446 : */
2447 147806 : if (restriction_is_or_clause(rinfo))
2448 11424 : *joinorclauses = list_append_unique_ptr(*joinorclauses, rinfo);
2449 :
2450 147806 : match_clause_to_index(root, rinfo, index, clauseset);
2451 : }
2452 853942 : }
2453 :
2454 : /*
2455 : * match_eclass_clauses_to_index
2456 : * Identify EquivalenceClass join clauses for the rel that match the index.
2457 : * Matching clauses are added to *clauseset.
2458 : */
2459 : static void
2460 853942 : match_eclass_clauses_to_index(PlannerInfo *root, IndexOptInfo *index,
2461 : IndexClauseSet *clauseset)
2462 : {
2463 : int indexcol;
2464 :
2465 : /* No work if rel is not in any such ECs */
2466 853942 : if (!index->rel->has_eclass_joins)
2467 377398 : return;
2468 :
2469 1233152 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2470 : {
2471 : ec_member_matches_arg arg;
2472 : List *clauses;
2473 :
2474 : /* Generate clauses, skipping any that join to lateral_referencers */
2475 756608 : arg.index = index;
2476 756608 : arg.indexcol = indexcol;
2477 756608 : clauses = generate_implied_equalities_for_column(root,
2478 : index->rel,
2479 : ec_member_matches_indexcol,
2480 : &arg,
2481 756608 : index->rel->lateral_referencers);
2482 :
2483 : /*
2484 : * We have to check whether the results actually do match the index,
2485 : * since for non-btree indexes the EC's equality operators might not
2486 : * be in the index opclass (cf ec_member_matches_indexcol).
2487 : */
2488 756608 : match_clauses_to_index(root, clauses, index, clauseset);
2489 : }
2490 : }
2491 :
2492 : /*
2493 : * match_clauses_to_index
2494 : * Perform match_clause_to_index() for each clause in a list.
2495 : * Matching clauses are added to *clauseset.
2496 : */
2497 : static void
2498 1670490 : match_clauses_to_index(PlannerInfo *root,
2499 : List *clauses,
2500 : IndexOptInfo *index,
2501 : IndexClauseSet *clauseset)
2502 : {
2503 : ListCell *lc;
2504 :
2505 3000630 : foreach(lc, clauses)
2506 : {
2507 1330140 : RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
2508 :
2509 1330140 : match_clause_to_index(root, rinfo, index, clauseset);
2510 : }
2511 1670490 : }
2512 :
2513 : /*
2514 : * match_clause_to_index
2515 : * Test whether a qual clause can be used with an index.
2516 : *
2517 : * If the clause is usable, add an IndexClause entry for it to the appropriate
2518 : * list in *clauseset. (*clauseset must be initialized to zeroes before first
2519 : * call.)
2520 : *
2521 : * Note: in some circumstances we may find the same RestrictInfos coming from
2522 : * multiple places. Defend against redundant outputs by refusing to add a
2523 : * clause twice (pointer equality should be a good enough check for this).
2524 : *
2525 : * Note: it's possible that a badly-defined index could have multiple matching
2526 : * columns. We always select the first match if so; this avoids scenarios
2527 : * wherein we get an inflated idea of the index's selectivity by using the
2528 : * same clause multiple times with different index columns.
2529 : */
2530 : static void
2531 1477946 : match_clause_to_index(PlannerInfo *root,
2532 : RestrictInfo *rinfo,
2533 : IndexOptInfo *index,
2534 : IndexClauseSet *clauseset)
2535 : {
2536 : int indexcol;
2537 :
2538 : /*
2539 : * Never match pseudoconstants to indexes. (Normally a match could not
2540 : * happen anyway, since a pseudoconstant clause couldn't contain a Var,
2541 : * but what if someone builds an expression index on a constant? It's not
2542 : * totally unreasonable to do so with a partial index, either.)
2543 : */
2544 1477946 : if (rinfo->pseudoconstant)
2545 12948 : return;
2546 :
2547 : /*
2548 : * If clause can't be used as an indexqual because it must wait till after
2549 : * some lower-security-level restriction clause, reject it.
2550 : */
2551 1464998 : if (!restriction_is_securely_promotable(rinfo, index->rel))
2552 474 : return;
2553 :
2554 : /* OK, check each index key column for a match */
2555 3081030 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
2556 : {
2557 : IndexClause *iclause;
2558 : ListCell *lc;
2559 :
2560 : /* Ignore duplicates */
2561 2399944 : foreach(lc, clauseset->indexclauses[indexcol])
2562 : {
2563 158442 : iclause = (IndexClause *) lfirst(lc);
2564 :
2565 158442 : if (iclause->rinfo == rinfo)
2566 0 : return;
2567 : }
2568 :
2569 : /* OK, try to match the clause to the index column */
2570 2241502 : iclause = match_clause_to_indexcol(root,
2571 : rinfo,
2572 : indexcol,
2573 : index);
2574 2241502 : if (iclause)
2575 : {
2576 : /* Success, so record it */
2577 624996 : clauseset->indexclauses[indexcol] =
2578 624996 : lappend(clauseset->indexclauses[indexcol], iclause);
2579 624996 : clauseset->nonempty = true;
2580 624996 : return;
2581 : }
2582 : }
2583 : }
2584 :
2585 : /*
2586 : * match_clause_to_indexcol()
2587 : * Determine whether a restriction clause matches a column of an index,
2588 : * and if so, build an IndexClause node describing the details.
2589 : *
2590 : * To match an index normally, an operator clause:
2591 : *
2592 : * (1) must be in the form (indexkey op const) or (const op indexkey);
2593 : * and
2594 : * (2) must contain an operator which is in the index's operator family
2595 : * for this column; and
2596 : * (3) must match the collation of the index, if collation is relevant.
2597 : *
2598 : * Our definition of "const" is exceedingly liberal: we allow anything that
2599 : * doesn't involve a volatile function or a Var of the index's relation.
2600 : * In particular, Vars belonging to other relations of the query are
2601 : * accepted here, since a clause of that form can be used in a
2602 : * parameterized indexscan. It's the responsibility of higher code levels
2603 : * to manage restriction and join clauses appropriately.
2604 : *
2605 : * Note: we do need to check for Vars of the index's relation on the
2606 : * "const" side of the clause, since clauses like (a.f1 OP (b.f2 OP a.f3))
2607 : * are not processable by a parameterized indexscan on a.f1, whereas
2608 : * something like (a.f1 OP (b.f2 OP c.f3)) is.
2609 : *
2610 : * Presently, the executor can only deal with indexquals that have the
2611 : * indexkey on the left, so we can only use clauses that have the indexkey
2612 : * on the right if we can commute the clause to put the key on the left.
2613 : * We handle that by generating an IndexClause with the correctly-commuted
2614 : * opclause as a derived indexqual.
2615 : *
2616 : * If the index has a collation, the clause must have the same collation.
2617 : * For collation-less indexes, we assume it doesn't matter; this is
2618 : * necessary for cases like "hstore ? text", wherein hstore's operators
2619 : * don't care about collation but the clause will get marked with a
2620 : * collation anyway because of the text argument. (This logic is
2621 : * embodied in the macro IndexCollMatchesExprColl.)
2622 : *
2623 : * It is also possible to match RowCompareExpr clauses to indexes (but
2624 : * currently, only btree indexes handle this).
2625 : *
2626 : * It is also possible to match ScalarArrayOpExpr clauses to indexes, when
2627 : * the clause is of the form "indexkey op ANY (arrayconst)".
2628 : *
2629 : * It is also possible to match a list of OR clauses if it might be
2630 : * transformed into a single ScalarArrayOpExpr clause. On success,
2631 : * the returning index clause will contain a transformed clause.
2632 : *
2633 : * For boolean indexes, it is also possible to match the clause directly
2634 : * to the indexkey; or perhaps the clause is (NOT indexkey).
2635 : *
2636 : * And, last but not least, some operators and functions can be processed
2637 : * to derive (typically lossy) indexquals from a clause that isn't in
2638 : * itself indexable. If we see that any operand of an OpExpr or FuncExpr
2639 : * matches the index key, and the function has a planner support function
2640 : * attached to it, we'll invoke the support function to see if such an
2641 : * indexqual can be built.
2642 : *
2643 : * 'rinfo' is the clause to be tested (as a RestrictInfo node).
2644 : * 'indexcol' is a column number of 'index' (counting from 0).
2645 : * 'index' is the index of interest.
2646 : *
2647 : * Returns an IndexClause if the clause can be used with this index key,
2648 : * or NULL if not.
2649 : *
2650 : * NOTE: This routine always returns NULL if the clause is an AND clause.
2651 : * Higher-level routines deal with OR and AND clauses. OR clause can be
2652 : * matched as a whole by match_orclause_to_indexcol() though.
2653 : */
2654 : static IndexClause *
2655 2241502 : match_clause_to_indexcol(PlannerInfo *root,
2656 : RestrictInfo *rinfo,
2657 : int indexcol,
2658 : IndexOptInfo *index)
2659 : {
2660 : IndexClause *iclause;
2661 2241502 : Expr *clause = rinfo->clause;
2662 : Oid opfamily;
2663 :
2664 : Assert(indexcol < index->nkeycolumns);
2665 :
2666 : /*
2667 : * Historically this code has coped with NULL clauses. That's probably
2668 : * not possible anymore, but we might as well continue to cope.
2669 : */
2670 2241502 : if (clause == NULL)
2671 0 : return NULL;
2672 :
2673 : /* First check for boolean-index cases. */
2674 2241502 : opfamily = index->opfamily[indexcol];
2675 2241502 : if (IsBooleanOpfamily(opfamily))
2676 : {
2677 338 : iclause = match_boolean_index_clause(root, rinfo, indexcol, index);
2678 338 : if (iclause)
2679 240 : return iclause;
2680 : }
2681 :
2682 : /*
2683 : * Clause must be an opclause, funcclause, ScalarArrayOpExpr,
2684 : * RowCompareExpr, or OR-clause that could be converted to SAOP. Or, if
2685 : * the index supports it, we can handle IS NULL/NOT NULL clauses.
2686 : */
2687 2241262 : if (IsA(clause, OpExpr))
2688 : {
2689 1719540 : return match_opclause_to_indexcol(root, rinfo, indexcol, index);
2690 : }
2691 521722 : else if (IsA(clause, FuncExpr))
2692 : {
2693 134352 : return match_funcclause_to_indexcol(root, rinfo, indexcol, index);
2694 : }
2695 387370 : else if (IsA(clause, ScalarArrayOpExpr))
2696 : {
2697 64810 : return match_saopclause_to_indexcol(root, rinfo, indexcol, index);
2698 : }
2699 322560 : else if (IsA(clause, RowCompareExpr))
2700 : {
2701 432 : return match_rowcompare_to_indexcol(root, rinfo, indexcol, index);
2702 : }
2703 322128 : else if (restriction_is_or_clause(rinfo))
2704 : {
2705 95806 : return match_orclause_to_indexcol(root, rinfo, indexcol, index);
2706 : }
2707 226322 : else if (index->amsearchnulls && IsA(clause, NullTest))
2708 : {
2709 14476 : NullTest *nt = (NullTest *) clause;
2710 :
2711 28952 : if (!nt->argisrow &&
2712 14476 : match_index_to_operand((Node *) nt->arg, indexcol, index))
2713 : {
2714 1442 : iclause = makeNode(IndexClause);
2715 1442 : iclause->rinfo = rinfo;
2716 1442 : iclause->indexquals = list_make1(rinfo);
2717 1442 : iclause->lossy = false;
2718 1442 : iclause->indexcol = indexcol;
2719 1442 : iclause->indexcols = NIL;
2720 1442 : return iclause;
2721 : }
2722 : }
2723 :
2724 224880 : return NULL;
2725 : }
2726 :
2727 : /*
2728 : * IsBooleanOpfamily
2729 : * Detect whether an opfamily supports boolean equality as an operator.
2730 : *
2731 : * If the opfamily OID is in the range of built-in objects, we can rely
2732 : * on hard-wired knowledge of which built-in opfamilies support this.
2733 : * For extension opfamilies, there's no choice but to do a catcache lookup.
2734 : */
2735 : static bool
2736 3049334 : IsBooleanOpfamily(Oid opfamily)
2737 : {
2738 3049334 : if (opfamily < FirstNormalObjectId)
2739 3046128 : return IsBuiltinBooleanOpfamily(opfamily);
2740 : else
2741 3206 : return op_in_opfamily(BooleanEqualOperator, opfamily);
2742 : }
2743 :
2744 : /*
2745 : * match_boolean_index_clause
2746 : * Recognize restriction clauses that can be matched to a boolean index.
2747 : *
2748 : * The idea here is that, for an index on a boolean column that supports the
2749 : * BooleanEqualOperator, we can transform a plain reference to the indexkey
2750 : * into "indexkey = true", or "NOT indexkey" into "indexkey = false", etc,
2751 : * so as to make the expression indexable using the index's "=" operator.
2752 : * Since Postgres 8.1, we must do this because constant simplification does
2753 : * the reverse transformation; without this code there'd be no way to use
2754 : * such an index at all.
2755 : *
2756 : * This should be called only when IsBooleanOpfamily() recognizes the
2757 : * index's operator family. We check to see if the clause matches the
2758 : * index's key, and if so, build a suitable IndexClause.
2759 : */
2760 : static IndexClause *
2761 1346 : match_boolean_index_clause(PlannerInfo *root,
2762 : RestrictInfo *rinfo,
2763 : int indexcol,
2764 : IndexOptInfo *index)
2765 : {
2766 1346 : Node *clause = (Node *) rinfo->clause;
2767 1346 : Expr *op = NULL;
2768 :
2769 : /* Direct match? */
2770 1346 : if (match_index_to_operand(clause, indexcol, index))
2771 : {
2772 : /* convert to indexkey = TRUE */
2773 94 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2774 : (Expr *) clause,
2775 94 : (Expr *) makeBoolConst(true, false),
2776 : InvalidOid, InvalidOid);
2777 : }
2778 : /* NOT clause? */
2779 1252 : else if (is_notclause(clause))
2780 : {
2781 1082 : Node *arg = (Node *) get_notclausearg((Expr *) clause);
2782 :
2783 1082 : if (match_index_to_operand(arg, indexcol, index))
2784 : {
2785 : /* convert to indexkey = FALSE */
2786 1082 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2787 : (Expr *) arg,
2788 1082 : (Expr *) makeBoolConst(false, false),
2789 : InvalidOid, InvalidOid);
2790 : }
2791 : }
2792 :
2793 : /*
2794 : * Since we only consider clauses at top level of WHERE, we can convert
2795 : * indexkey IS TRUE and indexkey IS FALSE to index searches as well. The
2796 : * different meaning for NULL isn't important.
2797 : */
2798 170 : else if (clause && IsA(clause, BooleanTest))
2799 : {
2800 36 : BooleanTest *btest = (BooleanTest *) clause;
2801 36 : Node *arg = (Node *) btest->arg;
2802 :
2803 54 : if (btest->booltesttype == IS_TRUE &&
2804 18 : match_index_to_operand(arg, indexcol, index))
2805 : {
2806 : /* convert to indexkey = TRUE */
2807 18 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2808 : (Expr *) arg,
2809 18 : (Expr *) makeBoolConst(true, false),
2810 : InvalidOid, InvalidOid);
2811 : }
2812 36 : else if (btest->booltesttype == IS_FALSE &&
2813 18 : match_index_to_operand(arg, indexcol, index))
2814 : {
2815 : /* convert to indexkey = FALSE */
2816 18 : op = make_opclause(BooleanEqualOperator, BOOLOID, false,
2817 : (Expr *) arg,
2818 18 : (Expr *) makeBoolConst(false, false),
2819 : InvalidOid, InvalidOid);
2820 : }
2821 : }
2822 :
2823 : /*
2824 : * If we successfully made an operator clause from the given qual, we must
2825 : * wrap it in an IndexClause. It's not lossy.
2826 : */
2827 1346 : if (op)
2828 : {
2829 1212 : IndexClause *iclause = makeNode(IndexClause);
2830 :
2831 1212 : iclause->rinfo = rinfo;
2832 1212 : iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
2833 1212 : iclause->lossy = false;
2834 1212 : iclause->indexcol = indexcol;
2835 1212 : iclause->indexcols = NIL;
2836 1212 : return iclause;
2837 : }
2838 :
2839 134 : return NULL;
2840 : }
2841 :
2842 : /*
2843 : * match_opclause_to_indexcol()
2844 : * Handles the OpExpr case for match_clause_to_indexcol(),
2845 : * which see for comments.
2846 : */
2847 : static IndexClause *
2848 1719540 : match_opclause_to_indexcol(PlannerInfo *root,
2849 : RestrictInfo *rinfo,
2850 : int indexcol,
2851 : IndexOptInfo *index)
2852 : {
2853 : IndexClause *iclause;
2854 1719540 : OpExpr *clause = (OpExpr *) rinfo->clause;
2855 : Node *leftop,
2856 : *rightop;
2857 : Oid expr_op;
2858 : Oid expr_coll;
2859 : Index index_relid;
2860 : Oid opfamily;
2861 : Oid idxcollation;
2862 :
2863 : /*
2864 : * Only binary operators need apply. (In theory, a planner support
2865 : * function could do something with a unary operator, but it seems
2866 : * unlikely to be worth the cycles to check.)
2867 : */
2868 1719540 : if (list_length(clause->args) != 2)
2869 0 : return NULL;
2870 :
2871 1719540 : leftop = (Node *) linitial(clause->args);
2872 1719540 : rightop = (Node *) lsecond(clause->args);
2873 1719540 : expr_op = clause->opno;
2874 1719540 : expr_coll = clause->inputcollid;
2875 :
2876 1719540 : index_relid = index->rel->relid;
2877 1719540 : opfamily = index->opfamily[indexcol];
2878 1719540 : idxcollation = index->indexcollations[indexcol];
2879 :
2880 : /*
2881 : * Check for clauses of the form: (indexkey operator constant) or
2882 : * (constant operator indexkey). See match_clause_to_indexcol's notes
2883 : * about const-ness.
2884 : *
2885 : * Note that we don't ask the support function about clauses that don't
2886 : * have one of these forms. Again, in principle it might be possible to
2887 : * do something, but it seems unlikely to be worth the cycles to check.
2888 : */
2889 1719540 : if (match_index_to_operand(leftop, indexcol, index) &&
2890 464558 : !bms_is_member(index_relid, rinfo->right_relids) &&
2891 464384 : !contain_volatile_functions(rightop))
2892 : {
2893 922330 : if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
2894 457946 : op_in_opfamily(expr_op, opfamily))
2895 : {
2896 452570 : iclause = makeNode(IndexClause);
2897 452570 : iclause->rinfo = rinfo;
2898 452570 : iclause->indexquals = list_make1(rinfo);
2899 452570 : iclause->lossy = false;
2900 452570 : iclause->indexcol = indexcol;
2901 452570 : iclause->indexcols = NIL;
2902 452570 : return iclause;
2903 : }
2904 :
2905 : /*
2906 : * If we didn't find a member of the index's opfamily, try the support
2907 : * function for the operator's underlying function.
2908 : */
2909 11814 : set_opfuncid(clause); /* make sure we have opfuncid */
2910 11814 : return get_index_clause_from_support(root,
2911 : rinfo,
2912 : clause->opfuncid,
2913 : 0, /* indexarg on left */
2914 : indexcol,
2915 : index);
2916 : }
2917 :
2918 1255156 : if (match_index_to_operand(rightop, indexcol, index) &&
2919 162632 : !bms_is_member(index_relid, rinfo->left_relids) &&
2920 162506 : !contain_volatile_functions(leftop))
2921 : {
2922 162506 : if (IndexCollMatchesExprColl(idxcollation, expr_coll))
2923 : {
2924 162494 : Oid comm_op = get_commutator(expr_op);
2925 :
2926 324988 : if (OidIsValid(comm_op) &&
2927 162494 : op_in_opfamily(comm_op, opfamily))
2928 : {
2929 : RestrictInfo *commrinfo;
2930 :
2931 : /* Build a commuted OpExpr and RestrictInfo */
2932 162042 : commrinfo = commute_restrictinfo(rinfo, comm_op);
2933 :
2934 : /* Make an IndexClause showing that as a derived qual */
2935 162042 : iclause = makeNode(IndexClause);
2936 162042 : iclause->rinfo = rinfo;
2937 162042 : iclause->indexquals = list_make1(commrinfo);
2938 162042 : iclause->lossy = false;
2939 162042 : iclause->indexcol = indexcol;
2940 162042 : iclause->indexcols = NIL;
2941 162042 : return iclause;
2942 : }
2943 : }
2944 :
2945 : /*
2946 : * If we didn't find a member of the index's opfamily, try the support
2947 : * function for the operator's underlying function.
2948 : */
2949 464 : set_opfuncid(clause); /* make sure we have opfuncid */
2950 464 : return get_index_clause_from_support(root,
2951 : rinfo,
2952 : clause->opfuncid,
2953 : 1, /* indexarg on right */
2954 : indexcol,
2955 : index);
2956 : }
2957 :
2958 1092650 : return NULL;
2959 : }
2960 :
2961 : /*
2962 : * match_funcclause_to_indexcol()
2963 : * Handles the FuncExpr case for match_clause_to_indexcol(),
2964 : * which see for comments.
2965 : */
2966 : static IndexClause *
2967 134352 : match_funcclause_to_indexcol(PlannerInfo *root,
2968 : RestrictInfo *rinfo,
2969 : int indexcol,
2970 : IndexOptInfo *index)
2971 : {
2972 134352 : FuncExpr *clause = (FuncExpr *) rinfo->clause;
2973 : int indexarg;
2974 : ListCell *lc;
2975 :
2976 : /*
2977 : * We have no built-in intelligence about function clauses, but if there's
2978 : * a planner support function, it might be able to do something. But, to
2979 : * cut down on wasted planning cycles, only call the support function if
2980 : * at least one argument matches the target index column.
2981 : *
2982 : * Note that we don't insist on the other arguments being pseudoconstants;
2983 : * the support function has to check that. This is to allow cases where
2984 : * only some of the other arguments need to be included in the indexqual.
2985 : */
2986 134352 : indexarg = 0;
2987 425440 : foreach(lc, clause->args)
2988 : {
2989 320158 : Node *op = (Node *) lfirst(lc);
2990 :
2991 320158 : if (match_index_to_operand(op, indexcol, index))
2992 : {
2993 29070 : return get_index_clause_from_support(root,
2994 : rinfo,
2995 : clause->funcid,
2996 : indexarg,
2997 : indexcol,
2998 : index);
2999 : }
3000 :
3001 291088 : indexarg++;
3002 : }
3003 :
3004 105282 : return NULL;
3005 : }
3006 :
3007 : /*
3008 : * get_index_clause_from_support()
3009 : * If the function has a planner support function, try to construct
3010 : * an IndexClause using indexquals created by the support function.
3011 : */
3012 : static IndexClause *
3013 41348 : get_index_clause_from_support(PlannerInfo *root,
3014 : RestrictInfo *rinfo,
3015 : Oid funcid,
3016 : int indexarg,
3017 : int indexcol,
3018 : IndexOptInfo *index)
3019 : {
3020 41348 : Oid prosupport = get_func_support(funcid);
3021 : SupportRequestIndexCondition req;
3022 : List *sresult;
3023 :
3024 41348 : if (!OidIsValid(prosupport))
3025 33490 : return NULL;
3026 :
3027 7858 : req.type = T_SupportRequestIndexCondition;
3028 7858 : req.root = root;
3029 7858 : req.funcid = funcid;
3030 7858 : req.node = (Node *) rinfo->clause;
3031 7858 : req.indexarg = indexarg;
3032 7858 : req.index = index;
3033 7858 : req.indexcol = indexcol;
3034 7858 : req.opfamily = index->opfamily[indexcol];
3035 7858 : req.indexcollation = index->indexcollations[indexcol];
3036 :
3037 7858 : req.lossy = true; /* default assumption */
3038 :
3039 : sresult = (List *)
3040 7858 : DatumGetPointer(OidFunctionCall1(prosupport,
3041 : PointerGetDatum(&req)));
3042 :
3043 7858 : if (sresult != NIL)
3044 : {
3045 1366 : IndexClause *iclause = makeNode(IndexClause);
3046 1366 : List *indexquals = NIL;
3047 : ListCell *lc;
3048 :
3049 : /*
3050 : * The support function API says it should just give back bare
3051 : * clauses, so here we must wrap each one in a RestrictInfo.
3052 : */
3053 4020 : foreach(lc, sresult)
3054 : {
3055 2654 : Expr *clause = (Expr *) lfirst(lc);
3056 :
3057 2654 : indexquals = lappend(indexquals,
3058 2654 : make_simple_restrictinfo(root, clause));
3059 : }
3060 :
3061 1366 : iclause->rinfo = rinfo;
3062 1366 : iclause->indexquals = indexquals;
3063 1366 : iclause->lossy = req.lossy;
3064 1366 : iclause->indexcol = indexcol;
3065 1366 : iclause->indexcols = NIL;
3066 :
3067 1366 : return iclause;
3068 : }
3069 :
3070 6492 : return NULL;
3071 : }
3072 :
3073 : /*
3074 : * match_saopclause_to_indexcol()
3075 : * Handles the ScalarArrayOpExpr case for match_clause_to_indexcol(),
3076 : * which see for comments.
3077 : */
3078 : static IndexClause *
3079 64810 : match_saopclause_to_indexcol(PlannerInfo *root,
3080 : RestrictInfo *rinfo,
3081 : int indexcol,
3082 : IndexOptInfo *index)
3083 : {
3084 64810 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) rinfo->clause;
3085 : Node *leftop,
3086 : *rightop;
3087 : Relids right_relids;
3088 : Oid expr_op;
3089 : Oid expr_coll;
3090 : Index index_relid;
3091 : Oid opfamily;
3092 : Oid idxcollation;
3093 :
3094 : /* We only accept ANY clauses, not ALL */
3095 64810 : if (!saop->useOr)
3096 7270 : return NULL;
3097 57540 : leftop = (Node *) linitial(saop->args);
3098 57540 : rightop = (Node *) lsecond(saop->args);
3099 57540 : right_relids = pull_varnos(root, rightop);
3100 57540 : expr_op = saop->opno;
3101 57540 : expr_coll = saop->inputcollid;
3102 :
3103 57540 : index_relid = index->rel->relid;
3104 57540 : opfamily = index->opfamily[indexcol];
3105 57540 : idxcollation = index->indexcollations[indexcol];
3106 :
3107 : /*
3108 : * We must have indexkey on the left and a pseudo-constant array argument.
3109 : */
3110 57540 : if (match_index_to_operand(leftop, indexcol, index) &&
3111 6160 : !bms_is_member(index_relid, right_relids) &&
3112 6160 : !contain_volatile_functions(rightop))
3113 : {
3114 12314 : if (IndexCollMatchesExprColl(idxcollation, expr_coll) &&
3115 6154 : op_in_opfamily(expr_op, opfamily))
3116 : {
3117 6142 : IndexClause *iclause = makeNode(IndexClause);
3118 :
3119 6142 : iclause->rinfo = rinfo;
3120 6142 : iclause->indexquals = list_make1(rinfo);
3121 6142 : iclause->lossy = false;
3122 6142 : iclause->indexcol = indexcol;
3123 6142 : iclause->indexcols = NIL;
3124 6142 : return iclause;
3125 : }
3126 :
3127 : /*
3128 : * We do not currently ask support functions about ScalarArrayOpExprs,
3129 : * though in principle we could.
3130 : */
3131 : }
3132 :
3133 51398 : return NULL;
3134 : }
3135 :
3136 : /*
3137 : * match_rowcompare_to_indexcol()
3138 : * Handles the RowCompareExpr case for match_clause_to_indexcol(),
3139 : * which see for comments.
3140 : *
3141 : * In this routine we check whether the first column of the row comparison
3142 : * matches the target index column. This is sufficient to guarantee that some
3143 : * index condition can be constructed from the RowCompareExpr --- the rest
3144 : * is handled by expand_indexqual_rowcompare().
3145 : */
3146 : static IndexClause *
3147 432 : match_rowcompare_to_indexcol(PlannerInfo *root,
3148 : RestrictInfo *rinfo,
3149 : int indexcol,
3150 : IndexOptInfo *index)
3151 : {
3152 432 : RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
3153 : Index index_relid;
3154 : Oid opfamily;
3155 : Oid idxcollation;
3156 : Node *leftop,
3157 : *rightop;
3158 : bool var_on_left;
3159 : Oid expr_op;
3160 : Oid expr_coll;
3161 :
3162 : /* Forget it if we're not dealing with a btree index */
3163 432 : if (index->relam != BTREE_AM_OID)
3164 0 : return NULL;
3165 :
3166 432 : index_relid = index->rel->relid;
3167 432 : opfamily = index->opfamily[indexcol];
3168 432 : idxcollation = index->indexcollations[indexcol];
3169 :
3170 : /*
3171 : * We could do the matching on the basis of insisting that the opfamily
3172 : * shown in the RowCompareExpr be the same as the index column's opfamily,
3173 : * but that could fail in the presence of reverse-sort opfamilies: it'd be
3174 : * a matter of chance whether RowCompareExpr had picked the forward or
3175 : * reverse-sort family. So look only at the operator, and match if it is
3176 : * a member of the index's opfamily (after commutation, if the indexkey is
3177 : * on the right). We'll worry later about whether any additional
3178 : * operators are matchable to the index.
3179 : */
3180 432 : leftop = (Node *) linitial(clause->largs);
3181 432 : rightop = (Node *) linitial(clause->rargs);
3182 432 : expr_op = linitial_oid(clause->opnos);
3183 432 : expr_coll = linitial_oid(clause->inputcollids);
3184 :
3185 : /* Collations must match, if relevant */
3186 432 : if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
3187 0 : return NULL;
3188 :
3189 : /*
3190 : * These syntactic tests are the same as in match_opclause_to_indexcol()
3191 : */
3192 432 : if (match_index_to_operand(leftop, indexcol, index) &&
3193 126 : !bms_is_member(index_relid, pull_varnos(root, rightop)) &&
3194 126 : !contain_volatile_functions(rightop))
3195 : {
3196 : /* OK, indexkey is on left */
3197 126 : var_on_left = true;
3198 : }
3199 306 : else if (match_index_to_operand(rightop, indexcol, index) &&
3200 24 : !bms_is_member(index_relid, pull_varnos(root, leftop)) &&
3201 24 : !contain_volatile_functions(leftop))
3202 : {
3203 : /* indexkey is on right, so commute the operator */
3204 24 : expr_op = get_commutator(expr_op);
3205 24 : if (expr_op == InvalidOid)
3206 0 : return NULL;
3207 24 : var_on_left = false;
3208 : }
3209 : else
3210 282 : return NULL;
3211 :
3212 : /* We're good if the operator is the right type of opfamily member */
3213 150 : switch (get_op_opfamily_strategy(expr_op, opfamily))
3214 : {
3215 150 : case BTLessStrategyNumber:
3216 : case BTLessEqualStrategyNumber:
3217 : case BTGreaterEqualStrategyNumber:
3218 : case BTGreaterStrategyNumber:
3219 150 : return expand_indexqual_rowcompare(root,
3220 : rinfo,
3221 : indexcol,
3222 : index,
3223 : expr_op,
3224 : var_on_left);
3225 : }
3226 :
3227 0 : return NULL;
3228 : }
3229 :
3230 : /*
3231 : * match_orclause_to_indexcol()
3232 : * Handles the OR-expr case for match_clause_to_indexcol() in the case
3233 : * when it could be transformed to ScalarArrayOpExpr.
3234 : *
3235 : * In this routine, we attempt to transform a list of OR-clause args into a
3236 : * single SAOP expression matching the target index column. On success,
3237 : * return an IndexClause, containing the transformed expression or NULL,
3238 : * if failed.
3239 : */
3240 : static IndexClause *
3241 95806 : match_orclause_to_indexcol(PlannerInfo *root,
3242 : RestrictInfo *rinfo,
3243 : int indexcol,
3244 : IndexOptInfo *index)
3245 : {
3246 : ListCell *lc;
3247 95806 : BoolExpr *orclause = (BoolExpr *) rinfo->orclause;
3248 95806 : Node *indexExpr = NULL;
3249 95806 : List *consts = NIL;
3250 95806 : Node *arrayNode = NULL;
3251 95806 : ScalarArrayOpExpr *saopexpr = NULL;
3252 95806 : Oid matchOpno = InvalidOid;
3253 : IndexClause *iclause;
3254 95806 : Oid consttype = InvalidOid;
3255 95806 : Oid arraytype = InvalidOid;
3256 95806 : Oid inputcollid = InvalidOid;
3257 95806 : bool firstTime = true;
3258 95806 : bool haveNonConst = false;
3259 95806 : Index indexRelid = index->rel->relid;
3260 :
3261 : Assert(IsA(orclause, BoolExpr));
3262 : Assert(orclause->boolop == OR_EXPR);
3263 :
3264 : /* Ignore index if it doesn't support SAOP clauses */
3265 95806 : if (!index->amsearcharray)
3266 106 : return NULL;
3267 :
3268 : /*
3269 : * Try to convert a list of OR-clauses to a single SAOP expression. Each
3270 : * OR entry must be in the form: (indexkey operator constant) or (constant
3271 : * operator indexkey). Operators of all the entries must match. To be
3272 : * effective, give up on the first non-matching entry. Exit is
3273 : * implemented as a break from the loop, which is catched afterwards.
3274 : */
3275 99456 : foreach(lc, orclause->args)
3276 : {
3277 : RestrictInfo *subRinfo;
3278 : OpExpr *subClause;
3279 : Oid opno;
3280 : Node *leftop,
3281 : *rightop;
3282 : Node *constExpr;
3283 :
3284 98412 : if (!IsA(lfirst(lc), RestrictInfo))
3285 3712 : break;
3286 :
3287 94700 : subRinfo = (RestrictInfo *) lfirst(lc);
3288 :
3289 : /* Only operator clauses can match */
3290 94700 : if (!IsA(subRinfo->clause, OpExpr))
3291 70054 : break;
3292 :
3293 24646 : subClause = (OpExpr *) subRinfo->clause;
3294 24646 : opno = subClause->opno;
3295 :
3296 : /* Only binary operators can match */
3297 24646 : if (list_length(subClause->args) != 2)
3298 0 : break;
3299 :
3300 : /*
3301 : * The parameters below must match between sub-rinfo and its parent as
3302 : * make_restrictinfo() fills them with the same values, and further
3303 : * modifications are also the same for the whole subtree. However,
3304 : * still make a sanity check.
3305 : */
3306 : Assert(subRinfo->is_pushed_down == rinfo->is_pushed_down);
3307 : Assert(subRinfo->is_clone == rinfo->is_clone);
3308 : Assert(subRinfo->security_level == rinfo->security_level);
3309 : Assert(bms_equal(subRinfo->incompatible_relids, rinfo->incompatible_relids));
3310 : Assert(bms_equal(subRinfo->outer_relids, rinfo->outer_relids));
3311 :
3312 : /*
3313 : * Also, check that required_relids in sub-rinfo is subset of parent's
3314 : * required_relids.
3315 : */
3316 : Assert(bms_is_subset(subRinfo->required_relids, rinfo->required_relids));
3317 :
3318 : /* Only the operator returning a boolean suit the transformation. */
3319 24646 : if (get_op_rettype(opno) != BOOLOID)
3320 0 : break;
3321 :
3322 : /*
3323 : * Check for clauses of the form: (indexkey operator constant) or
3324 : * (constant operator indexkey). See match_clause_to_indexcol's notes
3325 : * about const-ness.
3326 : */
3327 24646 : leftop = (Node *) linitial(subClause->args);
3328 24646 : rightop = (Node *) lsecond(subClause->args);
3329 24646 : if (match_index_to_operand(leftop, indexcol, index) &&
3330 5378 : !bms_is_member(indexRelid, subRinfo->right_relids) &&
3331 5360 : !contain_volatile_functions(rightop))
3332 : {
3333 5360 : indexExpr = leftop;
3334 5360 : constExpr = rightop;
3335 : }
3336 19286 : else if (match_index_to_operand(rightop, indexcol, index) &&
3337 142 : !bms_is_member(indexRelid, subRinfo->left_relids) &&
3338 136 : !contain_volatile_functions(leftop))
3339 : {
3340 136 : opno = get_commutator(opno);
3341 136 : if (!OidIsValid(opno))
3342 : {
3343 : /* commutator doesn't exist, we can't reverse the order */
3344 0 : break;
3345 : }
3346 136 : indexExpr = rightop;
3347 136 : constExpr = leftop;
3348 : }
3349 : else
3350 : {
3351 : break;
3352 : }
3353 :
3354 : /*
3355 : * Ignore any RelabelType node above the operands. This is needed to
3356 : * be able to apply indexscanning in binary-compatible-operator cases.
3357 : * Note: we can assume there is at most one RelabelType node;
3358 : * eval_const_expressions() will have simplified if more than one.
3359 : */
3360 5496 : if (IsA(constExpr, RelabelType))
3361 0 : constExpr = (Node *) ((RelabelType *) constExpr)->arg;
3362 5496 : if (IsA(indexExpr, RelabelType))
3363 6 : indexExpr = (Node *) ((RelabelType *) indexExpr)->arg;
3364 :
3365 : /* Forbid transformation for composite types, records. */
3366 10992 : if (type_is_rowtype(exprType(constExpr)) ||
3367 5496 : type_is_rowtype(exprType(indexExpr)))
3368 : break;
3369 :
3370 : /*
3371 : * Save information about the operator, type, and collation for the
3372 : * first matching qual. Then, check that subsequent quals match the
3373 : * first.
3374 : */
3375 5496 : if (firstTime)
3376 : {
3377 3768 : matchOpno = opno;
3378 3768 : consttype = exprType(constExpr);
3379 3768 : arraytype = get_array_type(consttype);
3380 3768 : inputcollid = subClause->inputcollid;
3381 :
3382 : /*
3383 : * Check that the operator is presented in the opfamily and that
3384 : * the expression collation matches the index collation. Also,
3385 : * there must be an array type to construct an array later.
3386 : */
3387 3768 : if (!IndexCollMatchesExprColl(index->indexcollations[indexcol], inputcollid) ||
3388 3660 : !op_in_opfamily(matchOpno, index->opfamily[indexcol]) ||
3389 : !OidIsValid(arraytype))
3390 : break;
3391 2154 : firstTime = false;
3392 : }
3393 : else
3394 : {
3395 1728 : if (opno != matchOpno ||
3396 3204 : inputcollid != subClause->inputcollid ||
3397 1602 : consttype != exprType(constExpr))
3398 : break;
3399 : }
3400 :
3401 : /*
3402 : * Check if our list of constants in match_clause_to_indexcol's
3403 : * understanding of const-ness have something other than Const.
3404 : */
3405 3756 : if (!IsA(constExpr, Const))
3406 316 : haveNonConst = true;
3407 3756 : consts = lappend(consts, constExpr);
3408 : }
3409 :
3410 : /*
3411 : * Catch the break from the loop above. Normally, a foreach() loop ends
3412 : * up with a NULL list cell. A non-NULL list cell indicates a break from
3413 : * the foreach() loop. Free the consts list and return NULL then.
3414 : */
3415 95700 : if (lc != NULL)
3416 : {
3417 94656 : list_free(consts);
3418 94656 : return NULL;
3419 : }
3420 :
3421 : /*
3422 : * Assemble an array from the list of constants. It seems more profitable
3423 : * to build a const array. But in the presence of other nodes, we don't
3424 : * have a specific value here and must employ an ArrayExpr instead.
3425 : */
3426 1044 : if (haveNonConst)
3427 : {
3428 96 : ArrayExpr *arrayExpr = makeNode(ArrayExpr);
3429 :
3430 : /* array_collid will be set by parse_collate.c */
3431 96 : arrayExpr->element_typeid = consttype;
3432 96 : arrayExpr->array_typeid = arraytype;
3433 96 : arrayExpr->multidims = false;
3434 96 : arrayExpr->elements = consts;
3435 96 : arrayExpr->location = -1;
3436 :
3437 96 : arrayNode = (Node *) arrayExpr;
3438 : }
3439 : else
3440 : {
3441 : int16 typlen;
3442 : bool typbyval;
3443 : char typalign;
3444 : Datum *elems;
3445 948 : int i = 0;
3446 : ArrayType *arrayConst;
3447 :
3448 948 : get_typlenbyvalalign(consttype, &typlen, &typbyval, &typalign);
3449 :
3450 948 : elems = (Datum *) palloc(sizeof(Datum) * list_length(consts));
3451 4230 : foreach_node(Const, value, consts)
3452 : {
3453 : Assert(!value->constisnull);
3454 :
3455 2334 : elems[i++] = value->constvalue;
3456 : }
3457 :
3458 948 : arrayConst = construct_array(elems, i, consttype,
3459 : typlen, typbyval, typalign);
3460 948 : arrayNode = (Node *) makeConst(arraytype, -1, inputcollid,
3461 : -1, PointerGetDatum(arrayConst),
3462 : false, false);
3463 :
3464 948 : pfree(elems);
3465 948 : list_free(consts);
3466 : }
3467 :
3468 : /* Build the SAOP expression node */
3469 1044 : saopexpr = makeNode(ScalarArrayOpExpr);
3470 1044 : saopexpr->opno = matchOpno;
3471 1044 : saopexpr->opfuncid = get_opcode(matchOpno);
3472 1044 : saopexpr->hashfuncid = InvalidOid;
3473 1044 : saopexpr->negfuncid = InvalidOid;
3474 1044 : saopexpr->useOr = true;
3475 1044 : saopexpr->inputcollid = inputcollid;
3476 1044 : saopexpr->args = list_make2(indexExpr, arrayNode);
3477 1044 : saopexpr->location = -1;
3478 :
3479 : /*
3480 : * Finally, build an IndexClause based on the SAOP node. Use
3481 : * make_simple_restrictinfo() to get RestrictInfo with clean selectivity
3482 : * estimations, because they may differ from the estimation made for an OR
3483 : * clause. Although it is not a lossy expression, keep the original rinfo
3484 : * in iclause->rinfo as prescribed.
3485 : */
3486 1044 : iclause = makeNode(IndexClause);
3487 1044 : iclause->rinfo = rinfo;
3488 1044 : iclause->indexquals = list_make1(make_simple_restrictinfo(root,
3489 : &saopexpr->xpr));
3490 1044 : iclause->lossy = false;
3491 1044 : iclause->indexcol = indexcol;
3492 1044 : iclause->indexcols = NIL;
3493 1044 : return iclause;
3494 : }
3495 :
3496 : /*
3497 : * expand_indexqual_rowcompare --- expand a single indexqual condition
3498 : * that is a RowCompareExpr
3499 : *
3500 : * It's already known that the first column of the row comparison matches
3501 : * the specified column of the index. We can use additional columns of the
3502 : * row comparison as index qualifications, so long as they match the index
3503 : * in the "same direction", ie, the indexkeys are all on the same side of the
3504 : * clause and the operators are all the same-type members of the opfamilies.
3505 : *
3506 : * If all the columns of the RowCompareExpr match in this way, we just use it
3507 : * as-is, except for possibly commuting it to put the indexkeys on the left.
3508 : *
3509 : * Otherwise, we build a shortened RowCompareExpr (if more than one
3510 : * column matches) or a simple OpExpr (if the first-column match is all
3511 : * there is). In these cases the modified clause is always "<=" or ">="
3512 : * even when the original was "<" or ">" --- this is necessary to match all
3513 : * the rows that could match the original. (We are building a lossy version
3514 : * of the row comparison when we do this, so we set lossy = true.)
3515 : *
3516 : * Note: this is really just the last half of match_rowcompare_to_indexcol,
3517 : * but we split it out for comprehensibility.
3518 : */
3519 : static IndexClause *
3520 150 : expand_indexqual_rowcompare(PlannerInfo *root,
3521 : RestrictInfo *rinfo,
3522 : int indexcol,
3523 : IndexOptInfo *index,
3524 : Oid expr_op,
3525 : bool var_on_left)
3526 : {
3527 150 : IndexClause *iclause = makeNode(IndexClause);
3528 150 : RowCompareExpr *clause = (RowCompareExpr *) rinfo->clause;
3529 : int op_strategy;
3530 : Oid op_lefttype;
3531 : Oid op_righttype;
3532 : int matching_cols;
3533 : List *expr_ops;
3534 : List *opfamilies;
3535 : List *lefttypes;
3536 : List *righttypes;
3537 : List *new_ops;
3538 : List *var_args;
3539 : List *non_var_args;
3540 :
3541 150 : iclause->rinfo = rinfo;
3542 150 : iclause->indexcol = indexcol;
3543 :
3544 150 : if (var_on_left)
3545 : {
3546 126 : var_args = clause->largs;
3547 126 : non_var_args = clause->rargs;
3548 : }
3549 : else
3550 : {
3551 24 : var_args = clause->rargs;
3552 24 : non_var_args = clause->largs;
3553 : }
3554 :
3555 150 : get_op_opfamily_properties(expr_op, index->opfamily[indexcol], false,
3556 : &op_strategy,
3557 : &op_lefttype,
3558 : &op_righttype);
3559 :
3560 : /* Initialize returned list of which index columns are used */
3561 150 : iclause->indexcols = list_make1_int(indexcol);
3562 :
3563 : /* Build lists of ops, opfamilies and operator datatypes in case needed */
3564 150 : expr_ops = list_make1_oid(expr_op);
3565 150 : opfamilies = list_make1_oid(index->opfamily[indexcol]);
3566 150 : lefttypes = list_make1_oid(op_lefttype);
3567 150 : righttypes = list_make1_oid(op_righttype);
3568 :
3569 : /*
3570 : * See how many of the remaining columns match some index column in the
3571 : * same way. As in match_clause_to_indexcol(), the "other" side of any
3572 : * potential index condition is OK as long as it doesn't use Vars from the
3573 : * indexed relation.
3574 : */
3575 150 : matching_cols = 1;
3576 :
3577 282 : while (matching_cols < list_length(var_args))
3578 : {
3579 186 : Node *varop = (Node *) list_nth(var_args, matching_cols);
3580 186 : Node *constop = (Node *) list_nth(non_var_args, matching_cols);
3581 : int i;
3582 :
3583 186 : expr_op = list_nth_oid(clause->opnos, matching_cols);
3584 186 : if (!var_on_left)
3585 : {
3586 : /* indexkey is on right, so commute the operator */
3587 24 : expr_op = get_commutator(expr_op);
3588 24 : if (expr_op == InvalidOid)
3589 0 : break; /* operator is not usable */
3590 : }
3591 186 : if (bms_is_member(index->rel->relid, pull_varnos(root, constop)))
3592 0 : break; /* no good, Var on wrong side */
3593 186 : if (contain_volatile_functions(constop))
3594 0 : break; /* no good, volatile comparison value */
3595 :
3596 : /*
3597 : * The Var side can match any key column of the index.
3598 : */
3599 444 : for (i = 0; i < index->nkeycolumns; i++)
3600 : {
3601 390 : if (match_index_to_operand(varop, i, index) &&
3602 132 : get_op_opfamily_strategy(expr_op,
3603 132 : index->opfamily[i]) == op_strategy &&
3604 132 : IndexCollMatchesExprColl(index->indexcollations[i],
3605 : list_nth_oid(clause->inputcollids,
3606 : matching_cols)))
3607 : break;
3608 : }
3609 186 : if (i >= index->nkeycolumns)
3610 54 : break; /* no match found */
3611 :
3612 : /* Add column number to returned list */
3613 132 : iclause->indexcols = lappend_int(iclause->indexcols, i);
3614 :
3615 : /* Add operator info to lists */
3616 132 : get_op_opfamily_properties(expr_op, index->opfamily[i], false,
3617 : &op_strategy,
3618 : &op_lefttype,
3619 : &op_righttype);
3620 132 : expr_ops = lappend_oid(expr_ops, expr_op);
3621 132 : opfamilies = lappend_oid(opfamilies, index->opfamily[i]);
3622 132 : lefttypes = lappend_oid(lefttypes, op_lefttype);
3623 132 : righttypes = lappend_oid(righttypes, op_righttype);
3624 :
3625 : /* This column matches, keep scanning */
3626 132 : matching_cols++;
3627 : }
3628 :
3629 : /* Result is non-lossy if all columns are usable as index quals */
3630 150 : iclause->lossy = (matching_cols != list_length(clause->opnos));
3631 :
3632 : /*
3633 : * We can use rinfo->clause as-is if we have var on left and it's all
3634 : * usable as index quals.
3635 : */
3636 150 : if (var_on_left && !iclause->lossy)
3637 84 : iclause->indexquals = list_make1(rinfo);
3638 : else
3639 : {
3640 : /*
3641 : * We have to generate a modified rowcompare (possibly just one
3642 : * OpExpr). The painful part of this is changing < to <= or > to >=,
3643 : * so deal with that first.
3644 : */
3645 66 : if (!iclause->lossy)
3646 : {
3647 : /* very easy, just use the commuted operators */
3648 12 : new_ops = expr_ops;
3649 : }
3650 54 : else if (op_strategy == BTLessEqualStrategyNumber ||
3651 54 : op_strategy == BTGreaterEqualStrategyNumber)
3652 : {
3653 : /* easy, just use the same (possibly commuted) operators */
3654 0 : new_ops = list_truncate(expr_ops, matching_cols);
3655 : }
3656 : else
3657 : {
3658 : ListCell *opfamilies_cell;
3659 : ListCell *lefttypes_cell;
3660 : ListCell *righttypes_cell;
3661 :
3662 54 : if (op_strategy == BTLessStrategyNumber)
3663 30 : op_strategy = BTLessEqualStrategyNumber;
3664 24 : else if (op_strategy == BTGreaterStrategyNumber)
3665 24 : op_strategy = BTGreaterEqualStrategyNumber;
3666 : else
3667 0 : elog(ERROR, "unexpected strategy number %d", op_strategy);
3668 54 : new_ops = NIL;
3669 144 : forthree(opfamilies_cell, opfamilies,
3670 : lefttypes_cell, lefttypes,
3671 : righttypes_cell, righttypes)
3672 : {
3673 90 : Oid opfam = lfirst_oid(opfamilies_cell);
3674 90 : Oid lefttype = lfirst_oid(lefttypes_cell);
3675 90 : Oid righttype = lfirst_oid(righttypes_cell);
3676 :
3677 90 : expr_op = get_opfamily_member(opfam, lefttype, righttype,
3678 : op_strategy);
3679 90 : if (!OidIsValid(expr_op)) /* should not happen */
3680 0 : elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3681 : op_strategy, lefttype, righttype, opfam);
3682 90 : new_ops = lappend_oid(new_ops, expr_op);
3683 : }
3684 : }
3685 :
3686 : /* If we have more than one matching col, create a subset rowcompare */
3687 66 : if (matching_cols > 1)
3688 : {
3689 48 : RowCompareExpr *rc = makeNode(RowCompareExpr);
3690 :
3691 48 : rc->cmptype = (CompareType) op_strategy;
3692 48 : rc->opnos = new_ops;
3693 48 : rc->opfamilies = list_copy_head(clause->opfamilies,
3694 : matching_cols);
3695 48 : rc->inputcollids = list_copy_head(clause->inputcollids,
3696 : matching_cols);
3697 48 : rc->largs = list_copy_head(var_args, matching_cols);
3698 48 : rc->rargs = list_copy_head(non_var_args, matching_cols);
3699 48 : iclause->indexquals = list_make1(make_simple_restrictinfo(root,
3700 : (Expr *) rc));
3701 : }
3702 : else
3703 : {
3704 : Expr *op;
3705 :
3706 : /* We don't report an index column list in this case */
3707 18 : iclause->indexcols = NIL;
3708 :
3709 18 : op = make_opclause(linitial_oid(new_ops), BOOLOID, false,
3710 18 : copyObject(linitial(var_args)),
3711 18 : copyObject(linitial(non_var_args)),
3712 : InvalidOid,
3713 18 : linitial_oid(clause->inputcollids));
3714 18 : iclause->indexquals = list_make1(make_simple_restrictinfo(root, op));
3715 : }
3716 : }
3717 :
3718 150 : return iclause;
3719 : }
3720 :
3721 :
3722 : /****************************************************************************
3723 : * ---- ROUTINES TO CHECK ORDERING OPERATORS ----
3724 : ****************************************************************************/
3725 :
3726 : /*
3727 : * match_pathkeys_to_index
3728 : * For the given 'index' and 'pathkeys', output a list of suitable ORDER
3729 : * BY expressions, each of the form "indexedcol operator pseudoconstant",
3730 : * along with an integer list of the index column numbers (zero based)
3731 : * that each clause would be used with.
3732 : *
3733 : * This attempts to find an ORDER BY and index column number for all items in
3734 : * the pathkey list, however, if we're unable to match any given pathkey to an
3735 : * index column, we return just the ones matched by the function so far. This
3736 : * allows callers who are interested in partial matches to get them. Callers
3737 : * can determine a partial match vs a full match by checking the outputted
3738 : * list lengths. A full match will have one item in the output lists for each
3739 : * item in the given 'pathkeys' list.
3740 : */
3741 : static void
3742 1074 : match_pathkeys_to_index(IndexOptInfo *index, List *pathkeys,
3743 : List **orderby_clauses_p,
3744 : List **clause_columns_p)
3745 : {
3746 : ListCell *lc1;
3747 :
3748 1074 : *orderby_clauses_p = NIL; /* set default results */
3749 1074 : *clause_columns_p = NIL;
3750 :
3751 : /* Only indexes with the amcanorderbyop property are interesting here */
3752 1074 : if (!index->amcanorderbyop)
3753 0 : return;
3754 :
3755 1548 : foreach(lc1, pathkeys)
3756 : {
3757 1080 : PathKey *pathkey = (PathKey *) lfirst(lc1);
3758 1080 : bool found = false;
3759 : ListCell *lc2;
3760 :
3761 :
3762 : /* Pathkey must request default sort order for the target opfamily */
3763 1080 : if (pathkey->pk_strategy != BTLessStrategyNumber ||
3764 1046 : pathkey->pk_nulls_first)
3765 606 : return;
3766 :
3767 : /* If eclass is volatile, no hope of using an indexscan */
3768 1046 : if (pathkey->pk_eclass->ec_has_volatile)
3769 0 : return;
3770 :
3771 : /*
3772 : * Try to match eclass member expression(s) to index. Note that child
3773 : * EC members are considered, but only when they belong to the target
3774 : * relation. (Unlike regular members, the same expression could be a
3775 : * child member of more than one EC. Therefore, the same index could
3776 : * be considered to match more than one pathkey list, which is OK
3777 : * here. See also get_eclass_for_sort_expr.)
3778 : */
3779 1682 : foreach(lc2, pathkey->pk_eclass->ec_members)
3780 : {
3781 1110 : EquivalenceMember *member = (EquivalenceMember *) lfirst(lc2);
3782 : int indexcol;
3783 :
3784 : /* No possibility of match if it references other relations */
3785 1110 : if (!bms_equal(member->em_relids, index->rel->relids))
3786 64 : continue;
3787 :
3788 : /*
3789 : * We allow any column of the index to match each pathkey; they
3790 : * don't have to match left-to-right as you might expect. This is
3791 : * correct for GiST, and it doesn't matter for SP-GiST because
3792 : * that doesn't handle multiple columns anyway, and no other
3793 : * existing AMs support amcanorderbyop. We might need different
3794 : * logic in future for other implementations.
3795 : */
3796 1906 : for (indexcol = 0; indexcol < index->nkeycolumns; indexcol++)
3797 : {
3798 : Expr *expr;
3799 :
3800 1334 : expr = match_clause_to_ordering_op(index,
3801 : indexcol,
3802 : member->em_expr,
3803 : pathkey->pk_opfamily);
3804 1334 : if (expr)
3805 : {
3806 474 : *orderby_clauses_p = lappend(*orderby_clauses_p, expr);
3807 474 : *clause_columns_p = lappend_int(*clause_columns_p, indexcol);
3808 474 : found = true;
3809 474 : break;
3810 : }
3811 : }
3812 :
3813 1046 : if (found) /* don't want to look at remaining members */
3814 474 : break;
3815 : }
3816 :
3817 : /*
3818 : * Return the matches found so far when this pathkey couldn't be
3819 : * matched to the index.
3820 : */
3821 1046 : if (!found)
3822 572 : return;
3823 : }
3824 : }
3825 :
3826 : /*
3827 : * match_clause_to_ordering_op
3828 : * Determines whether an ordering operator expression matches an
3829 : * index column.
3830 : *
3831 : * This is similar to, but simpler than, match_clause_to_indexcol.
3832 : * We only care about simple OpExpr cases. The input is a bare
3833 : * expression that is being ordered by, which must be of the form
3834 : * (indexkey op const) or (const op indexkey) where op is an ordering
3835 : * operator for the column's opfamily.
3836 : *
3837 : * 'index' is the index of interest.
3838 : * 'indexcol' is a column number of 'index' (counting from 0).
3839 : * 'clause' is the ordering expression to be tested.
3840 : * 'pk_opfamily' is the btree opfamily describing the required sort order.
3841 : *
3842 : * Note that we currently do not consider the collation of the ordering
3843 : * operator's result. In practical cases the result type will be numeric
3844 : * and thus have no collation, and it's not very clear what to match to
3845 : * if it did have a collation. The index's collation should match the
3846 : * ordering operator's input collation, not its result.
3847 : *
3848 : * If successful, return 'clause' as-is if the indexkey is on the left,
3849 : * otherwise a commuted copy of 'clause'. If no match, return NULL.
3850 : */
3851 : static Expr *
3852 1334 : match_clause_to_ordering_op(IndexOptInfo *index,
3853 : int indexcol,
3854 : Expr *clause,
3855 : Oid pk_opfamily)
3856 : {
3857 : Oid opfamily;
3858 : Oid idxcollation;
3859 : Node *leftop,
3860 : *rightop;
3861 : Oid expr_op;
3862 : Oid expr_coll;
3863 : Oid sortfamily;
3864 : bool commuted;
3865 :
3866 : Assert(indexcol < index->nkeycolumns);
3867 :
3868 1334 : opfamily = index->opfamily[indexcol];
3869 1334 : idxcollation = index->indexcollations[indexcol];
3870 :
3871 : /*
3872 : * Clause must be a binary opclause.
3873 : */
3874 1334 : if (!is_opclause(clause))
3875 860 : return NULL;
3876 474 : leftop = get_leftop(clause);
3877 474 : rightop = get_rightop(clause);
3878 474 : if (!leftop || !rightop)
3879 0 : return NULL;
3880 474 : expr_op = ((OpExpr *) clause)->opno;
3881 474 : expr_coll = ((OpExpr *) clause)->inputcollid;
3882 :
3883 : /*
3884 : * We can forget the whole thing right away if wrong collation.
3885 : */
3886 474 : if (!IndexCollMatchesExprColl(idxcollation, expr_coll))
3887 0 : return NULL;
3888 :
3889 : /*
3890 : * Check for clauses of the form: (indexkey operator constant) or
3891 : * (constant operator indexkey).
3892 : */
3893 474 : if (match_index_to_operand(leftop, indexcol, index) &&
3894 450 : !contain_var_clause(rightop) &&
3895 450 : !contain_volatile_functions(rightop))
3896 : {
3897 450 : commuted = false;
3898 : }
3899 24 : else if (match_index_to_operand(rightop, indexcol, index) &&
3900 24 : !contain_var_clause(leftop) &&
3901 24 : !contain_volatile_functions(leftop))
3902 : {
3903 : /* Might match, but we need a commuted operator */
3904 24 : expr_op = get_commutator(expr_op);
3905 24 : if (expr_op == InvalidOid)
3906 0 : return NULL;
3907 24 : commuted = true;
3908 : }
3909 : else
3910 0 : return NULL;
3911 :
3912 : /*
3913 : * Is the (commuted) operator an ordering operator for the opfamily? And
3914 : * if so, does it yield the right sorting semantics?
3915 : */
3916 474 : sortfamily = get_op_opfamily_sortfamily(expr_op, opfamily);
3917 474 : if (sortfamily != pk_opfamily)
3918 0 : return NULL;
3919 :
3920 : /* We have a match. Return clause or a commuted version thereof. */
3921 474 : if (commuted)
3922 : {
3923 24 : OpExpr *newclause = makeNode(OpExpr);
3924 :
3925 : /* flat-copy all the fields of clause */
3926 24 : memcpy(newclause, clause, sizeof(OpExpr));
3927 :
3928 : /* commute it */
3929 24 : newclause->opno = expr_op;
3930 24 : newclause->opfuncid = InvalidOid;
3931 24 : newclause->args = list_make2(rightop, leftop);
3932 :
3933 24 : clause = (Expr *) newclause;
3934 : }
3935 :
3936 474 : return clause;
3937 : }
3938 :
3939 :
3940 : /****************************************************************************
3941 : * ---- ROUTINES TO DO PARTIAL INDEX PREDICATE TESTS ----
3942 : ****************************************************************************/
3943 :
3944 : /*
3945 : * check_index_predicates
3946 : * Set the predicate-derived IndexOptInfo fields for each index
3947 : * of the specified relation.
3948 : *
3949 : * predOK is set true if the index is partial and its predicate is satisfied
3950 : * for this query, ie the query's WHERE clauses imply the predicate.
3951 : *
3952 : * indrestrictinfo is set to the relation's baserestrictinfo list less any
3953 : * conditions that are implied by the index's predicate. (Obviously, for a
3954 : * non-partial index, this is the same as baserestrictinfo.) Such conditions
3955 : * can be dropped from the plan when using the index, in certain cases.
3956 : *
3957 : * At one time it was possible for this to get re-run after adding more
3958 : * restrictions to the rel, thus possibly letting us prove more indexes OK.
3959 : * That doesn't happen any more (at least not in the core code's usage),
3960 : * but this code still supports it in case extensions want to mess with the
3961 : * baserestrictinfo list. We assume that adding more restrictions can't make
3962 : * an index not predOK. We must recompute indrestrictinfo each time, though,
3963 : * to make sure any newly-added restrictions get into it if needed.
3964 : */
3965 : void
3966 465388 : check_index_predicates(PlannerInfo *root, RelOptInfo *rel)
3967 : {
3968 : List *clauselist;
3969 : bool have_partial;
3970 : bool is_target_rel;
3971 : Relids otherrels;
3972 : ListCell *lc;
3973 :
3974 : /* Indexes are available only on base or "other" member relations. */
3975 : Assert(IS_SIMPLE_REL(rel));
3976 :
3977 : /*
3978 : * Initialize the indrestrictinfo lists to be identical to
3979 : * baserestrictinfo, and check whether there are any partial indexes. If
3980 : * not, this is all we need to do.
3981 : */
3982 465388 : have_partial = false;
3983 1320036 : foreach(lc, rel->indexlist)
3984 : {
3985 854648 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
3986 :
3987 854648 : index->indrestrictinfo = rel->baserestrictinfo;
3988 854648 : if (index->indpred)
3989 984 : have_partial = true;
3990 : }
3991 465388 : if (!have_partial)
3992 464728 : return;
3993 :
3994 : /*
3995 : * Construct a list of clauses that we can assume true for the purpose of
3996 : * proving the index(es) usable. Restriction clauses for the rel are
3997 : * always usable, and so are any join clauses that are "movable to" this
3998 : * rel. Also, we can consider any EC-derivable join clauses (which must
3999 : * be "movable to" this rel, by definition).
4000 : */
4001 660 : clauselist = list_copy(rel->baserestrictinfo);
4002 :
4003 : /* Scan the rel's join clauses */
4004 660 : foreach(lc, rel->joininfo)
4005 : {
4006 0 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4007 :
4008 : /* Check if clause can be moved to this rel */
4009 0 : if (!join_clause_is_movable_to(rinfo, rel))
4010 0 : continue;
4011 :
4012 0 : clauselist = lappend(clauselist, rinfo);
4013 : }
4014 :
4015 : /*
4016 : * Add on any equivalence-derivable join clauses. Computing the correct
4017 : * relid sets for generate_join_implied_equalities is slightly tricky
4018 : * because the rel could be a child rel rather than a true baserel, and in
4019 : * that case we must subtract its parents' relid(s) from all_query_rels.
4020 : * Additionally, we mustn't consider clauses that are only computable
4021 : * after outer joins that can null the rel.
4022 : */
4023 660 : if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
4024 72 : otherrels = bms_difference(root->all_query_rels,
4025 72 : find_childrel_parents(root, rel));
4026 : else
4027 588 : otherrels = bms_difference(root->all_query_rels, rel->relids);
4028 660 : otherrels = bms_del_members(otherrels, rel->nulling_relids);
4029 :
4030 660 : if (!bms_is_empty(otherrels))
4031 : clauselist =
4032 88 : list_concat(clauselist,
4033 88 : generate_join_implied_equalities(root,
4034 88 : bms_union(rel->relids,
4035 : otherrels),
4036 : otherrels,
4037 : rel,
4038 : NULL));
4039 :
4040 : /*
4041 : * Normally we remove quals that are implied by a partial index's
4042 : * predicate from indrestrictinfo, indicating that they need not be
4043 : * checked explicitly by an indexscan plan using this index. However, if
4044 : * the rel is a target relation of UPDATE/DELETE/MERGE/SELECT FOR UPDATE,
4045 : * we cannot remove such quals from the plan, because they need to be in
4046 : * the plan so that they will be properly rechecked by EvalPlanQual
4047 : * testing. Some day we might want to remove such quals from the main
4048 : * plan anyway and pass them through to EvalPlanQual via a side channel;
4049 : * but for now, we just don't remove implied quals at all for target
4050 : * relations.
4051 : */
4052 1208 : is_target_rel = (bms_is_member(rel->relid, root->all_result_relids) ||
4053 548 : get_plan_rowmark(root->rowMarks, rel->relid) != NULL);
4054 :
4055 : /*
4056 : * Now try to prove each index predicate true, and compute the
4057 : * indrestrictinfo lists for partial indexes. Note that we compute the
4058 : * indrestrictinfo list even for non-predOK indexes; this might seem
4059 : * wasteful, but we may be able to use such indexes in OR clauses, cf
4060 : * generate_bitmap_or_paths().
4061 : */
4062 2030 : foreach(lc, rel->indexlist)
4063 : {
4064 1370 : IndexOptInfo *index = (IndexOptInfo *) lfirst(lc);
4065 : ListCell *lcr;
4066 :
4067 1370 : if (index->indpred == NIL)
4068 386 : continue; /* ignore non-partial indexes here */
4069 :
4070 984 : if (!index->predOK) /* don't repeat work if already proven OK */
4071 984 : index->predOK = predicate_implied_by(index->indpred, clauselist,
4072 : false);
4073 :
4074 : /* If rel is an update target, leave indrestrictinfo as set above */
4075 984 : if (is_target_rel)
4076 172 : continue;
4077 :
4078 : /* Else compute indrestrictinfo as the non-implied quals */
4079 812 : index->indrestrictinfo = NIL;
4080 1914 : foreach(lcr, rel->baserestrictinfo)
4081 : {
4082 1102 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lcr);
4083 :
4084 : /* predicate_implied_by() assumes first arg is immutable */
4085 1102 : if (contain_mutable_functions((Node *) rinfo->clause) ||
4086 1102 : !predicate_implied_by(list_make1(rinfo->clause),
4087 : index->indpred, false))
4088 782 : index->indrestrictinfo = lappend(index->indrestrictinfo, rinfo);
4089 : }
4090 : }
4091 : }
4092 :
4093 : /****************************************************************************
4094 : * ---- ROUTINES TO CHECK EXTERNALLY-VISIBLE CONDITIONS ----
4095 : ****************************************************************************/
4096 :
4097 : /*
4098 : * ec_member_matches_indexcol
4099 : * Test whether an EquivalenceClass member matches an index column.
4100 : *
4101 : * This is a callback for use by generate_implied_equalities_for_column.
4102 : */
4103 : static bool
4104 790506 : ec_member_matches_indexcol(PlannerInfo *root, RelOptInfo *rel,
4105 : EquivalenceClass *ec, EquivalenceMember *em,
4106 : void *arg)
4107 : {
4108 790506 : IndexOptInfo *index = ((ec_member_matches_arg *) arg)->index;
4109 790506 : int indexcol = ((ec_member_matches_arg *) arg)->indexcol;
4110 : Oid curFamily;
4111 : Oid curCollation;
4112 :
4113 : Assert(indexcol < index->nkeycolumns);
4114 :
4115 790506 : curFamily = index->opfamily[indexcol];
4116 790506 : curCollation = index->indexcollations[indexcol];
4117 :
4118 : /*
4119 : * If it's a btree index, we can reject it if its opfamily isn't
4120 : * compatible with the EC, since no clause generated from the EC could be
4121 : * used with the index. For non-btree indexes, we can't easily tell
4122 : * whether clauses generated from the EC could be used with the index, so
4123 : * don't check the opfamily. This might mean we return "true" for a
4124 : * useless EC, so we have to recheck the results of
4125 : * generate_implied_equalities_for_column; see
4126 : * match_eclass_clauses_to_index.
4127 : */
4128 790506 : if (index->relam == BTREE_AM_OID &&
4129 790464 : !list_member_oid(ec->ec_opfamilies, curFamily))
4130 265246 : return false;
4131 :
4132 : /* We insist on collation match for all index types, though */
4133 525260 : if (!IndexCollMatchesExprColl(curCollation, ec->ec_collation))
4134 14 : return false;
4135 :
4136 525246 : return match_index_to_operand((Node *) em->em_expr, indexcol, index);
4137 : }
4138 :
4139 : /*
4140 : * relation_has_unique_index_for
4141 : * Determine whether the relation provably has at most one row satisfying
4142 : * a set of equality conditions, because the conditions constrain all
4143 : * columns of some unique index.
4144 : *
4145 : * The conditions can be represented in either or both of two ways:
4146 : * 1. A list of RestrictInfo nodes, where the caller has already determined
4147 : * that each condition is a mergejoinable equality with an expression in
4148 : * this relation on one side, and an expression not involving this relation
4149 : * on the other. The transient outer_is_left flag is used to identify which
4150 : * side we should look at: left side if outer_is_left is false, right side
4151 : * if it is true.
4152 : * 2. A list of expressions in this relation, and a corresponding list of
4153 : * equality operators. The caller must have already checked that the operators
4154 : * represent equality. (Note: the operators could be cross-type; the
4155 : * expressions should correspond to their RHS inputs.)
4156 : *
4157 : * The caller need only supply equality conditions arising from joins;
4158 : * this routine automatically adds in any usable baserestrictinfo clauses.
4159 : * (Note that the passed-in restrictlist will be destructively modified!)
4160 : */
4161 : bool
4162 928 : relation_has_unique_index_for(PlannerInfo *root, RelOptInfo *rel,
4163 : List *restrictlist,
4164 : List *exprlist, List *oprlist)
4165 : {
4166 928 : return relation_has_unique_index_ext(root, rel, restrictlist,
4167 : exprlist, oprlist, NULL);
4168 : }
4169 :
4170 : /*
4171 : * relation_has_unique_index_ext
4172 : * Same as relation_has_unique_index_for(), but supports extra_clauses
4173 : * parameter. If extra_clauses isn't NULL, return baserestrictinfo clauses
4174 : * which were used to derive uniqueness.
4175 : */
4176 : bool
4177 366244 : relation_has_unique_index_ext(PlannerInfo *root, RelOptInfo *rel,
4178 : List *restrictlist,
4179 : List *exprlist, List *oprlist,
4180 : List **extra_clauses)
4181 : {
4182 : ListCell *ic;
4183 :
4184 : Assert(list_length(exprlist) == list_length(oprlist));
4185 :
4186 : /* Short-circuit if no indexes... */
4187 366244 : if (rel->indexlist == NIL)
4188 458 : return false;
4189 :
4190 : /*
4191 : * Examine the rel's restriction clauses for usable var = const clauses
4192 : * that we can add to the restrictlist.
4193 : */
4194 645550 : foreach(ic, rel->baserestrictinfo)
4195 : {
4196 279764 : RestrictInfo *restrictinfo = (RestrictInfo *) lfirst(ic);
4197 :
4198 : /*
4199 : * Note: can_join won't be set for a restriction clause, but
4200 : * mergeopfamilies will be if it has a mergejoinable operator and
4201 : * doesn't contain volatile functions.
4202 : */
4203 279764 : if (restrictinfo->mergeopfamilies == NIL)
4204 119300 : continue; /* not mergejoinable */
4205 :
4206 : /*
4207 : * The clause certainly doesn't refer to anything but the given rel.
4208 : * If either side is pseudoconstant then we can use it.
4209 : */
4210 160464 : if (bms_is_empty(restrictinfo->left_relids))
4211 : {
4212 : /* righthand side is inner */
4213 40 : restrictinfo->outer_is_left = true;
4214 : }
4215 160424 : else if (bms_is_empty(restrictinfo->right_relids))
4216 : {
4217 : /* lefthand side is inner */
4218 160298 : restrictinfo->outer_is_left = false;
4219 : }
4220 : else
4221 126 : continue;
4222 :
4223 : /* OK, add to list */
4224 160338 : restrictlist = lappend(restrictlist, restrictinfo);
4225 : }
4226 :
4227 : /* Short-circuit the easy case */
4228 365786 : if (restrictlist == NIL && exprlist == NIL)
4229 980 : return false;
4230 :
4231 : /* Examine each index of the relation ... */
4232 819232 : foreach(ic, rel->indexlist)
4233 : {
4234 667756 : IndexOptInfo *ind = (IndexOptInfo *) lfirst(ic);
4235 : int c;
4236 667756 : List *exprs = NIL;
4237 :
4238 : /*
4239 : * If the index is not unique, or not immediately enforced, or if it's
4240 : * a partial index, it's useless here. We're unable to make use of
4241 : * predOK partial unique indexes due to the fact that
4242 : * check_index_predicates() also makes use of join predicates to
4243 : * determine if the partial index is usable. Here we need proofs that
4244 : * hold true before any joins are evaluated.
4245 : */
4246 667756 : if (!ind->unique || !ind->immediate || ind->indpred != NIL)
4247 158254 : continue;
4248 :
4249 : /*
4250 : * Try to find each index column in the lists of conditions. This is
4251 : * O(N^2) or worse, but we expect all the lists to be short.
4252 : */
4253 1003372 : for (c = 0; c < ind->nkeycolumns; c++)
4254 : {
4255 790042 : bool matched = false;
4256 : ListCell *lc;
4257 : ListCell *lc2;
4258 :
4259 1382978 : foreach(lc, restrictlist)
4260 : {
4261 1086806 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4262 : Node *rexpr;
4263 :
4264 : /*
4265 : * The condition's equality operator must be a member of the
4266 : * index opfamily, else it is not asserting the right kind of
4267 : * equality behavior for this index. We check this first
4268 : * since it's probably cheaper than match_index_to_operand().
4269 : */
4270 1086806 : if (!list_member_oid(rinfo->mergeopfamilies, ind->opfamily[c]))
4271 399834 : continue;
4272 :
4273 : /*
4274 : * XXX at some point we may need to check collations here too.
4275 : * For the moment we assume all collations reduce to the same
4276 : * notion of equality.
4277 : */
4278 :
4279 : /* OK, see if the condition operand matches the index key */
4280 686972 : if (rinfo->outer_is_left)
4281 281682 : rexpr = get_rightop(rinfo->clause);
4282 : else
4283 405290 : rexpr = get_leftop(rinfo->clause);
4284 :
4285 686972 : if (match_index_to_operand(rexpr, c, ind))
4286 : {
4287 493870 : matched = true; /* column is unique */
4288 :
4289 493870 : if (bms_membership(rinfo->clause_relids) == BMS_SINGLETON)
4290 : {
4291 : MemoryContext oldMemCtx =
4292 105604 : MemoryContextSwitchTo(root->planner_cxt);
4293 :
4294 : /*
4295 : * Add filter clause into a list allowing caller to
4296 : * know if uniqueness have made not only by join
4297 : * clauses.
4298 : */
4299 : Assert(bms_is_empty(rinfo->left_relids) ||
4300 : bms_is_empty(rinfo->right_relids));
4301 105604 : if (extra_clauses)
4302 144 : exprs = lappend(exprs, rinfo);
4303 105604 : MemoryContextSwitchTo(oldMemCtx);
4304 : }
4305 :
4306 493870 : break;
4307 : }
4308 : }
4309 :
4310 790042 : if (matched)
4311 493870 : continue;
4312 :
4313 296330 : forboth(lc, exprlist, lc2, oprlist)
4314 : {
4315 158 : Node *expr = (Node *) lfirst(lc);
4316 158 : Oid opr = lfirst_oid(lc2);
4317 :
4318 : /* See if the expression matches the index key */
4319 158 : if (!match_index_to_operand(expr, c, ind))
4320 158 : continue;
4321 :
4322 : /*
4323 : * The equality operator must be a member of the index
4324 : * opfamily, else it is not asserting the right kind of
4325 : * equality behavior for this index. We assume the caller
4326 : * determined it is an equality operator, so we don't need to
4327 : * check any more tightly than this.
4328 : */
4329 0 : if (!op_in_opfamily(opr, ind->opfamily[c]))
4330 0 : continue;
4331 :
4332 : /*
4333 : * XXX at some point we may need to check collations here too.
4334 : * For the moment we assume all collations reduce to the same
4335 : * notion of equality.
4336 : */
4337 :
4338 0 : matched = true; /* column is unique */
4339 0 : break;
4340 : }
4341 :
4342 296172 : if (!matched)
4343 296172 : break; /* no match; this index doesn't help us */
4344 : }
4345 :
4346 : /* Matched all key columns of this index? */
4347 509502 : if (c == ind->nkeycolumns)
4348 : {
4349 213330 : if (extra_clauses)
4350 642 : *extra_clauses = exprs;
4351 213330 : return true;
4352 : }
4353 : }
4354 :
4355 151476 : return false;
4356 : }
4357 :
4358 : /*
4359 : * indexcol_is_bool_constant_for_query
4360 : *
4361 : * If an index column is constrained to have a constant value by the query's
4362 : * WHERE conditions, then it's irrelevant for sort-order considerations.
4363 : * Usually that means we have a restriction clause WHERE indexcol = constant,
4364 : * which gets turned into an EquivalenceClass containing a constant, which
4365 : * is recognized as redundant by build_index_pathkeys(). But if the index
4366 : * column is a boolean variable (or expression), then we are not going to
4367 : * see WHERE indexcol = constant, because expression preprocessing will have
4368 : * simplified that to "WHERE indexcol" or "WHERE NOT indexcol". So we are not
4369 : * going to have a matching EquivalenceClass (unless the query also contains
4370 : * "ORDER BY indexcol"). To allow such cases to work the same as they would
4371 : * for non-boolean values, this function is provided to detect whether the
4372 : * specified index column matches a boolean restriction clause.
4373 : */
4374 : bool
4375 807832 : indexcol_is_bool_constant_for_query(PlannerInfo *root,
4376 : IndexOptInfo *index,
4377 : int indexcol)
4378 : {
4379 : ListCell *lc;
4380 :
4381 : /* If the index isn't boolean, we can't possibly get a match */
4382 807832 : if (!IsBooleanOpfamily(index->opfamily[indexcol]))
4383 734728 : return false;
4384 :
4385 : /* Check each restriction clause for the index's rel */
4386 73140 : foreach(lc, index->rel->baserestrictinfo)
4387 : {
4388 1008 : RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4389 :
4390 : /*
4391 : * As in match_clause_to_indexcol, never match pseudoconstants to
4392 : * indexes. (It might be semantically okay to do so here, but the
4393 : * odds of getting a match are negligible, so don't waste the cycles.)
4394 : */
4395 1008 : if (rinfo->pseudoconstant)
4396 0 : continue;
4397 :
4398 : /* See if we can match the clause's expression to the index column */
4399 1008 : if (match_boolean_index_clause(root, rinfo, indexcol, index))
4400 972 : return true;
4401 : }
4402 :
4403 72132 : return false;
4404 : }
4405 :
4406 :
4407 : /****************************************************************************
4408 : * ---- ROUTINES TO CHECK OPERANDS ----
4409 : ****************************************************************************/
4410 :
4411 : /*
4412 : * match_index_to_operand()
4413 : * Generalized test for a match between an index's key
4414 : * and the operand on one side of a restriction or join clause.
4415 : *
4416 : * operand: the nodetree to be compared to the index
4417 : * indexcol: the column number of the index (counting from 0)
4418 : * index: the index of interest
4419 : *
4420 : * Note that we aren't interested in collations here; the caller must check
4421 : * for a collation match, if it's dealing with an operator where that matters.
4422 : *
4423 : * This is exported for use in selfuncs.c.
4424 : */
4425 : bool
4426 5006806 : match_index_to_operand(Node *operand,
4427 : int indexcol,
4428 : IndexOptInfo *index)
4429 : {
4430 : int indkey;
4431 :
4432 : /*
4433 : * Ignore any RelabelType node above the operand. This is needed to be
4434 : * able to apply indexscanning in binary-compatible-operator cases. Note:
4435 : * we can assume there is at most one RelabelType node;
4436 : * eval_const_expressions() will have simplified if more than one.
4437 : */
4438 5006806 : if (operand && IsA(operand, RelabelType))
4439 23022 : operand = (Node *) ((RelabelType *) operand)->arg;
4440 :
4441 5006806 : indkey = index->indexkeys[indexcol];
4442 5006806 : if (indkey != 0)
4443 : {
4444 : /*
4445 : * Simple index column; operand must be a matching Var.
4446 : */
4447 5000832 : if (operand && IsA(operand, Var) &&
4448 3939506 : index->rel->relid == ((Var *) operand)->varno &&
4449 3511906 : indkey == ((Var *) operand)->varattno &&
4450 1628508 : ((Var *) operand)->varnullingrels == NULL)
4451 1627758 : return true;
4452 : }
4453 : else
4454 : {
4455 : /*
4456 : * Index expression; find the correct expression. (This search could
4457 : * be avoided, at the cost of complicating all the callers of this
4458 : * routine; doesn't seem worth it.)
4459 : */
4460 : ListCell *indexpr_item;
4461 : int i;
4462 : Node *indexkey;
4463 :
4464 5974 : indexpr_item = list_head(index->indexprs);
4465 5974 : for (i = 0; i < indexcol; i++)
4466 : {
4467 0 : if (index->indexkeys[i] == 0)
4468 : {
4469 0 : if (indexpr_item == NULL)
4470 0 : elog(ERROR, "wrong number of index expressions");
4471 0 : indexpr_item = lnext(index->indexprs, indexpr_item);
4472 : }
4473 : }
4474 5974 : if (indexpr_item == NULL)
4475 0 : elog(ERROR, "wrong number of index expressions");
4476 5974 : indexkey = (Node *) lfirst(indexpr_item);
4477 :
4478 : /*
4479 : * Does it match the operand? Again, strip any relabeling.
4480 : */
4481 5974 : if (indexkey && IsA(indexkey, RelabelType))
4482 10 : indexkey = (Node *) ((RelabelType *) indexkey)->arg;
4483 :
4484 5974 : if (equal(indexkey, operand))
4485 2164 : return true;
4486 : }
4487 :
4488 3376884 : return false;
4489 : }
4490 :
4491 : /*
4492 : * is_pseudo_constant_for_index()
4493 : * Test whether the given expression can be used as an indexscan
4494 : * comparison value.
4495 : *
4496 : * An indexscan comparison value must not contain any volatile functions,
4497 : * and it can't contain any Vars of the index's own table. Vars of
4498 : * other tables are okay, though; in that case we'd be producing an
4499 : * indexqual usable in a parameterized indexscan. This is, therefore,
4500 : * a weaker condition than is_pseudo_constant_clause().
4501 : *
4502 : * This function is exported for use by planner support functions,
4503 : * which will have available the IndexOptInfo, but not any RestrictInfo
4504 : * infrastructure. It is making the same test made by functions above
4505 : * such as match_opclause_to_indexcol(), but those rely where possible
4506 : * on RestrictInfo information about variable membership.
4507 : *
4508 : * expr: the nodetree to be checked
4509 : * index: the index of interest
4510 : */
4511 : bool
4512 0 : is_pseudo_constant_for_index(PlannerInfo *root, Node *expr, IndexOptInfo *index)
4513 : {
4514 : /* pull_varnos is cheaper than volatility check, so do that first */
4515 0 : if (bms_is_member(index->rel->relid, pull_varnos(root, expr)))
4516 0 : return false; /* no good, contains Var of table */
4517 0 : if (contain_volatile_functions(expr))
4518 0 : return false; /* no good, volatile comparison value */
4519 0 : return true;
4520 : }
|