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

Generated by: LCOV version 1.14