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

Generated by: LCOV version 1.16