LCOV - code coverage report
Current view: top level - src/backend/optimizer/path - indxpath.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 955 1021 93.5 %
Date: 2019-09-19 02:07:14 Functions: 42 43 97.7 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13