LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - plancat.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 800 866 92.4 %
Date: 2025-11-12 19:18:39 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      476456 : get_relation_info(PlannerInfo *root, Oid relationObjectId, bool inhparent,
     125             :                   RelOptInfo *rel)
     126             : {
     127      476456 :     Index       varno = rel->relid;
     128             :     Relation    relation;
     129             :     bool        hasindex;
     130      476456 :     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      476456 :     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      476456 :     if (!relation->rd_tableam)
     147             :     {
     148       20192 :         if (!(relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE ||
     149       17678 :               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      476456 :     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      476456 :     rel->min_attr = FirstLowInvalidHeapAttributeNumber + 1;
     164      476456 :     rel->max_attr = RelationGetNumberOfAttributes(relation);
     165      476456 :     rel->reltablespace = RelationGetForm(relation)->reltablespace;
     166             : 
     167             :     Assert(rel->max_attr >= rel->min_attr);
     168      476456 :     rel->attr_needed = (Relids *)
     169      476456 :         palloc0((rel->max_attr - rel->min_attr + 1) * sizeof(Relids));
     170      476456 :     rel->attr_widths = (int32 *)
     171      476456 :         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      476456 :     if (!inhparent || relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     183      438782 :         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      476456 :     if (!inhparent)
     191      421144 :         estimate_rel_size(relation, rel->attr_widths - rel->min_attr,
     192      421144 :                           &rel->pages, &rel->tuples, &rel->allvisfrac);
     193             : 
     194             :     /* Retrieve the parallel_workers reloption, or -1 if not set. */
     195      476456 :     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      476456 :     if ((inhparent && relation->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
     206      438782 :         || (IgnoreSystemIndexes && IsSystemRelation(relation)))
     207       37674 :         hasindex = false;
     208             :     else
     209      438782 :         hasindex = relation->rd_rel->relhasindex;
     210             : 
     211      476456 :     if (hasindex)
     212             :     {
     213             :         List       *indexoidlist;
     214             :         LOCKMODE    lmode;
     215             :         ListCell   *l;
     216             : 
     217      353406 :         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      353406 :         lmode = root->simple_rte_array[varno]->rellockmode;
     228             : 
     229     1099292 :         foreach(l, indexoidlist)
     230             :         {
     231      745886 :             Oid         indexoid = lfirst_oid(l);
     232             :             Relation    indexRelation;
     233             :             Form_pg_index index;
     234      745886 :             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      745886 :             indexRelation = index_open(indexoid, lmode);
     244      745886 :             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      745886 :             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      745864 :             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      745570 :             info = makeNode(IndexOptInfo);
     274             : 
     275      745570 :             info->indexoid = index->indexrelid;
     276      745570 :             info->reltablespace =
     277      745570 :                 RelationGetForm(indexRelation)->reltablespace;
     278      745570 :             info->rel = rel;
     279      745570 :             info->ncolumns = ncolumns = index->indnatts;
     280      745570 :             info->nkeycolumns = nkeycolumns = index->indnkeyatts;
     281             : 
     282      745570 :             info->indexkeys = (int *) palloc(sizeof(int) * ncolumns);
     283      745570 :             info->indexcollations = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
     284      745570 :             info->opfamily = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
     285      745570 :             info->opcintype = (Oid *) palloc(sizeof(Oid) * nkeycolumns);
     286      745570 :             info->canreturn = (bool *) palloc(sizeof(bool) * ncolumns);
     287             : 
     288     2150120 :             for (i = 0; i < ncolumns; i++)
     289             :             {
     290     1404550 :                 info->indexkeys[i] = index->indkey.values[i];
     291     1404550 :                 info->canreturn[i] = index_can_return(indexRelation, i + 1);
     292             :             }
     293             : 
     294     2149702 :             for (i = 0; i < nkeycolumns; i++)
     295             :             {
     296     1404132 :                 info->opfamily[i] = indexRelation->rd_opfamily[i];
     297     1404132 :                 info->opcintype[i] = indexRelation->rd_opcintype[i];
     298     1404132 :                 info->indexcollations[i] = indexRelation->rd_indcollation[i];
     299             :             }
     300             : 
     301      745570 :             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      745570 :             if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
     308             :             {
     309             :                 /* We copy just the fields we need, not all of rd_indam */
     310      738906 :                 amroutine = indexRelation->rd_indam;
     311      738906 :                 info->amcanorderbyop = amroutine->amcanorderbyop;
     312      738906 :                 info->amoptionalkey = amroutine->amoptionalkey;
     313      738906 :                 info->amsearcharray = amroutine->amsearcharray;
     314      738906 :                 info->amsearchnulls = amroutine->amsearchnulls;
     315      738906 :                 info->amcanparallel = amroutine->amcanparallel;
     316      738906 :                 info->amhasgettuple = (amroutine->amgettuple != NULL);
     317     1477812 :                 info->amhasgetbitmap = amroutine->amgetbitmap != NULL &&
     318      738906 :                     relation->rd_tableam->scan_bitmap_next_tuple != NULL;
     319     1455716 :                 info->amcanmarkpos = (amroutine->ammarkpos != NULL &&
     320      716810 :                                       amroutine->amrestrpos != NULL);
     321      738906 :                 info->amcostestimate = amroutine->amcostestimate;
     322             :                 Assert(info->amcostestimate != NULL);
     323             : 
     324             :                 /* Fetch index opclass options */
     325      738906 :                 info->opclassoptions = RelationGetIndexAttOptions(indexRelation, true);
     326             : 
     327             :                 /*
     328             :                  * Fetch the ordering information for the index, if any.
     329             :                  */
     330      738906 :                 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      716810 :                     info->sortopfamily = info->opfamily;
     339      716810 :                     info->reverse_sort = (bool *) palloc(sizeof(bool) * nkeycolumns);
     340      716810 :                     info->nulls_first = (bool *) palloc(sizeof(bool) * nkeycolumns);
     341             : 
     342     1831362 :                     for (i = 0; i < nkeycolumns; i++)
     343             :                     {
     344     1114552 :                         int16       opt = indexRelation->rd_indoption[i];
     345             : 
     346     1114552 :                         info->reverse_sort[i] = (opt & INDOPTION_DESC) != 0;
     347     1114552 :                         info->nulls_first[i] = (opt & INDOPTION_NULLS_FIRST) != 0;
     348             :                     }
     349             :                 }
     350       22096 :                 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       22096 :                     info->sortopfamily = NULL;
     406       22096 :                     info->reverse_sort = NULL;
     407       22096 :                     info->nulls_first = NULL;
     408             :                 }
     409             :             }
     410             :             else
     411             :             {
     412        6664 :                 info->amcanorderbyop = false;
     413        6664 :                 info->amoptionalkey = false;
     414        6664 :                 info->amsearcharray = false;
     415        6664 :                 info->amsearchnulls = false;
     416        6664 :                 info->amcanparallel = false;
     417        6664 :                 info->amhasgettuple = false;
     418        6664 :                 info->amhasgetbitmap = false;
     419        6664 :                 info->amcanmarkpos = false;
     420        6664 :                 info->amcostestimate = NULL;
     421             : 
     422        6664 :                 info->sortopfamily = NULL;
     423        6664 :                 info->reverse_sort = NULL;
     424        6664 :                 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      745570 :             info->indexprs = RelationGetIndexExpressions(indexRelation);
     434      745570 :             info->indpred = RelationGetIndexPredicate(indexRelation);
     435      745570 :             if (info->indexprs && varno != 1)
     436        1938 :                 ChangeVarNodes((Node *) info->indexprs, 1, varno, 0);
     437      745570 :             if (info->indpred && varno != 1)
     438         126 :                 ChangeVarNodes((Node *) info->indpred, 1, varno, 0);
     439             : 
     440             :             /* Build targetlist using the completed indexprs data */
     441      745570 :             info->indextlist = build_index_tlist(root, info, relation);
     442             : 
     443      745570 :             info->indrestrictinfo = NIL; /* set later, in indxpath.c */
     444      745570 :             info->predOK = false;    /* set later, in indxpath.c */
     445      745570 :             info->unique = index->indisunique;
     446      745570 :             info->nullsnotdistinct = index->indnullsnotdistinct;
     447      745570 :             info->immediate = index->indimmediate;
     448      745570 :             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      745570 :             if (indexRelation->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
     459             :             {
     460      738906 :                 if (info->indpred == NIL)
     461             :                 {
     462      737922 :                     info->pages = RelationGetNumberOfBlocks(indexRelation);
     463      737922 :                     info->tuples = rel->tuples;
     464             :                 }
     465             :                 else
     466             :                 {
     467             :                     double      allvisfrac; /* dummy */
     468             : 
     469         984 :                     estimate_rel_size(indexRelation, NULL,
     470         984 :                                       &info->pages, &info->tuples, &allvisfrac);
     471         984 :                     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      738906 :                 if (amroutine->amgettreeheight)
     479             :                 {
     480      716810 :                     info->tree_height = amroutine->amgettreeheight(indexRelation);
     481             :                 }
     482             :                 else
     483             :                 {
     484             :                     /* For other index types, just set it to "unknown" for now */
     485       22096 :                     info->tree_height = -1;
     486             :                 }
     487             :             }
     488             :             else
     489             :             {
     490             :                 /* Zero these out for partitioned indexes */
     491        6664 :                 info->pages = 0;
     492        6664 :                 info->tuples = 0.0;
     493        6664 :                 info->tree_height = -1;
     494             :             }
     495             : 
     496      745570 :             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      745570 :             indexinfos = lcons(info, indexinfos);
     506             :         }
     507             : 
     508      353406 :         list_free(indexoidlist);
     509             :     }
     510             : 
     511      476456 :     rel->indexlist = indexinfos;
     512             : 
     513      476456 :     rel->statlist = get_relation_statistics(root, rel, relation);
     514             : 
     515             :     /* Grab foreign-table info using the relcache, while we have it */
     516      476456 :     if (relation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
     517             :     {
     518             :         /* Check if the access to foreign tables is restricted */
     519        2514 :         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        2510 :         rel->serverid = GetForeignServerIdByRelId(RelationGetRelid(relation));
     530        2510 :         rel->fdwroutine = GetFdwRoutineForRelation(relation, true);
     531             :     }
     532             :     else
     533             :     {
     534      473942 :         rel->serverid = InvalidOid;
     535      473942 :         rel->fdwroutine = NULL;
     536             :     }
     537             : 
     538             :     /* Collect info about relation's foreign keys, if relevant */
     539      476438 :     get_relation_foreign_keys(root, rel, relation, inhparent);
     540             : 
     541             :     /* Collect info about functions implemented by the rel's table AM. */
     542      476438 :     if (relation->rd_tableam &&
     543      456264 :         relation->rd_tableam->scan_set_tidrange != NULL &&
     544      456264 :         relation->rd_tableam->scan_getnextslot_tidrange != NULL)
     545      456264 :         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      476438 :     if (inhparent && relation->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
     552       17638 :         set_relation_partition_info(root, rel, relation);
     553             : 
     554      476438 :     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      476438 :     if (get_relation_info_hook)
     562           0 :         (*get_relation_info_hook) (root, relationObjectId, inhparent, rel);
     563      476438 : }
     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      476438 : get_relation_foreign_keys(PlannerInfo *root, RelOptInfo *rel,
     577             :                           Relation relation, bool inhparent)
     578             : {
     579      476438 :     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      909418 :     if (rel->reloptkind != RELOPT_BASEREL ||
     589      432980 :         list_length(rtable) < 2)
     590      244160 :         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      232278 :     if (inhparent)
     599        5898 :         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      226380 :     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      228974 :     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      514588 : get_relation_notnullatts(PlannerInfo *root, Relation relation)
     683             : {
     684      514588 :     Oid         relid = RelationGetRelid(relation);
     685             :     NotnullHashEntry *hentry;
     686             :     bool        found;
     687      514588 :     Bitmapset  *notnullattnums = NULL;
     688             : 
     689             :     /* bail out if the relation has no not-null constraints */
     690      514588 :     if (relation->rd_att->constr == NULL ||
     691      343126 :         !relation->rd_att->constr->has_not_null)
     692      215794 :         return;
     693             : 
     694             :     /* create the hash table if it hasn't been created yet */
     695      337830 :     if (root->glob->rel_notnullatts_hash == NULL)
     696             :     {
     697             :         HTAB       *hashtab;
     698             :         HASHCTL     hash_ctl;
     699             : 
     700      171130 :         hash_ctl.keysize = sizeof(Oid);
     701      171130 :         hash_ctl.entrysize = sizeof(NotnullHashEntry);
     702      171130 :         hash_ctl.hcxt = CurrentMemoryContext;
     703             : 
     704      171130 :         hashtab = hash_create("Relation NOT NULL attnums",
     705             :                               64L,  /* arbitrary initial size */
     706             :                               &hash_ctl,
     707             :                               HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
     708             : 
     709      171130 :         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      337830 :     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      337830 :     if (found)
     723       39036 :         return;
     724             : 
     725             :     /* collect the column not-null constraint information for this relation */
     726     4467260 :     for (int i = 0; i < relation->rd_att->natts; i++)
     727             :     {
     728     4168466 :         CompactAttribute *attr = TupleDescCompactAttr(relation->rd_att, i);
     729             : 
     730             :         Assert(attr->attnullability != ATTNULLABLE_UNKNOWN);
     731             : 
     732     4168466 :         if (attr->attnullability == ATTNULLABLE_VALID)
     733             :         {
     734     3528584 :             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      298794 :     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      452744 : find_relation_notnullatts(PlannerInfo *root, Oid relid)
     756             : {
     757             :     NotnullHashEntry *hentry;
     758             :     bool        found;
     759             : 
     760      452744 :     if (root->glob->rel_notnullatts_hash == NULL)
     761      120070 :         return NULL;
     762             : 
     763      332674 :     hentry = (NotnullHashEntry *) hash_search(root->glob->rel_notnullatts_hash,
     764             :                                               &relid,
     765             :                                               HASH_FIND,
     766             :                                               &found);
     767      332674 :     if (!found)
     768        5068 :         return NULL;
     769             : 
     770      327606 :     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             :  * Note: during index CONCURRENTLY operations, different transactions may
     794             :  * reference different sets of arbiter indexes. This can lead to false unique
     795             :  * constraint violations that wouldn't occur during normal operations.  For
     796             :  * more information, see insert.sgml.
     797             :  */
     798             : List *
     799        1862 : infer_arbiter_indexes(PlannerInfo *root)
     800             : {
     801        1862 :     OnConflictExpr *onconflict = root->parse->onConflict;
     802             : 
     803             :     /* Iteration state */
     804             :     Index       varno;
     805             :     RangeTblEntry *rte;
     806             :     Relation    relation;
     807        1862 :     Oid         indexOidFromConstraint = InvalidOid;
     808             :     List       *indexList;
     809             :     ListCell   *l;
     810             : 
     811             :     /* Normalized inference attributes and inference expressions: */
     812        1862 :     Bitmapset  *inferAttrs = NULL;
     813        1862 :     List       *inferElems = NIL;
     814             : 
     815             :     /* Results */
     816        1862 :     List       *results = NIL;
     817             : 
     818             :     /*
     819             :      * Quickly return NIL for ON CONFLICT DO NOTHING without an inference
     820             :      * specification or named constraint.  ON CONFLICT DO UPDATE statements
     821             :      * must always provide one or the other (but parser ought to have caught
     822             :      * that already).
     823             :      */
     824        1862 :     if (onconflict->arbiterElems == NIL &&
     825         426 :         onconflict->constraint == InvalidOid)
     826         234 :         return NIL;
     827             : 
     828             :     /*
     829             :      * We need not lock the relation since it was already locked, either by
     830             :      * the rewriter or when expand_inherited_rtentry() added it to the query's
     831             :      * rangetable.
     832             :      */
     833        1628 :     varno = root->parse->resultRelation;
     834        1628 :     rte = rt_fetch(varno, root->parse->rtable);
     835             : 
     836        1628 :     relation = table_open(rte->relid, NoLock);
     837             : 
     838             :     /*
     839             :      * Build normalized/BMS representation of plain indexed attributes, as
     840             :      * well as a separate list of expression items.  This simplifies matching
     841             :      * the cataloged definition of indexes.
     842             :      */
     843        3518 :     foreach(l, onconflict->arbiterElems)
     844             :     {
     845        1890 :         InferenceElem *elem = (InferenceElem *) lfirst(l);
     846             :         Var        *var;
     847             :         int         attno;
     848             : 
     849        1890 :         if (!IsA(elem->expr, Var))
     850             :         {
     851             :             /* If not a plain Var, just shove it in inferElems for now */
     852         174 :             inferElems = lappend(inferElems, elem->expr);
     853         174 :             continue;
     854             :         }
     855             : 
     856        1716 :         var = (Var *) elem->expr;
     857        1716 :         attno = var->varattno;
     858             : 
     859        1716 :         if (attno == 0)
     860           0 :             ereport(ERROR,
     861             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     862             :                      errmsg("whole row unique index inference specifications are not supported")));
     863             : 
     864        1716 :         inferAttrs = bms_add_member(inferAttrs,
     865             :                                     attno - FirstLowInvalidHeapAttributeNumber);
     866             :     }
     867             : 
     868             :     /*
     869             :      * Lookup named constraint's index.  This is not immediately returned
     870             :      * because some additional sanity checks are required.
     871             :      */
     872        1628 :     if (onconflict->constraint != InvalidOid)
     873             :     {
     874         192 :         indexOidFromConstraint = get_constraint_index(onconflict->constraint);
     875             : 
     876         192 :         if (indexOidFromConstraint == InvalidOid)
     877           0 :             ereport(ERROR,
     878             :                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     879             :                      errmsg("constraint in ON CONFLICT clause has no associated index")));
     880             :     }
     881             : 
     882             :     /*
     883             :      * Using that representation, iterate through the list of indexes on the
     884             :      * target relation to try and find a match
     885             :      */
     886        1628 :     indexList = RelationGetIndexList(relation);
     887             : 
     888        3492 :     foreach(l, indexList)
     889             :     {
     890        2056 :         Oid         indexoid = lfirst_oid(l);
     891             :         Relation    idxRel;
     892             :         Form_pg_index idxForm;
     893             :         Bitmapset  *indexedAttrs;
     894             :         List       *idxExprs;
     895             :         List       *predExprs;
     896             :         AttrNumber  natt;
     897             :         ListCell   *el;
     898             : 
     899             :         /*
     900             :          * Extract info from the relation descriptor for the index.  Obtain
     901             :          * the same lock type that the executor will ultimately use.
     902             :          *
     903             :          * Let executor complain about !indimmediate case directly, because
     904             :          * enforcement needs to occur there anyway when an inference clause is
     905             :          * omitted.
     906             :          */
     907        2056 :         idxRel = index_open(indexoid, rte->rellockmode);
     908        2056 :         idxForm = idxRel->rd_index;
     909             : 
     910        2056 :         if (!idxForm->indisvalid)
     911           6 :             goto next;
     912             : 
     913             :         /*
     914             :          * Note that we do not perform a check against indcheckxmin (like e.g.
     915             :          * get_relation_info()) here to eliminate candidates, because
     916             :          * uniqueness checking only cares about the most recently committed
     917             :          * tuple versions.
     918             :          */
     919             : 
     920             :         /*
     921             :          * Look for match on "ON constraint_name" variant, which may not be
     922             :          * unique constraint.  This can only be a constraint name.
     923             :          */
     924        2050 :         if (indexOidFromConstraint == idxForm->indexrelid)
     925             :         {
     926         192 :             if (idxForm->indisexclusion && onconflict->action == ONCONFLICT_UPDATE)
     927          78 :                 ereport(ERROR,
     928             :                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     929             :                          errmsg("ON CONFLICT DO UPDATE not supported with exclusion constraints")));
     930             : 
     931         114 :             results = lappend_oid(results, idxForm->indexrelid);
     932         114 :             list_free(indexList);
     933         114 :             index_close(idxRel, NoLock);
     934         114 :             table_close(relation, NoLock);
     935         114 :             return results;
     936             :         }
     937        1858 :         else if (indexOidFromConstraint != InvalidOid)
     938             :         {
     939             :             /* No point in further work for index in named constraint case */
     940          18 :             goto next;
     941             :         }
     942             : 
     943             :         /*
     944             :          * Only considering conventional inference at this point (not named
     945             :          * constraints), so index under consideration can be immediately
     946             :          * skipped if it's not unique
     947             :          */
     948        1840 :         if (!idxForm->indisunique)
     949           4 :             goto next;
     950             : 
     951             :         /*
     952             :          * So-called unique constraints with WITHOUT OVERLAPS are really
     953             :          * exclusion constraints, so skip those too.
     954             :          */
     955        1836 :         if (idxForm->indisexclusion)
     956         144 :             goto next;
     957             : 
     958             :         /* Build BMS representation of plain (non expression) index attrs */
     959        1692 :         indexedAttrs = NULL;
     960        3948 :         for (natt = 0; natt < idxForm->indnkeyatts; natt++)
     961             :         {
     962        2256 :             int         attno = idxRel->rd_index->indkey.values[natt];
     963             : 
     964        2256 :             if (attno != 0)
     965        1944 :                 indexedAttrs = bms_add_member(indexedAttrs,
     966             :                                               attno - FirstLowInvalidHeapAttributeNumber);
     967             :         }
     968             : 
     969             :         /* Non-expression attributes (if any) must match */
     970        1692 :         if (!bms_equal(indexedAttrs, inferAttrs))
     971         378 :             goto next;
     972             : 
     973             :         /* Expression attributes (if any) must match */
     974        1314 :         idxExprs = RelationGetIndexExpressions(idxRel);
     975        1314 :         if (idxExprs && varno != 1)
     976           6 :             ChangeVarNodes((Node *) idxExprs, 1, varno, 0);
     977             : 
     978        2988 :         foreach(el, onconflict->arbiterElems)
     979             :         {
     980        1722 :             InferenceElem *elem = (InferenceElem *) lfirst(el);
     981             : 
     982             :             /*
     983             :              * Ensure that collation/opclass aspects of inference expression
     984             :              * element match.  Even though this loop is primarily concerned
     985             :              * with matching expressions, it is a convenient point to check
     986             :              * this for both expressions and ordinary (non-expression)
     987             :              * attributes appearing as inference elements.
     988             :              */
     989        1722 :             if (!infer_collation_opclass_match(elem, idxRel, idxExprs))
     990          48 :                 goto next;
     991             : 
     992             :             /*
     993             :              * Plain Vars don't factor into count of expression elements, and
     994             :              * the question of whether or not they satisfy the index
     995             :              * definition has already been considered (they must).
     996             :              */
     997        1686 :             if (IsA(elem->expr, Var))
     998        1512 :                 continue;
     999             : 
    1000             :             /*
    1001             :              * Might as well avoid redundant check in the rare cases where
    1002             :              * infer_collation_opclass_match() is required to do real work.
    1003             :              * Otherwise, check that element expression appears in cataloged
    1004             :              * index definition.
    1005             :              */
    1006         174 :             if (elem->infercollid != InvalidOid ||
    1007         306 :                 elem->inferopclass != InvalidOid ||
    1008         150 :                 list_member(idxExprs, elem->expr))
    1009         162 :                 continue;
    1010             : 
    1011          12 :             goto next;
    1012             :         }
    1013             : 
    1014             :         /*
    1015             :          * Now that all inference elements were matched, ensure that the
    1016             :          * expression elements from inference clause are not missing any
    1017             :          * cataloged expressions.  This does the right thing when unique
    1018             :          * indexes redundantly repeat the same attribute, or if attributes
    1019             :          * redundantly appear multiple times within an inference clause.
    1020             :          */
    1021        1266 :         if (list_difference(idxExprs, inferElems) != NIL)
    1022          54 :             goto next;
    1023             : 
    1024             :         /*
    1025             :          * If it's a partial index, its predicate must be implied by the ON
    1026             :          * CONFLICT's WHERE clause.
    1027             :          */
    1028        1212 :         predExprs = RelationGetIndexPredicate(idxRel);
    1029        1212 :         if (predExprs && varno != 1)
    1030           6 :             ChangeVarNodes((Node *) predExprs, 1, varno, 0);
    1031             : 
    1032        1212 :         if (!predicate_implied_by(predExprs, (List *) onconflict->arbiterWhere, false))
    1033          36 :             goto next;
    1034             : 
    1035        1176 :         results = lappend_oid(results, idxForm->indexrelid);
    1036        1864 : next:
    1037        1864 :         index_close(idxRel, NoLock);
    1038             :     }
    1039             : 
    1040        1436 :     list_free(indexList);
    1041        1436 :     table_close(relation, NoLock);
    1042             : 
    1043        1436 :     if (results == NIL)
    1044         314 :         ereport(ERROR,
    1045             :                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
    1046             :                  errmsg("there is no unique or exclusion constraint matching the ON CONFLICT specification")));
    1047             : 
    1048        1122 :     return results;
    1049             : }
    1050             : 
    1051             : /*
    1052             :  * infer_collation_opclass_match - ensure infer element opclass/collation match
    1053             :  *
    1054             :  * Given unique index inference element from inference specification, if
    1055             :  * collation was specified, or if opclass was specified, verify that there is
    1056             :  * at least one matching indexed attribute (occasionally, there may be more).
    1057             :  * Skip this in the common case where inference specification does not include
    1058             :  * collation or opclass (instead matching everything, regardless of cataloged
    1059             :  * collation/opclass of indexed attribute).
    1060             :  *
    1061             :  * At least historically, Postgres has not offered collations or opclasses
    1062             :  * with alternative-to-default notions of equality, so these additional
    1063             :  * criteria should only be required infrequently.
    1064             :  *
    1065             :  * Don't give up immediately when an inference element matches some attribute
    1066             :  * cataloged as indexed but not matching additional opclass/collation
    1067             :  * criteria.  This is done so that the implementation is as forgiving as
    1068             :  * possible of redundancy within cataloged index attributes (or, less
    1069             :  * usefully, within inference specification elements).  If collations actually
    1070             :  * differ between apparently redundantly indexed attributes (redundant within
    1071             :  * or across indexes), then there really is no redundancy as such.
    1072             :  *
    1073             :  * Note that if an inference element specifies an opclass and a collation at
    1074             :  * once, both must match in at least one particular attribute within index
    1075             :  * catalog definition in order for that inference element to be considered
    1076             :  * inferred/satisfied.
    1077             :  */
    1078             : static bool
    1079        1722 : infer_collation_opclass_match(InferenceElem *elem, Relation idxRel,
    1080             :                               List *idxExprs)
    1081             : {
    1082             :     AttrNumber  natt;
    1083        1722 :     Oid         inferopfamily = InvalidOid; /* OID of opclass opfamily */
    1084        1722 :     Oid         inferopcinputtype = InvalidOid; /* OID of opclass input type */
    1085        1722 :     int         nplain = 0;     /* # plain attrs observed */
    1086             : 
    1087             :     /*
    1088             :      * If inference specification element lacks collation/opclass, then no
    1089             :      * need to check for exact match.
    1090             :      */
    1091        1722 :     if (elem->infercollid == InvalidOid && elem->inferopclass == InvalidOid)
    1092        1608 :         return true;
    1093             : 
    1094             :     /*
    1095             :      * Lookup opfamily and input type, for matching indexes
    1096             :      */
    1097         114 :     if (elem->inferopclass)
    1098             :     {
    1099          84 :         inferopfamily = get_opclass_family(elem->inferopclass);
    1100          84 :         inferopcinputtype = get_opclass_input_type(elem->inferopclass);
    1101             :     }
    1102             : 
    1103         246 :     for (natt = 1; natt <= idxRel->rd_att->natts; natt++)
    1104             :     {
    1105         210 :         Oid         opfamily = idxRel->rd_opfamily[natt - 1];
    1106         210 :         Oid         opcinputtype = idxRel->rd_opcintype[natt - 1];
    1107         210 :         Oid         collation = idxRel->rd_indcollation[natt - 1];
    1108         210 :         int         attno = idxRel->rd_index->indkey.values[natt - 1];
    1109             : 
    1110         210 :         if (attno != 0)
    1111         168 :             nplain++;
    1112             : 
    1113         210 :         if (elem->inferopclass != InvalidOid &&
    1114          66 :             (inferopfamily != opfamily || inferopcinputtype != opcinputtype))
    1115             :         {
    1116             :             /* Attribute needed to match opclass, but didn't */
    1117          90 :             continue;
    1118             :         }
    1119             : 
    1120         120 :         if (elem->infercollid != InvalidOid &&
    1121          84 :             elem->infercollid != collation)
    1122             :         {
    1123             :             /* Attribute needed to match collation, but didn't */
    1124          36 :             continue;
    1125             :         }
    1126             : 
    1127             :         /* If one matching index att found, good enough -- return true */
    1128          84 :         if (IsA(elem->expr, Var))
    1129             :         {
    1130          54 :             if (((Var *) elem->expr)->varattno == attno)
    1131          54 :                 return true;
    1132             :         }
    1133          30 :         else if (attno == 0)
    1134             :         {
    1135          30 :             Node       *nattExpr = list_nth(idxExprs, (natt - 1) - nplain);
    1136             : 
    1137             :             /*
    1138             :              * Note that unlike routines like match_index_to_operand() we
    1139             :              * don't need to care about RelabelType.  Neither the index
    1140             :              * definition nor the inference clause should contain them.
    1141             :              */
    1142          30 :             if (equal(elem->expr, nattExpr))
    1143          24 :                 return true;
    1144             :         }
    1145             :     }
    1146             : 
    1147          36 :     return false;
    1148             : }
    1149             : 
    1150             : /*
    1151             :  * estimate_rel_size - estimate # pages and # tuples in a table or index
    1152             :  *
    1153             :  * We also estimate the fraction of the pages that are marked all-visible in
    1154             :  * the visibility map, for use in estimation of index-only scans.
    1155             :  *
    1156             :  * If attr_widths isn't NULL, it points to the zero-index entry of the
    1157             :  * relation's attr_widths[] cache; we fill this in if we have need to compute
    1158             :  * the attribute widths for estimation purposes.
    1159             :  */
    1160             : void
    1161      455110 : estimate_rel_size(Relation rel, int32 *attr_widths,
    1162             :                   BlockNumber *pages, double *tuples, double *allvisfrac)
    1163             : {
    1164             :     BlockNumber curpages;
    1165             :     BlockNumber relpages;
    1166             :     double      reltuples;
    1167             :     BlockNumber relallvisible;
    1168             :     double      density;
    1169             : 
    1170      455110 :     if (RELKIND_HAS_TABLE_AM(rel->rd_rel->relkind))
    1171             :     {
    1172      451554 :         table_relation_estimate_size(rel, attr_widths, pages, tuples,
    1173             :                                      allvisfrac);
    1174             :     }
    1175        3556 :     else if (rel->rd_rel->relkind == RELKIND_INDEX)
    1176             :     {
    1177             :         /*
    1178             :          * XXX: It'd probably be good to move this into a callback, individual
    1179             :          * index types e.g. know if they have a metapage.
    1180             :          */
    1181             : 
    1182             :         /* it has storage, ok to call the smgr */
    1183         984 :         curpages = RelationGetNumberOfBlocks(rel);
    1184             : 
    1185             :         /* report estimated # pages */
    1186         984 :         *pages = curpages;
    1187             :         /* quick exit if rel is clearly empty */
    1188         984 :         if (curpages == 0)
    1189             :         {
    1190           0 :             *tuples = 0;
    1191           0 :             *allvisfrac = 0;
    1192           0 :             return;
    1193             :         }
    1194             : 
    1195             :         /* coerce values in pg_class to more desirable types */
    1196         984 :         relpages = (BlockNumber) rel->rd_rel->relpages;
    1197         984 :         reltuples = (double) rel->rd_rel->reltuples;
    1198         984 :         relallvisible = (BlockNumber) rel->rd_rel->relallvisible;
    1199             : 
    1200             :         /*
    1201             :          * Discount the metapage while estimating the number of tuples. This
    1202             :          * is a kluge because it assumes more than it ought to about index
    1203             :          * structure.  Currently it's OK for btree, hash, and GIN indexes but
    1204             :          * suspect for GiST indexes.
    1205             :          */
    1206         984 :         if (relpages > 0)
    1207             :         {
    1208         966 :             curpages--;
    1209         966 :             relpages--;
    1210             :         }
    1211             : 
    1212             :         /* estimate number of tuples from previous tuple density */
    1213         984 :         if (reltuples >= 0 && relpages > 0)
    1214         666 :             density = reltuples / (double) relpages;
    1215             :         else
    1216             :         {
    1217             :             /*
    1218             :              * If we have no data because the relation was never vacuumed,
    1219             :              * estimate tuple width from attribute datatypes.  We assume here
    1220             :              * that the pages are completely full, which is OK for tables
    1221             :              * (since they've presumably not been VACUUMed yet) but is
    1222             :              * probably an overestimate for indexes.  Fortunately
    1223             :              * get_relation_info() can clamp the overestimate to the parent
    1224             :              * table's size.
    1225             :              *
    1226             :              * Note: this code intentionally disregards alignment
    1227             :              * considerations, because (a) that would be gilding the lily
    1228             :              * considering how crude the estimate is, and (b) it creates
    1229             :              * platform dependencies in the default plans which are kind of a
    1230             :              * headache for regression testing.
    1231             :              *
    1232             :              * XXX: Should this logic be more index specific?
    1233             :              */
    1234             :             int32       tuple_width;
    1235             : 
    1236         318 :             tuple_width = get_rel_data_width(rel, attr_widths);
    1237         318 :             tuple_width += MAXALIGN(SizeofHeapTupleHeader);
    1238         318 :             tuple_width += sizeof(ItemIdData);
    1239             :             /* note: integer division is intentional here */
    1240         318 :             density = (BLCKSZ - SizeOfPageHeaderData) / tuple_width;
    1241             :         }
    1242         984 :         *tuples = rint(density * (double) curpages);
    1243             : 
    1244             :         /*
    1245             :          * We use relallvisible as-is, rather than scaling it up like we do
    1246             :          * for the pages and tuples counts, on the theory that any pages added
    1247             :          * since the last VACUUM are most likely not marked all-visible.  But
    1248             :          * costsize.c wants it converted to a fraction.
    1249             :          */
    1250         984 :         if (relallvisible == 0 || curpages <= 0)
    1251         984 :             *allvisfrac = 0;
    1252           0 :         else if ((double) relallvisible >= curpages)
    1253           0 :             *allvisfrac = 1;
    1254             :         else
    1255           0 :             *allvisfrac = (double) relallvisible / curpages;
    1256             :     }
    1257             :     else
    1258             :     {
    1259             :         /*
    1260             :          * Just use whatever's in pg_class.  This covers foreign tables,
    1261             :          * sequences, and also relkinds without storage (shouldn't get here?);
    1262             :          * see initializations in AddNewRelationTuple().  Note that FDW must
    1263             :          * cope if reltuples is -1!
    1264             :          */
    1265        2572 :         *pages = rel->rd_rel->relpages;
    1266        2572 :         *tuples = rel->rd_rel->reltuples;
    1267        2572 :         *allvisfrac = 0;
    1268             :     }
    1269             : }
    1270             : 
    1271             : 
    1272             : /*
    1273             :  * get_rel_data_width
    1274             :  *
    1275             :  * Estimate the average width of (the data part of) the relation's tuples.
    1276             :  *
    1277             :  * If attr_widths isn't NULL, it points to the zero-index entry of the
    1278             :  * relation's attr_widths[] cache; use and update that cache as appropriate.
    1279             :  *
    1280             :  * Currently we ignore dropped columns.  Ideally those should be included
    1281             :  * in the result, but we haven't got any way to get info about them; and
    1282             :  * since they might be mostly NULLs, treating them as zero-width is not
    1283             :  * necessarily the wrong thing anyway.
    1284             :  */
    1285             : int32
    1286      151828 : get_rel_data_width(Relation rel, int32 *attr_widths)
    1287             : {
    1288      151828 :     int64       tuple_width = 0;
    1289             :     int         i;
    1290             : 
    1291      833426 :     for (i = 1; i <= RelationGetNumberOfAttributes(rel); i++)
    1292             :     {
    1293      681598 :         Form_pg_attribute att = TupleDescAttr(rel->rd_att, i - 1);
    1294             :         int32       item_width;
    1295             : 
    1296      681598 :         if (att->attisdropped)
    1297        2672 :             continue;
    1298             : 
    1299             :         /* use previously cached data, if any */
    1300      678926 :         if (attr_widths != NULL && attr_widths[i] > 0)
    1301             :         {
    1302        5852 :             tuple_width += attr_widths[i];
    1303        5852 :             continue;
    1304             :         }
    1305             : 
    1306             :         /* This should match set_rel_width() in costsize.c */
    1307      673074 :         item_width = get_attavgwidth(RelationGetRelid(rel), i);
    1308      673074 :         if (item_width <= 0)
    1309             :         {
    1310      671226 :             item_width = get_typavgwidth(att->atttypid, att->atttypmod);
    1311             :             Assert(item_width > 0);
    1312             :         }
    1313      673074 :         if (attr_widths != NULL)
    1314      598158 :             attr_widths[i] = item_width;
    1315      673074 :         tuple_width += item_width;
    1316             :     }
    1317             : 
    1318      151828 :     return clamp_width_est(tuple_width);
    1319             : }
    1320             : 
    1321             : /*
    1322             :  * get_relation_data_width
    1323             :  *
    1324             :  * External API for get_rel_data_width: same behavior except we have to
    1325             :  * open the relcache entry.
    1326             :  */
    1327             : int32
    1328        2556 : get_relation_data_width(Oid relid, int32 *attr_widths)
    1329             : {
    1330             :     int32       result;
    1331             :     Relation    relation;
    1332             : 
    1333             :     /* As above, assume relation is already locked */
    1334        2556 :     relation = table_open(relid, NoLock);
    1335             : 
    1336        2556 :     result = get_rel_data_width(relation, attr_widths);
    1337             : 
    1338        2556 :     table_close(relation, NoLock);
    1339             : 
    1340        2556 :     return result;
    1341             : }
    1342             : 
    1343             : 
    1344             : /*
    1345             :  * get_relation_constraints
    1346             :  *
    1347             :  * Retrieve the applicable constraint expressions of the given relation.
    1348             :  * Only constraints that have been validated are considered.
    1349             :  *
    1350             :  * Returns a List (possibly empty) of constraint expressions.  Each one
    1351             :  * has been canonicalized, and its Vars are changed to have the varno
    1352             :  * indicated by rel->relid.  This allows the expressions to be easily
    1353             :  * compared to expressions taken from WHERE.
    1354             :  *
    1355             :  * If include_noinherit is true, it's okay to include constraints that
    1356             :  * are marked NO INHERIT.
    1357             :  *
    1358             :  * If include_notnull is true, "col IS NOT NULL" expressions are generated
    1359             :  * and added to the result for each column that's marked attnotnull.
    1360             :  *
    1361             :  * If include_partition is true, and the relation is a partition,
    1362             :  * also include the partitioning constraints.
    1363             :  *
    1364             :  * Note: at present this is invoked at most once per relation per planner
    1365             :  * run, and in many cases it won't be invoked at all, so there seems no
    1366             :  * point in caching the data in RelOptInfo.
    1367             :  */
    1368             : static List *
    1369       21366 : get_relation_constraints(PlannerInfo *root,
    1370             :                          Oid relationObjectId, RelOptInfo *rel,
    1371             :                          bool include_noinherit,
    1372             :                          bool include_notnull,
    1373             :                          bool include_partition)
    1374             : {
    1375       21366 :     List       *result = NIL;
    1376       21366 :     Index       varno = rel->relid;
    1377             :     Relation    relation;
    1378             :     TupleConstr *constr;
    1379             : 
    1380             :     /*
    1381             :      * We assume the relation has already been safely locked.
    1382             :      */
    1383       21366 :     relation = table_open(relationObjectId, NoLock);
    1384             : 
    1385       21366 :     constr = relation->rd_att->constr;
    1386       21366 :     if (constr != NULL)
    1387             :     {
    1388        8068 :         int         num_check = constr->num_check;
    1389             :         int         i;
    1390             : 
    1391        8634 :         for (i = 0; i < num_check; i++)
    1392             :         {
    1393             :             Node       *cexpr;
    1394             : 
    1395             :             /*
    1396             :              * If this constraint hasn't been fully validated yet, we must
    1397             :              * ignore it here.
    1398             :              */
    1399         566 :             if (!constr->check[i].ccvalid)
    1400          54 :                 continue;
    1401             : 
    1402             :             /*
    1403             :              * NOT ENFORCED constraints are always marked as invalid, which
    1404             :              * should have been ignored.
    1405             :              */
    1406             :             Assert(constr->check[i].ccenforced);
    1407             : 
    1408             :             /*
    1409             :              * Also ignore if NO INHERIT and we weren't told that that's safe.
    1410             :              */
    1411         512 :             if (constr->check[i].ccnoinherit && !include_noinherit)
    1412           0 :                 continue;
    1413             : 
    1414         512 :             cexpr = stringToNode(constr->check[i].ccbin);
    1415             : 
    1416             :             /*
    1417             :              * Fix Vars to have the desired varno.  This must be done before
    1418             :              * const-simplification because eval_const_expressions reduces
    1419             :              * NullTest for Vars based on varno.
    1420             :              */
    1421         512 :             if (varno != 1)
    1422         488 :                 ChangeVarNodes(cexpr, 1, varno, 0);
    1423             : 
    1424             :             /*
    1425             :              * Run each expression through const-simplification and
    1426             :              * canonicalization.  This is not just an optimization, but is
    1427             :              * necessary, because we will be comparing it to
    1428             :              * similarly-processed qual clauses, and may fail to detect valid
    1429             :              * matches without this.  This must match the processing done to
    1430             :              * qual clauses in preprocess_expression()!  (We can skip the
    1431             :              * stuff involving subqueries, however, since we don't allow any
    1432             :              * in check constraints.)
    1433             :              */
    1434         512 :             cexpr = eval_const_expressions(root, cexpr);
    1435             : 
    1436         512 :             cexpr = (Node *) canonicalize_qual((Expr *) cexpr, true);
    1437             : 
    1438             :             /*
    1439             :              * Finally, convert to implicit-AND format (that is, a List) and
    1440             :              * append the resulting item(s) to our output list.
    1441             :              */
    1442         512 :             result = list_concat(result,
    1443         512 :                                  make_ands_implicit((Expr *) cexpr));
    1444             :         }
    1445             : 
    1446             :         /* Add NOT NULL constraints in expression form, if requested */
    1447        8068 :         if (include_notnull && constr->has_not_null)
    1448             :         {
    1449        7638 :             int         natts = relation->rd_att->natts;
    1450             : 
    1451       31116 :             for (i = 1; i <= natts; i++)
    1452             :             {
    1453       23478 :                 CompactAttribute *att = TupleDescCompactAttr(relation->rd_att, i - 1);
    1454             : 
    1455       23478 :                 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
    1456             :                 {
    1457        9392 :                     Form_pg_attribute wholeatt = TupleDescAttr(relation->rd_att, i - 1);
    1458        9392 :                     NullTest   *ntest = makeNode(NullTest);
    1459             : 
    1460        9392 :                     ntest->arg = (Expr *) makeVar(varno,
    1461             :                                                   i,
    1462             :                                                   wholeatt->atttypid,
    1463             :                                                   wholeatt->atttypmod,
    1464             :                                                   wholeatt->attcollation,
    1465             :                                                   0);
    1466        9392 :                     ntest->nulltesttype = IS_NOT_NULL;
    1467             : 
    1468             :                     /*
    1469             :                      * argisrow=false is correct even for a composite column,
    1470             :                      * because attnotnull does not represent a SQL-spec IS NOT
    1471             :                      * NULL test in such a case, just IS DISTINCT FROM NULL.
    1472             :                      */
    1473        9392 :                     ntest->argisrow = false;
    1474        9392 :                     ntest->location = -1;
    1475        9392 :                     result = lappend(result, ntest);
    1476             :                 }
    1477             :             }
    1478             :         }
    1479             :     }
    1480             : 
    1481             :     /*
    1482             :      * Add partitioning constraints, if requested.
    1483             :      */
    1484       21366 :     if (include_partition && relation->rd_rel->relispartition)
    1485             :     {
    1486             :         /* make sure rel->partition_qual is set */
    1487          12 :         set_baserel_partition_constraint(relation, rel);
    1488          12 :         result = list_concat(result, rel->partition_qual);
    1489             :     }
    1490             : 
    1491             :     /*
    1492             :      * Expand virtual generated columns in the constraint expressions.
    1493             :      */
    1494       21366 :     if (result)
    1495        7806 :         result = (List *) expand_generated_columns_in_expr((Node *) result,
    1496             :                                                            relation,
    1497             :                                                            varno);
    1498             : 
    1499       21366 :     table_close(relation, NoLock);
    1500             : 
    1501       21366 :     return result;
    1502             : }
    1503             : 
    1504             : /*
    1505             :  * Try loading data for the statistics object.
    1506             :  *
    1507             :  * We don't know if the data (specified by statOid and inh value) exist.
    1508             :  * The result is stored in stainfos list.
    1509             :  */
    1510             : static void
    1511        4012 : get_relation_statistics_worker(List **stainfos, RelOptInfo *rel,
    1512             :                                Oid statOid, bool inh,
    1513             :                                Bitmapset *keys, List *exprs)
    1514             : {
    1515             :     Form_pg_statistic_ext_data dataForm;
    1516             :     HeapTuple   dtup;
    1517             : 
    1518        4012 :     dtup = SearchSysCache2(STATEXTDATASTXOID,
    1519             :                            ObjectIdGetDatum(statOid), BoolGetDatum(inh));
    1520        4012 :     if (!HeapTupleIsValid(dtup))
    1521        2008 :         return;
    1522             : 
    1523        2004 :     dataForm = (Form_pg_statistic_ext_data) GETSTRUCT(dtup);
    1524             : 
    1525             :     /* add one StatisticExtInfo for each kind built */
    1526        2004 :     if (statext_is_kind_built(dtup, STATS_EXT_NDISTINCT))
    1527             :     {
    1528         714 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
    1529             : 
    1530         714 :         info->statOid = statOid;
    1531         714 :         info->inherit = dataForm->stxdinherit;
    1532         714 :         info->rel = rel;
    1533         714 :         info->kind = STATS_EXT_NDISTINCT;
    1534         714 :         info->keys = bms_copy(keys);
    1535         714 :         info->exprs = exprs;
    1536             : 
    1537         714 :         *stainfos = lappend(*stainfos, info);
    1538             :     }
    1539             : 
    1540        2004 :     if (statext_is_kind_built(dtup, STATS_EXT_DEPENDENCIES))
    1541             :     {
    1542         528 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
    1543             : 
    1544         528 :         info->statOid = statOid;
    1545         528 :         info->inherit = dataForm->stxdinherit;
    1546         528 :         info->rel = rel;
    1547         528 :         info->kind = STATS_EXT_DEPENDENCIES;
    1548         528 :         info->keys = bms_copy(keys);
    1549         528 :         info->exprs = exprs;
    1550             : 
    1551         528 :         *stainfos = lappend(*stainfos, info);
    1552             :     }
    1553             : 
    1554        2004 :     if (statext_is_kind_built(dtup, STATS_EXT_MCV))
    1555             :     {
    1556         882 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
    1557             : 
    1558         882 :         info->statOid = statOid;
    1559         882 :         info->inherit = dataForm->stxdinherit;
    1560         882 :         info->rel = rel;
    1561         882 :         info->kind = STATS_EXT_MCV;
    1562         882 :         info->keys = bms_copy(keys);
    1563         882 :         info->exprs = exprs;
    1564             : 
    1565         882 :         *stainfos = lappend(*stainfos, info);
    1566             :     }
    1567             : 
    1568        2004 :     if (statext_is_kind_built(dtup, STATS_EXT_EXPRESSIONS))
    1569             :     {
    1570         810 :         StatisticExtInfo *info = makeNode(StatisticExtInfo);
    1571             : 
    1572         810 :         info->statOid = statOid;
    1573         810 :         info->inherit = dataForm->stxdinherit;
    1574         810 :         info->rel = rel;
    1575         810 :         info->kind = STATS_EXT_EXPRESSIONS;
    1576         810 :         info->keys = bms_copy(keys);
    1577         810 :         info->exprs = exprs;
    1578             : 
    1579         810 :         *stainfos = lappend(*stainfos, info);
    1580             :     }
    1581             : 
    1582        2004 :     ReleaseSysCache(dtup);
    1583             : }
    1584             : 
    1585             : /*
    1586             :  * get_relation_statistics
    1587             :  *      Retrieve extended statistics defined on the table.
    1588             :  *
    1589             :  * Returns a List (possibly empty) of StatisticExtInfo objects describing
    1590             :  * the statistics.  Note that this doesn't load the actual statistics data,
    1591             :  * just the identifying metadata.  Only stats actually built are considered.
    1592             :  */
    1593             : static List *
    1594      476456 : get_relation_statistics(PlannerInfo *root, RelOptInfo *rel,
    1595             :                         Relation relation)
    1596             : {
    1597      476456 :     Index       varno = rel->relid;
    1598             :     List       *statoidlist;
    1599      476456 :     List       *stainfos = NIL;
    1600             :     ListCell   *l;
    1601             : 
    1602      476456 :     statoidlist = RelationGetStatExtList(relation);
    1603             : 
    1604      478462 :     foreach(l, statoidlist)
    1605             :     {
    1606        2006 :         Oid         statOid = lfirst_oid(l);
    1607             :         Form_pg_statistic_ext staForm;
    1608             :         HeapTuple   htup;
    1609        2006 :         Bitmapset  *keys = NULL;
    1610        2006 :         List       *exprs = NIL;
    1611             :         int         i;
    1612             : 
    1613        2006 :         htup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statOid));
    1614        2006 :         if (!HeapTupleIsValid(htup))
    1615           0 :             elog(ERROR, "cache lookup failed for statistics object %u", statOid);
    1616        2006 :         staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
    1617             : 
    1618             :         /*
    1619             :          * First, build the array of columns covered.  This is ultimately
    1620             :          * wasted if no stats within the object have actually been built, but
    1621             :          * it doesn't seem worth troubling over that case.
    1622             :          */
    1623        5698 :         for (i = 0; i < staForm->stxkeys.dim1; i++)
    1624        3692 :             keys = bms_add_member(keys, staForm->stxkeys.values[i]);
    1625             : 
    1626             :         /*
    1627             :          * Preprocess expressions (if any). We read the expressions, fix the
    1628             :          * varnos, and run them through eval_const_expressions.
    1629             :          *
    1630             :          * XXX We don't know yet if there are any data for this stats object,
    1631             :          * with either stxdinherit value. But it's reasonable to assume there
    1632             :          * is at least one of those, possibly both. So it's better to process
    1633             :          * keys and expressions here.
    1634             :          */
    1635             :         {
    1636             :             bool        isnull;
    1637             :             Datum       datum;
    1638             : 
    1639             :             /* decode expression (if any) */
    1640        2006 :             datum = SysCacheGetAttr(STATEXTOID, htup,
    1641             :                                     Anum_pg_statistic_ext_stxexprs, &isnull);
    1642             : 
    1643        2006 :             if (!isnull)
    1644             :             {
    1645             :                 char       *exprsString;
    1646             : 
    1647         814 :                 exprsString = TextDatumGetCString(datum);
    1648         814 :                 exprs = (List *) stringToNode(exprsString);
    1649         814 :                 pfree(exprsString);
    1650             : 
    1651             :                 /*
    1652             :                  * Modify the copies we obtain from the relcache to have the
    1653             :                  * correct varno for the parent relation, so that they match
    1654             :                  * up correctly against qual clauses.
    1655             :                  *
    1656             :                  * This must be done before const-simplification because
    1657             :                  * eval_const_expressions reduces NullTest for Vars based on
    1658             :                  * varno.
    1659             :                  */
    1660         814 :                 if (varno != 1)
    1661           0 :                     ChangeVarNodes((Node *) exprs, 1, varno, 0);
    1662             : 
    1663             :                 /*
    1664             :                  * Run the expressions through eval_const_expressions. This is
    1665             :                  * not just an optimization, but is necessary, because the
    1666             :                  * planner will be comparing them to similarly-processed qual
    1667             :                  * clauses, and may fail to detect valid matches without this.
    1668             :                  * We must not use canonicalize_qual, however, since these
    1669             :                  * aren't qual expressions.
    1670             :                  */
    1671         814 :                 exprs = (List *) eval_const_expressions(root, (Node *) exprs);
    1672             : 
    1673             :                 /* May as well fix opfuncids too */
    1674         814 :                 fix_opfuncids((Node *) exprs);
    1675             :             }
    1676             :         }
    1677             : 
    1678             :         /* extract statistics for possible values of stxdinherit flag */
    1679             : 
    1680        2006 :         get_relation_statistics_worker(&stainfos, rel, statOid, true, keys, exprs);
    1681             : 
    1682        2006 :         get_relation_statistics_worker(&stainfos, rel, statOid, false, keys, exprs);
    1683             : 
    1684        2006 :         ReleaseSysCache(htup);
    1685        2006 :         bms_free(keys);
    1686             :     }
    1687             : 
    1688      476456 :     list_free(statoidlist);
    1689             : 
    1690      476456 :     return stainfos;
    1691             : }
    1692             : 
    1693             : /*
    1694             :  * relation_excluded_by_constraints
    1695             :  *
    1696             :  * Detect whether the relation need not be scanned because it has either
    1697             :  * self-inconsistent restrictions, or restrictions inconsistent with the
    1698             :  * relation's applicable constraints.
    1699             :  *
    1700             :  * Note: this examines only rel->relid, rel->reloptkind, and
    1701             :  * rel->baserestrictinfo; therefore it can be called before filling in
    1702             :  * other fields of the RelOptInfo.
    1703             :  */
    1704             : bool
    1705      523130 : relation_excluded_by_constraints(PlannerInfo *root,
    1706             :                                  RelOptInfo *rel, RangeTblEntry *rte)
    1707             : {
    1708             :     bool        include_noinherit;
    1709             :     bool        include_notnull;
    1710      523130 :     bool        include_partition = false;
    1711             :     List       *safe_restrictions;
    1712             :     List       *constraint_pred;
    1713             :     List       *safe_constraints;
    1714             :     ListCell   *lc;
    1715             : 
    1716             :     /* As of now, constraint exclusion works only with simple relations. */
    1717             :     Assert(IS_SIMPLE_REL(rel));
    1718             : 
    1719             :     /*
    1720             :      * If there are no base restriction clauses, we have no hope of proving
    1721             :      * anything below, so fall out quickly.
    1722             :      */
    1723      523130 :     if (rel->baserestrictinfo == NIL)
    1724      239834 :         return false;
    1725             : 
    1726             :     /*
    1727             :      * Regardless of the setting of constraint_exclusion, detect
    1728             :      * constant-FALSE-or-NULL restriction clauses.  Although const-folding
    1729             :      * will reduce "anything AND FALSE" to just "FALSE", the baserestrictinfo
    1730             :      * list can still have other members besides the FALSE constant, due to
    1731             :      * qual pushdown and other mechanisms; so check them all.  This doesn't
    1732             :      * fire very often, but it seems cheap enough to be worth doing anyway.
    1733             :      * (Without this, we'd miss some optimizations that 9.5 and earlier found
    1734             :      * via much more roundabout methods.)
    1735             :      */
    1736      707004 :     foreach(lc, rel->baserestrictinfo)
    1737             :     {
    1738      424288 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
    1739      424288 :         Expr       *clause = rinfo->clause;
    1740             : 
    1741      424288 :         if (clause && IsA(clause, Const) &&
    1742         580 :             (((Const *) clause)->constisnull ||
    1743         574 :              !DatumGetBool(((Const *) clause)->constvalue)))
    1744         580 :             return true;
    1745             :     }
    1746             : 
    1747             :     /*
    1748             :      * Skip further tests, depending on constraint_exclusion.
    1749             :      */
    1750      282716 :     switch (constraint_exclusion)
    1751             :     {
    1752          54 :         case CONSTRAINT_EXCLUSION_OFF:
    1753             :             /* In 'off' mode, never make any further tests */
    1754          54 :             return false;
    1755             : 
    1756      282518 :         case CONSTRAINT_EXCLUSION_PARTITION:
    1757             : 
    1758             :             /*
    1759             :              * When constraint_exclusion is set to 'partition' we only handle
    1760             :              * appendrel members.  Partition pruning has already been applied,
    1761             :              * so there is no need to consider the rel's partition constraints
    1762             :              * here.
    1763             :              */
    1764      282518 :             if (rel->reloptkind == RELOPT_OTHER_MEMBER_REL)
    1765       21580 :                 break;          /* appendrel member, so process it */
    1766      260938 :             return false;
    1767             : 
    1768         144 :         case CONSTRAINT_EXCLUSION_ON:
    1769             : 
    1770             :             /*
    1771             :              * In 'on' mode, always apply constraint exclusion.  If we are
    1772             :              * considering a baserel that is a partition (i.e., it was
    1773             :              * directly named rather than expanded from a parent table), then
    1774             :              * its partition constraints haven't been considered yet, so
    1775             :              * include them in the processing here.
    1776             :              */
    1777         144 :             if (rel->reloptkind == RELOPT_BASEREL)
    1778         114 :                 include_partition = true;
    1779         144 :             break;              /* always try to exclude */
    1780             :     }
    1781             : 
    1782             :     /*
    1783             :      * Check for self-contradictory restriction clauses.  We dare not make
    1784             :      * deductions with non-immutable functions, but any immutable clauses that
    1785             :      * are self-contradictory allow us to conclude the scan is unnecessary.
    1786             :      *
    1787             :      * Note: strip off RestrictInfo because predicate_refuted_by() isn't
    1788             :      * expecting to see any in its predicate argument.
    1789             :      */
    1790       21724 :     safe_restrictions = NIL;
    1791       51258 :     foreach(lc, rel->baserestrictinfo)
    1792             :     {
    1793       29534 :         RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
    1794             : 
    1795       29534 :         if (!contain_mutable_functions((Node *) rinfo->clause))
    1796       27994 :             safe_restrictions = lappend(safe_restrictions, rinfo->clause);
    1797             :     }
    1798             : 
    1799             :     /*
    1800             :      * We can use weak refutation here, since we're comparing restriction
    1801             :      * clauses with restriction clauses.
    1802             :      */
    1803       21724 :     if (predicate_refuted_by(safe_restrictions, safe_restrictions, true))
    1804          72 :         return true;
    1805             : 
    1806             :     /*
    1807             :      * Only plain relations have constraints, so stop here for other rtekinds.
    1808             :      */
    1809       21652 :     if (rte->rtekind != RTE_RELATION)
    1810         286 :         return false;
    1811             : 
    1812             :     /*
    1813             :      * If we are scanning just this table, we can use NO INHERIT constraints,
    1814             :      * but not if we're scanning its children too.  (Note that partitioned
    1815             :      * tables should never have NO INHERIT constraints; but it's not necessary
    1816             :      * for us to assume that here.)
    1817             :      */
    1818       21366 :     include_noinherit = !rte->inh;
    1819             : 
    1820             :     /*
    1821             :      * Currently, attnotnull constraints must be treated as NO INHERIT unless
    1822             :      * this is a partitioned table.  In future we might track their
    1823             :      * inheritance status more accurately, allowing this to be refined.
    1824             :      *
    1825             :      * XXX do we need/want to change this?
    1826             :      */
    1827       21366 :     include_notnull = (!rte->inh || rte->relkind == RELKIND_PARTITIONED_TABLE);
    1828             : 
    1829             :     /*
    1830             :      * Fetch the appropriate set of constraint expressions.
    1831             :      */
    1832       21366 :     constraint_pred = get_relation_constraints(root, rte->relid, rel,
    1833             :                                                include_noinherit,
    1834             :                                                include_notnull,
    1835             :                                                include_partition);
    1836             : 
    1837             :     /*
    1838             :      * We do not currently enforce that CHECK constraints contain only
    1839             :      * immutable functions, so it's necessary to check here. We daren't draw
    1840             :      * conclusions from plan-time evaluation of non-immutable functions. Since
    1841             :      * they're ANDed, we can just ignore any mutable constraints in the list,
    1842             :      * and reason about the rest.
    1843             :      */
    1844       21366 :     safe_constraints = NIL;
    1845       31450 :     foreach(lc, constraint_pred)
    1846             :     {
    1847       10084 :         Node       *pred = (Node *) lfirst(lc);
    1848             : 
    1849       10084 :         if (!contain_mutable_functions(pred))
    1850       10084 :             safe_constraints = lappend(safe_constraints, pred);
    1851             :     }
    1852             : 
    1853             :     /*
    1854             :      * The constraints are effectively ANDed together, so we can just try to
    1855             :      * refute the entire collection at once.  This may allow us to make proofs
    1856             :      * that would fail if we took them individually.
    1857             :      *
    1858             :      * Note: we use rel->baserestrictinfo, not safe_restrictions as might seem
    1859             :      * an obvious optimization.  Some of the clauses might be OR clauses that
    1860             :      * have volatile and nonvolatile subclauses, and it's OK to make
    1861             :      * deductions with the nonvolatile parts.
    1862             :      *
    1863             :      * We need strong refutation because we have to prove that the constraints
    1864             :      * would yield false, not just NULL.
    1865             :      */
    1866       21366 :     if (predicate_refuted_by(safe_constraints, rel->baserestrictinfo, false))
    1867         192 :         return true;
    1868             : 
    1869       21174 :     return false;
    1870             : }
    1871             : 
    1872             : 
    1873             : /*
    1874             :  * build_physical_tlist
    1875             :  *
    1876             :  * Build a targetlist consisting of exactly the relation's user attributes,
    1877             :  * in order.  The executor can special-case such tlists to avoid a projection
    1878             :  * step at runtime, so we use such tlists preferentially for scan nodes.
    1879             :  *
    1880             :  * Exception: if there are any dropped or missing columns, we punt and return
    1881             :  * NIL.  Ideally we would like to handle these cases too.  However this
    1882             :  * creates problems for ExecTypeFromTL, which may be asked to build a tupdesc
    1883             :  * for a tlist that includes vars of no-longer-existent types.  In theory we
    1884             :  * could dig out the required info from the pg_attribute entries of the
    1885             :  * relation, but that data is not readily available to ExecTypeFromTL.
    1886             :  * For now, we don't apply the physical-tlist optimization when there are
    1887             :  * dropped cols.
    1888             :  *
    1889             :  * We also support building a "physical" tlist for subqueries, functions,
    1890             :  * values lists, table expressions, and CTEs, since the same optimization can
    1891             :  * occur in SubqueryScan, FunctionScan, ValuesScan, CteScan, TableFunc,
    1892             :  * NamedTuplestoreScan, and WorkTableScan nodes.
    1893             :  */
    1894             : List *
    1895      188216 : build_physical_tlist(PlannerInfo *root, RelOptInfo *rel)
    1896             : {
    1897      188216 :     List       *tlist = NIL;
    1898      188216 :     Index       varno = rel->relid;
    1899      188216 :     RangeTblEntry *rte = planner_rt_fetch(varno, root);
    1900             :     Relation    relation;
    1901             :     Query      *subquery;
    1902             :     Var        *var;
    1903             :     ListCell   *l;
    1904             :     int         attrno,
    1905             :                 numattrs;
    1906             :     List       *colvars;
    1907             : 
    1908      188216 :     switch (rte->rtekind)
    1909             :     {
    1910      161308 :         case RTE_RELATION:
    1911             :             /* Assume we already have adequate lock */
    1912      161308 :             relation = table_open(rte->relid, NoLock);
    1913             : 
    1914      161308 :             numattrs = RelationGetNumberOfAttributes(relation);
    1915     2862220 :             for (attrno = 1; attrno <= numattrs; attrno++)
    1916             :             {
    1917     2701050 :                 Form_pg_attribute att_tup = TupleDescAttr(relation->rd_att,
    1918             :                                                           attrno - 1);
    1919             : 
    1920     2701050 :                 if (att_tup->attisdropped || att_tup->atthasmissing)
    1921             :                 {
    1922             :                     /* found a dropped or missing col, so punt */
    1923         138 :                     tlist = NIL;
    1924         138 :                     break;
    1925             :                 }
    1926             : 
    1927     2700912 :                 var = makeVar(varno,
    1928             :                               attrno,
    1929             :                               att_tup->atttypid,
    1930             :                               att_tup->atttypmod,
    1931             :                               att_tup->attcollation,
    1932             :                               0);
    1933             : 
    1934     2700912 :                 tlist = lappend(tlist,
    1935     2700912 :                                 makeTargetEntry((Expr *) var,
    1936             :                                                 attrno,
    1937             :                                                 NULL,
    1938             :                                                 false));
    1939             :             }
    1940             : 
    1941      161308 :             table_close(relation, NoLock);
    1942      161308 :             break;
    1943             : 
    1944        2362 :         case RTE_SUBQUERY:
    1945        2362 :             subquery = rte->subquery;
    1946        8826 :             foreach(l, subquery->targetList)
    1947             :             {
    1948        6464 :                 TargetEntry *tle = (TargetEntry *) lfirst(l);
    1949             : 
    1950             :                 /*
    1951             :                  * A resjunk column of the subquery can be reflected as
    1952             :                  * resjunk in the physical tlist; we need not punt.
    1953             :                  */
    1954        6464 :                 var = makeVarFromTargetEntry(varno, tle);
    1955             : 
    1956        6464 :                 tlist = lappend(tlist,
    1957        6464 :                                 makeTargetEntry((Expr *) var,
    1958        6464 :                                                 tle->resno,
    1959             :                                                 NULL,
    1960        6464 :                                                 tle->resjunk));
    1961             :             }
    1962        2362 :             break;
    1963             : 
    1964       24546 :         case RTE_FUNCTION:
    1965             :         case RTE_TABLEFUNC:
    1966             :         case RTE_VALUES:
    1967             :         case RTE_CTE:
    1968             :         case RTE_NAMEDTUPLESTORE:
    1969             :         case RTE_RESULT:
    1970             :             /* Not all of these can have dropped cols, but share code anyway */
    1971       24546 :             expandRTE(rte, varno, 0, VAR_RETURNING_DEFAULT, -1,
    1972             :                       true /* include dropped */ , NULL, &colvars);
    1973      125462 :             foreach(l, colvars)
    1974             :             {
    1975      100916 :                 var = (Var *) lfirst(l);
    1976             : 
    1977             :                 /*
    1978             :                  * A non-Var in expandRTE's output means a dropped column;
    1979             :                  * must punt.
    1980             :                  */
    1981      100916 :                 if (!IsA(var, Var))
    1982             :                 {
    1983           0 :                     tlist = NIL;
    1984           0 :                     break;
    1985             :                 }
    1986             : 
    1987      100916 :                 tlist = lappend(tlist,
    1988      100916 :                                 makeTargetEntry((Expr *) var,
    1989      100916 :                                                 var->varattno,
    1990             :                                                 NULL,
    1991             :                                                 false));
    1992             :             }
    1993       24546 :             break;
    1994             : 
    1995           0 :         default:
    1996             :             /* caller error */
    1997           0 :             elog(ERROR, "unsupported RTE kind %d in build_physical_tlist",
    1998             :                  (int) rte->rtekind);
    1999             :             break;
    2000             :     }
    2001             : 
    2002      188216 :     return tlist;
    2003             : }
    2004             : 
    2005             : /*
    2006             :  * build_index_tlist
    2007             :  *
    2008             :  * Build a targetlist representing the columns of the specified index.
    2009             :  * Each column is represented by a Var for the corresponding base-relation
    2010             :  * column, or an expression in base-relation Vars, as appropriate.
    2011             :  *
    2012             :  * There are never any dropped columns in indexes, so unlike
    2013             :  * build_physical_tlist, we need no failure case.
    2014             :  */
    2015             : static List *
    2016      745570 : build_index_tlist(PlannerInfo *root, IndexOptInfo *index,
    2017             :                   Relation heapRelation)
    2018             : {
    2019      745570 :     List       *tlist = NIL;
    2020      745570 :     Index       varno = index->rel->relid;
    2021             :     ListCell   *indexpr_item;
    2022             :     int         i;
    2023             : 
    2024      745570 :     indexpr_item = list_head(index->indexprs);
    2025     2150120 :     for (i = 0; i < index->ncolumns; i++)
    2026             :     {
    2027     1404550 :         int         indexkey = index->indexkeys[i];
    2028             :         Expr       *indexvar;
    2029             : 
    2030     1404550 :         if (indexkey != 0)
    2031             :         {
    2032             :             /* simple column */
    2033             :             const FormData_pg_attribute *att_tup;
    2034             : 
    2035     1401534 :             if (indexkey < 0)
    2036           0 :                 att_tup = SystemAttributeDefinition(indexkey);
    2037             :             else
    2038     1401534 :                 att_tup = TupleDescAttr(heapRelation->rd_att, indexkey - 1);
    2039             : 
    2040     1401534 :             indexvar = (Expr *) makeVar(varno,
    2041             :                                         indexkey,
    2042     1401534 :                                         att_tup->atttypid,
    2043     1401534 :                                         att_tup->atttypmod,
    2044     1401534 :                                         att_tup->attcollation,
    2045             :                                         0);
    2046             :         }
    2047             :         else
    2048             :         {
    2049             :             /* expression column */
    2050        3016 :             if (indexpr_item == NULL)
    2051           0 :                 elog(ERROR, "wrong number of index expressions");
    2052        3016 :             indexvar = (Expr *) lfirst(indexpr_item);
    2053        3016 :             indexpr_item = lnext(index->indexprs, indexpr_item);
    2054             :         }
    2055             : 
    2056     1404550 :         tlist = lappend(tlist,
    2057     1404550 :                         makeTargetEntry(indexvar,
    2058     1404550 :                                         i + 1,
    2059             :                                         NULL,
    2060             :                                         false));
    2061             :     }
    2062      745570 :     if (indexpr_item != NULL)
    2063           0 :         elog(ERROR, "wrong number of index expressions");
    2064             : 
    2065      745570 :     return tlist;
    2066             : }
    2067             : 
    2068             : /*
    2069             :  * restriction_selectivity
    2070             :  *
    2071             :  * Returns the selectivity of a specified restriction operator clause.
    2072             :  * This code executes registered procedures stored in the
    2073             :  * operator relation, by calling the function manager.
    2074             :  *
    2075             :  * See clause_selectivity() for the meaning of the additional parameters.
    2076             :  */
    2077             : Selectivity
    2078      739098 : restriction_selectivity(PlannerInfo *root,
    2079             :                         Oid operatorid,
    2080             :                         List *args,
    2081             :                         Oid inputcollid,
    2082             :                         int varRelid)
    2083             : {
    2084      739098 :     RegProcedure oprrest = get_oprrest(operatorid);
    2085             :     float8      result;
    2086             : 
    2087             :     /*
    2088             :      * if the oprrest procedure is missing for whatever reason, use a
    2089             :      * selectivity of 0.5
    2090             :      */
    2091      739098 :     if (!oprrest)
    2092         160 :         return (Selectivity) 0.5;
    2093             : 
    2094      738938 :     result = DatumGetFloat8(OidFunctionCall4Coll(oprrest,
    2095             :                                                  inputcollid,
    2096             :                                                  PointerGetDatum(root),
    2097             :                                                  ObjectIdGetDatum(operatorid),
    2098             :                                                  PointerGetDatum(args),
    2099             :                                                  Int32GetDatum(varRelid)));
    2100             : 
    2101      738908 :     if (result < 0.0 || result > 1.0)
    2102           0 :         elog(ERROR, "invalid restriction selectivity: %f", result);
    2103             : 
    2104      738908 :     return (Selectivity) result;
    2105             : }
    2106             : 
    2107             : /*
    2108             :  * join_selectivity
    2109             :  *
    2110             :  * Returns the selectivity of a specified join operator clause.
    2111             :  * This code executes registered procedures stored in the
    2112             :  * operator relation, by calling the function manager.
    2113             :  *
    2114             :  * See clause_selectivity() for the meaning of the additional parameters.
    2115             :  */
    2116             : Selectivity
    2117      267550 : join_selectivity(PlannerInfo *root,
    2118             :                  Oid operatorid,
    2119             :                  List *args,
    2120             :                  Oid inputcollid,
    2121             :                  JoinType jointype,
    2122             :                  SpecialJoinInfo *sjinfo)
    2123             : {
    2124      267550 :     RegProcedure oprjoin = get_oprjoin(operatorid);
    2125             :     float8      result;
    2126             : 
    2127             :     /*
    2128             :      * if the oprjoin procedure is missing for whatever reason, use a
    2129             :      * selectivity of 0.5
    2130             :      */
    2131      267550 :     if (!oprjoin)
    2132         146 :         return (Selectivity) 0.5;
    2133             : 
    2134      267404 :     result = DatumGetFloat8(OidFunctionCall5Coll(oprjoin,
    2135             :                                                  inputcollid,
    2136             :                                                  PointerGetDatum(root),
    2137             :                                                  ObjectIdGetDatum(operatorid),
    2138             :                                                  PointerGetDatum(args),
    2139             :                                                  Int16GetDatum(jointype),
    2140             :                                                  PointerGetDatum(sjinfo)));
    2141             : 
    2142      267404 :     if (result < 0.0 || result > 1.0)
    2143           0 :         elog(ERROR, "invalid join selectivity: %f", result);
    2144             : 
    2145      267404 :     return (Selectivity) result;
    2146             : }
    2147             : 
    2148             : /*
    2149             :  * function_selectivity
    2150             :  *
    2151             :  * Attempt to estimate the selectivity of a specified boolean function clause
    2152             :  * by asking its support function.  If the function lacks support, return -1.
    2153             :  *
    2154             :  * See clause_selectivity() for the meaning of the additional parameters.
    2155             :  */
    2156             : Selectivity
    2157       12370 : function_selectivity(PlannerInfo *root,
    2158             :                      Oid funcid,
    2159             :                      List *args,
    2160             :                      Oid inputcollid,
    2161             :                      bool is_join,
    2162             :                      int varRelid,
    2163             :                      JoinType jointype,
    2164             :                      SpecialJoinInfo *sjinfo)
    2165             : {
    2166       12370 :     RegProcedure prosupport = get_func_support(funcid);
    2167             :     SupportRequestSelectivity req;
    2168             :     SupportRequestSelectivity *sresult;
    2169             : 
    2170       12370 :     if (!prosupport)
    2171       12340 :         return (Selectivity) -1;    /* no support function */
    2172             : 
    2173          30 :     req.type = T_SupportRequestSelectivity;
    2174          30 :     req.root = root;
    2175          30 :     req.funcid = funcid;
    2176          30 :     req.args = args;
    2177          30 :     req.inputcollid = inputcollid;
    2178          30 :     req.is_join = is_join;
    2179          30 :     req.varRelid = varRelid;
    2180          30 :     req.jointype = jointype;
    2181          30 :     req.sjinfo = sjinfo;
    2182          30 :     req.selectivity = -1;       /* to catch failure to set the value */
    2183             : 
    2184             :     sresult = (SupportRequestSelectivity *)
    2185          30 :         DatumGetPointer(OidFunctionCall1(prosupport,
    2186             :                                          PointerGetDatum(&req)));
    2187             : 
    2188          30 :     if (sresult != &req)
    2189           0 :         return (Selectivity) -1;    /* function did not honor request */
    2190             : 
    2191          30 :     if (req.selectivity < 0.0 || req.selectivity > 1.0)
    2192           0 :         elog(ERROR, "invalid function selectivity: %f", req.selectivity);
    2193             : 
    2194          30 :     return (Selectivity) req.selectivity;
    2195             : }
    2196             : 
    2197             : /*
    2198             :  * add_function_cost
    2199             :  *
    2200             :  * Get an estimate of the execution cost of a function, and *add* it to
    2201             :  * the contents of *cost.  The estimate may include both one-time and
    2202             :  * per-tuple components, since QualCost does.
    2203             :  *
    2204             :  * The funcid must always be supplied.  If it is being called as the
    2205             :  * implementation of a specific parsetree node (FuncExpr, OpExpr,
    2206             :  * WindowFunc, etc), pass that as "node", else pass NULL.
    2207             :  *
    2208             :  * In some usages root might be NULL, too.
    2209             :  */
    2210             : void
    2211     1162190 : add_function_cost(PlannerInfo *root, Oid funcid, Node *node,
    2212             :                   QualCost *cost)
    2213             : {
    2214             :     HeapTuple   proctup;
    2215             :     Form_pg_proc procform;
    2216             : 
    2217     1162190 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    2218     1162190 :     if (!HeapTupleIsValid(proctup))
    2219           0 :         elog(ERROR, "cache lookup failed for function %u", funcid);
    2220     1162190 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
    2221             : 
    2222     1162190 :     if (OidIsValid(procform->prosupport))
    2223             :     {
    2224             :         SupportRequestCost req;
    2225             :         SupportRequestCost *sresult;
    2226             : 
    2227       35326 :         req.type = T_SupportRequestCost;
    2228       35326 :         req.root = root;
    2229       35326 :         req.funcid = funcid;
    2230       35326 :         req.node = node;
    2231             : 
    2232             :         /* Initialize cost fields so that support function doesn't have to */
    2233       35326 :         req.startup = 0;
    2234       35326 :         req.per_tuple = 0;
    2235             : 
    2236             :         sresult = (SupportRequestCost *)
    2237       35326 :             DatumGetPointer(OidFunctionCall1(procform->prosupport,
    2238             :                                              PointerGetDatum(&req)));
    2239             : 
    2240       35326 :         if (sresult == &req)
    2241             :         {
    2242             :             /* Success, so accumulate support function's estimate into *cost */
    2243          18 :             cost->startup += req.startup;
    2244          18 :             cost->per_tuple += req.per_tuple;
    2245          18 :             ReleaseSysCache(proctup);
    2246          18 :             return;
    2247             :         }
    2248             :     }
    2249             : 
    2250             :     /* No support function, or it failed, so rely on procost */
    2251     1162172 :     cost->per_tuple += procform->procost * cpu_operator_cost;
    2252             : 
    2253     1162172 :     ReleaseSysCache(proctup);
    2254             : }
    2255             : 
    2256             : /*
    2257             :  * get_function_rows
    2258             :  *
    2259             :  * Get an estimate of the number of rows returned by a set-returning function.
    2260             :  *
    2261             :  * The funcid must always be supplied.  In current usage, the calling node
    2262             :  * will always be supplied, and will be either a FuncExpr or OpExpr.
    2263             :  * But it's a good idea to not fail if it's NULL.
    2264             :  *
    2265             :  * In some usages root might be NULL, too.
    2266             :  *
    2267             :  * Note: this returns the unfiltered result of the support function, if any.
    2268             :  * It's usually a good idea to apply clamp_row_est() to the result, but we
    2269             :  * leave it to the caller to do so.
    2270             :  */
    2271             : double
    2272       56316 : get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
    2273             : {
    2274             :     HeapTuple   proctup;
    2275             :     Form_pg_proc procform;
    2276             :     double      result;
    2277             : 
    2278       56316 :     proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
    2279       56316 :     if (!HeapTupleIsValid(proctup))
    2280           0 :         elog(ERROR, "cache lookup failed for function %u", funcid);
    2281       56316 :     procform = (Form_pg_proc) GETSTRUCT(proctup);
    2282             : 
    2283             :     Assert(procform->proretset); /* else caller error */
    2284             : 
    2285       56316 :     if (OidIsValid(procform->prosupport))
    2286             :     {
    2287             :         SupportRequestRows req;
    2288             :         SupportRequestRows *sresult;
    2289             : 
    2290       21070 :         req.type = T_SupportRequestRows;
    2291       21070 :         req.root = root;
    2292       21070 :         req.funcid = funcid;
    2293       21070 :         req.node = node;
    2294             : 
    2295       21070 :         req.rows = 0;           /* just for sanity */
    2296             : 
    2297             :         sresult = (SupportRequestRows *)
    2298       21070 :             DatumGetPointer(OidFunctionCall1(procform->prosupport,
    2299             :                                              PointerGetDatum(&req)));
    2300             : 
    2301       21070 :         if (sresult == &req)
    2302             :         {
    2303             :             /* Success */
    2304       17030 :             ReleaseSysCache(proctup);
    2305       17030 :             return req.rows;
    2306             :         }
    2307             :     }
    2308             : 
    2309             :     /* No support function, or it failed, so rely on prorows */
    2310       39286 :     result = procform->prorows;
    2311             : 
    2312       39286 :     ReleaseSysCache(proctup);
    2313             : 
    2314       39286 :     return result;
    2315             : }
    2316             : 
    2317             : /*
    2318             :  * has_unique_index
    2319             :  *
    2320             :  * Detect whether there is a unique index on the specified attribute
    2321             :  * of the specified relation, thus allowing us to conclude that all
    2322             :  * the (non-null) values of the attribute are distinct.
    2323             :  *
    2324             :  * This function does not check the index's indimmediate property, which
    2325             :  * means that uniqueness may transiently fail to hold intra-transaction.
    2326             :  * That's appropriate when we are making statistical estimates, but beware
    2327             :  * of using this for any correctness proofs.
    2328             :  */
    2329             : bool
    2330     2321306 : has_unique_index(RelOptInfo *rel, AttrNumber attno)
    2331             : {
    2332             :     ListCell   *ilist;
    2333             : 
    2334     5661358 :     foreach(ilist, rel->indexlist)
    2335             :     {
    2336     4055482 :         IndexOptInfo *index = (IndexOptInfo *) lfirst(ilist);
    2337             : 
    2338             :         /*
    2339             :          * Note: ignore partial indexes, since they don't allow us to conclude
    2340             :          * that all attr values are distinct, *unless* they are marked predOK
    2341             :          * which means we know the index's predicate is satisfied by the
    2342             :          * query. We don't take any interest in expressional indexes either.
    2343             :          * Also, a multicolumn unique index doesn't allow us to conclude that
    2344             :          * just the specified attr is unique.
    2345             :          */
    2346     4055482 :         if (index->unique &&
    2347     2827934 :             index->nkeycolumns == 1 &&
    2348     1531972 :             index->indexkeys[0] == attno &&
    2349      715466 :             (index->indpred == NIL || index->predOK))
    2350      715430 :             return true;
    2351             :     }
    2352     1605876 :     return false;
    2353             : }
    2354             : 
    2355             : 
    2356             : /*
    2357             :  * has_row_triggers
    2358             :  *
    2359             :  * Detect whether the specified relation has any row-level triggers for event.
    2360             :  */
    2361             : bool
    2362         516 : has_row_triggers(PlannerInfo *root, Index rti, CmdType event)
    2363             : {
    2364         516 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
    2365             :     Relation    relation;
    2366             :     TriggerDesc *trigDesc;
    2367         516 :     bool        result = false;
    2368             : 
    2369             :     /* Assume we already have adequate lock */
    2370         516 :     relation = table_open(rte->relid, NoLock);
    2371             : 
    2372         516 :     trigDesc = relation->trigdesc;
    2373         516 :     switch (event)
    2374             :     {
    2375         164 :         case CMD_INSERT:
    2376         164 :             if (trigDesc &&
    2377          26 :                 (trigDesc->trig_insert_after_row ||
    2378          14 :                  trigDesc->trig_insert_before_row))
    2379          26 :                 result = true;
    2380         164 :             break;
    2381         190 :         case CMD_UPDATE:
    2382         190 :             if (trigDesc &&
    2383          48 :                 (trigDesc->trig_update_after_row ||
    2384          28 :                  trigDesc->trig_update_before_row))
    2385          36 :                 result = true;
    2386         190 :             break;
    2387         162 :         case CMD_DELETE:
    2388         162 :             if (trigDesc &&
    2389          30 :                 (trigDesc->trig_delete_after_row ||
    2390          18 :                  trigDesc->trig_delete_before_row))
    2391          16 :                 result = true;
    2392         162 :             break;
    2393             :             /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
    2394           0 :         case CMD_MERGE:
    2395           0 :             result = false;
    2396           0 :             break;
    2397           0 :         default:
    2398           0 :             elog(ERROR, "unrecognized CmdType: %d", (int) event);
    2399             :             break;
    2400             :     }
    2401             : 
    2402         516 :     table_close(relation, NoLock);
    2403         516 :     return result;
    2404             : }
    2405             : 
    2406             : /*
    2407             :  * has_transition_tables
    2408             :  *
    2409             :  * Detect whether the specified relation has any transition tables for event.
    2410             :  */
    2411             : bool
    2412         390 : has_transition_tables(PlannerInfo *root, Index rti, CmdType event)
    2413             : {
    2414         390 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
    2415             :     Relation    relation;
    2416             :     TriggerDesc *trigDesc;
    2417         390 :     bool        result = false;
    2418             : 
    2419             :     Assert(rte->rtekind == RTE_RELATION);
    2420             : 
    2421             :     /* Currently foreign tables cannot have transition tables */
    2422         390 :     if (rte->relkind == RELKIND_FOREIGN_TABLE)
    2423         290 :         return result;
    2424             : 
    2425             :     /* Assume we already have adequate lock */
    2426         100 :     relation = table_open(rte->relid, NoLock);
    2427             : 
    2428         100 :     trigDesc = relation->trigdesc;
    2429         100 :     switch (event)
    2430             :     {
    2431           0 :         case CMD_INSERT:
    2432           0 :             if (trigDesc &&
    2433           0 :                 trigDesc->trig_insert_new_table)
    2434           0 :                 result = true;
    2435           0 :             break;
    2436          60 :         case CMD_UPDATE:
    2437          60 :             if (trigDesc &&
    2438           8 :                 (trigDesc->trig_update_old_table ||
    2439           0 :                  trigDesc->trig_update_new_table))
    2440           8 :                 result = true;
    2441          60 :             break;
    2442          40 :         case CMD_DELETE:
    2443          40 :             if (trigDesc &&
    2444           8 :                 trigDesc->trig_delete_old_table)
    2445           8 :                 result = true;
    2446          40 :             break;
    2447             :             /* There is no separate event for MERGE, only INSERT/UPDATE/DELETE */
    2448           0 :         case CMD_MERGE:
    2449           0 :             result = false;
    2450           0 :             break;
    2451           0 :         default:
    2452           0 :             elog(ERROR, "unrecognized CmdType: %d", (int) event);
    2453             :             break;
    2454             :     }
    2455             : 
    2456         100 :     table_close(relation, NoLock);
    2457         100 :     return result;
    2458             : }
    2459             : 
    2460             : /*
    2461             :  * has_stored_generated_columns
    2462             :  *
    2463             :  * Does table identified by RTI have any STORED GENERATED columns?
    2464             :  */
    2465             : bool
    2466         438 : has_stored_generated_columns(PlannerInfo *root, Index rti)
    2467             : {
    2468         438 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
    2469             :     Relation    relation;
    2470             :     TupleDesc   tupdesc;
    2471         438 :     bool        result = false;
    2472             : 
    2473             :     /* Assume we already have adequate lock */
    2474         438 :     relation = table_open(rte->relid, NoLock);
    2475             : 
    2476         438 :     tupdesc = RelationGetDescr(relation);
    2477         438 :     result = tupdesc->constr && tupdesc->constr->has_generated_stored;
    2478             : 
    2479         438 :     table_close(relation, NoLock);
    2480             : 
    2481         438 :     return result;
    2482             : }
    2483             : 
    2484             : /*
    2485             :  * get_dependent_generated_columns
    2486             :  *
    2487             :  * Get the column numbers of any STORED GENERATED columns of the relation
    2488             :  * that depend on any column listed in target_cols.  Both the input and
    2489             :  * result bitmapsets contain column numbers offset by
    2490             :  * FirstLowInvalidHeapAttributeNumber.
    2491             :  */
    2492             : Bitmapset *
    2493          90 : get_dependent_generated_columns(PlannerInfo *root, Index rti,
    2494             :                                 Bitmapset *target_cols)
    2495             : {
    2496          90 :     Bitmapset  *dependentCols = NULL;
    2497          90 :     RangeTblEntry *rte = planner_rt_fetch(rti, root);
    2498             :     Relation    relation;
    2499             :     TupleDesc   tupdesc;
    2500             :     TupleConstr *constr;
    2501             : 
    2502             :     /* Assume we already have adequate lock */
    2503          90 :     relation = table_open(rte->relid, NoLock);
    2504             : 
    2505          90 :     tupdesc = RelationGetDescr(relation);
    2506          90 :     constr = tupdesc->constr;
    2507             : 
    2508          90 :     if (constr && constr->has_generated_stored)
    2509             :     {
    2510          12 :         for (int i = 0; i < constr->num_defval; i++)
    2511             :         {
    2512           8 :             AttrDefault *defval = &constr->defval[i];
    2513             :             Node       *expr;
    2514           8 :             Bitmapset  *attrs_used = NULL;
    2515             : 
    2516             :             /* skip if not generated column */
    2517           8 :             if (!TupleDescCompactAttr(tupdesc, defval->adnum - 1)->attgenerated)
    2518           0 :                 continue;
    2519             : 
    2520             :             /* identify columns this generated column depends on */
    2521           8 :             expr = stringToNode(defval->adbin);
    2522           8 :             pull_varattnos(expr, 1, &attrs_used);
    2523             : 
    2524           8 :             if (bms_overlap(target_cols, attrs_used))
    2525           8 :                 dependentCols = bms_add_member(dependentCols,
    2526           8 :                                                defval->adnum - FirstLowInvalidHeapAttributeNumber);
    2527             :         }
    2528             :     }
    2529             : 
    2530          90 :     table_close(relation, NoLock);
    2531             : 
    2532          90 :     return dependentCols;
    2533             : }
    2534             : 
    2535             : /*
    2536             :  * set_relation_partition_info
    2537             :  *
    2538             :  * Set partitioning scheme and related information for a partitioned table.
    2539             :  */
    2540             : static void
    2541       17638 : set_relation_partition_info(PlannerInfo *root, RelOptInfo *rel,
    2542             :                             Relation relation)
    2543             : {
    2544             :     PartitionDesc partdesc;
    2545             : 
    2546             :     /*
    2547             :      * Create the PartitionDirectory infrastructure if we didn't already.
    2548             :      */
    2549       17638 :     if (root->glob->partition_directory == NULL)
    2550             :     {
    2551       11790 :         root->glob->partition_directory =
    2552       11790 :             CreatePartitionDirectory(CurrentMemoryContext, true);
    2553             :     }
    2554             : 
    2555       17638 :     partdesc = PartitionDirectoryLookup(root->glob->partition_directory,
    2556             :                                         relation);
    2557       17638 :     rel->part_scheme = find_partition_scheme(root, relation);
    2558             :     Assert(partdesc != NULL && rel->part_scheme != NULL);
    2559       17638 :     rel->boundinfo = partdesc->boundinfo;
    2560       17638 :     rel->nparts = partdesc->nparts;
    2561       17638 :     set_baserel_partition_key_exprs(relation, rel);
    2562       17638 :     set_baserel_partition_constraint(relation, rel);
    2563       17638 : }
    2564             : 
    2565             : /*
    2566             :  * find_partition_scheme
    2567             :  *
    2568             :  * Find or create a PartitionScheme for this Relation.
    2569             :  */
    2570             : static PartitionScheme
    2571       17638 : find_partition_scheme(PlannerInfo *root, Relation relation)
    2572             : {
    2573       17638 :     PartitionKey partkey = RelationGetPartitionKey(relation);
    2574             :     ListCell   *lc;
    2575             :     int         partnatts,
    2576             :                 i;
    2577             :     PartitionScheme part_scheme;
    2578             : 
    2579             :     /* A partitioned table should have a partition key. */
    2580             :     Assert(partkey != NULL);
    2581             : 
    2582       17638 :     partnatts = partkey->partnatts;
    2583             : 
    2584             :     /* Search for a matching partition scheme and return if found one. */
    2585       19528 :     foreach(lc, root->part_schemes)
    2586             :     {
    2587        6440 :         part_scheme = lfirst(lc);
    2588             : 
    2589             :         /* Match partitioning strategy and number of keys. */
    2590        6440 :         if (partkey->strategy != part_scheme->strategy ||
    2591        5450 :             partnatts != part_scheme->partnatts)
    2592        1440 :             continue;
    2593             : 
    2594             :         /* Match partition key type properties. */
    2595        5000 :         if (memcmp(partkey->partopfamily, part_scheme->partopfamily,
    2596        4550 :                    sizeof(Oid) * partnatts) != 0 ||
    2597        4550 :             memcmp(partkey->partopcintype, part_scheme->partopcintype,
    2598        4550 :                    sizeof(Oid) * partnatts) != 0 ||
    2599        4550 :             memcmp(partkey->partcollation, part_scheme->partcollation,
    2600             :                    sizeof(Oid) * partnatts) != 0)
    2601         450 :             continue;
    2602             : 
    2603             :         /*
    2604             :          * Length and byval information should match when partopcintype
    2605             :          * matches.
    2606             :          */
    2607             :         Assert(memcmp(partkey->parttyplen, part_scheme->parttyplen,
    2608             :                       sizeof(int16) * partnatts) == 0);
    2609             :         Assert(memcmp(partkey->parttypbyval, part_scheme->parttypbyval,
    2610             :                       sizeof(bool) * partnatts) == 0);
    2611             : 
    2612             :         /*
    2613             :          * If partopfamily and partopcintype matched, must have the same
    2614             :          * partition comparison functions.  Note that we cannot reliably
    2615             :          * Assert the equality of function structs themselves for they might
    2616             :          * be different across PartitionKey's, so just Assert for the function
    2617             :          * OIDs.
    2618             :          */
    2619             : #ifdef USE_ASSERT_CHECKING
    2620             :         for (i = 0; i < partkey->partnatts; i++)
    2621             :             Assert(partkey->partsupfunc[i].fn_oid ==
    2622             :                    part_scheme->partsupfunc[i].fn_oid);
    2623             : #endif
    2624             : 
    2625             :         /* Found matching partition scheme. */
    2626        4550 :         return part_scheme;
    2627             :     }
    2628             : 
    2629             :     /*
    2630             :      * Did not find matching partition scheme. Create one copying relevant
    2631             :      * information from the relcache. We need to copy the contents of the
    2632             :      * array since the relcache entry may not survive after we have closed the
    2633             :      * relation.
    2634             :      */
    2635       13088 :     part_scheme = (PartitionScheme) palloc0(sizeof(PartitionSchemeData));
    2636       13088 :     part_scheme->strategy = partkey->strategy;
    2637       13088 :     part_scheme->partnatts = partkey->partnatts;
    2638             : 
    2639       13088 :     part_scheme->partopfamily = (Oid *) palloc(sizeof(Oid) * partnatts);
    2640       13088 :     memcpy(part_scheme->partopfamily, partkey->partopfamily,
    2641             :            sizeof(Oid) * partnatts);
    2642             : 
    2643       13088 :     part_scheme->partopcintype = (Oid *) palloc(sizeof(Oid) * partnatts);
    2644       13088 :     memcpy(part_scheme->partopcintype, partkey->partopcintype,
    2645             :            sizeof(Oid) * partnatts);
    2646             : 
    2647       13088 :     part_scheme->partcollation = (Oid *) palloc(sizeof(Oid) * partnatts);
    2648       13088 :     memcpy(part_scheme->partcollation, partkey->partcollation,
    2649             :            sizeof(Oid) * partnatts);
    2650             : 
    2651       13088 :     part_scheme->parttyplen = (int16 *) palloc(sizeof(int16) * partnatts);
    2652       13088 :     memcpy(part_scheme->parttyplen, partkey->parttyplen,
    2653             :            sizeof(int16) * partnatts);
    2654             : 
    2655       13088 :     part_scheme->parttypbyval = (bool *) palloc(sizeof(bool) * partnatts);
    2656       13088 :     memcpy(part_scheme->parttypbyval, partkey->parttypbyval,
    2657             :            sizeof(bool) * partnatts);
    2658             : 
    2659       13088 :     part_scheme->partsupfunc = (FmgrInfo *)
    2660       13088 :         palloc(sizeof(FmgrInfo) * partnatts);
    2661       28024 :     for (i = 0; i < partnatts; i++)
    2662       14936 :         fmgr_info_copy(&part_scheme->partsupfunc[i], &partkey->partsupfunc[i],
    2663             :                        CurrentMemoryContext);
    2664             : 
    2665             :     /* Add the partitioning scheme to PlannerInfo. */
    2666       13088 :     root->part_schemes = lappend(root->part_schemes, part_scheme);
    2667             : 
    2668       13088 :     return part_scheme;
    2669             : }
    2670             : 
    2671             : /*
    2672             :  * set_baserel_partition_key_exprs
    2673             :  *
    2674             :  * Builds partition key expressions for the given base relation and fills
    2675             :  * rel->partexprs.
    2676             :  */
    2677             : static void
    2678       17638 : set_baserel_partition_key_exprs(Relation relation,
    2679             :                                 RelOptInfo *rel)
    2680             : {
    2681       17638 :     PartitionKey partkey = RelationGetPartitionKey(relation);
    2682             :     int         partnatts;
    2683             :     int         cnt;
    2684             :     List      **partexprs;
    2685             :     ListCell   *lc;
    2686       17638 :     Index       varno = rel->relid;
    2687             : 
    2688             :     Assert(IS_SIMPLE_REL(rel) && rel->relid > 0);
    2689             : 
    2690             :     /* A partitioned table should have a partition key. */
    2691             :     Assert(partkey != NULL);
    2692             : 
    2693       17638 :     partnatts = partkey->partnatts;
    2694       17638 :     partexprs = (List **) palloc(sizeof(List *) * partnatts);
    2695       17638 :     lc = list_head(partkey->partexprs);
    2696             : 
    2697       37154 :     for (cnt = 0; cnt < partnatts; cnt++)
    2698             :     {
    2699             :         Expr       *partexpr;
    2700       19516 :         AttrNumber  attno = partkey->partattrs[cnt];
    2701             : 
    2702       19516 :         if (attno != InvalidAttrNumber)
    2703             :         {
    2704             :             /* Single column partition key is stored as a Var node. */
    2705             :             Assert(attno > 0);
    2706             : 
    2707       18586 :             partexpr = (Expr *) makeVar(varno, attno,
    2708       18586 :                                         partkey->parttypid[cnt],
    2709       18586 :                                         partkey->parttypmod[cnt],
    2710       18586 :                                         partkey->parttypcoll[cnt], 0);
    2711             :         }
    2712             :         else
    2713             :         {
    2714         930 :             if (lc == NULL)
    2715           0 :                 elog(ERROR, "wrong number of partition key expressions");
    2716             : 
    2717             :             /* Re-stamp the expression with given varno. */
    2718         930 :             partexpr = (Expr *) copyObject(lfirst(lc));
    2719         930 :             ChangeVarNodes((Node *) partexpr, 1, varno, 0);
    2720         930 :             lc = lnext(partkey->partexprs, lc);
    2721             :         }
    2722             : 
    2723             :         /* Base relations have a single expression per key. */
    2724       19516 :         partexprs[cnt] = list_make1(partexpr);
    2725             :     }
    2726             : 
    2727       17638 :     rel->partexprs = partexprs;
    2728             : 
    2729             :     /*
    2730             :      * A base relation does not have nullable partition key expressions, since
    2731             :      * no outer join is involved.  We still allocate an array of empty
    2732             :      * expression lists to keep partition key expression handling code simple.
    2733             :      * See build_joinrel_partition_info() and match_expr_to_partition_keys().
    2734             :      */
    2735       17638 :     rel->nullable_partexprs = (List **) palloc0(sizeof(List *) * partnatts);
    2736       17638 : }
    2737             : 
    2738             : /*
    2739             :  * set_baserel_partition_constraint
    2740             :  *
    2741             :  * Builds the partition constraint for the given base relation and sets it
    2742             :  * in the given RelOptInfo.  All Var nodes are restamped with the relid of the
    2743             :  * given relation.
    2744             :  */
    2745             : static void
    2746       17650 : set_baserel_partition_constraint(Relation relation, RelOptInfo *rel)
    2747             : {
    2748             :     List       *partconstr;
    2749             : 
    2750       17650 :     if (rel->partition_qual) /* already done */
    2751           0 :         return;
    2752             : 
    2753             :     /*
    2754             :      * Run the partition quals through const-simplification similar to check
    2755             :      * constraints.  We skip canonicalize_qual, though, because partition
    2756             :      * quals should be in canonical form already; also, since the qual is in
    2757             :      * implicit-AND format, we'd have to explicitly convert it to explicit-AND
    2758             :      * format and back again.
    2759             :      */
    2760       17650 :     partconstr = RelationGetPartitionQual(relation);
    2761       17650 :     if (partconstr)
    2762             :     {
    2763        3712 :         partconstr = (List *) expression_planner((Expr *) partconstr);
    2764        3712 :         if (rel->relid != 1)
    2765        3630 :             ChangeVarNodes((Node *) partconstr, 1, rel->relid, 0);
    2766        3712 :         rel->partition_qual = partconstr;
    2767             :     }
    2768             : }

Generated by: LCOV version 1.16