LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/util - plancat.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 93.2 % 813 758 55 11 747 4
Current Date: 2024-04-14 14:21:10 Functions: 100.0 % 26 26 3 23
Baseline: 16@8cea358b128 Branches: 78.8 % 593 467 2 124 14 453
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 100.0 % 7 7 7
(60,120] days: 100.0 % 2 2 2
(180,240] days: 100.0 % 2 2 2
(240..) days: 93.1 % 802 747 55 747
Function coverage date bins:
(240..) days: 100.0 % 26 26 3 23
Branch coverage date bins:
[..60] days: 90.0 % 10 9 1 9
(180,240] days: 83.3 % 6 5 1 5
(240..) days: 78.5 % 577 453 124 453

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

Generated by: LCOV version 2.1-beta2-3-g6141622