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