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