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