LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - plancat.c (source / functions) Hit Total Coverage
Test: PostgreSQL 16beta1 Lines: 729 787 92.6 %
Date: 2023-05-30 23:12:14 Functions: 26 26 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14