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