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

Generated by: LCOV version 2.4-beta