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: 2024-11-21 08:14:44 Functions: 26 26 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14