LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - plancat.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 743 798 93.1 %
Date: 2024-07-27 02:11:23 Functions: 26 26 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14