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