LCOV - code coverage report
Current view: top level - src/backend/executor - execPartition.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 640 668 95.8 %
Date: 2025-02-22 07:14:56 Functions: 18 18 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * execPartition.c
       4             :  *    Support routines for partitioning.
       5             :  *
       6             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  * IDENTIFICATION
      10             :  *    src/backend/executor/execPartition.c
      11             :  *
      12             :  *-------------------------------------------------------------------------
      13             :  */
      14             : #include "postgres.h"
      15             : 
      16             : #include "access/table.h"
      17             : #include "access/tableam.h"
      18             : #include "catalog/partition.h"
      19             : #include "executor/execPartition.h"
      20             : #include "executor/executor.h"
      21             : #include "executor/nodeModifyTable.h"
      22             : #include "foreign/fdwapi.h"
      23             : #include "mb/pg_wchar.h"
      24             : #include "miscadmin.h"
      25             : #include "partitioning/partbounds.h"
      26             : #include "partitioning/partdesc.h"
      27             : #include "partitioning/partprune.h"
      28             : #include "rewrite/rewriteManip.h"
      29             : #include "storage/lmgr.h"
      30             : #include "utils/acl.h"
      31             : #include "utils/lsyscache.h"
      32             : #include "utils/partcache.h"
      33             : #include "utils/rls.h"
      34             : #include "utils/ruleutils.h"
      35             : 
      36             : 
      37             : /*-----------------------
      38             :  * PartitionTupleRouting - Encapsulates all information required to
      39             :  * route a tuple inserted into a partitioned table to one of its leaf
      40             :  * partitions.
      41             :  *
      42             :  * partition_root
      43             :  *      The partitioned table that's the target of the command.
      44             :  *
      45             :  * partition_dispatch_info
      46             :  *      Array of 'max_dispatch' elements containing a pointer to a
      47             :  *      PartitionDispatch object for every partitioned table touched by tuple
      48             :  *      routing.  The entry for the target partitioned table is *always*
      49             :  *      present in the 0th element of this array.  See comment for
      50             :  *      PartitionDispatchData->indexes for details on how this array is
      51             :  *      indexed.
      52             :  *
      53             :  * nonleaf_partitions
      54             :  *      Array of 'max_dispatch' elements containing pointers to fake
      55             :  *      ResultRelInfo objects for nonleaf partitions, useful for checking
      56             :  *      the partition constraint.
      57             :  *
      58             :  * num_dispatch
      59             :  *      The current number of items stored in the 'partition_dispatch_info'
      60             :  *      array.  Also serves as the index of the next free array element for
      61             :  *      new PartitionDispatch objects that need to be stored.
      62             :  *
      63             :  * max_dispatch
      64             :  *      The current allocated size of the 'partition_dispatch_info' array.
      65             :  *
      66             :  * partitions
      67             :  *      Array of 'max_partitions' elements containing a pointer to a
      68             :  *      ResultRelInfo for every leaf partition touched by tuple routing.
      69             :  *      Some of these are pointers to ResultRelInfos which are borrowed out of
      70             :  *      the owning ModifyTableState node.  The remainder have been built
      71             :  *      especially for tuple routing.  See comment for
      72             :  *      PartitionDispatchData->indexes for details on how this array is
      73             :  *      indexed.
      74             :  *
      75             :  * is_borrowed_rel
      76             :  *      Array of 'max_partitions' booleans recording whether a given entry
      77             :  *      in 'partitions' is a ResultRelInfo pointer borrowed from the owning
      78             :  *      ModifyTableState node, rather than being built here.
      79             :  *
      80             :  * num_partitions
      81             :  *      The current number of items stored in the 'partitions' array.  Also
      82             :  *      serves as the index of the next free array element for new
      83             :  *      ResultRelInfo objects that need to be stored.
      84             :  *
      85             :  * max_partitions
      86             :  *      The current allocated size of the 'partitions' array.
      87             :  *
      88             :  * memcxt
      89             :  *      Memory context used to allocate subsidiary structs.
      90             :  *-----------------------
      91             :  */
      92             : struct PartitionTupleRouting
      93             : {
      94             :     Relation    partition_root;
      95             :     PartitionDispatch *partition_dispatch_info;
      96             :     ResultRelInfo **nonleaf_partitions;
      97             :     int         num_dispatch;
      98             :     int         max_dispatch;
      99             :     ResultRelInfo **partitions;
     100             :     bool       *is_borrowed_rel;
     101             :     int         num_partitions;
     102             :     int         max_partitions;
     103             :     MemoryContext memcxt;
     104             : };
     105             : 
     106             : /*-----------------------
     107             :  * PartitionDispatch - information about one partitioned table in a partition
     108             :  * hierarchy required to route a tuple to any of its partitions.  A
     109             :  * PartitionDispatch is always encapsulated inside a PartitionTupleRouting
     110             :  * struct and stored inside its 'partition_dispatch_info' array.
     111             :  *
     112             :  * reldesc
     113             :  *      Relation descriptor of the table
     114             :  *
     115             :  * key
     116             :  *      Partition key information of the table
     117             :  *
     118             :  * keystate
     119             :  *      Execution state required for expressions in the partition key
     120             :  *
     121             :  * partdesc
     122             :  *      Partition descriptor of the table
     123             :  *
     124             :  * tupslot
     125             :  *      A standalone TupleTableSlot initialized with this table's tuple
     126             :  *      descriptor, or NULL if no tuple conversion between the parent is
     127             :  *      required.
     128             :  *
     129             :  * tupmap
     130             :  *      TupleConversionMap to convert from the parent's rowtype to this table's
     131             :  *      rowtype  (when extracting the partition key of a tuple just before
     132             :  *      routing it through this table). A NULL value is stored if no tuple
     133             :  *      conversion is required.
     134             :  *
     135             :  * indexes
     136             :  *      Array of partdesc->nparts elements.  For leaf partitions the index
     137             :  *      corresponds to the partition's ResultRelInfo in the encapsulating
     138             :  *      PartitionTupleRouting's partitions array.  For partitioned partitions,
     139             :  *      the index corresponds to the PartitionDispatch for it in its
     140             :  *      partition_dispatch_info array.  -1 indicates we've not yet allocated
     141             :  *      anything in PartitionTupleRouting for the partition.
     142             :  *-----------------------
     143             :  */
     144             : typedef struct PartitionDispatchData
     145             : {
     146             :     Relation    reldesc;
     147             :     PartitionKey key;
     148             :     List       *keystate;       /* list of ExprState */
     149             :     PartitionDesc partdesc;
     150             :     TupleTableSlot *tupslot;
     151             :     AttrMap    *tupmap;
     152             :     int         indexes[FLEXIBLE_ARRAY_MEMBER];
     153             : }           PartitionDispatchData;
     154             : 
     155             : 
     156             : static ResultRelInfo *ExecInitPartitionInfo(ModifyTableState *mtstate,
     157             :                                             EState *estate, PartitionTupleRouting *proute,
     158             :                                             PartitionDispatch dispatch,
     159             :                                             ResultRelInfo *rootResultRelInfo,
     160             :                                             int partidx);
     161             : static void ExecInitRoutingInfo(ModifyTableState *mtstate,
     162             :                                 EState *estate,
     163             :                                 PartitionTupleRouting *proute,
     164             :                                 PartitionDispatch dispatch,
     165             :                                 ResultRelInfo *partRelInfo,
     166             :                                 int partidx,
     167             :                                 bool is_borrowed_rel);
     168             : static PartitionDispatch ExecInitPartitionDispatchInfo(EState *estate,
     169             :                                                        PartitionTupleRouting *proute,
     170             :                                                        Oid partoid, PartitionDispatch parent_pd,
     171             :                                                        int partidx, ResultRelInfo *rootResultRelInfo);
     172             : static void FormPartitionKeyDatum(PartitionDispatch pd,
     173             :                                   TupleTableSlot *slot,
     174             :                                   EState *estate,
     175             :                                   Datum *values,
     176             :                                   bool *isnull);
     177             : static int  get_partition_for_tuple(PartitionDispatch pd, Datum *values,
     178             :                                     bool *isnull);
     179             : static char *ExecBuildSlotPartitionKeyDescription(Relation rel,
     180             :                                                   Datum *values,
     181             :                                                   bool *isnull,
     182             :                                                   int maxfieldlen);
     183             : static List *adjust_partition_colnos(List *colnos, ResultRelInfo *leaf_part_rri);
     184             : static List *adjust_partition_colnos_using_map(List *colnos, AttrMap *attrMap);
     185             : static PartitionPruneState *CreatePartitionPruneState(EState *estate,
     186             :                                                       PartitionPruneInfo *pruneinfo,
     187             :                                                       Bitmapset **all_leafpart_rtis);
     188             : static void InitPartitionPruneContext(PartitionPruneContext *context,
     189             :                                       List *pruning_steps,
     190             :                                       PartitionDesc partdesc,
     191             :                                       PartitionKey partkey,
     192             :                                       PlanState *planstate,
     193             :                                       ExprContext *econtext);
     194             : static void InitExecPartitionPruneContexts(PartitionPruneState *prunstate,
     195             :                                            PlanState *parent_plan,
     196             :                                            Bitmapset *initially_valid_subplans,
     197             :                                            int n_total_subplans);
     198             : static void find_matching_subplans_recurse(PartitionPruningData *prunedata,
     199             :                                            PartitionedRelPruningData *pprune,
     200             :                                            bool initial_prune,
     201             :                                            Bitmapset **validsubplans,
     202             :                                            Bitmapset **validsubplan_rtis);
     203             : 
     204             : 
     205             : /*
     206             :  * ExecSetupPartitionTupleRouting - sets up information needed during
     207             :  * tuple routing for partitioned tables, encapsulates it in
     208             :  * PartitionTupleRouting, and returns it.
     209             :  *
     210             :  * Callers must use the returned PartitionTupleRouting during calls to
     211             :  * ExecFindPartition().  The actual ResultRelInfo for a partition is only
     212             :  * allocated when the partition is found for the first time.
     213             :  *
     214             :  * The current memory context is used to allocate this struct and all
     215             :  * subsidiary structs that will be allocated from it later on.  Typically
     216             :  * it should be estate->es_query_cxt.
     217             :  */
     218             : PartitionTupleRouting *
     219        6940 : ExecSetupPartitionTupleRouting(EState *estate, Relation rel)
     220             : {
     221             :     PartitionTupleRouting *proute;
     222             : 
     223             :     /*
     224             :      * Here we attempt to expend as little effort as possible in setting up
     225             :      * the PartitionTupleRouting.  Each partition's ResultRelInfo is built on
     226             :      * demand, only when we actually need to route a tuple to that partition.
     227             :      * The reason for this is that a common case is for INSERT to insert a
     228             :      * single tuple into a partitioned table and this must be fast.
     229             :      */
     230        6940 :     proute = (PartitionTupleRouting *) palloc0(sizeof(PartitionTupleRouting));
     231        6940 :     proute->partition_root = rel;
     232        6940 :     proute->memcxt = CurrentMemoryContext;
     233             :     /* Rest of members initialized by zeroing */
     234             : 
     235             :     /*
     236             :      * Initialize this table's PartitionDispatch object.  Here we pass in the
     237             :      * parent as NULL as we don't need to care about any parent of the target
     238             :      * partitioned table.
     239             :      */
     240        6940 :     ExecInitPartitionDispatchInfo(estate, proute, RelationGetRelid(rel),
     241             :                                   NULL, 0, NULL);
     242             : 
     243        6940 :     return proute;
     244             : }
     245             : 
     246             : /*
     247             :  * ExecFindPartition -- Return the ResultRelInfo for the leaf partition that
     248             :  * the tuple contained in *slot should belong to.
     249             :  *
     250             :  * If the partition's ResultRelInfo does not yet exist in 'proute' then we set
     251             :  * one up or reuse one from mtstate's resultRelInfo array.  When reusing a
     252             :  * ResultRelInfo from the mtstate we verify that the relation is a valid
     253             :  * target for INSERTs and initialize tuple routing information.
     254             :  *
     255             :  * rootResultRelInfo is the relation named in the query.
     256             :  *
     257             :  * estate must be non-NULL; we'll need it to compute any expressions in the
     258             :  * partition keys.  Also, its per-tuple contexts are used as evaluation
     259             :  * scratch space.
     260             :  *
     261             :  * If no leaf partition is found, this routine errors out with the appropriate
     262             :  * error message.  An error may also be raised if the found target partition
     263             :  * is not a valid target for an INSERT.
     264             :  */
     265             : ResultRelInfo *
     266     1002810 : ExecFindPartition(ModifyTableState *mtstate,
     267             :                   ResultRelInfo *rootResultRelInfo,
     268             :                   PartitionTupleRouting *proute,
     269             :                   TupleTableSlot *slot, EState *estate)
     270             : {
     271     1002810 :     PartitionDispatch *pd = proute->partition_dispatch_info;
     272             :     Datum       values[PARTITION_MAX_KEYS];
     273             :     bool        isnull[PARTITION_MAX_KEYS];
     274             :     Relation    rel;
     275             :     PartitionDispatch dispatch;
     276             :     PartitionDesc partdesc;
     277     1002810 :     ExprContext *ecxt = GetPerTupleExprContext(estate);
     278     1002810 :     TupleTableSlot *ecxt_scantuple_saved = ecxt->ecxt_scantuple;
     279     1002810 :     TupleTableSlot *rootslot = slot;
     280     1002810 :     TupleTableSlot *myslot = NULL;
     281             :     MemoryContext oldcxt;
     282     1002810 :     ResultRelInfo *rri = NULL;
     283             : 
     284             :     /* use per-tuple context here to avoid leaking memory */
     285     1002810 :     oldcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
     286             : 
     287             :     /*
     288             :      * First check the root table's partition constraint, if any.  No point in
     289             :      * routing the tuple if it doesn't belong in the root table itself.
     290             :      */
     291     1002810 :     if (rootResultRelInfo->ri_RelationDesc->rd_rel->relispartition)
     292        4496 :         ExecPartitionCheck(rootResultRelInfo, slot, estate, true);
     293             : 
     294             :     /* start with the root partitioned table */
     295     1002778 :     dispatch = pd[0];
     296     2117876 :     while (dispatch != NULL)
     297             :     {
     298     1115272 :         int         partidx = -1;
     299             :         bool        is_leaf;
     300             : 
     301     1115272 :         CHECK_FOR_INTERRUPTS();
     302             : 
     303     1115272 :         rel = dispatch->reldesc;
     304     1115272 :         partdesc = dispatch->partdesc;
     305             : 
     306             :         /*
     307             :          * Extract partition key from tuple. Expression evaluation machinery
     308             :          * that FormPartitionKeyDatum() invokes expects ecxt_scantuple to
     309             :          * point to the correct tuple slot.  The slot might have changed from
     310             :          * what was used for the parent table if the table of the current
     311             :          * partitioning level has different tuple descriptor from the parent.
     312             :          * So update ecxt_scantuple accordingly.
     313             :          */
     314     1115272 :         ecxt->ecxt_scantuple = slot;
     315     1115272 :         FormPartitionKeyDatum(dispatch, slot, estate, values, isnull);
     316             : 
     317             :         /*
     318             :          * If this partitioned table has no partitions or no partition for
     319             :          * these values, error out.
     320             :          */
     321     2230502 :         if (partdesc->nparts == 0 ||
     322     1115230 :             (partidx = get_partition_for_tuple(dispatch, values, isnull)) < 0)
     323             :         {
     324             :             char       *val_desc;
     325             : 
     326         154 :             val_desc = ExecBuildSlotPartitionKeyDescription(rel,
     327             :                                                             values, isnull, 64);
     328             :             Assert(OidIsValid(RelationGetRelid(rel)));
     329         154 :             ereport(ERROR,
     330             :                     (errcode(ERRCODE_CHECK_VIOLATION),
     331             :                      errmsg("no partition of relation \"%s\" found for row",
     332             :                             RelationGetRelationName(rel)),
     333             :                      val_desc ?
     334             :                      errdetail("Partition key of the failing row contains %s.",
     335             :                                val_desc) : 0,
     336             :                      errtable(rel)));
     337             :         }
     338             : 
     339     1115118 :         is_leaf = partdesc->is_leaf[partidx];
     340     1115118 :         if (is_leaf)
     341             :         {
     342             :             /*
     343             :              * We've reached the leaf -- hurray, we're done.  Look to see if
     344             :              * we've already got a ResultRelInfo for this partition.
     345             :              */
     346     1002622 :             if (likely(dispatch->indexes[partidx] >= 0))
     347             :             {
     348             :                 /* ResultRelInfo already built */
     349             :                 Assert(dispatch->indexes[partidx] < proute->num_partitions);
     350      993870 :                 rri = proute->partitions[dispatch->indexes[partidx]];
     351             :             }
     352             :             else
     353             :             {
     354             :                 /*
     355             :                  * If the partition is known in the owning ModifyTableState
     356             :                  * node, we can re-use that ResultRelInfo instead of creating
     357             :                  * a new one with ExecInitPartitionInfo().
     358             :                  */
     359        8752 :                 rri = ExecLookupResultRelByOid(mtstate,
     360        8752 :                                                partdesc->oids[partidx],
     361             :                                                true, false);
     362        8752 :                 if (rri)
     363             :                 {
     364             :                     /* Verify this ResultRelInfo allows INSERTs */
     365         488 :                     CheckValidResultRel(rri, CMD_INSERT, NIL);
     366             : 
     367             :                     /*
     368             :                      * Initialize information needed to insert this and
     369             :                      * subsequent tuples routed to this partition.
     370             :                      */
     371         488 :                     ExecInitRoutingInfo(mtstate, estate, proute, dispatch,
     372             :                                         rri, partidx, true);
     373             :                 }
     374             :                 else
     375             :                 {
     376             :                     /* We need to create a new one. */
     377        8264 :                     rri = ExecInitPartitionInfo(mtstate, estate, proute,
     378             :                                                 dispatch,
     379             :                                                 rootResultRelInfo, partidx);
     380             :                 }
     381             :             }
     382             :             Assert(rri != NULL);
     383             : 
     384             :             /* Signal to terminate the loop */
     385     1002604 :             dispatch = NULL;
     386             :         }
     387             :         else
     388             :         {
     389             :             /*
     390             :              * Partition is a sub-partitioned table; get the PartitionDispatch
     391             :              */
     392      112496 :             if (likely(dispatch->indexes[partidx] >= 0))
     393             :             {
     394             :                 /* Already built. */
     395             :                 Assert(dispatch->indexes[partidx] < proute->num_dispatch);
     396             : 
     397      111332 :                 rri = proute->nonleaf_partitions[dispatch->indexes[partidx]];
     398             : 
     399             :                 /*
     400             :                  * Move down to the next partition level and search again
     401             :                  * until we find a leaf partition that matches this tuple
     402             :                  */
     403      111332 :                 dispatch = pd[dispatch->indexes[partidx]];
     404             :             }
     405             :             else
     406             :             {
     407             :                 /* Not yet built. Do that now. */
     408             :                 PartitionDispatch subdispatch;
     409             : 
     410             :                 /*
     411             :                  * Create the new PartitionDispatch.  We pass the current one
     412             :                  * in as the parent PartitionDispatch
     413             :                  */
     414        1164 :                 subdispatch = ExecInitPartitionDispatchInfo(estate,
     415             :                                                             proute,
     416        1164 :                                                             partdesc->oids[partidx],
     417             :                                                             dispatch, partidx,
     418             :                                                             mtstate->rootResultRelInfo);
     419             :                 Assert(dispatch->indexes[partidx] >= 0 &&
     420             :                        dispatch->indexes[partidx] < proute->num_dispatch);
     421             : 
     422        1164 :                 rri = proute->nonleaf_partitions[dispatch->indexes[partidx]];
     423        1164 :                 dispatch = subdispatch;
     424             :             }
     425             : 
     426             :             /*
     427             :              * Convert the tuple to the new parent's layout, if different from
     428             :              * the previous parent.
     429             :              */
     430      112496 :             if (dispatch->tupslot)
     431             :             {
     432       61692 :                 AttrMap    *map = dispatch->tupmap;
     433       61692 :                 TupleTableSlot *tempslot = myslot;
     434             : 
     435       61692 :                 myslot = dispatch->tupslot;
     436       61692 :                 slot = execute_attr_map_slot(map, slot, myslot);
     437             : 
     438       61692 :                 if (tempslot != NULL)
     439         294 :                     ExecClearTuple(tempslot);
     440             :             }
     441             :         }
     442             : 
     443             :         /*
     444             :          * If this partition is the default one, we must check its partition
     445             :          * constraint now, which may have changed concurrently due to
     446             :          * partitions being added to the parent.
     447             :          *
     448             :          * (We do this here, and do not rely on ExecInsert doing it, because
     449             :          * we don't want to miss doing it for non-leaf partitions.)
     450             :          */
     451     1115100 :         if (partidx == partdesc->boundinfo->default_index)
     452             :         {
     453             :             /*
     454             :              * The tuple must match the partition's layout for the constraint
     455             :              * expression to be evaluated successfully.  If the partition is
     456             :              * sub-partitioned, that would already be the case due to the code
     457             :              * above, but for a leaf partition the tuple still matches the
     458             :              * parent's layout.
     459             :              *
     460             :              * Note that we have a map to convert from root to current
     461             :              * partition, but not from immediate parent to current partition.
     462             :              * So if we have to convert, do it from the root slot; if not, use
     463             :              * the root slot as-is.
     464             :              */
     465         582 :             if (is_leaf)
     466             :             {
     467         538 :                 TupleConversionMap *map = ExecGetRootToChildMap(rri, estate);
     468             : 
     469         538 :                 if (map)
     470         162 :                     slot = execute_attr_map_slot(map->attrMap, rootslot,
     471             :                                                  rri->ri_PartitionTupleSlot);
     472             :                 else
     473         376 :                     slot = rootslot;
     474             :             }
     475             : 
     476         582 :             ExecPartitionCheck(rri, slot, estate, true);
     477             :         }
     478             :     }
     479             : 
     480             :     /* Release the tuple in the lowest parent's dedicated slot. */
     481     1002604 :     if (myslot != NULL)
     482       61360 :         ExecClearTuple(myslot);
     483             :     /* and restore ecxt's scantuple */
     484     1002604 :     ecxt->ecxt_scantuple = ecxt_scantuple_saved;
     485     1002604 :     MemoryContextSwitchTo(oldcxt);
     486             : 
     487     1002604 :     return rri;
     488             : }
     489             : 
     490             : /*
     491             :  * ExecInitPartitionInfo
     492             :  *      Lock the partition and initialize ResultRelInfo.  Also setup other
     493             :  *      information for the partition and store it in the next empty slot in
     494             :  *      the proute->partitions array.
     495             :  *
     496             :  * Returns the ResultRelInfo
     497             :  */
     498             : static ResultRelInfo *
     499        8264 : ExecInitPartitionInfo(ModifyTableState *mtstate, EState *estate,
     500             :                       PartitionTupleRouting *proute,
     501             :                       PartitionDispatch dispatch,
     502             :                       ResultRelInfo *rootResultRelInfo,
     503             :                       int partidx)
     504             : {
     505        8264 :     ModifyTable *node = (ModifyTable *) mtstate->ps.plan;
     506        8264 :     Oid         partOid = dispatch->partdesc->oids[partidx];
     507             :     Relation    partrel;
     508        8264 :     int         firstVarno = mtstate->resultRelInfo[0].ri_RangeTableIndex;
     509        8264 :     Relation    firstResultRel = mtstate->resultRelInfo[0].ri_RelationDesc;
     510             :     ResultRelInfo *leaf_part_rri;
     511             :     MemoryContext oldcxt;
     512        8264 :     AttrMap    *part_attmap = NULL;
     513             :     bool        found_whole_row;
     514             : 
     515        8264 :     oldcxt = MemoryContextSwitchTo(proute->memcxt);
     516             : 
     517        8264 :     partrel = table_open(partOid, RowExclusiveLock);
     518             : 
     519        8264 :     leaf_part_rri = makeNode(ResultRelInfo);
     520        8264 :     InitResultRelInfo(leaf_part_rri,
     521             :                       partrel,
     522             :                       0,
     523             :                       rootResultRelInfo,
     524             :                       estate->es_instrument);
     525             : 
     526             :     /*
     527             :      * Verify result relation is a valid target for an INSERT.  An UPDATE of a
     528             :      * partition-key becomes a DELETE+INSERT operation, so this check is still
     529             :      * required when the operation is CMD_UPDATE.
     530             :      */
     531        8264 :     CheckValidResultRel(leaf_part_rri, CMD_INSERT, NIL);
     532             : 
     533             :     /*
     534             :      * Open partition indices.  The user may have asked to check for conflicts
     535             :      * within this leaf partition and do "nothing" instead of throwing an
     536             :      * error.  Be prepared in that case by initializing the index information
     537             :      * needed by ExecInsert() to perform speculative insertions.
     538             :      */
     539        8258 :     if (partrel->rd_rel->relhasindex &&
     540        1796 :         leaf_part_rri->ri_IndexRelationDescs == NULL)
     541        1796 :         ExecOpenIndices(leaf_part_rri,
     542        3420 :                         (node != NULL &&
     543        1624 :                          node->onConflictAction != ONCONFLICT_NONE));
     544             : 
     545             :     /*
     546             :      * Build WITH CHECK OPTION constraints for the partition.  Note that we
     547             :      * didn't build the withCheckOptionList for partitions within the planner,
     548             :      * but simple translation of varattnos will suffice.  This only occurs for
     549             :      * the INSERT case or in the case of UPDATE/MERGE tuple routing where we
     550             :      * didn't find a result rel to reuse.
     551             :      */
     552        8258 :     if (node && node->withCheckOptionLists != NIL)
     553             :     {
     554             :         List       *wcoList;
     555          96 :         List       *wcoExprs = NIL;
     556             :         ListCell   *ll;
     557             : 
     558             :         /*
     559             :          * In the case of INSERT on a partitioned table, there is only one
     560             :          * plan.  Likewise, there is only one WCO list, not one per partition.
     561             :          * For UPDATE/MERGE, there are as many WCO lists as there are plans.
     562             :          */
     563             :         Assert((node->operation == CMD_INSERT &&
     564             :                 list_length(node->withCheckOptionLists) == 1 &&
     565             :                 list_length(node->resultRelations) == 1) ||
     566             :                (node->operation == CMD_UPDATE &&
     567             :                 list_length(node->withCheckOptionLists) ==
     568             :                 list_length(node->resultRelations)) ||
     569             :                (node->operation == CMD_MERGE &&
     570             :                 list_length(node->withCheckOptionLists) ==
     571             :                 list_length(node->resultRelations)));
     572             : 
     573             :         /*
     574             :          * Use the WCO list of the first plan as a reference to calculate
     575             :          * attno's for the WCO list of this partition.  In the INSERT case,
     576             :          * that refers to the root partitioned table, whereas in the UPDATE
     577             :          * tuple routing case, that refers to the first partition in the
     578             :          * mtstate->resultRelInfo array.  In any case, both that relation and
     579             :          * this partition should have the same columns, so we should be able
     580             :          * to map attributes successfully.
     581             :          */
     582          96 :         wcoList = linitial(node->withCheckOptionLists);
     583             : 
     584             :         /*
     585             :          * Convert Vars in it to contain this partition's attribute numbers.
     586             :          */
     587             :         part_attmap =
     588          96 :             build_attrmap_by_name(RelationGetDescr(partrel),
     589             :                                   RelationGetDescr(firstResultRel),
     590             :                                   false);
     591             :         wcoList = (List *)
     592          96 :             map_variable_attnos((Node *) wcoList,
     593             :                                 firstVarno, 0,
     594             :                                 part_attmap,
     595          96 :                                 RelationGetForm(partrel)->reltype,
     596             :                                 &found_whole_row);
     597             :         /* We ignore the value of found_whole_row. */
     598             : 
     599         270 :         foreach(ll, wcoList)
     600             :         {
     601         174 :             WithCheckOption *wco = lfirst_node(WithCheckOption, ll);
     602         174 :             ExprState  *wcoExpr = ExecInitQual(castNode(List, wco->qual),
     603             :                                                &mtstate->ps);
     604             : 
     605         174 :             wcoExprs = lappend(wcoExprs, wcoExpr);
     606             :         }
     607             : 
     608          96 :         leaf_part_rri->ri_WithCheckOptions = wcoList;
     609          96 :         leaf_part_rri->ri_WithCheckOptionExprs = wcoExprs;
     610             :     }
     611             : 
     612             :     /*
     613             :      * Build the RETURNING projection for the partition.  Note that we didn't
     614             :      * build the returningList for partitions within the planner, but simple
     615             :      * translation of varattnos will suffice.  This only occurs for the INSERT
     616             :      * case or in the case of UPDATE/MERGE tuple routing where we didn't find
     617             :      * a result rel to reuse.
     618             :      */
     619        8258 :     if (node && node->returningLists != NIL)
     620             :     {
     621             :         TupleTableSlot *slot;
     622             :         ExprContext *econtext;
     623             :         List       *returningList;
     624             : 
     625             :         /* See the comment above for WCO lists. */
     626             :         Assert((node->operation == CMD_INSERT &&
     627             :                 list_length(node->returningLists) == 1 &&
     628             :                 list_length(node->resultRelations) == 1) ||
     629             :                (node->operation == CMD_UPDATE &&
     630             :                 list_length(node->returningLists) ==
     631             :                 list_length(node->resultRelations)) ||
     632             :                (node->operation == CMD_MERGE &&
     633             :                 list_length(node->returningLists) ==
     634             :                 list_length(node->resultRelations)));
     635             : 
     636             :         /*
     637             :          * Use the RETURNING list of the first plan as a reference to
     638             :          * calculate attno's for the RETURNING list of this partition.  See
     639             :          * the comment above for WCO lists for more details on why this is
     640             :          * okay.
     641             :          */
     642         206 :         returningList = linitial(node->returningLists);
     643             : 
     644             :         /*
     645             :          * Convert Vars in it to contain this partition's attribute numbers.
     646             :          */
     647         206 :         if (part_attmap == NULL)
     648             :             part_attmap =
     649         206 :                 build_attrmap_by_name(RelationGetDescr(partrel),
     650             :                                       RelationGetDescr(firstResultRel),
     651             :                                       false);
     652             :         returningList = (List *)
     653         206 :             map_variable_attnos((Node *) returningList,
     654             :                                 firstVarno, 0,
     655             :                                 part_attmap,
     656         206 :                                 RelationGetForm(partrel)->reltype,
     657             :                                 &found_whole_row);
     658             :         /* We ignore the value of found_whole_row. */
     659             : 
     660         206 :         leaf_part_rri->ri_returningList = returningList;
     661             : 
     662             :         /*
     663             :          * Initialize the projection itself.
     664             :          *
     665             :          * Use the slot and the expression context that would have been set up
     666             :          * in ExecInitModifyTable() for projection's output.
     667             :          */
     668             :         Assert(mtstate->ps.ps_ResultTupleSlot != NULL);
     669         206 :         slot = mtstate->ps.ps_ResultTupleSlot;
     670             :         Assert(mtstate->ps.ps_ExprContext != NULL);
     671         206 :         econtext = mtstate->ps.ps_ExprContext;
     672         206 :         leaf_part_rri->ri_projectReturning =
     673         206 :             ExecBuildProjectionInfo(returningList, econtext, slot,
     674             :                                     &mtstate->ps, RelationGetDescr(partrel));
     675             :     }
     676             : 
     677             :     /* Set up information needed for routing tuples to the partition. */
     678        8258 :     ExecInitRoutingInfo(mtstate, estate, proute, dispatch,
     679             :                         leaf_part_rri, partidx, false);
     680             : 
     681             :     /*
     682             :      * If there is an ON CONFLICT clause, initialize state for it.
     683             :      */
     684        8258 :     if (node && node->onConflictAction != ONCONFLICT_NONE)
     685             :     {
     686         222 :         TupleDesc   partrelDesc = RelationGetDescr(partrel);
     687         222 :         ExprContext *econtext = mtstate->ps.ps_ExprContext;
     688             :         ListCell   *lc;
     689         222 :         List       *arbiterIndexes = NIL;
     690             : 
     691             :         /*
     692             :          * If there is a list of arbiter indexes, map it to a list of indexes
     693             :          * in the partition.  We do that by scanning the partition's index
     694             :          * list and searching for ancestry relationships to each index in the
     695             :          * ancestor table.
     696             :          */
     697         222 :         if (rootResultRelInfo->ri_onConflictArbiterIndexes != NIL)
     698             :         {
     699             :             List       *childIdxs;
     700             : 
     701         172 :             childIdxs = RelationGetIndexList(leaf_part_rri->ri_RelationDesc);
     702             : 
     703         356 :             foreach(lc, childIdxs)
     704             :             {
     705         184 :                 Oid         childIdx = lfirst_oid(lc);
     706             :                 List       *ancestors;
     707             :                 ListCell   *lc2;
     708             : 
     709         184 :                 ancestors = get_partition_ancestors(childIdx);
     710         368 :                 foreach(lc2, rootResultRelInfo->ri_onConflictArbiterIndexes)
     711             :                 {
     712         184 :                     if (list_member_oid(ancestors, lfirst_oid(lc2)))
     713         172 :                         arbiterIndexes = lappend_oid(arbiterIndexes, childIdx);
     714             :                 }
     715         184 :                 list_free(ancestors);
     716             :             }
     717             :         }
     718             : 
     719             :         /*
     720             :          * If the resulting lists are of inequal length, something is wrong.
     721             :          * (This shouldn't happen, since arbiter index selection should not
     722             :          * pick up an invalid index.)
     723             :          */
     724         444 :         if (list_length(rootResultRelInfo->ri_onConflictArbiterIndexes) !=
     725         222 :             list_length(arbiterIndexes))
     726           0 :             elog(ERROR, "invalid arbiter index list");
     727         222 :         leaf_part_rri->ri_onConflictArbiterIndexes = arbiterIndexes;
     728             : 
     729             :         /*
     730             :          * In the DO UPDATE case, we have some more state to initialize.
     731             :          */
     732         222 :         if (node->onConflictAction == ONCONFLICT_UPDATE)
     733             :         {
     734         166 :             OnConflictSetState *onconfl = makeNode(OnConflictSetState);
     735             :             TupleConversionMap *map;
     736             : 
     737         166 :             map = ExecGetRootToChildMap(leaf_part_rri, estate);
     738             : 
     739             :             Assert(node->onConflictSet != NIL);
     740             :             Assert(rootResultRelInfo->ri_onConflict != NULL);
     741             : 
     742         166 :             leaf_part_rri->ri_onConflict = onconfl;
     743             : 
     744             :             /*
     745             :              * Need a separate existing slot for each partition, as the
     746             :              * partition could be of a different AM, even if the tuple
     747             :              * descriptors match.
     748             :              */
     749         166 :             onconfl->oc_Existing =
     750         166 :                 table_slot_create(leaf_part_rri->ri_RelationDesc,
     751         166 :                                   &mtstate->ps.state->es_tupleTable);
     752             : 
     753             :             /*
     754             :              * If the partition's tuple descriptor matches exactly the root
     755             :              * parent (the common case), we can re-use most of the parent's ON
     756             :              * CONFLICT SET state, skipping a bunch of work.  Otherwise, we
     757             :              * need to create state specific to this partition.
     758             :              */
     759         166 :             if (map == NULL)
     760             :             {
     761             :                 /*
     762             :                  * It's safe to reuse these from the partition root, as we
     763             :                  * only process one tuple at a time (therefore we won't
     764             :                  * overwrite needed data in slots), and the results of
     765             :                  * projections are independent of the underlying storage.
     766             :                  * Projections and where clauses themselves don't store state
     767             :                  * / are independent of the underlying storage.
     768             :                  */
     769          90 :                 onconfl->oc_ProjSlot =
     770          90 :                     rootResultRelInfo->ri_onConflict->oc_ProjSlot;
     771          90 :                 onconfl->oc_ProjInfo =
     772          90 :                     rootResultRelInfo->ri_onConflict->oc_ProjInfo;
     773          90 :                 onconfl->oc_WhereClause =
     774          90 :                     rootResultRelInfo->ri_onConflict->oc_WhereClause;
     775             :             }
     776             :             else
     777             :             {
     778             :                 List       *onconflset;
     779             :                 List       *onconflcols;
     780             : 
     781             :                 /*
     782             :                  * Translate expressions in onConflictSet to account for
     783             :                  * different attribute numbers.  For that, map partition
     784             :                  * varattnos twice: first to catch the EXCLUDED
     785             :                  * pseudo-relation (INNER_VAR), and second to handle the main
     786             :                  * target relation (firstVarno).
     787             :                  */
     788          76 :                 onconflset = copyObject(node->onConflictSet);
     789          76 :                 if (part_attmap == NULL)
     790             :                     part_attmap =
     791          70 :                         build_attrmap_by_name(RelationGetDescr(partrel),
     792             :                                               RelationGetDescr(firstResultRel),
     793             :                                               false);
     794             :                 onconflset = (List *)
     795          76 :                     map_variable_attnos((Node *) onconflset,
     796             :                                         INNER_VAR, 0,
     797             :                                         part_attmap,
     798          76 :                                         RelationGetForm(partrel)->reltype,
     799             :                                         &found_whole_row);
     800             :                 /* We ignore the value of found_whole_row. */
     801             :                 onconflset = (List *)
     802          76 :                     map_variable_attnos((Node *) onconflset,
     803             :                                         firstVarno, 0,
     804             :                                         part_attmap,
     805          76 :                                         RelationGetForm(partrel)->reltype,
     806             :                                         &found_whole_row);
     807             :                 /* We ignore the value of found_whole_row. */
     808             : 
     809             :                 /* Finally, adjust the target colnos to match the partition. */
     810          76 :                 onconflcols = adjust_partition_colnos(node->onConflictCols,
     811             :                                                       leaf_part_rri);
     812             : 
     813             :                 /* create the tuple slot for the UPDATE SET projection */
     814          76 :                 onconfl->oc_ProjSlot =
     815          76 :                     table_slot_create(partrel,
     816          76 :                                       &mtstate->ps.state->es_tupleTable);
     817             : 
     818             :                 /* build UPDATE SET projection state */
     819          76 :                 onconfl->oc_ProjInfo =
     820          76 :                     ExecBuildUpdateProjection(onconflset,
     821             :                                               true,
     822             :                                               onconflcols,
     823             :                                               partrelDesc,
     824             :                                               econtext,
     825             :                                               onconfl->oc_ProjSlot,
     826             :                                               &mtstate->ps);
     827             : 
     828             :                 /*
     829             :                  * If there is a WHERE clause, initialize state where it will
     830             :                  * be evaluated, mapping the attribute numbers appropriately.
     831             :                  * As with onConflictSet, we need to map partition varattnos
     832             :                  * to the partition's tupdesc.
     833             :                  */
     834          76 :                 if (node->onConflictWhere)
     835             :                 {
     836             :                     List       *clause;
     837             : 
     838          30 :                     clause = copyObject((List *) node->onConflictWhere);
     839             :                     clause = (List *)
     840          30 :                         map_variable_attnos((Node *) clause,
     841             :                                             INNER_VAR, 0,
     842             :                                             part_attmap,
     843          30 :                                             RelationGetForm(partrel)->reltype,
     844             :                                             &found_whole_row);
     845             :                     /* We ignore the value of found_whole_row. */
     846             :                     clause = (List *)
     847          30 :                         map_variable_attnos((Node *) clause,
     848             :                                             firstVarno, 0,
     849             :                                             part_attmap,
     850          30 :                                             RelationGetForm(partrel)->reltype,
     851             :                                             &found_whole_row);
     852             :                     /* We ignore the value of found_whole_row. */
     853          30 :                     onconfl->oc_WhereClause =
     854          30 :                         ExecInitQual((List *) clause, &mtstate->ps);
     855             :                 }
     856             :             }
     857             :         }
     858             :     }
     859             : 
     860             :     /*
     861             :      * Since we've just initialized this ResultRelInfo, it's not in any list
     862             :      * attached to the estate as yet.  Add it, so that it can be found later.
     863             :      *
     864             :      * Note that the entries in this list appear in no predetermined order,
     865             :      * because partition result rels are initialized as and when they're
     866             :      * needed.
     867             :      */
     868        8258 :     MemoryContextSwitchTo(estate->es_query_cxt);
     869        8258 :     estate->es_tuple_routing_result_relations =
     870        8258 :         lappend(estate->es_tuple_routing_result_relations,
     871             :                 leaf_part_rri);
     872             : 
     873             :     /*
     874             :      * Initialize information about this partition that's needed to handle
     875             :      * MERGE.  We take the "first" result relation's mergeActionList as
     876             :      * reference and make copy for this relation, converting stuff that
     877             :      * references attribute numbers to match this relation's.
     878             :      *
     879             :      * This duplicates much of the logic in ExecInitMerge(), so something
     880             :      * changes there, look here too.
     881             :      */
     882        8258 :     if (node && node->operation == CMD_MERGE)
     883             :     {
     884          18 :         List       *firstMergeActionList = linitial(node->mergeActionLists);
     885             :         ListCell   *lc;
     886          18 :         ExprContext *econtext = mtstate->ps.ps_ExprContext;
     887             :         Node       *joinCondition;
     888             : 
     889          18 :         if (part_attmap == NULL)
     890             :             part_attmap =
     891           6 :                 build_attrmap_by_name(RelationGetDescr(partrel),
     892             :                                       RelationGetDescr(firstResultRel),
     893             :                                       false);
     894             : 
     895          18 :         if (unlikely(!leaf_part_rri->ri_projectNewInfoValid))
     896          18 :             ExecInitMergeTupleSlots(mtstate, leaf_part_rri);
     897             : 
     898             :         /* Initialize state for join condition checking. */
     899             :         joinCondition =
     900          18 :             map_variable_attnos(linitial(node->mergeJoinConditions),
     901             :                                 firstVarno, 0,
     902             :                                 part_attmap,
     903          18 :                                 RelationGetForm(partrel)->reltype,
     904             :                                 &found_whole_row);
     905             :         /* We ignore the value of found_whole_row. */
     906          18 :         leaf_part_rri->ri_MergeJoinCondition =
     907          18 :             ExecInitQual((List *) joinCondition, &mtstate->ps);
     908             : 
     909          42 :         foreach(lc, firstMergeActionList)
     910             :         {
     911             :             /* Make a copy for this relation to be safe.  */
     912          24 :             MergeAction *action = copyObject(lfirst(lc));
     913             :             MergeActionState *action_state;
     914             : 
     915             :             /* Generate the action's state for this relation */
     916          24 :             action_state = makeNode(MergeActionState);
     917          24 :             action_state->mas_action = action;
     918             : 
     919             :             /* And put the action in the appropriate list */
     920          48 :             leaf_part_rri->ri_MergeActions[action->matchKind] =
     921          24 :                 lappend(leaf_part_rri->ri_MergeActions[action->matchKind],
     922             :                         action_state);
     923             : 
     924          24 :             switch (action->commandType)
     925             :             {
     926           6 :                 case CMD_INSERT:
     927             : 
     928             :                     /*
     929             :                      * ExecCheckPlanOutput() already done on the targetlist
     930             :                      * when "first" result relation initialized and it is same
     931             :                      * for all result relations.
     932             :                      */
     933           6 :                     action_state->mas_proj =
     934           6 :                         ExecBuildProjectionInfo(action->targetList, econtext,
     935             :                                                 leaf_part_rri->ri_newTupleSlot,
     936             :                                                 &mtstate->ps,
     937             :                                                 RelationGetDescr(partrel));
     938           6 :                     break;
     939          18 :                 case CMD_UPDATE:
     940             : 
     941             :                     /*
     942             :                      * Convert updateColnos from "first" result relation
     943             :                      * attribute numbers to this result rel's.
     944             :                      */
     945          18 :                     if (part_attmap)
     946          18 :                         action->updateColnos =
     947          18 :                             adjust_partition_colnos_using_map(action->updateColnos,
     948             :                                                               part_attmap);
     949          18 :                     action_state->mas_proj =
     950          18 :                         ExecBuildUpdateProjection(action->targetList,
     951             :                                                   true,
     952             :                                                   action->updateColnos,
     953          18 :                                                   RelationGetDescr(leaf_part_rri->ri_RelationDesc),
     954             :                                                   econtext,
     955             :                                                   leaf_part_rri->ri_newTupleSlot,
     956             :                                                   NULL);
     957          18 :                     break;
     958           0 :                 case CMD_DELETE:
     959           0 :                     break;
     960             : 
     961           0 :                 default:
     962           0 :                     elog(ERROR, "unknown action in MERGE WHEN clause");
     963             :             }
     964             : 
     965             :             /* found_whole_row intentionally ignored. */
     966          24 :             action->qual =
     967          24 :                 map_variable_attnos(action->qual,
     968             :                                     firstVarno, 0,
     969             :                                     part_attmap,
     970          24 :                                     RelationGetForm(partrel)->reltype,
     971             :                                     &found_whole_row);
     972          24 :             action_state->mas_whenqual =
     973          24 :                 ExecInitQual((List *) action->qual, &mtstate->ps);
     974             :         }
     975             :     }
     976        8258 :     MemoryContextSwitchTo(oldcxt);
     977             : 
     978        8258 :     return leaf_part_rri;
     979             : }
     980             : 
     981             : /*
     982             :  * ExecInitRoutingInfo
     983             :  *      Set up information needed for translating tuples between root
     984             :  *      partitioned table format and partition format, and keep track of it
     985             :  *      in PartitionTupleRouting.
     986             :  */
     987             : static void
     988        8746 : ExecInitRoutingInfo(ModifyTableState *mtstate,
     989             :                     EState *estate,
     990             :                     PartitionTupleRouting *proute,
     991             :                     PartitionDispatch dispatch,
     992             :                     ResultRelInfo *partRelInfo,
     993             :                     int partidx,
     994             :                     bool is_borrowed_rel)
     995             : {
     996             :     MemoryContext oldcxt;
     997             :     int         rri_index;
     998             : 
     999        8746 :     oldcxt = MemoryContextSwitchTo(proute->memcxt);
    1000             : 
    1001             :     /*
    1002             :      * Set up tuple conversion between root parent and the partition if the
    1003             :      * two have different rowtypes.  If conversion is indeed required, also
    1004             :      * initialize a slot dedicated to storing this partition's converted
    1005             :      * tuples.  Various operations that are applied to tuples after routing,
    1006             :      * such as checking constraints, will refer to this slot.
    1007             :      */
    1008        8746 :     if (ExecGetRootToChildMap(partRelInfo, estate) != NULL)
    1009             :     {
    1010        1286 :         Relation    partrel = partRelInfo->ri_RelationDesc;
    1011             : 
    1012             :         /*
    1013             :          * This pins the partition's TupleDesc, which will be released at the
    1014             :          * end of the command.
    1015             :          */
    1016        1286 :         partRelInfo->ri_PartitionTupleSlot =
    1017        1286 :             table_slot_create(partrel, &estate->es_tupleTable);
    1018             :     }
    1019             :     else
    1020        7460 :         partRelInfo->ri_PartitionTupleSlot = NULL;
    1021             : 
    1022             :     /*
    1023             :      * If the partition is a foreign table, let the FDW init itself for
    1024             :      * routing tuples to the partition.
    1025             :      */
    1026        8746 :     if (partRelInfo->ri_FdwRoutine != NULL &&
    1027          84 :         partRelInfo->ri_FdwRoutine->BeginForeignInsert != NULL)
    1028          84 :         partRelInfo->ri_FdwRoutine->BeginForeignInsert(mtstate, partRelInfo);
    1029             : 
    1030             :     /*
    1031             :      * Determine if the FDW supports batch insert and determine the batch size
    1032             :      * (a FDW may support batching, but it may be disabled for the
    1033             :      * server/table or for this particular query).
    1034             :      *
    1035             :      * If the FDW does not support batching, we set the batch size to 1.
    1036             :      */
    1037        8734 :     if (partRelInfo->ri_FdwRoutine != NULL &&
    1038          72 :         partRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
    1039          72 :         partRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
    1040          72 :         partRelInfo->ri_BatchSize =
    1041          72 :             partRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(partRelInfo);
    1042             :     else
    1043        8662 :         partRelInfo->ri_BatchSize = 1;
    1044             : 
    1045             :     Assert(partRelInfo->ri_BatchSize >= 1);
    1046             : 
    1047        8734 :     partRelInfo->ri_CopyMultiInsertBuffer = NULL;
    1048             : 
    1049             :     /*
    1050             :      * Keep track of it in the PartitionTupleRouting->partitions array.
    1051             :      */
    1052             :     Assert(dispatch->indexes[partidx] == -1);
    1053             : 
    1054        8734 :     rri_index = proute->num_partitions++;
    1055             : 
    1056             :     /* Allocate or enlarge the array, as needed */
    1057        8734 :     if (proute->num_partitions >= proute->max_partitions)
    1058             :     {
    1059        6672 :         if (proute->max_partitions == 0)
    1060             :         {
    1061        6660 :             proute->max_partitions = 8;
    1062        6660 :             proute->partitions = (ResultRelInfo **)
    1063        6660 :                 palloc(sizeof(ResultRelInfo *) * proute->max_partitions);
    1064        6660 :             proute->is_borrowed_rel = (bool *)
    1065        6660 :                 palloc(sizeof(bool) * proute->max_partitions);
    1066             :         }
    1067             :         else
    1068             :         {
    1069          12 :             proute->max_partitions *= 2;
    1070          12 :             proute->partitions = (ResultRelInfo **)
    1071          12 :                 repalloc(proute->partitions, sizeof(ResultRelInfo *) *
    1072          12 :                          proute->max_partitions);
    1073          12 :             proute->is_borrowed_rel = (bool *)
    1074          12 :                 repalloc(proute->is_borrowed_rel, sizeof(bool) *
    1075          12 :                          proute->max_partitions);
    1076             :         }
    1077             :     }
    1078             : 
    1079        8734 :     proute->partitions[rri_index] = partRelInfo;
    1080        8734 :     proute->is_borrowed_rel[rri_index] = is_borrowed_rel;
    1081        8734 :     dispatch->indexes[partidx] = rri_index;
    1082             : 
    1083        8734 :     MemoryContextSwitchTo(oldcxt);
    1084        8734 : }
    1085             : 
    1086             : /*
    1087             :  * ExecInitPartitionDispatchInfo
    1088             :  *      Lock the partitioned table (if not locked already) and initialize
    1089             :  *      PartitionDispatch for a partitioned table and store it in the next
    1090             :  *      available slot in the proute->partition_dispatch_info array.  Also,
    1091             :  *      record the index into this array in the parent_pd->indexes[] array in
    1092             :  *      the partidx element so that we can properly retrieve the newly created
    1093             :  *      PartitionDispatch later.
    1094             :  */
    1095             : static PartitionDispatch
    1096        8104 : ExecInitPartitionDispatchInfo(EState *estate,
    1097             :                               PartitionTupleRouting *proute, Oid partoid,
    1098             :                               PartitionDispatch parent_pd, int partidx,
    1099             :                               ResultRelInfo *rootResultRelInfo)
    1100             : {
    1101             :     Relation    rel;
    1102             :     PartitionDesc partdesc;
    1103             :     PartitionDispatch pd;
    1104             :     int         dispatchidx;
    1105             :     MemoryContext oldcxt;
    1106             : 
    1107             :     /*
    1108             :      * For data modification, it is better that executor does not include
    1109             :      * partitions being detached, except when running in snapshot-isolation
    1110             :      * mode.  This means that a read-committed transaction immediately gets a
    1111             :      * "no partition for tuple" error when a tuple is inserted into a
    1112             :      * partition that's being detached concurrently, but a transaction in
    1113             :      * repeatable-read mode can still use such a partition.
    1114             :      */
    1115        8104 :     if (estate->es_partition_directory == NULL)
    1116        6928 :         estate->es_partition_directory =
    1117        6928 :             CreatePartitionDirectory(estate->es_query_cxt,
    1118             :                                      !IsolationUsesXactSnapshot());
    1119             : 
    1120        8104 :     oldcxt = MemoryContextSwitchTo(proute->memcxt);
    1121             : 
    1122             :     /*
    1123             :      * Only sub-partitioned tables need to be locked here.  The root
    1124             :      * partitioned table will already have been locked as it's referenced in
    1125             :      * the query's rtable.
    1126             :      */
    1127        8104 :     if (partoid != RelationGetRelid(proute->partition_root))
    1128        1164 :         rel = table_open(partoid, RowExclusiveLock);
    1129             :     else
    1130        6940 :         rel = proute->partition_root;
    1131        8104 :     partdesc = PartitionDirectoryLookup(estate->es_partition_directory, rel);
    1132             : 
    1133        8104 :     pd = (PartitionDispatch) palloc(offsetof(PartitionDispatchData, indexes) +
    1134        8104 :                                     partdesc->nparts * sizeof(int));
    1135        8104 :     pd->reldesc = rel;
    1136        8104 :     pd->key = RelationGetPartitionKey(rel);
    1137        8104 :     pd->keystate = NIL;
    1138        8104 :     pd->partdesc = partdesc;
    1139        8104 :     if (parent_pd != NULL)
    1140             :     {
    1141        1164 :         TupleDesc   tupdesc = RelationGetDescr(rel);
    1142             : 
    1143             :         /*
    1144             :          * For sub-partitioned tables where the column order differs from its
    1145             :          * direct parent partitioned table, we must store a tuple table slot
    1146             :          * initialized with its tuple descriptor and a tuple conversion map to
    1147             :          * convert a tuple from its parent's rowtype to its own.  This is to
    1148             :          * make sure that we are looking at the correct row using the correct
    1149             :          * tuple descriptor when computing its partition key for tuple
    1150             :          * routing.
    1151             :          */
    1152        1164 :         pd->tupmap = build_attrmap_by_name_if_req(RelationGetDescr(parent_pd->reldesc),
    1153             :                                                   tupdesc,
    1154             :                                                   false);
    1155        1164 :         pd->tupslot = pd->tupmap ?
    1156        1164 :             MakeSingleTupleTableSlot(tupdesc, &TTSOpsVirtual) : NULL;
    1157             :     }
    1158             :     else
    1159             :     {
    1160             :         /* Not required for the root partitioned table */
    1161        6940 :         pd->tupmap = NULL;
    1162        6940 :         pd->tupslot = NULL;
    1163             :     }
    1164             : 
    1165             :     /*
    1166             :      * Initialize with -1 to signify that the corresponding partition's
    1167             :      * ResultRelInfo or PartitionDispatch has not been created yet.
    1168             :      */
    1169        8104 :     memset(pd->indexes, -1, sizeof(int) * partdesc->nparts);
    1170             : 
    1171             :     /* Track in PartitionTupleRouting for later use */
    1172        8104 :     dispatchidx = proute->num_dispatch++;
    1173             : 
    1174             :     /* Allocate or enlarge the array, as needed */
    1175        8104 :     if (proute->num_dispatch >= proute->max_dispatch)
    1176             :     {
    1177        6940 :         if (proute->max_dispatch == 0)
    1178             :         {
    1179        6940 :             proute->max_dispatch = 4;
    1180        6940 :             proute->partition_dispatch_info = (PartitionDispatch *)
    1181        6940 :                 palloc(sizeof(PartitionDispatch) * proute->max_dispatch);
    1182        6940 :             proute->nonleaf_partitions = (ResultRelInfo **)
    1183        6940 :                 palloc(sizeof(ResultRelInfo *) * proute->max_dispatch);
    1184             :         }
    1185             :         else
    1186             :         {
    1187           0 :             proute->max_dispatch *= 2;
    1188           0 :             proute->partition_dispatch_info = (PartitionDispatch *)
    1189           0 :                 repalloc(proute->partition_dispatch_info,
    1190           0 :                          sizeof(PartitionDispatch) * proute->max_dispatch);
    1191           0 :             proute->nonleaf_partitions = (ResultRelInfo **)
    1192           0 :                 repalloc(proute->nonleaf_partitions,
    1193           0 :                          sizeof(ResultRelInfo *) * proute->max_dispatch);
    1194             :         }
    1195             :     }
    1196        8104 :     proute->partition_dispatch_info[dispatchidx] = pd;
    1197             : 
    1198             :     /*
    1199             :      * If setting up a PartitionDispatch for a sub-partitioned table, we may
    1200             :      * also need a minimally valid ResultRelInfo for checking the partition
    1201             :      * constraint later; set that up now.
    1202             :      */
    1203        8104 :     if (parent_pd)
    1204             :     {
    1205        1164 :         ResultRelInfo *rri = makeNode(ResultRelInfo);
    1206             : 
    1207        1164 :         InitResultRelInfo(rri, rel, 0, rootResultRelInfo, 0);
    1208        1164 :         proute->nonleaf_partitions[dispatchidx] = rri;
    1209             :     }
    1210             :     else
    1211        6940 :         proute->nonleaf_partitions[dispatchidx] = NULL;
    1212             : 
    1213             :     /*
    1214             :      * Finally, if setting up a PartitionDispatch for a sub-partitioned table,
    1215             :      * install a downlink in the parent to allow quick descent.
    1216             :      */
    1217        8104 :     if (parent_pd)
    1218             :     {
    1219             :         Assert(parent_pd->indexes[partidx] == -1);
    1220        1164 :         parent_pd->indexes[partidx] = dispatchidx;
    1221             :     }
    1222             : 
    1223        8104 :     MemoryContextSwitchTo(oldcxt);
    1224             : 
    1225        8104 :     return pd;
    1226             : }
    1227             : 
    1228             : /*
    1229             :  * ExecCleanupTupleRouting -- Clean up objects allocated for partition tuple
    1230             :  * routing.
    1231             :  *
    1232             :  * Close all the partitioned tables, leaf partitions, and their indices.
    1233             :  */
    1234             : void
    1235        6212 : ExecCleanupTupleRouting(ModifyTableState *mtstate,
    1236             :                         PartitionTupleRouting *proute)
    1237             : {
    1238             :     int         i;
    1239             : 
    1240             :     /*
    1241             :      * Remember, proute->partition_dispatch_info[0] corresponds to the root
    1242             :      * partitioned table, which we must not try to close, because it is the
    1243             :      * main target table of the query that will be closed by callers such as
    1244             :      * ExecEndPlan() or DoCopy(). Also, tupslot is NULL for the root
    1245             :      * partitioned table.
    1246             :      */
    1247        7152 :     for (i = 1; i < proute->num_dispatch; i++)
    1248             :     {
    1249         940 :         PartitionDispatch pd = proute->partition_dispatch_info[i];
    1250             : 
    1251         940 :         table_close(pd->reldesc, NoLock);
    1252             : 
    1253         940 :         if (pd->tupslot)
    1254         448 :             ExecDropSingleTupleTableSlot(pd->tupslot);
    1255             :     }
    1256             : 
    1257       14436 :     for (i = 0; i < proute->num_partitions; i++)
    1258             :     {
    1259        8224 :         ResultRelInfo *resultRelInfo = proute->partitions[i];
    1260             : 
    1261             :         /* Allow any FDWs to shut down */
    1262        8224 :         if (resultRelInfo->ri_FdwRoutine != NULL &&
    1263          68 :             resultRelInfo->ri_FdwRoutine->EndForeignInsert != NULL)
    1264          68 :             resultRelInfo->ri_FdwRoutine->EndForeignInsert(mtstate->ps.state,
    1265             :                                                            resultRelInfo);
    1266             : 
    1267             :         /*
    1268             :          * Close it if it's not one of the result relations borrowed from the
    1269             :          * owning ModifyTableState; those will be closed by ExecEndPlan().
    1270             :          */
    1271        8224 :         if (proute->is_borrowed_rel[i])
    1272         440 :             continue;
    1273             : 
    1274        7784 :         ExecCloseIndices(resultRelInfo);
    1275        7784 :         table_close(resultRelInfo->ri_RelationDesc, NoLock);
    1276             :     }
    1277        6212 : }
    1278             : 
    1279             : /* ----------------
    1280             :  *      FormPartitionKeyDatum
    1281             :  *          Construct values[] and isnull[] arrays for the partition key
    1282             :  *          of a tuple.
    1283             :  *
    1284             :  *  pd              Partition dispatch object of the partitioned table
    1285             :  *  slot            Heap tuple from which to extract partition key
    1286             :  *  estate          executor state for evaluating any partition key
    1287             :  *                  expressions (must be non-NULL)
    1288             :  *  values          Array of partition key Datums (output area)
    1289             :  *  isnull          Array of is-null indicators (output area)
    1290             :  *
    1291             :  * the ecxt_scantuple slot of estate's per-tuple expr context must point to
    1292             :  * the heap tuple passed in.
    1293             :  * ----------------
    1294             :  */
    1295             : static void
    1296     1115272 : FormPartitionKeyDatum(PartitionDispatch pd,
    1297             :                       TupleTableSlot *slot,
    1298             :                       EState *estate,
    1299             :                       Datum *values,
    1300             :                       bool *isnull)
    1301             : {
    1302             :     ListCell   *partexpr_item;
    1303             :     int         i;
    1304             : 
    1305     1115272 :     if (pd->key->partexprs != NIL && pd->keystate == NIL)
    1306             :     {
    1307             :         /* Check caller has set up context correctly */
    1308             :         Assert(estate != NULL &&
    1309             :                GetPerTupleExprContext(estate)->ecxt_scantuple == slot);
    1310             : 
    1311             :         /* First time through, set up expression evaluation state */
    1312         534 :         pd->keystate = ExecPrepareExprList(pd->key->partexprs, estate);
    1313             :     }
    1314             : 
    1315     1115272 :     partexpr_item = list_head(pd->keystate);
    1316     2253344 :     for (i = 0; i < pd->key->partnatts; i++)
    1317             :     {
    1318     1138072 :         AttrNumber  keycol = pd->key->partattrs[i];
    1319             :         Datum       datum;
    1320             :         bool        isNull;
    1321             : 
    1322     1138072 :         if (keycol != 0)
    1323             :         {
    1324             :             /* Plain column; get the value directly from the heap tuple */
    1325     1050448 :             datum = slot_getattr(slot, keycol, &isNull);
    1326             :         }
    1327             :         else
    1328             :         {
    1329             :             /* Expression; need to evaluate it */
    1330       87624 :             if (partexpr_item == NULL)
    1331           0 :                 elog(ERROR, "wrong number of partition key expressions");
    1332       87624 :             datum = ExecEvalExprSwitchContext((ExprState *) lfirst(partexpr_item),
    1333       87624 :                                               GetPerTupleExprContext(estate),
    1334             :                                               &isNull);
    1335       87624 :             partexpr_item = lnext(pd->keystate, partexpr_item);
    1336             :         }
    1337     1138072 :         values[i] = datum;
    1338     1138072 :         isnull[i] = isNull;
    1339             :     }
    1340             : 
    1341     1115272 :     if (partexpr_item != NULL)
    1342           0 :         elog(ERROR, "wrong number of partition key expressions");
    1343     1115272 : }
    1344             : 
    1345             : /*
    1346             :  * The number of times the same partition must be found in a row before we
    1347             :  * switch from a binary search for the given values to just checking if the
    1348             :  * values belong to the last found partition.  This must be above 0.
    1349             :  */
    1350             : #define PARTITION_CACHED_FIND_THRESHOLD         16
    1351             : 
    1352             : /*
    1353             :  * get_partition_for_tuple
    1354             :  *      Finds partition of relation which accepts the partition key specified
    1355             :  *      in values and isnull.
    1356             :  *
    1357             :  * Calling this function can be quite expensive when LIST and RANGE
    1358             :  * partitioned tables have many partitions.  This is due to the binary search
    1359             :  * that's done to find the correct partition.  Many of the use cases for LIST
    1360             :  * and RANGE partitioned tables make it likely that the same partition is
    1361             :  * found in subsequent ExecFindPartition() calls.  This is especially true for
    1362             :  * cases such as RANGE partitioned tables on a TIMESTAMP column where the
    1363             :  * partition key is the current time.  When asked to find a partition for a
    1364             :  * RANGE or LIST partitioned table, we record the partition index and datum
    1365             :  * offset we've found for the given 'values' in the PartitionDesc (which is
    1366             :  * stored in relcache), and if we keep finding the same partition
    1367             :  * PARTITION_CACHED_FIND_THRESHOLD times in a row, then we'll enable caching
    1368             :  * logic and instead of performing a binary search to find the correct
    1369             :  * partition, we'll just double-check that 'values' still belong to the last
    1370             :  * found partition, and if so, we'll return that partition index, thus
    1371             :  * skipping the need for the binary search.  If we fail to match the last
    1372             :  * partition when double checking, then we fall back on doing a binary search.
    1373             :  * In this case, unless we find 'values' belong to the DEFAULT partition,
    1374             :  * we'll reset the number of times we've hit the same partition so that we
    1375             :  * don't attempt to use the cache again until we've found that partition at
    1376             :  * least PARTITION_CACHED_FIND_THRESHOLD times in a row.
    1377             :  *
    1378             :  * For cases where the partition changes on each lookup, the amount of
    1379             :  * additional work required just amounts to recording the last found partition
    1380             :  * and bound offset then resetting the found counter.  This is cheap and does
    1381             :  * not appear to cause any meaningful slowdowns for such cases.
    1382             :  *
    1383             :  * No caching of partitions is done when the last found partition is the
    1384             :  * DEFAULT or NULL partition.  For the case of the DEFAULT partition, there
    1385             :  * is no bound offset storing the matching datum, so we cannot confirm the
    1386             :  * indexes match.  For the NULL partition, this is just so cheap, there's no
    1387             :  * sense in caching.
    1388             :  *
    1389             :  * Return value is index of the partition (>= 0 and < partdesc->nparts) if one
    1390             :  * found or -1 if none found.
    1391             :  */
    1392             : static int
    1393     1115230 : get_partition_for_tuple(PartitionDispatch pd, Datum *values, bool *isnull)
    1394             : {
    1395     1115230 :     int         bound_offset = -1;
    1396     1115230 :     int         part_index = -1;
    1397     1115230 :     PartitionKey key = pd->key;
    1398     1115230 :     PartitionDesc partdesc = pd->partdesc;
    1399     1115230 :     PartitionBoundInfo boundinfo = partdesc->boundinfo;
    1400             : 
    1401             :     /*
    1402             :      * In the switch statement below, when we perform a cached lookup for
    1403             :      * RANGE and LIST partitioned tables, if we find that the last found
    1404             :      * partition matches the 'values', we return the partition index right
    1405             :      * away.  We do this instead of breaking out of the switch as we don't
    1406             :      * want to execute the code about the DEFAULT partition or do any updates
    1407             :      * for any of the cache-related fields.  That would be a waste of effort
    1408             :      * as we already know it's not the DEFAULT partition and have no need to
    1409             :      * increment the number of times we found the same partition any higher
    1410             :      * than PARTITION_CACHED_FIND_THRESHOLD.
    1411             :      */
    1412             : 
    1413             :     /* Route as appropriate based on partitioning strategy. */
    1414     1115230 :     switch (key->strategy)
    1415             :     {
    1416      212726 :         case PARTITION_STRATEGY_HASH:
    1417             :             {
    1418             :                 uint64      rowHash;
    1419             : 
    1420             :                 /* hash partitioning is too cheap to bother caching */
    1421      212726 :                 rowHash = compute_partition_hash_value(key->partnatts,
    1422             :                                                        key->partsupfunc,
    1423      212726 :                                                        key->partcollation,
    1424             :                                                        values, isnull);
    1425             : 
    1426             :                 /*
    1427             :                  * HASH partitions can't have a DEFAULT partition and we don't
    1428             :                  * do any caching work for them, so just return the part index
    1429             :                  */
    1430      212726 :                 return boundinfo->indexes[rowHash % boundinfo->nindexes];
    1431             :             }
    1432             : 
    1433      170992 :         case PARTITION_STRATEGY_LIST:
    1434      170992 :             if (isnull[0])
    1435             :             {
    1436             :                 /* this is far too cheap to bother doing any caching */
    1437         132 :                 if (partition_bound_accepts_nulls(boundinfo))
    1438             :                 {
    1439             :                     /*
    1440             :                      * When there is a NULL partition we just return that
    1441             :                      * directly.  We don't have a bound_offset so it's not
    1442             :                      * valid to drop into the code after the switch which
    1443             :                      * checks and updates the cache fields.  We perhaps should
    1444             :                      * be invalidating the details of the last cached
    1445             :                      * partition but there's no real need to.  Keeping those
    1446             :                      * fields set gives a chance at matching to the cached
    1447             :                      * partition on the next lookup.
    1448             :                      */
    1449         102 :                     return boundinfo->null_index;
    1450             :                 }
    1451             :             }
    1452             :             else
    1453             :             {
    1454             :                 bool        equal;
    1455             : 
    1456      170860 :                 if (partdesc->last_found_count >= PARTITION_CACHED_FIND_THRESHOLD)
    1457             :                 {
    1458       23892 :                     int         last_datum_offset = partdesc->last_found_datum_index;
    1459       23892 :                     Datum       lastDatum = boundinfo->datums[last_datum_offset][0];
    1460             :                     int32       cmpval;
    1461             : 
    1462             :                     /* does the last found datum index match this datum? */
    1463       23892 :                     cmpval = DatumGetInt32(FunctionCall2Coll(&key->partsupfunc[0],
    1464       23892 :                                                              key->partcollation[0],
    1465             :                                                              lastDatum,
    1466             :                                                              values[0]));
    1467             : 
    1468       23892 :                     if (cmpval == 0)
    1469       23538 :                         return boundinfo->indexes[last_datum_offset];
    1470             : 
    1471             :                     /* fall-through and do a manual lookup */
    1472             :                 }
    1473             : 
    1474      147322 :                 bound_offset = partition_list_bsearch(key->partsupfunc,
    1475             :                                                       key->partcollation,
    1476             :                                                       boundinfo,
    1477             :                                                       values[0], &equal);
    1478      147322 :                 if (bound_offset >= 0 && equal)
    1479      146924 :                     part_index = boundinfo->indexes[bound_offset];
    1480             :             }
    1481      147352 :             break;
    1482             : 
    1483      731512 :         case PARTITION_STRATEGY_RANGE:
    1484             :             {
    1485      731512 :                 bool        equal = false,
    1486      731512 :                             range_partkey_has_null = false;
    1487             :                 int         i;
    1488             : 
    1489             :                 /*
    1490             :                  * No range includes NULL, so this will be accepted by the
    1491             :                  * default partition if there is one, and otherwise rejected.
    1492             :                  */
    1493     1485404 :                 for (i = 0; i < key->partnatts; i++)
    1494             :                 {
    1495      753946 :                     if (isnull[i])
    1496             :                     {
    1497          54 :                         range_partkey_has_null = true;
    1498          54 :                         break;
    1499             :                     }
    1500             :                 }
    1501             : 
    1502             :                 /* NULLs belong in the DEFAULT partition */
    1503      731512 :                 if (range_partkey_has_null)
    1504          54 :                     break;
    1505             : 
    1506      731458 :                 if (partdesc->last_found_count >= PARTITION_CACHED_FIND_THRESHOLD)
    1507             :                 {
    1508      244056 :                     int         last_datum_offset = partdesc->last_found_datum_index;
    1509      244056 :                     Datum      *lastDatums = boundinfo->datums[last_datum_offset];
    1510      244056 :                     PartitionRangeDatumKind *kind = boundinfo->kind[last_datum_offset];
    1511             :                     int32       cmpval;
    1512             : 
    1513             :                     /* check if the value is >= to the lower bound */
    1514      244056 :                     cmpval = partition_rbound_datum_cmp(key->partsupfunc,
    1515             :                                                         key->partcollation,
    1516             :                                                         lastDatums,
    1517             :                                                         kind,
    1518             :                                                         values,
    1519      244056 :                                                         key->partnatts);
    1520             : 
    1521             :                     /*
    1522             :                      * If it's equal to the lower bound then no need to check
    1523             :                      * the upper bound.
    1524             :                      */
    1525      244056 :                     if (cmpval == 0)
    1526      243806 :                         return boundinfo->indexes[last_datum_offset + 1];
    1527             : 
    1528      238158 :                     if (cmpval < 0 && last_datum_offset + 1 < boundinfo->ndatums)
    1529             :                     {
    1530             :                         /* check if the value is below the upper bound */
    1531      238128 :                         lastDatums = boundinfo->datums[last_datum_offset + 1];
    1532      238128 :                         kind = boundinfo->kind[last_datum_offset + 1];
    1533      238128 :                         cmpval = partition_rbound_datum_cmp(key->partsupfunc,
    1534             :                                                             key->partcollation,
    1535             :                                                             lastDatums,
    1536             :                                                             kind,
    1537             :                                                             values,
    1538      238128 :                                                             key->partnatts);
    1539             : 
    1540      238128 :                         if (cmpval > 0)
    1541      237908 :                             return boundinfo->indexes[last_datum_offset + 1];
    1542             :                     }
    1543             :                     /* fall-through and do a manual lookup */
    1544             :                 }
    1545             : 
    1546      487652 :                 bound_offset = partition_range_datum_bsearch(key->partsupfunc,
    1547             :                                                              key->partcollation,
    1548             :                                                              boundinfo,
    1549      487652 :                                                              key->partnatts,
    1550             :                                                              values,
    1551             :                                                              &equal);
    1552             : 
    1553             :                 /*
    1554             :                  * The bound at bound_offset is less than or equal to the
    1555             :                  * tuple value, so the bound at offset+1 is the upper bound of
    1556             :                  * the partition we're looking for, if there actually exists
    1557             :                  * one.
    1558             :                  */
    1559      487652 :                 part_index = boundinfo->indexes[bound_offset + 1];
    1560             :             }
    1561      487652 :             break;
    1562             : 
    1563           0 :         default:
    1564           0 :             elog(ERROR, "unexpected partition strategy: %d",
    1565             :                  (int) key->strategy);
    1566             :     }
    1567             : 
    1568             :     /*
    1569             :      * part_index < 0 means we failed to find a partition of this parent. Use
    1570             :      * the default partition, if there is one.
    1571             :      */
    1572      635058 :     if (part_index < 0)
    1573             :     {
    1574             :         /*
    1575             :          * No need to reset the cache fields here.  The next set of values
    1576             :          * might end up belonging to the cached partition, so leaving the
    1577             :          * cache alone improves the chances of a cache hit on the next lookup.
    1578             :          */
    1579         694 :         return boundinfo->default_index;
    1580             :     }
    1581             : 
    1582             :     /* we should only make it here when the code above set bound_offset */
    1583             :     Assert(bound_offset >= 0);
    1584             : 
    1585             :     /*
    1586             :      * Attend to the cache fields.  If the bound_offset matches the last
    1587             :      * cached bound offset then we've found the same partition as last time,
    1588             :      * so bump the count by one.  If all goes well, we'll eventually reach
    1589             :      * PARTITION_CACHED_FIND_THRESHOLD and try the cache path next time
    1590             :      * around.  Otherwise, we'll reset the cache count back to 1 to mark that
    1591             :      * we've found this partition for the first time.
    1592             :      */
    1593      634364 :     if (bound_offset == partdesc->last_found_datum_index)
    1594      437496 :         partdesc->last_found_count++;
    1595             :     else
    1596             :     {
    1597      196868 :         partdesc->last_found_count = 1;
    1598      196868 :         partdesc->last_found_part_index = part_index;
    1599      196868 :         partdesc->last_found_datum_index = bound_offset;
    1600             :     }
    1601             : 
    1602      634364 :     return part_index;
    1603             : }
    1604             : 
    1605             : /*
    1606             :  * ExecBuildSlotPartitionKeyDescription
    1607             :  *
    1608             :  * This works very much like BuildIndexValueDescription() and is currently
    1609             :  * used for building error messages when ExecFindPartition() fails to find
    1610             :  * partition for a row.
    1611             :  */
    1612             : static char *
    1613         154 : ExecBuildSlotPartitionKeyDescription(Relation rel,
    1614             :                                      Datum *values,
    1615             :                                      bool *isnull,
    1616             :                                      int maxfieldlen)
    1617             : {
    1618             :     StringInfoData buf;
    1619         154 :     PartitionKey key = RelationGetPartitionKey(rel);
    1620         154 :     int         partnatts = get_partition_natts(key);
    1621             :     int         i;
    1622         154 :     Oid         relid = RelationGetRelid(rel);
    1623             :     AclResult   aclresult;
    1624             : 
    1625         154 :     if (check_enable_rls(relid, InvalidOid, true) == RLS_ENABLED)
    1626           0 :         return NULL;
    1627             : 
    1628             :     /* If the user has table-level access, just go build the description. */
    1629         154 :     aclresult = pg_class_aclcheck(relid, GetUserId(), ACL_SELECT);
    1630         154 :     if (aclresult != ACLCHECK_OK)
    1631             :     {
    1632             :         /*
    1633             :          * Step through the columns of the partition key and make sure the
    1634             :          * user has SELECT rights on all of them.
    1635             :          */
    1636          24 :         for (i = 0; i < partnatts; i++)
    1637             :         {
    1638          18 :             AttrNumber  attnum = get_partition_col_attnum(key, i);
    1639             : 
    1640             :             /*
    1641             :              * If this partition key column is an expression, we return no
    1642             :              * detail rather than try to figure out what column(s) the
    1643             :              * expression includes and if the user has SELECT rights on them.
    1644             :              */
    1645          30 :             if (attnum == InvalidAttrNumber ||
    1646          12 :                 pg_attribute_aclcheck(relid, attnum, GetUserId(),
    1647             :                                       ACL_SELECT) != ACLCHECK_OK)
    1648          12 :                 return NULL;
    1649             :         }
    1650             :     }
    1651             : 
    1652         142 :     initStringInfo(&buf);
    1653         142 :     appendStringInfo(&buf, "(%s) = (",
    1654             :                      pg_get_partkeydef_columns(relid, true));
    1655             : 
    1656         338 :     for (i = 0; i < partnatts; i++)
    1657             :     {
    1658             :         char       *val;
    1659             :         int         vallen;
    1660             : 
    1661         196 :         if (isnull[i])
    1662          30 :             val = "null";
    1663             :         else
    1664             :         {
    1665             :             Oid         foutoid;
    1666             :             bool        typisvarlena;
    1667             : 
    1668         166 :             getTypeOutputInfo(get_partition_col_typid(key, i),
    1669             :                               &foutoid, &typisvarlena);
    1670         166 :             val = OidOutputFunctionCall(foutoid, values[i]);
    1671             :         }
    1672             : 
    1673         196 :         if (i > 0)
    1674          54 :             appendStringInfoString(&buf, ", ");
    1675             : 
    1676             :         /* truncate if needed */
    1677         196 :         vallen = strlen(val);
    1678         196 :         if (vallen <= maxfieldlen)
    1679         196 :             appendBinaryStringInfo(&buf, val, vallen);
    1680             :         else
    1681             :         {
    1682           0 :             vallen = pg_mbcliplen(val, vallen, maxfieldlen);
    1683           0 :             appendBinaryStringInfo(&buf, val, vallen);
    1684           0 :             appendStringInfoString(&buf, "...");
    1685             :         }
    1686             :     }
    1687             : 
    1688         142 :     appendStringInfoChar(&buf, ')');
    1689             : 
    1690         142 :     return buf.data;
    1691             : }
    1692             : 
    1693             : /*
    1694             :  * adjust_partition_colnos
    1695             :  *      Adjust the list of UPDATE target column numbers to account for
    1696             :  *      attribute differences between the parent and the partition.
    1697             :  *
    1698             :  * Note: mustn't be called if no adjustment is required.
    1699             :  */
    1700             : static List *
    1701          76 : adjust_partition_colnos(List *colnos, ResultRelInfo *leaf_part_rri)
    1702             : {
    1703          76 :     TupleConversionMap *map = ExecGetChildToRootMap(leaf_part_rri);
    1704             : 
    1705             :     Assert(map != NULL);
    1706             : 
    1707          76 :     return adjust_partition_colnos_using_map(colnos, map->attrMap);
    1708             : }
    1709             : 
    1710             : /*
    1711             :  * adjust_partition_colnos_using_map
    1712             :  *      Like adjust_partition_colnos, but uses a caller-supplied map instead
    1713             :  *      of assuming to map from the "root" result relation.
    1714             :  *
    1715             :  * Note: mustn't be called if no adjustment is required.
    1716             :  */
    1717             : static List *
    1718          94 : adjust_partition_colnos_using_map(List *colnos, AttrMap *attrMap)
    1719             : {
    1720          94 :     List       *new_colnos = NIL;
    1721             :     ListCell   *lc;
    1722             : 
    1723             :     Assert(attrMap != NULL);    /* else we shouldn't be here */
    1724             : 
    1725         232 :     foreach(lc, colnos)
    1726             :     {
    1727         138 :         AttrNumber  parentattrno = lfirst_int(lc);
    1728             : 
    1729         138 :         if (parentattrno <= 0 ||
    1730         138 :             parentattrno > attrMap->maplen ||
    1731         138 :             attrMap->attnums[parentattrno - 1] == 0)
    1732           0 :             elog(ERROR, "unexpected attno %d in target column list",
    1733             :                  parentattrno);
    1734         138 :         new_colnos = lappend_int(new_colnos,
    1735         138 :                                  attrMap->attnums[parentattrno - 1]);
    1736             :     }
    1737             : 
    1738          94 :     return new_colnos;
    1739             : }
    1740             : 
    1741             : /*-------------------------------------------------------------------------
    1742             :  * Run-Time Partition Pruning Support.
    1743             :  *
    1744             :  * The following series of functions exist to support the removal of unneeded
    1745             :  * subplans for queries against partitioned tables.  The supporting functions
    1746             :  * here are designed to work with any plan type which supports an arbitrary
    1747             :  * number of subplans, e.g. Append, MergeAppend.
    1748             :  *
    1749             :  * When pruning involves comparison of a partition key to a constant, it's
    1750             :  * done by the planner.  However, if we have a comparison to a non-constant
    1751             :  * but not volatile expression, that presents an opportunity for run-time
    1752             :  * pruning by the executor, allowing irrelevant partitions to be skipped
    1753             :  * dynamically.
    1754             :  *
    1755             :  * We must distinguish expressions containing PARAM_EXEC Params from
    1756             :  * expressions that don't contain those.  Even though a PARAM_EXEC Param is
    1757             :  * considered to be a stable expression, it can change value from one plan
    1758             :  * node scan to the next during query execution.  Stable comparison
    1759             :  * expressions that don't involve such Params allow partition pruning to be
    1760             :  * done once during executor startup.  Expressions that do involve such Params
    1761             :  * require us to prune separately for each scan of the parent plan node.
    1762             :  *
    1763             :  * Note that pruning away unneeded subplans during executor startup has the
    1764             :  * added benefit of not having to initialize the unneeded subplans at all.
    1765             :  *
    1766             :  *
    1767             :  * Functions:
    1768             :  *
    1769             :  * ExecDoInitialPruning:
    1770             :  *      Perform runtime "initial" pruning, if necessary, to determine the set
    1771             :  *      of child subnodes that need to be initialized during ExecInitNode() for
    1772             :  *      all plan nodes that contain a PartitionPruneInfo.  This also locks the
    1773             :  *      leaf partitions whose subnodes will be initialized if needed.
    1774             :  *
    1775             :  * ExecInitPartitionExecPruning:
    1776             :  *      Updates the PartitionPruneState found at given part_prune_index in
    1777             :  *      EState.es_part_prune_states for use during "exec" pruning if required.
    1778             :  *      Also returns the set of subplans to initialize that would be stored at
    1779             :  *      part_prune_index in EState.es_part_prune_result by
    1780             :  *      ExecDoInitialPruning().  Maps in PartitionPruneState are updated to
    1781             :  *      account for initial pruning possibly having eliminated some of the
    1782             :  *      subplans.
    1783             :  *
    1784             :  * ExecFindMatchingSubPlans:
    1785             :  *      Returns indexes of matching subplans after evaluating the expressions
    1786             :  *      that are safe to evaluate at a given point.  This function is first
    1787             :  *      called during ExecDoInitialPruning() to find the initially matching
    1788             :  *      subplans based on performing the initial pruning steps and then must be
    1789             :  *      called again each time the value of a Param listed in
    1790             :  *      PartitionPruneState's 'execparamids' changes.
    1791             :  *-------------------------------------------------------------------------
    1792             :  */
    1793             : 
    1794             : 
    1795             : /*
    1796             :  * ExecDoInitialPruning
    1797             :  *      Perform runtime "initial" pruning, if necessary, to determine the set
    1798             :  *      of child subnodes that need to be initialized during ExecInitNode() for
    1799             :  *      plan nodes that support partition pruning.  This also locks the leaf
    1800             :  *      partitions whose subnodes will be initialized if needed.
    1801             :  *
    1802             :  * This function iterates over each PartitionPruneInfo entry in
    1803             :  * estate->es_part_prune_infos. For each entry, it creates a PartitionPruneState
    1804             :  * and adds it to es_part_prune_states.  ExecInitPartitionExecPruning() accesses
    1805             :  * these states through their corresponding indexes in es_part_prune_states and
    1806             :  * assign each state to the parent node's PlanState, from where it will be used
    1807             :  * for "exec" pruning.
    1808             :  *
    1809             :  * If initial pruning steps exist for a PartitionPruneInfo entry, this function
    1810             :  * executes those pruning steps and stores the result as a bitmapset of valid
    1811             :  * child subplans, identifying which subplans should be initialized for
    1812             :  * execution.  The results are saved in estate->es_part_prune_results.
    1813             :  *
    1814             :  * If no initial pruning is performed for a given PartitionPruneInfo, a NULL
    1815             :  * entry  is still added to es_part_prune_results to maintain alignment with
    1816             :  * es_part_prune_infos. This ensures that ExecInitPartitionExecPruning() can
    1817             :  * use the same index to retrieve the pruning results.
    1818             :  */
    1819             : void
    1820      661116 : ExecDoInitialPruning(EState *estate)
    1821             : {
    1822             :     ListCell   *lc;
    1823      661116 :     List       *locked_relids = NIL;
    1824             : 
    1825      661866 :     foreach(lc, estate->es_part_prune_infos)
    1826             :     {
    1827         750 :         PartitionPruneInfo *pruneinfo = lfirst_node(PartitionPruneInfo, lc);
    1828             :         PartitionPruneState *prunestate;
    1829         750 :         Bitmapset  *validsubplans = NULL;
    1830         750 :         Bitmapset  *all_leafpart_rtis = NULL;
    1831         750 :         Bitmapset  *validsubplan_rtis = NULL;
    1832             : 
    1833             :         /* Create and save the PartitionPruneState. */
    1834         750 :         prunestate = CreatePartitionPruneState(estate, pruneinfo,
    1835             :                                                &all_leafpart_rtis);
    1836         750 :         estate->es_part_prune_states = lappend(estate->es_part_prune_states,
    1837             :                                                prunestate);
    1838             : 
    1839             :         /*
    1840             :          * Perform initial pruning steps, if any, and save the result
    1841             :          * bitmapset or NULL as described in the header comment.
    1842             :          */
    1843         750 :         if (prunestate->do_initial_prune)
    1844         398 :             validsubplans = ExecFindMatchingSubPlans(prunestate, true,
    1845             :                                                      &validsubplan_rtis);
    1846             :         else
    1847         352 :             validsubplan_rtis = all_leafpart_rtis;
    1848             : 
    1849         750 :         if (ExecShouldLockRelations(estate))
    1850             :         {
    1851         148 :             int         rtindex = -1;
    1852             : 
    1853         324 :             while ((rtindex = bms_next_member(validsubplan_rtis,
    1854             :                                               rtindex)) >= 0)
    1855             :             {
    1856         176 :                 RangeTblEntry *rte = exec_rt_fetch(rtindex, estate);
    1857             : 
    1858             :                 Assert(rte->rtekind == RTE_RELATION &&
    1859             :                        rte->rellockmode != NoLock);
    1860         176 :                 LockRelationOid(rte->relid, rte->rellockmode);
    1861         176 :                 locked_relids = lappend_int(locked_relids, rtindex);
    1862             :             }
    1863             :         }
    1864         750 :         estate->es_unpruned_relids = bms_add_members(estate->es_unpruned_relids,
    1865             :                                                      validsubplan_rtis);
    1866         750 :         estate->es_part_prune_results = lappend(estate->es_part_prune_results,
    1867             :                                                 validsubplans);
    1868             :     }
    1869             : 
    1870             :     /*
    1871             :      * Release the useless locks if the plan won't be executed.  This is the
    1872             :      * same as what CheckCachedPlan() in plancache.c does.
    1873             :      */
    1874      661116 :     if (!ExecPlanStillValid(estate))
    1875             :     {
    1876           0 :         foreach(lc, locked_relids)
    1877             :         {
    1878           0 :             RangeTblEntry *rte = exec_rt_fetch(lfirst_int(lc), estate);
    1879             : 
    1880           0 :             UnlockRelationOid(rte->relid, rte->rellockmode);
    1881             :         }
    1882             :     }
    1883      661116 : }
    1884             : 
    1885             : /*
    1886             :  * ExecInitPartitionExecPruning
    1887             :  *      Initialize the data structures needed for runtime "exec" partition
    1888             :  *      pruning and return the result of initial pruning, if available.
    1889             :  *
    1890             :  * 'relids' identifies the relation to which both the parent plan and the
    1891             :  * PartitionPruneInfo given by 'part_prune_index' belong.
    1892             :  *
    1893             :  * On return, *initially_valid_subplans is assigned the set of indexes of
    1894             :  * child subplans that must be initialized along with the parent plan node.
    1895             :  * Initial pruning would have been performed by ExecDoInitialPruning(), if
    1896             :  * necessary, and the bitmapset of surviving subplans' indexes would have
    1897             :  * been stored as the part_prune_index'th element of
    1898             :  * EState.es_part_prune_results.
    1899             :  *
    1900             :  * If subplans were indeed pruned during initial pruning, the subplan_map
    1901             :  * arrays in the returned PartitionPruneState are re-sequenced to exclude those
    1902             :  * subplans, but only if the maps will be needed for subsequent execution
    1903             :  * pruning passes.
    1904             :  */
    1905             : PartitionPruneState *
    1906         750 : ExecInitPartitionExecPruning(PlanState *planstate,
    1907             :                              int n_total_subplans,
    1908             :                              int part_prune_index,
    1909             :                              Bitmapset *relids,
    1910             :                              Bitmapset **initially_valid_subplans)
    1911             : {
    1912             :     PartitionPruneState *prunestate;
    1913         750 :     EState     *estate = planstate->state;
    1914             :     PartitionPruneInfo *pruneinfo;
    1915             : 
    1916             :     /* Obtain the pruneinfo we need. */
    1917         750 :     pruneinfo = list_nth_node(PartitionPruneInfo, estate->es_part_prune_infos,
    1918             :                               part_prune_index);
    1919             : 
    1920             :     /* Its relids better match the plan node's or the planner messed up. */
    1921         750 :     if (!bms_equal(relids, pruneinfo->relids))
    1922           0 :         elog(ERROR, "wrong pruneinfo with relids=%s found at part_prune_index=%d contained in plan node with relids=%s",
    1923             :              bmsToString(pruneinfo->relids), part_prune_index,
    1924             :              bmsToString(relids));
    1925             : 
    1926             :     /*
    1927             :      * The PartitionPruneState would have been created by
    1928             :      * ExecDoInitialPruning() and stored as the part_prune_index'th element of
    1929             :      * EState.es_part_prune_states.
    1930             :      */
    1931         750 :     prunestate = list_nth(estate->es_part_prune_states, part_prune_index);
    1932             :     Assert(prunestate != NULL);
    1933             : 
    1934             :     /* Use the result of initial pruning done by ExecDoInitialPruning(). */
    1935         750 :     if (prunestate->do_initial_prune)
    1936         398 :         *initially_valid_subplans = list_nth_node(Bitmapset,
    1937             :                                                   estate->es_part_prune_results,
    1938             :                                                   part_prune_index);
    1939             :     else
    1940             :     {
    1941             :         /* No pruning, so we'll need to initialize all subplans */
    1942             :         Assert(n_total_subplans > 0);
    1943         352 :         *initially_valid_subplans = bms_add_range(NULL, 0,
    1944             :                                                   n_total_subplans - 1);
    1945             :     }
    1946             : 
    1947             :     /*
    1948             :      * The exec pruning state must also be initialized, if needed, before it
    1949             :      * can be used for pruning during execution.
    1950             :      *
    1951             :      * This also re-sequences subplan indexes contained in prunestate to
    1952             :      * account for any that were removed due to initial pruning; refer to the
    1953             :      * condition in InitExecPartitionPruneContexts() that is used to determine
    1954             :      * whether to do this.  If no exec pruning needs to be done, we would thus
    1955             :      * leave the maps to be in an invalid invalid state, but that's ok since
    1956             :      * that data won't be consulted again (cf initial Assert in
    1957             :      * ExecFindMatchingSubPlans).
    1958             :      */
    1959         750 :     if (prunestate->do_exec_prune)
    1960         394 :         InitExecPartitionPruneContexts(prunestate, planstate,
    1961             :                                        *initially_valid_subplans,
    1962             :                                        n_total_subplans);
    1963             : 
    1964         750 :     return prunestate;
    1965             : }
    1966             : 
    1967             : /*
    1968             :  * CreatePartitionPruneState
    1969             :  *      Build the data structure required for calling ExecFindMatchingSubPlans
    1970             :  *
    1971             :  * This includes PartitionPruneContexts (stored in each
    1972             :  * PartitionedRelPruningData corresponding to a PartitionedRelPruneInfo),
    1973             :  * which hold the ExprStates needed to evaluate pruning expressions, and
    1974             :  * mapping arrays to convert partition indexes from the pruning logic
    1975             :  * into subplan indexes in the parent plan node's list of child subplans.
    1976             :  *
    1977             :  * 'pruneinfo' is a PartitionPruneInfo as generated by
    1978             :  * make_partition_pruneinfo.  Here we build a PartitionPruneState containing a
    1979             :  * PartitionPruningData for each partitioning hierarchy (i.e., each sublist of
    1980             :  * pruneinfo->prune_infos), each of which contains a PartitionedRelPruningData
    1981             :  * for each PartitionedRelPruneInfo appearing in that sublist.  This two-level
    1982             :  * system is needed to keep from confusing the different hierarchies when a
    1983             :  * UNION ALL contains multiple partitioned tables as children.  The data
    1984             :  * stored in each PartitionedRelPruningData can be re-used each time we
    1985             :  * re-evaluate which partitions match the pruning steps provided in each
    1986             :  * PartitionedRelPruneInfo.
    1987             :  *
    1988             :  * Note that only the PartitionPruneContexts for initial pruning are
    1989             :  * initialized here. Those required for exec pruning are initialized later in
    1990             :  * ExecInitPartitionExecPruning(), as they depend on the availability of the
    1991             :  * parent plan node's PlanState.
    1992             :  *
    1993             :  * If initial pruning steps are to be skipped (e.g., during EXPLAIN
    1994             :  * (GENERIC_PLAN)), *all_leafpart_rtis will be populated with the RT indexes of
    1995             :  * all leaf partitions whose scanning subnode is included in the parent plan
    1996             :  * node's list of child plans. The caller must add these RT indexes to
    1997             :  * estate->es_unpruned_relids.
    1998             :  */
    1999             : static PartitionPruneState *
    2000         750 : CreatePartitionPruneState(EState *estate, PartitionPruneInfo *pruneinfo,
    2001             :                           Bitmapset **all_leafpart_rtis)
    2002             : {
    2003             :     PartitionPruneState *prunestate;
    2004             :     int         n_part_hierarchies;
    2005             :     ListCell   *lc;
    2006             :     int         i;
    2007             : 
    2008             :     /*
    2009             :      * Expression context that will be used by partkey_datum_from_expr() to
    2010             :      * evaluate expressions for comparison against partition bounds.
    2011             :      */
    2012         750 :     ExprContext *econtext = CreateExprContext(estate);
    2013             : 
    2014             :     /* For data reading, executor always includes detached partitions */
    2015         750 :     if (estate->es_partition_directory == NULL)
    2016         720 :         estate->es_partition_directory =
    2017         720 :             CreatePartitionDirectory(estate->es_query_cxt, false);
    2018             : 
    2019         750 :     n_part_hierarchies = list_length(pruneinfo->prune_infos);
    2020             :     Assert(n_part_hierarchies > 0);
    2021             : 
    2022             :     /*
    2023             :      * Allocate the data structure
    2024             :      */
    2025             :     prunestate = (PartitionPruneState *)
    2026         750 :         palloc(offsetof(PartitionPruneState, partprunedata) +
    2027             :                sizeof(PartitionPruningData *) * n_part_hierarchies);
    2028             : 
    2029             :     /* Save ExprContext for use during InitExecPartitionPruneContexts(). */
    2030         750 :     prunestate->econtext = econtext;
    2031         750 :     prunestate->execparamids = NULL;
    2032             :     /* other_subplans can change at runtime, so we need our own copy */
    2033         750 :     prunestate->other_subplans = bms_copy(pruneinfo->other_subplans);
    2034         750 :     prunestate->do_initial_prune = false;    /* may be set below */
    2035         750 :     prunestate->do_exec_prune = false;   /* may be set below */
    2036         750 :     prunestate->num_partprunedata = n_part_hierarchies;
    2037             : 
    2038             :     /*
    2039             :      * Create a short-term memory context which we'll use when making calls to
    2040             :      * the partition pruning functions.  This avoids possible memory leaks,
    2041             :      * since the pruning functions call comparison functions that aren't under
    2042             :      * our control.
    2043             :      */
    2044         750 :     prunestate->prune_context =
    2045         750 :         AllocSetContextCreate(CurrentMemoryContext,
    2046             :                               "Partition Prune",
    2047             :                               ALLOCSET_DEFAULT_SIZES);
    2048             : 
    2049         750 :     i = 0;
    2050        1524 :     foreach(lc, pruneinfo->prune_infos)
    2051             :     {
    2052         774 :         List       *partrelpruneinfos = lfirst_node(List, lc);
    2053         774 :         int         npartrelpruneinfos = list_length(partrelpruneinfos);
    2054             :         PartitionPruningData *prunedata;
    2055             :         ListCell   *lc2;
    2056             :         int         j;
    2057             : 
    2058             :         prunedata = (PartitionPruningData *)
    2059         774 :             palloc(offsetof(PartitionPruningData, partrelprunedata) +
    2060         774 :                    npartrelpruneinfos * sizeof(PartitionedRelPruningData));
    2061         774 :         prunestate->partprunedata[i] = prunedata;
    2062         774 :         prunedata->num_partrelprunedata = npartrelpruneinfos;
    2063             : 
    2064         774 :         j = 0;
    2065        2358 :         foreach(lc2, partrelpruneinfos)
    2066             :         {
    2067        1584 :             PartitionedRelPruneInfo *pinfo = lfirst_node(PartitionedRelPruneInfo, lc2);
    2068        1584 :             PartitionedRelPruningData *pprune = &prunedata->partrelprunedata[j];
    2069             :             Relation    partrel;
    2070             :             PartitionDesc partdesc;
    2071             :             PartitionKey partkey;
    2072             : 
    2073             :             /*
    2074             :              * We can rely on the copies of the partitioned table's partition
    2075             :              * key and partition descriptor appearing in its relcache entry,
    2076             :              * because that entry will be held open and locked for the
    2077             :              * duration of this executor run.
    2078             :              */
    2079        1584 :             partrel = ExecGetRangeTableRelation(estate, pinfo->rtindex);
    2080             : 
    2081             :             /* Remember for InitExecPartitionPruneContext(). */
    2082        1584 :             pprune->partrel = partrel;
    2083             : 
    2084        1584 :             partkey = RelationGetPartitionKey(partrel);
    2085        1584 :             partdesc = PartitionDirectoryLookup(estate->es_partition_directory,
    2086             :                                                 partrel);
    2087             : 
    2088             :             /*
    2089             :              * Initialize the subplan_map and subpart_map.
    2090             :              *
    2091             :              * The set of partitions that exist now might not be the same that
    2092             :              * existed when the plan was made.  The normal case is that it is;
    2093             :              * optimize for that case with a quick comparison, and just copy
    2094             :              * the subplan_map and make subpart_map, leafpart_rti_map point to
    2095             :              * the ones in PruneInfo.
    2096             :              *
    2097             :              * For the case where they aren't identical, we could have more
    2098             :              * partitions on either side; or even exactly the same number of
    2099             :              * them on both but the set of OIDs doesn't match fully.  Handle
    2100             :              * this by creating new subplan_map and subpart_map arrays that
    2101             :              * corresponds to the ones in the PruneInfo where the new
    2102             :              * partition descriptor's OIDs match.  Any that don't match can be
    2103             :              * set to -1, as if they were pruned.  By construction, both
    2104             :              * arrays are in partition bounds order.
    2105             :              */
    2106        1584 :             pprune->nparts = partdesc->nparts;
    2107        1584 :             pprune->subplan_map = palloc(sizeof(int) * partdesc->nparts);
    2108             : 
    2109        1584 :             if (partdesc->nparts == pinfo->nparts &&
    2110        1582 :                 memcmp(partdesc->oids, pinfo->relid_map,
    2111        1582 :                        sizeof(int) * partdesc->nparts) == 0)
    2112             :             {
    2113        1460 :                 pprune->subpart_map = pinfo->subpart_map;
    2114        1460 :                 pprune->leafpart_rti_map = pinfo->leafpart_rti_map;
    2115        1460 :                 memcpy(pprune->subplan_map, pinfo->subplan_map,
    2116        1460 :                        sizeof(int) * pinfo->nparts);
    2117             :             }
    2118             :             else
    2119             :             {
    2120         124 :                 int         pd_idx = 0;
    2121             :                 int         pp_idx;
    2122             : 
    2123             :                 /*
    2124             :                  * When the partition arrays are not identical, there could be
    2125             :                  * some new ones but it's also possible that one was removed;
    2126             :                  * we cope with both situations by walking the arrays and
    2127             :                  * discarding those that don't match.
    2128             :                  *
    2129             :                  * If the number of partitions on both sides match, it's still
    2130             :                  * possible that one partition has been detached and another
    2131             :                  * attached.  Cope with that by creating a map that skips any
    2132             :                  * mismatches.
    2133             :                  */
    2134         124 :                 pprune->subpart_map = palloc(sizeof(int) * partdesc->nparts);
    2135         124 :                 pprune->leafpart_rti_map = palloc(sizeof(int) * partdesc->nparts);
    2136             : 
    2137         528 :                 for (pp_idx = 0; pp_idx < partdesc->nparts; pp_idx++)
    2138             :                 {
    2139             :                     /* Skip any InvalidOid relid_map entries */
    2140         624 :                     while (pd_idx < pinfo->nparts &&
    2141         504 :                            !OidIsValid(pinfo->relid_map[pd_idx]))
    2142         220 :                         pd_idx++;
    2143             : 
    2144         404 :             recheck:
    2145         404 :                     if (pd_idx < pinfo->nparts &&
    2146         284 :                         pinfo->relid_map[pd_idx] == partdesc->oids[pp_idx])
    2147             :                     {
    2148             :                         /* match... */
    2149         182 :                         pprune->subplan_map[pp_idx] =
    2150         182 :                             pinfo->subplan_map[pd_idx];
    2151         182 :                         pprune->subpart_map[pp_idx] =
    2152         182 :                             pinfo->subpart_map[pd_idx];
    2153         182 :                         pprune->leafpart_rti_map[pp_idx] =
    2154         182 :                             pinfo->leafpart_rti_map[pd_idx];
    2155         182 :                         pd_idx++;
    2156         182 :                         continue;
    2157             :                     }
    2158             : 
    2159             :                     /*
    2160             :                      * There isn't an exact match in the corresponding
    2161             :                      * positions of both arrays.  Peek ahead in
    2162             :                      * pinfo->relid_map to see if we have a match for the
    2163             :                      * current partition in partdesc.  Normally if a match
    2164             :                      * exists it's just one element ahead, and it means the
    2165             :                      * planner saw one extra partition that we no longer see
    2166             :                      * now (its concurrent detach finished just in between);
    2167             :                      * so we skip that one by updating pd_idx to the new
    2168             :                      * location and jumping above.  We can then continue to
    2169             :                      * match the rest of the elements after skipping the OID
    2170             :                      * with no match; no future matches are tried for the
    2171             :                      * element that was skipped, because we know the arrays to
    2172             :                      * be in the same order.
    2173             :                      *
    2174             :                      * If we don't see a match anywhere in the rest of the
    2175             :                      * pinfo->relid_map array, that means we see an element
    2176             :                      * now that the planner didn't see, so mark that one as
    2177             :                      * pruned and move on.
    2178             :                      */
    2179         288 :                     for (int pd_idx2 = pd_idx + 1; pd_idx2 < pinfo->nparts; pd_idx2++)
    2180             :                     {
    2181          66 :                         if (pd_idx2 >= pinfo->nparts)
    2182           0 :                             break;
    2183          66 :                         if (pinfo->relid_map[pd_idx2] == partdesc->oids[pp_idx])
    2184             :                         {
    2185           0 :                             pd_idx = pd_idx2;
    2186           0 :                             goto recheck;
    2187             :                         }
    2188             :                     }
    2189             : 
    2190         222 :                     pprune->subpart_map[pp_idx] = -1;
    2191         222 :                     pprune->subplan_map[pp_idx] = -1;
    2192         222 :                     pprune->leafpart_rti_map[pp_idx] = 0;
    2193             :                 }
    2194             :             }
    2195             : 
    2196             :             /* present_parts is also subject to later modification */
    2197        1584 :             pprune->present_parts = bms_copy(pinfo->present_parts);
    2198             : 
    2199             :             /*
    2200             :              * Only initial_context is initialized here.  exec_context is
    2201             :              * initialized during ExecInitPartitionExecPruning() when the
    2202             :              * parent plan's PlanState is available.
    2203             :              *
    2204             :              * Note that we must skip execution-time (both "init" and "exec")
    2205             :              * partition pruning in EXPLAIN (GENERIC_PLAN), since parameter
    2206             :              * values may be missing.
    2207             :              */
    2208        1584 :             pprune->initial_pruning_steps = pinfo->initial_pruning_steps;
    2209        1584 :             if (pinfo->initial_pruning_steps &&
    2210         506 :                 !(econtext->ecxt_estate->es_top_eflags & EXEC_FLAG_EXPLAIN_GENERIC))
    2211             :             {
    2212         500 :                 InitPartitionPruneContext(&pprune->initial_context,
    2213             :                                           pprune->initial_pruning_steps,
    2214             :                                           partdesc, partkey, NULL,
    2215             :                                           econtext);
    2216             :                 /* Record whether initial pruning is needed at any level */
    2217         500 :                 prunestate->do_initial_prune = true;
    2218             :             }
    2219        1584 :             pprune->exec_pruning_steps = pinfo->exec_pruning_steps;
    2220        1584 :             if (pinfo->exec_pruning_steps &&
    2221         508 :                 !(econtext->ecxt_estate->es_top_eflags & EXEC_FLAG_EXPLAIN_GENERIC))
    2222             :             {
    2223             :                 /* Record whether exec pruning is needed at any level */
    2224         508 :                 prunestate->do_exec_prune = true;
    2225             :             }
    2226             : 
    2227             :             /*
    2228             :              * Accumulate the IDs of all PARAM_EXEC Params affecting the
    2229             :              * partitioning decisions at this plan node.
    2230             :              */
    2231        3168 :             prunestate->execparamids = bms_add_members(prunestate->execparamids,
    2232        1584 :                                                        pinfo->execparamids);
    2233             : 
    2234             :             /*
    2235             :              * Return all leaf partition indexes if we're skipping pruning in
    2236             :              * the EXPLAIN (GENERIC_PLAN) case.
    2237             :              */
    2238        1584 :             if (pinfo->initial_pruning_steps && !prunestate->do_initial_prune)
    2239             :             {
    2240           6 :                 int         part_index = -1;
    2241             : 
    2242          18 :                 while ((part_index = bms_next_member(pprune->present_parts,
    2243             :                                                      part_index)) >= 0)
    2244             :                 {
    2245          12 :                     Index       rtindex = pprune->leafpart_rti_map[part_index];
    2246             : 
    2247          12 :                     if (rtindex)
    2248          12 :                         *all_leafpart_rtis = bms_add_member(*all_leafpart_rtis,
    2249             :                                                             rtindex);
    2250             :                 }
    2251             :             }
    2252             : 
    2253        1584 :             j++;
    2254             :         }
    2255         774 :         i++;
    2256             :     }
    2257             : 
    2258         750 :     return prunestate;
    2259             : }
    2260             : 
    2261             : /*
    2262             :  * Initialize a PartitionPruneContext for the given list of pruning steps.
    2263             :  */
    2264             : static void
    2265        1008 : InitPartitionPruneContext(PartitionPruneContext *context,
    2266             :                           List *pruning_steps,
    2267             :                           PartitionDesc partdesc,
    2268             :                           PartitionKey partkey,
    2269             :                           PlanState *planstate,
    2270             :                           ExprContext *econtext)
    2271             : {
    2272             :     int         n_steps;
    2273             :     int         partnatts;
    2274             :     ListCell   *lc;
    2275             : 
    2276        1008 :     n_steps = list_length(pruning_steps);
    2277             : 
    2278        1008 :     context->strategy = partkey->strategy;
    2279        1008 :     context->partnatts = partnatts = partkey->partnatts;
    2280        1008 :     context->nparts = partdesc->nparts;
    2281        1008 :     context->boundinfo = partdesc->boundinfo;
    2282        1008 :     context->partcollation = partkey->partcollation;
    2283        1008 :     context->partsupfunc = partkey->partsupfunc;
    2284             : 
    2285             :     /* We'll look up type-specific support functions as needed */
    2286        1008 :     context->stepcmpfuncs = (FmgrInfo *)
    2287        1008 :         palloc0(sizeof(FmgrInfo) * n_steps * partnatts);
    2288             : 
    2289        1008 :     context->ppccontext = CurrentMemoryContext;
    2290        1008 :     context->planstate = planstate;
    2291        1008 :     context->exprcontext = econtext;
    2292             : 
    2293             :     /* Initialize expression state for each expression we need */
    2294        1008 :     context->exprstates = (ExprState **)
    2295        1008 :         palloc0(sizeof(ExprState *) * n_steps * partnatts);
    2296        2678 :     foreach(lc, pruning_steps)
    2297             :     {
    2298        1670 :         PartitionPruneStepOp *step = (PartitionPruneStepOp *) lfirst(lc);
    2299        1670 :         ListCell   *lc2 = list_head(step->exprs);
    2300             :         int         keyno;
    2301             : 
    2302             :         /* not needed for other step kinds */
    2303        1670 :         if (!IsA(step, PartitionPruneStepOp))
    2304         286 :             continue;
    2305             : 
    2306             :         Assert(list_length(step->exprs) <= partnatts);
    2307             : 
    2308        2918 :         for (keyno = 0; keyno < partnatts; keyno++)
    2309             :         {
    2310        1534 :             if (bms_is_member(keyno, step->nullkeys))
    2311           6 :                 continue;
    2312             : 
    2313        1528 :             if (lc2 != NULL)
    2314             :             {
    2315        1432 :                 Expr       *expr = lfirst(lc2);
    2316             : 
    2317             :                 /* not needed for Consts */
    2318        1432 :                 if (!IsA(expr, Const))
    2319             :                 {
    2320        1338 :                     int         stateidx = PruneCxtStateIdx(partnatts,
    2321             :                                                             step->step.step_id,
    2322             :                                                             keyno);
    2323             : 
    2324             :                     /*
    2325             :                      * When planstate is NULL, pruning_steps is known not to
    2326             :                      * contain any expressions that depend on the parent plan.
    2327             :                      * Information of any available EXTERN parameters must be
    2328             :                      * passed explicitly in that case, which the caller must
    2329             :                      * have made available via econtext.
    2330             :                      */
    2331        1338 :                     if (planstate == NULL)
    2332         764 :                         context->exprstates[stateidx] =
    2333         764 :                             ExecInitExprWithParams(expr,
    2334             :                                                    econtext->ecxt_param_list_info);
    2335             :                     else
    2336         574 :                         context->exprstates[stateidx] =
    2337         574 :                             ExecInitExpr(expr, context->planstate);
    2338             :                 }
    2339        1432 :                 lc2 = lnext(step->exprs, lc2);
    2340             :             }
    2341             :         }
    2342             :     }
    2343        1008 : }
    2344             : 
    2345             : /*
    2346             :  * InitExecPartitionPruneContexts
    2347             :  *      Initialize exec pruning contexts deferred by CreatePartitionPruneState()
    2348             :  *
    2349             :  * This function finalizes exec pruning setup for a PartitionPruneState by
    2350             :  * initializing contexts for pruning steps that require the parent plan's
    2351             :  * PlanState. It iterates over PartitionPruningData entries and sets up the
    2352             :  * necessary execution contexts for pruning during query execution.
    2353             :  *
    2354             :  * Also fix the mapping of partition indexes to subplan indexes contained in
    2355             :  * prunestate by considering the new list of subplans that survived initial
    2356             :  * pruning.
    2357             :  *
    2358             :  * Current values of the indexes present in PartitionPruneState count all the
    2359             :  * subplans that would be present before initial pruning was done.  If initial
    2360             :  * pruning got rid of some of the subplans, any subsequent pruning passes will
    2361             :  * be looking at a different set of target subplans to choose from than those
    2362             :  * in the pre-initial-pruning set, so the maps in PartitionPruneState
    2363             :  * containing those indexes must be updated to reflect the new indexes of
    2364             :  * subplans in the post-initial-pruning set.
    2365             :  */
    2366             : static void
    2367         394 : InitExecPartitionPruneContexts(PartitionPruneState *prunestate,
    2368             :                                PlanState *parent_plan,
    2369             :                                Bitmapset *initially_valid_subplans,
    2370             :                                int n_total_subplans)
    2371             : {
    2372             :     EState     *estate;
    2373         394 :     int        *new_subplan_indexes = NULL;
    2374             :     Bitmapset  *new_other_subplans;
    2375             :     int         i;
    2376             :     int         newidx;
    2377         394 :     bool        fix_subplan_map = false;
    2378             : 
    2379             :     Assert(prunestate->do_exec_prune);
    2380             :     Assert(parent_plan != NULL);
    2381         394 :     estate = parent_plan->state;
    2382             : 
    2383             :     /*
    2384             :      * No need to fix subplans maps if initial pruning didn't eliminate any
    2385             :      * subplans.
    2386             :      */
    2387         394 :     if (bms_num_members(initially_valid_subplans) < n_total_subplans)
    2388             :     {
    2389          48 :         fix_subplan_map = true;
    2390             : 
    2391             :         /*
    2392             :          * First we must build a temporary array which maps old subplan
    2393             :          * indexes to new ones.  For convenience of initialization, we use
    2394             :          * 1-based indexes in this array and leave pruned items as 0.
    2395             :          */
    2396          48 :         new_subplan_indexes = (int *) palloc0(sizeof(int) * n_total_subplans);
    2397          48 :         newidx = 1;
    2398          48 :         i = -1;
    2399         186 :         while ((i = bms_next_member(initially_valid_subplans, i)) >= 0)
    2400             :         {
    2401             :             Assert(i < n_total_subplans);
    2402         138 :             new_subplan_indexes[i] = newidx++;
    2403             :         }
    2404             :     }
    2405             : 
    2406             :     /*
    2407             :      * Now we can update each PartitionedRelPruneInfo's subplan_map with new
    2408             :      * subplan indexes.  We must also recompute its present_parts bitmap.
    2409             :      */
    2410         812 :     for (i = 0; i < prunestate->num_partprunedata; i++)
    2411             :     {
    2412         418 :         PartitionPruningData *prunedata = prunestate->partprunedata[i];
    2413             :         int         j;
    2414             : 
    2415             :         /*
    2416             :          * Within each hierarchy, we perform this loop in back-to-front order
    2417             :          * so that we determine present_parts for the lowest-level partitioned
    2418             :          * tables first.  This way we can tell whether a sub-partitioned
    2419             :          * table's partitions were entirely pruned so we can exclude it from
    2420             :          * the current level's present_parts.
    2421             :          */
    2422        1292 :         for (j = prunedata->num_partrelprunedata - 1; j >= 0; j--)
    2423             :         {
    2424         874 :             PartitionedRelPruningData *pprune = &prunedata->partrelprunedata[j];
    2425         874 :             int         nparts = pprune->nparts;
    2426             :             int         k;
    2427             : 
    2428             :             /* Initialize PartitionPruneContext for exec pruning, if needed. */
    2429         874 :             if (pprune->exec_pruning_steps != NIL)
    2430             :             {
    2431             :                 PartitionKey partkey;
    2432             :                 PartitionDesc partdesc;
    2433             : 
    2434             :                 /*
    2435             :                  * See the comment in CreatePartitionPruneState() regarding
    2436             :                  * the usage of partdesc and partkey.
    2437             :                  */
    2438         508 :                 partkey = RelationGetPartitionKey(pprune->partrel);
    2439         508 :                 partdesc = PartitionDirectoryLookup(estate->es_partition_directory,
    2440             :                                                     pprune->partrel);
    2441             : 
    2442         508 :                 InitPartitionPruneContext(&pprune->exec_context,
    2443             :                                           pprune->exec_pruning_steps,
    2444             :                                           partdesc, partkey, parent_plan,
    2445             :                                           prunestate->econtext);
    2446             :             }
    2447             : 
    2448         874 :             if (!fix_subplan_map)
    2449         682 :                 continue;
    2450             : 
    2451             :             /* We just rebuild present_parts from scratch */
    2452         192 :             bms_free(pprune->present_parts);
    2453         192 :             pprune->present_parts = NULL;
    2454             : 
    2455         708 :             for (k = 0; k < nparts; k++)
    2456             :             {
    2457         516 :                 int         oldidx = pprune->subplan_map[k];
    2458             :                 int         subidx;
    2459             : 
    2460             :                 /*
    2461             :                  * If this partition existed as a subplan then change the old
    2462             :                  * subplan index to the new subplan index.  The new index may
    2463             :                  * become -1 if the partition was pruned above, or it may just
    2464             :                  * come earlier in the subplan list due to some subplans being
    2465             :                  * removed earlier in the list.  If it's a subpartition, add
    2466             :                  * it to present_parts unless it's entirely pruned.
    2467             :                  */
    2468         516 :                 if (oldidx >= 0)
    2469             :                 {
    2470             :                     Assert(oldidx < n_total_subplans);
    2471         396 :                     pprune->subplan_map[k] = new_subplan_indexes[oldidx] - 1;
    2472             : 
    2473         396 :                     if (new_subplan_indexes[oldidx] > 0)
    2474         114 :                         pprune->present_parts =
    2475         114 :                             bms_add_member(pprune->present_parts, k);
    2476             :                 }
    2477         120 :                 else if ((subidx = pprune->subpart_map[k]) >= 0)
    2478             :                 {
    2479             :                     PartitionedRelPruningData *subprune;
    2480             : 
    2481         120 :                     subprune = &prunedata->partrelprunedata[subidx];
    2482             : 
    2483         120 :                     if (!bms_is_empty(subprune->present_parts))
    2484          48 :                         pprune->present_parts =
    2485          48 :                             bms_add_member(pprune->present_parts, k);
    2486             :                 }
    2487             :             }
    2488             :         }
    2489             :     }
    2490             : 
    2491             :     /*
    2492             :      * If we fixed subplan maps, we must also recompute the other_subplans
    2493             :      * set, since indexes in it may change.
    2494             :      */
    2495         394 :     if (fix_subplan_map)
    2496             :     {
    2497          48 :         new_other_subplans = NULL;
    2498          48 :         i = -1;
    2499          72 :         while ((i = bms_next_member(prunestate->other_subplans, i)) >= 0)
    2500          24 :             new_other_subplans = bms_add_member(new_other_subplans,
    2501          24 :                                                 new_subplan_indexes[i] - 1);
    2502             : 
    2503          48 :         bms_free(prunestate->other_subplans);
    2504          48 :         prunestate->other_subplans = new_other_subplans;
    2505             : 
    2506          48 :         pfree(new_subplan_indexes);
    2507             :     }
    2508         394 : }
    2509             : 
    2510             : /*
    2511             :  * ExecFindMatchingSubPlans
    2512             :  *      Determine which subplans match the pruning steps detailed in
    2513             :  *      'prunestate' for the current comparison expression values.
    2514             :  *
    2515             :  * Pass initial_prune if PARAM_EXEC Params cannot yet be evaluated.  This
    2516             :  * differentiates the initial executor-time pruning step from later
    2517             :  * runtime pruning.
    2518             :  *
    2519             :  * The caller must pass a non-NULL validsubplan_rtis during initial pruning
    2520             :  * to collect the RT indexes of leaf partitions whose subnodes will be
    2521             :  * executed.  These RT indexes are later added to EState.es_unpruned_relids.
    2522             :  */
    2523             : Bitmapset *
    2524        3844 : ExecFindMatchingSubPlans(PartitionPruneState *prunestate,
    2525             :                          bool initial_prune,
    2526             :                          Bitmapset **validsubplan_rtis)
    2527             : {
    2528        3844 :     Bitmapset  *result = NULL;
    2529             :     MemoryContext oldcontext;
    2530             :     int         i;
    2531             : 
    2532             :     /*
    2533             :      * Either we're here on the initial prune done during pruning
    2534             :      * initialization, or we're at a point where PARAM_EXEC Params can be
    2535             :      * evaluated *and* there are steps in which to do so.
    2536             :      */
    2537             :     Assert(initial_prune || prunestate->do_exec_prune);
    2538             :     Assert(validsubplan_rtis != NULL || !initial_prune);
    2539             : 
    2540             :     /*
    2541             :      * Switch to a temp context to avoid leaking memory in the executor's
    2542             :      * query-lifespan memory context.
    2543             :      */
    2544        3844 :     oldcontext = MemoryContextSwitchTo(prunestate->prune_context);
    2545             : 
    2546             :     /*
    2547             :      * For each hierarchy, do the pruning tests, and add nondeletable
    2548             :      * subplans' indexes to "result".
    2549             :      */
    2550        7730 :     for (i = 0; i < prunestate->num_partprunedata; i++)
    2551             :     {
    2552        3886 :         PartitionPruningData *prunedata = prunestate->partprunedata[i];
    2553             :         PartitionedRelPruningData *pprune;
    2554             : 
    2555             :         /*
    2556             :          * We pass the zeroth item, belonging to the root table of the
    2557             :          * hierarchy, and find_matching_subplans_recurse() takes care of
    2558             :          * recursing to other (lower-level) parents as needed.
    2559             :          */
    2560        3886 :         pprune = &prunedata->partrelprunedata[0];
    2561        3886 :         find_matching_subplans_recurse(prunedata, pprune, initial_prune,
    2562             :                                        &result, validsubplan_rtis);
    2563             : 
    2564             :         /*
    2565             :          * Expression eval may have used space in ExprContext too. Avoid
    2566             :          * accessing exec_context during initial pruning, as it is not valid
    2567             :          * at that stage.
    2568             :          */
    2569        3886 :         if (!initial_prune && pprune->exec_pruning_steps)
    2570        3392 :             ResetExprContext(pprune->exec_context.exprcontext);
    2571             :     }
    2572             : 
    2573             :     /* Add in any subplans that partition pruning didn't account for */
    2574        3844 :     result = bms_add_members(result, prunestate->other_subplans);
    2575             : 
    2576        3844 :     MemoryContextSwitchTo(oldcontext);
    2577             : 
    2578             :     /* Copy result out of the temp context before we reset it */
    2579        3844 :     result = bms_copy(result);
    2580        3844 :     if (validsubplan_rtis)
    2581         398 :         *validsubplan_rtis = bms_copy(*validsubplan_rtis);
    2582             : 
    2583        3844 :     MemoryContextReset(prunestate->prune_context);
    2584             : 
    2585        3844 :     return result;
    2586             : }
    2587             : 
    2588             : /*
    2589             :  * find_matching_subplans_recurse
    2590             :  *      Recursive worker function for ExecFindMatchingSubPlans
    2591             :  *
    2592             :  * Adds valid (non-prunable) subplan IDs to *validsubplans and the RT indexes
    2593             :  * of their corresponding leaf partitions to *validsubplan_rtis if
    2594             :  * it's non-NULL.
    2595             :  */
    2596             : static void
    2597        4300 : find_matching_subplans_recurse(PartitionPruningData *prunedata,
    2598             :                                PartitionedRelPruningData *pprune,
    2599             :                                bool initial_prune,
    2600             :                                Bitmapset **validsubplans,
    2601             :                                Bitmapset **validsubplan_rtis)
    2602             : {
    2603             :     Bitmapset  *partset;
    2604             :     int         i;
    2605             : 
    2606             :     /* Guard against stack overflow due to overly deep partition hierarchy. */
    2607        4300 :     check_stack_depth();
    2608             : 
    2609             :     /*
    2610             :      * Prune as appropriate, if we have pruning steps matching the current
    2611             :      * execution context.  Otherwise just include all partitions at this
    2612             :      * level.
    2613             :      */
    2614        4300 :     if (initial_prune && pprune->initial_pruning_steps)
    2615         482 :         partset = get_matching_partitions(&pprune->initial_context,
    2616             :                                           pprune->initial_pruning_steps);
    2617        3818 :     else if (!initial_prune && pprune->exec_pruning_steps)
    2618        3476 :         partset = get_matching_partitions(&pprune->exec_context,
    2619             :                                           pprune->exec_pruning_steps);
    2620             :     else
    2621         342 :         partset = pprune->present_parts;
    2622             : 
    2623             :     /* Translate partset into subplan indexes */
    2624        4300 :     i = -1;
    2625        6056 :     while ((i = bms_next_member(partset, i)) >= 0)
    2626             :     {
    2627        1756 :         if (pprune->subplan_map[i] >= 0)
    2628             :         {
    2629        2680 :             *validsubplans = bms_add_member(*validsubplans,
    2630        1340 :                                             pprune->subplan_map[i]);
    2631        1340 :             if (validsubplan_rtis)
    2632         636 :                 *validsubplan_rtis = bms_add_member(*validsubplan_rtis,
    2633         636 :                                                     pprune->leafpart_rti_map[i]);
    2634             :         }
    2635             :         else
    2636             :         {
    2637         416 :             int         partidx = pprune->subpart_map[i];
    2638             : 
    2639         416 :             if (partidx >= 0)
    2640         414 :                 find_matching_subplans_recurse(prunedata,
    2641             :                                                &prunedata->partrelprunedata[partidx],
    2642             :                                                initial_prune, validsubplans,
    2643             :                                                validsubplan_rtis);
    2644             :             else
    2645             :             {
    2646             :                 /*
    2647             :                  * We get here if the planner already pruned all the sub-
    2648             :                  * partitions for this partition.  Silently ignore this
    2649             :                  * partition in this case.  The end result is the same: we
    2650             :                  * would have pruned all partitions just the same, but we
    2651             :                  * don't have any pruning steps to execute to verify this.
    2652             :                  */
    2653             :             }
    2654             :         }
    2655             :     }
    2656        4300 : }

Generated by: LCOV version 1.14