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