LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/path - indxpath.c (source / functions) Coverage Total Hit LBC UBC GNC CBC DUB DCB
Current: a2387c32f2f8a1643c7d71b951587e6bcb2d4744 vs 371a302eecdc82274b0ae2967d18fd726a0aa6a1 Lines: 94.3 % 1236 1165 1 70 3 1162 4 15
Current Date: 2025-10-26 12:31:50 -0700 Functions: 97.9 % 47 46 1 1 45 1
Baseline: lcov-20251027-010456-baseline Branches: 81.9 % 1140 934 2 204 4 930
Baseline Date: 2025-10-26 11:01:32 +1300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(30,360] days: 95.1 % 283 269 14 3 266
(360..) days: 94.0 % 953 896 1 56 896
Function coverage date bins:
(30,360] days: 100.0 % 5 5 5
(360..) days: 97.6 % 42 41 1 1 40
Branch coverage date bins:
(30,360] days: 82.0 % 244 200 44 4 196
(360..) days: 81.9 % 896 734 2 160 734

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

Generated by: LCOV version 2.4-beta