LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/util - plancat.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DUB DCB
Current: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 92.5 % 885 819 1 65 36 783 1 12
Current Date: 2025-09-06 07:49:51 +0900 Functions: 100.0 % 29 29 5 24 1
Baseline: lcov-20250906-005545-baseline Branches: 78.1 % 652 509 3 140 21 488
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 85.7 % 7 6 1 6
(7,30] days: 65.6 % 32 21 11 21
(30,360] days: 85.7 % 49 42 7 30 12
(360..) days: 94.1 % 797 750 47 750
Function coverage date bins:
(1,7] days: 100.0 % 1 1 1
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 2 2 2
(360..) days: 100.0 % 25 25 2 23
Branch coverage date bins:
(1,7] days: 75.0 % 4 3 1 3
(7,30] days: 44.4 % 27 12 15 12
(30,360] days: 77.5 % 40 31 2 7 18 13
(360..) days: 79.7 % 581 463 118 463

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * plancat.c
                                  4                 :                :  *     routines for accessing the system catalogs
                                  5                 :                :  *
                                  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/util/plancat.c
                                 13                 :                :  *
                                 14                 :                :  *-------------------------------------------------------------------------
                                 15                 :                :  */
                                 16                 :                : #include "postgres.h"
                                 17                 :                : 
                                 18                 :                : #include <math.h>
                                 19                 :                : 
                                 20                 :                : #include "access/genam.h"
                                 21                 :                : #include "access/htup_details.h"
                                 22                 :                : #include "access/nbtree.h"
                                 23                 :                : #include "access/sysattr.h"
                                 24                 :                : #include "access/table.h"
                                 25                 :                : #include "access/tableam.h"
                                 26                 :                : #include "access/transam.h"
                                 27                 :                : #include "access/xlog.h"
                                 28                 :                : #include "catalog/catalog.h"
                                 29                 :                : #include "catalog/heap.h"
                                 30                 :                : #include "catalog/pg_am.h"
                                 31                 :                : #include "catalog/pg_proc.h"
                                 32                 :                : #include "catalog/pg_statistic_ext.h"
                                 33                 :                : #include "catalog/pg_statistic_ext_data.h"
                                 34                 :                : #include "foreign/fdwapi.h"
                                 35                 :                : #include "miscadmin.h"
                                 36                 :                : #include "nodes/makefuncs.h"
                                 37                 :                : #include "nodes/nodeFuncs.h"
                                 38                 :                : #include "nodes/supportnodes.h"
                                 39                 :                : #include "optimizer/cost.h"
                                 40                 :                : #include "optimizer/optimizer.h"
                                 41                 :                : #include "optimizer/plancat.h"
                                 42                 :                : #include "parser/parse_relation.h"
                                 43                 :                : #include "parser/parsetree.h"
                                 44                 :                : #include "partitioning/partdesc.h"
                                 45                 :                : #include "rewrite/rewriteManip.h"
                                 46                 :                : #include "statistics/statistics.h"
                                 47                 :                : #include "storage/bufmgr.h"
                                 48                 :                : #include "tcop/tcopprot.h"
                                 49                 :                : #include "utils/builtins.h"
                                 50                 :                : #include "utils/lsyscache.h"
                                 51                 :                : #include "utils/partcache.h"
                                 52                 :                : #include "utils/rel.h"
                                 53                 :                : #include "utils/snapmgr.h"
                                 54                 :                : #include "utils/syscache.h"
                                 55                 :                : 
                                 56                 :                : /* GUC parameter */
                                 57                 :                : int         constraint_exclusion = CONSTRAINT_EXCLUSION_PARTITION;
                                 58                 :                : 
                                 59                 :                : /* Hook for plugins to get control in get_relation_info() */
                                 60                 :                : get_relation_info_hook_type get_relation_info_hook = NULL;
                                 61                 :                : 
                                 62                 :                : typedef struct NotnullHashEntry
                                 63                 :                : {
                                 64                 :                :     Oid         relid;          /* OID of the relation */
                                 65                 :                :     Relids      notnullattnums; /* attnums of NOT NULL columns */
                                 66                 :                : } NotnullHashEntry;
                                 67                 :                : 
                                 68                 :                : 
                                 69                 :                : static void get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
                                 70                 :                :                                       Relation relation, bool inhparent);
                                 71                 :                : static bool infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
                                 72                 :                :                                           List *idxExprs);
                                 73                 :                : static List *get_relation_constraints(PlannerInfo *root,
                                 74                 :                :                                       Oid relationObjectId, RelOptInfo *rel,
                                 75                 :                :                                       bool include_noinherit,
                                 76                 :                :                                       bool include_notnull,
                                 77                 :                :                                       bool include_partition);
                                 78                 :                : static List *build_index_tlist(PlannerInfo *root, IndexOptInfo *index,
                                 79                 :                :                                Relation heapRelation);
                                 80                 :                : static List *get_relation_statistics(PlannerInfo *root, RelOptInfo *rel,
                                 81                 :                :                                      Relation relation);
                                 82                 :                : static void set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel,
                                 83                 :                :                                         Relation relation);
                                 84                 :                : static PartitionScheme find_partition_scheme(PlannerInfo *root,
                                 85                 :                :                                              Relation relation);
                                 86                 :                : static void set_baserel_partition_key_exprs(Relation relation,
                                 87                 :                :                                             RelOptInfo *rel);
                                 88                 :                : static void set_baserel_partition_constraint(Relation relation,
                                 89                 :                :                                              RelOptInfo *rel);
                                 90                 :                : 
                                 91                 :                : 
                                 92                 :                : /*
                                 93                 :                :  * get_relation_info -
                                 94                 :                :  *    Retrieves catalog information for a given relation.
                                 95                 :                :  *
                                 96                 :                :  * Given the Oid of the relation, return the following info into fields
                                 97                 :                :  * of the RelOptInfo struct:
                                 98                 :                :  *
                                 99                 :                :  *  min_attr    lowest valid AttrNumber
                                100                 :                :  *  max_attr    highest valid AttrNumber
                                101                 :                :  *  indexlist   list of IndexOptInfos for relation's indexes
                                102                 :                :  *  statlist    list of StatisticExtInfo for relation's statistic objects
                                103                 :                :  *  serverid    if it's a foreign table, the server OID
                                104                 :                :  *  fdwroutine  if it's a foreign table, the FDW function pointers
                                105                 :                :  *  pages       number of pages
                                106                 :                :  *  tuples      number of tuples
                                107                 :                :  *  rel_parallel_workers user-defined number of parallel workers
                                108                 :                :  *
                                109                 :                :  * Also, add information about the relation's foreign keys to root->fkey_list.
                                110                 :                :  *
                                111                 :                :  * Also, initialize the attr_needed[] and attr_widths[] arrays.  In most
                                112                 :                :  * cases these are left as zeroes, but sometimes we need to compute attr
                                113                 :                :  * widths here, and we may as well cache the results for costsize.c.
                                114                 :                :  *
                                115                 :                :  * If inhparent is true, all we need to do is set up the attr arrays:
                                116                 :                :  * the RelOptInfo actually represents the appendrel formed by an inheritance
                                117                 :                :  * tree, and so the parent rel's physical size and index information isn't
                                118                 :                :  * important for it, however, for partitioned tables, we do populate the
                                119                 :                :  * indexlist as the planner uses unique indexes as unique proofs for certain
                                120                 :                :  * optimizations.
                                121                 :                :  */
                                122                 :                : void
 6927 tgl@sss.pgh.pa.us         123                 :CBC      230828 : get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
                                124                 :                :                   RelOptInfo *rel)
                                125                 :                : {
 8246                           126                 :         230828 :     Index       varno = rel->relid;
                                127                 :                :     Relation    relation;
                                128                 :                :     bool        hasindex;
 8251                           129                 :         230828 :     List       *indexinfos = NIL;
                                130                 :                : 
                                131                 :                :     /*
                                132                 :                :      * We need not lock the relation since it was already locked, either by
                                133                 :                :      * the rewriter or when expand_inherited_rtentry() added it to the query's
                                134                 :                :      * rangetable.
                                135                 :                :      */
 2420 andres@anarazel.de        136                 :         230828 :     relation = table_open(relationObjectId, NoLock);
                                137                 :                : 
                                138                 :                :     /*
                                139                 :                :      * Relations without a table AM can be used in a query only if they are of
                                140                 :                :      * special-cased relkinds.  This check prevents us from crashing later if,
                                141                 :                :      * for example, a view's ON SELECT rule has gone missing.  Note that
                                142                 :                :      * table_open() already rejected indexes and composite types; spell the
                                143                 :                :      * error the same way it does.
                                144                 :                :      */
 1055 tgl@sss.pgh.pa.us         145         [ +  + ]:         230828 :     if (!relation->rd_tableam)
                                146                 :                :     {
                                147         [ +  + ]:           9762 :         if (!(relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE ||
                                148         [ -  + ]:           8511 :               relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE))
 1055 tgl@sss.pgh.pa.us         149         [ #  # ]:UBC           0 :             ereport(ERROR,
                                150                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                                151                 :                :                      errmsg("cannot open relation \"%s\"",
                                152                 :                :                             RelationGetRelationName(relation)),
                                153                 :                :                      errdetail_relkind_not_supported(relation->rd_rel->relkind)));
                                154                 :                :     }
                                155                 :                : 
                                156                 :                :     /* Temporary and unlogged relations are inaccessible during recovery. */
 1629 bruce@momjian.us          157   [ +  +  -  + ]:CBC      230828 :     if (!RelationIsPermanent(relation) && RecoveryInProgress())
 5205 rhaas@postgresql.org      158         [ #  # ]:UBC           0 :         ereport(ERROR,
                                159                 :                :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                160                 :                :                  errmsg("cannot access temporary or unlogged relations during recovery")));
                                161                 :                : 
 8105 tgl@sss.pgh.pa.us         162                 :CBC      230828 :     rel->min_attr = FirstLowInvalidHeapAttributeNumber + 1;
                                163                 :         230828 :     rel->max_attr = RelationGetNumberOfAttributes(relation);
 5723 rhaas@postgresql.org      164                 :         230828 :     rel->reltablespace = RelationGetForm(relation)->reltablespace;
                                165                 :                : 
 7584 tgl@sss.pgh.pa.us         166         [ -  + ]:         230828 :     Assert(rel->max_attr >= rel->min_attr);
                                167                 :         230828 :     rel->attr_needed = (Relids *)
                                168                 :         230828 :         palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
                                169                 :         230828 :     rel->attr_widths = (int32 *)
                                170                 :         230828 :         palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(int32));
                                171                 :                : 
                                172                 :                :     /*
                                173                 :                :      * Record which columns are defined as NOT NULL.  We leave this
                                174                 :                :      * unpopulated for non-partitioned inheritance parent relations as it's
                                175                 :                :      * ambiguous as to what it means.  Some child tables may have a NOT NULL
                                176                 :                :      * constraint for a column while others may not.  We could work harder and
                                177                 :                :      * build a unioned set of all child relations notnullattnums, but there's
                                178                 :                :      * currently no need.  The RelOptInfo corresponding to the !inh
                                179                 :                :      * RangeTblEntry does get populated.
                                180                 :                :      */
  512 drowley@postgresql.o      181   [ +  +  +  + ]:         230828 :     if (!inhparent || relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
   46 rguo@postgresql.org       182                 :GNC      212276 :         rel->notnullattnums = find_relation_notnullatts(root, relationObjectId);
                                183                 :                : 
                                184                 :                :     /*
                                185                 :                :      * Estimate relation size --- unless it's an inheritance parent, in which
                                186                 :                :      * case the size we want is not the rel's own size but the size of its
                                187                 :                :      * inheritance tree.  That will be computed in set_append_rel_size().
                                188                 :                :      */
 6927 tgl@sss.pgh.pa.us         189         [ +  + ]:CBC      230828 :     if (!inhparent)
                                190                 :         203785 :         estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
 5076                           191                 :         203785 :                           &rel->pages, &rel->tuples, &rel->allvisfrac);
                                192                 :                : 
                                193                 :                :     /* Retrieve the parallel_workers reloption, or -1 if not set. */
 3376                           194         [ +  + ]:         230828 :     rel->rel_parallel_workers = RelationGetParallelWorkers(relation, -1);
                                195                 :                : 
                                196                 :                :     /*
                                197                 :                :      * Make list of indexes.  Ignore indexes on system catalogs if told to.
                                198                 :                :      * Don't bother with indexes from traditional inheritance parents.  For
                                199                 :                :      * partitioned tables, we need a list of at least unique indexes as these
                                200                 :                :      * serve as unique proofs for certain planner optimizations.  However,
                                201                 :                :      * let's not discriminate here and just record all partitioned indexes
                                202                 :                :      * whether they're unique indexes or not.
                                203                 :                :      */
  971 drowley@postgresql.o      204   [ +  +  +  + ]:         230828 :     if ((inhparent && relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
                                205   [ -  +  -  - ]:         212276 :         || (IgnoreSystemIndexes && IsSystemRelation(relation)))
 8251 tgl@sss.pgh.pa.us         206                 :          18552 :         hasindex = false;
                                207                 :                :     else
                                208                 :         212276 :         hasindex = relation->rd_rel->relhasindex;
                                209                 :                : 
                                210         [ +  + ]:         230828 :     if (hasindex)
                                211                 :                :     {
                                212                 :                :         List       *indexoidlist;
                                213                 :                :         LOCKMODE    lmode;
                                214                 :                :         ListCell   *l;
                                215                 :                : 
                                216                 :         171072 :         indexoidlist = RelationGetIndexList(relation);
                                217                 :                : 
                                218                 :                :         /*
                                219                 :                :          * For each index, we get the same type of lock that the executor will
                                220                 :                :          * need, and do not release it.  This saves a couple of trips to the
                                221                 :                :          * shared lock manager while not creating any real loss of
                                222                 :                :          * concurrency, because no schema changes could be happening on the
                                223                 :                :          * index while we hold lock on the parent rel, and no lock type used
                                224                 :                :          * for queries blocks any other kind of index operation.
                                225                 :                :          */
 2347                           226                 :         171072 :         lmode = root->simple_rte_array[varno]->rellockmode;
                                227                 :                : 
 7773 neilc@samurai.com         228   [ +  +  +  +  :         534038 :         foreach(l, indexoidlist)
                                              +  + ]
                                229                 :                :         {
 7769                           230                 :         362966 :             Oid         indexoid = lfirst_oid(l);
                                231                 :                :             Relation    indexRelation;
                                232                 :                :             Form_pg_index index;
  361 peter@eisentraut.org      233                 :         362966 :             IndexAmRoutine *amroutine = NULL;
                                234                 :                :             IndexOptInfo *info;
                                235                 :                :             int         ncolumns,
                                236                 :                :                         nkeycolumns;
                                237                 :                :             int         i;
                                238                 :                : 
                                239                 :                :             /*
                                240                 :                :              * Extract info from the relation descriptor for the index.
                                241                 :                :              */
 6977 tgl@sss.pgh.pa.us         242                 :         362966 :             indexRelation = index_open(indexoid, lmode);
 8137                           243                 :         362966 :             index = indexRelation->rd_index;
                                244                 :                : 
                                245                 :                :             /*
                                246                 :                :              * Ignore invalid indexes, since they can't safely be used for
                                247                 :                :              * queries.  Note that this is OK because the data structure we
                                248                 :                :              * are constructing is only used by the planner --- the executor
                                249                 :                :              * still needs to insert into "invalid" indexes, if they're marked
                                250                 :                :              * indisready.
                                251                 :                :              */
 2445 peter_e@gmx.net           252         [ +  + ]:         362966 :             if (!index->indisvalid)
                                253                 :                :             {
 6952 tgl@sss.pgh.pa.us         254                 :             11 :                 index_close(indexRelation, NoLock);
                                255                 :             11 :                 continue;
                                256                 :                :             }
                                257                 :                : 
                                258                 :                :             /*
                                259                 :                :              * If the index is valid, but cannot yet be used, ignore it; but
                                260                 :                :              * mark the plan we are generating as transient. See
                                261                 :                :              * src/backend/access/heap/README.HOT for discussion.
                                262                 :                :              */
 6561                           263         [ +  + ]:         362955 :             if (index->indcheckxmin &&
                                264         [ +  + ]:            149 :                 !TransactionIdPrecedes(HeapTupleHeaderGetXmin(indexRelation->rd_indextuple->t_data),
                                265                 :                :                                        TransactionXmin))
                                266                 :                :             {
                                267                 :            147 :                 root->glob->transientPlan = true;
                                268                 :            147 :                 index_close(indexRelation, NoLock);
                                269                 :            147 :                 continue;
                                270                 :                :             }
                                271                 :                : 
 8251                           272                 :         362808 :             info = makeNode(IndexOptInfo);
                                273                 :                : 
                                274                 :         362808 :             info->indexoid = index->indexrelid;
 5723 rhaas@postgresql.org      275                 :         362808 :             info->reltablespace =
                                276                 :         362808 :                 RelationGetForm(indexRelation)->reltablespace;
 7468 tgl@sss.pgh.pa.us         277                 :         362808 :             info->rel = rel;
 8137                           278                 :         362808 :             info->ncolumns = ncolumns = index->indnatts;
 2709 teodor@sigaev.ru          279                 :         362808 :             info->nkeycolumns = nkeycolumns = index->indnkeyatts;
                                280                 :                : 
 8137 tgl@sss.pgh.pa.us         281                 :         362808 :             info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
 2704 teodor@sigaev.ru          282                 :         362808 :             info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
 2709                           283                 :         362808 :             info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
                                284                 :         362808 :             info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
 3817 heikki.linnakangas@i      285                 :         362808 :             info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
                                286                 :                : 
 8137 tgl@sss.pgh.pa.us         287         [ +  + ]:        1049780 :             for (i = 0; i < ncolumns; i++)
                                288                 :                :             {
 7466                           289                 :         686972 :                 info->indexkeys[i] = index->indkey.values[i];
 2709 teodor@sigaev.ru          290                 :         686972 :                 info->canreturn[i] = index_can_return(indexRelation, i + 1);
                                291                 :                :             }
                                292                 :                : 
                                293         [ +  + ]:        1049571 :             for (i = 0; i < nkeycolumns; i++)
                                294                 :                :             {
 6673 tgl@sss.pgh.pa.us         295                 :         686763 :                 info->opfamily[i] = indexRelation->rd_opfamily[i];
                                296                 :         686763 :                 info->opcintype[i] = indexRelation->rd_opcintype[i];
 2704 teodor@sigaev.ru          297                 :         686763 :                 info->indexcollations[i] = indexRelation->rd_indcollation[i];
                                298                 :                :             }
                                299                 :                : 
 8251 tgl@sss.pgh.pa.us         300                 :         362808 :             info->relam = indexRelation->rd_rel->relam;
                                301                 :                : 
                                302                 :                :             /*
                                303                 :                :              * We don't have an AM for partitioned indexes, so we'll just
                                304                 :                :              * NULLify the AM related fields for those.
                                305                 :                :              */
  971 drowley@postgresql.o      306         [ +  + ]:         362808 :             if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
                                307                 :                :             {
                                308                 :                :                 /* We copy just the fields we need, not all of rd_indam */
                                309                 :         359485 :                 amroutine = indexRelation->rd_indam;
                                310                 :         359485 :                 info->amcanorderbyop = amroutine->amcanorderbyop;
                                311                 :         359485 :                 info->amoptionalkey = amroutine->amoptionalkey;
                                312                 :         359485 :                 info->amsearcharray = amroutine->amsearcharray;
                                313                 :         359485 :                 info->amsearchnulls = amroutine->amsearchnulls;
                                314                 :         359485 :                 info->amcanparallel = amroutine->amcanparallel;
                                315                 :         359485 :                 info->amhasgettuple = (amroutine->amgettuple != NULL);
                                316         [ +  - ]:         718970 :                 info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
  175 melanieplageman@gmai      317         [ +  - ]:         359485 :                     relation->rd_tableam->scan_bitmap_next_tuple != NULL;
  971 drowley@postgresql.o      318         [ +  + ]:         707985 :                 info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
                                319         [ +  - ]:         348500 :                                       amroutine->amrestrpos != NULL);
                                320                 :         359485 :                 info->amcostestimate = amroutine->amcostestimate;
                                321         [ -  + ]:         359485 :                 Assert(info->amcostestimate != NULL);
                                322                 :                : 
                                323                 :                :                 /* Fetch index opclass options */
                                324                 :         359485 :                 info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
                                325                 :                : 
                                326                 :                :                 /*
                                327                 :                :                  * Fetch the ordering information for the index, if any.
                                328                 :                :                  */
                                329         [ +  + ]:         359485 :                 if (info->relam == BTREE_AM_OID)
                                330                 :                :                 {
                                331                 :                :                     /*
                                332                 :                :                      * If it's a btree index, we can use its opfamily OIDs
                                333                 :                :                      * directly as the sort ordering opfamily OIDs.
                                334                 :                :                      */
                                335         [ -  + ]:         348500 :                     Assert(amroutine->amcanorder);
                                336                 :                : 
                                337                 :         348500 :                     info->sortopfamily = info->opfamily;
                                338                 :         348500 :                     info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
                                339                 :         348500 :                     info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
                                340                 :                : 
                                341         [ +  + ]:         890603 :                     for (i = 0; i < nkeycolumns; i++)
                                342                 :                :                     {
                                343                 :         542103 :                         int16       opt = indexRelation->rd_indoption[i];
                                344                 :                : 
                                345                 :         542103 :                         info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
                                346                 :         542103 :                         info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
                                347                 :                :                     }
                                348                 :                :                 }
                                349         [ -  + ]:          10985 :                 else if (amroutine->amcanorder)
                                350                 :                :                 {
                                351                 :                :                     /*
                                352                 :                :                      * Otherwise, identify the corresponding btree opfamilies
                                353                 :                :                      * by trying to map this index's "<" operators into btree.
                                354                 :                :                      * Since "<" uniquely defines the behavior of a sort
                                355                 :                :                      * order, this is a sufficient test.
                                356                 :                :                      *
                                357                 :                :                      * XXX This method is rather slow and complicated.  It'd
                                358                 :                :                      * be better to have a way to explicitly declare the
                                359                 :                :                      * corresponding btree opfamily for each opfamily of the
                                360                 :                :                      * other index type.
                                361                 :                :                      */
  971 drowley@postgresql.o      362                 :UBC           0 :                     info->sortopfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
                                363                 :              0 :                     info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
                                364                 :              0 :                     info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
                                365                 :                : 
                                366         [ #  # ]:              0 :                     for (i = 0; i < nkeycolumns; i++)
                                367                 :                :                     {
                                368                 :              0 :                         int16       opt = indexRelation->rd_indoption[i];
                                369                 :                :                         Oid         ltopr;
                                370                 :                :                         Oid         opfamily;
                                371                 :                :                         Oid         opcintype;
                                372                 :                :                         CompareType cmptype;
                                373                 :                : 
                                374                 :              0 :                         info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
                                375                 :              0 :                         info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
                                376                 :                : 
  153 peter@eisentraut.org      377                 :              0 :                         ltopr = get_opfamily_member_for_cmptype(info->opfamily[i],
                                378                 :              0 :                                                                 info->opcintype[i],
                                379                 :              0 :                                                                 info->opcintype[i],
                                380                 :                :                                                                 COMPARE_LT);
  971 drowley@postgresql.o      381   [ #  #  #  # ]:              0 :                         if (OidIsValid(ltopr) &&
                                382                 :              0 :                             get_ordering_op_properties(ltopr,
                                383                 :                :                                                        &opfamily,
                                384                 :                :                                                        &opcintype,
  153 peter@eisentraut.org      385                 :              0 :                                                        &cmptype) &&
                                386         [ #  # ]:              0 :                             opcintype == info->opcintype[i] &&
                                387         [ #  # ]:              0 :                             cmptype == COMPARE_LT)
                                388                 :                :                         {
                                389                 :                :                             /* Successful mapping */
                                390                 :              0 :                             info->sortopfamily[i] = opfamily;
                                391                 :                :                         }
                                392                 :                :                         else
                                393                 :                :                         {
                                394                 :                :                             /* Fail ... quietly treat index as unordered */
  971 drowley@postgresql.o      395                 :              0 :                             info->sortopfamily = NULL;
                                396                 :              0 :                             info->reverse_sort = NULL;
                                397                 :              0 :                             info->nulls_first = NULL;
                                398                 :              0 :                             break;
                                399                 :                :                         }
                                400                 :                :                     }
                                401                 :                :                 }
                                402                 :                :                 else
                                403                 :                :                 {
  971 drowley@postgresql.o      404                 :CBC       10985 :                     info->sortopfamily = NULL;
                                405                 :          10985 :                     info->reverse_sort = NULL;
                                406                 :          10985 :                     info->nulls_first = NULL;
                                407                 :                :                 }
                                408                 :                :             }
                                409                 :                :             else
                                410                 :                :             {
                                411                 :           3323 :                 info->amcanorderbyop = false;
                                412                 :           3323 :                 info->amoptionalkey = false;
                                413                 :           3323 :                 info->amsearcharray = false;
                                414                 :           3323 :                 info->amsearchnulls = false;
                                415                 :           3323 :                 info->amcanparallel = false;
                                416                 :           3323 :                 info->amhasgettuple = false;
                                417                 :           3323 :                 info->amhasgetbitmap = false;
                                418                 :           3323 :                 info->amcanmarkpos = false;
                                419                 :           3323 :                 info->amcostestimate = NULL;
                                420                 :                : 
 5395 tgl@sss.pgh.pa.us         421                 :           3323 :                 info->sortopfamily = NULL;
                                422                 :           3323 :                 info->reverse_sort = NULL;
                                423                 :           3323 :                 info->nulls_first = NULL;
                                424                 :                :             }
                                425                 :                : 
                                426                 :                :             /*
                                427                 :                :              * Fetch the index expressions and predicate, if any.  We must
                                428                 :                :              * modify the copies we obtain from the relcache to have the
                                429                 :                :              * correct varno for the parent relation, so that they match up
                                430                 :                :              * correctly against qual clauses.
                                431                 :                :              */
 8137                           432                 :         362808 :             info->indexprs = RelationGetIndexExpressions(indexRelation);
                                433                 :         362808 :             info->indpred = RelationGetIndexPredicate(indexRelation);
                                434   [ +  +  +  + ]:         362808 :             if (info->indexprs && varno != 1)
                                435                 :            969 :                 ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
                                436   [ +  +  +  + ]:         362808 :             if (info->indpred && varno != 1)
                                437                 :             63 :                 ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
                                438                 :                : 
                                439                 :                :             /* Build targetlist using the completed indexprs data */
 5079                           440                 :         362808 :             info->indextlist = build_index_tlist(root, info, relation);
                                441                 :                : 
 2999                           442                 :         362808 :             info->indrestrictinfo = NIL; /* set later, in indxpath.c */
                                443                 :         362808 :             info->predOK = false;    /* set later, in indxpath.c */
 8137                           444                 :         362808 :             info->unique = index->indisunique;
  268 drowley@postgresql.o      445                 :         362808 :             info->nullsnotdistinct = index->indnullsnotdistinct;
 5067 tgl@sss.pgh.pa.us         446                 :         362808 :             info->immediate = index->indimmediate;
 5316                           447                 :         362808 :             info->hypothetical = false;
                                448                 :                : 
                                449                 :                :             /*
                                450                 :                :              * Estimate the index size.  If it's not a partial index, we lock
                                451                 :                :              * the number-of-tuples estimate to equal the parent table; if it
                                452                 :                :              * is partial then we have to use the same methods as we would for
                                453                 :                :              * a table, except we can be sure that the index is not larger
                                454                 :                :              * than the table.  We must ignore partitioned indexes here as
                                455                 :                :              * there are not physical indexes.
                                456                 :                :              */
  971 drowley@postgresql.o      457         [ +  + ]:         362808 :             if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
                                458                 :                :             {
                                459         [ +  + ]:         359485 :                 if (info->indpred == NIL)
                                460                 :                :                 {
                                461                 :         358993 :                     info->pages = RelationGetNumberOfBlocks(indexRelation);
 7584 tgl@sss.pgh.pa.us         462                 :         358993 :                     info->tuples = rel->tuples;
                                463                 :                :                 }
                                464                 :                :                 else
                                465                 :                :                 {
                                466                 :                :                     double      allvisfrac; /* dummy */
                                467                 :                : 
  971 drowley@postgresql.o      468                 :            492 :                     estimate_rel_size(indexRelation, NULL,
                                469                 :            492 :                                       &info->pages, &info->tuples, &allvisfrac);
                                470         [ +  + ]:            492 :                     if (info->tuples > rel->tuples)
                                471                 :              9 :                         info->tuples = rel->tuples;
                                472                 :                :                 }
                                473                 :                : 
                                474                 :                :                 /*
                                475                 :                :                  * Get tree height while we have the index open
                                476                 :                :                  */
  361 peter@eisentraut.org      477         [ +  + ]:         359485 :                 if (amroutine->amgettreeheight)
                                478                 :                :                 {
                                479                 :         348500 :                     info->tree_height = amroutine->amgettreeheight(indexRelation);
                                480                 :                :                 }
                                481                 :                :                 else
                                482                 :                :                 {
                                483                 :                :                     /* For other index types, just set it to "unknown" for now */
  971 drowley@postgresql.o      484                 :          10985 :                     info->tree_height = -1;
                                485                 :                :                 }
                                486                 :                :             }
                                487                 :                :             else
                                488                 :                :             {
                                489                 :                :                 /* Zero these out for partitioned indexes */
                                490                 :           3323 :                 info->pages = 0;
                                491                 :           3323 :                 info->tuples = 0.0;
 4621 tgl@sss.pgh.pa.us         492                 :           3323 :                 info->tree_height = -1;
                                493                 :                :             }
                                494                 :                : 
 6977                           495                 :         362808 :             index_close(indexRelation, NoLock);
                                496                 :                : 
                                497                 :                :             /*
                                498                 :                :              * We've historically used lcons() here.  It'd make more sense to
                                499                 :                :              * use lappend(), but that causes the planner to change behavior
                                500                 :                :              * in cases where two indexes seem equally attractive.  For now,
                                501                 :                :              * stick with lcons() --- few tables should have so many indexes
                                502                 :                :              * that the O(N^2) behavior of lcons() is really a problem.
                                503                 :                :              */
 8251                           504                 :         362808 :             indexinfos = lcons(info, indexinfos);
                                505                 :                :         }
                                506                 :                : 
 7769 neilc@samurai.com         507                 :         171072 :         list_free(indexoidlist);
                                508                 :                :     }
                                509                 :                : 
 8251 tgl@sss.pgh.pa.us         510                 :         230828 :     rel->indexlist = indexinfos;
                                511                 :                : 
    6 rguo@postgresql.org       512                 :GNC      230828 :     rel->statlist = get_relation_statistics(root, rel, relation);
                                513                 :                : 
                                514                 :                :     /* Grab foreign-table info using the relcache, while we have it */
 4567 tgl@sss.pgh.pa.us         515         [ +  + ]:CBC      230828 :     if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
                                516                 :                :     {
                                517                 :                :         /* Check if the access to foreign tables is restricted */
  397 msawada@postgresql.o      518         [ +  + ]:           1251 :         if (unlikely((restrict_nonsystem_relation_kind & RESTRICT_RELKIND_FOREIGN_TABLE) != 0))
                                519                 :                :         {
                                520                 :                :             /* there must not be built-in foreign tables */
                                521         [ -  + ]:              2 :             Assert(RelationGetRelid(relation) >= FirstNormalObjectId);
                                522                 :                : 
                                523         [ +  - ]:              2 :             ereport(ERROR,
                                524                 :                :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                                525                 :                :                      errmsg("access to non-system foreign table is restricted")));
                                526                 :                :         }
                                527                 :                : 
 3772 tgl@sss.pgh.pa.us         528                 :           1249 :         rel->serverid = GetForeignServerIdByRelId(RelationGetRelid(relation));
 4567                           529                 :           1249 :         rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
                                530                 :                :     }
                                531                 :                :     else
                                532                 :                :     {
 3772                           533                 :         229577 :         rel->serverid = InvalidOid;
 4567                           534                 :         229577 :         rel->fdwroutine = NULL;
                                535                 :                :     }
                                536                 :                : 
                                537                 :                :     /* Collect info about relation's foreign keys, if relevant */
 3230                           538                 :         230819 :     get_relation_foreign_keys(root, rel, relation, inhparent);
                                539                 :                : 
                                540                 :                :     /* Collect info about functions implemented by the rel's table AM. */
 1652 drowley@postgresql.o      541         [ +  + ]:         230819 :     if (relation->rd_tableam &&
                                542         [ +  - ]:         221066 :         relation->rd_tableam->scan_set_tidrange != NULL &&
                                543         [ +  - ]:         221066 :         relation->rd_tableam->scan_getnextslot_tidrange != NULL)
                                544                 :         221066 :         rel->amflags |= AMFLAG_HAS_TID_RANGE;
                                545                 :                : 
                                546                 :                :     /*
                                547                 :                :      * Collect info about relation's partitioning scheme, if any. Only
                                548                 :                :      * inheritance parents may be partitioned.
                                549                 :                :      */
 2908 rhaas@postgresql.org      550   [ +  +  +  + ]:         230819 :     if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
                                551                 :           8491 :         set_relation_partition_info(root, rel, relation);
                                552                 :                : 
 2420 andres@anarazel.de        553                 :         230819 :     table_close(relation, NoLock);
                                554                 :                : 
                                555                 :                :     /*
                                556                 :                :      * Allow a plugin to editorialize on the info we obtained from the
                                557                 :                :      * catalogs.  Actions might include altering the assumed relation size,
                                558                 :                :      * removing an index, or adding a hypothetical index to the indexlist.
                                559                 :                :      */
 6679 tgl@sss.pgh.pa.us         560         [ -  + ]:         230819 :     if (get_relation_info_hook)
 6679 tgl@sss.pgh.pa.us         561                 :UBC           0 :         (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
10651 scrappy@hub.org           562                 :CBC      230819 : }
                                563                 :                : 
                                564                 :                : /*
                                565                 :                :  * get_relation_foreign_keys -
                                566                 :                :  *    Retrieves foreign key information for a given relation.
                                567                 :                :  *
                                568                 :                :  * ForeignKeyOptInfos for relevant foreign keys are created and added to
                                569                 :                :  * root->fkey_list.  We do this now while we have the relcache entry open.
                                570                 :                :  * We could sometimes avoid making useless ForeignKeyOptInfos if we waited
                                571                 :                :  * until all RelOptInfos have been built, but the cost of re-opening the
                                572                 :                :  * relcache entries would probably exceed any savings.
                                573                 :                :  */
                                574                 :                : static void
 3367 tgl@sss.pgh.pa.us         575                 :         230819 : get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
                                576                 :                :                           Relation relation, bool inhparent)
                                577                 :                : {
                                578                 :         230819 :     List       *rtable = root->parse->rtable;
                                579                 :                :     List       *cachedfkeys;
                                580                 :                :     ListCell   *lc;
                                581                 :                : 
                                582                 :                :     /*
                                583                 :                :      * If it's not a baserel, we don't care about its FKs.  Also, if the query
                                584                 :                :      * references only a single relation, we can skip the lookup since no FKs
                                585                 :                :      * could satisfy the requirements below.
                                586                 :                :      */
                                587   [ +  +  +  + ]:         440722 :     if (rel->reloptkind != RELOPT_BASEREL ||
                                588                 :         209903 :         list_length(rtable) < 2)
                                589                 :         121610 :         return;
                                590                 :                : 
                                591                 :                :     /*
                                592                 :                :      * If it's the parent of an inheritance tree, ignore its FKs.  We could
                                593                 :                :      * make useful FK-based deductions if we found that all members of the
                                594                 :                :      * inheritance tree have equivalent FK constraints, but detecting that
                                595                 :                :      * would require code that hasn't been written.
                                596                 :                :      */
 3230                           597         [ +  + ]:         109209 :     if (inhparent)
                                598                 :           2787 :         return;
                                599                 :                : 
                                600                 :                :     /*
                                601                 :                :      * Extract data about relation's FKs from the relcache.  Note that this
                                602                 :                :      * list belongs to the relcache and might disappear in a cache flush, so
                                603                 :                :      * we must not do any further catalog access within this function.
                                604                 :                :      */
 3367                           605                 :         106422 :     cachedfkeys = RelationGetFKeyList(relation);
                                606                 :                : 
                                607                 :                :     /*
                                608                 :                :      * Figure out which FKs are of interest for this query, and create
                                609                 :                :      * ForeignKeyOptInfos for them.  We want only FKs that reference some
                                610                 :                :      * other RTE of the current query.  In queries containing self-joins,
                                611                 :                :      * there might be more than one other RTE for a referenced table, and we
                                612                 :                :      * should make a ForeignKeyOptInfo for each occurrence.
                                613                 :                :      *
                                614                 :                :      * Ideally, we would ignore RTEs that correspond to non-baserels, but it's
                                615                 :                :      * too hard to identify those here, so we might end up making some useless
                                616                 :                :      * ForeignKeyOptInfos.  If so, match_foreign_keys_to_quals() will remove
                                617                 :                :      * them again.
                                618                 :                :      */
                                619   [ +  +  +  +  :         107719 :     foreach(lc, cachedfkeys)
                                              +  + ]
                                620                 :                :     {
                                621                 :           1297 :         ForeignKeyCacheInfo *cachedfk = (ForeignKeyCacheInfo *) lfirst(lc);
                                622                 :                :         Index       rti;
                                623                 :                :         ListCell   *lc2;
                                624                 :                : 
                                625                 :                :         /* conrelid should always be that of the table we're considering */
                                626         [ -  + ]:           1297 :         Assert(cachedfk->conrelid == RelationGetRelid(relation));
                                627                 :                : 
                                628                 :                :         /* skip constraints currently not enforced */
  157 peter@eisentraut.org      629         [ +  + ]:           1297 :         if (!cachedfk->conenforced)
                                630                 :              9 :             continue;
                                631                 :                : 
                                632                 :                :         /* Scan to find other RTEs matching confrelid */
 3367 tgl@sss.pgh.pa.us         633                 :           1288 :         rti = 0;
                                634   [ +  -  +  +  :           5698 :         foreach(lc2, rtable)
                                              +  + ]
                                635                 :                :         {
                                636                 :           4410 :             RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc2);
                                637                 :                :             ForeignKeyOptInfo *info;
                                638                 :                : 
                                639                 :           4410 :             rti++;
                                640                 :                :             /* Ignore if not the correct table */
                                641         [ +  + ]:           4410 :             if (rte->rtekind != RTE_RELATION ||
                                642         [ +  + ]:           2747 :                 rte->relid != cachedfk->confrelid)
                                643                 :           3325 :                 continue;
                                644                 :                :             /* Ignore if it's an inheritance parent; doesn't really match */
 3230                           645         [ +  + ]:           1085 :             if (rte->inh)
                                646                 :            129 :                 continue;
                                647                 :                :             /* Ignore self-referential FKs; we only care about joins */
 3367                           648         [ +  + ]:            956 :             if (rti == rel->relid)
                                649                 :             66 :                 continue;
                                650                 :                : 
                                651                 :                :             /* OK, let's make an entry */
                                652                 :            890 :             info = makeNode(ForeignKeyOptInfo);
                                653                 :            890 :             info->con_relid = rel->relid;
                                654                 :            890 :             info->ref_relid = rti;
                                655                 :            890 :             info->nkeys = cachedfk->nkeys;
                                656                 :            890 :             memcpy(info->conkey, cachedfk->conkey, sizeof(info->conkey));
                                657                 :            890 :             memcpy(info->confkey, cachedfk->confkey, sizeof(info->confkey));
                                658                 :            890 :             memcpy(info->conpfeqop, cachedfk->conpfeqop, sizeof(info->conpfeqop));
                                659                 :                :             /* zero out fields to be filled by match_foreign_keys_to_quals */
                                660                 :            890 :             info->nmatched_ec = 0;
 1774                           661                 :            890 :             info->nconst_ec = 0;
 3367                           662                 :            890 :             info->nmatched_rcols = 0;
                                663                 :            890 :             info->nmatched_ri = 0;
                                664                 :            890 :             memset(info->eclass, 0, sizeof(info->eclass));
 1774                           665                 :            890 :             memset(info->fk_eclass_member, 0, sizeof(info->fk_eclass_member));
 3367                           666                 :            890 :             memset(info->rinfos, 0, sizeof(info->rinfos));
                                667                 :                : 
                                668                 :            890 :             root->fkey_list = lappend(root->fkey_list, info);
                                669                 :                :         }
                                670                 :                :     }
                                671                 :                : }
                                672                 :                : 
                                673                 :                : /*
                                674                 :                :  * get_relation_notnullatts -
                                675                 :                :  *    Retrieves column not-null constraint information for a given relation.
                                676                 :                :  *
                                677                 :                :  * We do this while we have the relcache entry open, and store the column
                                678                 :                :  * not-null constraint information in a hash table based on the relation OID.
                                679                 :                :  */
                                680                 :                : void
   46 rguo@postgresql.org       681                 :GNC      249497 : get_relation_notnullatts(PlannerInfo *root, Relation relation)
                                682                 :                : {
                                683                 :         249497 :     Oid         relid = RelationGetRelid(relation);
                                684                 :                :     NotnullHashEntry *hentry;
                                685                 :                :     bool        found;
                                686                 :         249497 :     Relids      notnullattnums = NULL;
                                687                 :                : 
                                688                 :                :     /* bail out if the relation has no not-null constraints */
                                689         [ +  + ]:         249497 :     if (relation->rd_att->constr == NULL ||
                                690         [ +  + ]:         165414 :         !relation->rd_att->constr->has_not_null)
                                691                 :         102832 :         return;
                                692                 :                : 
                                693                 :                :     /* create the hash table if it hasn't been created yet */
                                694         [ +  + ]:         162747 :     if (root->glob->rel_notnullatts_hash == NULL)
                                695                 :                :     {
                                696                 :                :         HTAB       *hashtab;
                                697                 :                :         HASHCTL     hash_ctl;
                                698                 :                : 
                                699                 :          85506 :         hash_ctl.keysize = sizeof(Oid);
                                700                 :          85506 :         hash_ctl.entrysize = sizeof(NotnullHashEntry);
                                701                 :          85506 :         hash_ctl.hcxt = CurrentMemoryContext;
                                702                 :                : 
                                703                 :          85506 :         hashtab = hash_create("Relation NOT NULL attnums",
                                704                 :                :                               64L,  /* arbitrary initial size */
                                705                 :                :                               &hash_ctl,
                                706                 :                :                               HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
                                707                 :                : 
                                708                 :          85506 :         root->glob->rel_notnullatts_hash = hashtab;
                                709                 :                :     }
                                710                 :                : 
                                711                 :                :     /*
                                712                 :                :      * Create a hash entry for this relation OID, if we don't have one
                                713                 :                :      * already.
                                714                 :                :      */
                                715                 :         162747 :     hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
                                716                 :                :                                               &relid,
                                717                 :                :                                               HASH_ENTER,
                                718                 :                :                                               &found);
                                719                 :                : 
                                720                 :                :     /* bail out if a hash entry already exists for this relation OID */
                                721         [ +  + ]:         162747 :     if (found)
                                722                 :          16082 :         return;
                                723                 :                : 
                                724                 :                :     /* collect the column not-null constraint information for this relation */
                                725         [ +  + ]:        2172296 :     for (int i = 0; i < relation->rd_att->natts; i++)
                                726                 :                :     {
                                727                 :        2025631 :         CompactAttribute *attr = TupleDescCompactAttr(relation->rd_att, i);
                                728                 :                : 
                                729         [ -  + ]:        2025631 :         Assert(attr->attnullability != ATTNULLABLE_UNKNOWN);
                                730                 :                : 
                                731         [ +  + ]:        2025631 :         if (attr->attnullability == ATTNULLABLE_VALID)
                                732                 :                :         {
                                733                 :        1705494 :             notnullattnums = bms_add_member(notnullattnums, i + 1);
                                734                 :                : 
                                735                 :                :             /*
                                736                 :                :              * Per RemoveAttributeById(), dropped columns will have their
                                737                 :                :              * attnotnull unset, so we needn't check for dropped columns in
                                738                 :                :              * the above condition.
                                739                 :                :              */
                                740         [ -  + ]:        1705494 :             Assert(!attr->attisdropped);
                                741                 :                :         }
                                742                 :                :     }
                                743                 :                : 
                                744                 :                :     /* ... and initialize the new hash entry */
                                745                 :         146665 :     hentry->notnullattnums = notnullattnums;
                                746                 :                : }
                                747                 :                : 
                                748                 :                : /*
                                749                 :                :  * find_relation_notnullatts -
                                750                 :                :  *    Searches the hash table and returns the column not-null constraint
                                751                 :                :  *    information for a given relation.
                                752                 :                :  */
                                753                 :                : Relids
                                754                 :         219391 : find_relation_notnullatts(PlannerInfo *root, Oid relid)
                                755                 :                : {
                                756                 :                :     NotnullHashEntry *hentry;
                                757                 :                :     bool        found;
                                758                 :                : 
                                759         [ +  + ]:         219391 :     if (root->glob->rel_notnullatts_hash == NULL)
                                760                 :          58737 :         return NULL;
                                761                 :                : 
                                762                 :         160654 :     hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
                                763                 :                :                                               &relid,
                                764                 :                :                                               HASH_FIND,
                                765                 :                :                                               &found);
                                766         [ +  + ]:         160654 :     if (!found)
                                767                 :           2458 :         return NULL;
                                768                 :                : 
                                769                 :         158196 :     return hentry->notnullattnums;
                                770                 :                : }
                                771                 :                : 
                                772                 :                : /*
                                773                 :                :  * infer_arbiter_indexes -
                                774                 :                :  *    Determine the unique indexes used to arbitrate speculative insertion.
                                775                 :                :  *
                                776                 :                :  * Uses user-supplied inference clause expressions and predicate to match a
                                777                 :                :  * unique index from those defined and ready on the heap relation (target).
                                778                 :                :  * An exact match is required on columns/expressions (although they can appear
                                779                 :                :  * in any order).  However, the predicate given by the user need only restrict
                                780                 :                :  * insertion to a subset of some part of the table covered by some particular
                                781                 :                :  * unique index (in particular, a partial unique index) in order to be
                                782                 :                :  * inferred.
                                783                 :                :  *
                                784                 :                :  * The implementation does not consider which B-Tree operator class any
                                785                 :                :  * particular available unique index attribute uses, unless one was specified
                                786                 :                :  * in the inference specification. The same is true of collations.  In
                                787                 :                :  * particular, there is no system dependency on the default operator class for
                                788                 :                :  * the purposes of inference.  If no opclass (or collation) is specified, then
                                789                 :                :  * all matching indexes (that may or may not match the default in terms of
                                790                 :                :  * each attribute opclass/collation) are used for inference.
                                791                 :                :  */
                                792                 :                : List *
 3774 andres@anarazel.de        793                 :CBC         910 : infer_arbiter_indexes(PlannerInfo *root)
                                794                 :                : {
                                795                 :            910 :     OnConflictExpr *onconflict = root->parse->onConflict;
                                796                 :                : 
                                797                 :                :     /* Iteration state */
                                798                 :                :     Index       varno;
                                799                 :                :     RangeTblEntry *rte;
                                800                 :                :     Relation    relation;
                                801                 :            910 :     Oid         indexOidFromConstraint = InvalidOid;
                                802                 :                :     List       *indexList;
                                803                 :                :     ListCell   *l;
                                804                 :                : 
                                805                 :                :     /* Normalized inference attributes and inference expressions: */
                                806                 :            910 :     Bitmapset  *inferAttrs = NULL;
                                807                 :            910 :     List       *inferElems = NIL;
                                808                 :                : 
                                809                 :                :     /* Results */
 3763                           810                 :            910 :     List       *results = NIL;
                                811                 :                : 
                                812                 :                :     /*
                                813                 :                :      * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
                                814                 :                :      * specification or named constraint.  ON CONFLICT DO UPDATE statements
                                815                 :                :      * must always provide one or the other (but parser ought to have caught
                                816                 :                :      * that already).
                                817                 :                :      */
 3774                           818         [ +  + ]:            910 :     if (onconflict->arbiterElems == NIL &&
                                819         [ +  + ]:            210 :         onconflict->constraint == InvalidOid)
                                820                 :            114 :         return NIL;
                                821                 :                : 
                                822                 :                :     /*
                                823                 :                :      * We need not lock the relation since it was already locked, either by
                                824                 :                :      * the rewriter or when expand_inherited_rtentry() added it to the query's
                                825                 :                :      * rangetable.
                                826                 :                :      */
  452 tgl@sss.pgh.pa.us         827                 :            796 :     varno = root->parse->resultRelation;
                                828                 :            796 :     rte = rt_fetch(varno, root->parse->rtable);
                                829                 :                : 
 2347                           830                 :            796 :     relation = table_open(rte->relid, NoLock);
                                831                 :                : 
                                832                 :                :     /*
                                833                 :                :      * Build normalized/BMS representation of plain indexed attributes, as
                                834                 :                :      * well as a separate list of expression items.  This simplifies matching
                                835                 :                :      * the cataloged definition of indexes.
                                836                 :                :      */
 3774 andres@anarazel.de        837   [ +  +  +  +  :           1723 :     foreach(l, onconflict->arbiterElems)
                                              +  + ]
                                838                 :                :     {
 3405 tgl@sss.pgh.pa.us         839                 :            927 :         InferenceElem *elem = (InferenceElem *) lfirst(l);
                                840                 :                :         Var        *var;
                                841                 :                :         int         attno;
                                842                 :                : 
 3774 andres@anarazel.de        843         [ +  + ]:            927 :         if (!IsA(elem->expr, Var))
                                844                 :                :         {
                                845                 :                :             /* If not a plain Var, just shove it in inferElems for now */
                                846                 :             87 :             inferElems = lappend(inferElems, elem->expr);
                                847                 :             87 :             continue;
                                848                 :                :         }
                                849                 :                : 
                                850                 :            840 :         var = (Var *) elem->expr;
                                851                 :            840 :         attno = var->varattno;
                                852                 :                : 
 3405 tgl@sss.pgh.pa.us         853         [ -  + ]:            840 :         if (attno == 0)
 3774 andres@anarazel.de        854         [ #  # ]:UBC           0 :             ereport(ERROR,
                                855                 :                :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                                856                 :                :                      errmsg("whole row unique index inference specifications are not supported")));
                                857                 :                : 
 3405 tgl@sss.pgh.pa.us         858                 :CBC         840 :         inferAttrs = bms_add_member(inferAttrs,
                                859                 :                :                                     attno - FirstLowInvalidHeapAttributeNumber);
                                860                 :                :     }
                                861                 :                : 
                                862                 :                :     /*
                                863                 :                :      * Lookup named constraint's index.  This is not immediately returned
                                864                 :                :      * because some additional sanity checks are required.
                                865                 :                :      */
 3774 andres@anarazel.de        866         [ +  + ]:            796 :     if (onconflict->constraint != InvalidOid)
                                867                 :                :     {
                                868                 :             96 :         indexOidFromConstraint = get_constraint_index(onconflict->constraint);
                                869                 :                : 
                                870         [ -  + ]:             96 :         if (indexOidFromConstraint == InvalidOid)
 3774 andres@anarazel.de        871         [ #  # ]:UBC           0 :             ereport(ERROR,
                                872                 :                :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                                873                 :                :                      errmsg("constraint in ON CONFLICT clause has no associated index")));
                                874                 :                :     }
                                875                 :                : 
                                876                 :                :     /*
                                877                 :                :      * Using that representation, iterate through the list of indexes on the
                                878                 :                :      * target relation to try and find a match
                                879                 :                :      */
 3405 tgl@sss.pgh.pa.us         880                 :CBC         796 :     indexList = RelationGetIndexList(relation);
                                881                 :                : 
 3774 andres@anarazel.de        882   [ +  +  +  +  :           1710 :     foreach(l, indexList)
                                              +  + ]
                                883                 :                :     {
                                884                 :           1010 :         Oid         indexoid = lfirst_oid(l);
                                885                 :                :         Relation    idxRel;
                                886                 :                :         Form_pg_index idxForm;
                                887                 :                :         Bitmapset  *indexedAttrs;
                                888                 :                :         List       *idxExprs;
                                889                 :                :         List       *predExprs;
                                890                 :                :         AttrNumber  natt;
                                891                 :                :         ListCell   *el;
                                892                 :                : 
                                893                 :                :         /*
                                894                 :                :          * Extract info from the relation descriptor for the index.  Obtain
                                895                 :                :          * the same lock type that the executor will ultimately use.
                                896                 :                :          *
                                897                 :                :          * Let executor complain about !indimmediate case directly, because
                                898                 :                :          * enforcement needs to occur there anyway when an inference clause is
                                899                 :                :          * omitted.
                                900                 :                :          */
 2347 tgl@sss.pgh.pa.us         901                 :           1010 :         idxRel = index_open(indexoid, rte->rellockmode);
 3774 andres@anarazel.de        902                 :           1010 :         idxForm = idxRel->rd_index;
                                903                 :                : 
 2445 peter_e@gmx.net           904         [ +  + ]:           1010 :         if (!idxForm->indisvalid)
 3774 andres@anarazel.de        905                 :              3 :             goto next;
                                906                 :                : 
                                907                 :                :         /*
                                908                 :                :          * Note that we do not perform a check against indcheckxmin (like e.g.
                                909                 :                :          * get_relation_info()) here to eliminate candidates, because
                                910                 :                :          * uniqueness checking only cares about the most recently committed
                                911                 :                :          * tuple versions.
                                912                 :                :          */
                                913                 :                : 
                                914                 :                :         /*
                                915                 :                :          * Look for match on "ON constraint_name" variant, which may not be
                                916                 :                :          * unique constraint.  This can only be a constraint name.
                                917                 :                :          */
                                918         [ +  + ]:           1007 :         if (indexOidFromConstraint == idxForm->indexrelid)
                                919                 :                :         {
  354 peter@eisentraut.org      920   [ +  +  +  + ]:             96 :             if (idxForm->indisexclusion && onconflict->action == ONCONFLICT_UPDATE)
 3774 andres@anarazel.de        921         [ +  - ]:             39 :                 ereport(ERROR,
                                922                 :                :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
                                923                 :                :                          errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
                                924                 :                : 
 3763                           925                 :             57 :             results = lappend_oid(results, idxForm->indexrelid);
 3774                           926                 :             57 :             list_free(indexList);
                                927                 :             57 :             index_close(idxRel, NoLock);
 2420                           928                 :             57 :             table_close(relation, NoLock);
 3763                           929                 :             57 :             return results;
                                930                 :                :         }
 3774                           931         [ +  + ]:            911 :         else if (indexOidFromConstraint != InvalidOid)
                                932                 :                :         {
                                933                 :                :             /* No point in further work for index in named constraint case */
                                934                 :              9 :             goto next;
                                935                 :                :         }
                                936                 :                : 
                                937                 :                :         /*
                                938                 :                :          * Only considering conventional inference at this point (not named
                                939                 :                :          * constraints), so index under consideration can be immediately
                                940                 :                :          * skipped if it's not unique
                                941                 :                :          */
                                942         [ +  + ]:            902 :         if (!idxForm->indisunique)
                                943                 :              2 :             goto next;
                                944                 :                : 
                                945                 :                :         /*
                                946                 :                :          * So-called unique constraints with WITHOUT OVERLAPS are really
                                947                 :                :          * exclusion constraints, so skip those too.
                                948                 :                :          */
  354 peter@eisentraut.org      949         [ +  + ]:            900 :         if (idxForm->indisexclusion)
                                950                 :             72 :             goto next;
                                951                 :                : 
                                952                 :                :         /* Build BMS representation of plain (non expression) index attrs */
 3405 tgl@sss.pgh.pa.us         953                 :            828 :         indexedAttrs = NULL;
 2709 teodor@sigaev.ru          954         [ +  + ]:           1938 :         for (natt = 0; natt < idxForm->indnkeyatts; natt++)
                                955                 :                :         {
 3774 andres@anarazel.de        956                 :           1110 :             int         attno = idxRel->rd_index->indkey.values[natt];
                                957                 :                : 
                                958         [ +  + ]:           1110 :             if (attno != 0)
 3405 tgl@sss.pgh.pa.us         959                 :            954 :                 indexedAttrs = bms_add_member(indexedAttrs,
                                960                 :                :                                               attno - FirstLowInvalidHeapAttributeNumber);
                                961                 :                :         }
                                962                 :                : 
                                963                 :                :         /* Non-expression attributes (if any) must match */
 3774 andres@anarazel.de        964         [ +  + ]:            828 :         if (!bms_equal(indexedAttrs, inferAttrs))
                                965                 :            189 :             goto next;
                                966                 :                : 
                                967                 :                :         /* Expression attributes (if any) must match */
                                968                 :            639 :         idxExprs = RelationGetIndexExpressions(idxRel);
  452 tgl@sss.pgh.pa.us         969   [ +  +  +  + ]:            639 :         if (idxExprs && varno != 1)
                                970                 :              3 :             ChangeVarNodes((Node *) idxExprs, 1, varno, 0);
                                971                 :                : 
 3774 andres@anarazel.de        972   [ +  -  +  +  :           1458 :         foreach(el, onconflict->arbiterElems)
                                              +  + ]
                                973                 :                :         {
 3759 bruce@momjian.us          974                 :            843 :             InferenceElem *elem = (InferenceElem *) lfirst(el);
                                975                 :                : 
                                976                 :                :             /*
                                977                 :                :              * Ensure that collation/opclass aspects of inference expression
                                978                 :                :              * element match.  Even though this loop is primarily concerned
                                979                 :                :              * with matching expressions, it is a convenient point to check
                                980                 :                :              * this for both expressions and ordinary (non-expression)
                                981                 :                :              * attributes appearing as inference elements.
                                982                 :                :              */
 3695 andres@anarazel.de        983         [ +  + ]:            843 :             if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
 3774                           984                 :             24 :                 goto next;
                                985                 :                : 
                                986                 :                :             /*
                                987                 :                :              * Plain Vars don't factor into count of expression elements, and
                                988                 :                :              * the question of whether or not they satisfy the index
                                989                 :                :              * definition has already been considered (they must).
                                990                 :                :              */
                                991         [ +  + ]:            825 :             if (IsA(elem->expr, Var))
                                992                 :            738 :                 continue;
                                993                 :                : 
                                994                 :                :             /*
                                995                 :                :              * Might as well avoid redundant check in the rare cases where
                                996                 :                :              * infer_collation_opclass_match() is required to do real work.
                                997                 :                :              * Otherwise, check that element expression appears in cataloged
                                998                 :                :              * index definition.
                                999                 :                :              */
                               1000         [ +  + ]:             87 :             if (elem->infercollid != InvalidOid ||
 3763                          1001   [ +  +  +  + ]:            153 :                 elem->inferopclass != InvalidOid ||
 3774                          1002                 :             75 :                 list_member(idxExprs, elem->expr))
                               1003                 :             81 :                 continue;
                               1004                 :                : 
                               1005                 :              6 :             goto next;
                               1006                 :                :         }
                               1007                 :                : 
                               1008                 :                :         /*
                               1009                 :                :          * Now that all inference elements were matched, ensure that the
                               1010                 :                :          * expression elements from inference clause are not missing any
                               1011                 :                :          * cataloged expressions.  This does the right thing when unique
                               1012                 :                :          * indexes redundantly repeat the same attribute, or if attributes
                               1013                 :                :          * redundantly appear multiple times within an inference clause.
                               1014                 :                :          */
                               1015         [ +  + ]:            615 :         if (list_difference(idxExprs, inferElems) != NIL)
                               1016                 :             27 :             goto next;
                               1017                 :                : 
                               1018                 :                :         /*
                               1019                 :                :          * If it's a partial index, its predicate must be implied by the ON
                               1020                 :                :          * CONFLICT's WHERE clause.
                               1021                 :                :          */
                               1022                 :            588 :         predExprs = RelationGetIndexPredicate(idxRel);
  452 tgl@sss.pgh.pa.us        1023   [ +  +  +  + ]:            588 :         if (predExprs && varno != 1)
                               1024                 :              3 :             ChangeVarNodes((Node *) predExprs, 1, varno, 0);
                               1025                 :                : 
 3006 rhaas@postgresql.org     1026         [ +  + ]:            588 :         if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere, false))
 3774 andres@anarazel.de       1027                 :             18 :             goto next;
                               1028                 :                : 
 3763                          1029                 :            570 :         results = lappend_oid(results, idxForm->indexrelid);
 3774                          1030                 :            914 : next:
                               1031                 :            914 :         index_close(idxRel, NoLock);
                               1032                 :                :     }
                               1033                 :                : 
                               1034                 :            700 :     list_free(indexList);
 2420                          1035                 :            700 :     table_close(relation, NoLock);
                               1036                 :                : 
 3763                          1037         [ +  + ]:            700 :     if (results == NIL)
 3774                          1038         [ +  - ]:            157 :         ereport(ERROR,
                               1039                 :                :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
                               1040                 :                :                  errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
                               1041                 :                : 
 3763                          1042                 :            543 :     return results;
                               1043                 :                : }
                               1044                 :                : 
                               1045                 :                : /*
                               1046                 :                :  * infer_collation_opclass_match - ensure infer element opclass/collation match
                               1047                 :                :  *
                               1048                 :                :  * Given unique index inference element from inference specification, if
                               1049                 :                :  * collation was specified, or if opclass was specified, verify that there is
                               1050                 :                :  * at least one matching indexed attribute (occasionally, there may be more).
                               1051                 :                :  * Skip this in the common case where inference specification does not include
                               1052                 :                :  * collation or opclass (instead matching everything, regardless of cataloged
                               1053                 :                :  * collation/opclass of indexed attribute).
                               1054                 :                :  *
                               1055                 :                :  * At least historically, Postgres has not offered collations or opclasses
                               1056                 :                :  * with alternative-to-default notions of equality, so these additional
                               1057                 :                :  * criteria should only be required infrequently.
                               1058                 :                :  *
                               1059                 :                :  * Don't give up immediately when an inference element matches some attribute
                               1060                 :                :  * cataloged as indexed but not matching additional opclass/collation
                               1061                 :                :  * criteria.  This is done so that the implementation is as forgiving as
                               1062                 :                :  * possible of redundancy within cataloged index attributes (or, less
                               1063                 :                :  * usefully, within inference specification elements).  If collations actually
                               1064                 :                :  * differ between apparently redundantly indexed attributes (redundant within
                               1065                 :                :  * or across indexes), then there really is no redundancy as such.
                               1066                 :                :  *
                               1067                 :                :  * Note that if an inference element specifies an opclass and a collation at
                               1068                 :                :  * once, both must match in at least one particular attribute within index
                               1069                 :                :  * catalog definition in order for that inference element to be considered
                               1070                 :                :  * inferred/satisfied.
                               1071                 :                :  */
                               1072                 :                : static bool
 3774                          1073                 :            843 : infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
                               1074                 :                :                               List *idxExprs)
                               1075                 :                : {
                               1076                 :                :     AttrNumber  natt;
 2999 tgl@sss.pgh.pa.us        1077                 :            843 :     Oid         inferopfamily = InvalidOid; /* OID of opclass opfamily */
 3695 andres@anarazel.de       1078                 :            843 :     Oid         inferopcinputtype = InvalidOid; /* OID of opclass input type */
 3376 rhaas@postgresql.org     1079                 :            843 :     int         nplain = 0;     /* # plain attrs observed */
                               1080                 :                : 
                               1081                 :                :     /*
                               1082                 :                :      * If inference specification element lacks collation/opclass, then no
                               1083                 :                :      * need to check for exact match.
                               1084                 :                :      */
 3763 andres@anarazel.de       1085   [ +  +  +  + ]:            843 :     if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
 3774                          1086                 :            786 :         return true;
                               1087                 :                : 
                               1088                 :                :     /*
                               1089                 :                :      * Lookup opfamily and input type, for matching indexes
                               1090                 :                :      */
 3763                          1091         [ +  + ]:             57 :     if (elem->inferopclass)
                               1092                 :                :     {
                               1093                 :             42 :         inferopfamily = get_opclass_family(elem->inferopclass);
                               1094                 :             42 :         inferopcinputtype = get_opclass_input_type(elem->inferopclass);
                               1095                 :                :     }
                               1096                 :                : 
 3774                          1097         [ +  + ]:            123 :     for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
                               1098                 :                :     {
 3759 bruce@momjian.us         1099                 :            105 :         Oid         opfamily = idxRel->rd_opfamily[natt - 1];
                               1100                 :            105 :         Oid         opcinputtype = idxRel->rd_opcintype[natt - 1];
                               1101                 :            105 :         Oid         collation = idxRel->rd_indcollation[natt - 1];
 3695 andres@anarazel.de       1102                 :            105 :         int         attno = idxRel->rd_index->indkey.values[natt - 1];
                               1103                 :                : 
                               1104         [ +  + ]:            105 :         if (attno != 0)
                               1105                 :             84 :             nplain++;
                               1106                 :                : 
 3763                          1107   [ +  +  +  + ]:            105 :         if (elem->inferopclass != InvalidOid &&
                               1108         [ -  + ]:             33 :             (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
                               1109                 :                :         {
                               1110                 :                :             /* Attribute needed to match opclass, but didn't */
 3774                          1111                 :             45 :             continue;
                               1112                 :                :         }
                               1113                 :                : 
                               1114         [ +  + ]:             60 :         if (elem->infercollid != InvalidOid &&
                               1115         [ +  + ]:             42 :             elem->infercollid != collation)
                               1116                 :                :         {
                               1117                 :                :             /* Attribute needed to match collation, but didn't */
                               1118                 :             18 :             continue;
                               1119                 :                :         }
                               1120                 :                : 
                               1121                 :                :         /* If one matching index att found, good enough -- return true */
 3695                          1122         [ +  + ]:             42 :         if (IsA(elem->expr, Var))
                               1123                 :                :         {
                               1124         [ +  - ]:             27 :             if (((Var *) elem->expr)->varattno == attno)
                               1125                 :             27 :                 return true;
                               1126                 :                :         }
                               1127         [ +  - ]:             15 :         else if (attno == 0)
                               1128                 :                :         {
                               1129                 :             15 :             Node       *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
                               1130                 :                : 
                               1131                 :                :             /*
                               1132                 :                :              * Note that unlike routines like match_index_to_operand() we
                               1133                 :                :              * don't need to care about RelabelType.  Neither the index
                               1134                 :                :              * definition nor the inference clause should contain them.
                               1135                 :                :              */
                               1136         [ +  + ]:             15 :             if (equal(elem->expr, nattExpr))
                               1137                 :             12 :                 return true;
                               1138                 :                :         }
                               1139                 :                :     }
                               1140                 :                : 
 3774                          1141                 :             18 :     return false;
                               1142                 :                : }
                               1143                 :                : 
                               1144                 :                : /*
                               1145                 :                :  * estimate_rel_size - estimate # pages and # tuples in a table or index
                               1146                 :                :  *
                               1147                 :                :  * We also estimate the fraction of the pages that are marked all-visible in
                               1148                 :                :  * the visibility map, for use in estimation of index-only scans.
                               1149                 :                :  *
                               1150                 :                :  * If attr_widths isn't NULL, it points to the zero-index entry of the
                               1151                 :                :  * relation's attr_widths[] cache; we fill this in if we have need to compute
                               1152                 :                :  * the attribute widths for estimation purposes.
                               1153                 :                :  */
                               1154                 :                : void
 7584 tgl@sss.pgh.pa.us        1155                 :         220493 : estimate_rel_size(Relation rel, int32 *attr_widths,
                               1156                 :                :                   BlockNumber *pages, double *tuples, double *allvisfrac)
                               1157                 :                : {
                               1158                 :                :     BlockNumber curpages;
                               1159                 :                :     BlockNumber relpages;
                               1160                 :                :     double      reltuples;
                               1161                 :                :     BlockNumber relallvisible;
                               1162                 :                :     double      density;
                               1163                 :                : 
 1373 peter@eisentraut.org     1164   [ +  +  +  +  :         220493 :     if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
                                              +  + ]
                               1165                 :                :     {
 1213 tgl@sss.pgh.pa.us        1166                 :         218730 :         table_relation_estimate_size(rel, attr_widths, pages, tuples,
                               1167                 :                :                                      allvisfrac);
                               1168                 :                :     }
 1373 peter@eisentraut.org     1169         [ +  + ]:           1763 :     else if (rel->rd_rel->relkind == RELKIND_INDEX)
                               1170                 :                :     {
                               1171                 :                :         /*
                               1172                 :                :          * XXX: It'd probably be good to move this into a callback, individual
                               1173                 :                :          * index types e.g. know if they have a metapage.
                               1174                 :                :          */
                               1175                 :                : 
                               1176                 :                :         /* it has storage, ok to call the smgr */
 1213 tgl@sss.pgh.pa.us        1177                 :            492 :         curpages = RelationGetNumberOfBlocks(rel);
                               1178                 :                : 
                               1179                 :                :         /* report estimated # pages */
                               1180                 :            492 :         *pages = curpages;
                               1181                 :                :         /* quick exit if rel is clearly empty */
                               1182         [ -  + ]:            492 :         if (curpages == 0)
                               1183                 :                :         {
 1213 tgl@sss.pgh.pa.us        1184                 :UBC           0 :             *tuples = 0;
                               1185                 :              0 :             *allvisfrac = 0;
                               1186                 :              0 :             return;
                               1187                 :                :         }
                               1188                 :                : 
                               1189                 :                :         /* coerce values in pg_class to more desirable types */
 1213 tgl@sss.pgh.pa.us        1190                 :CBC         492 :         relpages = (BlockNumber) rel->rd_rel->relpages;
                               1191                 :            492 :         reltuples = (double) rel->rd_rel->reltuples;
                               1192                 :            492 :         relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
                               1193                 :                : 
                               1194                 :                :         /*
                               1195                 :                :          * Discount the metapage while estimating the number of tuples. This
                               1196                 :                :          * is a kluge because it assumes more than it ought to about index
                               1197                 :                :          * structure.  Currently it's OK for btree, hash, and GIN indexes but
                               1198                 :                :          * suspect for GiST indexes.
                               1199                 :                :          */
                               1200         [ +  + ]:            492 :         if (relpages > 0)
                               1201                 :                :         {
                               1202                 :            483 :             curpages--;
                               1203                 :            483 :             relpages--;
                               1204                 :                :         }
                               1205                 :                : 
                               1206                 :                :         /* estimate number of tuples from previous tuple density */
                               1207   [ +  +  +  + ]:            492 :         if (reltuples >= 0 && relpages > 0)
                               1208                 :            333 :             density = reltuples / (double) relpages;
                               1209                 :                :         else
                               1210                 :                :         {
                               1211                 :                :             /*
                               1212                 :                :              * If we have no data because the relation was never vacuumed,
                               1213                 :                :              * estimate tuple width from attribute datatypes.  We assume here
                               1214                 :                :              * that the pages are completely full, which is OK for tables
                               1215                 :                :              * (since they've presumably not been VACUUMed yet) but is
                               1216                 :                :              * probably an overestimate for indexes.  Fortunately
                               1217                 :                :              * get_relation_info() can clamp the overestimate to the parent
                               1218                 :                :              * table's size.
                               1219                 :                :              *
                               1220                 :                :              * Note: this code intentionally disregards alignment
                               1221                 :                :              * considerations, because (a) that would be gilding the lily
                               1222                 :                :              * considering how crude the estimate is, and (b) it creates
                               1223                 :                :              * platform dependencies in the default plans which are kind of a
                               1224                 :                :              * headache for regression testing.
                               1225                 :                :              *
                               1226                 :                :              * XXX: Should this logic be more index specific?
                               1227                 :                :              */
                               1228                 :                :             int32       tuple_width;
                               1229                 :                : 
                               1230                 :            159 :             tuple_width = get_rel_data_width(rel, attr_widths);
                               1231                 :            159 :             tuple_width += MAXALIGN(SizeofHeapTupleHeader);
                               1232                 :            159 :             tuple_width += sizeof(ItemIdData);
                               1233                 :                :             /* note: integer division is intentional here */
                               1234                 :            159 :             density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
                               1235                 :                :         }
                               1236                 :            492 :         *tuples = rint(density * (double) curpages);
                               1237                 :                : 
                               1238                 :                :         /*
                               1239                 :                :          * We use relallvisible as-is, rather than scaling it up like we do
                               1240                 :                :          * for the pages and tuples counts, on the theory that any pages added
                               1241                 :                :          * since the last VACUUM are most likely not marked all-visible.  But
                               1242                 :                :          * costsize.c wants it converted to a fraction.
                               1243                 :                :          */
                               1244   [ -  +  -  - ]:            492 :         if (relallvisible == 0 || curpages <= 0)
                               1245                 :            492 :             *allvisfrac = 0;
 1213 tgl@sss.pgh.pa.us        1246         [ #  # ]:UBC           0 :         else if ((double) relallvisible >= curpages)
                               1247                 :              0 :             *allvisfrac = 1;
                               1248                 :                :         else
                               1249                 :              0 :             *allvisfrac = (double) relallvisible / curpages;
                               1250                 :                :     }
                               1251                 :                :     else
                               1252                 :                :     {
                               1253                 :                :         /*
                               1254                 :                :          * Just use whatever's in pg_class.  This covers foreign tables,
                               1255                 :                :          * sequences, and also relkinds without storage (shouldn't get here?);
                               1256                 :                :          * see initializations in AddNewRelationTuple().  Note that FDW must
                               1257                 :                :          * cope if reltuples is -1!
                               1258                 :                :          */
 1213 tgl@sss.pgh.pa.us        1259                 :CBC        1271 :         *pages = rel->rd_rel->relpages;
                               1260                 :           1271 :         *tuples = rel->rd_rel->reltuples;
                               1261                 :           1271 :         *allvisfrac = 0;
                               1262                 :                :     }
                               1263                 :                : }
                               1264                 :                : 
                               1265                 :                : 
                               1266                 :                : /*
                               1267                 :                :  * get_rel_data_width
                               1268                 :                :  *
                               1269                 :                :  * Estimate the average width of (the data part of) the relation's tuples.
                               1270                 :                :  *
                               1271                 :                :  * If attr_widths isn't NULL, it points to the zero-index entry of the
                               1272                 :                :  * relation's attr_widths[] cache; use and update that cache as appropriate.
                               1273                 :                :  *
                               1274                 :                :  * Currently we ignore dropped columns.  Ideally those should be included
                               1275                 :                :  * in the result, but we haven't got any way to get info about them; and
                               1276                 :                :  * since they might be mostly NULLs, treating them as zero-width is not
                               1277                 :                :  * necessarily the wrong thing anyway.
                               1278                 :                :  */
                               1279                 :                : int32
 5448                          1280                 :          73455 : get_rel_data_width(Relation rel, int32 *attr_widths)
                               1281                 :                : {
  627                          1282                 :          73455 :     int64       tuple_width = 0;
                               1283                 :                :     int         i;
                               1284                 :                : 
 5448                          1285         [ +  + ]:         393979 :     for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
                               1286                 :                :     {
 2939 andres@anarazel.de       1287                 :         320524 :         Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
                               1288                 :                :         int32       item_width;
                               1289                 :                : 
 5448 tgl@sss.pgh.pa.us        1290         [ +  + ]:         320524 :         if (att->attisdropped)
                               1291                 :           1336 :             continue;
                               1292                 :                : 
                               1293                 :                :         /* use previously cached data, if any */
 5405                          1294   [ +  +  +  + ]:         319188 :         if (attr_widths != NULL && attr_widths[i] > 0)
                               1295                 :                :         {
                               1296                 :           2911 :             tuple_width += attr_widths[i];
                               1297                 :           2911 :             continue;
                               1298                 :                :         }
                               1299                 :                : 
                               1300                 :                :         /* This should match set_rel_width() in costsize.c */
 5448                          1301                 :         316277 :         item_width = get_attavgwidth(RelationGetRelid(rel), i);
                               1302         [ +  + ]:         316277 :         if (item_width <= 0)
                               1303                 :                :         {
                               1304                 :         315353 :             item_width = get_typavgwidth(att->atttypid, att->atttypmod);
                               1305         [ -  + ]:         315353 :             Assert(item_width > 0);
                               1306                 :                :         }
                               1307         [ +  + ]:         316277 :         if (attr_widths != NULL)
                               1308                 :         279442 :             attr_widths[i] = item_width;
                               1309                 :         316277 :         tuple_width += item_width;
                               1310                 :                :     }
                               1311                 :                : 
  627                          1312                 :          73455 :     return clamp_width_est(tuple_width);
                               1313                 :                : }
                               1314                 :                : 
                               1315                 :                : /*
                               1316                 :                :  * get_relation_data_width
                               1317                 :                :  *
                               1318                 :                :  * External API for get_rel_data_width: same behavior except we have to
                               1319                 :                :  * open the relcache entry.
                               1320                 :                :  */
                               1321                 :                : int32
 5405                          1322                 :           1265 : get_relation_data_width(Oid relid, int32 *attr_widths)
                               1323                 :                : {
                               1324                 :                :     int32       result;
                               1325                 :                :     Relation    relation;
                               1326                 :                : 
                               1327                 :                :     /* As above, assume relation is already locked */
 2420 andres@anarazel.de       1328                 :           1265 :     relation = table_open(relid, NoLock);
                               1329                 :                : 
 5405 tgl@sss.pgh.pa.us        1330                 :           1265 :     result = get_rel_data_width(relation, attr_widths);
                               1331                 :                : 
 2420 andres@anarazel.de       1332                 :           1265 :     table_close(relation, NoLock);
                               1333                 :                : 
 5448 tgl@sss.pgh.pa.us        1334                 :           1265 :     return result;
                               1335                 :                : }
                               1336                 :                : 
                               1337                 :                : 
                               1338                 :                : /*
                               1339                 :                :  * get_relation_constraints
                               1340                 :                :  *
                               1341                 :                :  * Retrieve the applicable constraint expressions of the given relation.
                               1342                 :                :  * Only constraints that have been validated are considered.
                               1343                 :                :  *
                               1344                 :                :  * Returns a List (possibly empty) of constraint expressions.  Each one
                               1345                 :                :  * has been canonicalized, and its Vars are changed to have the varno
                               1346                 :                :  * indicated by rel->relid.  This allows the expressions to be easily
                               1347                 :                :  * compared to expressions taken from WHERE.
                               1348                 :                :  *
                               1349                 :                :  * If include_noinherit is true, it's okay to include constraints that
                               1350                 :                :  * are marked NO INHERIT.
                               1351                 :                :  *
                               1352                 :                :  * If include_notnull is true, "col IS NOT NULL" expressions are generated
                               1353                 :                :  * and added to the result for each column that's marked attnotnull.
                               1354                 :                :  *
                               1355                 :                :  * If include_partition is true, and the relation is a partition,
                               1356                 :                :  * also include the partitioning constraints.
                               1357                 :                :  *
                               1358                 :                :  * Note: at present this is invoked at most once per relation per planner
                               1359                 :                :  * run, and in many cases it won't be invoked at all, so there seems no
                               1360                 :                :  * point in caching the data in RelOptInfo.
                               1361                 :                :  */
                               1362                 :                : static List *
 6367                          1363                 :          10644 : get_relation_constraints(PlannerInfo *root,
                               1364                 :                :                          Oid relationObjectId, RelOptInfo *rel,
                               1365                 :                :                          bool include_noinherit,
                               1366                 :                :                          bool include_notnull,
                               1367                 :                :                          bool include_partition)
                               1368                 :                : {
 7350                          1369                 :          10644 :     List       *result = NIL;
                               1370                 :          10644 :     Index       varno = rel->relid;
                               1371                 :                :     Relation    relation;
                               1372                 :                :     TupleConstr *constr;
                               1373                 :                : 
                               1374                 :                :     /*
                               1375                 :                :      * We assume the relation has already been safely locked.
                               1376                 :                :      */
 2420 andres@anarazel.de       1377                 :          10644 :     relation = table_open(relationObjectId, NoLock);
                               1378                 :                : 
 7350 tgl@sss.pgh.pa.us        1379                 :          10644 :     constr = relation->rd_att->constr;
                               1380         [ +  + ]:          10644 :     if (constr != NULL)
                               1381                 :                :     {
 7266 bruce@momjian.us         1382                 :           4008 :         int         num_check = constr->num_check;
                               1383                 :                :         int         i;
                               1384                 :                : 
 7350 tgl@sss.pgh.pa.us        1385         [ +  + ]:           4292 :         for (i = 0; i < num_check; i++)
                               1386                 :                :         {
                               1387                 :                :             Node       *cexpr;
                               1388                 :                : 
                               1389                 :                :             /*
                               1390                 :                :              * If this constraint hasn't been fully validated yet, we must
                               1391                 :                :              * ignore it here.
                               1392                 :                :              */
 5211 alvherre@alvh.no-ip.     1393         [ +  + ]:            284 :             if (!constr->check[i].ccvalid)
                               1394                 :             27 :                 continue;
                               1395                 :                : 
                               1396                 :                :             /*
                               1397                 :                :              * NOT ENFORCED constraints are always marked as invalid, which
                               1398                 :                :              * should have been ignored.
                               1399                 :                :              */
  238 peter@eisentraut.org     1400         [ -  + ]:            257 :             Assert(constr->check[i].ccenforced);
                               1401                 :                : 
                               1402                 :                :             /*
                               1403                 :                :              * Also ignore if NO INHERIT and we weren't told that that's safe.
                               1404                 :                :              */
 2321 tgl@sss.pgh.pa.us        1405   [ +  +  -  + ]:            257 :             if (constr->check[i].ccnoinherit && !include_noinherit)
 2321 tgl@sss.pgh.pa.us        1406                 :UBC           0 :                 continue;
                               1407                 :                : 
 7350 tgl@sss.pgh.pa.us        1408                 :CBC         257 :             cexpr = stringToNode(constr->check[i].ccbin);
                               1409                 :                : 
                               1410                 :                :             /*
                               1411                 :                :              * Fix Vars to have the desired varno.  This must be done before
                               1412                 :                :              * const-simplification because eval_const_expressions reduces
                               1413                 :                :              * NullTest for Vars based on varno.
                               1414                 :                :              */
    6 rguo@postgresql.org      1415         [ +  + ]:GNC         257 :             if (varno != 1)
                               1416                 :            251 :                 ChangeVarNodes(cexpr, 1, varno, 0);
                               1417                 :                : 
                               1418                 :                :             /*
                               1419                 :                :              * Run each expression through const-simplification and
                               1420                 :                :              * canonicalization.  This is not just an optimization, but is
                               1421                 :                :              * necessary, because we will be comparing it to
                               1422                 :                :              * similarly-processed qual clauses, and may fail to detect valid
                               1423                 :                :              * matches without this.  This must match the processing done to
                               1424                 :                :              * qual clauses in preprocess_expression()!  (We can skip the
                               1425                 :                :              * stuff involving subqueries, however, since we don't allow any
                               1426                 :                :              * in check constraints.)
                               1427                 :                :              */
 6367 tgl@sss.pgh.pa.us        1428                 :CBC         257 :             cexpr = eval_const_expressions(root, cexpr);
                               1429                 :                : 
 2736                          1430                 :            257 :             cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
                               1431                 :                : 
                               1432                 :                :             /*
                               1433                 :                :              * Finally, convert to implicit-AND format (that is, a List) and
                               1434                 :                :              * append the resulting item(s) to our output list.
                               1435                 :                :              */
 7350                          1436                 :            257 :             result = list_concat(result,
                               1437                 :            257 :                                  make_ands_implicit((Expr *) cexpr));
                               1438                 :                :         }
                               1439                 :                : 
                               1440                 :                :         /* Add NOT NULL constraints in expression form, if requested */
 6447                          1441   [ +  +  +  + ]:           4008 :         if (include_notnull && constr->has_not_null)
                               1442                 :                :         {
 5931 bruce@momjian.us         1443                 :           3786 :             int         natts = relation->rd_att->natts;
                               1444                 :                : 
 6447 tgl@sss.pgh.pa.us        1445         [ +  + ]:          15405 :             for (i = 1; i <= natts; i++)
                               1446                 :                :             {
  152 alvherre@alvh.no-ip.     1447                 :          11619 :                 CompactAttribute *att = TupleDescCompactAttr(relation->rd_att, i - 1);
                               1448                 :                : 
                               1449   [ +  +  +  - ]:          11619 :                 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
                               1450                 :                :                 {
                               1451                 :           4663 :                     Form_pg_attribute wholeatt = TupleDescAttr(relation->rd_att, i - 1);
 5931 bruce@momjian.us         1452                 :           4663 :                     NullTest   *ntest = makeNode(NullTest);
                               1453                 :                : 
 6447 tgl@sss.pgh.pa.us        1454                 :           4663 :                     ntest->arg = (Expr *) makeVar(varno,
                               1455                 :                :                                                   i,
                               1456                 :                :                                                   wholeatt->atttypid,
                               1457                 :                :                                                   wholeatt->atttypmod,
                               1458                 :                :                                                   wholeatt->attcollation,
                               1459                 :                :                                                   0);
                               1460                 :           4663 :                     ntest->nulltesttype = IS_NOT_NULL;
                               1461                 :                : 
                               1462                 :                :                     /*
                               1463                 :                :                      * argisrow=false is correct even for a composite column,
                               1464                 :                :                      * because attnotnull does not represent a SQL-spec IS NOT
                               1465                 :                :                      * NULL test in such a case, just IS DISTINCT FROM NULL.
                               1466                 :                :                      */
 3327                          1467                 :           4663 :                     ntest->argisrow = false;
 3849                          1468                 :           4663 :                     ntest->location = -1;
 6447                          1469                 :           4663 :                     result = lappend(result, ntest);
                               1470                 :                :                 }
                               1471                 :                :             }
                               1472                 :                :         }
                               1473                 :                :     }
                               1474                 :                : 
                               1475                 :                :     /*
                               1476                 :                :      * Add partitioning constraints, if requested.
                               1477                 :                :      */
 2321                          1478   [ +  +  +  + ]:          10644 :     if (include_partition && relation->rd_rel->relispartition)
                               1479                 :                :     {
                               1480                 :                :         /* make sure rel->partition_qual is set */
 2216 alvherre@alvh.no-ip.     1481                 :              6 :         set_baserel_partition_constraint(relation, rel);
                               1482                 :              6 :         result = list_concat(result, rel->partition_qual);
                               1483                 :                :     }
                               1484                 :                : 
 2420 andres@anarazel.de       1485                 :          10644 :     table_close(relation, NoLock);
                               1486                 :                : 
 7350 tgl@sss.pgh.pa.us        1487                 :          10644 :     return result;
                               1488                 :                : }
                               1489                 :                : 
                               1490                 :                : /*
                               1491                 :                :  * Try loading data for the statistics object.
                               1492                 :                :  *
                               1493                 :                :  * We don't know if the data (specified by statOid and inh value) exist.
                               1494                 :                :  * The result is stored in stainfos list.
                               1495                 :                :  */
                               1496                 :                : static void
 1329 tomas.vondra@postgre     1497                 :           1988 : get_relation_statistics_worker(List **stainfos, RelOptInfo *rel,
                               1498                 :                :                                Oid statOid, bool inh,
                               1499                 :                :                                Bitmapset *keys, List *exprs)
                               1500                 :                : {
                               1501                 :                :     Form_pg_statistic_ext_data dataForm;
                               1502                 :                :     HeapTuple   dtup;
                               1503                 :                : 
                               1504                 :           1988 :     dtup = SearchSysCache2(STATEXTDATASTXOID,
                               1505                 :                :                            ObjectIdGetDatum(statOid), BoolGetDatum(inh));
                               1506         [ +  + ]:           1988 :     if (!HeapTupleIsValid(dtup))
                               1507                 :            995 :         return;
                               1508                 :                : 
                               1509                 :            993 :     dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
                               1510                 :                : 
                               1511                 :                :     /* add one StatisticExtInfo for each kind built */
                               1512         [ +  + ]:            993 :     if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
                               1513                 :                :     {
                               1514                 :            351 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
                               1515                 :                : 
                               1516                 :            351 :         info->statOid = statOid;
                               1517                 :            351 :         info->inherit = dataForm->stxdinherit;
                               1518                 :            351 :         info->rel = rel;
                               1519                 :            351 :         info->kind = STATS_EXT_NDISTINCT;
                               1520                 :            351 :         info->keys = bms_copy(keys);
                               1521                 :            351 :         info->exprs = exprs;
                               1522                 :                : 
                               1523                 :            351 :         *stainfos = lappend(*stainfos, info);
                               1524                 :                :     }
                               1525                 :                : 
                               1526         [ +  + ]:            993 :     if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
                               1527                 :                :     {
                               1528                 :            264 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
                               1529                 :                : 
                               1530                 :            264 :         info->statOid = statOid;
                               1531                 :            264 :         info->inherit = dataForm->stxdinherit;
                               1532                 :            264 :         info->rel = rel;
                               1533                 :            264 :         info->kind = STATS_EXT_DEPENDENCIES;
                               1534                 :            264 :         info->keys = bms_copy(keys);
                               1535                 :            264 :         info->exprs = exprs;
                               1536                 :                : 
                               1537                 :            264 :         *stainfos = lappend(*stainfos, info);
                               1538                 :                :     }
                               1539                 :                : 
                               1540         [ +  + ]:            993 :     if (statext_is_kind_built(dtup, STATS_EXT_MCV))
                               1541                 :                :     {
                               1542                 :            441 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
                               1543                 :                : 
                               1544                 :            441 :         info->statOid = statOid;
                               1545                 :            441 :         info->inherit = dataForm->stxdinherit;
                               1546                 :            441 :         info->rel = rel;
                               1547                 :            441 :         info->kind = STATS_EXT_MCV;
                               1548                 :            441 :         info->keys = bms_copy(keys);
                               1549                 :            441 :         info->exprs = exprs;
                               1550                 :                : 
                               1551                 :            441 :         *stainfos = lappend(*stainfos, info);
                               1552                 :                :     }
                               1553                 :                : 
                               1554         [ +  + ]:            993 :     if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
                               1555                 :                :     {
                               1556                 :            402 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
                               1557                 :                : 
                               1558                 :            402 :         info->statOid = statOid;
                               1559                 :            402 :         info->inherit = dataForm->stxdinherit;
                               1560                 :            402 :         info->rel = rel;
                               1561                 :            402 :         info->kind = STATS_EXT_EXPRESSIONS;
                               1562                 :            402 :         info->keys = bms_copy(keys);
                               1563                 :            402 :         info->exprs = exprs;
                               1564                 :                : 
                               1565                 :            402 :         *stainfos = lappend(*stainfos, info);
                               1566                 :                :     }
                               1567                 :                : 
                               1568                 :            993 :     ReleaseSysCache(dtup);
                               1569                 :                : }
                               1570                 :                : 
                               1571                 :                : /*
                               1572                 :                :  * get_relation_statistics
                               1573                 :                :  *      Retrieve extended statistics defined on the table.
                               1574                 :                :  *
                               1575                 :                :  * Returns a List (possibly empty) of StatisticExtInfo objects describing
                               1576                 :                :  * the statistics.  Note that this doesn't load the actual statistics data,
                               1577                 :                :  * just the identifying metadata.  Only stats actually built are considered.
                               1578                 :                :  */
                               1579                 :                : static List *
    6 rguo@postgresql.org      1580                 :GNC      230828 : get_relation_statistics(PlannerInfo *root, RelOptInfo *rel,
                               1581                 :                :                         Relation relation)
                               1582                 :                : {
 1625 tomas.vondra@postgre     1583                 :CBC      230828 :     Index       varno = rel->relid;
                               1584                 :                :     List       *statoidlist;
 3088 alvherre@alvh.no-ip.     1585                 :         230828 :     List       *stainfos = NIL;
                               1586                 :                :     ListCell   *l;
                               1587                 :                : 
                               1588                 :         230828 :     statoidlist = RelationGetStatExtList(relation);
                               1589                 :                : 
                               1590   [ +  +  +  +  :         231822 :     foreach(l, statoidlist)
                                              +  + ]
                               1591                 :                :     {
                               1592                 :            994 :         Oid         statOid = lfirst_oid(l);
                               1593                 :                :         Form_pg_statistic_ext staForm;
                               1594                 :                :         HeapTuple   htup;
                               1595                 :            994 :         Bitmapset  *keys = NULL;
 1625 tomas.vondra@postgre     1596                 :            994 :         List       *exprs = NIL;
                               1597                 :                :         int         i;
                               1598                 :                : 
 3088 alvherre@alvh.no-ip.     1599                 :            994 :         htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
 2316 tgl@sss.pgh.pa.us        1600         [ -  + ]:            994 :         if (!HeapTupleIsValid(htup))
 3037 tgl@sss.pgh.pa.us        1601         [ #  # ]:UBC           0 :             elog(ERROR, "cache lookup failed for statistics object %u", statOid);
 3088 alvherre@alvh.no-ip.     1602                 :CBC         994 :         staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
                               1603                 :                : 
                               1604                 :                :         /*
                               1605                 :                :          * First, build the array of columns covered.  This is ultimately
                               1606                 :                :          * wasted if no stats within the object have actually been built, but
                               1607                 :                :          * it doesn't seem worth troubling over that case.
                               1608                 :                :          */
 3064                          1609         [ +  + ]:           2822 :         for (i = 0; i < staForm->stxkeys.dim1; i++)
                               1610                 :           1828 :             keys = bms_add_member(keys, staForm->stxkeys.values[i]);
                               1611                 :                : 
                               1612                 :                :         /*
                               1613                 :                :          * Preprocess expressions (if any). We read the expressions, fix the
                               1614                 :                :          * varnos, and run them through eval_const_expressions.
                               1615                 :                :          *
                               1616                 :                :          * XXX We don't know yet if there are any data for this stats object,
                               1617                 :                :          * with either stxdinherit value. But it's reasonable to assume there
                               1618                 :                :          * is at least one of those, possibly both. So it's better to process
                               1619                 :                :          * keys and expressions here.
                               1620                 :                :          */
                               1621                 :                :         {
                               1622                 :                :             bool        isnull;
                               1623                 :                :             Datum       datum;
                               1624                 :                : 
                               1625                 :                :             /* decode expression (if any) */
 1625 tomas.vondra@postgre     1626                 :            994 :             datum = SysCacheGetAttr(STATEXTOID, htup,
                               1627                 :                :                                     Anum_pg_statistic_ext_stxexprs, &isnull);
                               1628                 :                : 
                               1629         [ +  + ]:            994 :             if (!isnull)
                               1630                 :                :             {
                               1631                 :                :                 char       *exprsString;
                               1632                 :                : 
                               1633                 :            404 :                 exprsString = TextDatumGetCString(datum);
                               1634                 :            404 :                 exprs = (List *) stringToNode(exprsString);
                               1635                 :            404 :                 pfree(exprsString);
                               1636                 :                : 
                               1637                 :                :                 /*
                               1638                 :                :                  * Modify the copies we obtain from the relcache to have the
                               1639                 :                :                  * correct varno for the parent relation, so that they match
                               1640                 :                :                  * up correctly against qual clauses.
                               1641                 :                :                  *
                               1642                 :                :                  * This must be done before const-simplification because
                               1643                 :                :                  * eval_const_expressions reduces NullTest for Vars based on
                               1644                 :                :                  * varno.
                               1645                 :                :                  */
    6 rguo@postgresql.org      1646         [ -  + ]:GNC         404 :                 if (varno != 1)
    6 rguo@postgresql.org      1647                 :UNC           0 :                     ChangeVarNodes((Node *) exprs, 1, varno, 0);
                               1648                 :                : 
                               1649                 :                :                 /*
                               1650                 :                :                  * Run the expressions through eval_const_expressions. This is
                               1651                 :                :                  * not just an optimization, but is necessary, because the
                               1652                 :                :                  * planner will be comparing them to similarly-processed qual
                               1653                 :                :                  * clauses, and may fail to detect valid matches without this.
                               1654                 :                :                  * We must not use canonicalize_qual, however, since these
                               1655                 :                :                  * aren't qual expressions.
                               1656                 :                :                  */
    6 rguo@postgresql.org      1657                 :GNC         404 :                 exprs = (List *) eval_const_expressions(root, (Node *) exprs);
                               1658                 :                : 
                               1659                 :                :                 /* May as well fix opfuncids too */
 1625 tomas.vondra@postgre     1660                 :CBC         404 :                 fix_opfuncids((Node *) exprs);
                               1661                 :                :             }
                               1662                 :                :         }
                               1663                 :                : 
                               1664                 :                :         /* extract statistics for possible values of stxdinherit flag */
                               1665                 :                : 
 1329                          1666                 :            994 :         get_relation_statistics_worker(&stainfos, rel, statOid, true, keys, exprs);
                               1667                 :                : 
                               1668                 :            994 :         get_relation_statistics_worker(&stainfos, rel, statOid, false, keys, exprs);
                               1669                 :                : 
 3088 alvherre@alvh.no-ip.     1670                 :            994 :         ReleaseSysCache(htup);
                               1671                 :            994 :         bms_free(keys);
                               1672                 :                :     }
                               1673                 :                : 
                               1674                 :         230828 :     list_free(statoidlist);
                               1675                 :                : 
                               1676                 :         230828 :     return stainfos;
                               1677                 :                : }
                               1678                 :                : 
                               1679                 :                : /*
                               1680                 :                :  * relation_excluded_by_constraints
                               1681                 :                :  *
                               1682                 :                :  * Detect whether the relation need not be scanned because it has either
                               1683                 :                :  * self-inconsistent restrictions, or restrictions inconsistent with the
                               1684                 :                :  * relation's applicable constraints.
                               1685                 :                :  *
                               1686                 :                :  * Note: this examines only rel->relid, rel->reloptkind, and
                               1687                 :                :  * rel->baserestrictinfo; therefore it can be called before filling in
                               1688                 :                :  * other fields of the RelOptInfo.
                               1689                 :                :  */
                               1690                 :                : bool
 6367 tgl@sss.pgh.pa.us        1691                 :         250021 : relation_excluded_by_constraints(PlannerInfo *root,
                               1692                 :                :                                  RelOptInfo *rel, RangeTblEntry *rte)
                               1693                 :                : {
                               1694                 :                :     bool        include_noinherit;
                               1695                 :                :     bool        include_notnull;
 2321                          1696                 :         250021 :     bool        include_partition = false;
                               1697                 :                :     List       *safe_restrictions;
                               1698                 :                :     List       *constraint_pred;
                               1699                 :                :     List       *safe_constraints;
                               1700                 :                :     ListCell   *lc;
                               1701                 :                : 
                               1702                 :                :     /* As of now, constraint exclusion works only with simple relations. */
 3078 rhaas@postgresql.org     1703   [ +  +  -  + ]:         250021 :     Assert(IS_SIMPLE_REL(rel));
                               1704                 :                : 
                               1705                 :                :     /*
                               1706                 :                :      * If there are no base restriction clauses, we have no hope of proving
                               1707                 :                :      * anything below, so fall out quickly.
                               1708                 :                :      */
 2321 tgl@sss.pgh.pa.us        1709         [ +  + ]:         250021 :     if (rel->baserestrictinfo == NIL)
                               1710                 :         109751 :         return false;
                               1711                 :                : 
                               1712                 :                :     /*
                               1713                 :                :      * Regardless of the setting of constraint_exclusion, detect
                               1714                 :                :      * constant-FALSE-or-NULL restriction clauses.  Although const-folding
                               1715                 :                :      * will reduce "anything AND FALSE" to just "FALSE", the baserestrictinfo
                               1716                 :                :      * list can still have other members besides the FALSE constant, due to
                               1717                 :                :      * qual pushdown and other mechanisms; so check them all.  This doesn't
                               1718                 :                :      * fire very often, but it seems cheap enough to be worth doing anyway.
                               1719                 :                :      * (Without this, we'd miss some optimizations that 9.5 and earlier found
                               1720                 :                :      * via much more roundabout methods.)
                               1721                 :                :      */
  696                          1722   [ +  -  +  +  :         350599 :     foreach(lc, rel->baserestrictinfo)
                                              +  + ]
                               1723                 :                :     {
                               1724                 :         210569 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
 3470                          1725                 :         210569 :         Expr       *clause = rinfo->clause;
                               1726                 :                : 
                               1727   [ +  -  +  + ]:         210569 :         if (clause && IsA(clause, Const) &&
                               1728         [ +  + ]:            240 :             (((Const *) clause)->constisnull ||
                               1729         [ +  - ]:            237 :              !DatumGetBool(((Const *) clause)->constvalue)))
                               1730                 :            240 :             return true;
                               1731                 :                :     }
                               1732                 :                : 
                               1733                 :                :     /*
                               1734                 :                :      * Skip further tests, depending on constraint_exclusion.
                               1735                 :                :      */
 2693 alvherre@alvh.no-ip.     1736   [ +  +  +  - ]:         140030 :     switch (constraint_exclusion)
                               1737                 :                :     {
                               1738                 :             27 :         case CONSTRAINT_EXCLUSION_OFF:
                               1739                 :                :             /* In 'off' mode, never make any further tests */
                               1740                 :             27 :             return false;
                               1741                 :                : 
                               1742                 :         139937 :         case CONSTRAINT_EXCLUSION_PARTITION:
                               1743                 :                : 
                               1744                 :                :             /*
                               1745                 :                :              * When constraint_exclusion is set to 'partition' we only handle
                               1746                 :                :              * appendrel members.  Partition pruning has already been applied,
                               1747                 :                :              * so there is no need to consider the rel's partition constraints
                               1748                 :                :              * here.
                               1749                 :                :              */
 1620 tgl@sss.pgh.pa.us        1750         [ +  + ]:         139937 :             if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
 2321                          1751                 :          10757 :                 break;          /* appendrel member, so process it */
                               1752                 :         129180 :             return false;
                               1753                 :                : 
 2693 alvherre@alvh.no-ip.     1754                 :             66 :         case CONSTRAINT_EXCLUSION_ON:
                               1755                 :                : 
                               1756                 :                :             /*
                               1757                 :                :              * In 'on' mode, always apply constraint exclusion.  If we are
                               1758                 :                :              * considering a baserel that is a partition (i.e., it was
                               1759                 :                :              * directly named rather than expanded from a parent table), then
                               1760                 :                :              * its partition constraints haven't been considered yet, so
                               1761                 :                :              * include them in the processing here.
                               1762                 :                :              */
 1620 tgl@sss.pgh.pa.us        1763         [ +  + ]:             66 :             if (rel->reloptkind == RELOPT_BASEREL)
 2321                          1764                 :             51 :                 include_partition = true;
 2690                          1765                 :             66 :             break;              /* always try to exclude */
                               1766                 :                :     }
                               1767                 :                : 
                               1768                 :                :     /*
                               1769                 :                :      * Check for self-contradictory restriction clauses.  We dare not make
                               1770                 :                :      * deductions with non-immutable functions, but any immutable clauses that
                               1771                 :                :      * are self-contradictory allow us to conclude the scan is unnecessary.
                               1772                 :                :      *
                               1773                 :                :      * Note: strip off RestrictInfo because predicate_refuted_by() isn't
                               1774                 :                :      * expecting to see any in its predicate argument.
                               1775                 :                :      */
 6972                          1776                 :          10823 :     safe_restrictions = NIL;
                               1777   [ +  -  +  +  :          25548 :     foreach(lc, rel->baserestrictinfo)
                                              +  + ]
                               1778                 :                :     {
                               1779                 :          14725 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
                               1780                 :                : 
                               1781         [ +  + ]:          14725 :         if (!contain_mutable_functions((Node *) rinfo->clause))
                               1782                 :          13955 :             safe_restrictions = lappend(safe_restrictions, rinfo->clause);
                               1783                 :                :     }
                               1784                 :                : 
                               1785                 :                :     /*
                               1786                 :                :      * We can use weak refutation here, since we're comparing restriction
                               1787                 :                :      * clauses with restriction clauses.
                               1788                 :                :      */
 2738                          1789         [ +  + ]:          10823 :     if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
 6972                          1790                 :             36 :         return true;
                               1791                 :                : 
                               1792                 :                :     /*
                               1793                 :                :      * Only plain relations have constraints, so stop here for other rtekinds.
                               1794                 :                :      */
 2321                          1795         [ +  + ]:          10787 :     if (rte->rtekind != RTE_RELATION)
 7154                          1796                 :            143 :         return false;
                               1797                 :                : 
                               1798                 :                :     /*
                               1799                 :                :      * If we are scanning just this table, we can use NO INHERIT constraints,
                               1800                 :                :      * but not if we're scanning its children too.  (Note that partitioned
                               1801                 :                :      * tables should never have NO INHERIT constraints; but it's not necessary
                               1802                 :                :      * for us to assume that here.)
                               1803                 :                :      */
 2321                          1804                 :          10644 :     include_noinherit = !rte->inh;
                               1805                 :                : 
                               1806                 :                :     /*
                               1807                 :                :      * Currently, attnotnull constraints must be treated as NO INHERIT unless
                               1808                 :                :      * this is a partitioned table.  In future we might track their
                               1809                 :                :      * inheritance status more accurately, allowing this to be refined.
                               1810                 :                :      *
                               1811                 :                :      * XXX do we need/want to change this?
                               1812                 :                :      */
                               1813   [ +  +  +  + ]:          10644 :     include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
                               1814                 :                : 
                               1815                 :                :     /*
                               1816                 :                :      * Fetch the appropriate set of constraint expressions.
                               1817                 :                :      */
                               1818                 :          10644 :     constraint_pred = get_relation_constraints(root, rte->relid, rel,
                               1819                 :                :                                                include_noinherit,
                               1820                 :                :                                                include_notnull,
                               1821                 :                :                                                include_partition);
                               1822                 :                : 
                               1823                 :                :     /*
                               1824                 :                :      * We do not currently enforce that CHECK constraints contain only
                               1825                 :                :      * immutable functions, so it's necessary to check here. We daren't draw
                               1826                 :                :      * conclusions from plan-time evaluation of non-immutable functions. Since
                               1827                 :                :      * they're ANDed, we can just ignore any mutable constraints in the list,
                               1828                 :                :      * and reason about the rest.
                               1829                 :                :      */
 6972                          1830                 :          10644 :     safe_constraints = NIL;
                               1831   [ +  +  +  +  :          15665 :     foreach(lc, constraint_pred)
                                              +  + ]
                               1832                 :                :     {
 6912 bruce@momjian.us         1833                 :           5021 :         Node       *pred = (Node *) lfirst(lc);
                               1834                 :                : 
 6972 tgl@sss.pgh.pa.us        1835         [ +  - ]:           5021 :         if (!contain_mutable_functions(pred))
                               1836                 :           5021 :             safe_constraints = lappend(safe_constraints, pred);
                               1837                 :                :     }
                               1838                 :                : 
                               1839                 :                :     /*
                               1840                 :                :      * The constraints are effectively ANDed together, so we can just try to
                               1841                 :                :      * refute the entire collection at once.  This may allow us to make proofs
                               1842                 :                :      * that would fail if we took them individually.
                               1843                 :                :      *
                               1844                 :                :      * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
                               1845                 :                :      * an obvious optimization.  Some of the clauses might be OR clauses that
                               1846                 :                :      * have volatile and nonvolatile subclauses, and it's OK to make
                               1847                 :                :      * deductions with the nonvolatile parts.
                               1848                 :                :      *
                               1849                 :                :      * We need strong refutation because we have to prove that the constraints
                               1850                 :                :      * would yield false, not just NULL.
                               1851                 :                :      */
 3006 rhaas@postgresql.org     1852         [ +  + ]:          10644 :     if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
 7154 tgl@sss.pgh.pa.us        1853                 :             90 :         return true;
                               1854                 :                : 
                               1855                 :          10554 :     return false;
                               1856                 :                : }
                               1857                 :                : 
                               1858                 :                : 
                               1859                 :                : /*
                               1860                 :                :  * build_physical_tlist
                               1861                 :                :  *
                               1862                 :                :  * Build a targetlist consisting of exactly the relation's user attributes,
                               1863                 :                :  * in order.  The executor can special-case such tlists to avoid a projection
                               1864                 :                :  * step at runtime, so we use such tlists preferentially for scan nodes.
                               1865                 :                :  *
                               1866                 :                :  * Exception: if there are any dropped or missing columns, we punt and return
                               1867                 :                :  * NIL.  Ideally we would like to handle these cases too.  However this
                               1868                 :                :  * creates problems for ExecTypeFromTL, which may be asked to build a tupdesc
                               1869                 :                :  * for a tlist that includes vars of no-longer-existent types.  In theory we
                               1870                 :                :  * could dig out the required info from the pg_attribute entries of the
                               1871                 :                :  * relation, but that data is not readily available to ExecTypeFromTL.
                               1872                 :                :  * For now, we don't apply the physical-tlist optimization when there are
                               1873                 :                :  * dropped cols.
                               1874                 :                :  *
                               1875                 :                :  * We also support building a "physical" tlist for subqueries, functions,
                               1876                 :                :  * values lists, table expressions, and CTEs, since the same optimization can
                               1877                 :                :  * occur in SubqueryScan, FunctionScan, ValuesScan, CteScan, TableFunc,
                               1878                 :                :  * NamedTuplestoreScan, and WorkTableScan nodes.
                               1879                 :                :  */
                               1880                 :                : List *
 7398                          1881                 :          90090 : build_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
                               1882                 :                : {
 7412                          1883                 :          90090 :     List       *tlist = NIL;
 8105                          1884                 :          90090 :     Index       varno = rel->relid;
 6713                          1885         [ +  - ]:          90090 :     RangeTblEntry *rte = planner_rt_fetch(varno, root);
                               1886                 :                :     Relation    relation;
                               1887                 :                :     Query      *subquery;
                               1888                 :                :     Var        *var;
                               1889                 :                :     ListCell   *l;
                               1890                 :                :     int         attrno,
                               1891                 :                :                 numattrs;
                               1892                 :                :     List       *colvars;
                               1893                 :                : 
 7412                          1894   [ +  +  +  - ]:          90090 :     switch (rte->rtekind)
                               1895                 :                :     {
                               1896                 :          78320 :         case RTE_RELATION:
                               1897                 :                :             /* Assume we already have adequate lock */
 2420 andres@anarazel.de       1898                 :          78320 :             relation = table_open(rte->relid, NoLock);
                               1899                 :                : 
 7412 tgl@sss.pgh.pa.us        1900                 :          78320 :             numattrs = RelationGetNumberOfAttributes(relation);
                               1901         [ +  + ]:        1410716 :             for (attrno = 1; attrno <= numattrs; attrno++)
                               1902                 :                :             {
 2939 andres@anarazel.de       1903                 :        1332465 :                 Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
                               1904                 :                :                                                           attrno - 1);
                               1905                 :                : 
 2719 andrew@dunslane.net      1906   [ +  +  +  + ]:        1332465 :                 if (att_tup->attisdropped || att_tup->atthasmissing)
                               1907                 :                :                 {
                               1908                 :                :                     /* found a dropped or missing col, so punt */
 7412 tgl@sss.pgh.pa.us        1909                 :             69 :                     tlist = NIL;
                               1910                 :             69 :                     break;
                               1911                 :                :                 }
                               1912                 :                : 
                               1913                 :        1332396 :                 var = makeVar(varno,
                               1914                 :                :                               attrno,
                               1915                 :                :                               att_tup->atttypid,
                               1916                 :                :                               att_tup->atttypmod,
                               1917                 :                :                               att_tup->attcollation,
                               1918                 :                :                               0);
                               1919                 :                : 
                               1920                 :        1332396 :                 tlist = lappend(tlist,
                               1921                 :        1332396 :                                 makeTargetEntry((Expr *) var,
                               1922                 :                :                                                 attrno,
                               1923                 :                :                                                 NULL,
                               1924                 :                :                                                 false));
                               1925                 :                :             }
                               1926                 :                : 
 2420 andres@anarazel.de       1927                 :          78320 :             table_close(relation, NoLock);
 8105 tgl@sss.pgh.pa.us        1928                 :          78320 :             break;
                               1929                 :                : 
 7412                          1930                 :           1102 :         case RTE_SUBQUERY:
                               1931                 :           1102 :             subquery = rte->subquery;
                               1932   [ +  -  +  +  :           4222 :             foreach(l, subquery->targetList)
                                              +  + ]
                               1933                 :                :             {
                               1934                 :           3120 :                 TargetEntry *tle = (TargetEntry *) lfirst(l);
                               1935                 :                : 
                               1936                 :                :                 /*
                               1937                 :                :                  * A resjunk column of the subquery can be reflected as
                               1938                 :                :                  * resjunk in the physical tlist; we need not punt.
                               1939                 :                :                  */
 5489 peter_e@gmx.net          1940                 :           3120 :                 var = makeVarFromTargetEntry(varno, tle);
                               1941                 :                : 
 7412 tgl@sss.pgh.pa.us        1942                 :           3120 :                 tlist = lappend(tlist,
                               1943                 :           3120 :                                 makeTargetEntry((Expr *) var,
                               1944                 :           3120 :                                                 tle->resno,
                               1945                 :                :                                                 NULL,
                               1946                 :           3120 :                                                 tle->resjunk));
                               1947                 :                :             }
                               1948                 :           1102 :             break;
                               1949                 :                : 
 7404                          1950                 :          10668 :         case RTE_FUNCTION:
                               1951                 :                :         case RTE_TABLEFUNC:
                               1952                 :                :         case RTE_VALUES:
                               1953                 :                :         case RTE_CTE:
                               1954                 :                :         case RTE_NAMEDTUPLESTORE:
                               1955                 :                :         case RTE_RESULT:
                               1956                 :                :             /* Not all of these can have dropped cols, but share code anyway */
  233 dean.a.rasheed@gmail     1957                 :          10668 :             expandRTE(rte, varno, 0, VAR_RETURNING_DEFAULT, -1,
                               1958                 :                :                       true /* include dropped */ , NULL, &colvars);
 7404 tgl@sss.pgh.pa.us        1959   [ +  -  +  +  :          54529 :             foreach(l, colvars)
                                              +  + ]
                               1960                 :                :             {
                               1961                 :          43861 :                 var = (Var *) lfirst(l);
                               1962                 :                : 
                               1963                 :                :                 /*
                               1964                 :                :                  * A non-Var in expandRTE's output means a dropped column;
                               1965                 :                :                  * must punt.
                               1966                 :                :                  */
                               1967         [ -  + ]:          43861 :                 if (!IsA(var, Var))
                               1968                 :                :                 {
 7404 tgl@sss.pgh.pa.us        1969                 :UBC           0 :                     tlist = NIL;
                               1970                 :              0 :                     break;
                               1971                 :                :                 }
                               1972                 :                : 
 7404 tgl@sss.pgh.pa.us        1973                 :CBC       43861 :                 tlist = lappend(tlist,
                               1974                 :          43861 :                                 makeTargetEntry((Expr *) var,
                               1975                 :          43861 :                                                 var->varattno,
                               1976                 :                :                                                 NULL,
                               1977                 :                :                                                 false));
                               1978                 :                :             }
                               1979                 :          10668 :             break;
                               1980                 :                : 
 7412 tgl@sss.pgh.pa.us        1981                 :UBC           0 :         default:
                               1982                 :                :             /* caller error */
                               1983         [ #  # ]:              0 :             elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
                               1984                 :                :                  (int) rte->rtekind);
                               1985                 :                :             break;
                               1986                 :                :     }
                               1987                 :                : 
 7767 tgl@sss.pgh.pa.us        1988                 :CBC       90090 :     return tlist;
                               1989                 :                : }
                               1990                 :                : 
                               1991                 :                : /*
                               1992                 :                :  * build_index_tlist
                               1993                 :                :  *
                               1994                 :                :  * Build a targetlist representing the columns of the specified index.
                               1995                 :                :  * Each column is represented by a Var for the corresponding base-relation
                               1996                 :                :  * column, or an expression in base-relation Vars, as appropriate.
                               1997                 :                :  *
                               1998                 :                :  * There are never any dropped columns in indexes, so unlike
                               1999                 :                :  * build_physical_tlist, we need no failure case.
                               2000                 :                :  */
                               2001                 :                : static List *
 5079                          2002                 :         362808 : build_index_tlist(PlannerInfo *root, IndexOptInfo *index,
                               2003                 :                :                   Relation heapRelation)
                               2004                 :                : {
                               2005                 :         362808 :     List       *tlist = NIL;
                               2006                 :         362808 :     Index       varno = index->rel->relid;
                               2007                 :                :     ListCell   *indexpr_item;
                               2008                 :                :     int         i;
                               2009                 :                : 
                               2010                 :         362808 :     indexpr_item = list_head(index->indexprs);
                               2011         [ +  + ]:        1049780 :     for (i = 0; i < index->ncolumns; i++)
                               2012                 :                :     {
                               2013                 :         686972 :         int         indexkey = index->indexkeys[i];
                               2014                 :                :         Expr       *indexvar;
                               2015                 :                : 
                               2016         [ +  + ]:         686972 :         if (indexkey != 0)
                               2017                 :                :         {
                               2018                 :                :             /* simple column */
                               2019                 :                :             const FormData_pg_attribute *att_tup;
                               2020                 :                : 
                               2021         [ -  + ]:         685464 :             if (indexkey < 0)
 2482 andres@anarazel.de       2022                 :UBC           0 :                 att_tup = SystemAttributeDefinition(indexkey);
                               2023                 :                :             else
 2939 andres@anarazel.de       2024                 :CBC      685464 :                 att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
                               2025                 :                : 
 5079 tgl@sss.pgh.pa.us        2026                 :         685464 :             indexvar = (Expr *) makeVar(varno,
                               2027                 :                :                                         indexkey,
                               2028                 :         685464 :                                         att_tup->atttypid,
                               2029                 :         685464 :                                         att_tup->atttypmod,
                               2030                 :         685464 :                                         att_tup->attcollation,
                               2031                 :                :                                         0);
                               2032                 :                :         }
                               2033                 :                :         else
                               2034                 :                :         {
                               2035                 :                :             /* expression column */
                               2036         [ -  + ]:           1508 :             if (indexpr_item == NULL)
 5079 tgl@sss.pgh.pa.us        2037         [ #  # ]:UBC           0 :                 elog(ERROR, "wrong number of index expressions");
 5079 tgl@sss.pgh.pa.us        2038                 :CBC        1508 :             indexvar = (Expr *) lfirst(indexpr_item);
 2245                          2039                 :           1508 :             indexpr_item = lnext(index->indexprs, indexpr_item);
                               2040                 :                :         }
                               2041                 :                : 
 5079                          2042                 :         686972 :         tlist = lappend(tlist,
                               2043                 :         686972 :                         makeTargetEntry(indexvar,
                               2044                 :         686972 :                                         i + 1,
                               2045                 :                :                                         NULL,
                               2046                 :                :                                         false));
                               2047                 :                :     }
                               2048         [ -  + ]:         362808 :     if (indexpr_item != NULL)
 5079 tgl@sss.pgh.pa.us        2049         [ #  # ]:UBC           0 :         elog(ERROR, "wrong number of index expressions");
                               2050                 :                : 
 5079 tgl@sss.pgh.pa.us        2051                 :CBC      362808 :     return tlist;
                               2052                 :                : }
                               2053                 :                : 
                               2054                 :                : /*
                               2055                 :                :  * restriction_selectivity
                               2056                 :                :  *
                               2057                 :                :  * Returns the selectivity of a specified restriction operator clause.
                               2058                 :                :  * This code executes registered procedures stored in the
                               2059                 :                :  * operator relation, by calling the function manager.
                               2060                 :                :  *
                               2061                 :                :  * See clause_selectivity() for the meaning of the additional parameters.
                               2062                 :                :  */
                               2063                 :                : Selectivity
 7398                          2064                 :         340713 : restriction_selectivity(PlannerInfo *root,
                               2065                 :                :                         Oid operatorid,
                               2066                 :                :                         List *args,
                               2067                 :                :                         Oid inputcollid,
                               2068                 :                :                         int varRelid)
                               2069                 :                : {
 5896 peter_e@gmx.net          2070                 :         340713 :     RegProcedure oprrest = get_oprrest(operatorid);
                               2071                 :                :     float8      result;
                               2072                 :                : 
                               2073                 :                :     /*
                               2074                 :                :      * if the oprrest procedure is missing for whatever reason, use a
                               2075                 :                :      * selectivity of 0.5
                               2076                 :                :      */
 8875 tgl@sss.pgh.pa.us        2077         [ +  + ]:         340713 :     if (!oprrest)
                               2078                 :             80 :         return (Selectivity) 0.5;
                               2079                 :                : 
 4808                          2080                 :         340633 :     result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
                               2081                 :                :                                                  inputcollid,
                               2082                 :                :                                                  PointerGetDatum(root),
                               2083                 :                :                                                  ObjectIdGetDatum(operatorid),
                               2084                 :                :                                                  PointerGetDatum(args),
                               2085                 :                :                                                  Int32GetDatum(varRelid)));
                               2086                 :                : 
 9230                          2087   [ +  -  -  + ]:         340618 :     if (result < 0.0 || result > 1.0)
 8079 tgl@sss.pgh.pa.us        2088         [ #  # ]:UBC           0 :         elog(ERROR, "invalid restriction selectivity: %f", result);
                               2089                 :                : 
 9230 tgl@sss.pgh.pa.us        2090                 :CBC      340618 :     return (Selectivity) result;
                               2091                 :                : }
                               2092                 :                : 
                               2093                 :                : /*
                               2094                 :                :  * join_selectivity
                               2095                 :                :  *
                               2096                 :                :  * Returns the selectivity of a specified join operator clause.
                               2097                 :                :  * This code executes registered procedures stored in the
                               2098                 :                :  * operator relation, by calling the function manager.
                               2099                 :                :  *
                               2100                 :                :  * See clause_selectivity() for the meaning of the additional parameters.
                               2101                 :                :  */
                               2102                 :                : Selectivity
 7398                          2103                 :         113946 : join_selectivity(PlannerInfo *root,
                               2104                 :                :                  Oid operatorid,
                               2105                 :                :                  List *args,
                               2106                 :                :                  Oid inputcollid,
                               2107                 :                :                  JoinType jointype,
                               2108                 :                :                  SpecialJoinInfo *sjinfo)
                               2109                 :                : {
 5896 peter_e@gmx.net          2110                 :         113946 :     RegProcedure oprjoin = get_oprjoin(operatorid);
                               2111                 :                :     float8      result;
                               2112                 :                : 
                               2113                 :                :     /*
                               2114                 :                :      * if the oprjoin procedure is missing for whatever reason, use a
                               2115                 :                :      * selectivity of 0.5
                               2116                 :                :      */
 8875 tgl@sss.pgh.pa.us        2117         [ +  + ]:         113946 :     if (!oprjoin)
                               2118                 :             73 :         return (Selectivity) 0.5;
                               2119                 :                : 
 4808                          2120                 :         113873 :     result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
                               2121                 :                :                                                  inputcollid,
                               2122                 :                :                                                  PointerGetDatum(root),
                               2123                 :                :                                                  ObjectIdGetDatum(operatorid),
                               2124                 :                :                                                  PointerGetDatum(args),
                               2125                 :                :                                                  Int16GetDatum(jointype),
                               2126                 :                :                                                  PointerGetDatum(sjinfo)));
                               2127                 :                : 
 9230                          2128   [ +  -  -  + ]:         113873 :     if (result < 0.0 || result > 1.0)
 8079 tgl@sss.pgh.pa.us        2129         [ #  # ]:UBC           0 :         elog(ERROR, "invalid join selectivity: %f", result);
                               2130                 :                : 
 9230 tgl@sss.pgh.pa.us        2131                 :CBC      113873 :     return (Selectivity) result;
                               2132                 :                : }
                               2133                 :                : 
                               2134                 :                : /*
                               2135                 :                :  * function_selectivity
                               2136                 :                :  *
                               2137                 :                :  * Returns the selectivity of a specified boolean function clause.
                               2138                 :                :  * This code executes registered procedures stored in the
                               2139                 :                :  * pg_proc relation, by calling the function manager.
                               2140                 :                :  *
                               2141                 :                :  * See clause_selectivity() for the meaning of the additional parameters.
                               2142                 :                :  */
                               2143                 :                : Selectivity
 2401                          2144                 :           6102 : function_selectivity(PlannerInfo *root,
                               2145                 :                :                      Oid funcid,
                               2146                 :                :                      List *args,
                               2147                 :                :                      Oid inputcollid,
                               2148                 :                :                      bool is_join,
                               2149                 :                :                      int varRelid,
                               2150                 :                :                      JoinType jointype,
                               2151                 :                :                      SpecialJoinInfo *sjinfo)
                               2152                 :                : {
                               2153                 :           6102 :     RegProcedure prosupport = get_func_support(funcid);
                               2154                 :                :     SupportRequestSelectivity req;
                               2155                 :                :     SupportRequestSelectivity *sresult;
                               2156                 :                : 
                               2157                 :                :     /*
                               2158                 :                :      * If no support function is provided, use our historical default
                               2159                 :                :      * estimate, 0.3333333.  This seems a pretty unprincipled choice, but
                               2160                 :                :      * Postgres has been using that estimate for function calls since 1992.
                               2161                 :                :      * The hoariness of this behavior suggests that we should not be in too
                               2162                 :                :      * much hurry to use another value.
                               2163                 :                :      */
                               2164         [ +  + ]:           6102 :     if (!prosupport)
                               2165                 :           6087 :         return (Selectivity) 0.3333333;
                               2166                 :                : 
                               2167                 :             15 :     req.type = T_SupportRequestSelectivity;
                               2168                 :             15 :     req.root = root;
                               2169                 :             15 :     req.funcid = funcid;
                               2170                 :             15 :     req.args = args;
                               2171                 :             15 :     req.inputcollid = inputcollid;
                               2172                 :             15 :     req.is_join = is_join;
                               2173                 :             15 :     req.varRelid = varRelid;
                               2174                 :             15 :     req.jointype = jointype;
                               2175                 :             15 :     req.sjinfo = sjinfo;
                               2176                 :             15 :     req.selectivity = -1;       /* to catch failure to set the value */
                               2177                 :                : 
                               2178                 :                :     sresult = (SupportRequestSelectivity *)
                               2179                 :             15 :         DatumGetPointer(OidFunctionCall1(prosupport,
                               2180                 :                :                                          PointerGetDatum(&req)));
                               2181                 :                : 
                               2182                 :                :     /* If support function fails, use default */
                               2183         [ -  + ]:             15 :     if (sresult != &req)
 2401 tgl@sss.pgh.pa.us        2184                 :UBC           0 :         return (Selectivity) 0.3333333;
                               2185                 :                : 
 2401 tgl@sss.pgh.pa.us        2186   [ +  -  -  + ]:CBC          15 :     if (req.selectivity < 0.0 || req.selectivity > 1.0)
 2401 tgl@sss.pgh.pa.us        2187         [ #  # ]:UBC           0 :         elog(ERROR, "invalid function selectivity: %f", req.selectivity);
                               2188                 :                : 
 2401 tgl@sss.pgh.pa.us        2189                 :CBC          15 :     return (Selectivity) req.selectivity;
                               2190                 :                : }
                               2191                 :                : 
                               2192                 :                : /*
                               2193                 :                :  * add_function_cost
                               2194                 :                :  *
                               2195                 :                :  * Get an estimate of the execution cost of a function, and *add* it to
                               2196                 :                :  * the contents of *cost.  The estimate may include both one-time and
                               2197                 :                :  * per-tuple components, since QualCost does.
                               2198                 :                :  *
                               2199                 :                :  * The funcid must always be supplied.  If it is being called as the
                               2200                 :                :  * implementation of a specific parsetree node (FuncExpr, OpExpr,
                               2201                 :                :  * WindowFunc, etc), pass that as "node", else pass NULL.
                               2202                 :                :  *
                               2203                 :                :  * In some usages root might be NULL, too.
                               2204                 :                :  */
                               2205                 :                : void
                               2206                 :         557162 : add_function_cost(PlannerInfo *root, Oid funcid, Node *node,
                               2207                 :                :                   QualCost *cost)
                               2208                 :                : {
                               2209                 :                :     HeapTuple   proctup;
                               2210                 :                :     Form_pg_proc procform;
                               2211                 :                : 
                               2212                 :         557162 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
                               2213         [ -  + ]:         557162 :     if (!HeapTupleIsValid(proctup))
 2401 tgl@sss.pgh.pa.us        2214         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for function %u", funcid);
 2401 tgl@sss.pgh.pa.us        2215                 :CBC      557162 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
                               2216                 :                : 
                               2217         [ +  + ]:         557162 :     if (OidIsValid(procform->prosupport))
                               2218                 :                :     {
                               2219                 :                :         SupportRequestCost req;
                               2220                 :                :         SupportRequestCost *sresult;
                               2221                 :                : 
                               2222                 :          16625 :         req.type = T_SupportRequestCost;
                               2223                 :          16625 :         req.root = root;
                               2224                 :          16625 :         req.funcid = funcid;
                               2225                 :          16625 :         req.node = node;
                               2226                 :                : 
                               2227                 :                :         /* Initialize cost fields so that support function doesn't have to */
                               2228                 :          16625 :         req.startup = 0;
                               2229                 :          16625 :         req.per_tuple = 0;
                               2230                 :                : 
                               2231                 :                :         sresult = (SupportRequestCost *)
                               2232                 :          16625 :             DatumGetPointer(OidFunctionCall1(procform->prosupport,
                               2233                 :                :                                              PointerGetDatum(&req)));
                               2234                 :                : 
                               2235         [ +  + ]:          16625 :         if (sresult == &req)
                               2236                 :                :         {
                               2237                 :                :             /* Success, so accumulate support function's estimate into *cost */
                               2238                 :              9 :             cost->startup += req.startup;
                               2239                 :              9 :             cost->per_tuple += req.per_tuple;
                               2240                 :              9 :             ReleaseSysCache(proctup);
                               2241                 :              9 :             return;
                               2242                 :                :         }
                               2243                 :                :     }
                               2244                 :                : 
                               2245                 :                :     /* No support function, or it failed, so rely on procost */
                               2246                 :         557153 :     cost->per_tuple += procform->procost * cpu_operator_cost;
                               2247                 :                : 
                               2248                 :         557153 :     ReleaseSysCache(proctup);
                               2249                 :                : }
                               2250                 :                : 
                               2251                 :                : /*
                               2252                 :                :  * get_function_rows
                               2253                 :                :  *
                               2254                 :                :  * Get an estimate of the number of rows returned by a set-returning function.
                               2255                 :                :  *
                               2256                 :                :  * The funcid must always be supplied.  In current usage, the calling node
                               2257                 :                :  * will always be supplied, and will be either a FuncExpr or OpExpr.
                               2258                 :                :  * But it's a good idea to not fail if it's NULL.
                               2259                 :                :  *
                               2260                 :                :  * In some usages root might be NULL, too.
                               2261                 :                :  *
                               2262                 :                :  * Note: this returns the unfiltered result of the support function, if any.
                               2263                 :                :  * It's usually a good idea to apply clamp_row_est() to the result, but we
                               2264                 :                :  * leave it to the caller to do so.
                               2265                 :                :  */
                               2266                 :                : double
                               2267                 :          26472 : get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
                               2268                 :                : {
                               2269                 :                :     HeapTuple   proctup;
                               2270                 :                :     Form_pg_proc procform;
                               2271                 :                :     double      result;
                               2272                 :                : 
                               2273                 :          26472 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
                               2274         [ -  + ]:          26472 :     if (!HeapTupleIsValid(proctup))
 2401 tgl@sss.pgh.pa.us        2275         [ #  # ]:UBC           0 :         elog(ERROR, "cache lookup failed for function %u", funcid);
 2401 tgl@sss.pgh.pa.us        2276                 :CBC       26472 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
                               2277                 :                : 
                               2278         [ -  + ]:          26472 :     Assert(procform->proretset); /* else caller error */
                               2279                 :                : 
                               2280         [ +  + ]:          26472 :     if (OidIsValid(procform->prosupport))
                               2281                 :                :     {
                               2282                 :                :         SupportRequestRows req;
                               2283                 :                :         SupportRequestRows *sresult;
                               2284                 :                : 
                               2285                 :           9552 :         req.type = T_SupportRequestRows;
                               2286                 :           9552 :         req.root = root;
                               2287                 :           9552 :         req.funcid = funcid;
                               2288                 :           9552 :         req.node = node;
                               2289                 :                : 
                               2290                 :           9552 :         req.rows = 0;           /* just for sanity */
                               2291                 :                : 
                               2292                 :                :         sresult = (SupportRequestRows *)
                               2293                 :           9552 :             DatumGetPointer(OidFunctionCall1(procform->prosupport,
                               2294                 :                :                                              PointerGetDatum(&req)));
                               2295                 :                : 
                               2296         [ +  + ]:           9552 :         if (sresult == &req)
                               2297                 :                :         {
                               2298                 :                :             /* Success */
                               2299                 :           7531 :             ReleaseSysCache(proctup);
                               2300                 :           7531 :             return req.rows;
                               2301                 :                :         }
                               2302                 :                :     }
                               2303                 :                : 
                               2304                 :                :     /* No support function, or it failed, so rely on prorows */
                               2305                 :          18941 :     result = procform->prorows;
                               2306                 :                : 
                               2307                 :          18941 :     ReleaseSysCache(proctup);
                               2308                 :                : 
                               2309                 :          18941 :     return result;
                               2310                 :                : }
                               2311                 :                : 
                               2312                 :                : /*
                               2313                 :                :  * has_unique_index
                               2314                 :                :  *
                               2315                 :                :  * Detect whether there is a unique index on the specified attribute
                               2316                 :                :  * of the specified relation, thus allowing us to conclude that all
                               2317                 :                :  * the (non-null) values of the attribute are distinct.
                               2318                 :                :  *
                               2319                 :                :  * This function does not check the index's indimmediate property, which
                               2320                 :                :  * means that uniqueness may transiently fail to hold intra-transaction.
                               2321                 :                :  * That's appropriate when we are making statistical estimates, but beware
                               2322                 :                :  * of using this for any correctness proofs.
                               2323                 :                :  */
                               2324                 :                : bool
 8875                          2325                 :        1028309 : has_unique_index(RelOptInfo *rel, AttrNumber attno)
                               2326                 :                : {
                               2327                 :                :     ListCell   *ilist;
                               2328                 :                : 
                               2329   [ +  +  +  +  :        2595187 :     foreach(ilist, rel->indexlist)
                                              +  + ]
                               2330                 :                :     {
                               2331                 :        1900421 :         IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
                               2332                 :                : 
                               2333                 :                :         /*
                               2334                 :                :          * Note: ignore partial indexes, since they don't allow us to conclude
                               2335                 :                :          * that all attr values are distinct, *unless* they are marked predOK
                               2336                 :                :          * which means we know the index's predicate is satisfied by the
                               2337                 :                :          * query. We don't take any interest in expressional indexes either.
                               2338                 :                :          * Also, a multicolumn unique index doesn't allow us to conclude that
                               2339                 :                :          * just the specified attr is unique.
                               2340                 :                :          */
                               2341         [ +  + ]:        1900421 :         if (index->unique &&
 2709 teodor@sigaev.ru         2342         [ +  + ]:        1300546 :             index->nkeycolumns == 1 &&
 8875 tgl@sss.pgh.pa.us        2343         [ +  + ]:         714048 :             index->indexkeys[0] == attno &&
 6047                          2344   [ +  +  +  + ]:         333561 :             (index->indpred == NIL || index->predOK))
 8875                          2345                 :         333543 :             return true;
                               2346                 :                :     }
                               2347                 :         694766 :     return false;
                               2348                 :                : }
                               2349                 :                : 
                               2350                 :                : 
                               2351                 :                : /*
                               2352                 :                :  * has_row_triggers
                               2353                 :                :  *
                               2354                 :                :  * Detect whether the specified relation has any row-level triggers for event.
                               2355                 :                :  */
                               2356                 :                : bool
 3459 rhaas@postgresql.org     2357                 :            258 : has_row_triggers(PlannerInfo *root, Index rti, CmdType event)
                               2358                 :                : {
                               2359         [ +  - ]:            258 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
                               2360                 :                :     Relation    relation;
                               2361                 :                :     TriggerDesc *trigDesc;
                               2362                 :            258 :     bool        result = false;
                               2363                 :                : 
                               2364                 :                :     /* Assume we already have adequate lock */
 2420 andres@anarazel.de       2365                 :            258 :     relation = table_open(rte->relid, NoLock);
                               2366                 :                : 
 3459 rhaas@postgresql.org     2367                 :            258 :     trigDesc = relation->trigdesc;
                               2368   [ +  +  +  -  :            258 :     switch (event)
                                                 - ]
                               2369                 :                :     {
                               2370                 :             82 :         case CMD_INSERT:
                               2371         [ +  + ]:             82 :             if (trigDesc &&
                               2372         [ +  + ]:             13 :                 (trigDesc->trig_insert_after_row ||
                               2373         [ +  - ]:              7 :                  trigDesc->trig_insert_before_row))
                               2374                 :             13 :                 result = true;
                               2375                 :             82 :             break;
                               2376                 :             95 :         case CMD_UPDATE:
                               2377         [ +  + ]:             95 :             if (trigDesc &&
                               2378         [ +  + ]:             24 :                 (trigDesc->trig_update_after_row ||
                               2379         [ +  + ]:             14 :                  trigDesc->trig_update_before_row))
                               2380                 :             18 :                 result = true;
                               2381                 :             95 :             break;
                               2382                 :             81 :         case CMD_DELETE:
                               2383         [ +  + ]:             81 :             if (trigDesc &&
                               2384         [ +  + ]:             15 :                 (trigDesc->trig_delete_after_row ||
                               2385         [ +  + ]:              9 :                  trigDesc->trig_delete_before_row))
                               2386                 :              8 :                 result = true;
                               2387                 :             81 :             break;
                               2388                 :                :             /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
 1258 alvherre@alvh.no-ip.     2389                 :UBC           0 :         case CMD_MERGE:
                               2390                 :              0 :             result = false;
   29 efujita@postgresql.o     2391                 :              0 :             break;
                               2392                 :              0 :         default:
                               2393         [ #  # ]:              0 :             elog(ERROR, "unrecognized CmdType: %d", (int) event);
                               2394                 :                :             break;
                               2395                 :                :     }
                               2396                 :                : 
   29 efujita@postgresql.o     2397                 :CBC         258 :     table_close(relation, NoLock);
                               2398                 :            258 :     return result;
                               2399                 :                : }
                               2400                 :                : 
                               2401                 :                : /*
                               2402                 :                :  * has_transition_tables
                               2403                 :                :  *
                               2404                 :                :  * Detect whether the specified relation has any transition tables for event.
                               2405                 :                :  */
                               2406                 :                : bool
                               2407                 :            195 : has_transition_tables(PlannerInfo *root, Index rti, CmdType event)
                               2408                 :                : {
                               2409         [ +  - ]:            195 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
                               2410                 :                :     Relation    relation;
                               2411                 :                :     TriggerDesc *trigDesc;
                               2412                 :            195 :     bool        result = false;
                               2413                 :                : 
                               2414         [ -  + ]:            195 :     Assert(rte->rtekind == RTE_RELATION);
                               2415                 :                : 
                               2416                 :                :     /* Currently foreign tables cannot have transition tables */
                               2417         [ +  + ]:            195 :     if (rte->relkind == RELKIND_FOREIGN_TABLE)
                               2418                 :            145 :         return result;
                               2419                 :                : 
                               2420                 :                :     /* Assume we already have adequate lock */
                               2421                 :             50 :     relation = table_open(rte->relid, NoLock);
                               2422                 :                : 
                               2423                 :             50 :     trigDesc = relation->trigdesc;
                               2424   [ -  +  +  -  :             50 :     switch (event)
                                                 - ]
                               2425                 :                :     {
   29 efujita@postgresql.o     2426                 :UBC           0 :         case CMD_INSERT:
                               2427         [ #  # ]:              0 :             if (trigDesc &&
                               2428         [ #  # ]:              0 :                 trigDesc->trig_insert_new_table)
                               2429                 :              0 :                 result = true;
                               2430                 :              0 :             break;
   29 efujita@postgresql.o     2431                 :CBC          30 :         case CMD_UPDATE:
                               2432         [ +  + ]:             30 :             if (trigDesc &&
                               2433         [ -  + ]:              4 :                 (trigDesc->trig_update_old_table ||
   29 efujita@postgresql.o     2434         [ #  # ]:UBC           0 :                  trigDesc->trig_update_new_table))
   29 efujita@postgresql.o     2435                 :CBC           4 :                 result = true;
                               2436                 :             30 :             break;
                               2437                 :             20 :         case CMD_DELETE:
                               2438         [ +  + ]:             20 :             if (trigDesc &&
                               2439         [ +  - ]:              4 :                 trigDesc->trig_delete_old_table)
                               2440                 :              4 :                 result = true;
                               2441                 :             20 :             break;
                               2442                 :                :             /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
   29 efujita@postgresql.o     2443                 :UBC           0 :         case CMD_MERGE:
                               2444                 :              0 :             result = false;
 1258 alvherre@alvh.no-ip.     2445                 :              0 :             break;
 3459 rhaas@postgresql.org     2446                 :              0 :         default:
                               2447         [ #  # ]:              0 :             elog(ERROR, "unrecognized CmdType: %d", (int) event);
                               2448                 :                :             break;
                               2449                 :                :     }
                               2450                 :                : 
 2420 andres@anarazel.de       2451                 :CBC          50 :     table_close(relation, NoLock);
 3459 rhaas@postgresql.org     2452                 :             50 :     return result;
                               2453                 :                : }
                               2454                 :                : 
                               2455                 :                : /*
                               2456                 :                :  * has_stored_generated_columns
                               2457                 :                :  *
                               2458                 :                :  * Does table identified by RTI have any STORED GENERATED columns?
                               2459                 :                :  */
                               2460                 :                : bool
 2352 peter@eisentraut.org     2461                 :            219 : has_stored_generated_columns(PlannerInfo *root, Index rti)
                               2462                 :                : {
                               2463         [ +  - ]:            219 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
                               2464                 :                :     Relation    relation;
                               2465                 :                :     TupleDesc   tupdesc;
      andres@anarazel.de       2466                 :            219 :     bool        result = false;
                               2467                 :                : 
                               2468                 :                :     /* Assume we already have adequate lock */
 2149 michael@paquier.xyz      2469                 :            219 :     relation = table_open(rte->relid, NoLock);
                               2470                 :                : 
 2352 peter@eisentraut.org     2471                 :            219 :     tupdesc = RelationGetDescr(relation);
                               2472   [ +  +  +  + ]:            219 :     result = tupdesc->constr && tupdesc->constr->has_generated_stored;
                               2473                 :                : 
 2149 michael@paquier.xyz      2474                 :            219 :     table_close(relation, NoLock);
                               2475                 :                : 
 2352 peter@eisentraut.org     2476                 :            219 :     return result;
                               2477                 :                : }
                               2478                 :                : 
                               2479                 :                : /*
                               2480                 :                :  * get_dependent_generated_columns
                               2481                 :                :  *
                               2482                 :                :  * Get the column numbers of any STORED GENERATED columns of the relation
                               2483                 :                :  * that depend on any column listed in target_cols.  Both the input and
                               2484                 :                :  * result bitmapsets contain column numbers offset by
                               2485                 :                :  * FirstLowInvalidHeapAttributeNumber.
                               2486                 :                :  */
                               2487                 :                : Bitmapset *
  975 tgl@sss.pgh.pa.us        2488                 :             45 : get_dependent_generated_columns(PlannerInfo *root, Index rti,
                               2489                 :                :                                 Bitmapset *target_cols)
                               2490                 :                : {
                               2491                 :             45 :     Bitmapset  *dependentCols = NULL;
                               2492         [ +  - ]:             45 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
                               2493                 :                :     Relation    relation;
                               2494                 :                :     TupleDesc   tupdesc;
                               2495                 :                :     TupleConstr *constr;
                               2496                 :                : 
                               2497                 :                :     /* Assume we already have adequate lock */
                               2498                 :             45 :     relation = table_open(rte->relid, NoLock);
                               2499                 :                : 
                               2500                 :             45 :     tupdesc = RelationGetDescr(relation);
                               2501                 :             45 :     constr = tupdesc->constr;
                               2502                 :                : 
                               2503   [ +  +  +  + ]:             45 :     if (constr && constr->has_generated_stored)
                               2504                 :                :     {
                               2505         [ +  + ]:              6 :         for (int i = 0; i < constr->num_defval; i++)
                               2506                 :                :         {
                               2507                 :              4 :             AttrDefault *defval = &constr->defval[i];
                               2508                 :                :             Node       *expr;
                               2509                 :              4 :             Bitmapset  *attrs_used = NULL;
                               2510                 :                : 
                               2511                 :                :             /* skip if not generated column */
                               2512         [ -  + ]:              4 :             if (!TupleDescAttr(tupdesc, defval->adnum - 1)->attgenerated)
  975 tgl@sss.pgh.pa.us        2513                 :UBC           0 :                 continue;
                               2514                 :                : 
                               2515                 :                :             /* identify columns this generated column depends on */
  975 tgl@sss.pgh.pa.us        2516                 :CBC           4 :             expr = stringToNode(defval->adbin);
                               2517                 :              4 :             pull_varattnos(expr, 1, &attrs_used);
                               2518                 :                : 
                               2519         [ +  - ]:              4 :             if (bms_overlap(target_cols, attrs_used))
                               2520                 :              4 :                 dependentCols = bms_add_member(dependentCols,
                               2521                 :              4 :                                                defval->adnum - FirstLowInvalidHeapAttributeNumber);
                               2522                 :                :         }
                               2523                 :                :     }
                               2524                 :                : 
                               2525                 :             45 :     table_close(relation, NoLock);
                               2526                 :                : 
                               2527                 :             45 :     return dependentCols;
                               2528                 :                : }
                               2529                 :                : 
                               2530                 :                : /*
                               2531                 :                :  * set_relation_partition_info
                               2532                 :                :  *
                               2533                 :                :  * Set partitioning scheme and related information for a partitioned table.
                               2534                 :                :  */
                               2535                 :                : static void
 2908 rhaas@postgresql.org     2536                 :           8491 : set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel,
                               2537                 :                :                             Relation relation)
                               2538                 :                : {
                               2539                 :                :     PartitionDesc partdesc;
                               2540                 :                : 
                               2541                 :                :     /*
                               2542                 :                :      * Create the PartitionDirectory infrastructure if we didn't already.
                               2543                 :                :      */
 2352 tgl@sss.pgh.pa.us        2544         [ +  + ]:           8491 :     if (root->glob->partition_directory == NULL)
                               2545                 :                :     {
                               2546                 :           5801 :         root->glob->partition_directory =
 1598 alvherre@alvh.no-ip.     2547                 :           5801 :             CreatePartitionDirectory(CurrentMemoryContext, true);
                               2548                 :                :     }
                               2549                 :                : 
 2375 rhaas@postgresql.org     2550                 :           8491 :     partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
                               2551                 :                :                                         relation);
 2908                          2552                 :           8491 :     rel->part_scheme = find_partition_scheme(root, relation);
                               2553   [ +  -  -  + ]:           8491 :     Assert(partdesc != NULL && rel->part_scheme != NULL);
 2360 tgl@sss.pgh.pa.us        2554                 :           8491 :     rel->boundinfo = partdesc->boundinfo;
 2908 rhaas@postgresql.org     2555                 :           8491 :     rel->nparts = partdesc->nparts;
 2892                          2556                 :           8491 :     set_baserel_partition_key_exprs(relation, rel);
 2216 alvherre@alvh.no-ip.     2557                 :           8491 :     set_baserel_partition_constraint(relation, rel);
 2908 rhaas@postgresql.org     2558                 :           8491 : }
                               2559                 :                : 
                               2560                 :                : /*
                               2561                 :                :  * find_partition_scheme
                               2562                 :                :  *
                               2563                 :                :  * Find or create a PartitionScheme for this Relation.
                               2564                 :                :  */
                               2565                 :                : static PartitionScheme
                               2566                 :           8491 : find_partition_scheme(PlannerInfo *root, Relation relation)
                               2567                 :                : {
                               2568                 :           8491 :     PartitionKey partkey = RelationGetPartitionKey(relation);
                               2569                 :                :     ListCell   *lc;
                               2570                 :                :     int         partnatts,
                               2571                 :                :                 i;
                               2572                 :                :     PartitionScheme part_scheme;
                               2573                 :                : 
                               2574                 :                :     /* A partitioned table should have a partition key. */
                               2575         [ -  + ]:           8491 :     Assert(partkey != NULL);
                               2576                 :                : 
                               2577                 :           8491 :     partnatts = partkey->partnatts;
                               2578                 :                : 
                               2579                 :                :     /* Search for a matching partition scheme and return if found one. */
                               2580   [ +  +  +  +  :           9436 :     foreach(lc, root->part_schemes)
                                              +  + ]
                               2581                 :                :     {
                               2582                 :           2986 :         part_scheme = lfirst(lc);
                               2583                 :                : 
                               2584                 :                :         /* Match partitioning strategy and number of keys. */
                               2585         [ +  + ]:           2986 :         if (partkey->strategy != part_scheme->strategy ||
                               2586         [ +  + ]:           2491 :             partnatts != part_scheme->partnatts)
                               2587                 :            720 :             continue;
                               2588                 :                : 
                               2589                 :                :         /* Match partition key type properties. */
                               2590         [ +  + ]:           2266 :         if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
                               2591                 :           2041 :                    sizeof(Oid) * partnatts) != 0 ||
                               2592         [ +  - ]:           2041 :             memcmp(partkey->partopcintype, part_scheme->partopcintype,
                               2593                 :           2041 :                    sizeof(Oid) * partnatts) != 0 ||
 2747                          2594         [ -  + ]:           2041 :             memcmp(partkey->partcollation, part_scheme->partcollation,
                               2595                 :                :                    sizeof(Oid) * partnatts) != 0)
 2908                          2596                 :            225 :             continue;
                               2597                 :                : 
                               2598                 :                :         /*
                               2599                 :                :          * Length and byval information should match when partopcintype
                               2600                 :                :          * matches.
                               2601                 :                :          */
                               2602         [ -  + ]:           2041 :         Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
                               2603                 :                :                       sizeof(int16) * partnatts) == 0);
                               2604         [ -  + ]:           2041 :         Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
                               2605                 :                :                       sizeof(bool) * partnatts) == 0);
                               2606                 :                : 
                               2607                 :                :         /*
                               2608                 :                :          * If partopfamily and partopcintype matched, must have the same
                               2609                 :                :          * partition comparison functions.  Note that we cannot reliably
                               2610                 :                :          * Assert the equality of function structs themselves for they might
                               2611                 :                :          * be different across PartitionKey's, so just Assert for the function
                               2612                 :                :          * OIDs.
                               2613                 :                :          */
                               2614                 :                : #ifdef USE_ASSERT_CHECKING
 2710 alvherre@alvh.no-ip.     2615         [ +  + ]:           4097 :         for (i = 0; i < partkey->partnatts; i++)
                               2616         [ -  + ]:           2056 :             Assert(partkey->partsupfunc[i].fn_oid ==
                               2617                 :                :                    part_scheme->partsupfunc[i].fn_oid);
                               2618                 :                : #endif
                               2619                 :                : 
                               2620                 :                :         /* Found matching partition scheme. */
 2908 rhaas@postgresql.org     2621                 :           2041 :         return part_scheme;
                               2622                 :                :     }
                               2623                 :                : 
                               2624                 :                :     /*
                               2625                 :                :      * Did not find matching partition scheme. Create one copying relevant
                               2626                 :                :      * information from the relcache. We need to copy the contents of the
                               2627                 :                :      * array since the relcache entry may not survive after we have closed the
                               2628                 :                :      * relation.
                               2629                 :                :      */
                               2630                 :           6450 :     part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
                               2631                 :           6450 :     part_scheme->strategy = partkey->strategy;
                               2632                 :           6450 :     part_scheme->partnatts = partkey->partnatts;
                               2633                 :                : 
 2892                          2634                 :           6450 :     part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
                               2635                 :           6450 :     memcpy(part_scheme->partopfamily, partkey->partopfamily,
                               2636                 :                :            sizeof(Oid) * partnatts);
                               2637                 :                : 
                               2638                 :           6450 :     part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
                               2639                 :           6450 :     memcpy(part_scheme->partopcintype, partkey->partopcintype,
                               2640                 :                :            sizeof(Oid) * partnatts);
                               2641                 :                : 
 2747                          2642                 :           6450 :     part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
                               2643                 :           6450 :     memcpy(part_scheme->partcollation, partkey->partcollation,
                               2644                 :                :            sizeof(Oid) * partnatts);
                               2645                 :                : 
 2892                          2646                 :           6450 :     part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
                               2647                 :           6450 :     memcpy(part_scheme->parttyplen, partkey->parttyplen,
                               2648                 :                :            sizeof(int16) * partnatts);
                               2649                 :                : 
                               2650                 :           6450 :     part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
                               2651                 :           6450 :     memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
                               2652                 :                :            sizeof(bool) * partnatts);
                               2653                 :                : 
 2710 alvherre@alvh.no-ip.     2654                 :           6450 :     part_scheme->partsupfunc = (FmgrInfo *)
                               2655                 :           6450 :         palloc(sizeof(FmgrInfo) * partnatts);
                               2656         [ +  + ]:          13824 :     for (i = 0; i < partnatts; i++)
                               2657                 :           7374 :         fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
                               2658                 :                :                        CurrentMemoryContext);
                               2659                 :                : 
                               2660                 :                :     /* Add the partitioning scheme to PlannerInfo. */
 2908 rhaas@postgresql.org     2661                 :           6450 :     root->part_schemes = lappend(root->part_schemes, part_scheme);
                               2662                 :                : 
                               2663                 :           6450 :     return part_scheme;
                               2664                 :                : }
                               2665                 :                : 
                               2666                 :                : /*
                               2667                 :                :  * set_baserel_partition_key_exprs
                               2668                 :                :  *
                               2669                 :                :  * Builds partition key expressions for the given base relation and fills
                               2670                 :                :  * rel->partexprs.
                               2671                 :                :  */
                               2672                 :                : static void
 2892                          2673                 :           8491 : set_baserel_partition_key_exprs(Relation relation,
                               2674                 :                :                                 RelOptInfo *rel)
                               2675                 :                : {
 2908                          2676                 :           8491 :     PartitionKey partkey = RelationGetPartitionKey(relation);
                               2677                 :                :     int         partnatts;
                               2678                 :                :     int         cnt;
                               2679                 :                :     List      **partexprs;
                               2680                 :                :     ListCell   *lc;
 2892                          2681                 :           8491 :     Index       varno = rel->relid;
                               2682                 :                : 
                               2683   [ +  +  +  -  :           8491 :     Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
                                              -  + ]
                               2684                 :                : 
                               2685                 :                :     /* A partitioned table should have a partition key. */
 2908                          2686         [ -  + ]:           8491 :     Assert(partkey != NULL);
                               2687                 :                : 
                               2688                 :           8491 :     partnatts = partkey->partnatts;
                               2689                 :           8491 :     partexprs = (List **) palloc(sizeof(List *) * partnatts);
                               2690                 :           8491 :     lc = list_head(partkey->partexprs);
                               2691                 :                : 
                               2692         [ +  + ]:          17921 :     for (cnt = 0; cnt < partnatts; cnt++)
                               2693                 :                :     {
                               2694                 :                :         Expr       *partexpr;
                               2695                 :           9430 :         AttrNumber  attno = partkey->partattrs[cnt];
                               2696                 :                : 
                               2697         [ +  + ]:           9430 :         if (attno != InvalidAttrNumber)
                               2698                 :                :         {
                               2699                 :                :             /* Single column partition key is stored as a Var node. */
                               2700         [ -  + ]:           8965 :             Assert(attno > 0);
                               2701                 :                : 
                               2702                 :           8965 :             partexpr = (Expr *) makeVar(varno, attno,
                               2703                 :           8965 :                                         partkey->parttypid[cnt],
                               2704                 :           8965 :                                         partkey->parttypmod[cnt],
                               2705                 :           8965 :                                         partkey->parttypcoll[cnt], 0);
                               2706                 :                :         }
                               2707                 :                :         else
                               2708                 :                :         {
                               2709         [ -  + ]:            465 :             if (lc == NULL)
 2908 rhaas@postgresql.org     2710         [ #  # ]:UBC           0 :                 elog(ERROR, "wrong number of partition key expressions");
                               2711                 :                : 
                               2712                 :                :             /* Re-stamp the expression with given varno. */
 2908 rhaas@postgresql.org     2713                 :CBC         465 :             partexpr = (Expr *) copyObject(lfirst(lc));
                               2714                 :            465 :             ChangeVarNodes((Node *) partexpr, 1, varno, 0);
 2245 tgl@sss.pgh.pa.us        2715                 :            465 :             lc = lnext(partkey->partexprs, lc);
                               2716                 :                :         }
                               2717                 :                : 
                               2718                 :                :         /* Base relations have a single expression per key. */
 2908 rhaas@postgresql.org     2719                 :           9430 :         partexprs[cnt] = list_make1(partexpr);
                               2720                 :                :     }
                               2721                 :                : 
 2892                          2722                 :           8491 :     rel->partexprs = partexprs;
                               2723                 :                : 
                               2724                 :                :     /*
                               2725                 :                :      * A base relation does not have nullable partition key expressions, since
                               2726                 :                :      * no outer join is involved.  We still allocate an array of empty
                               2727                 :                :      * expression lists to keep partition key expression handling code simple.
                               2728                 :                :      * See build_joinrel_partition_info() and match_expr_to_partition_keys().
                               2729                 :                :      */
                               2730                 :           8491 :     rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
 2908                          2731                 :           8491 : }
                               2732                 :                : 
                               2733                 :                : /*
                               2734                 :                :  * set_baserel_partition_constraint
                               2735                 :                :  *
                               2736                 :                :  * Builds the partition constraint for the given base relation and sets it
                               2737                 :                :  * in the given RelOptInfo.  All Var nodes are restamped with the relid of the
                               2738                 :                :  * given relation.
                               2739                 :                :  */
                               2740                 :                : static void
 2216 alvherre@alvh.no-ip.     2741                 :           8497 : set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
                               2742                 :                : {
                               2743                 :                :     List       *partconstr;
                               2744                 :                : 
                               2745         [ -  + ]:           8497 :     if (rel->partition_qual) /* already done */
 2216 alvherre@alvh.no-ip.     2746                 :UBC           0 :         return;
                               2747                 :                : 
                               2748                 :                :     /*
                               2749                 :                :      * Run the partition quals through const-simplification similar to check
                               2750                 :                :      * constraints.  We skip canonicalize_qual, though, because partition
                               2751                 :                :      * quals should be in canonical form already; also, since the qual is in
                               2752                 :                :      * implicit-AND format, we'd have to explicitly convert it to explicit-AND
                               2753                 :                :      * format and back again.
                               2754                 :                :      */
 2216 alvherre@alvh.no-ip.     2755                 :CBC        8497 :     partconstr = RelationGetPartitionQual(relation);
                               2756         [ +  + ]:           8497 :     if (partconstr)
                               2757                 :                :     {
                               2758                 :           1712 :         partconstr = (List *) expression_planner((Expr *) partconstr);
                               2759         [ +  + ]:           1712 :         if (rel->relid != 1)
                               2760                 :           1671 :             ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
                               2761                 :           1712 :         rel->partition_qual = partconstr;
                               2762                 :                :     }
                               2763                 :                : }
        

Generated by: LCOV version 2.4-beta