LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - plancat.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 818 887 92.2 %
Date: 2025-12-03 05:18:44 Functions: 29 29 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16