PostgreSQL Source Code git master
Loading...
Searching...
No Matches
partbounds.c File Reference
#include "postgres.h"
#include "access/relation.h"
#include "access/table.h"
#include "access/tableam.h"
#include "catalog/namespace.h"
#include "catalog/partition.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_type.h"
#include "commands/tablecmds.h"
#include "common/hashfn.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pathnodes.h"
#include "parser/parse_coerce.h"
#include "partitioning/partbounds.h"
#include "partitioning/partdesc.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/partcache.h"
#include "utils/ruleutils.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
Include dependency graph for partbounds.c:

Go to the source code of this file.

Data Structures

struct  PartitionHashBound
 
struct  PartitionListValue
 
struct  PartitionRangeBound
 
struct  PartitionMap
 

Macros

#define compare_range_bounds(partnatts, partsupfunc, partcollations, bound1, bound2)
 

Typedefs

typedef struct PartitionHashBound PartitionHashBound
 
typedef struct PartitionListValue PartitionListValue
 
typedef struct PartitionRangeBound PartitionRangeBound
 
typedef struct PartitionMap PartitionMap
 

Functions

static int32 qsort_partition_hbound_cmp (const void *a, const void *b)
 
static int32 qsort_partition_list_value_cmp (const void *a, const void *b, void *arg)
 
static int32 qsort_partition_rbound_cmp (const void *a, const void *b, void *arg)
 
static PartitionBoundInfo create_hash_bounds (PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
 
static PartitionBoundInfo create_list_bounds (PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
 
static PartitionBoundInfo create_range_bounds (PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
 
static PartitionBoundInfo merge_list_bounds (FmgrInfo *partsupfunc, Oid *partcollation, RelOptInfo *outer_rel, RelOptInfo *inner_rel, JoinType jointype, List **outer_parts, List **inner_parts)
 
static PartitionBoundInfo merge_range_bounds (int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, RelOptInfo *outer_rel, RelOptInfo *inner_rel, JoinType jointype, List **outer_parts, List **inner_parts)
 
static void init_partition_map (RelOptInfo *rel, PartitionMap *map)
 
static void free_partition_map (PartitionMap *map)
 
static bool is_dummy_partition (RelOptInfo *rel, int part_index)
 
static int merge_matching_partitions (PartitionMap *outer_map, PartitionMap *inner_map, int outer_index, int inner_index, int *next_index)
 
static int process_outer_partition (PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_default, bool inner_has_default, int outer_index, int inner_default, JoinType jointype, int *next_index, int *default_index)
 
static int process_inner_partition (PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_default, bool inner_has_default, int inner_index, int outer_default, JoinType jointype, int *next_index, int *default_index)
 
static void merge_null_partitions (PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_null, bool inner_has_null, int outer_null, int inner_null, JoinType jointype, int *next_index, int *null_index)
 
static void merge_default_partitions (PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_default, bool inner_has_default, int outer_default, int inner_default, JoinType jointype, int *next_index, int *default_index)
 
static int merge_partition_with_dummy (PartitionMap *map, int index, int *next_index)
 
static void fix_merged_indexes (PartitionMap *outer_map, PartitionMap *inner_map, int nmerged, List *merged_indexes)
 
static void generate_matching_part_pairs (RelOptInfo *outer_rel, RelOptInfo *inner_rel, PartitionMap *outer_map, PartitionMap *inner_map, int nmerged, List **outer_parts, List **inner_parts)
 
static PartitionBoundInfo build_merged_partition_bounds (char strategy, List *merged_datums, List *merged_kinds, List *merged_indexes, int null_index, int default_index)
 
static int get_range_partition (RelOptInfo *rel, PartitionBoundInfo bi, int *lb_pos, PartitionRangeBound *lb, PartitionRangeBound *ub)
 
static int get_range_partition_internal (PartitionBoundInfo bi, int *lb_pos, PartitionRangeBound *lb, PartitionRangeBound *ub)
 
static bool compare_range_partitions (int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, PartitionRangeBound *outer_lb, PartitionRangeBound *outer_ub, PartitionRangeBound *inner_lb, PartitionRangeBound *inner_ub, int *lb_cmpval, int *ub_cmpval)
 
static void get_merged_range_bounds (int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, JoinType jointype, PartitionRangeBound *outer_lb, PartitionRangeBound *outer_ub, PartitionRangeBound *inner_lb, PartitionRangeBound *inner_ub, int lb_cmpval, int ub_cmpval, PartitionRangeBound *merged_lb, PartitionRangeBound *merged_ub)
 
static void add_merged_range_bounds (int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, PartitionRangeBound *merged_lb, PartitionRangeBound *merged_ub, int merged_index, List **merged_datums, List **merged_kinds, List **merged_indexes)
 
static PartitionRangeBoundmake_one_partition_rbound (PartitionKey key, int index, List *datums, bool lower)
 
static int32 partition_hbound_cmp (int modulus1, int remainder1, int modulus2, int remainder2)
 
static int32 partition_rbound_cmp (int partnatts, FmgrInfo *partsupfunc, Oid *partcollation, Datum *datums1, PartitionRangeDatumKind *kind1, bool lower1, PartitionRangeBound *b2)
 
static int partition_range_bsearch (int partnatts, FmgrInfo *partsupfunc, Oid *partcollation, PartitionBoundInfo boundinfo, PartitionRangeBound *probe, int32 *cmpval)
 
static Exprmake_partition_op_expr (PartitionKey key, int keynum, uint16 strategy, Expr *arg1, Expr *arg2)
 
static Oid get_partition_operator (PartitionKey key, int col, StrategyNumber strategy, bool *need_relabel)
 
static Listget_qual_for_hash (Relation parent, PartitionBoundSpec *spec)
 
static Listget_qual_for_list (Relation parent, PartitionBoundSpec *spec)
 
static Listget_qual_for_range (Relation parent, PartitionBoundSpec *spec, bool for_default)
 
static void get_range_key_properties (PartitionKey key, int keynum, PartitionRangeDatum *ldatum, PartitionRangeDatum *udatum, ListCell **partexprs_item, Expr **keyCol, Const **lower_val, Const **upper_val)
 
static Listget_range_nulltest (PartitionKey key)
 
Listget_qual_from_partbound (Relation parent, PartitionBoundSpec *spec)
 
PartitionBoundInfo partition_bounds_create (PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
 
static int get_non_null_list_datum_count (PartitionBoundSpec **boundspecs, int nparts)
 
bool partition_bounds_equal (int partnatts, int16 *parttyplen, bool *parttypbyval, PartitionBoundInfo b1, PartitionBoundInfo b2)
 
PartitionBoundInfo partition_bounds_copy (PartitionBoundInfo src, PartitionKey key)
 
PartitionBoundInfo partition_bounds_merge (int partnatts, FmgrInfo *partsupfunc, Oid *partcollation, RelOptInfo *outer_rel, RelOptInfo *inner_rel, JoinType jointype, List **outer_parts, List **inner_parts)
 
bool partitions_are_ordered (PartitionBoundInfo boundinfo, Bitmapset *live_parts)
 
void check_new_partition_bound (char *relname, Relation parent, PartitionBoundSpec *spec, ParseState *pstate)
 
void check_default_partition_contents (Relation parent, Relation default_rel, PartitionBoundSpec *new_spec)
 
int get_hash_partition_greatest_modulus (PartitionBoundInfo bound)
 
int32 partition_rbound_datum_cmp (FmgrInfo *partsupfunc, Oid *partcollation, const Datum *rb_datums, PartitionRangeDatumKind *rb_kind, const Datum *tuple_datums, int n_tuple_datums)
 
int partition_list_bsearch (FmgrInfo *partsupfunc, Oid *partcollation, PartitionBoundInfo boundinfo, Datum value, bool *is_equal)
 
int partition_range_datum_bsearch (FmgrInfo *partsupfunc, Oid *partcollation, PartitionBoundInfo boundinfo, int nvalues, const Datum *values, bool *is_equal)
 
int partition_hash_bsearch (PartitionBoundInfo boundinfo, int modulus, int remainder)
 
uint64 compute_partition_hash_value (int partnatts, FmgrInfo *partsupfunc, const Oid *partcollation, const Datum *values, const bool *isnull)
 
Datum satisfies_hash_partition (PG_FUNCTION_ARGS)
 
static void check_two_partitions_bounds_range (Relation parent, RangeVar *first_name, PartitionBoundSpec *first_bound, RangeVar *second_name, PartitionBoundSpec *second_bound, bool defaultPart, bool is_merge, ParseState *pstate)
 
static PartitionBoundSpecget_partition_bound_spec (Oid partOid)
 
void calculate_partition_bound_for_merge (Relation parent, List *partNames, List *partOids, PartitionBoundSpec *spec, ParseState *pstate)
 
static Listpartitions_listdatum_intersection (FmgrInfo *partsupfunc, Oid *partcollation, const List *list1, const List *list2)
 
static void check_partitions_not_overlap_list (Relation parent, SinglePartitionSpec **parts, int nparts, ParseState *pstate)
 
static void check_partition_bounds_for_split_range (Relation parent, char *relname, PartitionBoundSpec *spec, Oid splitPartOid, bool first, bool last, bool defaultPart, ParseState *pstate)
 
static void check_partition_bounds_for_split_list (Relation parent, char *relname, PartitionBoundSpec *spec, Oid splitPartOid, ParseState *pstate)
 
static bool find_value_in_new_partitions_list (FmgrInfo *partsupfunc, Oid *partcollation, SinglePartitionSpec **parts, int nparts, Datum value, bool isnull)
 
static void check_parent_values_in_new_partitions (Relation parent, Oid partOid, SinglePartitionSpec **parts, int nparts, ParseState *pstate)
 
void check_partitions_for_split (Relation parent, Oid splitPartOid, List *partlist, ParseState *pstate)
 

Macro Definition Documentation

◆ compare_range_bounds

#define compare_range_bounds (   partnatts,
  partsupfunc,
  partcollations,
  bound1,
  bound2 
)
Value:
(partition_rbound_cmp(partnatts, partsupfunc, partcollations, \
(bound1)->datums, (bound1)->kind, (bound1)->lower, \
Datum lower(PG_FUNCTION_ARGS)
static int32 partition_rbound_cmp(int partnatts, FmgrInfo *partsupfunc, Oid *partcollation, Datum *datums1, PartitionRangeDatumKind *kind1, bool lower1, PartitionRangeBound *b2)
static int fb(int x)

Definition at line 89 of file partbounds.c.

250{
252 List *my_qual = NIL;
253
254 Assert(key != NULL);
255
256 switch (key->strategy)
257 {
259 Assert(spec->strategy == PARTITION_STRATEGY_HASH);
260 my_qual = get_qual_for_hash(parent, spec);
261 break;
262
264 Assert(spec->strategy == PARTITION_STRATEGY_LIST);
265 my_qual = get_qual_for_list(parent, spec);
266 break;
267
270 my_qual = get_qual_for_range(parent, spec, false);
271 break;
272 }
273
274 return my_qual;
275}
276
277/*
278 * partition_bounds_create
279 * Build a PartitionBoundInfo struct from a list of PartitionBoundSpec
280 * nodes
281 *
282 * This function creates a PartitionBoundInfo and fills the values of its
283 * various members based on the input list. Importantly, 'datums' array will
284 * contain Datum representation of individual bounds (possibly after
285 * de-duplication as in case of range bounds), sorted in a canonical order
286 * defined by qsort_partition_* functions of respective partitioning methods.
287 * 'indexes' array will contain as many elements as there are bounds (specific
288 * exceptions to this rule are listed in the function body), which represent
289 * the 0-based canonical positions of partitions.
290 *
291 * Upon return from this function, *mapping is set to an array of
292 * list_length(boundspecs) elements, each of which maps the original index of
293 * a partition to its canonical index.
294 *
295 * Note: The objects returned by this function are wholly allocated in the
296 * current memory context.
297 */
300 PartitionKey key, int **mapping)
301{
302 int i;
303
304 Assert(nparts > 0);
305
306 /*
307 * For each partitioning method, we first convert the partition bounds
308 * from their parser node representation to the internal representation,
309 * along with any additional preprocessing (such as de-duplicating range
310 * bounds). Resulting bound datums are then added to the 'datums' array
311 * in PartitionBoundInfo. For each datum added, an integer indicating the
312 * canonical partition index is added to the 'indexes' array.
313 *
314 * For each bound, we remember its partition's position (0-based) in the
315 * original list to later map it to the canonical index.
316 */
317
318 /*
319 * Initialize mapping array with invalid values, this is filled within
320 * each sub-routine below depending on the bound type.
321 */
322 *mapping = palloc_array(int, nparts);
323 for (i = 0; i < nparts; i++)
324 (*mapping)[i] = -1;
325
326 switch (key->strategy)
327 {
329 return create_hash_bounds(boundspecs, nparts, key, mapping);
330
332 return create_list_bounds(boundspecs, nparts, key, mapping);
333
335 return create_range_bounds(boundspecs, nparts, key, mapping);
336 }
337
338 Assert(false);
339 return NULL; /* keep compiler quiet */
340}
341
342/*
343 * create_hash_bounds
344 * Create a PartitionBoundInfo for a hash partitioned table
345 */
348 PartitionKey key, int **mapping)
349{
350 PartitionBoundInfo boundinfo;
352 int i;
355
357 boundinfo->strategy = key->strategy;
358 /* No special hash partitions. */
359 boundinfo->null_index = -1;
360 boundinfo->default_index = -1;
361
363
364 /* Convert from node to the internal representation */
365 for (i = 0; i < nparts; i++)
366 {
368
369 if (spec->strategy != PARTITION_STRATEGY_HASH)
370 elog(ERROR, "invalid strategy in partition bound spec");
371
372 hbounds[i].modulus = spec->modulus;
373 hbounds[i].remainder = spec->remainder;
374 hbounds[i].index = i;
375 }
376
377 /* Sort all the bounds in ascending order */
378 qsort(hbounds, nparts, sizeof(PartitionHashBound),
380
381 /* After sorting, moduli are now stored in ascending order. */
382 greatest_modulus = hbounds[nparts - 1].modulus;
383
384 boundinfo->ndatums = nparts;
385 boundinfo->datums = palloc0_array(Datum *, nparts);
386 boundinfo->kind = NULL;
387 boundinfo->interleaved_parts = NULL;
388 boundinfo->nindexes = greatest_modulus;
389 boundinfo->indexes = (int *) palloc(greatest_modulus * sizeof(int));
390 for (i = 0; i < greatest_modulus; i++)
391 boundinfo->indexes[i] = -1;
392
393 /*
394 * In the loop below, to save from allocating a series of small datum
395 * arrays, here we just allocate a single array and below we'll just
396 * assign a portion of this array per partition.
397 */
398 boundDatums = (Datum *) palloc(nparts * 2 * sizeof(Datum));
399
400 /*
401 * For hash partitioning, there are as many datums (modulus and remainder
402 * pairs) as there are partitions. Indexes are simply values ranging from
403 * 0 to (nparts - 1).
404 */
405 for (i = 0; i < nparts; i++)
406 {
407 int modulus = hbounds[i].modulus;
408 int remainder = hbounds[i].remainder;
409
410 boundinfo->datums[i] = &boundDatums[i * 2];
411 boundinfo->datums[i][0] = Int32GetDatum(modulus);
412 boundinfo->datums[i][1] = Int32GetDatum(remainder);
413
415 {
416 /* overlap? */
417 Assert(boundinfo->indexes[remainder] == -1);
418 boundinfo->indexes[remainder] = i;
419 remainder += modulus;
420 }
421
422 (*mapping)[hbounds[i].index] = i;
423 }
424 pfree(hbounds);
425
426 return boundinfo;
427}
428
429/*
430 * get_non_null_list_datum_count
431 * Counts the number of non-null Datums in each partition.
432 */
433static int
435{
436 int i;
437 int count = 0;
438
439 for (i = 0; i < nparts; i++)
440 {
441 ListCell *lc;
442
443 foreach(lc, boundspecs[i]->listdatums)
444 {
446
447 if (!val->constisnull)
448 count++;
449 }
450 }
451
452 return count;
453}
454
455/*
456 * create_list_bounds
457 * Create a PartitionBoundInfo for a list partitioned table
458 */
461 PartitionKey key, int **mapping)
462{
463 PartitionBoundInfo boundinfo;
465 int i;
466 int j;
467 int ndatums;
468 int next_index = 0;
469 int default_index = -1;
470 int null_index = -1;
472
474 boundinfo->strategy = key->strategy;
475 /* Will be set correctly below. */
476 boundinfo->null_index = -1;
477 boundinfo->default_index = -1;
478
479 ndatums = get_non_null_list_datum_count(boundspecs, nparts);
481 palloc(ndatums * sizeof(PartitionListValue));
482
483 /* Create a unified list of non-null values across all partitions. */
484 for (j = 0, i = 0; i < nparts; i++)
485 {
487 ListCell *c;
488
489 if (spec->strategy != PARTITION_STRATEGY_LIST)
490 elog(ERROR, "invalid strategy in partition bound spec");
491
492 /*
493 * Note the index of the partition bound spec for the default
494 * partition. There's no datum to add to the list on non-null datums
495 * for this partition.
496 */
497 if (spec->is_default)
498 {
499 default_index = i;
500 continue;
501 }
502
503 foreach(c, spec->listdatums)
504 {
506
507 if (!val->constisnull)
508 {
509 all_values[j].index = i;
510 all_values[j].value = val->constvalue;
511 j++;
512 }
513 else
514 {
515 /*
516 * Never put a null into the values array; save the index of
517 * the partition that stores nulls, instead.
518 */
519 if (null_index != -1)
520 elog(ERROR, "found null more than once");
521 null_index = i;
522 }
523 }
524 }
525
526 /* ensure we found a Datum for every slot in the all_values array */
527 Assert(j == ndatums);
528
529 qsort_arg(all_values, ndatums, sizeof(PartitionListValue),
531
532 boundinfo->ndatums = ndatums;
533 boundinfo->datums = palloc0_array(Datum *, ndatums);
534 boundinfo->kind = NULL;
535 boundinfo->interleaved_parts = NULL;
536 boundinfo->nindexes = ndatums;
537 boundinfo->indexes = (int *) palloc(ndatums * sizeof(int));
538
539 /*
540 * In the loop below, to save from allocating a series of small datum
541 * arrays, here we just allocate a single array and below we'll just
542 * assign a portion of this array per datum.
543 */
544 boundDatums = (Datum *) palloc(ndatums * sizeof(Datum));
545
546 /*
547 * Copy values. Canonical indexes are values ranging from 0 to (nparts -
548 * 1) assigned to each partition such that all datums of a given partition
549 * receive the same value. The value for a given partition is the index of
550 * that partition's smallest datum in the all_values[] array.
551 */
552 for (i = 0; i < ndatums; i++)
553 {
554 int orig_index = all_values[i].index;
555
556 boundinfo->datums[i] = &boundDatums[i];
557 boundinfo->datums[i][0] = datumCopy(all_values[i].value,
558 key->parttypbyval[0],
559 key->parttyplen[0]);
560
561 /* If the old index has no mapping, assign one */
562 if ((*mapping)[orig_index] == -1)
563 (*mapping)[orig_index] = next_index++;
564
565 boundinfo->indexes[i] = (*mapping)[orig_index];
566 }
567
569
570 /*
571 * Set the canonical value for null_index, if any.
572 *
573 * It is possible that the null-accepting partition has not been assigned
574 * an index yet, which could happen if such partition accepts only null
575 * and hence not handled in the above loop which only looked at non-null
576 * values.
577 */
578 if (null_index != -1)
579 {
580 Assert(null_index >= 0);
581 if ((*mapping)[null_index] == -1)
582 (*mapping)[null_index] = next_index++;
583 boundinfo->null_index = (*mapping)[null_index];
584 }
585
586 /* Set the canonical value for default_index, if any. */
587 if (default_index != -1)
588 {
589 /*
590 * The default partition accepts any value not specified in the lists
591 * of other partitions, hence it should not get mapped index while
592 * assigning those for non-null datums.
593 */
594 Assert(default_index >= 0);
595 Assert((*mapping)[default_index] == -1);
596 (*mapping)[default_index] = next_index++;
597 boundinfo->default_index = (*mapping)[default_index];
598 }
599
600 /*
601 * Calculate interleaved partitions. Here we look for partitions which
602 * might be interleaved with other partitions and set a bit in
603 * interleaved_parts for any partitions which may be interleaved with
604 * another partition.
605 */
606
607 /*
608 * There must be multiple partitions to have any interleaved partitions,
609 * otherwise there's nothing to interleave with.
610 */
611 if (nparts > 1)
612 {
613 /*
614 * Short-circuit check to see if only 1 Datum is allowed per
615 * partition. When this is true there's no need to do the more
616 * expensive checks to look for interleaved values.
617 */
618 if (boundinfo->ndatums +
620 partition_bound_has_default(boundinfo) != nparts)
621 {
622 int last_index = -1;
623
624 /*
625 * Since the indexes array is sorted in Datum order, if any
626 * partitions are interleaved then it will show up by the
627 * partition indexes not being in ascending order. Here we check
628 * for that and record all partitions that are out of order.
629 */
630 for (i = 0; i < boundinfo->nindexes; i++)
631 {
632 int index = boundinfo->indexes[i];
633
634 if (index < last_index)
635 boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
636 index);
637
638 /*
639 * Otherwise, if the null_index exists in the indexes array,
640 * then the NULL partition must also allow some other Datum,
641 * therefore it's "interleaved".
642 */
643 else if (partition_bound_accepts_nulls(boundinfo) &&
644 index == boundinfo->null_index)
645 boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
646 index);
647
649 }
650 }
651
652 /*
653 * The DEFAULT partition is the "catch-all" partition that can contain
654 * anything that does not belong to any other partition. If there are
655 * any other partitions then the DEFAULT partition must be marked as
656 * interleaved.
657 */
658 if (partition_bound_has_default(boundinfo))
659 boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
660 boundinfo->default_index);
661 }
662
663
664 /* All partitions must now have been assigned canonical indexes. */
665 Assert(next_index == nparts);
666 return boundinfo;
667}
668
669/*
670 * create_range_bounds
671 * Create a PartitionBoundInfo for a range partitioned table
672 */
675 PartitionKey key, int **mapping)
676{
677 PartitionBoundInfo boundinfo;
680 *prev;
681 int i,
682 k,
683 partnatts;
684 int ndatums = 0;
685 int default_index = -1;
686 int next_index = 0;
689
691 boundinfo->strategy = key->strategy;
692 /* There is no special null-accepting range partition. */
693 boundinfo->null_index = -1;
694 /* Will be set correctly below. */
695 boundinfo->default_index = -1;
696
698
699 /* Create a unified list of range bounds across all the partitions. */
700 ndatums = 0;
701 for (i = 0; i < nparts; i++)
702 {
705 *upper;
706
707 if (spec->strategy != PARTITION_STRATEGY_RANGE)
708 elog(ERROR, "invalid strategy in partition bound spec");
709
710 /*
711 * Note the index of the partition bound spec for the default
712 * partition. There's no datum to add to the all_bounds array for
713 * this partition.
714 */
715 if (spec->is_default)
716 {
717 default_index = i;
718 continue;
719 }
720
721 lower = make_one_partition_rbound(key, i, spec->lowerdatums, true);
722 upper = make_one_partition_rbound(key, i, spec->upperdatums, false);
723 all_bounds[ndatums++] = lower;
724 all_bounds[ndatums++] = upper;
725 }
726
727 Assert(ndatums == nparts * 2 ||
728 (default_index != -1 && ndatums == (nparts - 1) * 2));
729
730 /* Sort all the bounds in ascending order */
731 qsort_arg(all_bounds, ndatums,
732 sizeof(PartitionRangeBound *),
734 key);
735
736 /* Save distinct bounds from all_bounds into rbounds. */
738 palloc(ndatums * sizeof(PartitionRangeBound *));
739 k = 0;
740 prev = NULL;
741 for (i = 0; i < ndatums; i++)
742 {
744 bool is_distinct = false;
745 int j;
746
747 /* Is the current bound distinct from the previous one? */
748 for (j = 0; j < key->partnatts; j++)
749 {
751
752 if (prev == NULL || cur->kind[j] != prev->kind[j])
753 {
754 is_distinct = true;
755 break;
756 }
757
758 /*
759 * If the bounds are both MINVALUE or MAXVALUE, stop now and treat
760 * them as equal, since any values after this point must be
761 * ignored.
762 */
763 if (cur->kind[j] != PARTITION_RANGE_DATUM_VALUE)
764 break;
765
766 cmpval = FunctionCall2Coll(&key->partsupfunc[j],
767 key->partcollation[j],
768 cur->datums[j],
769 prev->datums[j]);
770 if (DatumGetInt32(cmpval) != 0)
771 {
772 is_distinct = true;
773 break;
774 }
775 }
776
777 /*
778 * Only if the bound is distinct save it into a temporary array, i.e,
779 * rbounds which is later copied into boundinfo datums array.
780 */
781 if (is_distinct)
782 rbounds[k++] = all_bounds[i];
783
784 prev = cur;
785 }
786
788
789 /* Update ndatums to hold the count of distinct datums. */
790 ndatums = k;
791
792 /*
793 * Add datums to boundinfo. Canonical indexes are values ranging from 0
794 * to nparts - 1, assigned in that order to each partition's upper bound.
795 * For 'datums' elements that are lower bounds, there is -1 in the
796 * 'indexes' array to signify that no partition exists for the values less
797 * than such a bound and greater than or equal to the previous upper
798 * bound.
799 */
800 boundinfo->ndatums = ndatums;
801 boundinfo->datums = palloc0_array(Datum *, ndatums);
802 boundinfo->kind = palloc0_array(PartitionRangeDatumKind *, ndatums);
803 boundinfo->interleaved_parts = NULL;
804
805 /*
806 * For range partitioning, an additional value of -1 is stored as the last
807 * element of the indexes[] array.
808 */
809 boundinfo->nindexes = ndatums + 1;
810 boundinfo->indexes = palloc_array(int, (ndatums + 1));
811
812 /*
813 * In the loop below, to save from allocating a series of small arrays,
814 * here we just allocate a single array for Datums and another for
815 * PartitionRangeDatumKinds, below we'll just assign a portion of these
816 * arrays in each loop.
817 */
818 partnatts = key->partnatts;
819 boundDatums = (Datum *) palloc(ndatums * partnatts * sizeof(Datum));
820 boundKinds = palloc_array(PartitionRangeDatumKind, ndatums * partnatts);
821
822 for (i = 0; i < ndatums; i++)
823 {
824 int j;
825
826 boundinfo->datums[i] = &boundDatums[i * partnatts];
827 boundinfo->kind[i] = &boundKinds[i * partnatts];
828 for (j = 0; j < partnatts; j++)
829 {
830 if (rbounds[i]->kind[j] == PARTITION_RANGE_DATUM_VALUE)
831 boundinfo->datums[i][j] =
832 datumCopy(rbounds[i]->datums[j],
833 key->parttypbyval[j],
834 key->parttyplen[j]);
835 boundinfo->kind[i][j] = rbounds[i]->kind[j];
836 }
837
838 /*
839 * There is no mapping for invalid indexes.
840 *
841 * Any lower bounds in the rbounds array have invalid indexes
842 * assigned, because the values between the previous bound (if there
843 * is one) and this (lower) bound are not part of the range of any
844 * existing partition.
845 */
846 if (rbounds[i]->lower)
847 boundinfo->indexes[i] = -1;
848 else
849 {
850 int orig_index = rbounds[i]->index;
851
852 /* If the old index has no mapping, assign one */
853 if ((*mapping)[orig_index] == -1)
854 (*mapping)[orig_index] = next_index++;
855
856 boundinfo->indexes[i] = (*mapping)[orig_index];
857 }
858 }
859
860 pfree(rbounds);
861
862 /* Set the canonical value for default_index, if any. */
863 if (default_index != -1)
864 {
865 Assert(default_index >= 0 && (*mapping)[default_index] == -1);
866 (*mapping)[default_index] = next_index++;
867 boundinfo->default_index = (*mapping)[default_index];
868 }
869
870 /* The extra -1 element. */
871 Assert(i == ndatums);
872 boundinfo->indexes[i] = -1;
873
874 /* All partitions must now have been assigned canonical indexes. */
875 Assert(next_index == nparts);
876 return boundinfo;
877}
878
879/*
880 * Are two partition bound collections logically equal?
881 *
882 * Used in the keep logic of relcache.c (ie, in RelationClearRelation()).
883 * This is also useful when b1 and b2 are bound collections of two separate
884 * relations, respectively, because PartitionBoundInfo is a canonical
885 * representation of partition bounds.
886 */
887bool
888partition_bounds_equal(int partnatts, int16 *parttyplen, bool *parttypbyval,
890{
891 int i;
892
893 if (b1->strategy != b2->strategy)
894 return false;
895
896 if (b1->ndatums != b2->ndatums)
897 return false;
898
899 if (b1->nindexes != b2->nindexes)
900 return false;
901
902 if (b1->null_index != b2->null_index)
903 return false;
904
905 if (b1->default_index != b2->default_index)
906 return false;
907
908 /* For all partition strategies, the indexes[] arrays have to match */
909 for (i = 0; i < b1->nindexes; i++)
910 {
911 if (b1->indexes[i] != b2->indexes[i])
912 return false;
913 }
914
915 /* Finally, compare the datums[] arrays */
916 if (b1->strategy == PARTITION_STRATEGY_HASH)
917 {
918 /*
919 * We arrange the partitions in the ascending order of their moduli
920 * and remainders. Also every modulus is factor of next larger
921 * modulus. Therefore we can safely store index of a given partition
922 * in indexes array at remainder of that partition. Also entries at
923 * (remainder + N * modulus) positions in indexes array are all same
924 * for (modulus, remainder) specification for any partition. Thus the
925 * datums arrays from the given bounds are the same, if and only if
926 * their indexes arrays are the same. So, it suffices to compare the
927 * indexes arrays.
928 *
929 * Nonetheless make sure that the bounds are indeed the same when the
930 * indexes match. Hash partition bound stores modulus and remainder
931 * at b1->datums[i][0] and b1->datums[i][1] position respectively.
932 */
933#ifdef USE_ASSERT_CHECKING
934 for (i = 0; i < b1->ndatums; i++)
935 Assert((b1->datums[i][0] == b2->datums[i][0] &&
936 b1->datums[i][1] == b2->datums[i][1]));
937#endif
938 }
939 else
940 {
941 for (i = 0; i < b1->ndatums; i++)
942 {
943 int j;
944
945 for (j = 0; j < partnatts; j++)
946 {
947 /* For range partitions, the bounds might not be finite. */
948 if (b1->kind != NULL)
949 {
950 /* The different kinds of bound all differ from each other */
951 if (b1->kind[i][j] != b2->kind[i][j])
952 return false;
953
954 /*
955 * Non-finite bounds are equal without further
956 * examination.
957 */
958 if (b1->kind[i][j] != PARTITION_RANGE_DATUM_VALUE)
959 continue;
960 }
961
962 /*
963 * Compare the actual values. Note that it would be both
964 * incorrect and unsafe to invoke the comparison operator
965 * derived from the partitioning specification here. It would
966 * be incorrect because we want the relcache entry to be
967 * updated for ANY change to the partition bounds, not just
968 * those that the partitioning operator thinks are
969 * significant. It would be unsafe because we might reach
970 * this code in the context of an aborted transaction, and an
971 * arbitrary partitioning operator might not be safe in that
972 * context. datumIsEqual() should be simple enough to be
973 * safe.
974 */
975 if (!datumIsEqual(b1->datums[i][j], b2->datums[i][j],
976 parttypbyval[j], parttyplen[j]))
977 return false;
978 }
979 }
980 }
981 return true;
982}
983
984/*
985 * Return a copy of given PartitionBoundInfo structure. The data types of bounds
986 * are described by given partition key specification.
987 *
988 * Note: it's important that this function and its callees not do any catalog
989 * access, nor anything else that would result in allocating memory other than
990 * the returned data structure. Since this is called in a long-lived context,
991 * that would result in unwanted memory leaks.
992 */
995 PartitionKey key)
996{
998 int i;
999 int ndatums;
1000 int nindexes;
1001 int partnatts;
1002
1004
1005 dest->strategy = src->strategy;
1006 ndatums = dest->ndatums = src->ndatums;
1007 nindexes = dest->nindexes = src->nindexes;
1008 partnatts = key->partnatts;
1009
1010 /* List partitioned tables have only a single partition key. */
1011 Assert(key->strategy != PARTITION_STRATEGY_LIST || partnatts == 1);
1012
1013 dest->datums = palloc_array(Datum *, ndatums);
1014
1015 if (src->kind != NULL && ndatums > 0)
1016 {
1018
1019 /* only RANGE partition should have a non-NULL kind */
1020 Assert(key->strategy == PARTITION_STRATEGY_RANGE);
1021
1022 dest->kind = (PartitionRangeDatumKind **) palloc(ndatums *
1023 sizeof(PartitionRangeDatumKind *));
1024
1025 /*
1026 * In the loop below, to save from allocating a series of small arrays
1027 * for storing the PartitionRangeDatumKind, we allocate a single chunk
1028 * here and use a smaller portion of it for each datum.
1029 */
1030 boundKinds = (PartitionRangeDatumKind *) palloc(ndatums * partnatts *
1031 sizeof(PartitionRangeDatumKind));
1032
1033 for (i = 0; i < ndatums; i++)
1034 {
1035 dest->kind[i] = &boundKinds[i * partnatts];
1036 memcpy(dest->kind[i], src->kind[i],
1037 sizeof(PartitionRangeDatumKind) * partnatts);
1038 }
1039 }
1040 else
1041 dest->kind = NULL;
1042
1043 /* copy interleaved partitions for LIST partitioned tables */
1044 dest->interleaved_parts = bms_copy(src->interleaved_parts);
1045
1046 /*
1047 * For hash partitioning, datums array will have two elements - modulus
1048 * and remainder.
1049 */
1050 if (ndatums > 0)
1051 {
1052 bool hash_part = (key->strategy == PARTITION_STRATEGY_HASH);
1053 int natts = hash_part ? 2 : partnatts;
1054 Datum *boundDatums = palloc(ndatums * natts * sizeof(Datum));
1055
1056 for (i = 0; i < ndatums; i++)
1057 {
1058 int j;
1059
1060 dest->datums[i] = &boundDatums[i * natts];
1061
1062 for (j = 0; j < natts; j++)
1063 {
1064 if (dest->kind == NULL ||
1066 {
1067 bool byval;
1068 int typlen;
1069
1070 if (hash_part)
1071 {
1072 typlen = sizeof(int32); /* Always int4 */
1073 byval = true; /* int4 is pass-by-value */
1074 }
1075 else
1076 {
1077 byval = key->parttypbyval[j];
1078 typlen = key->parttyplen[j];
1079 }
1080 dest->datums[i][j] = datumCopy(src->datums[i][j],
1081 byval, typlen);
1082 }
1083 }
1084 }
1085 }
1086
1087 dest->indexes = palloc_array(int, nindexes);
1088 memcpy(dest->indexes, src->indexes, sizeof(int) * nindexes);
1089
1090 dest->null_index = src->null_index;
1091 dest->default_index = src->default_index;
1092
1093 return dest;
1094}
1095
1096/*
1097 * partition_bounds_merge
1098 * Check to see whether every partition of 'outer_rel' matches/overlaps
1099 * one partition of 'inner_rel' at most, and vice versa; and if so, build
1100 * and return the partition bounds for a join relation between the rels,
1101 * generating two lists of the matching/overlapping partitions, which are
1102 * returned to *outer_parts and *inner_parts respectively.
1103 *
1104 * The lists contain the same number of partitions, and the partitions at the
1105 * same positions in the lists indicate join pairs used for partitioned join.
1106 * If a partition on one side matches/overlaps multiple partitions on the other
1107 * side, this function returns NULL, setting *outer_parts and *inner_parts to
1108 * NIL.
1109 */
1111partition_bounds_merge(int partnatts,
1112 FmgrInfo *partsupfunc, Oid *partcollation,
1114 JoinType jointype,
1116{
1117 /*
1118 * Currently, this function is called only from try_partitionwise_join(),
1119 * so the join type should be INNER, LEFT, FULL, SEMI, or ANTI.
1120 */
1121 Assert(jointype == JOIN_INNER || jointype == JOIN_LEFT ||
1122 jointype == JOIN_FULL || jointype == JOIN_SEMI ||
1123 jointype == JOIN_ANTI);
1124
1125 /* The partitioning strategies should be the same. */
1126 Assert(outer_rel->boundinfo->strategy == inner_rel->boundinfo->strategy);
1127
1129 switch (outer_rel->boundinfo->strategy)
1130 {
1132
1133 /*
1134 * For hash partitioned tables, we currently support partitioned
1135 * join only when they have exactly the same partition bounds.
1136 *
1137 * XXX: it might be possible to relax the restriction to support
1138 * cases where hash partitioned tables have missing partitions
1139 * and/or different moduli, but it's not clear if it would be
1140 * useful to support the former case since it's unusual to have
1141 * missing partitions. On the other hand, it would be useful to
1142 * support the latter case, but in that case, there is a high
1143 * probability that a partition on one side will match multiple
1144 * partitions on the other side, which is the scenario the current
1145 * implementation of partitioned join can't handle.
1146 */
1147 return NULL;
1148
1150 return merge_list_bounds(partsupfunc,
1151 partcollation,
1152 outer_rel,
1153 inner_rel,
1154 jointype,
1156 inner_parts);
1157
1159 return merge_range_bounds(partnatts,
1160 partsupfunc,
1161 partcollation,
1162 outer_rel,
1163 inner_rel,
1164 jointype,
1166 inner_parts);
1167 }
1168
1169 return NULL;
1170}
1171
1172/*
1173 * merge_list_bounds
1174 * Create the partition bounds for a join relation between list
1175 * partitioned tables, if possible
1176 *
1177 * In this function we try to find sets of matching partitions from both sides
1178 * by comparing list values stored in their partition bounds. Since the list
1179 * values appear in the ascending order, an algorithm similar to merge join is
1180 * used for that. If a partition on one side doesn't have a matching
1181 * partition on the other side, the algorithm tries to match it with the
1182 * default partition on the other side if any; if not, the algorithm tries to
1183 * match it with a dummy partition on the other side if it's on the
1184 * non-nullable side of an outer join. Also, if both sides have the default
1185 * partitions, the algorithm tries to match them with each other. We give up
1186 * if the algorithm finds a partition matching multiple partitions on the
1187 * other side, which is the scenario the current implementation of partitioned
1188 * join can't handle.
1189 */
1190static PartitionBoundInfo
1191merge_list_bounds(FmgrInfo *partsupfunc, Oid *partcollation,
1193 JoinType jointype,
1195{
1201 int outer_default = outer_bi->default_index;
1202 int inner_default = inner_bi->default_index;
1207 int outer_pos;
1208 int inner_pos;
1209 int next_index = 0;
1210 int null_index = -1;
1211 int default_index = -1;
1213 List *merged_indexes = NIL;
1214
1215 Assert(*outer_parts == NIL);
1216 Assert(*inner_parts == NIL);
1217 Assert(outer_bi->strategy == inner_bi->strategy &&
1218 outer_bi->strategy == PARTITION_STRATEGY_LIST);
1219 /* List partitioning doesn't require kinds. */
1220 Assert(!outer_bi->kind && !inner_bi->kind);
1221
1224
1225 /*
1226 * If the default partitions (if any) have been proven empty, deem them
1227 * non-existent.
1228 */
1230 outer_has_default = false;
1232 inner_has_default = false;
1233
1234 /*
1235 * Merge partitions from both sides. In each iteration we compare a pair
1236 * of list values, one from each side, and decide whether the
1237 * corresponding partitions match or not. If the two values match
1238 * exactly, move to the next pair of list values, otherwise move to the
1239 * next list value on the side with a smaller list value.
1240 */
1241 outer_pos = inner_pos = 0;
1242 while (outer_pos < outer_bi->ndatums || inner_pos < inner_bi->ndatums)
1243 {
1244 int outer_index = -1;
1245 int inner_index = -1;
1248 int cmpval;
1250 int merged_index = -1;
1251
1252 if (outer_pos < outer_bi->ndatums)
1253 {
1254 /*
1255 * If the partition on the outer side has been proven empty,
1256 * ignore it and move to the next datum on the outer side.
1257 */
1258 outer_index = outer_bi->indexes[outer_pos];
1260 {
1261 outer_pos++;
1262 continue;
1263 }
1264 }
1265 if (inner_pos < inner_bi->ndatums)
1266 {
1267 /*
1268 * If the partition on the inner side has been proven empty,
1269 * ignore it and move to the next datum on the inner side.
1270 */
1271 inner_index = inner_bi->indexes[inner_pos];
1273 {
1274 inner_pos++;
1275 continue;
1276 }
1277 }
1278
1279 /* Get the list values. */
1280 outer_datums = outer_pos < outer_bi->ndatums ?
1281 outer_bi->datums[outer_pos] : NULL;
1282 inner_datums = inner_pos < inner_bi->ndatums ?
1283 inner_bi->datums[inner_pos] : NULL;
1284
1285 /*
1286 * We run this loop till both sides finish. This allows us to avoid
1287 * duplicating code to handle the remaining values on the side which
1288 * finishes later. For that we set the comparison parameter cmpval in
1289 * such a way that it appears as if the side which finishes earlier
1290 * has an extra value higher than any other value on the unfinished
1291 * side. That way we advance the values on the unfinished side till
1292 * all of its values are exhausted.
1293 */
1294 if (outer_pos >= outer_bi->ndatums)
1295 cmpval = 1;
1296 else if (inner_pos >= inner_bi->ndatums)
1297 cmpval = -1;
1298 else
1299 {
1301 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
1302 partcollation[0],
1303 outer_datums[0],
1304 inner_datums[0]));
1305 }
1306
1307 if (cmpval == 0)
1308 {
1309 /* Two list values match exactly. */
1312 Assert(outer_index >= 0);
1313 Assert(inner_index >= 0);
1314
1315 /*
1316 * Try merging both partitions. If successful, add the list value
1317 * and index of the merged partition below.
1318 */
1321 &next_index);
1322 if (merged_index == -1)
1323 goto cleanup;
1324
1326
1327 /* Move to the next pair of list values. */
1328 outer_pos++;
1329 inner_pos++;
1330 }
1331 else if (cmpval < 0)
1332 {
1333 /* A list value missing from the inner side. */
1335
1336 /*
1337 * If the inner side has the default partition, or this is an
1338 * outer join, try to assign a merged partition to the outer
1339 * partition (see process_outer_partition()). Otherwise, the
1340 * outer partition will not contribute to the result.
1341 */
1342 if (inner_has_default || IS_OUTER_JOIN(jointype))
1343 {
1344 /* Get the outer partition. */
1345 outer_index = outer_bi->indexes[outer_pos];
1346 Assert(outer_index >= 0);
1348 &inner_map,
1353 jointype,
1354 &next_index,
1355 &default_index);
1356 if (merged_index == -1)
1357 goto cleanup;
1359 }
1360
1361 /* Move to the next list value on the outer side. */
1362 outer_pos++;
1363 }
1364 else
1365 {
1366 /* A list value missing from the outer side. */
1367 Assert(cmpval > 0);
1369
1370 /*
1371 * If the outer side has the default partition, or this is a FULL
1372 * join, try to assign a merged partition to the inner partition
1373 * (see process_inner_partition()). Otherwise, the inner
1374 * partition will not contribute to the result.
1375 */
1376 if (outer_has_default || jointype == JOIN_FULL)
1377 {
1378 /* Get the inner partition. */
1379 inner_index = inner_bi->indexes[inner_pos];
1380 Assert(inner_index >= 0);
1382 &inner_map,
1387 jointype,
1388 &next_index,
1389 &default_index);
1390 if (merged_index == -1)
1391 goto cleanup;
1393 }
1394
1395 /* Move to the next list value on the inner side. */
1396 inner_pos++;
1397 }
1398
1399 /*
1400 * If we assigned a merged partition, add the list value and index of
1401 * the merged partition if appropriate.
1402 */
1403 if (merged_index >= 0 && merged_index != default_index)
1404 {
1406 merged_indexes = lappend_int(merged_indexes, merged_index);
1407 }
1408 }
1409
1410 /*
1411 * If the NULL partitions (if any) have been proven empty, deem them
1412 * non-existent.
1413 */
1414 if (outer_has_null &&
1416 outer_has_null = false;
1417 if (inner_has_null &&
1419 inner_has_null = false;
1420
1421 /* Merge the NULL partitions if any. */
1425 outer_bi->null_index, inner_bi->null_index,
1426 jointype, &next_index, &null_index);
1427 else
1428 Assert(null_index == -1);
1429
1430 /* Merge the default partitions if any. */
1435 jointype, &next_index, &default_index);
1436 else
1437 Assert(default_index == -1);
1438
1439 /* If we have merged partitions, create the partition bounds. */
1440 if (next_index > 0)
1441 {
1442 /* Fix the merged_indexes list if necessary. */
1443 if (outer_map.did_remapping || inner_map.did_remapping)
1444 {
1445 Assert(jointype == JOIN_FULL);
1447 next_index, merged_indexes);
1448 }
1449
1450 /* Use maps to match partitions from inputs. */
1453 next_index,
1455 Assert(*outer_parts != NIL);
1456 Assert(*inner_parts != NIL);
1459
1460 /* Make a PartitionBoundInfo struct to return. */
1463 NIL,
1464 merged_indexes,
1465 null_index,
1466 default_index);
1468 }
1469
1470cleanup:
1471 /* Free local memory before returning. */
1473 list_free(merged_indexes);
1476
1477 return merged_bounds;
1478}
1479
1480/*
1481 * merge_range_bounds
1482 * Create the partition bounds for a join relation between range
1483 * partitioned tables, if possible
1484 *
1485 * In this function we try to find sets of overlapping partitions from both
1486 * sides by comparing ranges stored in their partition bounds. Since the
1487 * ranges appear in the ascending order, an algorithm similar to merge join is
1488 * used for that. If a partition on one side doesn't have an overlapping
1489 * partition on the other side, the algorithm tries to match it with the
1490 * default partition on the other side if any; if not, the algorithm tries to
1491 * match it with a dummy partition on the other side if it's on the
1492 * non-nullable side of an outer join. Also, if both sides have the default
1493 * partitions, the algorithm tries to match them with each other. We give up
1494 * if the algorithm finds a partition overlapping multiple partitions on the
1495 * other side, which is the scenario the current implementation of partitioned
1496 * join can't handle.
1497 */
1498static PartitionBoundInfo
1502 JoinType jointype,
1504{
1510 int outer_default = outer_bi->default_index;
1511 int inner_default = inner_bi->default_index;
1514 int outer_index;
1515 int inner_index;
1516 int outer_lb_pos;
1517 int inner_lb_pos;
1522 int next_index = 0;
1523 int default_index = -1;
1526 List *merged_indexes = NIL;
1527
1528 Assert(*outer_parts == NIL);
1529 Assert(*inner_parts == NIL);
1530 Assert(outer_bi->strategy == inner_bi->strategy &&
1531 outer_bi->strategy == PARTITION_STRATEGY_RANGE);
1532
1535
1536 /*
1537 * If the default partitions (if any) have been proven empty, deem them
1538 * non-existent.
1539 */
1541 outer_has_default = false;
1543 inner_has_default = false;
1544
1545 /*
1546 * Merge partitions from both sides. In each iteration we compare a pair
1547 * of ranges, one from each side, and decide whether the corresponding
1548 * partitions match or not. If the two ranges overlap, move to the next
1549 * pair of ranges, otherwise move to the next range on the side with a
1550 * lower range. outer_lb_pos/inner_lb_pos keep track of the positions of
1551 * lower bounds in the datums arrays in the outer/inner
1552 * PartitionBoundInfos respectively.
1553 */
1556 &outer_lb, &outer_ub);
1558 &inner_lb, &inner_ub);
1559 while (outer_index >= 0 || inner_index >= 0)
1560 {
1561 bool overlap;
1562 int ub_cmpval;
1563 int lb_cmpval;
1564 PartitionRangeBound merged_lb = {-1, NULL, NULL, true};
1565 PartitionRangeBound merged_ub = {-1, NULL, NULL, false};
1566 int merged_index = -1;
1567
1568 /*
1569 * We run this loop till both sides finish. This allows us to avoid
1570 * duplicating code to handle the remaining ranges on the side which
1571 * finishes later. For that we set the comparison parameter cmpval in
1572 * such a way that it appears as if the side which finishes earlier
1573 * has an extra range higher than any other range on the unfinished
1574 * side. That way we advance the ranges on the unfinished side till
1575 * all of its ranges are exhausted.
1576 */
1577 if (outer_index == -1)
1578 {
1579 overlap = false;
1580 lb_cmpval = 1;
1581 ub_cmpval = 1;
1582 }
1583 else if (inner_index == -1)
1584 {
1585 overlap = false;
1586 lb_cmpval = -1;
1587 ub_cmpval = -1;
1588 }
1589 else
1590 overlap = compare_range_partitions(partnatts, partsupfuncs,
1592 &outer_lb, &outer_ub,
1593 &inner_lb, &inner_ub,
1594 &lb_cmpval, &ub_cmpval);
1595
1596 if (overlap)
1597 {
1598 /* Two ranges overlap; form a join pair. */
1599
1602
1603 /* Both partitions should not have been merged yet. */
1604 Assert(outer_index >= 0);
1605 Assert(outer_map.merged_indexes[outer_index] == -1 &&
1606 outer_map.merged[outer_index] == false);
1607 Assert(inner_index >= 0);
1608 Assert(inner_map.merged_indexes[inner_index] == -1 &&
1609 inner_map.merged[inner_index] == false);
1610
1611 /*
1612 * Get the index of the merged partition. Both partitions aren't
1613 * merged yet, so the partitions should be merged successfully.
1614 */
1617 &next_index);
1618 Assert(merged_index >= 0);
1619
1620 /* Get the range bounds of the merged partition. */
1622 partcollations, jointype,
1623 &outer_lb, &outer_ub,
1624 &inner_lb, &inner_ub,
1626 &merged_lb, &merged_ub);
1627
1628 /* Save the upper bounds of both partitions for use below. */
1631
1632 /* Move to the next pair of ranges. */
1634 &outer_lb, &outer_ub);
1636 &inner_lb, &inner_ub);
1637
1638 /*
1639 * If the range of a partition on one side overlaps the range of
1640 * the next partition on the other side, that will cause the
1641 * partition on one side to match at least two partitions on the
1642 * other side, which is the case that we currently don't support
1643 * partitioned join for; give up.
1644 */
1645 if (ub_cmpval > 0 && inner_index >= 0 &&
1647 &save_outer_ub, &inner_lb) > 0)
1648 goto cleanup;
1651 &outer_lb, &save_inner_ub) < 0)
1652 goto cleanup;
1653
1654 /*
1655 * A row from a non-overlapping portion (if any) of a partition on
1656 * one side might find its join partner in the default partition
1657 * (if any) on the other side, causing the same situation as
1658 * above; give up in that case.
1659 */
1660 if ((outer_has_default && (lb_cmpval > 0 || ub_cmpval < 0)) ||
1662 goto cleanup;
1663 }
1664 else if (ub_cmpval < 0)
1665 {
1666 /* A non-overlapping outer range. */
1667
1668 /* The outer partition should not have been merged yet. */
1669 Assert(outer_index >= 0);
1670 Assert(outer_map.merged_indexes[outer_index] == -1 &&
1671 outer_map.merged[outer_index] == false);
1672
1673 /*
1674 * If the inner side has the default partition, or this is an
1675 * outer join, try to assign a merged partition to the outer
1676 * partition (see process_outer_partition()). Otherwise, the
1677 * outer partition will not contribute to the result.
1678 */
1679 if (inner_has_default || IS_OUTER_JOIN(jointype))
1680 {
1682 &inner_map,
1687 jointype,
1688 &next_index,
1689 &default_index);
1690 if (merged_index == -1)
1691 goto cleanup;
1694 }
1695
1696 /* Move to the next range on the outer side. */
1698 &outer_lb, &outer_ub);
1699 }
1700 else
1701 {
1702 /* A non-overlapping inner range. */
1703 Assert(ub_cmpval > 0);
1704
1705 /* The inner partition should not have been merged yet. */
1706 Assert(inner_index >= 0);
1707 Assert(inner_map.merged_indexes[inner_index] == -1 &&
1708 inner_map.merged[inner_index] == false);
1709
1710 /*
1711 * If the outer side has the default partition, or this is a FULL
1712 * join, try to assign a merged partition to the inner partition
1713 * (see process_inner_partition()). Otherwise, the inner
1714 * partition will not contribute to the result.
1715 */
1716 if (outer_has_default || jointype == JOIN_FULL)
1717 {
1719 &inner_map,
1724 jointype,
1725 &next_index,
1726 &default_index);
1727 if (merged_index == -1)
1728 goto cleanup;
1731 }
1732
1733 /* Move to the next range on the inner side. */
1735 &inner_lb, &inner_ub);
1736 }
1737
1738 /*
1739 * If we assigned a merged partition, add the range bounds and index
1740 * of the merged partition if appropriate.
1741 */
1742 if (merged_index >= 0 && merged_index != default_index)
1746 &merged_indexes);
1747 }
1748
1749 /* Merge the default partitions if any. */
1754 jointype, &next_index, &default_index);
1755 else
1756 Assert(default_index == -1);
1757
1758 /* If we have merged partitions, create the partition bounds. */
1759 if (next_index > 0)
1760 {
1761 /*
1762 * Unlike the case of list partitioning, we wouldn't have re-merged
1763 * partitions, so did_remapping should be left alone.
1764 */
1765 Assert(!outer_map.did_remapping);
1766 Assert(!inner_map.did_remapping);
1767
1768 /* Use maps to match partitions from inputs. */
1771 next_index,
1773 Assert(*outer_parts != NIL);
1774 Assert(*inner_parts != NIL);
1777
1778 /* Make a PartitionBoundInfo struct to return. */
1782 merged_indexes,
1783 -1,
1784 default_index);
1786 }
1787
1788cleanup:
1789 /* Free local memory before returning. */
1792 list_free(merged_indexes);
1795
1796 return merged_bounds;
1797}
1798
1799/*
1800 * init_partition_map
1801 * Initialize a PartitionMap struct for given relation
1802 */
1803static void
1805{
1806 int nparts = rel->nparts;
1807 int i;
1808
1809 map->nparts = nparts;
1810 map->merged_indexes = palloc_array(int, nparts);
1811 map->merged = palloc_array(bool, nparts);
1812 map->did_remapping = false;
1813 map->old_indexes = palloc_array(int, nparts);
1814 for (i = 0; i < nparts; i++)
1815 {
1816 map->merged_indexes[i] = map->old_indexes[i] = -1;
1817 map->merged[i] = false;
1818 }
1819}
1820
1821/*
1822 * free_partition_map
1823 */
1824static void
1826{
1827 pfree(map->merged_indexes);
1828 pfree(map->merged);
1829 pfree(map->old_indexes);
1830}
1831
1832/*
1833 * is_dummy_partition --- has partition been proven empty?
1834 */
1835static bool
1837{
1839
1840 Assert(part_index >= 0);
1841 part_rel = rel->part_rels[part_index];
1843 return true;
1844 return false;
1845}
1846
1847/*
1848 * merge_matching_partitions
1849 * Try to merge given outer/inner partitions, and return the index of a
1850 * merged partition produced from them if successful, -1 otherwise
1851 *
1852 * If the merged partition is newly created, *next_index is incremented.
1853 */
1854static int
1856 int outer_index, int inner_index, int *next_index)
1857{
1860 bool outer_merged;
1861 bool inner_merged;
1862
1864 outer_merged_index = outer_map->merged_indexes[outer_index];
1867 inner_merged_index = inner_map->merged_indexes[inner_index];
1869
1870 /*
1871 * Handle cases where we have already assigned a merged partition to each
1872 * of the given partitions.
1873 */
1874 if (outer_merged_index >= 0 && inner_merged_index >= 0)
1875 {
1876 /*
1877 * If the merged partitions are the same, no need to do anything;
1878 * return the index of the merged partitions. Otherwise, if each of
1879 * the given partitions has been merged with a dummy partition on the
1880 * other side, re-map them to either of the two merged partitions.
1881 * Otherwise, they can't be merged, so return -1.
1882 */
1884 {
1887 return outer_merged_index;
1888 }
1889 if (!outer_merged && !inner_merged)
1890 {
1891 /*
1892 * This can only happen for a list-partitioning case. We re-map
1893 * them to the merged partition with the smaller of the two merged
1894 * indexes to preserve the property that the canonical order of
1895 * list partitions is determined by the indexes assigned to the
1896 * smallest list value of each partition.
1897 */
1899 {
1900 outer_map->merged[outer_index] = true;
1901 inner_map->merged_indexes[inner_index] = outer_merged_index;
1902 inner_map->merged[inner_index] = true;
1903 inner_map->did_remapping = true;
1905 return outer_merged_index;
1906 }
1907 else
1908 {
1909 inner_map->merged[inner_index] = true;
1910 outer_map->merged_indexes[outer_index] = inner_merged_index;
1911 outer_map->merged[outer_index] = true;
1912 outer_map->did_remapping = true;
1914 return inner_merged_index;
1915 }
1916 }
1917 return -1;
1918 }
1919
1920 /* At least one of the given partitions should not have yet been merged. */
1922
1923 /*
1924 * If neither of them has been merged, merge them. Otherwise, if one has
1925 * been merged with a dummy partition on the other side (and the other
1926 * hasn't yet been merged with anything), re-merge them. Otherwise, they
1927 * can't be merged, so return -1.
1928 */
1929 if (outer_merged_index == -1 && inner_merged_index == -1)
1930 {
1931 int merged_index = *next_index;
1932
1935 outer_map->merged_indexes[outer_index] = merged_index;
1936 outer_map->merged[outer_index] = true;
1937 inner_map->merged_indexes[inner_index] = merged_index;
1938 inner_map->merged[inner_index] = true;
1939 *next_index = *next_index + 1;
1940 return merged_index;
1941 }
1942 if (outer_merged_index >= 0 && !outer_map->merged[outer_index])
1943 {
1946 inner_map->merged_indexes[inner_index] = outer_merged_index;
1947 inner_map->merged[inner_index] = true;
1948 outer_map->merged[outer_index] = true;
1949 return outer_merged_index;
1950 }
1951 if (inner_merged_index >= 0 && !inner_map->merged[inner_index])
1952 {
1955 outer_map->merged_indexes[outer_index] = inner_merged_index;
1956 outer_map->merged[outer_index] = true;
1957 inner_map->merged[inner_index] = true;
1958 return inner_merged_index;
1959 }
1960 return -1;
1961}
1962
1963/*
1964 * process_outer_partition
1965 * Try to assign given outer partition a merged partition, and return the
1966 * index of the merged partition if successful, -1 otherwise
1967 *
1968 * If the partition is newly created, *next_index is incremented. Also, if it
1969 * is the default partition of the join relation, *default_index is set to the
1970 * index if not already done.
1971 */
1972static int
1975 bool outer_has_default,
1976 bool inner_has_default,
1977 int outer_index,
1978 int inner_default,
1979 JoinType jointype,
1980 int *next_index,
1981 int *default_index)
1982{
1983 int merged_index = -1;
1984
1985 Assert(outer_index >= 0);
1986
1987 /*
1988 * If the inner side has the default partition, a row from the outer
1989 * partition might find its join partner in the default partition; try
1990 * merging the outer partition with the default partition. Otherwise,
1991 * this should be an outer join, in which case the outer partition has to
1992 * be scanned all the way anyway; merge the outer partition with a dummy
1993 * partition on the other side.
1994 */
1996 {
1997 Assert(inner_default >= 0);
1998
1999 /*
2000 * If the outer side has the default partition as well, the default
2001 * partition on the inner side will have two matching partitions on
2002 * the other side: the outer partition and the default partition on
2003 * the outer side. Partitionwise join doesn't handle this scenario
2004 * yet.
2005 */
2007 return -1;
2008
2011 next_index);
2012 if (merged_index == -1)
2013 return -1;
2014
2015 /*
2016 * If this is a FULL join, the default partition on the inner side has
2017 * to be scanned all the way anyway, so the resulting partition will
2018 * contain all key values from the default partition, which any other
2019 * partition of the join relation will not contain. Thus the
2020 * resulting partition will act as the default partition of the join
2021 * relation; record the index in *default_index if not already done.
2022 */
2023 if (jointype == JOIN_FULL)
2024 {
2025 if (*default_index == -1)
2026 *default_index = merged_index;
2027 else
2028 Assert(*default_index == merged_index);
2029 }
2030 }
2031 else
2032 {
2033 Assert(IS_OUTER_JOIN(jointype));
2034 Assert(jointype != JOIN_RIGHT);
2035
2036 /* If we have already assigned a partition, no need to do anything. */
2037 merged_index = outer_map->merged_indexes[outer_index];
2038 if (merged_index == -1)
2040 next_index);
2041 }
2042 return merged_index;
2043}
2044
2045/*
2046 * process_inner_partition
2047 * Try to assign given inner partition a merged partition, and return the
2048 * index of the merged partition if successful, -1 otherwise
2049 *
2050 * If the partition is newly created, *next_index is incremented. Also, if it
2051 * is the default partition of the join relation, *default_index is set to the
2052 * index if not already done.
2053 */
2054static int
2057 bool outer_has_default,
2058 bool inner_has_default,
2059 int inner_index,
2060 int outer_default,
2061 JoinType jointype,
2062 int *next_index,
2063 int *default_index)
2064{
2065 int merged_index = -1;
2066
2067 Assert(inner_index >= 0);
2068
2069 /*
2070 * If the outer side has the default partition, a row from the inner
2071 * partition might find its join partner in the default partition; try
2072 * merging the inner partition with the default partition. Otherwise,
2073 * this should be a FULL join, in which case the inner partition has to be
2074 * scanned all the way anyway; merge the inner partition with a dummy
2075 * partition on the other side.
2076 */
2078 {
2079 Assert(outer_default >= 0);
2080
2081 /*
2082 * If the inner side has the default partition as well, the default
2083 * partition on the outer side will have two matching partitions on
2084 * the other side: the inner partition and the default partition on
2085 * the inner side. Partitionwise join doesn't handle this scenario
2086 * yet.
2087 */
2089 return -1;
2090
2093 next_index);
2094 if (merged_index == -1)
2095 return -1;
2096
2097 /*
2098 * If this is an outer join, the default partition on the outer side
2099 * has to be scanned all the way anyway, so the resulting partition
2100 * will contain all key values from the default partition, which any
2101 * other partition of the join relation will not contain. Thus the
2102 * resulting partition will act as the default partition of the join
2103 * relation; record the index in *default_index if not already done.
2104 */
2105 if (IS_OUTER_JOIN(jointype))
2106 {
2107 Assert(jointype != JOIN_RIGHT);
2108 if (*default_index == -1)
2109 *default_index = merged_index;
2110 else
2111 Assert(*default_index == merged_index);
2112 }
2113 }
2114 else
2115 {
2116 Assert(jointype == JOIN_FULL);
2117
2118 /* If we have already assigned a partition, no need to do anything. */
2119 merged_index = inner_map->merged_indexes[inner_index];
2120 if (merged_index == -1)
2122 next_index);
2123 }
2124 return merged_index;
2125}
2126
2127/*
2128 * merge_null_partitions
2129 * Merge the NULL partitions from a join's outer and inner sides.
2130 *
2131 * If the merged partition produced from them is the NULL partition of the join
2132 * relation, *null_index is set to the index of the merged partition.
2133 *
2134 * Note: We assume here that the join clause for a partitioned join is strict
2135 * because have_partkey_equi_join() requires that the corresponding operator
2136 * be mergejoinable, and we currently assume that mergejoinable operators are
2137 * strict (see MJEvalOuterValues()/MJEvalInnerValues()).
2138 */
2139static void
2142 bool outer_has_null,
2143 bool inner_has_null,
2144 int outer_null,
2145 int inner_null,
2146 JoinType jointype,
2147 int *next_index,
2148 int *null_index)
2149{
2150 bool consider_outer_null = false;
2151 bool consider_inner_null = false;
2152
2154 Assert(*null_index == -1);
2155
2156 /*
2157 * Check whether the NULL partitions have already been merged and if so,
2158 * set the consider_outer_null/consider_inner_null flags.
2159 */
2160 if (outer_has_null)
2161 {
2163 if (outer_map->merged_indexes[outer_null] == -1)
2164 consider_outer_null = true;
2165 }
2166 if (inner_has_null)
2167 {
2169 if (inner_map->merged_indexes[inner_null] == -1)
2170 consider_inner_null = true;
2171 }
2172
2173 /* If both flags are set false, we don't need to do anything. */
2175 return;
2176
2178 {
2180
2181 /*
2182 * If this is an outer join, the NULL partition on the outer side has
2183 * to be scanned all the way anyway; merge the NULL partition with a
2184 * dummy partition on the other side. In that case
2185 * consider_outer_null means that the NULL partition only contains
2186 * NULL values as the key values, so the merged partition will do so;
2187 * treat it as the NULL partition of the join relation.
2188 */
2189 if (IS_OUTER_JOIN(jointype))
2190 {
2191 Assert(jointype != JOIN_RIGHT);
2193 next_index);
2194 }
2195 }
2197 {
2199
2200 /*
2201 * If this is a FULL join, the NULL partition on the inner side has to
2202 * be scanned all the way anyway; merge the NULL partition with a
2203 * dummy partition on the other side. In that case
2204 * consider_inner_null means that the NULL partition only contains
2205 * NULL values as the key values, so the merged partition will do so;
2206 * treat it as the NULL partition of the join relation.
2207 */
2208 if (jointype == JOIN_FULL)
2210 next_index);
2211 }
2212 else
2213 {
2217
2218 /*
2219 * If this is an outer join, the NULL partition on the outer side (and
2220 * that on the inner side if this is a FULL join) have to be scanned
2221 * all the way anyway, so merge them. Note that each of the NULL
2222 * partitions isn't merged yet, so they should be merged successfully.
2223 * Like the above, each of the NULL partitions only contains NULL
2224 * values as the key values, so the merged partition will do so; treat
2225 * it as the NULL partition of the join relation.
2226 *
2227 * Note: if this an INNER/SEMI join, the join clause will never be
2228 * satisfied by two NULL values (see comments above), so both the NULL
2229 * partitions can be eliminated.
2230 */
2231 if (IS_OUTER_JOIN(jointype))
2232 {
2233 Assert(jointype != JOIN_RIGHT);
2236 next_index);
2237 Assert(*null_index >= 0);
2238 }
2239 }
2240}
2241
2242/*
2243 * merge_default_partitions
2244 * Merge the default partitions from a join's outer and inner sides.
2245 *
2246 * If the merged partition produced from them is the default partition of the
2247 * join relation, *default_index is set to the index of the merged partition.
2248 */
2249static void
2252 bool outer_has_default,
2253 bool inner_has_default,
2254 int outer_default,
2255 int inner_default,
2256 JoinType jointype,
2257 int *next_index,
2258 int *default_index)
2259{
2260 int outer_merged_index = -1;
2261 int inner_merged_index = -1;
2262
2264
2265 /* Get the merged partition indexes for the default partitions. */
2267 {
2269 outer_merged_index = outer_map->merged_indexes[outer_default];
2270 }
2272 {
2274 inner_merged_index = inner_map->merged_indexes[inner_default];
2275 }
2276
2278 {
2279 /*
2280 * If this is an outer join, the default partition on the outer side
2281 * has to be scanned all the way anyway; if we have not yet assigned a
2282 * partition, merge the default partition with a dummy partition on
2283 * the other side. The merged partition will act as the default
2284 * partition of the join relation (see comments in
2285 * process_inner_partition()).
2286 */
2287 if (IS_OUTER_JOIN(jointype))
2288 {
2289 Assert(jointype != JOIN_RIGHT);
2290 if (outer_merged_index == -1)
2291 {
2292 Assert(*default_index == -1);
2293 *default_index = merge_partition_with_dummy(outer_map,
2295 next_index);
2296 }
2297 else
2298 Assert(*default_index == outer_merged_index);
2299 }
2300 else
2301 Assert(*default_index == -1);
2302 }
2304 {
2305 /*
2306 * If this is a FULL join, the default partition on the inner side has
2307 * to be scanned all the way anyway; if we have not yet assigned a
2308 * partition, merge the default partition with a dummy partition on
2309 * the other side. The merged partition will act as the default
2310 * partition of the join relation (see comments in
2311 * process_outer_partition()).
2312 */
2313 if (jointype == JOIN_FULL)
2314 {
2315 if (inner_merged_index == -1)
2316 {
2317 Assert(*default_index == -1);
2318 *default_index = merge_partition_with_dummy(inner_map,
2320 next_index);
2321 }
2322 else
2323 Assert(*default_index == inner_merged_index);
2324 }
2325 else
2326 Assert(*default_index == -1);
2327 }
2328 else
2329 {
2331
2332 /*
2333 * The default partitions have to be joined with each other, so merge
2334 * them. Note that each of the default partitions isn't merged yet
2335 * (see, process_outer_partition()/process_inner_partition()), so they
2336 * should be merged successfully. The merged partition will act as
2337 * the default partition of the join relation.
2338 */
2341 Assert(*default_index == -1);
2342 *default_index = merge_matching_partitions(outer_map,
2343 inner_map,
2346 next_index);
2347 Assert(*default_index >= 0);
2348 }
2349}
2350
2351/*
2352 * merge_partition_with_dummy
2353 * Assign given partition a new partition of a join relation
2354 *
2355 * Note: The caller assumes that the given partition doesn't have a non-dummy
2356 * matching partition on the other side, but if the given partition finds the
2357 * matching partition later, we will adjust the assignment.
2358 */
2359static int
2361{
2362 int merged_index = *next_index;
2363
2364 Assert(index >= 0 && index < map->nparts);
2365 Assert(map->merged_indexes[index] == -1);
2366 Assert(!map->merged[index]);
2368 /* Leave the merged flag alone! */
2369 *next_index = *next_index + 1;
2370 return merged_index;
2371}
2372
2373/*
2374 * fix_merged_indexes
2375 * Adjust merged indexes of re-merged partitions
2376 */
2377static void
2379 int nmerged, List *merged_indexes)
2380{
2381 int *new_indexes;
2382 int merged_index;
2383 int i;
2384 ListCell *lc;
2385
2386 Assert(nmerged > 0);
2387
2389 for (i = 0; i < nmerged; i++)
2390 new_indexes[i] = -1;
2391
2392 /* Build the mapping of old merged indexes to new merged indexes. */
2393 if (outer_map->did_remapping)
2394 {
2395 for (i = 0; i < outer_map->nparts; i++)
2396 {
2397 merged_index = outer_map->old_indexes[i];
2398 if (merged_index >= 0)
2399 new_indexes[merged_index] = outer_map->merged_indexes[i];
2400 }
2401 }
2402 if (inner_map->did_remapping)
2403 {
2404 for (i = 0; i < inner_map->nparts; i++)
2405 {
2406 merged_index = inner_map->old_indexes[i];
2407 if (merged_index >= 0)
2408 new_indexes[merged_index] = inner_map->merged_indexes[i];
2409 }
2410 }
2411
2412 /* Fix the merged_indexes list using the mapping. */
2413 foreach(lc, merged_indexes)
2414 {
2416 Assert(merged_index >= 0);
2417 if (new_indexes[merged_index] >= 0)
2419 }
2420
2422}
2423
2424/*
2425 * generate_matching_part_pairs
2426 * Generate a pair of lists of partitions that produce merged partitions
2427 *
2428 * The lists of partitions are built in the order of merged partition indexes,
2429 * and returned in *outer_parts and *inner_parts.
2430 */
2431static void
2434 int nmerged,
2436{
2437 int outer_nparts = outer_map->nparts;
2438 int inner_nparts = inner_map->nparts;
2439 int *outer_indexes;
2440 int *inner_indexes;
2441 int max_nparts;
2442 int i;
2443
2444 Assert(nmerged > 0);
2445 Assert(*outer_parts == NIL);
2446 Assert(*inner_parts == NIL);
2447
2450 for (i = 0; i < nmerged; i++)
2451 outer_indexes[i] = inner_indexes[i] = -1;
2452
2453 /* Set pairs of matching partitions. */
2454 Assert(outer_nparts == outer_rel->nparts);
2455 Assert(inner_nparts == inner_rel->nparts);
2457 for (i = 0; i < max_nparts; i++)
2458 {
2459 if (i < outer_nparts)
2460 {
2461 int merged_index = outer_map->merged_indexes[i];
2462
2463 if (merged_index >= 0)
2464 {
2467 }
2468 }
2469 if (i < inner_nparts)
2470 {
2471 int merged_index = inner_map->merged_indexes[i];
2472
2473 if (merged_index >= 0)
2474 {
2477 }
2478 }
2479 }
2480
2481 /* Build the list pairs. */
2482 for (i = 0; i < nmerged; i++)
2483 {
2486
2487 /*
2488 * If both partitions are dummy, it means the merged partition that
2489 * had been assigned to the outer/inner partition was removed when
2490 * re-merging the outer/inner partition in
2491 * merge_matching_partitions(); ignore the merged partition.
2492 */
2493 if (outer_index == -1 && inner_index == -1)
2494 continue;
2495
2497 outer_rel->part_rels[outer_index] : NULL);
2499 inner_rel->part_rels[inner_index] : NULL);
2500 }
2501
2504}
2505
2506/*
2507 * build_merged_partition_bounds
2508 * Create a PartitionBoundInfo struct from merged partition bounds
2509 */
2510static PartitionBoundInfo
2512 List *merged_kinds, List *merged_indexes,
2513 int null_index, int default_index)
2514{
2516 int ndatums = list_length(merged_datums);
2517 int pos;
2518 ListCell *lc;
2519
2521 merged_bounds->strategy = strategy;
2522 merged_bounds->ndatums = ndatums;
2523
2524 merged_bounds->datums = palloc_array(Datum *, ndatums);
2525 pos = 0;
2526 foreach(lc, merged_datums)
2527 merged_bounds->datums[pos++] = (Datum *) lfirst(lc);
2528
2529 if (strategy == PARTITION_STRATEGY_RANGE)
2530 {
2531 Assert(list_length(merged_kinds) == ndatums);
2533 pos = 0;
2534 foreach(lc, merged_kinds)
2535 merged_bounds->kind[pos++] = (PartitionRangeDatumKind *) lfirst(lc);
2536
2537 /* There are ndatums+1 indexes in the case of range partitioning. */
2538 merged_indexes = lappend_int(merged_indexes, -1);
2539 ndatums++;
2540 }
2541 else
2542 {
2543 Assert(strategy == PARTITION_STRATEGY_LIST);
2545 merged_bounds->kind = NULL;
2546 }
2547
2548 /* interleaved_parts is always NULL for join relations. */
2549 merged_bounds->interleaved_parts = NULL;
2550
2551 Assert(list_length(merged_indexes) == ndatums);
2552 merged_bounds->nindexes = ndatums;
2553 merged_bounds->indexes = palloc_array(int, ndatums);
2554 pos = 0;
2555 foreach(lc, merged_indexes)
2556 merged_bounds->indexes[pos++] = lfirst_int(lc);
2557
2558 merged_bounds->null_index = null_index;
2559 merged_bounds->default_index = default_index;
2560
2561 return merged_bounds;
2562}
2563
2564/*
2565 * get_range_partition
2566 * Get the next non-dummy partition of a range-partitioned relation,
2567 * returning the index of that partition
2568 *
2569 * *lb and *ub are set to the lower and upper bounds of that partition
2570 * respectively, and *lb_pos is advanced to the next lower bound, if any.
2571 */
2572static int
2575 int *lb_pos,
2578{
2579 int part_index;
2580
2581 Assert(bi->strategy == PARTITION_STRATEGY_RANGE);
2582
2583 do
2584 {
2586 if (part_index == -1)
2587 return -1;
2588 } while (is_dummy_partition(rel, part_index));
2589
2590 return part_index;
2591}
2592
2593static int
2595 int *lb_pos,
2598{
2599 /* Return the index as -1 if we've exhausted all lower bounds. */
2600 if (*lb_pos >= bi->ndatums)
2601 return -1;
2602
2603 /* A lower bound should have at least one more bound after it. */
2604 Assert(*lb_pos + 1 < bi->ndatums);
2605
2606 /* Set the lower bound. */
2607 lb->index = bi->indexes[*lb_pos];
2608 lb->datums = bi->datums[*lb_pos];
2609 lb->kind = bi->kind[*lb_pos];
2610 lb->lower = true;
2611 /* Set the upper bound. */
2612 ub->index = bi->indexes[*lb_pos + 1];
2613 ub->datums = bi->datums[*lb_pos + 1];
2614 ub->kind = bi->kind[*lb_pos + 1];
2615 ub->lower = false;
2616
2617 /* The index assigned to an upper bound should be valid. */
2618 Assert(ub->index >= 0);
2619
2620 /*
2621 * Advance the position to the next lower bound. If there are no bounds
2622 * left beyond the upper bound, we have reached the last lower bound.
2623 */
2624 if (*lb_pos + 2 >= bi->ndatums)
2625 *lb_pos = bi->ndatums;
2626 else
2627 {
2628 /*
2629 * If the index assigned to the bound next to the upper bound isn't
2630 * valid, that is the next lower bound; else, the upper bound is also
2631 * the lower bound of the next range partition.
2632 */
2633 if (bi->indexes[*lb_pos + 2] < 0)
2634 *lb_pos = *lb_pos + 2;
2635 else
2636 *lb_pos = *lb_pos + 1;
2637 }
2638
2639 return ub->index;
2640}
2641
2642/*
2643 * compare_range_partitions
2644 * Compare the bounds of two range partitions, and return true if the
2645 * two partitions overlap, false otherwise
2646 *
2647 * *lb_cmpval is set to -1, 0, or 1 if the outer partition's lower bound is
2648 * lower than, equal to, or higher than the inner partition's lower bound
2649 * respectively. Likewise, *ub_cmpval is set to -1, 0, or 1 if the outer
2650 * partition's upper bound is lower than, equal to, or higher than the inner
2651 * partition's upper bound respectively.
2652 */
2653static bool
2660 int *lb_cmpval, int *ub_cmpval)
2661{
2662 /*
2663 * Check if the outer partition's upper bound is lower than the inner
2664 * partition's lower bound; if so the partitions aren't overlapping.
2665 */
2667 outer_ub, inner_lb) < 0)
2668 {
2669 *lb_cmpval = -1;
2670 *ub_cmpval = -1;
2671 return false;
2672 }
2673
2674 /*
2675 * Check if the outer partition's lower bound is higher than the inner
2676 * partition's upper bound; if so the partitions aren't overlapping.
2677 */
2679 outer_lb, inner_ub) > 0)
2680 {
2681 *lb_cmpval = 1;
2682 *ub_cmpval = 1;
2683 return false;
2684 }
2685
2686 /* All other cases indicate overlapping partitions. */
2691 return true;
2692}
2693
2694/*
2695 * get_merged_range_bounds
2696 * Given the bounds of range partitions to be joined, determine the bounds
2697 * of a merged partition produced from the range partitions
2698 *
2699 * *merged_lb and *merged_ub are set to the lower and upper bounds of the
2700 * merged partition.
2701 */
2702static void
2704 Oid *partcollations, JoinType jointype,
2709 int lb_cmpval, int ub_cmpval,
2712{
2717
2718 switch (jointype)
2719 {
2720 case JOIN_INNER:
2721 case JOIN_SEMI:
2722
2723 /*
2724 * An INNER/SEMI join will have the rows that fit both sides, so
2725 * the lower bound of the merged partition will be the higher of
2726 * the two lower bounds, and the upper bound of the merged
2727 * partition will be the lower of the two upper bounds.
2728 */
2729 *merged_lb = (lb_cmpval > 0) ? *outer_lb : *inner_lb;
2730 *merged_ub = (ub_cmpval < 0) ? *outer_ub : *inner_ub;
2731 break;
2732
2733 case JOIN_LEFT:
2734 case JOIN_ANTI:
2735
2736 /*
2737 * A LEFT/ANTI join will have all the rows from the outer side, so
2738 * the bounds of the merged partition will be the same as the
2739 * outer bounds.
2740 */
2741 *merged_lb = *outer_lb;
2742 *merged_ub = *outer_ub;
2743 break;
2744
2745 case JOIN_FULL:
2746
2747 /*
2748 * A FULL join will have all the rows from both sides, so the
2749 * lower bound of the merged partition will be the lower of the
2750 * two lower bounds, and the upper bound of the merged partition
2751 * will be the higher of the two upper bounds.
2752 */
2753 *merged_lb = (lb_cmpval < 0) ? *outer_lb : *inner_lb;
2754 *merged_ub = (ub_cmpval > 0) ? *outer_ub : *inner_ub;
2755 break;
2756
2757 default:
2758 elog(ERROR, "unrecognized join type: %d", (int) jointype);
2759 }
2760}
2761
2762/*
2763 * add_merged_range_bounds
2764 * Add the bounds of a merged partition to the lists of range bounds
2765 */
2766static void
2771 int merged_index,
2774 List **merged_indexes)
2775{
2776 int cmpval;
2777
2778 if (!*merged_datums)
2779 {
2780 /* First merged partition */
2782 Assert(!*merged_indexes);
2783 cmpval = 1;
2784 }
2785 else
2786 {
2788
2791 Assert(*merged_indexes);
2792
2793 /* Get the last upper bound. */
2794 prev_ub.index = llast_int(*merged_indexes);
2795 prev_ub.datums = (Datum *) llast(*merged_datums);
2797 prev_ub.lower = false;
2798
2799 /*
2800 * We pass lower1 = false to partition_rbound_cmp() to prevent it from
2801 * considering the last upper bound to be smaller than the lower bound
2802 * of the merged partition when the values of the two range bounds
2803 * compare equal.
2804 */
2806 merged_lb->datums, merged_lb->kind,
2807 false, &prev_ub);
2808 Assert(cmpval >= 0);
2809 }
2810
2811 /*
2812 * If the lower bound is higher than the last upper bound, add the lower
2813 * bound with the index as -1 indicating that that is a lower bound; else,
2814 * the last upper bound will be reused as the lower bound of the merged
2815 * partition, so skip this.
2816 */
2817 if (cmpval > 0)
2818 {
2821 *merged_indexes = lappend_int(*merged_indexes, -1);
2822 }
2823
2824 /* Add the upper bound and index of the merged partition. */
2827 *merged_indexes = lappend_int(*merged_indexes, merged_index);
2828}
2829
2830/*
2831 * partitions_are_ordered
2832 * Determine whether the partitions described by 'boundinfo' are ordered,
2833 * that is partitions appearing earlier in the PartitionDesc sequence
2834 * contain partition keys strictly less than those appearing later.
2835 * Also, if NULL values are possible, they must come in the last
2836 * partition defined in the PartitionDesc. 'live_parts' marks which
2837 * partitions we should include when checking the ordering. Partitions
2838 * that do not appear in 'live_parts' are ignored.
2839 *
2840 * If out of order, or there is insufficient info to know the order,
2841 * then we return false.
2842 */
2843bool
2845{
2846 Assert(boundinfo != NULL);
2847
2848 switch (boundinfo->strategy)
2849 {
2851
2852 /*
2853 * RANGE-type partitioning guarantees that the partitions can be
2854 * scanned in the order that they're defined in the PartitionDesc
2855 * to provide sequential, non-overlapping ranges of tuples.
2856 * However, if a DEFAULT partition exists and it's contained
2857 * within live_parts, then the partitions are not ordered.
2858 */
2859 if (!partition_bound_has_default(boundinfo) ||
2860 !bms_is_member(boundinfo->default_index, live_parts))
2861 return true;
2862 break;
2863
2865
2866 /*
2867 * LIST partitioned are ordered providing none of live_parts
2868 * overlap with the partitioned table's interleaved partitions.
2869 */
2870 if (!bms_overlap(live_parts, boundinfo->interleaved_parts))
2871 return true;
2872
2873 break;
2875 break;
2876 }
2877
2878 return false;
2879}
2880
2881/*
2882 * check_new_partition_bound
2883 *
2884 * Checks if the new partition's bound overlaps any of the existing partitions
2885 * of parent. Also performs additional checks as necessary per strategy.
2886 */
2887void
2890{
2892 PartitionDesc partdesc = RelationGetPartitionDesc(parent, false);
2893 PartitionBoundInfo boundinfo = partdesc->boundinfo;
2894 int with = -1;
2895 bool overlap = false;
2896 int overlap_location = -1;
2897
2898 if (spec->is_default)
2899 {
2900 /*
2901 * The default partition bound never conflicts with any other
2902 * partition's; if that's what we're attaching, the only possible
2903 * problem is that one already exists, so check for that and we're
2904 * done.
2905 */
2906 if (boundinfo == NULL || !partition_bound_has_default(boundinfo))
2907 return;
2908
2909 /* Default partition already exists, error out. */
2910 ereport(ERROR,
2912 errmsg("partition \"%s\" conflicts with existing default partition \"%s\"",
2913 relname, get_rel_name(partdesc->oids[boundinfo->default_index])),
2914 parser_errposition(pstate, spec->location)));
2915 }
2916
2917 switch (key->strategy)
2918 {
2920 {
2921 Assert(spec->strategy == PARTITION_STRATEGY_HASH);
2922 Assert(spec->remainder >= 0 && spec->remainder < spec->modulus);
2923
2924 if (partdesc->nparts > 0)
2925 {
2926 int greatest_modulus;
2927 int remainder;
2928 int offset;
2929
2930 /*
2931 * Check rule that every modulus must be a factor of the
2932 * next larger modulus. (For example, if you have a bunch
2933 * of partitions that all have modulus 5, you can add a
2934 * new partition with modulus 10 or a new partition with
2935 * modulus 15, but you cannot add both a partition with
2936 * modulus 10 and a partition with modulus 15, because 10
2937 * is not a factor of 15.) We need only check the next
2938 * smaller and next larger existing moduli, relying on
2939 * previous enforcement of this rule to be sure that the
2940 * rest are in line.
2941 */
2942
2943 /*
2944 * Get the greatest (modulus, remainder) pair contained in
2945 * boundinfo->datums that is less than or equal to the
2946 * (spec->modulus, spec->remainder) pair.
2947 */
2948 offset = partition_hash_bsearch(boundinfo,
2949 spec->modulus,
2950 spec->remainder);
2951 if (offset < 0)
2952 {
2953 int next_modulus;
2954
2955 /*
2956 * All existing moduli are greater or equal, so the
2957 * new one must be a factor of the smallest one, which
2958 * is first in the boundinfo.
2959 */
2960 next_modulus = DatumGetInt32(boundinfo->datums[0][0]);
2961 if (next_modulus % spec->modulus != 0)
2962 ereport(ERROR,
2964 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
2965 errdetail("The new modulus %d is not a factor of %d, the modulus of existing partition \"%s\".",
2966 spec->modulus, next_modulus,
2967 get_rel_name(partdesc->oids[0]))));
2968 }
2969 else
2970 {
2971 int prev_modulus;
2972
2973 /*
2974 * We found the largest (modulus, remainder) pair less
2975 * than or equal to the new one. That modulus must be
2976 * a divisor of, or equal to, the new modulus.
2977 */
2978 prev_modulus = DatumGetInt32(boundinfo->datums[offset][0]);
2979
2980 if (spec->modulus % prev_modulus != 0)
2981 ereport(ERROR,
2983 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
2984 errdetail("The new modulus %d is not divisible by %d, the modulus of existing partition \"%s\".",
2985 spec->modulus,
2987 get_rel_name(partdesc->oids[offset]))));
2988
2989 if (offset + 1 < boundinfo->ndatums)
2990 {
2991 int next_modulus;
2992
2993 /*
2994 * Look at the next higher (modulus, remainder)
2995 * pair. That could have the same modulus and a
2996 * larger remainder than the new pair, in which
2997 * case we're good. If it has a larger modulus,
2998 * the new modulus must divide that one.
2999 */
3000 next_modulus = DatumGetInt32(boundinfo->datums[offset + 1][0]);
3001
3002 if (next_modulus % spec->modulus != 0)
3003 ereport(ERROR,
3005 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
3006 errdetail("The new modulus %d is not a factor of %d, the modulus of existing partition \"%s\".",
3007 spec->modulus, next_modulus,
3008 get_rel_name(partdesc->oids[offset + 1]))));
3009 }
3010 }
3011
3012 greatest_modulus = boundinfo->nindexes;
3013 remainder = spec->remainder;
3014
3015 /*
3016 * Normally, the lowest remainder that could conflict with
3017 * the new partition is equal to the remainder specified
3018 * for the new partition, but when the new partition has a
3019 * modulus higher than any used so far, we need to adjust.
3020 */
3023
3024 /* Check every potentially-conflicting remainder. */
3025 do
3026 {
3027 if (boundinfo->indexes[remainder] != -1)
3028 {
3029 overlap = true;
3030 overlap_location = spec->location;
3031 with = boundinfo->indexes[remainder];
3032 break;
3033 }
3034 remainder += spec->modulus;
3035 } while (remainder < greatest_modulus);
3036 }
3037
3038 break;
3039 }
3040
3042 {
3043 Assert(spec->strategy == PARTITION_STRATEGY_LIST);
3044
3045 if (partdesc->nparts > 0)
3046 {
3047 ListCell *cell;
3048
3049 Assert(boundinfo &&
3050 boundinfo->strategy == PARTITION_STRATEGY_LIST &&
3051 (boundinfo->ndatums > 0 ||
3052 partition_bound_accepts_nulls(boundinfo) ||
3053 partition_bound_has_default(boundinfo)));
3054
3055 foreach(cell, spec->listdatums)
3056 {
3057 Const *val = lfirst_node(Const, cell);
3058
3059 overlap_location = val->location;
3060 if (!val->constisnull)
3061 {
3062 int offset;
3063 bool equal;
3064
3065 offset = partition_list_bsearch(&key->partsupfunc[0],
3066 key->partcollation,
3067 boundinfo,
3068 val->constvalue,
3069 &equal);
3070 if (offset >= 0 && equal)
3071 {
3072 overlap = true;
3073 with = boundinfo->indexes[offset];
3074 break;
3075 }
3076 }
3077 else if (partition_bound_accepts_nulls(boundinfo))
3078 {
3079 overlap = true;
3080 with = boundinfo->null_index;
3081 break;
3082 }
3083 }
3084 }
3085
3086 break;
3087 }
3088
3090 {
3092 *upper;
3093 int cmpval;
3094
3095 Assert(spec->strategy == PARTITION_STRATEGY_RANGE);
3096 lower = make_one_partition_rbound(key, -1, spec->lowerdatums, true);
3097 upper = make_one_partition_rbound(key, -1, spec->upperdatums, false);
3098
3099 /*
3100 * First check if the resulting range would be empty with
3101 * specified lower and upper bounds. partition_rbound_cmp
3102 * cannot return zero here, since the lower-bound flags are
3103 * different.
3104 */
3105 cmpval = partition_rbound_cmp(key->partnatts,
3106 key->partsupfunc,
3107 key->partcollation,
3108 lower->datums, lower->kind,
3109 true, upper);
3110 Assert(cmpval != 0);
3111 if (cmpval > 0)
3112 {
3113 /* Point to problematic key in the lower datums list. */
3114 PartitionRangeDatum *datum = list_nth(spec->lowerdatums,
3115 cmpval - 1);
3116
3117 ereport(ERROR,
3119 errmsg("empty range bound specified for partition \"%s\"",
3120 relname),
3121 errdetail("Specified lower bound %s is greater than or equal to upper bound %s.",
3122 get_range_partbound_string(spec->lowerdatums),
3123 get_range_partbound_string(spec->upperdatums)),
3124 parser_errposition(pstate, datum->location)));
3125 }
3126
3127 if (partdesc->nparts > 0)
3128 {
3129 int offset;
3130
3131 Assert(boundinfo &&
3132 boundinfo->strategy == PARTITION_STRATEGY_RANGE &&
3133 (boundinfo->ndatums > 0 ||
3134 partition_bound_has_default(boundinfo)));
3135
3136 /*
3137 * Test whether the new lower bound (which is treated
3138 * inclusively as part of the new partition) lies inside
3139 * an existing partition, or in a gap.
3140 *
3141 * If it's inside an existing partition, the bound at
3142 * offset + 1 will be the upper bound of that partition,
3143 * and its index will be >= 0.
3144 *
3145 * If it's in a gap, the bound at offset + 1 will be the
3146 * lower bound of the next partition, and its index will
3147 * be -1. This is also true if there is no next partition,
3148 * since the index array is initialised with an extra -1
3149 * at the end.
3150 */
3151 offset = partition_range_bsearch(key->partnatts,
3152 key->partsupfunc,
3153 key->partcollation,
3154 boundinfo, lower,
3155 &cmpval);
3156
3157 if (boundinfo->indexes[offset + 1] < 0)
3158 {
3159 /*
3160 * Check that the new partition will fit in the gap.
3161 * For it to fit, the new upper bound must be less
3162 * than or equal to the lower bound of the next
3163 * partition, if there is one.
3164 */
3165 if (offset + 1 < boundinfo->ndatums)
3166 {
3167 Datum *datums;
3169 bool is_lower;
3170
3171 datums = boundinfo->datums[offset + 1];
3172 kind = boundinfo->kind[offset + 1];
3173 is_lower = (boundinfo->indexes[offset + 1] == -1);
3174
3175 cmpval = partition_rbound_cmp(key->partnatts,
3176 key->partsupfunc,
3177 key->partcollation,
3178 datums, kind,
3179 is_lower, upper);
3180 if (cmpval < 0)
3181 {
3182 /*
3183 * Point to problematic key in the upper
3184 * datums list.
3185 */
3186 PartitionRangeDatum *datum =
3187 list_nth(spec->upperdatums, abs(cmpval) - 1);
3188
3189 /*
3190 * The new partition overlaps with the
3191 * existing partition between offset + 1 and
3192 * offset + 2.
3193 */
3194 overlap = true;
3195 overlap_location = datum->location;
3196 with = boundinfo->indexes[offset + 2];
3197 }
3198 }
3199 }
3200 else
3201 {
3202 /*
3203 * The new partition overlaps with the existing
3204 * partition between offset and offset + 1.
3205 */
3206 PartitionRangeDatum *datum;
3207
3208 /*
3209 * Point to problematic key in the lower datums list;
3210 * if we have equality, point to the first one.
3211 */
3212 datum = cmpval == 0 ? linitial(spec->lowerdatums) :
3213 list_nth(spec->lowerdatums, abs(cmpval) - 1);
3214 overlap = true;
3215 overlap_location = datum->location;
3216 with = boundinfo->indexes[offset + 1];
3217 }
3218 }
3219
3220 break;
3221 }
3222 }
3223
3224 if (overlap)
3225 {
3226 Assert(with >= 0);
3227 ereport(ERROR,
3229 errmsg("partition \"%s\" would overlap partition \"%s\"",
3230 relname, get_rel_name(partdesc->oids[with])),
3232 }
3233}
3234
3235/*
3236 * check_default_partition_contents
3237 *
3238 * This function checks if there exists a row in the default partition that
3239 * would properly belong to the new partition being added. If it finds one,
3240 * it throws an error.
3241 */
3242void
3245{
3248 List *all_parts;
3249 ListCell *lc;
3250
3252 ? get_qual_for_list(parent, new_spec)
3253 : get_qual_for_range(parent, new_spec, false);
3256
3257 /*
3258 * Map the Vars in the constraint expression from parent's attnos to
3259 * default_rel's.
3260 */
3263 parent);
3264
3265 /*
3266 * If the existing constraints on the default partition imply that it will
3267 * not contain any row that would belong to the new partition, we can
3268 * avoid scanning the default partition.
3269 */
3271 {
3273 (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
3275 return;
3276 }
3277
3278 /*
3279 * Scan the default partition and its subpartitions, and check for rows
3280 * that do not satisfy the revised partition constraints.
3281 */
3282 if (default_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3285 else
3287
3288 foreach(lc, all_parts)
3289 {
3292 Expr *partition_constraint;
3293 EState *estate;
3294 ExprState *partqualstate = NULL;
3295 Snapshot snapshot;
3296 ExprContext *econtext;
3297 TableScanDesc scan;
3299 TupleTableSlot *tupslot;
3300
3301 /* Lock already taken above. */
3303 {
3305
3306 /*
3307 * Map the Vars in the constraint expression from default_rel's
3308 * the sub-partition's.
3309 */
3310 partition_constraint = make_ands_explicit(def_part_constraints);
3311 partition_constraint = (Expr *)
3312 map_partition_varattnos((List *) partition_constraint, 1,
3314
3315 /*
3316 * If the partition constraints on default partition child imply
3317 * that it will not contain any row that would belong to the new
3318 * partition, we can avoid scanning the child table.
3319 */
3322 {
3324 (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
3326
3328 continue;
3329 }
3330 }
3331 else
3332 {
3334 partition_constraint = make_ands_explicit(def_part_constraints);
3335 }
3336
3337 /*
3338 * Only RELKIND_RELATION relations (i.e. leaf partitions) need to be
3339 * scanned.
3340 */
3341 if (part_rel->rd_rel->relkind != RELKIND_RELATION)
3342 {
3343 if (part_rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3346 errmsg("skipped scanning foreign table \"%s\" which is a partition of default partition \"%s\"",
3349
3352
3353 continue;
3354 }
3355
3356 estate = CreateExecutorState();
3357
3358 /* Build expression execution states for partition check quals */
3359 partqualstate = ExecPrepareExpr(partition_constraint, estate);
3360
3361 econtext = GetPerTupleExprContext(estate);
3362 snapshot = RegisterSnapshot(GetLatestSnapshot());
3363 tupslot = table_slot_create(part_rel, &estate->es_tupleTable);
3364 scan = table_beginscan(part_rel, snapshot, 0, NULL);
3365
3366 /*
3367 * Switch to per-tuple memory context and reset it for each tuple
3368 * produced, so we don't leak memory.
3369 */
3371
3372 while (table_scan_getnextslot(scan, ForwardScanDirection, tupslot))
3373 {
3374 econtext->ecxt_scantuple = tupslot;
3375
3376 if (!ExecCheck(partqualstate, econtext))
3377 ereport(ERROR,
3379 errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
3382
3383 ResetExprContext(econtext);
3385 }
3386
3388 table_endscan(scan);
3389 UnregisterSnapshot(snapshot);
3391 FreeExecutorState(estate);
3392
3394 table_close(part_rel, NoLock); /* keep the lock until commit */
3395 }
3396}
3397
3398/*
3399 * get_hash_partition_greatest_modulus
3400 *
3401 * Returns the greatest modulus of the hash partition bound.
3402 * This is no longer used in the core code, but we keep it around
3403 * in case external modules are using it.
3404 */
3405int
3407{
3408 Assert(bound && bound->strategy == PARTITION_STRATEGY_HASH);
3409 return bound->nindexes;
3410}
3411
3412/*
3413 * make_one_partition_rbound
3414 *
3415 * Return a PartitionRangeBound given a list of PartitionRangeDatum elements
3416 * and a flag telling whether the bound is lower or not. Made into a function
3417 * because there are multiple sites that want to use this facility.
3418 */
3419static PartitionRangeBound *
3420make_one_partition_rbound(PartitionKey key, int index, List *datums, bool lower)
3421{
3422 PartitionRangeBound *bound;
3423 ListCell *lc;
3424 int i;
3425
3426 Assert(datums != NIL);
3427
3429 bound->index = index;
3430 bound->datums = palloc0_array(Datum, key->partnatts);
3431 bound->kind = palloc0_array(PartitionRangeDatumKind, key->partnatts);
3432 bound->lower = lower;
3433
3434 i = 0;
3435 foreach(lc, datums)
3436 {
3438
3439 /* What's contained in this range datum? */
3440 bound->kind[i] = datum->kind;
3441
3442 if (datum->kind == PARTITION_RANGE_DATUM_VALUE)
3443 {
3444 Const *val = castNode(Const, datum->value);
3445
3446 if (val->constisnull)
3447 elog(ERROR, "invalid range bound datum");
3448 bound->datums[i] = val->constvalue;
3449 }
3450
3451 i++;
3452 }
3453
3454 return bound;
3455}
3456
3457/*
3458 * partition_rbound_cmp
3459 *
3460 * For two range bounds this decides whether the 1st one (specified by
3461 * datums1, kind1, and lower1) is <, =, or > the bound specified in *b2.
3462 *
3463 * 0 is returned if they are equal, otherwise a non-zero integer whose sign
3464 * indicates the ordering, and whose absolute value gives the 1-based
3465 * partition key number of the first mismatching column.
3466 *
3467 * partnatts, partsupfunc and partcollation give the number of attributes in the
3468 * bounds to be compared, comparison function to be used and the collations of
3469 * attributes, respectively.
3470 *
3471 * Note that if the values of the two range bounds compare equal, then we take
3472 * into account whether they are upper or lower bounds, and an upper bound is
3473 * considered to be smaller than a lower bound. This is important to the way
3474 * that RelationBuildPartitionDesc() builds the PartitionBoundInfoData
3475 * structure, which only stores the upper bound of a common boundary between
3476 * two contiguous partitions.
3477 */
3478static int32
3479partition_rbound_cmp(int partnatts, FmgrInfo *partsupfunc,
3480 Oid *partcollation,
3483{
3484 int32 colnum = 0;
3485 int32 cmpval = 0; /* placate compiler */
3486 int i;
3487 Datum *datums2 = b2->datums;
3489 bool lower2 = b2->lower;
3490
3491 for (i = 0; i < partnatts; i++)
3492 {
3493 /* Track column number in case we need it for result */
3494 colnum++;
3495
3496 /*
3497 * First, handle cases where the column is unbounded, which should not
3498 * invoke the comparison procedure, and should not consider any later
3499 * columns. Note that the PartitionRangeDatumKind enum elements
3500 * compare the same way as the values they represent.
3501 */
3502 if (kind1[i] < kind2[i])
3503 return -colnum;
3504 else if (kind1[i] > kind2[i])
3505 return colnum;
3506 else if (kind1[i] != PARTITION_RANGE_DATUM_VALUE)
3507 {
3508 /*
3509 * The column bounds are both MINVALUE or both MAXVALUE. No later
3510 * columns should be considered, but we still need to compare
3511 * whether they are upper or lower bounds.
3512 */
3513 break;
3514 }
3515
3516 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[i],
3517 partcollation[i],
3518 datums1[i],
3519 datums2[i]));
3520 if (cmpval != 0)
3521 break;
3522 }
3523
3524 /*
3525 * If the comparison is anything other than equal, we're done. If they
3526 * compare equal though, we still have to consider whether the boundaries
3527 * are inclusive or exclusive. Exclusive one is considered smaller of the
3528 * two.
3529 */
3530 if (cmpval == 0 && lower1 != lower2)
3531 cmpval = lower1 ? 1 : -1;
3532
3533 return cmpval == 0 ? 0 : (cmpval < 0 ? -colnum : colnum);
3534}
3535
3536/*
3537 * partition_rbound_datum_cmp
3538 *
3539 * Return whether range bound (specified in rb_datums and rb_kind)
3540 * is <, =, or > partition key of tuple (tuple_datums)
3541 *
3542 * n_tuple_datums, partsupfunc and partcollation give number of attributes in
3543 * the bounds to be compared, comparison function to be used and the collations
3544 * of attributes resp.
3545 */
3546int32
3547partition_rbound_datum_cmp(FmgrInfo *partsupfunc, Oid *partcollation,
3549 const Datum *tuple_datums, int n_tuple_datums)
3550{
3551 int i;
3552 int32 cmpval = -1;
3553
3554 for (i = 0; i < n_tuple_datums; i++)
3555 {
3557 return -1;
3559 return 1;
3560
3561 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[i],
3562 partcollation[i],
3563 rb_datums[i],
3564 tuple_datums[i]));
3565 if (cmpval != 0)
3566 break;
3567 }
3568
3569 return cmpval;
3570}
3571
3572/*
3573 * partition_hbound_cmp
3574 *
3575 * Compares modulus first, then remainder if modulus is equal.
3576 */
3577static int32
3579{
3580 if (modulus1 < modulus2)
3581 return -1;
3582 if (modulus1 > modulus2)
3583 return 1;
3585 return (remainder1 > remainder2) ? 1 : -1;
3586 return 0;
3587}
3588
3589/*
3590 * partition_list_bsearch
3591 * Returns the index of the greatest bound datum that is less than equal
3592 * to the given value or -1 if all of the bound datums are greater
3593 *
3594 * *is_equal is set to true if the bound datum at the returned index is equal
3595 * to the input value.
3596 */
3597int
3598partition_list_bsearch(FmgrInfo *partsupfunc, Oid *partcollation,
3599 PartitionBoundInfo boundinfo,
3600 Datum value, bool *is_equal)
3601{
3602 int lo,
3603 hi,
3604 mid;
3605
3606 lo = -1;
3607 hi = boundinfo->ndatums - 1;
3608 while (lo < hi)
3609 {
3610 int32 cmpval;
3611
3612 mid = (lo + hi + 1) / 2;
3613 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
3614 partcollation[0],
3615 boundinfo->datums[mid][0],
3616 value));
3617 if (cmpval <= 0)
3618 {
3619 lo = mid;
3620 *is_equal = (cmpval == 0);
3621 if (*is_equal)
3622 break;
3623 }
3624 else
3625 hi = mid - 1;
3626 }
3627
3628 return lo;
3629}
3630
3631/*
3632 * partition_range_bsearch
3633 * Returns the index of the greatest range bound that is less than or
3634 * equal to the given range bound or -1 if all of the range bounds are
3635 * greater
3636 *
3637 * Upon return from this function, *cmpval is set to 0 if the bound at the
3638 * returned index matches the input range bound exactly, otherwise a
3639 * non-zero integer whose sign indicates the ordering, and whose absolute
3640 * value gives the 1-based partition key number of the first mismatching
3641 * column.
3642 */
3643static int
3644partition_range_bsearch(int partnatts, FmgrInfo *partsupfunc,
3645 Oid *partcollation,
3646 PartitionBoundInfo boundinfo,
3648{
3649 int lo,
3650 hi,
3651 mid;
3652
3653 lo = -1;
3654 hi = boundinfo->ndatums - 1;
3655 while (lo < hi)
3656 {
3657 mid = (lo + hi + 1) / 2;
3658 *cmpval = partition_rbound_cmp(partnatts, partsupfunc,
3659 partcollation,
3660 boundinfo->datums[mid],
3661 boundinfo->kind[mid],
3662 (boundinfo->indexes[mid] == -1),
3663 probe);
3664 if (*cmpval <= 0)
3665 {
3666 lo = mid;
3667 if (*cmpval == 0)
3668 break;
3669 }
3670 else
3671 hi = mid - 1;
3672 }
3673
3674 return lo;
3675}
3676
3677/*
3678 * partition_range_datum_bsearch
3679 * Returns the index of the greatest range bound that is less than or
3680 * equal to the given tuple or -1 if all of the range bounds are greater
3681 *
3682 * *is_equal is set to true if the range bound at the returned index is equal
3683 * to the input tuple.
3684 */
3685int
3686partition_range_datum_bsearch(FmgrInfo *partsupfunc, Oid *partcollation,
3687 PartitionBoundInfo boundinfo,
3688 int nvalues, const Datum *values, bool *is_equal)
3689{
3690 int lo,
3691 hi,
3692 mid;
3693
3694 lo = -1;
3695 hi = boundinfo->ndatums - 1;
3696 while (lo < hi)
3697 {
3698 int32 cmpval;
3699
3700 mid = (lo + hi + 1) / 2;
3701 cmpval = partition_rbound_datum_cmp(partsupfunc,
3702 partcollation,
3703 boundinfo->datums[mid],
3704 boundinfo->kind[mid],
3705 values,
3706 nvalues);
3707 if (cmpval <= 0)
3708 {
3709 lo = mid;
3710 *is_equal = (cmpval == 0);
3711
3712 if (*is_equal)
3713 break;
3714 }
3715 else
3716 hi = mid - 1;
3717 }
3718
3719 return lo;
3720}
3721
3722/*
3723 * partition_hash_bsearch
3724 * Returns the index of the greatest (modulus, remainder) pair that is
3725 * less than or equal to the given (modulus, remainder) pair or -1 if
3726 * all of them are greater
3727 */
3728int
3730 int modulus, int remainder)
3731{
3732 int lo,
3733 hi,
3734 mid;
3735
3736 lo = -1;
3737 hi = boundinfo->ndatums - 1;
3738 while (lo < hi)
3739 {
3740 int32 cmpval,
3743
3744 mid = (lo + hi + 1) / 2;
3745 bound_modulus = DatumGetInt32(boundinfo->datums[mid][0]);
3746 bound_remainder = DatumGetInt32(boundinfo->datums[mid][1]);
3748 modulus, remainder);
3749 if (cmpval <= 0)
3750 {
3751 lo = mid;
3752
3753 if (cmpval == 0)
3754 break;
3755 }
3756 else
3757 hi = mid - 1;
3758 }
3759
3760 return lo;
3761}
3762
3763/*
3764 * qsort_partition_hbound_cmp
3765 *
3766 * Hash bounds are sorted by modulus, then by remainder.
3767 */
3768static int32
3769qsort_partition_hbound_cmp(const void *a, const void *b)
3770{
3771 const PartitionHashBound *h1 = (const PartitionHashBound *) a;
3772 const PartitionHashBound *h2 = (const PartitionHashBound *) b;
3773
3774 return partition_hbound_cmp(h1->modulus, h1->remainder,
3775 h2->modulus, h2->remainder);
3776}
3777
3778/*
3779 * qsort_partition_list_value_cmp
3780 *
3781 * Compare two list partition bound datums.
3782 */
3783static int32
3784qsort_partition_list_value_cmp(const void *a, const void *b, void *arg)
3785{
3786 Datum val1 = ((const PartitionListValue *) a)->value,
3787 val2 = ((const PartitionListValue *) b)->value;
3789
3790 return DatumGetInt32(FunctionCall2Coll(&key->partsupfunc[0],
3791 key->partcollation[0],
3792 val1, val2));
3793}
3794
3795/*
3796 * qsort_partition_rbound_cmp
3797 *
3798 * Used when sorting range bounds across all range partitions.
3799 */
3800static int32
3801qsort_partition_rbound_cmp(const void *a, const void *b, void *arg)
3802{
3806
3807 return compare_range_bounds(key->partnatts, key->partsupfunc,
3808 key->partcollation,
3809 b1, b2);
3810}
3811
3812/*
3813 * get_partition_operator
3814 *
3815 * Return oid of the operator of the given strategy for the given partition
3816 * key column. It is assumed that the partitioning key is of the same type as
3817 * the chosen partitioning opclass, or at least binary-compatible. In the
3818 * latter case, *need_relabel is set to true if the opclass is not of a
3819 * polymorphic type (indicating a RelabelType node needed on top), otherwise
3820 * false.
3821 */
3822static Oid
3824 bool *need_relabel)
3825{
3826 Oid operoid;
3827
3828 /*
3829 * Get the operator in the partitioning opfamily using the opclass'
3830 * declared input type as both left- and righttype.
3831 */
3832 operoid = get_opfamily_member(key->partopfamily[col],
3833 key->partopcintype[col],
3834 key->partopcintype[col],
3835 strategy);
3836 if (!OidIsValid(operoid))
3837 elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u",
3838 strategy, key->partopcintype[col], key->partopcintype[col],
3839 key->partopfamily[col]);
3840
3841 /*
3842 * If the partition key column is not of the same type as the operator
3843 * class and not polymorphic, tell caller to wrap the non-Const expression
3844 * in a RelabelType. This matches what parse_coerce.c does.
3845 */
3846 *need_relabel = (key->parttypid[col] != key->partopcintype[col] &&
3847 key->partopcintype[col] != RECORDOID &&
3848 !IsPolymorphicType(key->partopcintype[col]));
3849
3850 return operoid;
3851}
3852
3853/*
3854 * make_partition_op_expr
3855 * Returns an Expr for the given partition key column with arg1 and
3856 * arg2 as its leftop and rightop, respectively
3857 */
3858static Expr *
3860 uint16 strategy, Expr *arg1, Expr *arg2)
3861{
3862 Oid operoid;
3863 bool need_relabel = false;
3864 Expr *result = NULL;
3865
3866 /* Get the correct btree operator for this partitioning column */
3868
3869 /*
3870 * Chosen operator may be such that the non-Const operand needs to be
3871 * coerced, so apply the same; see the comment in
3872 * get_partition_operator().
3873 */
3874 if (!IsA(arg1, Const) &&
3875 (need_relabel ||
3876 key->partcollation[keynum] != key->parttypcoll[keynum]))
3878 key->partopcintype[keynum],
3879 -1,
3880 key->partcollation[keynum],
3882
3883 /* Generate the actual expression */
3884 switch (key->strategy)
3885 {
3887 {
3888 List *elems = (List *) arg2;
3889 int nelems = list_length(elems);
3890
3891 Assert(nelems >= 1);
3892 Assert(keynum == 0);
3893
3894 if (nelems > 1 &&
3895 !type_is_array(key->parttypid[keynum]))
3896 {
3899
3900 /* Construct an ArrayExpr for the right-hand inputs */
3902 arrexpr->array_typeid =
3903 get_array_type(key->parttypid[keynum]);
3904 arrexpr->array_collid = key->parttypcoll[keynum];
3905 arrexpr->element_typeid = key->parttypid[keynum];
3906 arrexpr->elements = elems;
3907 arrexpr->multidims = false;
3908 arrexpr->location = -1;
3909
3910 /* Build leftop = ANY (rightop) */
3912 saopexpr->opno = operoid;
3913 saopexpr->opfuncid = get_opcode(operoid);
3914 saopexpr->hashfuncid = InvalidOid;
3915 saopexpr->negfuncid = InvalidOid;
3916 saopexpr->useOr = true;
3917 saopexpr->inputcollid = key->partcollation[keynum];
3918 saopexpr->args = list_make2(arg1, arrexpr);
3919 saopexpr->location = -1;
3920
3921 result = (Expr *) saopexpr;
3922 }
3923 else
3924 {
3925 List *elemops = NIL;
3926 ListCell *lc;
3927
3928 foreach(lc, elems)
3929 {
3930 Expr *elem = lfirst(lc),
3931 *elemop;
3932
3934 BOOLOID,
3935 false,
3936 arg1, elem,
3937 InvalidOid,
3938 key->partcollation[keynum]);
3940 }
3941
3942 result = nelems > 1 ? makeBoolExpr(OR_EXPR, elemops, -1) : linitial(elemops);
3943 }
3944 break;
3945 }
3946
3948 result = make_opclause(operoid,
3949 BOOLOID,
3950 false,
3951 arg1, arg2,
3952 InvalidOid,
3953 key->partcollation[keynum]);
3954 break;
3955
3957 Assert(false);
3958 break;
3959 }
3960
3961 return result;
3962}
3963
3964/*
3965 * get_qual_for_hash
3966 *
3967 * Returns a CHECK constraint expression to use as a hash partition's
3968 * constraint, given the parent relation and partition bound structure.
3969 *
3970 * The partition constraint for a hash partition is always a call to the
3971 * built-in function satisfies_hash_partition().
3972 */
3973static List *
3975{
3977 FuncExpr *fexpr;
3981 List *args;
3983 int i;
3984
3985 /* Fixed arguments. */
3987 -1,
3988 InvalidOid,
3989 sizeof(Oid),
3991 false,
3992 true);
3993
3995 -1,
3996 InvalidOid,
3997 sizeof(int32),
3998 Int32GetDatum(spec->modulus),
3999 false,
4000 true);
4001
4003 -1,
4004 InvalidOid,
4005 sizeof(int32),
4006 Int32GetDatum(spec->remainder),
4007 false,
4008 true);
4009
4011 partexprs_item = list_head(key->partexprs);
4012
4013 /* Add an argument for each key column. */
4014 for (i = 0; i < key->partnatts; i++)
4015 {
4016 Node *keyCol;
4017
4018 /* Left operand */
4019 if (key->partattrs[i] != 0)
4020 {
4021 keyCol = (Node *) makeVar(1,
4022 key->partattrs[i],
4023 key->parttypid[i],
4024 key->parttypmod[i],
4025 key->parttypcoll[i],
4026 0);
4027 }
4028 else
4029 {
4031 partexprs_item = lnext(key->partexprs, partexprs_item);
4032 }
4033
4034 args = lappend(args, keyCol);
4035 }
4036
4038 BOOLOID,
4039 args,
4040 InvalidOid,
4041 InvalidOid,
4043
4044 return list_make1(fexpr);
4045}
4046
4047/*
4048 * get_qual_for_list
4049 *
4050 * Returns an implicit-AND list of expressions to use as a list partition's
4051 * constraint, given the parent relation and partition bound structure.
4052 *
4053 * The function returns NIL for a default partition when it's the only
4054 * partition since in that case there is no constraint.
4055 */
4056static List *
4058{
4060 List *result;
4061 Expr *keyCol;
4062 Expr *opexpr;
4064 ListCell *cell;
4065 List *elems = NIL;
4066 bool list_has_null = false;
4067
4068 /*
4069 * Only single-column list partitioning is supported, so we are worried
4070 * only about the partition key with index 0.
4071 */
4072 Assert(key->partnatts == 1);
4073
4074 /* Construct Var or expression representing the partition column */
4075 if (key->partattrs[0] != 0)
4076 keyCol = (Expr *) makeVar(1,
4077 key->partattrs[0],
4078 key->parttypid[0],
4079 key->parttypmod[0],
4080 key->parttypcoll[0],
4081 0);
4082 else
4083 keyCol = (Expr *) copyObject(linitial(key->partexprs));
4084
4085 /*
4086 * For default list partition, collect datums for all the partitions. The
4087 * default partition constraint should check that the partition key is
4088 * equal to none of those.
4089 */
4090 if (spec->is_default)
4091 {
4092 int i;
4093 int ndatums = 0;
4095 PartitionBoundInfo boundinfo = pdesc->boundinfo;
4096
4097 if (boundinfo)
4098 {
4099 ndatums = boundinfo->ndatums;
4100
4101 if (partition_bound_accepts_nulls(boundinfo))
4102 list_has_null = true;
4103 }
4104
4105 /*
4106 * If default is the only partition, there need not be any partition
4107 * constraint on it.
4108 */
4109 if (ndatums == 0 && !list_has_null)
4110 return NIL;
4111
4112 for (i = 0; i < ndatums; i++)
4113 {
4114 Const *val;
4115
4116 /*
4117 * Construct Const from known-not-null datum. We must be careful
4118 * to copy the value, because our result has to be able to outlive
4119 * the relcache entry we're copying from.
4120 */
4121 val = makeConst(key->parttypid[0],
4122 key->parttypmod[0],
4123 key->parttypcoll[0],
4124 key->parttyplen[0],
4125 datumCopy(*boundinfo->datums[i],
4126 key->parttypbyval[0],
4127 key->parttyplen[0]),
4128 false, /* isnull */
4129 key->parttypbyval[0]);
4130
4131 elems = lappend(elems, val);
4132 }
4133 }
4134 else
4135 {
4136 /*
4137 * Create list of Consts for the allowed values, excluding any nulls.
4138 */
4139 foreach(cell, spec->listdatums)
4140 {
4141 Const *val = lfirst_node(Const, cell);
4142
4143 if (val->constisnull)
4144 list_has_null = true;
4145 else
4146 elems = lappend(elems, copyObject(val));
4147 }
4148 }
4149
4150 if (elems)
4151 {
4152 /*
4153 * Generate the operator expression from the non-null partition
4154 * values.
4155 */
4157 keyCol, (Expr *) elems);
4158 }
4159 else
4160 {
4161 /*
4162 * If there are no partition values, we don't need an operator
4163 * expression.
4164 */
4165 opexpr = NULL;
4166 }
4167
4168 if (!list_has_null)
4169 {
4170 /*
4171 * Gin up a "col IS NOT NULL" test that will be ANDed with the main
4172 * expression. This might seem redundant, but the partition routing
4173 * machinery needs it.
4174 */
4176 nulltest->arg = keyCol;
4177 nulltest->nulltesttype = IS_NOT_NULL;
4178 nulltest->argisrow = false;
4179 nulltest->location = -1;
4180
4181 result = opexpr ? list_make2(nulltest, opexpr) : list_make1(nulltest);
4182 }
4183 else
4184 {
4185 /*
4186 * Gin up a "col IS NULL" test that will be OR'd with the main
4187 * expression.
4188 */
4190 nulltest->arg = keyCol;
4191 nulltest->nulltesttype = IS_NULL;
4192 nulltest->argisrow = false;
4193 nulltest->location = -1;
4194
4195 if (opexpr)
4196 {
4197 Expr *or;
4198
4199 or = makeBoolExpr(OR_EXPR, list_make2(nulltest, opexpr), -1);
4200 result = list_make1(or);
4201 }
4202 else
4203 result = list_make1(nulltest);
4204 }
4205
4206 /*
4207 * Note that, in general, applying NOT to a constraint expression doesn't
4208 * necessarily invert the set of rows it accepts, because NOT (NULL) is
4209 * NULL. However, the partition constraints we construct here never
4210 * evaluate to NULL, so applying NOT works as intended.
4211 */
4212 if (spec->is_default)
4213 {
4214 result = list_make1(make_ands_explicit(result));
4215 result = list_make1(makeBoolExpr(NOT_EXPR, result, -1));
4216 }
4217
4218 return result;
4219}
4220
4221/*
4222 * get_qual_for_range
4223 *
4224 * Returns an implicit-AND list of expressions to use as a range partition's
4225 * constraint, given the parent relation and partition bound structure.
4226 *
4227 * For a multi-column range partition key, say (a, b, c), with (al, bl, cl)
4228 * as the lower bound tuple and (au, bu, cu) as the upper bound tuple, we
4229 * generate an expression tree of the following form:
4230 *
4231 * (a IS NOT NULL) and (b IS NOT NULL) and (c IS NOT NULL)
4232 * AND
4233 * (a > al OR (a = al AND b > bl) OR (a = al AND b = bl AND c >= cl))
4234 * AND
4235 * (a < au OR (a = au AND b < bu) OR (a = au AND b = bu AND c < cu))
4236 *
4237 * It is often the case that a prefix of lower and upper bound tuples contains
4238 * the same values, for example, (al = au), in which case, we will emit an
4239 * expression tree of the following form:
4240 *
4241 * (a IS NOT NULL) and (b IS NOT NULL) and (c IS NOT NULL)
4242 * AND
4243 * (a = al)
4244 * AND
4245 * (b > bl OR (b = bl AND c >= cl))
4246 * AND
4247 * (b < bu OR (b = bu AND c < cu))
4248 *
4249 * If a bound datum is either MINVALUE or MAXVALUE, these expressions are
4250 * simplified using the fact that any value is greater than MINVALUE and less
4251 * than MAXVALUE. So, for example, if cu = MAXVALUE, c < cu is automatically
4252 * true, and we need not emit any expression for it, and the last line becomes
4253 *
4254 * (b < bu) OR (b = bu), which is simplified to (b <= bu)
4255 *
4256 * In most common cases with only one partition column, say a, the following
4257 * expression tree will be generated: a IS NOT NULL AND a >= al AND a < au
4258 *
4259 * For default partition, it returns the negation of the constraints of all
4260 * the other partitions.
4261 *
4262 * External callers should pass for_default as false; we set it to true only
4263 * when recursing.
4264 */
4265static List *
4267 bool for_default)
4268{
4269 List *result = NIL;
4270 ListCell *cell1,
4271 *cell2,
4274 int i,
4275 j;
4276 PartitionRangeDatum *ldatum,
4277 *udatum;
4279 Expr *keyCol;
4281 *upper_val;
4284 int num_or_arms,
4290
4291 if (spec->is_default)
4292 {
4295 Oid *inhoids = pdesc->oids;
4296 int nparts = pdesc->nparts,
4297 k;
4298
4299 for (k = 0; k < nparts; k++)
4300 {
4301 Oid inhrelid = inhoids[k];
4302 HeapTuple tuple;
4303 Datum datum;
4305
4306 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(inhrelid));
4307 if (!HeapTupleIsValid(tuple))
4308 elog(ERROR, "cache lookup failed for relation %u", inhrelid);
4309
4310 datum = SysCacheGetAttrNotNull(RELOID, tuple,
4315 elog(ERROR, "expected PartitionBoundSpec");
4316
4317 if (!bspec->is_default)
4318 {
4319 List *part_qual;
4320
4321 part_qual = get_qual_for_range(parent, bspec, true);
4322
4323 /*
4324 * AND the constraints of the partition and add to
4325 * or_expr_args
4326 */
4329 : linitial(part_qual));
4330 }
4331 ReleaseSysCache(tuple);
4332 }
4333
4334 if (or_expr_args != NIL)
4335 {
4337
4338 /*
4339 * Combine the constraints obtained for non-default partitions
4340 * using OR. As requested, each of the OR's args doesn't include
4341 * the NOT NULL test for partition keys (which is to avoid its
4342 * useless repetition). Add the same now.
4343 */
4349 -1)
4351 -1);
4352
4353 /*
4354 * Finally, the default partition contains everything *NOT*
4355 * contained in the non-default partitions.
4356 */
4359 }
4360
4361 return result;
4362 }
4363
4364 /*
4365 * If it is the recursive call for default, we skip the get_range_nulltest
4366 * to avoid accumulating the NullTest on the same keys for each partition.
4367 */
4368 if (!for_default)
4369 result = get_range_nulltest(key);
4370
4371 /*
4372 * Iterate over the key columns and check if the corresponding lower and
4373 * upper datums are equal using the btree equality operator for the
4374 * column's type. If equal, we emit single keyCol = common_value
4375 * expression. Starting from the first column for which the corresponding
4376 * lower and upper bound datums are not equal, we generate OR expressions
4377 * as shown in the function's header comment.
4378 */
4379 i = 0;
4380 partexprs_item = list_head(key->partexprs);
4381 partexprs_item_saved = partexprs_item; /* placate compiler */
4382 forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
4383 {
4384 EState *estate;
4386 Expr *test_expr;
4389 bool isNull;
4390
4393
4394 /*
4395 * Since get_range_key_properties() modifies partexprs_item, and we
4396 * might need to start over from the previous expression in the later
4397 * part of this function, save away the current value.
4398 */
4400
4401 get_range_key_properties(key, i, ldatum, udatum,
4403 &keyCol,
4404 &lower_val, &upper_val);
4405
4406 /*
4407 * If either value is NULL, the corresponding partition bound is
4408 * either MINVALUE or MAXVALUE, and we treat them as unequal, because
4409 * even if they're the same, there is no common value to equate the
4410 * key column with.
4411 */
4412 if (!lower_val || !upper_val)
4413 break;
4414
4415 /* Create the test expression */
4416 estate = CreateExecutorState();
4419 (Expr *) lower_val,
4420 (Expr *) upper_val);
4424 GetPerTupleExprContext(estate),
4425 &isNull);
4427 FreeExecutorState(estate);
4428
4429 /* If not equal, go generate the OR expressions */
4431 break;
4432
4433 /*
4434 * The bounds for the last key column can't be equal, because such a
4435 * range partition would never be allowed to be defined (it would have
4436 * an empty range otherwise).
4437 */
4438 if (i == key->partnatts - 1)
4439 elog(ERROR, "invalid range bound specification");
4440
4441 /* Equal, so generate keyCol = lower_val expression */
4442 result = lappend(result,
4444 keyCol, (Expr *) lower_val));
4445
4446 i++;
4447 }
4448
4449 /* First pair of lower_val and upper_val that are not equal. */
4452
4453 /* OR will have as many arms as there are key columns left. */
4454 num_or_arms = key->partnatts - i;
4455 current_or_arm = 0;
4458 while (current_or_arm < num_or_arms)
4459 {
4462
4463 /* Restart scan of columns from the i'th one */
4464 j = i;
4466
4468 cell2, spec->upperdatums, upper_or_start_datum)
4469 {
4471 *udatum_next = NULL;
4472
4474 if (lnext(spec->lowerdatums, cell1))
4476 lfirst(lnext(spec->lowerdatums, cell1)));
4478 if (lnext(spec->upperdatums, cell2))
4480 lfirst(lnext(spec->upperdatums, cell2)));
4481 get_range_key_properties(key, j, ldatum, udatum,
4483 &keyCol,
4484 &lower_val, &upper_val);
4485
4487 {
4488 uint16 strategy;
4489
4490 /*
4491 * For the non-last columns of this arm, use the EQ operator.
4492 * For the last column of this arm, use GT, unless this is the
4493 * last column of the whole bound check, or the next bound
4494 * datum is MINVALUE, in which case use GE.
4495 */
4496 if (j - i < current_or_arm)
4497 strategy = BTEqualStrategyNumber;
4498 else if (j == key->partnatts - 1 ||
4499 (ldatum_next &&
4502 else
4503 strategy = BTGreaterStrategyNumber;
4504
4507 strategy,
4508 keyCol,
4509 (Expr *) lower_val));
4510 }
4511
4513 {
4514 uint16 strategy;
4515
4516 /*
4517 * For the non-last columns of this arm, use the EQ operator.
4518 * For the last column of this arm, use LT, unless the next
4519 * bound datum is MAXVALUE, in which case use LE.
4520 */
4521 if (j - i < current_or_arm)
4522 strategy = BTEqualStrategyNumber;
4523 else if (udatum_next &&
4525 strategy = BTLessEqualStrategyNumber;
4526 else
4527 strategy = BTLessStrategyNumber;
4528
4531 strategy,
4532 keyCol,
4533 (Expr *) upper_val));
4534 }
4535
4536 /*
4537 * Did we generate enough of OR's arguments? First arm considers
4538 * the first of the remaining columns, second arm considers first
4539 * two of the remaining columns, and so on.
4540 */
4541 ++j;
4542 if (j - i > current_or_arm)
4543 {
4544 /*
4545 * We must not emit any more arms if the new column that will
4546 * be considered is unbounded, or this one was.
4547 */
4548 if (!lower_val || !ldatum_next ||
4550 need_next_lower_arm = false;
4551 if (!upper_val || !udatum_next ||
4553 need_next_upper_arm = false;
4554 break;
4555 }
4556 }
4557
4558 if (lower_or_arm_args != NIL)
4563
4564 if (upper_or_arm_args != NIL)
4569
4570 /* If no work to do in the next iteration, break away. */
4572 break;
4573
4575 }
4576
4577 /*
4578 * Generate the OR expressions for each of lower and upper bounds (if
4579 * required), and append to the list of implicitly ANDed list of
4580 * expressions.
4581 */
4582 if (lower_or_arms != NIL)
4583 result = lappend(result,
4587 if (upper_or_arms != NIL)
4588 result = lappend(result,
4592
4593 /*
4594 * As noted above, for non-default, we return list with constant TRUE. If
4595 * the result is NIL during the recursive call for default, it implies
4596 * this is the only other partition which can hold every value of the key
4597 * except NULL. Hence we return the NullTest result skipped earlier.
4598 */
4599 if (result == NIL)
4600 result = for_default
4601 ? get_range_nulltest(key)
4603
4604 return result;
4605}
4606
4607/*
4608 * get_range_key_properties
4609 * Returns range partition key information for a given column
4610 *
4611 * This is a subroutine for get_qual_for_range, and its API is pretty
4612 * specialized to that caller.
4613 *
4614 * Constructs an Expr for the key column (returned in *keyCol) and Consts
4615 * for the lower and upper range limits (returned in *lower_val and
4616 * *upper_val). For MINVALUE/MAXVALUE limits, NULL is returned instead of
4617 * a Const. All of these structures are freshly palloc'd.
4618 *
4619 * *partexprs_item points to the cell containing the next expression in
4620 * the key->partexprs list, or NULL. It may be advanced upon return.
4621 */
4622static void
4624 PartitionRangeDatum *ldatum,
4627 Expr **keyCol,
4629{
4630 /* Get partition key expression for this column */
4631 if (key->partattrs[keynum] != 0)
4632 {
4633 *keyCol = (Expr *) makeVar(1,
4634 key->partattrs[keynum],
4635 key->parttypid[keynum],
4636 key->parttypmod[keynum],
4637 key->parttypcoll[keynum],
4638 0);
4639 }
4640 else
4641 {
4642 if (*partexprs_item == NULL)
4643 elog(ERROR, "wrong number of partition key expressions");
4645 *partexprs_item = lnext(key->partexprs, *partexprs_item);
4646 }
4647
4648 /* Get appropriate Const nodes for the bounds */
4649 if (ldatum->kind == PARTITION_RANGE_DATUM_VALUE)
4650 *lower_val = castNode(Const, copyObject(ldatum->value));
4651 else
4652 *lower_val = NULL;
4653
4656 else
4657 *upper_val = NULL;
4658}
4659
4660/*
4661 * get_range_nulltest
4662 *
4663 * A non-default range partition table does not currently allow partition
4664 * keys to be null, so emit an IS NOT NULL expression for each key column.
4665 */
4666static List *
4668{
4669 List *result = NIL;
4672 int i;
4673
4674 partexprs_item = list_head(key->partexprs);
4675 for (i = 0; i < key->partnatts; i++)
4676 {
4677 Expr *keyCol;
4678
4679 if (key->partattrs[i] != 0)
4680 {
4681 keyCol = (Expr *) makeVar(1,
4682 key->partattrs[i],
4683 key->parttypid[i],
4684 key->parttypmod[i],
4685 key->parttypcoll[i],
4686 0);
4687 }
4688 else
4689 {
4690 if (partexprs_item == NULL)
4691 elog(ERROR, "wrong number of partition key expressions");
4693 partexprs_item = lnext(key->partexprs, partexprs_item);
4694 }
4695
4697 nulltest->arg = keyCol;
4698 nulltest->nulltesttype = IS_NOT_NULL;
4699 nulltest->argisrow = false;
4700 nulltest->location = -1;
4701 result = lappend(result, nulltest);
4702 }
4703
4704 return result;
4705}
4706
4707/*
4708 * compute_partition_hash_value
4709 *
4710 * Compute the hash value for given partition key values.
4711 */
4712uint64
4713compute_partition_hash_value(int partnatts, FmgrInfo *partsupfunc, const Oid *partcollation,
4714 const Datum *values, const bool *isnull)
4715{
4716 int i;
4717 uint64 rowHash = 0;
4719
4720 for (i = 0; i < partnatts; i++)
4721 {
4722 /* Nulls are just ignored */
4723 if (!isnull[i])
4724 {
4725 Datum hash;
4726
4727 Assert(OidIsValid(partsupfunc[i].fn_oid));
4728
4729 /*
4730 * Compute hash for each datum value by calling respective
4731 * datatype-specific hash functions of each partition key
4732 * attribute.
4733 */
4734 hash = FunctionCall2Coll(&partsupfunc[i], partcollation[i],
4735 values[i], seed);
4736
4737 /* Form a single 64-bit hash value */
4739 }
4740 }
4741
4742 return rowHash;
4743}
4744
4745/*
4746 * satisfies_hash_partition
4747 *
4748 * This is an SQL-callable function for use in hash partition constraints.
4749 * The first three arguments are the parent table OID, modulus, and remainder.
4750 * The remaining arguments are the value of the partitioning columns (or
4751 * expressions); these are hashed and the results are combined into a single
4752 * hash value by calling hash_combine64.
4753 *
4754 * Returns true if remainder produced when this computed single hash value is
4755 * divided by the given modulus is equal to given remainder, otherwise false.
4756 * NB: it's important that this never return null, as the constraint machinery
4757 * would consider that to be a "pass".
4758 *
4759 * See get_qual_for_hash() for usage.
4760 */
4761Datum
4763{
4764 typedef struct ColumnsHashData
4765 {
4766 Oid relid;
4767 int nkeys;
4770 bool variadic_typbyval;
4771 char variadic_typalign;
4773 FmgrInfo partsupfunc[FLEXIBLE_ARRAY_MEMBER];
4775 Oid parentId;
4776 int modulus;
4777 int remainder;
4780 uint64 rowHash = 0;
4781
4782 /* Return false if the parent OID, modulus, or remainder is NULL. */
4783 if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
4784 PG_RETURN_BOOL(false);
4786 modulus = PG_GETARG_INT32(1);
4788
4789 /* Sanity check modulus and remainder. */
4790 if (modulus <= 0)
4791 ereport(ERROR,
4793 errmsg("modulus for hash partition must be an integer value greater than zero")));
4794 if (remainder < 0)
4795 ereport(ERROR,
4797 errmsg("remainder for hash partition must be an integer value greater than or equal to zero")));
4798 if (remainder >= modulus)
4799 ereport(ERROR,
4801 errmsg("remainder for hash partition must be less than modulus")));
4802
4803 /*
4804 * Cache hash function information.
4805 */
4806 my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
4807 if (my_extra == NULL || my_extra->relid != parentId)
4808 {
4809 Relation parent;
4811 int j;
4812
4813 /* Open parent relation and fetch partition key info */
4815 key = RelationGetPartitionKey(parent);
4816
4817 /* Reject parent table that is not hash-partitioned. */
4818 if (key == NULL || key->strategy != PARTITION_STRATEGY_HASH)
4819 ereport(ERROR,
4821 errmsg("\"%s\" is not a hash partitioned table",
4823
4824 if (!get_fn_expr_variadic(fcinfo->flinfo))
4825 {
4826 int nargs = PG_NARGS() - 3;
4827
4828 /* complain if wrong number of column values */
4829 if (key->partnatts != nargs)
4830 ereport(ERROR,
4832 errmsg("number of partitioning columns (%d) does not match number of partition keys provided (%d)",
4833 key->partnatts, nargs)));
4834
4835 /* allocate space for our cache */
4836 fcinfo->flinfo->fn_extra =
4837 MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
4838 offsetof(ColumnsHashData, partsupfunc) +
4839 sizeof(FmgrInfo) * nargs);
4840 my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
4841 my_extra->relid = parentId;
4842 my_extra->nkeys = key->partnatts;
4843 memcpy(my_extra->partcollid, key->partcollation,
4844 key->partnatts * sizeof(Oid));
4845
4846 /* check argument types and save fmgr_infos */
4847 for (j = 0; j < key->partnatts; ++j)
4848 {
4849 Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, j + 3);
4850
4851 if (argtype != key->parttypid[j] && !IsBinaryCoercible(argtype, key->parttypid[j]))
4852 ereport(ERROR,
4854 errmsg("column %d of the partition key has type %s, but supplied value is of type %s",
4855 j + 1, format_type_be(key->parttypid[j]), format_type_be(argtype))));
4856
4857 fmgr_info_copy(&my_extra->partsupfunc[j],
4858 &key->partsupfunc[j],
4859 fcinfo->flinfo->fn_mcxt);
4860 }
4861 }
4862 else
4863 {
4865
4866 /* allocate space for our cache -- just one FmgrInfo in this case */
4867 fcinfo->flinfo->fn_extra =
4868 MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
4869 offsetof(ColumnsHashData, partsupfunc) +
4870 sizeof(FmgrInfo));
4871 my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
4872 my_extra->relid = parentId;
4873 my_extra->nkeys = key->partnatts;
4874 my_extra->variadic_type = ARR_ELEMTYPE(variadic_array);
4875 get_typlenbyvalalign(my_extra->variadic_type,
4876 &my_extra->variadic_typlen,
4877 &my_extra->variadic_typbyval,
4878 &my_extra->variadic_typalign);
4879 my_extra->partcollid[0] = key->partcollation[0];
4880
4881 /* check argument types */
4882 for (j = 0; j < key->partnatts; ++j)
4883 if (key->parttypid[j] != my_extra->variadic_type)
4884 ereport(ERROR,
4886 errmsg("column %d of the partition key has type \"%s\", but supplied value is of type \"%s\"",
4887 j + 1,
4888 format_type_be(key->parttypid[j]),
4889 format_type_be(my_extra->variadic_type))));
4890
4891 fmgr_info_copy(&my_extra->partsupfunc[0],
4892 &key->partsupfunc[0],
4893 fcinfo->flinfo->fn_mcxt);
4894 }
4895
4896 /* Hold lock until commit */
4897 relation_close(parent, NoLock);
4898 }
4899
4900 if (!OidIsValid(my_extra->variadic_type))
4901 {
4902 int nkeys = my_extra->nkeys;
4903 int i;
4904
4905 /*
4906 * For a non-variadic call, neither the number of arguments nor their
4907 * types can change across calls, so avoid the expense of rechecking
4908 * here.
4909 */
4910
4911 for (i = 0; i < nkeys; i++)
4912 {
4913 Datum hash;
4914
4915 /* keys start from fourth argument of function. */
4916 int argno = i + 3;
4917
4918 if (PG_ARGISNULL(argno))
4919 continue;
4920
4921 hash = FunctionCall2Coll(&my_extra->partsupfunc[i],
4922 my_extra->partcollid[i],
4924 seed);
4925
4926 /* Form a single 64-bit hash value */
4928 }
4929 }
4930 else
4931 {
4933 int i;
4934 int nelems;
4935 Datum *datum;
4936 bool *isnull;
4937
4939 my_extra->variadic_type,
4940 my_extra->variadic_typlen,
4941 my_extra->variadic_typbyval,
4942 my_extra->variadic_typalign,
4943 &datum, &isnull, &nelems);
4944
4945 /* complain if wrong number of column values */
4946 if (nelems != my_extra->nkeys)
4947 ereport(ERROR,
4949 errmsg("number of partitioning columns (%d) does not match number of partition keys provided (%d)",
4950 my_extra->nkeys, nelems)));
4951
4952 for (i = 0; i < nelems; i++)
4953 {
4954 Datum hash;
4955
4956 if (isnull[i])
4957 continue;
4958
4959 hash = FunctionCall2Coll(&my_extra->partsupfunc[0],
4960 my_extra->partcollid[0],
4961 datum[i],
4962 seed);
4963
4964 /* Form a single 64-bit hash value */
4966 }
4967 }
4968
4969 PG_RETURN_BOOL(rowHash % modulus == remainder);
4970}
4971
4972/*
4973 * check_two_partitions_bounds_range
4974 *
4975 * (function for BY RANGE partitioning)
4976 *
4977 * This is a helper function for check_partitions_for_split() and
4978 * calculate_partition_bound_for_merge(). This function compares the upper
4979 * bound of first_bound and the lower bound of second_bound. These bounds
4980 * should be equal except when "defaultPart == true" (this means that one of
4981 * the split partitions is DEFAULT). In this case, the upper bound of
4982 * first_bound can be less than the lower bound of second_bound because
4983 * the space between these bounds will be included in the DEFAULT partition.
4984 *
4985 * parent: partitioned table
4986 * first_name: name of the first partition
4987 * first_bound: bound of the first partition
4988 * second_name: name of the second partition
4989 * second_bound: bound of the second partition
4990 * defaultPart: true if one of the new partitions is DEFAULT
4991 * is_merge: true indicates the operation is MERGE PARTITIONS;
4992 * false indicates the operation is SPLIT PARTITION.
4993 * pstate: pointer to ParseState struct for determining error position
4994 */
4995static void
5001 bool defaultPart,
5002 bool is_merge,
5003 ParseState *pstate)
5004{
5008 int cmpval;
5009
5010 Assert(key->strategy == PARTITION_STRATEGY_RANGE);
5011
5012 first_upper = make_one_partition_rbound(key, -1, first_bound->upperdatums, false);
5013 second_lower = make_one_partition_rbound(key, -1, second_bound->lowerdatums, true);
5014
5015 /*
5016 * lower1 argument of partition_rbound_cmp() is set to false for the
5017 * correct comparison result of the lower and upper bounds.
5018 */
5019 cmpval = partition_rbound_cmp(key->partnatts,
5020 key->partsupfunc,
5021 key->partcollation,
5022 second_lower->datums, second_lower->kind,
5023 false, first_upper);
5024 if ((!defaultPart && cmpval) || (defaultPart && cmpval < 0))
5025 {
5026 PartitionRangeDatum *datum = linitial(second_bound->lowerdatums);
5027
5028 if (is_merge)
5029 ereport(ERROR,
5031 errmsg("can not merge partition \"%s\" together with partition \"%s\"",
5032 second_name->relname, first_name->relname),
5033 errdetail("lower bound of partition \"%s\" is not equal to the upper bound of partition \"%s\"",
5034 second_name->relname, first_name->relname),
5035 errhint("ALTER TABLE ... MERGE PARTITIONS requires the partition bounds to be adjacent."),
5036 parser_errposition(pstate, datum->location));
5037 else
5038 ereport(ERROR,
5040 errmsg("can not split to partition \"%s\" together with partition \"%s\"",
5041 second_name->relname, first_name->relname),
5042 errdetail("lower bound of partition \"%s\" is not equal to the upper bound of partition \"%s\"",
5043 second_name->relname, first_name->relname),
5044 errhint("ALTER TABLE ... SPLIT PARTITION requires the partition bounds to be adjacent."),
5045 parser_errposition(pstate, datum->location));
5046 }
5047}
5048
5049/*
5050 * get_partition_bound_spec
5051 *
5052 * Returns the PartitionBoundSpec for the partition with the given OID partOid.
5053 */
5054static PartitionBoundSpec *
5056{
5057 HeapTuple tuple;
5058 Datum datum;
5059 bool isnull;
5061
5062 /* Try fetching the tuple from the catcache, for speed. */
5063 tuple = SearchSysCache1(RELOID, partOid);
5064 if (!HeapTupleIsValid(tuple))
5065 elog(ERROR, "cache lookup failed for relation %u", partOid);
5066
5067 datum = SysCacheGetAttr(RELOID, tuple,
5069 &isnull);
5070 if (isnull)
5071 elog(ERROR, "partition bound for relation %u is null",
5072 partOid);
5073
5075
5077 elog(ERROR, "expected PartitionBoundSpec for relation %u",
5078 partOid);
5079
5080 ReleaseSysCache(tuple);
5081 return boundspec;
5082}
5083
5084/*
5085 * calculate_partition_bound_for_merge
5086 *
5087 * Calculates the bound of the merged partition "spec" by using the bounds of
5088 * the partitions to be merged.
5089 *
5090 * parent: partitioned table
5091 * partNames: names of partitions to be merged
5092 * partOids: Oids of partitions to be merged
5093 * spec (out): bounds specification of the merged partition
5094 * pstate: pointer to ParseState struct to determine error position
5095 */
5096void
5098 List *partNames,
5099 List *partOids,
5101 ParseState *pstate)
5102{
5104 PartitionBoundSpec *bound;
5105
5106 Assert(!spec->is_default);
5107
5108 switch (key->strategy)
5109 {
5111 {
5112 int i;
5114 int nparts = list_length(partOids);
5115 List *bounds = NIL;
5116
5118
5119 /*
5120 * Create an array of lower bounds and a list of
5121 * PartitionBoundSpec.
5122 */
5123 foreach_oid(partoid, partOids)
5124 {
5125 bound = get_partition_bound_spec(partoid);
5126 i = foreach_current_index(partoid);
5127
5128 lower_bounds[i] = make_one_partition_rbound(key, i, bound->lowerdatums, true);
5129 bounds = lappend(bounds, bound);
5130 }
5131
5132 /* Sort the array of lower bounds. */
5133 qsort_arg(lower_bounds, nparts, sizeof(PartitionRangeBound *),
5135
5136 /* Ranges of partitions should be adjacent. */
5137 for (i = 1; i < nparts; i++)
5138 {
5139 int index = lower_bounds[i]->index;
5140 int prev_index = lower_bounds[i - 1]->index;
5141
5147 false,
5148 true,
5149 pstate);
5150 }
5151
5152 /*
5153 * The lower bound of the first partition is the lower bound
5154 * of the merged partition.
5155 */
5156 spec->lowerdatums =
5157 ((PartitionBoundSpec *) list_nth(bounds, lower_bounds[0]->index))->lowerdatums;
5158
5159 /*
5160 * The upper bound of the last partition is the upper bound of
5161 * the merged partition.
5162 */
5163 spec->upperdatums =
5164 ((PartitionBoundSpec *) list_nth(bounds, lower_bounds[nparts - 1]->index))->upperdatums;
5165
5168 break;
5169 }
5170
5172 {
5173 /* Consolidate bounds for all partitions in the list. */
5174 foreach_oid(partoid, partOids)
5175 {
5176 bound = get_partition_bound_spec(partoid);
5177 spec->listdatums = list_concat(spec->listdatums, bound->listdatums);
5178 }
5179 break;
5180 }
5181
5182 default:
5183 elog(ERROR, "unexpected partition strategy: %d",
5184 (int) key->strategy);
5185 }
5186}
5187
5188/*
5189 * partitions_listdatum_intersection
5190 *
5191 * (function for BY LIST partitioning)
5192 *
5193 * Function compares lists of values for different partitions.
5194 * Return a list that contains *one* cell that is present in both list1 and
5195 * list2. The returned list is freshly allocated via palloc(), but the
5196 * cells themselves point to the same objects as the cells of the
5197 * input lists.
5198 *
5199 * Currently, there is no need to collect all common partition datums from the
5200 * two lists.
5201 */
5202static List *
5203partitions_listdatum_intersection(FmgrInfo *partsupfunc, Oid *partcollation,
5204 const List *list1, const List *list2)
5205{
5206 List *result = NIL;
5207
5208 if (list1 == NIL || list2 == NIL)
5209 return result;
5210
5212 {
5213 bool isnull1 = val1->constisnull;
5214
5216 {
5217 if (val2->constisnull)
5218 {
5219 if (isnull1)
5220 {
5221 result = lappend(result, val1);
5222 return result;
5223 }
5224 continue;
5225 }
5226 else if (isnull1)
5227 continue;
5228
5229 /* Compare two datum values. */
5230 if (DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
5231 partcollation[0],
5232 val1->constvalue,
5233 val2->constvalue)) == 0)
5234 {
5235 result = lappend(result, val1);
5236 return result;
5237 }
5238 }
5239 }
5240
5241 return result;
5242}
5243
5244/*
5245 * check_partitions_not_overlap_list
5246 *
5247 * (function for BY LIST partitioning)
5248 *
5249 * This is a helper function for check_partitions_for_split().
5250 * Checks that the values of the new partitions do not overlap.
5251 *
5252 * parent: partitioned table
5253 * parts: array of SinglePartitionSpec structs with info about split partitions
5254 * nparts: size of array "parts"
5255 */
5256static void
5259 int nparts,
5260 ParseState *pstate)
5261{
5263 int i,
5264 j;
5266 *sps2;
5267 List *overlap;
5268
5269 Assert(key->strategy == PARTITION_STRATEGY_LIST);
5270
5271 for (i = 0; i < nparts; i++)
5272 {
5273 sps1 = parts[i];
5274
5275 for (j = i + 1; j < nparts; j++)
5276 {
5277 sps2 = parts[j];
5278
5279 overlap = partitions_listdatum_intersection(&key->partsupfunc[0],
5280 key->partcollation,
5281 sps1->bound->listdatums,
5282 sps2->bound->listdatums);
5283 if (list_length(overlap) > 0)
5284 {
5285 Const *val = (Const *) linitial_node(Const, overlap);
5286
5287 ereport(ERROR,
5289 errmsg("new partition \"%s\" would overlap with another new partition \"%s\"",
5290 sps1->name->relname, sps2->name->relname),
5291 parser_errposition(pstate, exprLocation((Node *) val)));
5292 }
5293 }
5294 }
5295}
5296
5297/*
5298 * check_partition_bounds_for_split_range
5299 *
5300 * (function for BY RANGE partitioning)
5301 *
5302 * Checks that bounds of new partition "spec" are inside bounds of split
5303 * partition (with Oid splitPartOid). If first=true (this means that "spec" is
5304 * the first of the new partitions), then the lower bound of "spec" should be
5305 * equal (or greater than or equal in case defaultPart=true) to the lower
5306 * bound of the split partition. If last=true (this means that "spec" is the
5307 * last of the new partitions), then the upper bound of "spec" should be
5308 * equal (or less than or equal in case defaultPart=true) to the upper bound
5309 * of the split partition.
5310 *
5311 * parent: partitioned table
5312 * relname: name of the new partition
5313 * spec: bounds specification of the new partition
5314 * splitPartOid: split partition Oid
5315 * first: true iff the new partition "spec" is the first of the
5316 * new partitions
5317 * last: true iff the new partition "spec" is the last of the
5318 * new partitions
5319 * defaultPart: true iff new partitions contain the DEFAULT partition
5320 * pstate: pointer to ParseState struct to determine error position
5321 */
5322static void
5324 char *relname,
5327 bool first,
5328 bool last,
5329 bool defaultPart,
5330 ParseState *pstate)
5331{
5334 *upper;
5335 int cmpval;
5336
5337 Assert(key->strategy == PARTITION_STRATEGY_RANGE);
5338 Assert(spec->strategy == PARTITION_STRATEGY_RANGE);
5339
5340 lower = make_one_partition_rbound(key, -1, spec->lowerdatums, true);
5341 upper = make_one_partition_rbound(key, -1, spec->upperdatums, false);
5342
5343 /*
5344 * First, check if the resulting range would be empty with the specified
5345 * lower and upper bounds. partition_rbound_cmp cannot return zero here,
5346 * since the lower-bound flags are different.
5347 */
5348 cmpval = partition_rbound_cmp(key->partnatts,
5349 key->partsupfunc,
5350 key->partcollation,
5351 lower->datums, lower->kind,
5352 true, upper);
5353 Assert(cmpval != 0);
5354 if (cmpval > 0)
5355 {
5356 /* Point to the problematic key in the lower datums list. */
5357 PartitionRangeDatum *datum = list_nth(spec->lowerdatums, cmpval - 1);
5358
5359 ereport(ERROR,
5361 errmsg("empty range bound specified for partition \"%s\"",
5362 relname),
5363 errdetail("Specified lower bound %s is greater than or equal to upper bound %s.",
5364 get_range_partbound_string(spec->lowerdatums),
5365 get_range_partbound_string(spec->upperdatums)),
5366 parser_errposition(pstate, exprLocation((Node *) datum)));
5367 }
5368
5369 /*
5370 * Need to check first and last partitions (from the set of new
5371 * partitions)
5372 */
5373 if (first || last)
5374 {
5376 PartitionRangeDatum *datum;
5377
5378 if (first)
5379 {
5381
5382 split_lower = make_one_partition_rbound(key, -1, split_spec->lowerdatums, true);
5383
5384 cmpval = partition_rbound_cmp(key->partnatts,
5385 key->partsupfunc,
5386 key->partcollation,
5387 lower->datums, lower->kind,
5388 true, split_lower);
5389 if (cmpval != 0)
5390 datum = list_nth(spec->lowerdatums, abs(cmpval) - 1);
5391
5392 /*
5393 * The lower bound of "spec" must equal the lower bound of the
5394 * split partition. However, if one of the new partitions is
5395 * DEFAULT, then it is ok for the new partition's lower bound to
5396 * be greater than that of the split partition.
5397 */
5398 if (!defaultPart)
5399 {
5400 if (cmpval != 0)
5401 ereport(ERROR,
5403 errmsg("lower bound of partition \"%s\" is not equal to lower bound of split partition \"%s\"",
5404 relname,
5406 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5407 "ALTER TABLE ... SPLIT PARTITION"),
5408 parser_errposition(pstate, exprLocation((Node *) datum)));
5409 }
5410 else if (cmpval < 0)
5411 ereport(ERROR,
5413 errmsg("lower bound of partition \"%s\" is less than lower bound of split partition \"%s\"",
5414 relname,
5416 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5417 "ALTER TABLE ... SPLIT PARTITION"),
5418 parser_errposition(pstate, exprLocation((Node *) datum)));
5419 }
5420 else
5421 {
5423
5424 split_upper = make_one_partition_rbound(key, -1, split_spec->upperdatums, false);
5425
5426 cmpval = partition_rbound_cmp(key->partnatts,
5427 key->partsupfunc,
5428 key->partcollation,
5429 upper->datums, upper->kind,
5430 false, split_upper);
5431 if (cmpval != 0)
5432 datum = list_nth(spec->upperdatums, abs(cmpval) - 1);
5433
5434 /*
5435 * The upper bound of "spec" must equal the upper bound of the
5436 * split partition. However, if one of the new partitions is
5437 * DEFAULT, then it is ok for the new partition's upper bound to
5438 * be less than that of the split partition.
5439 */
5440 if (!defaultPart)
5441 {
5442 if (cmpval != 0)
5443 ereport(ERROR,
5445 errmsg("upper bound of partition \"%s\" is not equal to upper bound of split partition \"%s\"",
5446 relname,
5448 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5449 "ALTER TABLE ... SPLIT PARTITION"),
5450 parser_errposition(pstate, exprLocation((Node *) datum)));
5451 }
5452 else if (cmpval > 0)
5453 ereport(ERROR,
5455 errmsg("upper bound of partition \"%s\" is greater than upper bound of split partition \"%s\"",
5456 relname,
5458 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5459 "ALTER TABLE ... SPLIT PARTITION"),
5460 parser_errposition(pstate, exprLocation((Node *) datum)));
5461 }
5462 }
5463}
5464
5465/*
5466 * check_partition_bounds_for_split_list
5467 *
5468 * (function for BY LIST partitioning)
5469 *
5470 * Checks that the bounds of the new partition are inside the bounds of the
5471 * split partition (with Oid splitPartOid).
5472 *
5473 * parent: partitioned table
5474 * relname: name of the new partition
5475 * spec: bounds specification of the new partition
5476 * splitPartOid: split partition Oid
5477 * pstate: pointer to ParseState struct to determine error position
5478 */
5479static void
5483 ParseState *pstate)
5484{
5486 PartitionDesc partdesc = RelationGetPartitionDesc(parent, false);
5487 PartitionBoundInfo boundinfo = partdesc->boundinfo;
5488 int with = -1;
5489 bool overlap = false;
5490 int overlap_location = -1;
5491
5492 Assert(key->strategy == PARTITION_STRATEGY_LIST);
5493 Assert(spec->strategy == PARTITION_STRATEGY_LIST);
5494 Assert(boundinfo && boundinfo->strategy == PARTITION_STRATEGY_LIST);
5495
5496 /*
5497 * Search each value of the new partition "spec" in the existing
5498 * partitions. All of them should be in the split partition (with Oid
5499 * splitPartOid).
5500 */
5501 foreach_node(Const, val, spec->listdatums)
5502 {
5504 if (!val->constisnull)
5505 {
5506 int offset;
5507 bool equal;
5508
5509 offset = partition_list_bsearch(&key->partsupfunc[0],
5510 key->partcollation,
5511 boundinfo,
5512 val->constvalue,
5513 &equal);
5514 if (offset >= 0 && equal)
5515 {
5516 with = boundinfo->indexes[offset];
5517 if (partdesc->oids[with] != splitPartOid)
5518 {
5519 overlap = true;
5520 break;
5521 }
5522 }
5523 else
5524 ereport(ERROR,
5526 errmsg("new partition \"%s\" cannot have this value because split partition \"%s\" does not have",
5527 relname,
5530 }
5531 else if (partition_bound_accepts_nulls(boundinfo))
5532 {
5533 with = boundinfo->null_index;
5534 if (partdesc->oids[with] != splitPartOid)
5535 {
5536 overlap = true;
5537 break;
5538 }
5539 }
5540 else
5541 ereport(ERROR,
5543 errmsg("new partition \"%s\" cannot have NULL value because split partition \"%s\" does not have",
5544 relname,
5547 }
5548
5549 if (overlap)
5550 {
5551 Assert(with >= 0);
5552 ereport(ERROR,
5554 errmsg("new partition \"%s\" would overlap with another (not split) partition \"%s\"",
5555 relname, get_rel_name(partdesc->oids[with])),
5557 }
5558}
5559
5560/*
5561 * find_value_in_new_partitions_list
5562 *
5563 * (function for BY LIST partitioning)
5564 *
5565 * Function returns true iff any of the new partitions contains the value
5566 * "value".
5567 *
5568 * partsupfunc: information about the comparison function associated with
5569 * the partition key
5570 * partcollation: partitioning collation
5571 * parts: pointer to an array with new partition descriptions
5572 * nparts: number of new partitions
5573 * value: the value that we are looking for
5574 * isnull: true if the value that we are looking for is NULL
5575 */
5576static bool
5578 Oid *partcollation,
5580 int nparts,
5581 Datum value,
5582 bool isnull)
5583{
5584 for (int i = 0; i < nparts; i++)
5585 {
5587
5588 foreach_node(Const, val, sps->bound->listdatums)
5589 {
5590 if (isnull && val->constisnull)
5591 return true;
5592
5593 if (!isnull && !val->constisnull)
5594 {
5595 if (DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
5596 partcollation[0],
5597 val->constvalue,
5598 value)) == 0)
5599 return true;
5600 }
5601 }
5602 }
5603 return false;
5604}
5605
5606/*
5607 * check_parent_values_in_new_partitions
5608 *
5609 * (function for BY LIST partitioning)
5610 *
5611 * Checks that all values of split partition (with Oid partOid) are contained
5612 * in new partitions.
5613 *
5614 * parent: partitioned table
5615 * partOid: split partition Oid
5616 * parts: pointer to an array with new partition descriptions
5617 * nparts: number of new partitions
5618 * pstate: pointer to ParseState struct to determine error position
5619 */
5620static void
5622 Oid partOid,
5624 int nparts,
5625 ParseState *pstate)
5626{
5628 PartitionDesc partdesc = RelationGetPartitionDesc(parent, false);
5629 PartitionBoundInfo boundinfo = partdesc->boundinfo;
5630 int i;
5631 bool found = true;
5632 Datum datum = PointerGetDatum(NULL);
5633
5634 Assert(key->strategy == PARTITION_STRATEGY_LIST);
5635
5636 /*
5637 * Special processing for NULL value. Search for a NULL value if the split
5638 * partition (partOid) contains it.
5639 */
5640 if (partition_bound_accepts_nulls(boundinfo) &&
5641 partdesc->oids[boundinfo->null_index] == partOid)
5642 {
5643 if (!find_value_in_new_partitions_list(&key->partsupfunc[0],
5644 key->partcollation, parts, nparts, datum, true))
5645 found = false;
5646 }
5647
5648 if (!found)
5649 ereport(ERROR,
5651 errmsg("new partitions combined partition bounds do not contain value (%s) but split partition \"%s\" does",
5652 "NULL",
5654 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5655 "ALTER TABLE ... SPLIT PARTITION"));
5656
5657 /*
5658 * Search all values of split partition with partOid in the PartitionDesc
5659 * of partitioned table.
5660 */
5661 for (i = 0; i < boundinfo->ndatums; i++)
5662 {
5663 if (partdesc->oids[boundinfo->indexes[i]] == partOid)
5664 {
5665 /* We found the value that the split partition contains. */
5666 datum = boundinfo->datums[i][0];
5667 if (!find_value_in_new_partitions_list(&key->partsupfunc[0],
5668 key->partcollation, parts, nparts, datum, false))
5669 {
5670 found = false;
5671 break;
5672 }
5673 }
5674 }
5675
5676 if (!found)
5677 {
5679
5680 /*
5681 * Make a Const for getting the string representation of the missing
5682 * value.
5683 */
5684 notFoundVal = makeConst(key->parttypid[0],
5685 key->parttypmod[0],
5686 key->parttypcoll[0],
5687 key->parttyplen[0],
5688 datum,
5689 false, /* isnull */
5690 key->parttypbyval[0]);
5691
5692 ereport(ERROR,
5694 errmsg("new partitions combined partition bounds do not contain value (%s) but split partition \"%s\" does",
5695 deparse_expression((Node *) notFoundVal, NIL, false, false),
5697 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5698 "ALTER TABLE ... SPLIT PARTITION"));
5699 }
5700}
5701
5702/*
5703 * check_partitions_for_split
5704 *
5705 * Checks new partitions for the SPLIT PARTITION command:
5706 * 1. Bounds of new partitions should not overlap with new and existing
5707 * partitions.
5708 * 2. In the case when new or existing partitions contain the DEFAULT
5709 * partition, new partitions can have any bounds inside the split partition
5710 * bound (can be spaces between partition bounds).
5711 * 3. In case new partitions don't contain the DEFAULT partition and the
5712 * partitioned table does not have the DEFAULT partition, the following
5713 * should be true: the sum of the bounds of new partitions should be equal
5714 & to the bound of the split partition.
5715 *
5716 * parent: partitioned table
5717 * splitPartOid: split partition Oid
5718 * partlist: list of new partitions after partition split
5719 * pstate: pointer to ParseState struct for determine error position
5720 */
5721void
5724 List *partlist,
5725 ParseState *pstate)
5726{
5728 char strategy;
5730 bool isSplitPartDefault;
5731 bool createDefaultPart = false;
5732 int default_index = -1;
5733 int i;
5736
5737 /*
5738 * nparts counts the number of split partitions, but it exclude the
5739 * default partition.
5740 */
5741 int nparts = 0;
5742
5743 key = RelationGetPartitionKey(parent);
5744 strategy = get_partition_strategy(key);
5745
5748
5749 Assert(strategy == PARTITION_STRATEGY_RANGE ||
5750 strategy == PARTITION_STRATEGY_LIST);
5751
5752 /*
5753 * Make an array new_parts with new partitions except the DEFAULT
5754 * partition.
5755 */
5757
5758 /* isSplitPartDefault flag: is split partition a DEFAULT partition? */
5760
5762 {
5763 if (sps->bound->is_default)
5764 default_index = foreach_current_index(sps);
5765 else
5766 new_parts[nparts++] = sps;
5767 }
5768
5769 /* An indicator that the DEFAULT partition will be created. */
5770 if (default_index != -1)
5771 {
5772 createDefaultPart = true;
5773 Assert(nparts == list_length(partlist) - 1);
5774 }
5775
5776 if (strategy == PARTITION_STRATEGY_RANGE)
5777 {
5780
5781 /*
5782 * To simplify the check for ranges of new partitions, we need to sort
5783 * all partitions in ascending order of their bounds (we compare the
5784 * lower bound only).
5785 */
5787
5788 /* Create an array of lower bounds. */
5789 for (i = 0; i < nparts; i++)
5790 {
5792 new_parts[i]->bound->lowerdatums, true);
5793 }
5794
5795 /* Sort the array of lower bounds. */
5796 qsort_arg(lower_bounds, nparts, sizeof(PartitionRangeBound *),
5797 qsort_partition_rbound_cmp, (void *) key);
5798
5799 /* Reorder the array of partitions. */
5802 for (i = 0; i < nparts; i++)
5804
5807 }
5808
5809 for (i = 0; i < nparts; i++)
5810 {
5812
5814 {
5815 /*
5816 * When the split partition is the DEFAULT partition, we can use
5817 * any free ranges - as when creating a new partition.
5818 */
5819 check_new_partition_bound(sps->name->relname, parent, sps->bound,
5820 pstate);
5821 }
5822 else
5823 {
5824 /*
5825 * Checks that the bounds of the current partition are inside the
5826 * bounds of the split partition. For range partitioning: checks
5827 * that the upper bound of the previous partition is equal to the
5828 * lower bound of the current partition. For list partitioning:
5829 * checks that the split partition contains all values of the
5830 * current partition.
5831 */
5832 if (strategy == PARTITION_STRATEGY_RANGE)
5833 {
5834 bool first = (i == 0);
5835 bool last = (i == (nparts - 1));
5836
5837 check_partition_bounds_for_split_range(parent, sps->name->relname, sps->bound,
5838 splitPartOid, first, last,
5839 createDefaultPart, pstate);
5840 }
5841 else
5842 check_partition_bounds_for_split_list(parent, sps->name->relname,
5843 sps->bound, splitPartOid, pstate);
5844 }
5845
5846 /* Ranges of new partitions should not overlap. */
5847 if (strategy == PARTITION_STRATEGY_RANGE && spsPrev)
5849 sps->name, sps->bound,
5851 false,
5852 pstate);
5853
5854 spsPrev = sps;
5855 }
5856
5857 if (strategy == PARTITION_STRATEGY_LIST)
5858 {
5859 /* Values of new partitions should not overlap. */
5861 pstate);
5862
5863 /*
5864 * Need to check that all values of the split partition are contained
5865 * in the new partitions. Skip this check if the DEFAULT partition
5866 * exists.
5867 */
5868 if (!createDefaultPart)
5870 new_parts, nparts, pstate);
5871 }
5872
5874}
#define PG_GETARG_ARRAYTYPE_P(n)
Definition array.h:263
#define ARR_ELEMTYPE(a)
Definition array.h:292
void deconstruct_array(const ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:814
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:581
Bitmapset * bms_copy(const Bitmapset *a)
Definition bitmapset.c:122
static Datum values[MAXATTR]
Definition bootstrap.c:155
static void cleanup(void)
Definition bootstrap.c:717
#define TextDatumGetCString(d)
Definition builtins.h:98
#define PG_USED_FOR_ASSERTS_ONLY
Definition c.h:223
#define Max(x, y)
Definition c.h:991
#define Assert(condition)
Definition c.h:873
#define FLEXIBLE_ARRAY_MEMBER
Definition c.h:480
int16_t int16
Definition c.h:541
int32_t int32
Definition c.h:542
uint64_t uint64
Definition c.h:547
uint16_t uint16
Definition c.h:545
#define OidIsValid(objectId)
Definition c.h:788
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition datum.c:132
bool datumIsEqual(Datum value1, Datum value2, bool typByVal, int typLen)
Definition datum.c:223
struct cursor * cur
Definition ecpg.c:29
int errmsg_internal(const char *fmt,...)
Definition elog.c:1170
int errdetail(const char *fmt,...)
Definition elog.c:1216
int errhint(const char *fmt,...)
Definition elog.c:1330
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#define WARNING
Definition elog.h:36
#define DEBUG1
Definition elog.h:30
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition execExpr.c:143
ExprState * ExecPrepareExpr(Expr *node, EState *estate)
Definition execExpr.c:765
bool ExecCheck(ExprState *state, ExprContext *econtext)
Definition execExpr.c:872
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
void FreeExecutorState(EState *estate)
Definition execUtils.c:192
EState * CreateExecutorState(void)
Definition execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition executor.h:656
#define ResetExprContext(econtext)
Definition executor.h:650
#define GetPerTupleMemoryContext(estate)
Definition executor.h:661
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:436
#define palloc_object(type)
Definition fe_memutils.h:74
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define palloc0_array(type, count)
Definition fe_memutils.h:77
#define palloc0_object(type)
Definition fe_memutils.h:75
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition fmgr.c:1150
bool get_fn_expr_variadic(FmgrInfo *flinfo)
Definition fmgr.c:2009
Oid get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
Definition fmgr.c:1875
void fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo, MemoryContext destcxt)
Definition fmgr.c:581
#define PG_GETARG_OID(n)
Definition fmgr.h:275
#define PG_ARGISNULL(n)
Definition fmgr.h:209
#define PG_GETARG_DATUM(n)
Definition fmgr.h:268
#define PG_NARGS()
Definition fmgr.h:203
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
#define PG_RETURN_BOOL(x)
Definition fmgr.h:360
char * format_type_be(Oid type_oid)
static uint64 hash_combine64(uint64 a, uint64 b)
Definition hashfn.h:80
size_t remainder
#define HeapTupleIsValid(tuple)
Definition htup.h:78
#define false
long val
Definition informix.c:689
static struct @172 value
int b
Definition isn.c:74
return true
Definition isn.c:130
int a
Definition isn.c:73
int j
Definition isn.c:78
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
List * list_concat(List *list1, const List *list2)
Definition list.c:561
List * lappend_int(List *list, int datum)
Definition list.c:357
void list_free(List *list)
Definition list.c:1546
#define NoLock
Definition lockdefs.h:34
#define AccessExclusiveLock
Definition lockdefs.h:43
#define AccessShareLock
Definition lockdefs.h:36
char * get_rel_name(Oid relid)
Definition lsyscache.c:2078
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2421
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1435
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition lsyscache.c:168
Oid get_array_type(Oid typid)
Definition lsyscache.c:2937
#define type_is_array(typid)
Definition lsyscache.h:214
Expr * make_ands_explicit(List *andclauses)
Definition makefuncs.c:799
Expr * makeBoolExpr(BoolExprType boolop, List *args, int location)
Definition makefuncs.c:420
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
Node * makeBoolConst(bool value, bool isnull)
Definition makefuncs.c:408
RelabelType * makeRelabelType(Expr *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat)
Definition makefuncs.c:453
FuncExpr * makeFuncExpr(Oid funcid, Oid rettype, List *args, Oid funccollid, Oid inputcollid, CoercionForm fformat)
Definition makefuncs.c:594
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition makefuncs.c:701
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition makefuncs.c:350
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition mcxt.c:1266
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc(Size size)
Definition mcxt.c:1387
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
int exprLocation(const Node *expr)
Definition nodeFuncs.c:1384
void fix_opfuncids(Node *node)
Definition nodeFuncs.c:1840
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define copyObject(obj)
Definition nodes.h:232
#define IS_OUTER_JOIN(jointype)
Definition nodes.h:348
#define makeNode(_type_)
Definition nodes.h:161
#define castNode(_type_, nodeptr)
Definition nodes.h:182
JoinType
Definition nodes.h:298
@ JOIN_SEMI
Definition nodes.h:317
@ JOIN_FULL
Definition nodes.h:305
@ JOIN_INNER
Definition nodes.h:303
@ JOIN_RIGHT
Definition nodes.h:306
@ JOIN_LEFT
Definition nodes.h:304
@ JOIN_ANTI
Definition nodes.h:318
Datum upper(PG_FUNCTION_ARGS)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
bool IsBinaryCoercible(Oid srctype, Oid targettype)
int parser_errposition(ParseState *pstate, int location)
Definition parse_node.c:106
@ PARTITION_STRATEGY_HASH
Definition parsenodes.h:903
@ PARTITION_STRATEGY_LIST
Definition parsenodes.h:901
@ PARTITION_STRATEGY_RANGE
Definition parsenodes.h:902
PartitionRangeDatumKind
Definition parsenodes.h:952
@ PARTITION_RANGE_DATUM_MAXVALUE
Definition parsenodes.h:955
@ PARTITION_RANGE_DATUM_VALUE
Definition parsenodes.h:954
@ PARTITION_RANGE_DATUM_MINVALUE
Definition parsenodes.h:953
static int partition_range_bsearch(int partnatts, FmgrInfo *partsupfunc, Oid *partcollation, PartitionBoundInfo boundinfo, PartitionRangeBound *probe, int32 *cmpval)
static int process_inner_partition(PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_default, bool inner_has_default, int inner_index, int outer_default, JoinType jointype, int *next_index, int *default_index)
static void merge_default_partitions(PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_default, bool inner_has_default, int outer_default, int inner_default, JoinType jointype, int *next_index, int *default_index)
static void init_partition_map(RelOptInfo *rel, PartitionMap *map)
static void check_partition_bounds_for_split_list(Relation parent, char *relname, PartitionBoundSpec *spec, Oid splitPartOid, ParseState *pstate)
static List * get_qual_for_list(Relation parent, PartitionBoundSpec *spec)
static void check_parent_values_in_new_partitions(Relation parent, Oid partOid, SinglePartitionSpec **parts, int nparts, ParseState *pstate)
static int32 qsort_partition_rbound_cmp(const void *a, const void *b, void *arg)
static PartitionBoundInfo create_list_bounds(PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
Definition partbounds.c:461
static bool is_dummy_partition(RelOptInfo *rel, int part_index)
static PartitionBoundInfo merge_range_bounds(int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, RelOptInfo *outer_rel, RelOptInfo *inner_rel, JoinType jointype, List **outer_parts, List **inner_parts)
bool partition_bounds_equal(int partnatts, int16 *parttyplen, bool *parttypbyval, PartitionBoundInfo b1, PartitionBoundInfo b2)
Definition partbounds.c:889
int32 partition_rbound_datum_cmp(FmgrInfo *partsupfunc, Oid *partcollation, const Datum *rb_datums, PartitionRangeDatumKind *rb_kind, const Datum *tuple_datums, int n_tuple_datums)
PartitionBoundInfo partition_bounds_merge(int partnatts, FmgrInfo *partsupfunc, Oid *partcollation, RelOptInfo *outer_rel, RelOptInfo *inner_rel, JoinType jointype, List **outer_parts, List **inner_parts)
static int merge_matching_partitions(PartitionMap *outer_map, PartitionMap *inner_map, int outer_index, int inner_index, int *next_index)
static List * get_qual_for_hash(Relation parent, PartitionBoundSpec *spec)
static void get_merged_range_bounds(int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, JoinType jointype, PartitionRangeBound *outer_lb, PartitionRangeBound *outer_ub, PartitionRangeBound *inner_lb, PartitionRangeBound *inner_ub, int lb_cmpval, int ub_cmpval, PartitionRangeBound *merged_lb, PartitionRangeBound *merged_ub)
static void check_two_partitions_bounds_range(Relation parent, RangeVar *first_name, PartitionBoundSpec *first_bound, RangeVar *second_name, PartitionBoundSpec *second_bound, bool defaultPart, bool is_merge, ParseState *pstate)
#define compare_range_bounds(partnatts, partsupfunc, partcollations, bound1, bound2)
Definition partbounds.c:89
static int32 qsort_partition_hbound_cmp(const void *a, const void *b)
static void free_partition_map(PartitionMap *map)
static int get_non_null_list_datum_count(PartitionBoundSpec **boundspecs, int nparts)
Definition partbounds.c:435
void check_new_partition_bound(char *relname, Relation parent, PartitionBoundSpec *spec, ParseState *pstate)
static void fix_merged_indexes(PartitionMap *outer_map, PartitionMap *inner_map, int nmerged, List *merged_indexes)
static PartitionBoundSpec * get_partition_bound_spec(Oid partOid)
static int merge_partition_with_dummy(PartitionMap *map, int index, int *next_index)
static void check_partition_bounds_for_split_range(Relation parent, char *relname, PartitionBoundSpec *spec, Oid splitPartOid, bool first, bool last, bool defaultPart, ParseState *pstate)
static Expr * make_partition_op_expr(PartitionKey key, int keynum, uint16 strategy, Expr *arg1, Expr *arg2)
uint64 compute_partition_hash_value(int partnatts, FmgrInfo *partsupfunc, const Oid *partcollation, const Datum *values, const bool *isnull)
PartitionBoundInfo partition_bounds_create(PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
Definition partbounds.c:300
static PartitionBoundInfo create_hash_bounds(PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
Definition partbounds.c:348
bool partitions_are_ordered(PartitionBoundInfo boundinfo, Bitmapset *live_parts)
static List * get_qual_for_range(Relation parent, PartitionBoundSpec *spec, bool for_default)
static PartitionBoundInfo merge_list_bounds(FmgrInfo *partsupfunc, Oid *partcollation, RelOptInfo *outer_rel, RelOptInfo *inner_rel, JoinType jointype, List **outer_parts, List **inner_parts)
static void generate_matching_part_pairs(RelOptInfo *outer_rel, RelOptInfo *inner_rel, PartitionMap *outer_map, PartitionMap *inner_map, int nmerged, List **outer_parts, List **inner_parts)
static void add_merged_range_bounds(int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, PartitionRangeBound *merged_lb, PartitionRangeBound *merged_ub, int merged_index, List **merged_datums, List **merged_kinds, List **merged_indexes)
Datum satisfies_hash_partition(PG_FUNCTION_ARGS)
static PartitionRangeBound * make_one_partition_rbound(PartitionKey key, int index, List *datums, bool lower)
int partition_hash_bsearch(PartitionBoundInfo boundinfo, int modulus, int remainder)
static bool find_value_in_new_partitions_list(FmgrInfo *partsupfunc, Oid *partcollation, SinglePartitionSpec **parts, int nparts, Datum value, bool isnull)
void check_partitions_for_split(Relation parent, Oid splitPartOid, List *partlist, ParseState *pstate)
static void get_range_key_properties(PartitionKey key, int keynum, PartitionRangeDatum *ldatum, PartitionRangeDatum *udatum, ListCell **partexprs_item, Expr **keyCol, Const **lower_val, Const **upper_val)
static int32 partition_hbound_cmp(int modulus1, int remainder1, int modulus2, int remainder2)
static PartitionBoundInfo create_range_bounds(PartitionBoundSpec **boundspecs, int nparts, PartitionKey key, int **mapping)
Definition partbounds.c:675
static List * partitions_listdatum_intersection(FmgrInfo *partsupfunc, Oid *partcollation, const List *list1, const List *list2)
void calculate_partition_bound_for_merge(Relation parent, List *partNames, List *partOids, PartitionBoundSpec *spec, ParseState *pstate)
static int32 qsort_partition_list_value_cmp(const void *a, const void *b, void *arg)
static void check_partitions_not_overlap_list(Relation parent, SinglePartitionSpec **parts, int nparts, ParseState *pstate)
static PartitionBoundInfo build_merged_partition_bounds(char strategy, List *merged_datums, List *merged_kinds, List *merged_indexes, int null_index, int default_index)
int get_hash_partition_greatest_modulus(PartitionBoundInfo bound)
static Oid get_partition_operator(PartitionKey key, int col, StrategyNumber strategy, bool *need_relabel)
static bool compare_range_partitions(int partnatts, FmgrInfo *partsupfuncs, Oid *partcollations, PartitionRangeBound *outer_lb, PartitionRangeBound *outer_ub, PartitionRangeBound *inner_lb, PartitionRangeBound *inner_ub, int *lb_cmpval, int *ub_cmpval)
static int get_range_partition(RelOptInfo *rel, PartitionBoundInfo bi, int *lb_pos, PartitionRangeBound *lb, PartitionRangeBound *ub)
int partition_range_datum_bsearch(FmgrInfo *partsupfunc, Oid *partcollation, PartitionBoundInfo boundinfo, int nvalues, const Datum *values, bool *is_equal)
static void merge_null_partitions(PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_null, bool inner_has_null, int outer_null, int inner_null, JoinType jointype, int *next_index, int *null_index)
void check_default_partition_contents(Relation parent, Relation default_rel, PartitionBoundSpec *new_spec)
static int get_range_partition_internal(PartitionBoundInfo bi, int *lb_pos, PartitionRangeBound *lb, PartitionRangeBound *ub)
static List * get_range_nulltest(PartitionKey key)
static int process_outer_partition(PartitionMap *outer_map, PartitionMap *inner_map, bool outer_has_default, bool inner_has_default, int outer_index, int inner_default, JoinType jointype, int *next_index, int *default_index)
int partition_list_bsearch(FmgrInfo *partsupfunc, Oid *partcollation, PartitionBoundInfo boundinfo, Datum value, bool *is_equal)
PartitionBoundInfo partition_bounds_copy(PartitionBoundInfo src, PartitionKey key)
Definition partbounds.c:995
#define partition_bound_has_default(bi)
Definition partbounds.h:99
#define partition_bound_accepts_nulls(bi)
Definition partbounds.h:98
PartitionKey RelationGetPartitionKey(Relation rel)
Definition partcache.c:51
static int get_partition_strategy(PartitionKey key)
Definition partcache.h:59
struct PartitionKeyData * PartitionKey
Definition partdefs.h:18
struct PartitionBoundInfoData * PartitionBoundInfo
Definition partdefs.h:16
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition partdesc.c:71
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition partdesc.c:501
List * map_partition_varattnos(List *expr, int fromrel_varno, Relation to_rel, Relation from_rel)
Definition partition.c:222
List * get_proposed_default_constraint(List *new_part_constraints)
Definition partition.c:370
#define HASH_PARTITION_SEED
Definition partition.h:20
#define IS_DUMMY_REL(r)
Definition pathnodes.h:2194
void * arg
NameData relname
Definition pg_class.h:38
#define PARTITION_MAX_KEYS
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
#define lfirst(lc)
Definition pg_list.h:172
#define llast_int(l)
Definition pg_list.h:199
#define llast(l)
Definition pg_list.h:198
#define lfirst_node(type, lc)
Definition pg_list.h:176
static int list_length(const List *l)
Definition pg_list.h:152
#define linitial_node(type, l)
Definition pg_list.h:181
#define NIL
Definition pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition pg_list.h:518
#define foreach_current_index(var_or_cell)
Definition pg_list.h:403
#define lfirst_int(lc)
Definition pg_list.h:173
#define list_make1_oid(x1)
Definition pg_list.h:242
#define list_make1(x1)
Definition pg_list.h:212
static void * list_nth(const List *list, int n)
Definition pg_list.h:299
#define linitial(l)
Definition pg_list.h:178
#define list_make3(x1, x2, x3)
Definition pg_list.h:216
#define foreach_node(type, var, lst)
Definition pg_list.h:496
static ListCell * list_head(const List *l)
Definition pg_list.h:128
#define for_both_cell(cell1, list1, initcell1, cell2, list2, initcell2)
Definition pg_list.h:540
#define foreach_oid(var, lst)
Definition pg_list.h:471
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:343
#define lfirst_oid(lc)
Definition pg_list.h:174
#define list_make2(x1, x2)
Definition pg_list.h:214
void qsort_arg(void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
#define qsort(a, b, c, d)
Definition port.h:495
static uint64 DatumGetUInt64(Datum X)
Definition postgres.h:433
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static Datum UInt64GetDatum(uint64 X)
Definition postgres.h:443
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
uint64_t Datum
Definition postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222
static int32 DatumGetInt32(Datum X)
Definition postgres.h:212
#define InvalidOid
unsigned int Oid
char * c
@ AND_EXPR
Definition primnodes.h:963
@ OR_EXPR
Definition primnodes.h:963
@ NOT_EXPR
Definition primnodes.h:963
@ COERCE_EXPLICIT_CAST
Definition primnodes.h:767
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:766
@ IS_NULL
Definition primnodes.h:1977
@ IS_NOT_NULL
Definition primnodes.h:1977
void * stringToNode(const char *str)
Definition read.c:90
static unsigned hash(unsigned *uv, int n)
Definition rege_dfa.c:715
#define RelationGetRelid(relation)
Definition rel.h:514
#define RelationGetRelationName(relation)
Definition rel.h:548
int errtable(Relation rel)
Definition relcache.c:6044
char * deparse_expression(Node *expr, List *dpcontext, bool forceprefix, bool showimplicit)
Definition ruleutils.c:3648
char * get_range_partbound_string(List *bound_datums)
@ ForwardScanDirection
Definition sdir.h:28
Snapshot GetLatestSnapshot(void)
Definition snapmgr.c:354
void UnregisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:866
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition snapmgr.c:824
void relation_close(Relation relation, LOCKMODE lockmode)
Definition relation.c:205
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition relation.c:47
uint16 StrategyNumber
Definition stratnum.h:22
#define BTGreaterStrategyNumber
Definition stratnum.h:33
#define BTLessStrategyNumber
Definition stratnum.h:29
#define BTEqualStrategyNumber
Definition stratnum.h:31
#define BTLessEqualStrategyNumber
Definition stratnum.h:30
#define BTGreaterEqualStrategyNumber
Definition stratnum.h:32
MemoryContext es_query_cxt
Definition execnodes.h:712
List * es_tupleTable
Definition execnodes.h:714
TupleTableSlot * ecxt_scantuple
Definition execnodes.h:275
Definition pg_list.h:54
Definition nodes.h:135
PartitionRangeDatumKind ** kind
Definition partbounds.h:84
PartitionStrategy strategy
Definition partbounds.h:81
Bitmapset * interleaved_parts
Definition partbounds.h:87
PartitionBoundInfo boundinfo
Definition partdesc.h:38
bool did_remapping
Definition partbounds.c:83
bool * merged
Definition partbounds.c:81
int * old_indexes
Definition partbounds.c:84
int * merged_indexes
Definition partbounds.c:80
PartitionRangeDatumKind * kind
Definition partbounds.c:69
PartitionRangeDatumKind kind
Definition parsenodes.h:962
Definition type.h:96
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625
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:92
static void table_endscan(TableScanDesc scan)
Definition tableam.h:985
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition tableam.h:1020
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, ScanKeyData *key)
Definition tableam.h:876
bool PartConstraintImpliedByRelConstraint(Relation scanrel, List *partConstraint)

Typedef Documentation

◆ PartitionHashBound

◆ PartitionListValue

◆ PartitionMap

◆ PartitionRangeBound

Function Documentation

◆ add_merged_range_bounds()

static void add_merged_range_bounds ( int  partnatts,
FmgrInfo partsupfuncs,
Oid partcollations,
PartitionRangeBound merged_lb,
PartitionRangeBound merged_ub,
int  merged_index,
List **  merged_datums,
List **  merged_kinds,
List **  merged_indexes 
)
static

Definition at line 2768 of file partbounds.c.

2776{
2777 int cmpval;
2778
2779 if (!*merged_datums)
2780 {
2781 /* First merged partition */
2783 Assert(!*merged_indexes);
2784 cmpval = 1;
2785 }
2786 else
2787 {
2789
2792 Assert(*merged_indexes);
2793
2794 /* Get the last upper bound. */
2795 prev_ub.index = llast_int(*merged_indexes);
2796 prev_ub.datums = (Datum *) llast(*merged_datums);
2798 prev_ub.lower = false;
2799
2800 /*
2801 * We pass lower1 = false to partition_rbound_cmp() to prevent it from
2802 * considering the last upper bound to be smaller than the lower bound
2803 * of the merged partition when the values of the two range bounds
2804 * compare equal.
2805 */
2807 merged_lb->datums, merged_lb->kind,
2808 false, &prev_ub);
2809 Assert(cmpval >= 0);
2810 }
2811
2812 /*
2813 * If the lower bound is higher than the last upper bound, add the lower
2814 * bound with the index as -1 indicating that that is a lower bound; else,
2815 * the last upper bound will be reused as the lower bound of the merged
2816 * partition, so skip this.
2817 */
2818 if (cmpval > 0)
2819 {
2822 *merged_indexes = lappend_int(*merged_indexes, -1);
2823 }
2824
2825 /* Add the upper bound and index of the merged partition. */
2828 *merged_indexes = lappend_int(*merged_indexes, merged_index);
2829}

References Assert, fb(), lappend(), lappend_int(), llast, llast_int, and partition_rbound_cmp().

Referenced by merge_range_bounds().

◆ build_merged_partition_bounds()

static PartitionBoundInfo build_merged_partition_bounds ( char  strategy,
List merged_datums,
List merged_kinds,
List merged_indexes,
int  null_index,
int  default_index 
)
static

Definition at line 2512 of file partbounds.c.

2515{
2517 int ndatums = list_length(merged_datums);
2518 int pos;
2519 ListCell *lc;
2520
2522 merged_bounds->strategy = strategy;
2523 merged_bounds->ndatums = ndatums;
2524
2525 merged_bounds->datums = palloc_array(Datum *, ndatums);
2526 pos = 0;
2527 foreach(lc, merged_datums)
2528 merged_bounds->datums[pos++] = (Datum *) lfirst(lc);
2529
2530 if (strategy == PARTITION_STRATEGY_RANGE)
2531 {
2532 Assert(list_length(merged_kinds) == ndatums);
2534 pos = 0;
2535 foreach(lc, merged_kinds)
2536 merged_bounds->kind[pos++] = (PartitionRangeDatumKind *) lfirst(lc);
2537
2538 /* There are ndatums+1 indexes in the case of range partitioning. */
2539 merged_indexes = lappend_int(merged_indexes, -1);
2540 ndatums++;
2541 }
2542 else
2543 {
2544 Assert(strategy == PARTITION_STRATEGY_LIST);
2546 merged_bounds->kind = NULL;
2547 }
2548
2549 /* interleaved_parts is always NULL for join relations. */
2550 merged_bounds->interleaved_parts = NULL;
2551
2552 Assert(list_length(merged_indexes) == ndatums);
2553 merged_bounds->nindexes = ndatums;
2554 merged_bounds->indexes = palloc_array(int, ndatums);
2555 pos = 0;
2556 foreach(lc, merged_indexes)
2557 merged_bounds->indexes[pos++] = lfirst_int(lc);
2558
2559 merged_bounds->null_index = null_index;
2560 merged_bounds->default_index = default_index;
2561
2562 return merged_bounds;
2563}

References Assert, fb(), lappend_int(), lfirst, lfirst_int, list_length(), NIL, palloc_array, palloc_object, PARTITION_STRATEGY_LIST, and PARTITION_STRATEGY_RANGE.

Referenced by merge_list_bounds(), and merge_range_bounds().

◆ calculate_partition_bound_for_merge()

void calculate_partition_bound_for_merge ( Relation  parent,
List partNames,
List partOids,
PartitionBoundSpec spec,
ParseState pstate 
)

Definition at line 5098 of file partbounds.c.

5103{
5105 PartitionBoundSpec *bound;
5106
5107 Assert(!spec->is_default);
5108
5109 switch (key->strategy)
5110 {
5112 {
5113 int i;
5115 int nparts = list_length(partOids);
5116 List *bounds = NIL;
5117
5119
5120 /*
5121 * Create an array of lower bounds and a list of
5122 * PartitionBoundSpec.
5123 */
5124 foreach_oid(partoid, partOids)
5125 {
5126 bound = get_partition_bound_spec(partoid);
5127 i = foreach_current_index(partoid);
5128
5129 lower_bounds[i] = make_one_partition_rbound(key, i, bound->lowerdatums, true);
5130 bounds = lappend(bounds, bound);
5131 }
5132
5133 /* Sort the array of lower bounds. */
5134 qsort_arg(lower_bounds, nparts, sizeof(PartitionRangeBound *),
5136
5137 /* Ranges of partitions should be adjacent. */
5138 for (i = 1; i < nparts; i++)
5139 {
5140 int index = lower_bounds[i]->index;
5141 int prev_index = lower_bounds[i - 1]->index;
5142
5148 false,
5149 true,
5150 pstate);
5151 }
5152
5153 /*
5154 * The lower bound of the first partition is the lower bound
5155 * of the merged partition.
5156 */
5157 spec->lowerdatums =
5158 ((PartitionBoundSpec *) list_nth(bounds, lower_bounds[0]->index))->lowerdatums;
5159
5160 /*
5161 * The upper bound of the last partition is the upper bound of
5162 * the merged partition.
5163 */
5164 spec->upperdatums =
5165 ((PartitionBoundSpec *) list_nth(bounds, lower_bounds[nparts - 1]->index))->upperdatums;
5166
5169 break;
5170 }
5171
5173 {
5174 /* Consolidate bounds for all partitions in the list. */
5175 foreach_oid(partoid, partOids)
5176 {
5177 bound = get_partition_bound_spec(partoid);
5178 spec->listdatums = list_concat(spec->listdatums, bound->listdatums);
5179 }
5180 break;
5181 }
5182
5183 default:
5184 elog(ERROR, "unexpected partition strategy: %d",
5185 (int) key->strategy);
5186 }
5187}

References Assert, check_two_partitions_bounds_range(), elog, ERROR, fb(), foreach_current_index, foreach_oid, get_partition_bound_spec(), i, lappend(), list_concat(), list_free(), list_length(), list_nth(), PartitionBoundSpec::listdatums, PartitionBoundSpec::lowerdatums, make_one_partition_rbound(), NIL, palloc0_array, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, pfree(), qsort_arg(), qsort_partition_rbound_cmp(), and RelationGetPartitionKey().

Referenced by transformPartitionCmdForMerge().

◆ check_default_partition_contents()

void check_default_partition_contents ( Relation  parent,
Relation  default_rel,
PartitionBoundSpec new_spec 
)

Definition at line 3244 of file partbounds.c.

3246{
3249 List *all_parts;
3250 ListCell *lc;
3251
3253 ? get_qual_for_list(parent, new_spec)
3254 : get_qual_for_range(parent, new_spec, false);
3257
3258 /*
3259 * Map the Vars in the constraint expression from parent's attnos to
3260 * default_rel's.
3261 */
3264 parent);
3265
3266 /*
3267 * If the existing constraints on the default partition imply that it will
3268 * not contain any row that would belong to the new partition, we can
3269 * avoid scanning the default partition.
3270 */
3272 {
3274 (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
3276 return;
3277 }
3278
3279 /*
3280 * Scan the default partition and its subpartitions, and check for rows
3281 * that do not satisfy the revised partition constraints.
3282 */
3283 if (default_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3286 else
3288
3289 foreach(lc, all_parts)
3290 {
3293 Expr *partition_constraint;
3294 EState *estate;
3295 ExprState *partqualstate = NULL;
3296 Snapshot snapshot;
3297 ExprContext *econtext;
3298 TableScanDesc scan;
3300 TupleTableSlot *tupslot;
3301
3302 /* Lock already taken above. */
3304 {
3306
3307 /*
3308 * Map the Vars in the constraint expression from default_rel's
3309 * the sub-partition's.
3310 */
3311 partition_constraint = make_ands_explicit(def_part_constraints);
3312 partition_constraint = (Expr *)
3313 map_partition_varattnos((List *) partition_constraint, 1,
3315
3316 /*
3317 * If the partition constraints on default partition child imply
3318 * that it will not contain any row that would belong to the new
3319 * partition, we can avoid scanning the child table.
3320 */
3323 {
3325 (errmsg_internal("updated partition constraint for default partition \"%s\" is implied by existing constraints",
3327
3329 continue;
3330 }
3331 }
3332 else
3333 {
3335 partition_constraint = make_ands_explicit(def_part_constraints);
3336 }
3337
3338 /*
3339 * Only RELKIND_RELATION relations (i.e. leaf partitions) need to be
3340 * scanned.
3341 */
3342 if (part_rel->rd_rel->relkind != RELKIND_RELATION)
3343 {
3344 if (part_rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
3347 errmsg("skipped scanning foreign table \"%s\" which is a partition of default partition \"%s\"",
3350
3353
3354 continue;
3355 }
3356
3357 estate = CreateExecutorState();
3358
3359 /* Build expression execution states for partition check quals */
3360 partqualstate = ExecPrepareExpr(partition_constraint, estate);
3361
3362 econtext = GetPerTupleExprContext(estate);
3363 snapshot = RegisterSnapshot(GetLatestSnapshot());
3364 tupslot = table_slot_create(part_rel, &estate->es_tupleTable);
3365 scan = table_beginscan(part_rel, snapshot, 0, NULL);
3366
3367 /*
3368 * Switch to per-tuple memory context and reset it for each tuple
3369 * produced, so we don't leak memory.
3370 */
3372
3373 while (table_scan_getnextslot(scan, ForwardScanDirection, tupslot))
3374 {
3375 econtext->ecxt_scantuple = tupslot;
3376
3377 if (!ExecCheck(partqualstate, econtext))
3378 ereport(ERROR,
3380 errmsg("updated partition constraint for default partition \"%s\" would be violated by some row",
3383
3384 ResetExprContext(econtext);
3386 }
3387
3389 table_endscan(scan);
3390 UnregisterSnapshot(snapshot);
3392 FreeExecutorState(estate);
3393
3395 table_close(part_rel, NoLock); /* keep the lock until commit */
3396 }
3397}

References AccessExclusiveLock, CHECK_FOR_INTERRUPTS, CreateExecutorState(), DEBUG1, ExprContext::ecxt_scantuple, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, errtable(), EState::es_tupleTable, ExecCheck(), ExecDropSingleTupleTableSlot(), ExecPrepareExpr(), fb(), find_all_inheritors(), ForwardScanDirection, FreeExecutorState(), get_proposed_default_constraint(), get_qual_for_list(), get_qual_for_range(), GetLatestSnapshot(), GetPerTupleExprContext, GetPerTupleMemoryContext, lfirst_oid, list_make1_oid, make_ands_explicit(), map_partition_varattnos(), MemoryContextSwitchTo(), NoLock, PartConstraintImpliedByRelConstraint(), PARTITION_STRATEGY_LIST, RegisterSnapshot(), RelationGetRelationName, RelationGetRelid, ResetExprContext, table_beginscan(), table_close(), table_endscan(), table_open(), table_scan_getnextslot(), table_slot_create(), UnregisterSnapshot(), and WARNING.

Referenced by DefineRelation().

◆ check_new_partition_bound()

void check_new_partition_bound ( char relname,
Relation  parent,
PartitionBoundSpec spec,
ParseState pstate 
)

Definition at line 2889 of file partbounds.c.

2891{
2893 PartitionDesc partdesc = RelationGetPartitionDesc(parent, false);
2894 PartitionBoundInfo boundinfo = partdesc->boundinfo;
2895 int with = -1;
2896 bool overlap = false;
2897 int overlap_location = -1;
2898
2899 if (spec->is_default)
2900 {
2901 /*
2902 * The default partition bound never conflicts with any other
2903 * partition's; if that's what we're attaching, the only possible
2904 * problem is that one already exists, so check for that and we're
2905 * done.
2906 */
2907 if (boundinfo == NULL || !partition_bound_has_default(boundinfo))
2908 return;
2909
2910 /* Default partition already exists, error out. */
2911 ereport(ERROR,
2913 errmsg("partition \"%s\" conflicts with existing default partition \"%s\"",
2914 relname, get_rel_name(partdesc->oids[boundinfo->default_index])),
2915 parser_errposition(pstate, spec->location)));
2916 }
2917
2918 switch (key->strategy)
2919 {
2921 {
2922 Assert(spec->strategy == PARTITION_STRATEGY_HASH);
2923 Assert(spec->remainder >= 0 && spec->remainder < spec->modulus);
2924
2925 if (partdesc->nparts > 0)
2926 {
2927 int greatest_modulus;
2928 int remainder;
2929 int offset;
2930
2931 /*
2932 * Check rule that every modulus must be a factor of the
2933 * next larger modulus. (For example, if you have a bunch
2934 * of partitions that all have modulus 5, you can add a
2935 * new partition with modulus 10 or a new partition with
2936 * modulus 15, but you cannot add both a partition with
2937 * modulus 10 and a partition with modulus 15, because 10
2938 * is not a factor of 15.) We need only check the next
2939 * smaller and next larger existing moduli, relying on
2940 * previous enforcement of this rule to be sure that the
2941 * rest are in line.
2942 */
2943
2944 /*
2945 * Get the greatest (modulus, remainder) pair contained in
2946 * boundinfo->datums that is less than or equal to the
2947 * (spec->modulus, spec->remainder) pair.
2948 */
2949 offset = partition_hash_bsearch(boundinfo,
2950 spec->modulus,
2951 spec->remainder);
2952 if (offset < 0)
2953 {
2954 int next_modulus;
2955
2956 /*
2957 * All existing moduli are greater or equal, so the
2958 * new one must be a factor of the smallest one, which
2959 * is first in the boundinfo.
2960 */
2961 next_modulus = DatumGetInt32(boundinfo->datums[0][0]);
2962 if (next_modulus % spec->modulus != 0)
2963 ereport(ERROR,
2965 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
2966 errdetail("The new modulus %d is not a factor of %d, the modulus of existing partition \"%s\".",
2967 spec->modulus, next_modulus,
2968 get_rel_name(partdesc->oids[0]))));
2969 }
2970 else
2971 {
2972 int prev_modulus;
2973
2974 /*
2975 * We found the largest (modulus, remainder) pair less
2976 * than or equal to the new one. That modulus must be
2977 * a divisor of, or equal to, the new modulus.
2978 */
2979 prev_modulus = DatumGetInt32(boundinfo->datums[offset][0]);
2980
2981 if (spec->modulus % prev_modulus != 0)
2982 ereport(ERROR,
2984 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
2985 errdetail("The new modulus %d is not divisible by %d, the modulus of existing partition \"%s\".",
2986 spec->modulus,
2988 get_rel_name(partdesc->oids[offset]))));
2989
2990 if (offset + 1 < boundinfo->ndatums)
2991 {
2992 int next_modulus;
2993
2994 /*
2995 * Look at the next higher (modulus, remainder)
2996 * pair. That could have the same modulus and a
2997 * larger remainder than the new pair, in which
2998 * case we're good. If it has a larger modulus,
2999 * the new modulus must divide that one.
3000 */
3001 next_modulus = DatumGetInt32(boundinfo->datums[offset + 1][0]);
3002
3003 if (next_modulus % spec->modulus != 0)
3004 ereport(ERROR,
3006 errmsg("every hash partition modulus must be a factor of the next larger modulus"),
3007 errdetail("The new modulus %d is not a factor of %d, the modulus of existing partition \"%s\".",
3008 spec->modulus, next_modulus,
3009 get_rel_name(partdesc->oids[offset + 1]))));
3010 }
3011 }
3012
3013 greatest_modulus = boundinfo->nindexes;
3014 remainder = spec->remainder;
3015
3016 /*
3017 * Normally, the lowest remainder that could conflict with
3018 * the new partition is equal to the remainder specified
3019 * for the new partition, but when the new partition has a
3020 * modulus higher than any used so far, we need to adjust.
3021 */
3024
3025 /* Check every potentially-conflicting remainder. */
3026 do
3027 {
3028 if (boundinfo->indexes[remainder] != -1)
3029 {
3030 overlap = true;
3031 overlap_location = spec->location;
3032 with = boundinfo->indexes[remainder];
3033 break;
3034 }
3035 remainder += spec->modulus;
3036 } while (remainder < greatest_modulus);
3037 }
3038
3039 break;
3040 }
3041
3043 {
3044 Assert(spec->strategy == PARTITION_STRATEGY_LIST);
3045
3046 if (partdesc->nparts > 0)
3047 {
3048 ListCell *cell;
3049
3050 Assert(boundinfo &&
3051 boundinfo->strategy == PARTITION_STRATEGY_LIST &&
3052 (boundinfo->ndatums > 0 ||
3053 partition_bound_accepts_nulls(boundinfo) ||
3054 partition_bound_has_default(boundinfo)));
3055
3056 foreach(cell, spec->listdatums)
3057 {
3058 Const *val = lfirst_node(Const, cell);
3059
3060 overlap_location = val->location;
3061 if (!val->constisnull)
3062 {
3063 int offset;
3064 bool equal;
3065
3066 offset = partition_list_bsearch(&key->partsupfunc[0],
3067 key->partcollation,
3068 boundinfo,
3069 val->constvalue,
3070 &equal);
3071 if (offset >= 0 && equal)
3072 {
3073 overlap = true;
3074 with = boundinfo->indexes[offset];
3075 break;
3076 }
3077 }
3078 else if (partition_bound_accepts_nulls(boundinfo))
3079 {
3080 overlap = true;
3081 with = boundinfo->null_index;
3082 break;
3083 }
3084 }
3085 }
3086
3087 break;
3088 }
3089
3091 {
3093 *upper;
3094 int cmpval;
3095
3096 Assert(spec->strategy == PARTITION_STRATEGY_RANGE);
3097 lower = make_one_partition_rbound(key, -1, spec->lowerdatums, true);
3098 upper = make_one_partition_rbound(key, -1, spec->upperdatums, false);
3099
3100 /*
3101 * First check if the resulting range would be empty with
3102 * specified lower and upper bounds. partition_rbound_cmp
3103 * cannot return zero here, since the lower-bound flags are
3104 * different.
3105 */
3106 cmpval = partition_rbound_cmp(key->partnatts,
3107 key->partsupfunc,
3108 key->partcollation,
3109 lower->datums, lower->kind,
3110 true, upper);
3111 Assert(cmpval != 0);
3112 if (cmpval > 0)
3113 {
3114 /* Point to problematic key in the lower datums list. */
3115 PartitionRangeDatum *datum = list_nth(spec->lowerdatums,
3116 cmpval - 1);
3117
3118 ereport(ERROR,
3120 errmsg("empty range bound specified for partition \"%s\"",
3121 relname),
3122 errdetail("Specified lower bound %s is greater than or equal to upper bound %s.",
3123 get_range_partbound_string(spec->lowerdatums),
3124 get_range_partbound_string(spec->upperdatums)),
3125 parser_errposition(pstate, datum->location)));
3126 }
3127
3128 if (partdesc->nparts > 0)
3129 {
3130 int offset;
3131
3132 Assert(boundinfo &&
3133 boundinfo->strategy == PARTITION_STRATEGY_RANGE &&
3134 (boundinfo->ndatums > 0 ||
3135 partition_bound_has_default(boundinfo)));
3136
3137 /*
3138 * Test whether the new lower bound (which is treated
3139 * inclusively as part of the new partition) lies inside
3140 * an existing partition, or in a gap.
3141 *
3142 * If it's inside an existing partition, the bound at
3143 * offset + 1 will be the upper bound of that partition,
3144 * and its index will be >= 0.
3145 *
3146 * If it's in a gap, the bound at offset + 1 will be the
3147 * lower bound of the next partition, and its index will
3148 * be -1. This is also true if there is no next partition,
3149 * since the index array is initialised with an extra -1
3150 * at the end.
3151 */
3152 offset = partition_range_bsearch(key->partnatts,
3153 key->partsupfunc,
3154 key->partcollation,
3155 boundinfo, lower,
3156 &cmpval);
3157
3158 if (boundinfo->indexes[offset + 1] < 0)
3159 {
3160 /*
3161 * Check that the new partition will fit in the gap.
3162 * For it to fit, the new upper bound must be less
3163 * than or equal to the lower bound of the next
3164 * partition, if there is one.
3165 */
3166 if (offset + 1 < boundinfo->ndatums)
3167 {
3168 Datum *datums;
3170 bool is_lower;
3171
3172 datums = boundinfo->datums[offset + 1];
3173 kind = boundinfo->kind[offset + 1];
3174 is_lower = (boundinfo->indexes[offset + 1] == -1);
3175
3176 cmpval = partition_rbound_cmp(key->partnatts,
3177 key->partsupfunc,
3178 key->partcollation,
3179 datums, kind,
3180 is_lower, upper);
3181 if (cmpval < 0)
3182 {
3183 /*
3184 * Point to problematic key in the upper
3185 * datums list.
3186 */
3187 PartitionRangeDatum *datum =
3188 list_nth(spec->upperdatums, abs(cmpval) - 1);
3189
3190 /*
3191 * The new partition overlaps with the
3192 * existing partition between offset + 1 and
3193 * offset + 2.
3194 */
3195 overlap = true;
3196 overlap_location = datum->location;
3197 with = boundinfo->indexes[offset + 2];
3198 }
3199 }
3200 }
3201 else
3202 {
3203 /*
3204 * The new partition overlaps with the existing
3205 * partition between offset and offset + 1.
3206 */
3207 PartitionRangeDatum *datum;
3208
3209 /*
3210 * Point to problematic key in the lower datums list;
3211 * if we have equality, point to the first one.
3212 */
3213 datum = cmpval == 0 ? linitial(spec->lowerdatums) :
3214 list_nth(spec->lowerdatums, abs(cmpval) - 1);
3215 overlap = true;
3216 overlap_location = datum->location;
3217 with = boundinfo->indexes[offset + 1];
3218 }
3219 }
3220
3221 break;
3222 }
3223 }
3224
3225 if (overlap)
3226 {
3227 Assert(with >= 0);
3228 ereport(ERROR,
3230 errmsg("partition \"%s\" would overlap partition \"%s\"",
3231 relname, get_rel_name(partdesc->oids[with])),
3233 }
3234}

References Assert, PartitionDescData::boundinfo, DatumGetInt32(), PartitionBoundInfoData::datums, PartitionBoundInfoData::default_index, equal(), ereport, errcode(), errdetail(), errmsg(), ERROR, fb(), get_range_partbound_string(), get_rel_name(), PartitionBoundInfoData::indexes, PartitionBoundInfoData::kind, lfirst_node, linitial, list_nth(), PartitionRangeDatum::location, lower(), make_one_partition_rbound(), PartitionBoundInfoData::ndatums, PartitionBoundInfoData::nindexes, PartitionDescData::nparts, PartitionBoundInfoData::null_index, PartitionDescData::oids, parser_errposition(), partition_bound_accepts_nulls, partition_bound_has_default, partition_hash_bsearch(), partition_list_bsearch(), partition_range_bsearch(), partition_rbound_cmp(), PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, RelationGetPartitionDesc(), RelationGetPartitionKey(), relname, remainder, PartitionBoundInfoData::strategy, upper(), and val.

Referenced by ATExecAttachPartition(), check_partitions_for_split(), and DefineRelation().

◆ check_parent_values_in_new_partitions()

static void check_parent_values_in_new_partitions ( Relation  parent,
Oid  partOid,
SinglePartitionSpec **  parts,
int  nparts,
ParseState pstate 
)
static

Definition at line 5622 of file partbounds.c.

5627{
5629 PartitionDesc partdesc = RelationGetPartitionDesc(parent, false);
5630 PartitionBoundInfo boundinfo = partdesc->boundinfo;
5631 int i;
5632 bool found = true;
5633 Datum datum = PointerGetDatum(NULL);
5634
5635 Assert(key->strategy == PARTITION_STRATEGY_LIST);
5636
5637 /*
5638 * Special processing for NULL value. Search for a NULL value if the split
5639 * partition (partOid) contains it.
5640 */
5641 if (partition_bound_accepts_nulls(boundinfo) &&
5642 partdesc->oids[boundinfo->null_index] == partOid)
5643 {
5644 if (!find_value_in_new_partitions_list(&key->partsupfunc[0],
5645 key->partcollation, parts, nparts, datum, true))
5646 found = false;
5647 }
5648
5649 if (!found)
5650 ereport(ERROR,
5652 errmsg("new partitions combined partition bounds do not contain value (%s) but split partition \"%s\" does",
5653 "NULL",
5655 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5656 "ALTER TABLE ... SPLIT PARTITION"));
5657
5658 /*
5659 * Search all values of split partition with partOid in the PartitionDesc
5660 * of partitioned table.
5661 */
5662 for (i = 0; i < boundinfo->ndatums; i++)
5663 {
5664 if (partdesc->oids[boundinfo->indexes[i]] == partOid)
5665 {
5666 /* We found the value that the split partition contains. */
5667 datum = boundinfo->datums[i][0];
5668 if (!find_value_in_new_partitions_list(&key->partsupfunc[0],
5669 key->partcollation, parts, nparts, datum, false))
5670 {
5671 found = false;
5672 break;
5673 }
5674 }
5675 }
5676
5677 if (!found)
5678 {
5680
5681 /*
5682 * Make a Const for getting the string representation of the missing
5683 * value.
5684 */
5685 notFoundVal = makeConst(key->parttypid[0],
5686 key->parttypmod[0],
5687 key->parttypcoll[0],
5688 key->parttyplen[0],
5689 datum,
5690 false, /* isnull */
5691 key->parttypbyval[0]);
5692
5693 ereport(ERROR,
5695 errmsg("new partitions combined partition bounds do not contain value (%s) but split partition \"%s\" does",
5696 deparse_expression((Node *) notFoundVal, NIL, false, false),
5698 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5699 "ALTER TABLE ... SPLIT PARTITION"));
5700 }
5701}

References Assert, PartitionDescData::boundinfo, PartitionBoundInfoData::datums, deparse_expression(), ereport, errcode(), errhint(), errmsg(), ERROR, fb(), find_value_in_new_partitions_list(), get_rel_name(), i, PartitionBoundInfoData::indexes, makeConst(), PartitionBoundInfoData::ndatums, NIL, PartitionBoundInfoData::null_index, PartitionDescData::oids, partition_bound_accepts_nulls, PARTITION_STRATEGY_LIST, PointerGetDatum(), RelationGetPartitionDesc(), and RelationGetPartitionKey().

Referenced by check_partitions_for_split().

◆ check_partition_bounds_for_split_list()

static void check_partition_bounds_for_split_list ( Relation  parent,
char relname,
PartitionBoundSpec spec,
Oid  splitPartOid,
ParseState pstate 
)
static

Definition at line 5481 of file partbounds.c.

5485{
5487 PartitionDesc partdesc = RelationGetPartitionDesc(parent, false);
5488 PartitionBoundInfo boundinfo = partdesc->boundinfo;
5489 int with = -1;
5490 bool overlap = false;
5491 int overlap_location = -1;
5492
5493 Assert(key->strategy == PARTITION_STRATEGY_LIST);
5494 Assert(spec->strategy == PARTITION_STRATEGY_LIST);
5495 Assert(boundinfo && boundinfo->strategy == PARTITION_STRATEGY_LIST);
5496
5497 /*
5498 * Search each value of the new partition "spec" in the existing
5499 * partitions. All of them should be in the split partition (with Oid
5500 * splitPartOid).
5501 */
5502 foreach_node(Const, val, spec->listdatums)
5503 {
5505 if (!val->constisnull)
5506 {
5507 int offset;
5508 bool equal;
5509
5510 offset = partition_list_bsearch(&key->partsupfunc[0],
5511 key->partcollation,
5512 boundinfo,
5513 val->constvalue,
5514 &equal);
5515 if (offset >= 0 && equal)
5516 {
5517 with = boundinfo->indexes[offset];
5518 if (partdesc->oids[with] != splitPartOid)
5519 {
5520 overlap = true;
5521 break;
5522 }
5523 }
5524 else
5525 ereport(ERROR,
5527 errmsg("new partition \"%s\" cannot have this value because split partition \"%s\" does not have",
5528 relname,
5531 }
5532 else if (partition_bound_accepts_nulls(boundinfo))
5533 {
5534 with = boundinfo->null_index;
5535 if (partdesc->oids[with] != splitPartOid)
5536 {
5537 overlap = true;
5538 break;
5539 }
5540 }
5541 else
5542 ereport(ERROR,
5544 errmsg("new partition \"%s\" cannot have NULL value because split partition \"%s\" does not have",
5545 relname,
5548 }
5549
5550 if (overlap)
5551 {
5552 Assert(with >= 0);
5553 ereport(ERROR,
5555 errmsg("new partition \"%s\" would overlap with another (not split) partition \"%s\"",
5556 relname, get_rel_name(partdesc->oids[with])),
5558 }
5559}

References Assert, PartitionDescData::boundinfo, equal(), ereport, errcode(), errmsg(), ERROR, exprLocation(), fb(), foreach_node, get_rel_name(), PartitionBoundInfoData::indexes, PartitionBoundInfoData::null_index, PartitionDescData::oids, parser_errposition(), partition_bound_accepts_nulls, partition_list_bsearch(), PARTITION_STRATEGY_LIST, RelationGetPartitionDesc(), RelationGetPartitionKey(), relname, PartitionBoundInfoData::strategy, and val.

Referenced by check_partitions_for_split().

◆ check_partition_bounds_for_split_range()

static void check_partition_bounds_for_split_range ( Relation  parent,
char relname,
PartitionBoundSpec spec,
Oid  splitPartOid,
bool  first,
bool  last,
bool  defaultPart,
ParseState pstate 
)
static

Definition at line 5324 of file partbounds.c.

5332{
5335 *upper;
5336 int cmpval;
5337
5338 Assert(key->strategy == PARTITION_STRATEGY_RANGE);
5339 Assert(spec->strategy == PARTITION_STRATEGY_RANGE);
5340
5341 lower = make_one_partition_rbound(key, -1, spec->lowerdatums, true);
5342 upper = make_one_partition_rbound(key, -1, spec->upperdatums, false);
5343
5344 /*
5345 * First, check if the resulting range would be empty with the specified
5346 * lower and upper bounds. partition_rbound_cmp cannot return zero here,
5347 * since the lower-bound flags are different.
5348 */
5349 cmpval = partition_rbound_cmp(key->partnatts,
5350 key->partsupfunc,
5351 key->partcollation,
5352 lower->datums, lower->kind,
5353 true, upper);
5354 Assert(cmpval != 0);
5355 if (cmpval > 0)
5356 {
5357 /* Point to the problematic key in the lower datums list. */
5358 PartitionRangeDatum *datum = list_nth(spec->lowerdatums, cmpval - 1);
5359
5360 ereport(ERROR,
5362 errmsg("empty range bound specified for partition \"%s\"",
5363 relname),
5364 errdetail("Specified lower bound %s is greater than or equal to upper bound %s.",
5365 get_range_partbound_string(spec->lowerdatums),
5366 get_range_partbound_string(spec->upperdatums)),
5367 parser_errposition(pstate, exprLocation((Node *) datum)));
5368 }
5369
5370 /*
5371 * Need to check first and last partitions (from the set of new
5372 * partitions)
5373 */
5374 if (first || last)
5375 {
5377 PartitionRangeDatum *datum;
5378
5379 if (first)
5380 {
5382
5383 split_lower = make_one_partition_rbound(key, -1, split_spec->lowerdatums, true);
5384
5385 cmpval = partition_rbound_cmp(key->partnatts,
5386 key->partsupfunc,
5387 key->partcollation,
5388 lower->datums, lower->kind,
5389 true, split_lower);
5390 if (cmpval != 0)
5391 datum = list_nth(spec->lowerdatums, abs(cmpval) - 1);
5392
5393 /*
5394 * The lower bound of "spec" must equal the lower bound of the
5395 * split partition. However, if one of the new partitions is
5396 * DEFAULT, then it is ok for the new partition's lower bound to
5397 * be greater than that of the split partition.
5398 */
5399 if (!defaultPart)
5400 {
5401 if (cmpval != 0)
5402 ereport(ERROR,
5404 errmsg("lower bound of partition \"%s\" is not equal to lower bound of split partition \"%s\"",
5405 relname,
5407 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5408 "ALTER TABLE ... SPLIT PARTITION"),
5409 parser_errposition(pstate, exprLocation((Node *) datum)));
5410 }
5411 else if (cmpval < 0)
5412 ereport(ERROR,
5414 errmsg("lower bound of partition \"%s\" is less than lower bound of split partition \"%s\"",
5415 relname,
5417 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5418 "ALTER TABLE ... SPLIT PARTITION"),
5419 parser_errposition(pstate, exprLocation((Node *) datum)));
5420 }
5421 else
5422 {
5424
5425 split_upper = make_one_partition_rbound(key, -1, split_spec->upperdatums, false);
5426
5427 cmpval = partition_rbound_cmp(key->partnatts,
5428 key->partsupfunc,
5429 key->partcollation,
5430 upper->datums, upper->kind,
5431 false, split_upper);
5432 if (cmpval != 0)
5433 datum = list_nth(spec->upperdatums, abs(cmpval) - 1);
5434
5435 /*
5436 * The upper bound of "spec" must equal the upper bound of the
5437 * split partition. However, if one of the new partitions is
5438 * DEFAULT, then it is ok for the new partition's upper bound to
5439 * be less than that of the split partition.
5440 */
5441 if (!defaultPart)
5442 {
5443 if (cmpval != 0)
5444 ereport(ERROR,
5446 errmsg("upper bound of partition \"%s\" is not equal to upper bound of split partition \"%s\"",
5447 relname,
5449 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5450 "ALTER TABLE ... SPLIT PARTITION"),
5451 parser_errposition(pstate, exprLocation((Node *) datum)));
5452 }
5453 else if (cmpval > 0)
5454 ereport(ERROR,
5456 errmsg("upper bound of partition \"%s\" is greater than upper bound of split partition \"%s\"",
5457 relname,
5459 errhint("%s require combined bounds of new partitions must exactly match the bound of the split partition",
5460 "ALTER TABLE ... SPLIT PARTITION"),
5461 parser_errposition(pstate, exprLocation((Node *) datum)));
5462 }
5463 }
5464}

References Assert, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, exprLocation(), fb(), get_partition_bound_spec(), get_range_partbound_string(), get_rel_name(), list_nth(), lower(), make_one_partition_rbound(), parser_errposition(), partition_rbound_cmp(), PARTITION_STRATEGY_RANGE, RelationGetPartitionKey(), relname, and upper().

Referenced by check_partitions_for_split().

◆ check_partitions_for_split()

void check_partitions_for_split ( Relation  parent,
Oid  splitPartOid,
List partlist,
ParseState pstate 
)

Definition at line 5723 of file partbounds.c.

5727{
5729 char strategy;
5731 bool isSplitPartDefault;
5732 bool createDefaultPart = false;
5733 int default_index = -1;
5734 int i;
5737
5738 /*
5739 * nparts counts the number of split partitions, but it exclude the
5740 * default partition.
5741 */
5742 int nparts = 0;
5743
5744 key = RelationGetPartitionKey(parent);
5745 strategy = get_partition_strategy(key);
5746
5749
5750 Assert(strategy == PARTITION_STRATEGY_RANGE ||
5751 strategy == PARTITION_STRATEGY_LIST);
5752
5753 /*
5754 * Make an array new_parts with new partitions except the DEFAULT
5755 * partition.
5756 */
5758
5759 /* isSplitPartDefault flag: is split partition a DEFAULT partition? */
5761
5763 {
5764 if (sps->bound->is_default)
5765 default_index = foreach_current_index(sps);
5766 else
5767 new_parts[nparts++] = sps;
5768 }
5769
5770 /* An indicator that the DEFAULT partition will be created. */
5771 if (default_index != -1)
5772 {
5773 createDefaultPart = true;
5774 Assert(nparts == list_length(partlist) - 1);
5775 }
5776
5777 if (strategy == PARTITION_STRATEGY_RANGE)
5778 {
5781
5782 /*
5783 * To simplify the check for ranges of new partitions, we need to sort
5784 * all partitions in ascending order of their bounds (we compare the
5785 * lower bound only).
5786 */
5788
5789 /* Create an array of lower bounds. */
5790 for (i = 0; i < nparts; i++)
5791 {
5793 new_parts[i]->bound->lowerdatums, true);
5794 }
5795
5796 /* Sort the array of lower bounds. */
5797 qsort_arg(lower_bounds, nparts, sizeof(PartitionRangeBound *),
5798 qsort_partition_rbound_cmp, (void *) key);
5799
5800 /* Reorder the array of partitions. */
5803 for (i = 0; i < nparts; i++)
5805
5808 }
5809
5810 for (i = 0; i < nparts; i++)
5811 {
5813
5815 {
5816 /*
5817 * When the split partition is the DEFAULT partition, we can use
5818 * any free ranges - as when creating a new partition.
5819 */
5820 check_new_partition_bound(sps->name->relname, parent, sps->bound,
5821 pstate);
5822 }
5823 else
5824 {
5825 /*
5826 * Checks that the bounds of the current partition are inside the
5827 * bounds of the split partition. For range partitioning: checks
5828 * that the upper bound of the previous partition is equal to the
5829 * lower bound of the current partition. For list partitioning:
5830 * checks that the split partition contains all values of the
5831 * current partition.
5832 */
5833 if (strategy == PARTITION_STRATEGY_RANGE)
5834 {
5835 bool first = (i == 0);
5836 bool last = (i == (nparts - 1));
5837
5838 check_partition_bounds_for_split_range(parent, sps->name->relname, sps->bound,
5839 splitPartOid, first, last,
5840 createDefaultPart, pstate);
5841 }
5842 else
5843 check_partition_bounds_for_split_list(parent, sps->name->relname,
5844 sps->bound, splitPartOid, pstate);
5845 }
5846
5847 /* Ranges of new partitions should not overlap. */
5848 if (strategy == PARTITION_STRATEGY_RANGE && spsPrev)
5850 sps->name, sps->bound,
5852 false,
5853 pstate);
5854
5855 spsPrev = sps;
5856 }
5857
5858 if (strategy == PARTITION_STRATEGY_LIST)
5859 {
5860 /* Values of new partitions should not overlap. */
5862 pstate);
5863
5864 /*
5865 * Need to check that all values of the split partition are contained
5866 * in the new partitions. Skip this check if the DEFAULT partition
5867 * exists.
5868 */
5869 if (!createDefaultPart)
5871 new_parts, nparts, pstate);
5872 }
5873
5875}

References Assert, check_new_partition_bound(), check_parent_values_in_new_partitions(), check_partition_bounds_for_split_list(), check_partition_bounds_for_split_range(), check_partitions_not_overlap_list(), check_two_partitions_bounds_range(), fb(), foreach_current_index, foreach_node, get_default_oid_from_partdesc(), get_partition_strategy(), i, list_length(), make_one_partition_rbound(), palloc0_array, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, pfree(), qsort_arg(), qsort_partition_rbound_cmp(), RelationGetPartitionDesc(), and RelationGetPartitionKey().

Referenced by transformPartitionCmdForSplit().

◆ check_partitions_not_overlap_list()

static void check_partitions_not_overlap_list ( Relation  parent,
SinglePartitionSpec **  parts,
int  nparts,
ParseState pstate 
)
static

Definition at line 5258 of file partbounds.c.

5262{
5264 int i,
5265 j;
5267 *sps2;
5268 List *overlap;
5269
5270 Assert(key->strategy == PARTITION_STRATEGY_LIST);
5271
5272 for (i = 0; i < nparts; i++)
5273 {
5274 sps1 = parts[i];
5275
5276 for (j = i + 1; j < nparts; j++)
5277 {
5278 sps2 = parts[j];
5279
5280 overlap = partitions_listdatum_intersection(&key->partsupfunc[0],
5281 key->partcollation,
5282 sps1->bound->listdatums,
5283 sps2->bound->listdatums);
5284 if (list_length(overlap) > 0)
5285 {
5286 Const *val = (Const *) linitial_node(Const, overlap);
5287
5288 ereport(ERROR,
5290 errmsg("new partition \"%s\" would overlap with another new partition \"%s\"",
5291 sps1->name->relname, sps2->name->relname),
5292 parser_errposition(pstate, exprLocation((Node *) val)));
5293 }
5294 }
5295 }
5296}

References Assert, ereport, errcode(), errmsg(), ERROR, exprLocation(), fb(), i, j, linitial_node, list_length(), parser_errposition(), PARTITION_STRATEGY_LIST, partitions_listdatum_intersection(), PG_USED_FOR_ASSERTS_ONLY, RelationGetPartitionKey(), and val.

Referenced by check_partitions_for_split().

◆ check_two_partitions_bounds_range()

static void check_two_partitions_bounds_range ( Relation  parent,
RangeVar first_name,
PartitionBoundSpec first_bound,
RangeVar second_name,
PartitionBoundSpec second_bound,
bool  defaultPart,
bool  is_merge,
ParseState pstate 
)
static

Definition at line 4997 of file partbounds.c.

5005{
5009 int cmpval;
5010
5011 Assert(key->strategy == PARTITION_STRATEGY_RANGE);
5012
5013 first_upper = make_one_partition_rbound(key, -1, first_bound->upperdatums, false);
5014 second_lower = make_one_partition_rbound(key, -1, second_bound->lowerdatums, true);
5015
5016 /*
5017 * lower1 argument of partition_rbound_cmp() is set to false for the
5018 * correct comparison result of the lower and upper bounds.
5019 */
5020 cmpval = partition_rbound_cmp(key->partnatts,
5021 key->partsupfunc,
5022 key->partcollation,
5023 second_lower->datums, second_lower->kind,
5024 false, first_upper);
5025 if ((!defaultPart && cmpval) || (defaultPart && cmpval < 0))
5026 {
5027 PartitionRangeDatum *datum = linitial(second_bound->lowerdatums);
5028
5029 if (is_merge)
5030 ereport(ERROR,
5032 errmsg("can not merge partition \"%s\" together with partition \"%s\"",
5033 second_name->relname, first_name->relname),
5034 errdetail("lower bound of partition \"%s\" is not equal to the upper bound of partition \"%s\"",
5035 second_name->relname, first_name->relname),
5036 errhint("ALTER TABLE ... MERGE PARTITIONS requires the partition bounds to be adjacent."),
5037 parser_errposition(pstate, datum->location));
5038 else
5039 ereport(ERROR,
5041 errmsg("can not split to partition \"%s\" together with partition \"%s\"",
5042 second_name->relname, first_name->relname),
5043 errdetail("lower bound of partition \"%s\" is not equal to the upper bound of partition \"%s\"",
5044 second_name->relname, first_name->relname),
5045 errhint("ALTER TABLE ... SPLIT PARTITION requires the partition bounds to be adjacent."),
5046 parser_errposition(pstate, datum->location));
5047 }
5048}

References Assert, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, fb(), linitial, PartitionRangeDatum::location, make_one_partition_rbound(), parser_errposition(), partition_rbound_cmp(), PARTITION_STRATEGY_RANGE, and RelationGetPartitionKey().

Referenced by calculate_partition_bound_for_merge(), and check_partitions_for_split().

◆ compare_range_partitions()

static bool compare_range_partitions ( int  partnatts,
FmgrInfo partsupfuncs,
Oid partcollations,
PartitionRangeBound outer_lb,
PartitionRangeBound outer_ub,
PartitionRangeBound inner_lb,
PartitionRangeBound inner_ub,
int lb_cmpval,
int ub_cmpval 
)
static

Definition at line 2655 of file partbounds.c.

2662{
2663 /*
2664 * Check if the outer partition's upper bound is lower than the inner
2665 * partition's lower bound; if so the partitions aren't overlapping.
2666 */
2668 outer_ub, inner_lb) < 0)
2669 {
2670 *lb_cmpval = -1;
2671 *ub_cmpval = -1;
2672 return false;
2673 }
2674
2675 /*
2676 * Check if the outer partition's lower bound is higher than the inner
2677 * partition's upper bound; if so the partitions aren't overlapping.
2678 */
2680 outer_lb, inner_ub) > 0)
2681 {
2682 *lb_cmpval = 1;
2683 *ub_cmpval = 1;
2684 return false;
2685 }
2686
2687 /* All other cases indicate overlapping partitions. */
2692 return true;
2693}

References compare_range_bounds, and fb().

Referenced by merge_range_bounds().

◆ compute_partition_hash_value()

uint64 compute_partition_hash_value ( int  partnatts,
FmgrInfo partsupfunc,
const Oid partcollation,
const Datum values,
const bool isnull 
)

Definition at line 4714 of file partbounds.c.

4716{
4717 int i;
4718 uint64 rowHash = 0;
4720
4721 for (i = 0; i < partnatts; i++)
4722 {
4723 /* Nulls are just ignored */
4724 if (!isnull[i])
4725 {
4726 Datum hash;
4727
4728 Assert(OidIsValid(partsupfunc[i].fn_oid));
4729
4730 /*
4731 * Compute hash for each datum value by calling respective
4732 * datatype-specific hash functions of each partition key
4733 * attribute.
4734 */
4735 hash = FunctionCall2Coll(&partsupfunc[i], partcollation[i],
4736 values[i], seed);
4737
4738 /* Form a single 64-bit hash value */
4740 }
4741 }
4742
4743 return rowHash;
4744}

References Assert, DatumGetUInt64(), fb(), FunctionCall2Coll(), hash(), hash_combine64(), HASH_PARTITION_SEED, i, OidIsValid, UInt64GetDatum(), and values.

Referenced by get_matching_hash_bounds(), and get_partition_for_tuple().

◆ create_hash_bounds()

static PartitionBoundInfo create_hash_bounds ( PartitionBoundSpec **  boundspecs,
int  nparts,
PartitionKey  key,
int **  mapping 
)
static

Definition at line 348 of file partbounds.c.

350{
351 PartitionBoundInfo boundinfo;
353 int i;
356
358 boundinfo->strategy = key->strategy;
359 /* No special hash partitions. */
360 boundinfo->null_index = -1;
361 boundinfo->default_index = -1;
362
364
365 /* Convert from node to the internal representation */
366 for (i = 0; i < nparts; i++)
367 {
369
370 if (spec->strategy != PARTITION_STRATEGY_HASH)
371 elog(ERROR, "invalid strategy in partition bound spec");
372
373 hbounds[i].modulus = spec->modulus;
374 hbounds[i].remainder = spec->remainder;
375 hbounds[i].index = i;
376 }
377
378 /* Sort all the bounds in ascending order */
379 qsort(hbounds, nparts, sizeof(PartitionHashBound),
381
382 /* After sorting, moduli are now stored in ascending order. */
383 greatest_modulus = hbounds[nparts - 1].modulus;
384
385 boundinfo->ndatums = nparts;
386 boundinfo->datums = palloc0_array(Datum *, nparts);
387 boundinfo->kind = NULL;
388 boundinfo->interleaved_parts = NULL;
389 boundinfo->nindexes = greatest_modulus;
390 boundinfo->indexes = (int *) palloc(greatest_modulus * sizeof(int));
391 for (i = 0; i < greatest_modulus; i++)
392 boundinfo->indexes[i] = -1;
393
394 /*
395 * In the loop below, to save from allocating a series of small datum
396 * arrays, here we just allocate a single array and below we'll just
397 * assign a portion of this array per partition.
398 */
399 boundDatums = (Datum *) palloc(nparts * 2 * sizeof(Datum));
400
401 /*
402 * For hash partitioning, there are as many datums (modulus and remainder
403 * pairs) as there are partitions. Indexes are simply values ranging from
404 * 0 to (nparts - 1).
405 */
406 for (i = 0; i < nparts; i++)
407 {
408 int modulus = hbounds[i].modulus;
409 int remainder = hbounds[i].remainder;
410
411 boundinfo->datums[i] = &boundDatums[i * 2];
412 boundinfo->datums[i][0] = Int32GetDatum(modulus);
413 boundinfo->datums[i][1] = Int32GetDatum(remainder);
414
416 {
417 /* overlap? */
418 Assert(boundinfo->indexes[remainder] == -1);
419 boundinfo->indexes[remainder] = i;
420 remainder += modulus;
421 }
422
423 (*mapping)[hbounds[i].index] = i;
424 }
425 pfree(hbounds);
426
427 return boundinfo;
428}

References Assert, PartitionBoundInfoData::datums, PartitionBoundInfoData::default_index, elog, ERROR, fb(), i, PartitionBoundInfoData::indexes, Int32GetDatum(), PartitionBoundInfoData::interleaved_parts, PartitionBoundInfoData::kind, PartitionBoundInfoData::ndatums, PartitionBoundInfoData::nindexes, PartitionBoundInfoData::null_index, palloc(), palloc0_array, palloc0_object, palloc_array, PARTITION_STRATEGY_HASH, pfree(), qsort, qsort_partition_hbound_cmp(), remainder, and PartitionBoundInfoData::strategy.

Referenced by partition_bounds_create().

◆ create_list_bounds()

static PartitionBoundInfo create_list_bounds ( PartitionBoundSpec **  boundspecs,
int  nparts,
PartitionKey  key,
int **  mapping 
)
static

Definition at line 461 of file partbounds.c.

463{
464 PartitionBoundInfo boundinfo;
466 int i;
467 int j;
468 int ndatums;
469 int next_index = 0;
470 int default_index = -1;
471 int null_index = -1;
473
475 boundinfo->strategy = key->strategy;
476 /* Will be set correctly below. */
477 boundinfo->null_index = -1;
478 boundinfo->default_index = -1;
479
480 ndatums = get_non_null_list_datum_count(boundspecs, nparts);
482 palloc(ndatums * sizeof(PartitionListValue));
483
484 /* Create a unified list of non-null values across all partitions. */
485 for (j = 0, i = 0; i < nparts; i++)
486 {
488 ListCell *c;
489
490 if (spec->strategy != PARTITION_STRATEGY_LIST)
491 elog(ERROR, "invalid strategy in partition bound spec");
492
493 /*
494 * Note the index of the partition bound spec for the default
495 * partition. There's no datum to add to the list on non-null datums
496 * for this partition.
497 */
498 if (spec->is_default)
499 {
500 default_index = i;
501 continue;
502 }
503
504 foreach(c, spec->listdatums)
505 {
507
508 if (!val->constisnull)
509 {
510 all_values[j].index = i;
511 all_values[j].value = val->constvalue;
512 j++;
513 }
514 else
515 {
516 /*
517 * Never put a null into the values array; save the index of
518 * the partition that stores nulls, instead.
519 */
520 if (null_index != -1)
521 elog(ERROR, "found null more than once");
522 null_index = i;
523 }
524 }
525 }
526
527 /* ensure we found a Datum for every slot in the all_values array */
528 Assert(j == ndatums);
529
530 qsort_arg(all_values, ndatums, sizeof(PartitionListValue),
532
533 boundinfo->ndatums = ndatums;
534 boundinfo->datums = palloc0_array(Datum *, ndatums);
535 boundinfo->kind = NULL;
536 boundinfo->interleaved_parts = NULL;
537 boundinfo->nindexes = ndatums;
538 boundinfo->indexes = (int *) palloc(ndatums * sizeof(int));
539
540 /*
541 * In the loop below, to save from allocating a series of small datum
542 * arrays, here we just allocate a single array and below we'll just
543 * assign a portion of this array per datum.
544 */
545 boundDatums = (Datum *) palloc(ndatums * sizeof(Datum));
546
547 /*
548 * Copy values. Canonical indexes are values ranging from 0 to (nparts -
549 * 1) assigned to each partition such that all datums of a given partition
550 * receive the same value. The value for a given partition is the index of
551 * that partition's smallest datum in the all_values[] array.
552 */
553 for (i = 0; i < ndatums; i++)
554 {
555 int orig_index = all_values[i].index;
556
557 boundinfo->datums[i] = &boundDatums[i];
558 boundinfo->datums[i][0] = datumCopy(all_values[i].value,
559 key->parttypbyval[0],
560 key->parttyplen[0]);
561
562 /* If the old index has no mapping, assign one */
563 if ((*mapping)[orig_index] == -1)
564 (*mapping)[orig_index] = next_index++;
565
566 boundinfo->indexes[i] = (*mapping)[orig_index];
567 }
568
570
571 /*
572 * Set the canonical value for null_index, if any.
573 *
574 * It is possible that the null-accepting partition has not been assigned
575 * an index yet, which could happen if such partition accepts only null
576 * and hence not handled in the above loop which only looked at non-null
577 * values.
578 */
579 if (null_index != -1)
580 {
581 Assert(null_index >= 0);
582 if ((*mapping)[null_index] == -1)
583 (*mapping)[null_index] = next_index++;
584 boundinfo->null_index = (*mapping)[null_index];
585 }
586
587 /* Set the canonical value for default_index, if any. */
588 if (default_index != -1)
589 {
590 /*
591 * The default partition accepts any value not specified in the lists
592 * of other partitions, hence it should not get mapped index while
593 * assigning those for non-null datums.
594 */
595 Assert(default_index >= 0);
596 Assert((*mapping)[default_index] == -1);
597 (*mapping)[default_index] = next_index++;
598 boundinfo->default_index = (*mapping)[default_index];
599 }
600
601 /*
602 * Calculate interleaved partitions. Here we look for partitions which
603 * might be interleaved with other partitions and set a bit in
604 * interleaved_parts for any partitions which may be interleaved with
605 * another partition.
606 */
607
608 /*
609 * There must be multiple partitions to have any interleaved partitions,
610 * otherwise there's nothing to interleave with.
611 */
612 if (nparts > 1)
613 {
614 /*
615 * Short-circuit check to see if only 1 Datum is allowed per
616 * partition. When this is true there's no need to do the more
617 * expensive checks to look for interleaved values.
618 */
619 if (boundinfo->ndatums +
621 partition_bound_has_default(boundinfo) != nparts)
622 {
623 int last_index = -1;
624
625 /*
626 * Since the indexes array is sorted in Datum order, if any
627 * partitions are interleaved then it will show up by the
628 * partition indexes not being in ascending order. Here we check
629 * for that and record all partitions that are out of order.
630 */
631 for (i = 0; i < boundinfo->nindexes; i++)
632 {
633 int index = boundinfo->indexes[i];
634
635 if (index < last_index)
636 boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
637 index);
638
639 /*
640 * Otherwise, if the null_index exists in the indexes array,
641 * then the NULL partition must also allow some other Datum,
642 * therefore it's "interleaved".
643 */
644 else if (partition_bound_accepts_nulls(boundinfo) &&
645 index == boundinfo->null_index)
646 boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
647 index);
648
650 }
651 }
652
653 /*
654 * The DEFAULT partition is the "catch-all" partition that can contain
655 * anything that does not belong to any other partition. If there are
656 * any other partitions then the DEFAULT partition must be marked as
657 * interleaved.
658 */
659 if (partition_bound_has_default(boundinfo))
660 boundinfo->interleaved_parts = bms_add_member(boundinfo->interleaved_parts,
661 boundinfo->default_index);
662 }
663
664
665 /* All partitions must now have been assigned canonical indexes. */
666 Assert(next_index == nparts);
667 return boundinfo;
668}

References Assert, bms_add_member(), datumCopy(), PartitionBoundInfoData::datums, PartitionBoundInfoData::default_index, elog, ERROR, fb(), get_non_null_list_datum_count(), i, PartitionBoundInfoData::indexes, PartitionBoundInfoData::interleaved_parts, j, PartitionBoundInfoData::kind, lfirst_node, PartitionBoundInfoData::ndatums, PartitionBoundInfoData::nindexes, PartitionBoundInfoData::null_index, palloc(), palloc0_array, palloc0_object, partition_bound_accepts_nulls, partition_bound_has_default, PARTITION_STRATEGY_LIST, pfree(), qsort_arg(), qsort_partition_list_value_cmp(), PartitionBoundInfoData::strategy, val, and value.

Referenced by partition_bounds_create().

◆ create_range_bounds()

static PartitionBoundInfo create_range_bounds ( PartitionBoundSpec **  boundspecs,
int  nparts,
PartitionKey  key,
int **  mapping 
)
static

Definition at line 675 of file partbounds.c.

677{
678 PartitionBoundInfo boundinfo;
681 *prev;
682 int i,
683 k,
684 partnatts;
685 int ndatums = 0;
686 int default_index = -1;
687 int next_index = 0;
690
692 boundinfo->strategy = key->strategy;
693 /* There is no special null-accepting range partition. */
694 boundinfo->null_index = -1;
695 /* Will be set correctly below. */
696 boundinfo->default_index = -1;
697
699
700 /* Create a unified list of range bounds across all the partitions. */
701 ndatums = 0;
702 for (i = 0; i < nparts; i++)
703 {
706 *upper;
707
708 if (spec->strategy != PARTITION_STRATEGY_RANGE)
709 elog(ERROR, "invalid strategy in partition bound spec");
710
711 /*
712 * Note the index of the partition bound spec for the default
713 * partition. There's no datum to add to the all_bounds array for
714 * this partition.
715 */
716 if (spec->is_default)
717 {
718 default_index = i;
719 continue;
720 }
721
722 lower = make_one_partition_rbound(key, i, spec->lowerdatums, true);
723 upper = make_one_partition_rbound(key, i, spec->upperdatums, false);
724 all_bounds[ndatums++] = lower;
725 all_bounds[ndatums++] = upper;
726 }
727
728 Assert(ndatums == nparts * 2 ||
729 (default_index != -1 && ndatums == (nparts - 1) * 2));
730
731 /* Sort all the bounds in ascending order */
732 qsort_arg(all_bounds, ndatums,
733 sizeof(PartitionRangeBound *),
735 key);
736
737 /* Save distinct bounds from all_bounds into rbounds. */
739 palloc(ndatums * sizeof(PartitionRangeBound *));
740 k = 0;
741 prev = NULL;
742 for (i = 0; i < ndatums; i++)
743 {
745 bool is_distinct = false;
746 int j;
747
748 /* Is the current bound distinct from the previous one? */
749 for (j = 0; j < key->partnatts; j++)
750 {
752
753 if (prev == NULL || cur->kind[j] != prev->kind[j])
754 {
755 is_distinct = true;
756 break;
757 }
758
759 /*
760 * If the bounds are both MINVALUE or MAXVALUE, stop now and treat
761 * them as equal, since any values after this point must be
762 * ignored.
763 */
764 if (cur->kind[j] != PARTITION_RANGE_DATUM_VALUE)
765 break;
766
767 cmpval = FunctionCall2Coll(&key->partsupfunc[j],
768 key->partcollation[j],
769 cur->datums[j],
770 prev->datums[j]);
771 if (DatumGetInt32(cmpval) != 0)
772 {
773 is_distinct = true;
774 break;
775 }
776 }
777
778 /*
779 * Only if the bound is distinct save it into a temporary array, i.e,
780 * rbounds which is later copied into boundinfo datums array.
781 */
782 if (is_distinct)
783 rbounds[k++] = all_bounds[i];
784
785 prev = cur;
786 }
787
789
790 /* Update ndatums to hold the count of distinct datums. */
791 ndatums = k;
792
793 /*
794 * Add datums to boundinfo. Canonical indexes are values ranging from 0
795 * to nparts - 1, assigned in that order to each partition's upper bound.
796 * For 'datums' elements that are lower bounds, there is -1 in the
797 * 'indexes' array to signify that no partition exists for the values less
798 * than such a bound and greater than or equal to the previous upper
799 * bound.
800 */
801 boundinfo->ndatums = ndatums;
802 boundinfo->datums = palloc0_array(Datum *, ndatums);
803 boundinfo->kind = palloc0_array(PartitionRangeDatumKind *, ndatums);
804 boundinfo->interleaved_parts = NULL;
805
806 /*
807 * For range partitioning, an additional value of -1 is stored as the last
808 * element of the indexes[] array.
809 */
810 boundinfo->nindexes = ndatums + 1;
811 boundinfo->indexes = palloc_array(int, (ndatums + 1));
812
813 /*
814 * In the loop below, to save from allocating a series of small arrays,
815 * here we just allocate a single array for Datums and another for
816 * PartitionRangeDatumKinds, below we'll just assign a portion of these
817 * arrays in each loop.
818 */
819 partnatts = key->partnatts;
820 boundDatums = (Datum *) palloc(ndatums * partnatts * sizeof(Datum));
821 boundKinds = palloc_array(PartitionRangeDatumKind, ndatums * partnatts);
822
823 for (i = 0; i < ndatums; i++)
824 {
825 int j;
826
827 boundinfo->datums[i] = &boundDatums[i * partnatts];
828 boundinfo->kind[i] = &boundKinds[i * partnatts];
829 for (j = 0; j < partnatts; j++)
830 {
831 if (rbounds[i]->kind[j] == PARTITION_RANGE_DATUM_VALUE)
832 boundinfo->datums[i][j] =
833 datumCopy(rbounds[i]->datums[j],
834 key->parttypbyval[j],
835 key->parttyplen[j]);
836 boundinfo->kind[i][j] = rbounds[i]->kind[j];
837 }
838
839 /*
840 * There is no mapping for invalid indexes.
841 *
842 * Any lower bounds in the rbounds array have invalid indexes
843 * assigned, because the values between the previous bound (if there
844 * is one) and this (lower) bound are not part of the range of any
845 * existing partition.
846 */
847 if (rbounds[i]->lower)
848 boundinfo->indexes[i] = -1;
849 else
850 {
851 int orig_index = rbounds[i]->index;
852
853 /* If the old index has no mapping, assign one */
854 if ((*mapping)[orig_index] == -1)
855 (*mapping)[orig_index] = next_index++;
856
857 boundinfo->indexes[i] = (*mapping)[orig_index];
858 }
859 }
860
861 pfree(rbounds);
862
863 /* Set the canonical value for default_index, if any. */
864 if (default_index != -1)
865 {
866 Assert(default_index >= 0 && (*mapping)[default_index] == -1);
867 (*mapping)[default_index] = next_index++;
868 boundinfo->default_index = (*mapping)[default_index];
869 }
870
871 /* The extra -1 element. */
872 Assert(i == ndatums);
873 boundinfo->indexes[i] = -1;
874
875 /* All partitions must now have been assigned canonical indexes. */
876 Assert(next_index == nparts);
877 return boundinfo;
878}

References Assert, cur, datumCopy(), DatumGetInt32(), PartitionRangeBound::datums, PartitionBoundInfoData::datums, PartitionBoundInfoData::default_index, elog, ERROR, fb(), FunctionCall2Coll(), i, PartitionBoundInfoData::indexes, PartitionBoundInfoData::interleaved_parts, j, PartitionRangeBound::kind, PartitionBoundInfoData::kind, lower(), make_one_partition_rbound(), PartitionBoundInfoData::ndatums, PartitionBoundInfoData::nindexes, PartitionBoundInfoData::null_index, palloc(), palloc0_array, palloc0_object, palloc_array, PARTITION_RANGE_DATUM_VALUE, PARTITION_STRATEGY_RANGE, pfree(), qsort_arg(), qsort_partition_rbound_cmp(), PartitionBoundInfoData::strategy, and upper().

Referenced by partition_bounds_create().

◆ find_value_in_new_partitions_list()

static bool find_value_in_new_partitions_list ( FmgrInfo partsupfunc,
Oid partcollation,
SinglePartitionSpec **  parts,
int  nparts,
Datum  value,
bool  isnull 
)
static

Definition at line 5578 of file partbounds.c.

5584{
5585 for (int i = 0; i < nparts; i++)
5586 {
5588
5589 foreach_node(Const, val, sps->bound->listdatums)
5590 {
5591 if (isnull && val->constisnull)
5592 return true;
5593
5594 if (!isnull && !val->constisnull)
5595 {
5596 if (DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
5597 partcollation[0],
5598 val->constvalue,
5599 value)) == 0)
5600 return true;
5601 }
5602 }
5603 }
5604 return false;
5605}

References DatumGetInt32(), fb(), foreach_node, FunctionCall2Coll(), i, val, and value.

Referenced by check_parent_values_in_new_partitions().

◆ fix_merged_indexes()

static void fix_merged_indexes ( PartitionMap outer_map,
PartitionMap inner_map,
int  nmerged,
List merged_indexes 
)
static

Definition at line 2379 of file partbounds.c.

2381{
2382 int *new_indexes;
2383 int merged_index;
2384 int i;
2385 ListCell *lc;
2386
2387 Assert(nmerged > 0);
2388
2390 for (i = 0; i < nmerged; i++)
2391 new_indexes[i] = -1;
2392
2393 /* Build the mapping of old merged indexes to new merged indexes. */
2394 if (outer_map->did_remapping)
2395 {
2396 for (i = 0; i < outer_map->nparts; i++)
2397 {
2398 merged_index = outer_map->old_indexes[i];
2399 if (merged_index >= 0)
2400 new_indexes[merged_index] = outer_map->merged_indexes[i];
2401 }
2402 }
2403 if (inner_map->did_remapping)
2404 {
2405 for (i = 0; i < inner_map->nparts; i++)
2406 {
2407 merged_index = inner_map->old_indexes[i];
2408 if (merged_index >= 0)
2409 new_indexes[merged_index] = inner_map->merged_indexes[i];
2410 }
2411 }
2412
2413 /* Fix the merged_indexes list using the mapping. */
2414 foreach(lc, merged_indexes)
2415 {
2417 Assert(merged_index >= 0);
2418 if (new_indexes[merged_index] >= 0)
2420 }
2421
2423}

References Assert, fb(), i, lfirst_int, palloc_array, and pfree().

Referenced by merge_list_bounds().

◆ free_partition_map()

static void free_partition_map ( PartitionMap map)
static

Definition at line 1826 of file partbounds.c.

1827{
1828 pfree(map->merged_indexes);
1829 pfree(map->merged);
1830 pfree(map->old_indexes);
1831}

References PartitionMap::merged, PartitionMap::merged_indexes, PartitionMap::old_indexes, and pfree().

Referenced by merge_list_bounds(), and merge_range_bounds().

◆ generate_matching_part_pairs()

static void generate_matching_part_pairs ( RelOptInfo outer_rel,
RelOptInfo inner_rel,
PartitionMap outer_map,
PartitionMap inner_map,
int  nmerged,
List **  outer_parts,
List **  inner_parts 
)
static

Definition at line 2433 of file partbounds.c.

2437{
2438 int outer_nparts = outer_map->nparts;
2439 int inner_nparts = inner_map->nparts;
2440 int *outer_indexes;
2441 int *inner_indexes;
2442 int max_nparts;
2443 int i;
2444
2445 Assert(nmerged > 0);
2446 Assert(*outer_parts == NIL);
2447 Assert(*inner_parts == NIL);
2448
2451 for (i = 0; i < nmerged; i++)
2452 outer_indexes[i] = inner_indexes[i] = -1;
2453
2454 /* Set pairs of matching partitions. */
2455 Assert(outer_nparts == outer_rel->nparts);
2456 Assert(inner_nparts == inner_rel->nparts);
2458 for (i = 0; i < max_nparts; i++)
2459 {
2460 if (i < outer_nparts)
2461 {
2462 int merged_index = outer_map->merged_indexes[i];
2463
2464 if (merged_index >= 0)
2465 {
2468 }
2469 }
2470 if (i < inner_nparts)
2471 {
2472 int merged_index = inner_map->merged_indexes[i];
2473
2474 if (merged_index >= 0)
2475 {
2478 }
2479 }
2480 }
2481
2482 /* Build the list pairs. */
2483 for (i = 0; i < nmerged; i++)
2484 {
2487
2488 /*
2489 * If both partitions are dummy, it means the merged partition that
2490 * had been assigned to the outer/inner partition was removed when
2491 * re-merging the outer/inner partition in
2492 * merge_matching_partitions(); ignore the merged partition.
2493 */
2494 if (outer_index == -1 && inner_index == -1)
2495 continue;
2496
2498 outer_rel->part_rels[outer_index] : NULL);
2500 inner_rel->part_rels[inner_index] : NULL);
2501 }
2502
2505}

References Assert, fb(), i, lappend(), Max, NIL, palloc_array, and pfree().

Referenced by merge_list_bounds(), and merge_range_bounds().

◆ get_hash_partition_greatest_modulus()

int get_hash_partition_greatest_modulus ( PartitionBoundInfo  bound)

Definition at line 3407 of file partbounds.c.

3408{
3409 Assert(bound && bound->strategy == PARTITION_STRATEGY_HASH);
3410 return bound->nindexes;
3411}

References Assert, PartitionBoundInfoData::nindexes, PARTITION_STRATEGY_HASH, and PartitionBoundInfoData::strategy.

◆ get_merged_range_bounds()

static void get_merged_range_bounds ( int  partnatts,
FmgrInfo partsupfuncs,
Oid partcollations,
JoinType  jointype,
PartitionRangeBound outer_lb,
PartitionRangeBound outer_ub,
PartitionRangeBound inner_lb,
PartitionRangeBound inner_ub,
int  lb_cmpval,
int  ub_cmpval,
PartitionRangeBound merged_lb,
PartitionRangeBound merged_ub 
)
static

Definition at line 2704 of file partbounds.c.

2713{
2718
2719 switch (jointype)
2720 {
2721 case JOIN_INNER:
2722 case JOIN_SEMI:
2723
2724 /*
2725 * An INNER/SEMI join will have the rows that fit both sides, so
2726 * the lower bound of the merged partition will be the higher of
2727 * the two lower bounds, and the upper bound of the merged
2728 * partition will be the lower of the two upper bounds.
2729 */
2730 *merged_lb = (lb_cmpval > 0) ? *outer_lb : *inner_lb;
2731 *merged_ub = (ub_cmpval < 0) ? *outer_ub : *inner_ub;
2732 break;
2733
2734 case JOIN_LEFT:
2735 case JOIN_ANTI:
2736
2737 /*
2738 * A LEFT/ANTI join will have all the rows from the outer side, so
2739 * the bounds of the merged partition will be the same as the
2740 * outer bounds.
2741 */
2742 *merged_lb = *outer_lb;
2743 *merged_ub = *outer_ub;
2744 break;
2745
2746 case JOIN_FULL:
2747
2748 /*
2749 * A FULL join will have all the rows from both sides, so the
2750 * lower bound of the merged partition will be the lower of the
2751 * two lower bounds, and the upper bound of the merged partition
2752 * will be the higher of the two upper bounds.
2753 */
2754 *merged_lb = (lb_cmpval < 0) ? *outer_lb : *inner_lb;
2755 *merged_ub = (ub_cmpval > 0) ? *outer_ub : *inner_ub;
2756 break;
2757
2758 default:
2759 elog(ERROR, "unrecognized join type: %d", (int) jointype);
2760 }
2761}

References Assert, compare_range_bounds, elog, ERROR, fb(), JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, and JOIN_SEMI.

Referenced by merge_range_bounds().

◆ get_non_null_list_datum_count()

static int get_non_null_list_datum_count ( PartitionBoundSpec **  boundspecs,
int  nparts 
)
static

Definition at line 435 of file partbounds.c.

436{
437 int i;
438 int count = 0;
439
440 for (i = 0; i < nparts; i++)
441 {
442 ListCell *lc;
443
444 foreach(lc, boundspecs[i]->listdatums)
445 {
447
448 if (!val->constisnull)
449 count++;
450 }
451 }
452
453 return count;
454}

References fb(), i, lfirst_node, and val.

Referenced by create_list_bounds().

◆ get_partition_bound_spec()

static PartitionBoundSpec * get_partition_bound_spec ( Oid  partOid)
static

Definition at line 5056 of file partbounds.c.

5057{
5058 HeapTuple tuple;
5059 Datum datum;
5060 bool isnull;
5062
5063 /* Try fetching the tuple from the catcache, for speed. */
5064 tuple = SearchSysCache1(RELOID, partOid);
5065 if (!HeapTupleIsValid(tuple))
5066 elog(ERROR, "cache lookup failed for relation %u", partOid);
5067
5068 datum = SysCacheGetAttr(RELOID, tuple,
5070 &isnull);
5071 if (isnull)
5072 elog(ERROR, "partition bound for relation %u is null",
5073 partOid);
5074
5076
5078 elog(ERROR, "expected PartitionBoundSpec for relation %u",
5079 partOid);
5080
5081 ReleaseSysCache(tuple);
5082 return boundspec;
5083}

References elog, ERROR, fb(), HeapTupleIsValid, IsA, ReleaseSysCache(), SearchSysCache1(), stringToNode(), SysCacheGetAttr(), and TextDatumGetCString.

Referenced by calculate_partition_bound_for_merge(), and check_partition_bounds_for_split_range().

◆ get_partition_operator()

static Oid get_partition_operator ( PartitionKey  key,
int  col,
StrategyNumber  strategy,
bool need_relabel 
)
static

Definition at line 3824 of file partbounds.c.

3826{
3827 Oid operoid;
3828
3829 /*
3830 * Get the operator in the partitioning opfamily using the opclass'
3831 * declared input type as both left- and righttype.
3832 */
3833 operoid = get_opfamily_member(key->partopfamily[col],
3834 key->partopcintype[col],
3835 key->partopcintype[col],
3836 strategy);
3837 if (!OidIsValid(operoid))
3838 elog(ERROR, "missing operator %d(%u,%u) in partition opfamily %u",
3839 strategy, key->partopcintype[col], key->partopcintype[col],
3840 key->partopfamily[col]);
3841
3842 /*
3843 * If the partition key column is not of the same type as the operator
3844 * class and not polymorphic, tell caller to wrap the non-Const expression
3845 * in a RelabelType. This matches what parse_coerce.c does.
3846 */
3847 *need_relabel = (key->parttypid[col] != key->partopcintype[col] &&
3848 key->partopcintype[col] != RECORDOID &&
3849 !IsPolymorphicType(key->partopcintype[col]));
3850
3851 return operoid;
3852}

References elog, ERROR, fb(), get_opfamily_member(), and OidIsValid.

Referenced by make_partition_op_expr().

◆ get_qual_for_hash()

static List * get_qual_for_hash ( Relation  parent,
PartitionBoundSpec spec 
)
static

Definition at line 3975 of file partbounds.c.

3976{
3978 FuncExpr *fexpr;
3982 List *args;
3984 int i;
3985
3986 /* Fixed arguments. */
3988 -1,
3989 InvalidOid,
3990 sizeof(Oid),
3992 false,
3993 true);
3994
3996 -1,
3997 InvalidOid,
3998 sizeof(int32),
3999 Int32GetDatum(spec->modulus),
4000 false,
4001 true);
4002
4004 -1,
4005 InvalidOid,
4006 sizeof(int32),
4007 Int32GetDatum(spec->remainder),
4008 false,
4009 true);
4010
4012 partexprs_item = list_head(key->partexprs);
4013
4014 /* Add an argument for each key column. */
4015 for (i = 0; i < key->partnatts; i++)
4016 {
4017 Node *keyCol;
4018
4019 /* Left operand */
4020 if (key->partattrs[i] != 0)
4021 {
4022 keyCol = (Node *) makeVar(1,
4023 key->partattrs[i],
4024 key->parttypid[i],
4025 key->parttypmod[i],
4026 key->parttypcoll[i],
4027 0);
4028 }
4029 else
4030 {
4032 partexprs_item = lnext(key->partexprs, partexprs_item);
4033 }
4034
4035 args = lappend(args, keyCol);
4036 }
4037
4039 BOOLOID,
4040 args,
4041 InvalidOid,
4042 InvalidOid,
4044
4045 return list_make1(fexpr);
4046}

References COERCE_EXPLICIT_CALL, copyObject, fb(), i, Int32GetDatum(), InvalidOid, lappend(), lfirst, list_head(), list_make1, list_make3, lnext(), makeConst(), makeFuncExpr(), makeVar(), ObjectIdGetDatum(), RelationGetPartitionKey(), and RelationGetRelid.

Referenced by get_qual_from_partbound().

◆ get_qual_for_list()

static List * get_qual_for_list ( Relation  parent,
PartitionBoundSpec spec 
)
static

Definition at line 4058 of file partbounds.c.

4059{
4061 List *result;
4062 Expr *keyCol;
4063 Expr *opexpr;
4065 ListCell *cell;
4066 List *elems = NIL;
4067 bool list_has_null = false;
4068
4069 /*
4070 * Only single-column list partitioning is supported, so we are worried
4071 * only about the partition key with index 0.
4072 */
4073 Assert(key->partnatts == 1);
4074
4075 /* Construct Var or expression representing the partition column */
4076 if (key->partattrs[0] != 0)
4077 keyCol = (Expr *) makeVar(1,
4078 key->partattrs[0],
4079 key->parttypid[0],
4080 key->parttypmod[0],
4081 key->parttypcoll[0],
4082 0);
4083 else
4084 keyCol = (Expr *) copyObject(linitial(key->partexprs));
4085
4086 /*
4087 * For default list partition, collect datums for all the partitions. The
4088 * default partition constraint should check that the partition key is
4089 * equal to none of those.
4090 */
4091 if (spec->is_default)
4092 {
4093 int i;
4094 int ndatums = 0;
4096 PartitionBoundInfo boundinfo = pdesc->boundinfo;
4097
4098 if (boundinfo)
4099 {
4100 ndatums = boundinfo->ndatums;
4101
4102 if (partition_bound_accepts_nulls(boundinfo))
4103 list_has_null = true;
4104 }
4105
4106 /*
4107 * If default is the only partition, there need not be any partition
4108 * constraint on it.
4109 */
4110 if (ndatums == 0 && !list_has_null)
4111 return NIL;
4112
4113 for (i = 0; i < ndatums; i++)
4114 {
4115 Const *val;
4116
4117 /*
4118 * Construct Const from known-not-null datum. We must be careful
4119 * to copy the value, because our result has to be able to outlive
4120 * the relcache entry we're copying from.
4121 */
4122 val = makeConst(key->parttypid[0],
4123 key->parttypmod[0],
4124 key->parttypcoll[0],
4125 key->parttyplen[0],
4126 datumCopy(*boundinfo->datums[i],
4127 key->parttypbyval[0],
4128 key->parttyplen[0]),
4129 false, /* isnull */
4130 key->parttypbyval[0]);
4131
4132 elems = lappend(elems, val);
4133 }
4134 }
4135 else
4136 {
4137 /*
4138 * Create list of Consts for the allowed values, excluding any nulls.
4139 */
4140 foreach(cell, spec->listdatums)
4141 {
4142 Const *val = lfirst_node(Const, cell);
4143
4144 if (val->constisnull)
4145 list_has_null = true;
4146 else
4147 elems = lappend(elems, copyObject(val));
4148 }
4149 }
4150
4151 if (elems)
4152 {
4153 /*
4154 * Generate the operator expression from the non-null partition
4155 * values.
4156 */
4158 keyCol, (Expr *) elems);
4159 }
4160 else
4161 {
4162 /*
4163 * If there are no partition values, we don't need an operator
4164 * expression.
4165 */
4166 opexpr = NULL;
4167 }
4168
4169 if (!list_has_null)
4170 {
4171 /*
4172 * Gin up a "col IS NOT NULL" test that will be ANDed with the main
4173 * expression. This might seem redundant, but the partition routing
4174 * machinery needs it.
4175 */
4177 nulltest->arg = keyCol;
4178 nulltest->nulltesttype = IS_NOT_NULL;
4179 nulltest->argisrow = false;
4180 nulltest->location = -1;
4181
4182 result = opexpr ? list_make2(nulltest, opexpr) : list_make1(nulltest);
4183 }
4184 else
4185 {
4186 /*
4187 * Gin up a "col IS NULL" test that will be OR'd with the main
4188 * expression.
4189 */
4191 nulltest->arg = keyCol;
4192 nulltest->nulltesttype = IS_NULL;
4193 nulltest->argisrow = false;
4194 nulltest->location = -1;
4195
4196 if (opexpr)
4197 {
4198 Expr *or;
4199
4200 or = makeBoolExpr(OR_EXPR, list_make2(nulltest, opexpr), -1);
4201 result = list_make1(or);
4202 }
4203 else
4204 result = list_make1(nulltest);
4205 }
4206
4207 /*
4208 * Note that, in general, applying NOT to a constraint expression doesn't
4209 * necessarily invert the set of rows it accepts, because NOT (NULL) is
4210 * NULL. However, the partition constraints we construct here never
4211 * evaluate to NULL, so applying NOT works as intended.
4212 */
4213 if (spec->is_default)
4214 {
4215 result = list_make1(make_ands_explicit(result));
4216 result = list_make1(makeBoolExpr(NOT_EXPR, result, -1));
4217 }
4218
4219 return result;
4220}

References Assert, BTEqualStrategyNumber, copyObject, datumCopy(), PartitionBoundInfoData::datums, fb(), i, IS_NOT_NULL, IS_NULL, lappend(), lfirst_node, linitial, list_make1, list_make2, make_ands_explicit(), make_partition_op_expr(), makeBoolExpr(), makeConst(), makeNode, makeVar(), PartitionBoundInfoData::ndatums, NIL, NOT_EXPR, OR_EXPR, partition_bound_accepts_nulls, RelationGetPartitionDesc(), RelationGetPartitionKey(), and val.

Referenced by check_default_partition_contents(), and get_qual_from_partbound().

◆ get_qual_for_range()

static List * get_qual_for_range ( Relation  parent,
PartitionBoundSpec spec,
bool  for_default 
)
static

Definition at line 4267 of file partbounds.c.

4269{
4270 List *result = NIL;
4271 ListCell *cell1,
4272 *cell2,
4275 int i,
4276 j;
4277 PartitionRangeDatum *ldatum,
4278 *udatum;
4280 Expr *keyCol;
4282 *upper_val;
4285 int num_or_arms,
4291
4292 if (spec->is_default)
4293 {
4296 Oid *inhoids = pdesc->oids;
4297 int nparts = pdesc->nparts,
4298 k;
4299
4300 for (k = 0; k < nparts; k++)
4301 {
4302 Oid inhrelid = inhoids[k];
4303 HeapTuple tuple;
4304 Datum datum;
4306
4307 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(inhrelid));
4308 if (!HeapTupleIsValid(tuple))
4309 elog(ERROR, "cache lookup failed for relation %u", inhrelid);
4310
4311 datum = SysCacheGetAttrNotNull(RELOID, tuple,
4316 elog(ERROR, "expected PartitionBoundSpec");
4317
4318 if (!bspec->is_default)
4319 {
4320 List *part_qual;
4321
4322 part_qual = get_qual_for_range(parent, bspec, true);
4323
4324 /*
4325 * AND the constraints of the partition and add to
4326 * or_expr_args
4327 */
4330 : linitial(part_qual));
4331 }
4332 ReleaseSysCache(tuple);
4333 }
4334
4335 if (or_expr_args != NIL)
4336 {
4338
4339 /*
4340 * Combine the constraints obtained for non-default partitions
4341 * using OR. As requested, each of the OR's args doesn't include
4342 * the NOT NULL test for partition keys (which is to avoid its
4343 * useless repetition). Add the same now.
4344 */
4350 -1)
4352 -1);
4353
4354 /*
4355 * Finally, the default partition contains everything *NOT*
4356 * contained in the non-default partitions.
4357 */
4360 }
4361
4362 return result;
4363 }
4364
4365 /*
4366 * If it is the recursive call for default, we skip the get_range_nulltest
4367 * to avoid accumulating the NullTest on the same keys for each partition.
4368 */
4369 if (!for_default)
4370 result = get_range_nulltest(key);
4371
4372 /*
4373 * Iterate over the key columns and check if the corresponding lower and
4374 * upper datums are equal using the btree equality operator for the
4375 * column's type. If equal, we emit single keyCol = common_value
4376 * expression. Starting from the first column for which the corresponding
4377 * lower and upper bound datums are not equal, we generate OR expressions
4378 * as shown in the function's header comment.
4379 */
4380 i = 0;
4381 partexprs_item = list_head(key->partexprs);
4382 partexprs_item_saved = partexprs_item; /* placate compiler */
4383 forboth(cell1, spec->lowerdatums, cell2, spec->upperdatums)
4384 {
4385 EState *estate;
4387 Expr *test_expr;
4390 bool isNull;
4391
4394
4395 /*
4396 * Since get_range_key_properties() modifies partexprs_item, and we
4397 * might need to start over from the previous expression in the later
4398 * part of this function, save away the current value.
4399 */
4401
4402 get_range_key_properties(key, i, ldatum, udatum,
4404 &keyCol,
4405 &lower_val, &upper_val);
4406
4407 /*
4408 * If either value is NULL, the corresponding partition bound is
4409 * either MINVALUE or MAXVALUE, and we treat them as unequal, because
4410 * even if they're the same, there is no common value to equate the
4411 * key column with.
4412 */
4413 if (!lower_val || !upper_val)
4414 break;
4415
4416 /* Create the test expression */
4417 estate = CreateExecutorState();
4420 (Expr *) lower_val,
4421 (Expr *) upper_val);
4425 GetPerTupleExprContext(estate),
4426 &isNull);
4428 FreeExecutorState(estate);
4429
4430 /* If not equal, go generate the OR expressions */
4432 break;
4433
4434 /*
4435 * The bounds for the last key column can't be equal, because such a
4436 * range partition would never be allowed to be defined (it would have
4437 * an empty range otherwise).
4438 */
4439 if (i == key->partnatts - 1)
4440 elog(ERROR, "invalid range bound specification");
4441
4442 /* Equal, so generate keyCol = lower_val expression */
4443 result = lappend(result,
4445 keyCol, (Expr *) lower_val));
4446
4447 i++;
4448 }
4449
4450 /* First pair of lower_val and upper_val that are not equal. */
4453
4454 /* OR will have as many arms as there are key columns left. */
4455 num_or_arms = key->partnatts - i;
4456 current_or_arm = 0;
4459 while (current_or_arm < num_or_arms)
4460 {
4463
4464 /* Restart scan of columns from the i'th one */
4465 j = i;
4467
4469 cell2, spec->upperdatums, upper_or_start_datum)
4470 {
4472 *udatum_next = NULL;
4473
4475 if (lnext(spec->lowerdatums, cell1))
4477 lfirst(lnext(spec->lowerdatums, cell1)));
4479 if (lnext(spec->upperdatums, cell2))
4481 lfirst(lnext(spec->upperdatums, cell2)));
4482 get_range_key_properties(key, j, ldatum, udatum,
4484 &keyCol,
4485 &lower_val, &upper_val);
4486
4488 {
4489 uint16 strategy;
4490
4491 /*
4492 * For the non-last columns of this arm, use the EQ operator.
4493 * For the last column of this arm, use GT, unless this is the
4494 * last column of the whole bound check, or the next bound
4495 * datum is MINVALUE, in which case use GE.
4496 */
4497 if (j - i < current_or_arm)
4498 strategy = BTEqualStrategyNumber;
4499 else if (j == key->partnatts - 1 ||
4500 (ldatum_next &&
4503 else
4504 strategy = BTGreaterStrategyNumber;
4505
4508 strategy,
4509 keyCol,
4510 (Expr *) lower_val));
4511 }
4512
4514 {
4515 uint16 strategy;
4516
4517 /*
4518 * For the non-last columns of this arm, use the EQ operator.
4519 * For the last column of this arm, use LT, unless the next
4520 * bound datum is MAXVALUE, in which case use LE.
4521 */
4522 if (j - i < current_or_arm)
4523 strategy = BTEqualStrategyNumber;
4524 else if (udatum_next &&
4526 strategy = BTLessEqualStrategyNumber;
4527 else
4528 strategy = BTLessStrategyNumber;
4529
4532 strategy,
4533 keyCol,
4534 (Expr *) upper_val));
4535 }
4536
4537 /*
4538 * Did we generate enough of OR's arguments? First arm considers
4539 * the first of the remaining columns, second arm considers first
4540 * two of the remaining columns, and so on.
4541 */
4542 ++j;
4543 if (j - i > current_or_arm)
4544 {
4545 /*
4546 * We must not emit any more arms if the new column that will
4547 * be considered is unbounded, or this one was.
4548 */
4549 if (!lower_val || !ldatum_next ||
4551 need_next_lower_arm = false;
4552 if (!upper_val || !udatum_next ||
4554 need_next_upper_arm = false;
4555 break;
4556 }
4557 }
4558
4559 if (lower_or_arm_args != NIL)
4564
4565 if (upper_or_arm_args != NIL)
4570
4571 /* If no work to do in the next iteration, break away. */
4573 break;
4574
4576 }
4577
4578 /*
4579 * Generate the OR expressions for each of lower and upper bounds (if
4580 * required), and append to the list of implicitly ANDed list of
4581 * expressions.
4582 */
4583 if (lower_or_arms != NIL)
4584 result = lappend(result,
4588 if (upper_or_arms != NIL)
4589 result = lappend(result,
4593
4594 /*
4595 * As noted above, for non-default, we return list with constant TRUE. If
4596 * the result is NIL during the recursive call for default, it implies
4597 * this is the only other partition which can hold every value of the key
4598 * except NULL. Hence we return the NullTest result skipped earlier.
4599 */
4600 if (result == NIL)
4601 result = for_default
4602 ? get_range_nulltest(key)
4604
4605 return result;
4606}

References AND_EXPR, BTEqualStrategyNumber, BTGreaterEqualStrategyNumber, BTGreaterStrategyNumber, BTLessEqualStrategyNumber, BTLessStrategyNumber, castNode, CreateExecutorState(), DatumGetBool(), elog, ERROR, EState::es_query_cxt, ExecEvalExprSwitchContext(), ExecInitExpr(), fb(), fix_opfuncids(), for_both_cell, forboth, FreeExecutorState(), get_qual_for_range(), get_range_key_properties(), get_range_nulltest(), GetPerTupleExprContext, HeapTupleIsValid, i, IsA, j, lappend(), lfirst, lfirst_node, linitial, list_head(), list_length(), list_make1, lnext(), make_partition_op_expr(), makeBoolConst(), makeBoolExpr(), MemoryContextSwitchTo(), NIL, NOT_EXPR, ObjectIdGetDatum(), OR_EXPR, PARTITION_RANGE_DATUM_MAXVALUE, PARTITION_RANGE_DATUM_MINVALUE, PARTITION_RANGE_DATUM_VALUE, RelationGetPartitionDesc(), RelationGetPartitionKey(), ReleaseSysCache(), SearchSysCache1(), stringToNode(), SysCacheGetAttrNotNull(), and TextDatumGetCString.

Referenced by check_default_partition_contents(), get_qual_for_range(), and get_qual_from_partbound().

◆ get_qual_from_partbound()

List * get_qual_from_partbound ( Relation  parent,
PartitionBoundSpec spec 
)

Definition at line 250 of file partbounds.c.

251{
253 List *my_qual = NIL;
254
255 Assert(key != NULL);
256
257 switch (key->strategy)
258 {
260 Assert(spec->strategy == PARTITION_STRATEGY_HASH);
261 my_qual = get_qual_for_hash(parent, spec);
262 break;
263
265 Assert(spec->strategy == PARTITION_STRATEGY_LIST);
266 my_qual = get_qual_for_list(parent, spec);
267 break;
268
271 my_qual = get_qual_for_range(parent, spec, false);
272 break;
273 }
274
275 return my_qual;
276}

References Assert, fb(), get_qual_for_hash(), get_qual_for_list(), get_qual_for_range(), NIL, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, and RelationGetPartitionKey().

Referenced by ATExecAttachPartition(), generate_partition_qual(), and SplitPartitionMoveRows().

◆ get_range_key_properties()

static void get_range_key_properties ( PartitionKey  key,
int  keynum,
PartitionRangeDatum ldatum,
PartitionRangeDatum udatum,
ListCell **  partexprs_item,
Expr **  keyCol,
Const **  lower_val,
Const **  upper_val 
)
static

Definition at line 4624 of file partbounds.c.

4630{
4631 /* Get partition key expression for this column */
4632 if (key->partattrs[keynum] != 0)
4633 {
4634 *keyCol = (Expr *) makeVar(1,
4635 key->partattrs[keynum],
4636 key->parttypid[keynum],
4637 key->parttypmod[keynum],
4638 key->parttypcoll[keynum],
4639 0);
4640 }
4641 else
4642 {
4643 if (*partexprs_item == NULL)
4644 elog(ERROR, "wrong number of partition key expressions");
4646 *partexprs_item = lnext(key->partexprs, *partexprs_item);
4647 }
4648
4649 /* Get appropriate Const nodes for the bounds */
4650 if (ldatum->kind == PARTITION_RANGE_DATUM_VALUE)
4651 *lower_val = castNode(Const, copyObject(ldatum->value));
4652 else
4653 *lower_val = NULL;
4654
4657 else
4658 *upper_val = NULL;
4659}

References castNode, copyObject, elog, ERROR, fb(), PartitionRangeDatum::kind, lfirst, lnext(), makeVar(), PARTITION_RANGE_DATUM_VALUE, and PartitionRangeDatum::value.

Referenced by get_qual_for_range().

◆ get_range_nulltest()

static List * get_range_nulltest ( PartitionKey  key)
static

Definition at line 4668 of file partbounds.c.

4669{
4670 List *result = NIL;
4673 int i;
4674
4675 partexprs_item = list_head(key->partexprs);
4676 for (i = 0; i < key->partnatts; i++)
4677 {
4678 Expr *keyCol;
4679
4680 if (key->partattrs[i] != 0)
4681 {
4682 keyCol = (Expr *) makeVar(1,
4683 key->partattrs[i],
4684 key->parttypid[i],
4685 key->parttypmod[i],
4686 key->parttypcoll[i],
4687 0);
4688 }
4689 else
4690 {
4691 if (partexprs_item == NULL)
4692 elog(ERROR, "wrong number of partition key expressions");
4694 partexprs_item = lnext(key->partexprs, partexprs_item);
4695 }
4696
4698 nulltest->arg = keyCol;
4699 nulltest->nulltesttype = IS_NOT_NULL;
4700 nulltest->argisrow = false;
4701 nulltest->location = -1;
4702 result = lappend(result, nulltest);
4703 }
4704
4705 return result;
4706}

References copyObject, elog, ERROR, fb(), i, IS_NOT_NULL, lappend(), lfirst, list_head(), lnext(), makeNode, makeVar(), and NIL.

Referenced by get_qual_for_range().

◆ get_range_partition()

static int get_range_partition ( RelOptInfo rel,
PartitionBoundInfo  bi,
int lb_pos,
PartitionRangeBound lb,
PartitionRangeBound ub 
)
static

Definition at line 2574 of file partbounds.c.

2579{
2580 int part_index;
2581
2582 Assert(bi->strategy == PARTITION_STRATEGY_RANGE);
2583
2584 do
2585 {
2587 if (part_index == -1)
2588 return -1;
2589 } while (is_dummy_partition(rel, part_index));
2590
2591 return part_index;
2592}

References Assert, fb(), get_range_partition_internal(), is_dummy_partition(), and PARTITION_STRATEGY_RANGE.

Referenced by merge_range_bounds().

◆ get_range_partition_internal()

static int get_range_partition_internal ( PartitionBoundInfo  bi,
int lb_pos,
PartitionRangeBound lb,
PartitionRangeBound ub 
)
static

Definition at line 2595 of file partbounds.c.

2599{
2600 /* Return the index as -1 if we've exhausted all lower bounds. */
2601 if (*lb_pos >= bi->ndatums)
2602 return -1;
2603
2604 /* A lower bound should have at least one more bound after it. */
2605 Assert(*lb_pos + 1 < bi->ndatums);
2606
2607 /* Set the lower bound. */
2608 lb->index = bi->indexes[*lb_pos];
2609 lb->datums = bi->datums[*lb_pos];
2610 lb->kind = bi->kind[*lb_pos];
2611 lb->lower = true;
2612 /* Set the upper bound. */
2613 ub->index = bi->indexes[*lb_pos + 1];
2614 ub->datums = bi->datums[*lb_pos + 1];
2615 ub->kind = bi->kind[*lb_pos + 1];
2616 ub->lower = false;
2617
2618 /* The index assigned to an upper bound should be valid. */
2619 Assert(ub->index >= 0);
2620
2621 /*
2622 * Advance the position to the next lower bound. If there are no bounds
2623 * left beyond the upper bound, we have reached the last lower bound.
2624 */
2625 if (*lb_pos + 2 >= bi->ndatums)
2626 *lb_pos = bi->ndatums;
2627 else
2628 {
2629 /*
2630 * If the index assigned to the bound next to the upper bound isn't
2631 * valid, that is the next lower bound; else, the upper bound is also
2632 * the lower bound of the next range partition.
2633 */
2634 if (bi->indexes[*lb_pos + 2] < 0)
2635 *lb_pos = *lb_pos + 2;
2636 else
2637 *lb_pos = *lb_pos + 1;
2638 }
2639
2640 return ub->index;
2641}

References Assert, PartitionRangeBound::datums, fb(), PartitionRangeBound::index, PartitionRangeBound::kind, and PartitionRangeBound::lower.

Referenced by get_range_partition().

◆ init_partition_map()

static void init_partition_map ( RelOptInfo rel,
PartitionMap map 
)
static

Definition at line 1805 of file partbounds.c.

1806{
1807 int nparts = rel->nparts;
1808 int i;
1809
1810 map->nparts = nparts;
1811 map->merged_indexes = palloc_array(int, nparts);
1812 map->merged = palloc_array(bool, nparts);
1813 map->did_remapping = false;
1814 map->old_indexes = palloc_array(int, nparts);
1815 for (i = 0; i < nparts; i++)
1816 {
1817 map->merged_indexes[i] = map->old_indexes[i] = -1;
1818 map->merged[i] = false;
1819 }
1820}

References PartitionMap::did_remapping, i, PartitionMap::merged, PartitionMap::merged_indexes, PartitionMap::nparts, RelOptInfo::nparts, PartitionMap::old_indexes, and palloc_array.

Referenced by merge_list_bounds(), and merge_range_bounds().

◆ is_dummy_partition()

static bool is_dummy_partition ( RelOptInfo rel,
int  part_index 
)
static

Definition at line 1837 of file partbounds.c.

1838{
1840
1841 Assert(part_index >= 0);
1842 part_rel = rel->part_rels[part_index];
1844 return true;
1845 return false;
1846}

References Assert, fb(), and IS_DUMMY_REL.

Referenced by get_range_partition(), merge_list_bounds(), and merge_range_bounds().

◆ make_one_partition_rbound()

static PartitionRangeBound * make_one_partition_rbound ( PartitionKey  key,
int  index,
List datums,
bool  lower 
)
static

Definition at line 3421 of file partbounds.c.

3422{
3423 PartitionRangeBound *bound;
3424 ListCell *lc;
3425 int i;
3426
3427 Assert(datums != NIL);
3428
3430 bound->index = index;
3431 bound->datums = palloc0_array(Datum, key->partnatts);
3432 bound->kind = palloc0_array(PartitionRangeDatumKind, key->partnatts);
3433 bound->lower = lower;
3434
3435 i = 0;
3436 foreach(lc, datums)
3437 {
3439
3440 /* What's contained in this range datum? */
3441 bound->kind[i] = datum->kind;
3442
3443 if (datum->kind == PARTITION_RANGE_DATUM_VALUE)
3444 {
3445 Const *val = castNode(Const, datum->value);
3446
3447 if (val->constisnull)
3448 elog(ERROR, "invalid range bound datum");
3449 bound->datums[i] = val->constvalue;
3450 }
3451
3452 i++;
3453 }
3454
3455 return bound;
3456}

References Assert, castNode, PartitionRangeBound::datums, elog, ERROR, fb(), i, PartitionRangeBound::index, PartitionRangeBound::kind, PartitionRangeDatum::kind, lfirst_node, PartitionRangeBound::lower, lower(), NIL, palloc0_array, palloc0_object, PARTITION_RANGE_DATUM_VALUE, val, and PartitionRangeDatum::value.

Referenced by calculate_partition_bound_for_merge(), check_new_partition_bound(), check_partition_bounds_for_split_range(), check_partitions_for_split(), check_two_partitions_bounds_range(), and create_range_bounds().

◆ make_partition_op_expr()

static Expr * make_partition_op_expr ( PartitionKey  key,
int  keynum,
uint16  strategy,
Expr arg1,
Expr arg2 
)
static

Definition at line 3860 of file partbounds.c.

3862{
3863 Oid operoid;
3864 bool need_relabel = false;
3865 Expr *result = NULL;
3866
3867 /* Get the correct btree operator for this partitioning column */
3869
3870 /*
3871 * Chosen operator may be such that the non-Const operand needs to be
3872 * coerced, so apply the same; see the comment in
3873 * get_partition_operator().
3874 */
3875 if (!IsA(arg1, Const) &&
3876 (need_relabel ||
3877 key->partcollation[keynum] != key->parttypcoll[keynum]))
3879 key->partopcintype[keynum],
3880 -1,
3881 key->partcollation[keynum],
3883
3884 /* Generate the actual expression */
3885 switch (key->strategy)
3886 {
3888 {
3889 List *elems = (List *) arg2;
3890 int nelems = list_length(elems);
3891
3892 Assert(nelems >= 1);
3893 Assert(keynum == 0);
3894
3895 if (nelems > 1 &&
3896 !type_is_array(key->parttypid[keynum]))
3897 {
3900
3901 /* Construct an ArrayExpr for the right-hand inputs */
3903 arrexpr->array_typeid =
3904 get_array_type(key->parttypid[keynum]);
3905 arrexpr->array_collid = key->parttypcoll[keynum];
3906 arrexpr->element_typeid = key->parttypid[keynum];
3907 arrexpr->elements = elems;
3908 arrexpr->multidims = false;
3909 arrexpr->location = -1;
3910
3911 /* Build leftop = ANY (rightop) */
3913 saopexpr->opno = operoid;
3914 saopexpr->opfuncid = get_opcode(operoid);
3915 saopexpr->hashfuncid = InvalidOid;
3916 saopexpr->negfuncid = InvalidOid;
3917 saopexpr->useOr = true;
3918 saopexpr->inputcollid = key->partcollation[keynum];
3919 saopexpr->args = list_make2(arg1, arrexpr);
3920 saopexpr->location = -1;
3921
3922 result = (Expr *) saopexpr;
3923 }
3924 else
3925 {
3926 List *elemops = NIL;
3927 ListCell *lc;
3928
3929 foreach(lc, elems)
3930 {
3931 Expr *elem = lfirst(lc),
3932 *elemop;
3933
3935 BOOLOID,
3936 false,
3937 arg1, elem,
3938 InvalidOid,
3939 key->partcollation[keynum]);
3941 }
3942
3943 result = nelems > 1 ? makeBoolExpr(OR_EXPR, elemops, -1) : linitial(elemops);
3944 }
3945 break;
3946 }
3947
3949 result = make_opclause(operoid,
3950 BOOLOID,
3951 false,
3952 arg1, arg2,
3953 InvalidOid,
3954 key->partcollation[keynum]);
3955 break;
3956
3958 Assert(false);
3959 break;
3960 }
3961
3962 return result;
3963}

References Assert, COERCE_EXPLICIT_CAST, fb(), get_array_type(), get_opcode(), get_partition_operator(), InvalidOid, IsA, lappend(), lfirst, linitial, list_length(), list_make2, make_opclause(), makeBoolExpr(), makeNode, makeRelabelType(), NIL, OR_EXPR, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, and type_is_array.

Referenced by get_qual_for_list(), and get_qual_for_range().

◆ merge_default_partitions()

static void merge_default_partitions ( PartitionMap outer_map,
PartitionMap inner_map,
bool  outer_has_default,
bool  inner_has_default,
int  outer_default,
int  inner_default,
JoinType  jointype,
int next_index,
int default_index 
)
static

Definition at line 2251 of file partbounds.c.

2260{
2261 int outer_merged_index = -1;
2262 int inner_merged_index = -1;
2263
2265
2266 /* Get the merged partition indexes for the default partitions. */
2268 {
2270 outer_merged_index = outer_map->merged_indexes[outer_default];
2271 }
2273 {
2275 inner_merged_index = inner_map->merged_indexes[inner_default];
2276 }
2277
2279 {
2280 /*
2281 * If this is an outer join, the default partition on the outer side
2282 * has to be scanned all the way anyway; if we have not yet assigned a
2283 * partition, merge the default partition with a dummy partition on
2284 * the other side. The merged partition will act as the default
2285 * partition of the join relation (see comments in
2286 * process_inner_partition()).
2287 */
2288 if (IS_OUTER_JOIN(jointype))
2289 {
2290 Assert(jointype != JOIN_RIGHT);
2291 if (outer_merged_index == -1)
2292 {
2293 Assert(*default_index == -1);
2294 *default_index = merge_partition_with_dummy(outer_map,
2296 next_index);
2297 }
2298 else
2299 Assert(*default_index == outer_merged_index);
2300 }
2301 else
2302 Assert(*default_index == -1);
2303 }
2305 {
2306 /*
2307 * If this is a FULL join, the default partition on the inner side has
2308 * to be scanned all the way anyway; if we have not yet assigned a
2309 * partition, merge the default partition with a dummy partition on
2310 * the other side. The merged partition will act as the default
2311 * partition of the join relation (see comments in
2312 * process_outer_partition()).
2313 */
2314 if (jointype == JOIN_FULL)
2315 {
2316 if (inner_merged_index == -1)
2317 {
2318 Assert(*default_index == -1);
2319 *default_index = merge_partition_with_dummy(inner_map,
2321 next_index);
2322 }
2323 else
2324 Assert(*default_index == inner_merged_index);
2325 }
2326 else
2327 Assert(*default_index == -1);
2328 }
2329 else
2330 {
2332
2333 /*
2334 * The default partitions have to be joined with each other, so merge
2335 * them. Note that each of the default partitions isn't merged yet
2336 * (see, process_outer_partition()/process_inner_partition()), so they
2337 * should be merged successfully. The merged partition will act as
2338 * the default partition of the join relation.
2339 */
2342 Assert(*default_index == -1);
2343 *default_index = merge_matching_partitions(outer_map,
2344 inner_map,
2347 next_index);
2348 Assert(*default_index >= 0);
2349 }
2350}

References Assert, fb(), IS_OUTER_JOIN, JOIN_FULL, JOIN_RIGHT, merge_matching_partitions(), and merge_partition_with_dummy().

Referenced by merge_list_bounds(), and merge_range_bounds().

◆ merge_list_bounds()

static PartitionBoundInfo merge_list_bounds ( FmgrInfo partsupfunc,
Oid partcollation,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
JoinType  jointype,
List **  outer_parts,
List **  inner_parts 
)
static

Definition at line 1192 of file partbounds.c.

1196{
1202 int outer_default = outer_bi->default_index;
1203 int inner_default = inner_bi->default_index;
1208 int outer_pos;
1209 int inner_pos;
1210 int next_index = 0;
1211 int null_index = -1;
1212 int default_index = -1;
1214 List *merged_indexes = NIL;
1215
1216 Assert(*outer_parts == NIL);
1217 Assert(*inner_parts == NIL);
1218 Assert(outer_bi->strategy == inner_bi->strategy &&
1219 outer_bi->strategy == PARTITION_STRATEGY_LIST);
1220 /* List partitioning doesn't require kinds. */
1221 Assert(!outer_bi->kind && !inner_bi->kind);
1222
1225
1226 /*
1227 * If the default partitions (if any) have been proven empty, deem them
1228 * non-existent.
1229 */
1231 outer_has_default = false;
1233 inner_has_default = false;
1234
1235 /*
1236 * Merge partitions from both sides. In each iteration we compare a pair
1237 * of list values, one from each side, and decide whether the
1238 * corresponding partitions match or not. If the two values match
1239 * exactly, move to the next pair of list values, otherwise move to the
1240 * next list value on the side with a smaller list value.
1241 */
1242 outer_pos = inner_pos = 0;
1243 while (outer_pos < outer_bi->ndatums || inner_pos < inner_bi->ndatums)
1244 {
1245 int outer_index = -1;
1246 int inner_index = -1;
1249 int cmpval;
1251 int merged_index = -1;
1252
1253 if (outer_pos < outer_bi->ndatums)
1254 {
1255 /*
1256 * If the partition on the outer side has been proven empty,
1257 * ignore it and move to the next datum on the outer side.
1258 */
1259 outer_index = outer_bi->indexes[outer_pos];
1261 {
1262 outer_pos++;
1263 continue;
1264 }
1265 }
1266 if (inner_pos < inner_bi->ndatums)
1267 {
1268 /*
1269 * If the partition on the inner side has been proven empty,
1270 * ignore it and move to the next datum on the inner side.
1271 */
1272 inner_index = inner_bi->indexes[inner_pos];
1274 {
1275 inner_pos++;
1276 continue;
1277 }
1278 }
1279
1280 /* Get the list values. */
1281 outer_datums = outer_pos < outer_bi->ndatums ?
1282 outer_bi->datums[outer_pos] : NULL;
1283 inner_datums = inner_pos < inner_bi->ndatums ?
1284 inner_bi->datums[inner_pos] : NULL;
1285
1286 /*
1287 * We run this loop till both sides finish. This allows us to avoid
1288 * duplicating code to handle the remaining values on the side which
1289 * finishes later. For that we set the comparison parameter cmpval in
1290 * such a way that it appears as if the side which finishes earlier
1291 * has an extra value higher than any other value on the unfinished
1292 * side. That way we advance the values on the unfinished side till
1293 * all of its values are exhausted.
1294 */
1295 if (outer_pos >= outer_bi->ndatums)
1296 cmpval = 1;
1297 else if (inner_pos >= inner_bi->ndatums)
1298 cmpval = -1;
1299 else
1300 {
1302 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
1303 partcollation[0],
1304 outer_datums[0],
1305 inner_datums[0]));
1306 }
1307
1308 if (cmpval == 0)
1309 {
1310 /* Two list values match exactly. */
1313 Assert(outer_index >= 0);
1314 Assert(inner_index >= 0);
1315
1316 /*
1317 * Try merging both partitions. If successful, add the list value
1318 * and index of the merged partition below.
1319 */
1322 &next_index);
1323 if (merged_index == -1)
1324 goto cleanup;
1325
1327
1328 /* Move to the next pair of list values. */
1329 outer_pos++;
1330 inner_pos++;
1331 }
1332 else if (cmpval < 0)
1333 {
1334 /* A list value missing from the inner side. */
1336
1337 /*
1338 * If the inner side has the default partition, or this is an
1339 * outer join, try to assign a merged partition to the outer
1340 * partition (see process_outer_partition()). Otherwise, the
1341 * outer partition will not contribute to the result.
1342 */
1343 if (inner_has_default || IS_OUTER_JOIN(jointype))
1344 {
1345 /* Get the outer partition. */
1346 outer_index = outer_bi->indexes[outer_pos];
1347 Assert(outer_index >= 0);
1349 &inner_map,
1354 jointype,
1355 &next_index,
1356 &default_index);
1357 if (merged_index == -1)
1358 goto cleanup;
1360 }
1361
1362 /* Move to the next list value on the outer side. */
1363 outer_pos++;
1364 }
1365 else
1366 {
1367 /* A list value missing from the outer side. */
1368 Assert(cmpval > 0);
1370
1371 /*
1372 * If the outer side has the default partition, or this is a FULL
1373 * join, try to assign a merged partition to the inner partition
1374 * (see process_inner_partition()). Otherwise, the inner
1375 * partition will not contribute to the result.
1376 */
1377 if (outer_has_default || jointype == JOIN_FULL)
1378 {
1379 /* Get the inner partition. */
1380 inner_index = inner_bi->indexes[inner_pos];
1381 Assert(inner_index >= 0);
1383 &inner_map,
1388 jointype,
1389 &next_index,
1390 &default_index);
1391 if (merged_index == -1)
1392 goto cleanup;
1394 }
1395
1396 /* Move to the next list value on the inner side. */
1397 inner_pos++;
1398 }
1399
1400 /*
1401 * If we assigned a merged partition, add the list value and index of
1402 * the merged partition if appropriate.
1403 */
1404 if (merged_index >= 0 && merged_index != default_index)
1405 {
1407 merged_indexes = lappend_int(merged_indexes, merged_index);
1408 }
1409 }
1410
1411 /*
1412 * If the NULL partitions (if any) have been proven empty, deem them
1413 * non-existent.
1414 */
1415 if (outer_has_null &&
1417 outer_has_null = false;
1418 if (inner_has_null &&
1420 inner_has_null = false;
1421
1422 /* Merge the NULL partitions if any. */
1426 outer_bi->null_index, inner_bi->null_index,
1427 jointype, &next_index, &null_index);
1428 else
1429 Assert(null_index == -1);
1430
1431 /* Merge the default partitions if any. */
1436 jointype, &next_index, &default_index);
1437 else
1438 Assert(default_index == -1);
1439
1440 /* If we have merged partitions, create the partition bounds. */
1441 if (next_index > 0)
1442 {
1443 /* Fix the merged_indexes list if necessary. */
1444 if (outer_map.did_remapping || inner_map.did_remapping)
1445 {
1446 Assert(jointype == JOIN_FULL);
1448 next_index, merged_indexes);
1449 }
1450
1451 /* Use maps to match partitions from inputs. */
1454 next_index,
1456 Assert(*outer_parts != NIL);
1457 Assert(*inner_parts != NIL);
1460
1461 /* Make a PartitionBoundInfo struct to return. */
1464 NIL,
1465 merged_indexes,
1466 null_index,
1467 default_index);
1469 }
1470
1471cleanup:
1472 /* Free local memory before returning. */
1474 list_free(merged_indexes);
1477
1478 return merged_bounds;
1479}

References Assert, build_merged_partition_bounds(), cleanup(), DatumGetInt32(), fb(), fix_merged_indexes(), free_partition_map(), FunctionCall2Coll(), generate_matching_part_pairs(), init_partition_map(), is_dummy_partition(), IS_OUTER_JOIN, JOIN_FULL, lappend(), lappend_int(), list_free(), list_length(), merge_default_partitions(), merge_matching_partitions(), merge_null_partitions(), NIL, partition_bound_accepts_nulls, partition_bound_has_default, PARTITION_STRATEGY_LIST, process_inner_partition(), and process_outer_partition().

Referenced by partition_bounds_merge().

◆ merge_matching_partitions()

static int merge_matching_partitions ( PartitionMap outer_map,
PartitionMap inner_map,
int  outer_index,
int  inner_index,
int next_index 
)
static

Definition at line 1856 of file partbounds.c.

1858{
1861 bool outer_merged;
1862 bool inner_merged;
1863
1865 outer_merged_index = outer_map->merged_indexes[outer_index];
1868 inner_merged_index = inner_map->merged_indexes[inner_index];
1870
1871 /*
1872 * Handle cases where we have already assigned a merged partition to each
1873 * of the given partitions.
1874 */
1875 if (outer_merged_index >= 0 && inner_merged_index >= 0)
1876 {
1877 /*
1878 * If the merged partitions are the same, no need to do anything;
1879 * return the index of the merged partitions. Otherwise, if each of
1880 * the given partitions has been merged with a dummy partition on the
1881 * other side, re-map them to either of the two merged partitions.
1882 * Otherwise, they can't be merged, so return -1.
1883 */
1885 {
1888 return outer_merged_index;
1889 }
1890 if (!outer_merged && !inner_merged)
1891 {
1892 /*
1893 * This can only happen for a list-partitioning case. We re-map
1894 * them to the merged partition with the smaller of the two merged
1895 * indexes to preserve the property that the canonical order of
1896 * list partitions is determined by the indexes assigned to the
1897 * smallest list value of each partition.
1898 */
1900 {
1901 outer_map->merged[outer_index] = true;
1902 inner_map->merged_indexes[inner_index] = outer_merged_index;
1903 inner_map->merged[inner_index] = true;
1904 inner_map->did_remapping = true;
1906 return outer_merged_index;
1907 }
1908 else
1909 {
1910 inner_map->merged[inner_index] = true;
1911 outer_map->merged_indexes[outer_index] = inner_merged_index;
1912 outer_map->merged[outer_index] = true;
1913 outer_map->did_remapping = true;
1915 return inner_merged_index;
1916 }
1917 }
1918 return -1;
1919 }
1920
1921 /* At least one of the given partitions should not have yet been merged. */
1923
1924 /*
1925 * If neither of them has been merged, merge them. Otherwise, if one has
1926 * been merged with a dummy partition on the other side (and the other
1927 * hasn't yet been merged with anything), re-merge them. Otherwise, they
1928 * can't be merged, so return -1.
1929 */
1930 if (outer_merged_index == -1 && inner_merged_index == -1)
1931 {
1932 int merged_index = *next_index;
1933
1936 outer_map->merged_indexes[outer_index] = merged_index;
1937 outer_map->merged[outer_index] = true;
1938 inner_map->merged_indexes[inner_index] = merged_index;
1939 inner_map->merged[inner_index] = true;
1940 *next_index = *next_index + 1;
1941 return merged_index;
1942 }
1943 if (outer_merged_index >= 0 && !outer_map->merged[outer_index])
1944 {
1947 inner_map->merged_indexes[inner_index] = outer_merged_index;
1948 inner_map->merged[inner_index] = true;
1949 outer_map->merged[outer_index] = true;
1950 return outer_merged_index;
1951 }
1952 if (inner_merged_index >= 0 && !inner_map->merged[inner_index])
1953 {
1956 outer_map->merged_indexes[outer_index] = inner_merged_index;
1957 outer_map->merged[outer_index] = true;
1958 inner_map->merged[inner_index] = true;
1959 return inner_merged_index;
1960 }
1961 return -1;
1962}

References Assert, and fb().

Referenced by merge_default_partitions(), merge_list_bounds(), merge_null_partitions(), merge_range_bounds(), process_inner_partition(), and process_outer_partition().

◆ merge_null_partitions()

static void merge_null_partitions ( PartitionMap outer_map,
PartitionMap inner_map,
bool  outer_has_null,
bool  inner_has_null,
int  outer_null,
int  inner_null,
JoinType  jointype,
int next_index,
int null_index 
)
static

Definition at line 2141 of file partbounds.c.

2150{
2151 bool consider_outer_null = false;
2152 bool consider_inner_null = false;
2153
2155 Assert(*null_index == -1);
2156
2157 /*
2158 * Check whether the NULL partitions have already been merged and if so,
2159 * set the consider_outer_null/consider_inner_null flags.
2160 */
2161 if (outer_has_null)
2162 {
2164 if (outer_map->merged_indexes[outer_null] == -1)
2165 consider_outer_null = true;
2166 }
2167 if (inner_has_null)
2168 {
2170 if (inner_map->merged_indexes[inner_null] == -1)
2171 consider_inner_null = true;
2172 }
2173
2174 /* If both flags are set false, we don't need to do anything. */
2176 return;
2177
2179 {
2181
2182 /*
2183 * If this is an outer join, the NULL partition on the outer side has
2184 * to be scanned all the way anyway; merge the NULL partition with a
2185 * dummy partition on the other side. In that case
2186 * consider_outer_null means that the NULL partition only contains
2187 * NULL values as the key values, so the merged partition will do so;
2188 * treat it as the NULL partition of the join relation.
2189 */
2190 if (IS_OUTER_JOIN(jointype))
2191 {
2192 Assert(jointype != JOIN_RIGHT);
2194 next_index);
2195 }
2196 }
2198 {
2200
2201 /*
2202 * If this is a FULL join, the NULL partition on the inner side has to
2203 * be scanned all the way anyway; merge the NULL partition with a
2204 * dummy partition on the other side. In that case
2205 * consider_inner_null means that the NULL partition only contains
2206 * NULL values as the key values, so the merged partition will do so;
2207 * treat it as the NULL partition of the join relation.
2208 */
2209 if (jointype == JOIN_FULL)
2211 next_index);
2212 }
2213 else
2214 {
2218
2219 /*
2220 * If this is an outer join, the NULL partition on the outer side (and
2221 * that on the inner side if this is a FULL join) have to be scanned
2222 * all the way anyway, so merge them. Note that each of the NULL
2223 * partitions isn't merged yet, so they should be merged successfully.
2224 * Like the above, each of the NULL partitions only contains NULL
2225 * values as the key values, so the merged partition will do so; treat
2226 * it as the NULL partition of the join relation.
2227 *
2228 * Note: if this an INNER/SEMI join, the join clause will never be
2229 * satisfied by two NULL values (see comments above), so both the NULL
2230 * partitions can be eliminated.
2231 */
2232 if (IS_OUTER_JOIN(jointype))
2233 {
2234 Assert(jointype != JOIN_RIGHT);
2237 next_index);
2238 Assert(*null_index >= 0);
2239 }
2240 }
2241}

References Assert, fb(), IS_OUTER_JOIN, JOIN_FULL, JOIN_RIGHT, merge_matching_partitions(), and merge_partition_with_dummy().

Referenced by merge_list_bounds().

◆ merge_partition_with_dummy()

static int merge_partition_with_dummy ( PartitionMap map,
int  index,
int next_index 
)
static

Definition at line 2361 of file partbounds.c.

2362{
2363 int merged_index = *next_index;
2364
2365 Assert(index >= 0 && index < map->nparts);
2366 Assert(map->merged_indexes[index] == -1);
2367 Assert(!map->merged[index]);
2369 /* Leave the merged flag alone! */
2370 *next_index = *next_index + 1;
2371 return merged_index;
2372}

References Assert, fb(), PartitionMap::merged, and PartitionMap::merged_indexes.

Referenced by merge_default_partitions(), merge_null_partitions(), process_inner_partition(), and process_outer_partition().

◆ merge_range_bounds()

static PartitionBoundInfo merge_range_bounds ( int  partnatts,
FmgrInfo partsupfuncs,
Oid partcollations,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
JoinType  jointype,
List **  outer_parts,
List **  inner_parts 
)
static

Definition at line 1500 of file partbounds.c.

1505{
1511 int outer_default = outer_bi->default_index;
1512 int inner_default = inner_bi->default_index;
1515 int outer_index;
1516 int inner_index;
1517 int outer_lb_pos;
1518 int inner_lb_pos;
1523 int next_index = 0;
1524 int default_index = -1;
1527 List *merged_indexes = NIL;
1528
1529 Assert(*outer_parts == NIL);
1530 Assert(*inner_parts == NIL);
1531 Assert(outer_bi->strategy == inner_bi->strategy &&
1532 outer_bi->strategy == PARTITION_STRATEGY_RANGE);
1533
1536
1537 /*
1538 * If the default partitions (if any) have been proven empty, deem them
1539 * non-existent.
1540 */
1542 outer_has_default = false;
1544 inner_has_default = false;
1545
1546 /*
1547 * Merge partitions from both sides. In each iteration we compare a pair
1548 * of ranges, one from each side, and decide whether the corresponding
1549 * partitions match or not. If the two ranges overlap, move to the next
1550 * pair of ranges, otherwise move to the next range on the side with a
1551 * lower range. outer_lb_pos/inner_lb_pos keep track of the positions of
1552 * lower bounds in the datums arrays in the outer/inner
1553 * PartitionBoundInfos respectively.
1554 */
1557 &outer_lb, &outer_ub);
1559 &inner_lb, &inner_ub);
1560 while (outer_index >= 0 || inner_index >= 0)
1561 {
1562 bool overlap;
1563 int ub_cmpval;
1564 int lb_cmpval;
1565 PartitionRangeBound merged_lb = {-1, NULL, NULL, true};
1566 PartitionRangeBound merged_ub = {-1, NULL, NULL, false};
1567 int merged_index = -1;
1568
1569 /*
1570 * We run this loop till both sides finish. This allows us to avoid
1571 * duplicating code to handle the remaining ranges on the side which
1572 * finishes later. For that we set the comparison parameter cmpval in
1573 * such a way that it appears as if the side which finishes earlier
1574 * has an extra range higher than any other range on the unfinished
1575 * side. That way we advance the ranges on the unfinished side till
1576 * all of its ranges are exhausted.
1577 */
1578 if (outer_index == -1)
1579 {
1580 overlap = false;
1581 lb_cmpval = 1;
1582 ub_cmpval = 1;
1583 }
1584 else if (inner_index == -1)
1585 {
1586 overlap = false;
1587 lb_cmpval = -1;
1588 ub_cmpval = -1;
1589 }
1590 else
1591 overlap = compare_range_partitions(partnatts, partsupfuncs,
1593 &outer_lb, &outer_ub,
1594 &inner_lb, &inner_ub,
1595 &lb_cmpval, &ub_cmpval);
1596
1597 if (overlap)
1598 {
1599 /* Two ranges overlap; form a join pair. */
1600
1603
1604 /* Both partitions should not have been merged yet. */
1605 Assert(outer_index >= 0);
1606 Assert(outer_map.merged_indexes[outer_index] == -1 &&
1607 outer_map.merged[outer_index] == false);
1608 Assert(inner_index >= 0);
1609 Assert(inner_map.merged_indexes[inner_index] == -1 &&
1610 inner_map.merged[inner_index] == false);
1611
1612 /*
1613 * Get the index of the merged partition. Both partitions aren't
1614 * merged yet, so the partitions should be merged successfully.
1615 */
1618 &next_index);
1619 Assert(merged_index >= 0);
1620
1621 /* Get the range bounds of the merged partition. */
1623 partcollations, jointype,
1624 &outer_lb, &outer_ub,
1625 &inner_lb, &inner_ub,
1627 &merged_lb, &merged_ub);
1628
1629 /* Save the upper bounds of both partitions for use below. */
1632
1633 /* Move to the next pair of ranges. */
1635 &outer_lb, &outer_ub);
1637 &inner_lb, &inner_ub);
1638
1639 /*
1640 * If the range of a partition on one side overlaps the range of
1641 * the next partition on the other side, that will cause the
1642 * partition on one side to match at least two partitions on the
1643 * other side, which is the case that we currently don't support
1644 * partitioned join for; give up.
1645 */
1646 if (ub_cmpval > 0 && inner_index >= 0 &&
1648 &save_outer_ub, &inner_lb) > 0)
1649 goto cleanup;
1652 &outer_lb, &save_inner_ub) < 0)
1653 goto cleanup;
1654
1655 /*
1656 * A row from a non-overlapping portion (if any) of a partition on
1657 * one side might find its join partner in the default partition
1658 * (if any) on the other side, causing the same situation as
1659 * above; give up in that case.
1660 */
1661 if ((outer_has_default && (lb_cmpval > 0 || ub_cmpval < 0)) ||
1663 goto cleanup;
1664 }
1665 else if (ub_cmpval < 0)
1666 {
1667 /* A non-overlapping outer range. */
1668
1669 /* The outer partition should not have been merged yet. */
1670 Assert(outer_index >= 0);
1671 Assert(outer_map.merged_indexes[outer_index] == -1 &&
1672 outer_map.merged[outer_index] == false);
1673
1674 /*
1675 * If the inner side has the default partition, or this is an
1676 * outer join, try to assign a merged partition to the outer
1677 * partition (see process_outer_partition()). Otherwise, the
1678 * outer partition will not contribute to the result.
1679 */
1680 if (inner_has_default || IS_OUTER_JOIN(jointype))
1681 {
1683 &inner_map,
1688 jointype,
1689 &next_index,
1690 &default_index);
1691 if (merged_index == -1)
1692 goto cleanup;
1695 }
1696
1697 /* Move to the next range on the outer side. */
1699 &outer_lb, &outer_ub);
1700 }
1701 else
1702 {
1703 /* A non-overlapping inner range. */
1704 Assert(ub_cmpval > 0);
1705
1706 /* The inner partition should not have been merged yet. */
1707 Assert(inner_index >= 0);
1708 Assert(inner_map.merged_indexes[inner_index] == -1 &&
1709 inner_map.merged[inner_index] == false);
1710
1711 /*
1712 * If the outer side has the default partition, or this is a FULL
1713 * join, try to assign a merged partition to the inner partition
1714 * (see process_inner_partition()). Otherwise, the inner
1715 * partition will not contribute to the result.
1716 */
1717 if (outer_has_default || jointype == JOIN_FULL)
1718 {
1720 &inner_map,
1725 jointype,
1726 &next_index,
1727 &default_index);
1728 if (merged_index == -1)
1729 goto cleanup;
1732 }
1733
1734 /* Move to the next range on the inner side. */
1736 &inner_lb, &inner_ub);
1737 }
1738
1739 /*
1740 * If we assigned a merged partition, add the range bounds and index
1741 * of the merged partition if appropriate.
1742 */
1743 if (merged_index >= 0 && merged_index != default_index)
1747 &merged_indexes);
1748 }
1749
1750 /* Merge the default partitions if any. */
1755 jointype, &next_index, &default_index);
1756 else
1757 Assert(default_index == -1);
1758
1759 /* If we have merged partitions, create the partition bounds. */
1760 if (next_index > 0)
1761 {
1762 /*
1763 * Unlike the case of list partitioning, we wouldn't have re-merged
1764 * partitions, so did_remapping should be left alone.
1765 */
1766 Assert(!outer_map.did_remapping);
1767 Assert(!inner_map.did_remapping);
1768
1769 /* Use maps to match partitions from inputs. */
1772 next_index,
1774 Assert(*outer_parts != NIL);
1775 Assert(*inner_parts != NIL);
1778
1779 /* Make a PartitionBoundInfo struct to return. */
1783 merged_indexes,
1784 -1,
1785 default_index);
1787 }
1788
1789cleanup:
1790 /* Free local memory before returning. */
1793 list_free(merged_indexes);
1796
1797 return merged_bounds;
1798}

References add_merged_range_bounds(), Assert, build_merged_partition_bounds(), cleanup(), compare_range_bounds, compare_range_partitions(), fb(), free_partition_map(), generate_matching_part_pairs(), get_merged_range_bounds(), get_range_partition(), init_partition_map(), is_dummy_partition(), IS_OUTER_JOIN, JOIN_FULL, list_free(), list_length(), merge_default_partitions(), merge_matching_partitions(), NIL, partition_bound_has_default, PARTITION_STRATEGY_RANGE, process_inner_partition(), and process_outer_partition().

Referenced by partition_bounds_merge().

◆ partition_bounds_copy()

PartitionBoundInfo partition_bounds_copy ( PartitionBoundInfo  src,
PartitionKey  key 
)

Definition at line 995 of file partbounds.c.

997{
999 int i;
1000 int ndatums;
1001 int nindexes;
1002 int partnatts;
1003
1005
1006 dest->strategy = src->strategy;
1007 ndatums = dest->ndatums = src->ndatums;
1008 nindexes = dest->nindexes = src->nindexes;
1009 partnatts = key->partnatts;
1010
1011 /* List partitioned tables have only a single partition key. */
1012 Assert(key->strategy != PARTITION_STRATEGY_LIST || partnatts == 1);
1013
1014 dest->datums = palloc_array(Datum *, ndatums);
1015
1016 if (src->kind != NULL && ndatums > 0)
1017 {
1019
1020 /* only RANGE partition should have a non-NULL kind */
1021 Assert(key->strategy == PARTITION_STRATEGY_RANGE);
1022
1023 dest->kind = (PartitionRangeDatumKind **) palloc(ndatums *
1024 sizeof(PartitionRangeDatumKind *));
1025
1026 /*
1027 * In the loop below, to save from allocating a series of small arrays
1028 * for storing the PartitionRangeDatumKind, we allocate a single chunk
1029 * here and use a smaller portion of it for each datum.
1030 */
1031 boundKinds = (PartitionRangeDatumKind *) palloc(ndatums * partnatts *
1032 sizeof(PartitionRangeDatumKind));
1033
1034 for (i = 0; i < ndatums; i++)
1035 {
1036 dest->kind[i] = &boundKinds[i * partnatts];
1037 memcpy(dest->kind[i], src->kind[i],
1038 sizeof(PartitionRangeDatumKind) * partnatts);
1039 }
1040 }
1041 else
1042 dest->kind = NULL;
1043
1044 /* copy interleaved partitions for LIST partitioned tables */
1045 dest->interleaved_parts = bms_copy(src->interleaved_parts);
1046
1047 /*
1048 * For hash partitioning, datums array will have two elements - modulus
1049 * and remainder.
1050 */
1051 if (ndatums > 0)
1052 {
1053 bool hash_part = (key->strategy == PARTITION_STRATEGY_HASH);
1054 int natts = hash_part ? 2 : partnatts;
1055 Datum *boundDatums = palloc(ndatums * natts * sizeof(Datum));
1056
1057 for (i = 0; i < ndatums; i++)
1058 {
1059 int j;
1060
1061 dest->datums[i] = &boundDatums[i * natts];
1062
1063 for (j = 0; j < natts; j++)
1064 {
1065 if (dest->kind == NULL ||
1067 {
1068 bool byval;
1069 int typlen;
1070
1071 if (hash_part)
1072 {
1073 typlen = sizeof(int32); /* Always int4 */
1074 byval = true; /* int4 is pass-by-value */
1075 }
1076 else
1077 {
1078 byval = key->parttypbyval[j];
1079 typlen = key->parttyplen[j];
1080 }
1081 dest->datums[i][j] = datumCopy(src->datums[i][j],
1082 byval, typlen);
1083 }
1084 }
1085 }
1086 }
1087
1088 dest->indexes = palloc_array(int, nindexes);
1089 memcpy(dest->indexes, src->indexes, sizeof(int) * nindexes);
1090
1091 dest->null_index = src->null_index;
1092 dest->default_index = src->default_index;
1093
1094 return dest;
1095}

References Assert, bms_copy(), datumCopy(), PartitionBoundInfoData::datums, PartitionBoundInfoData::default_index, fb(), i, PartitionBoundInfoData::indexes, PartitionBoundInfoData::interleaved_parts, j, PartitionBoundInfoData::kind, PartitionBoundInfoData::ndatums, PartitionBoundInfoData::nindexes, PartitionBoundInfoData::null_index, palloc(), palloc_array, palloc_object, PARTITION_RANGE_DATUM_VALUE, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, and PartitionBoundInfoData::strategy.

Referenced by RelationBuildPartitionDesc().

◆ partition_bounds_create()

PartitionBoundInfo partition_bounds_create ( PartitionBoundSpec **  boundspecs,
int  nparts,
PartitionKey  key,
int **  mapping 
)

Definition at line 300 of file partbounds.c.

302{
303 int i;
304
305 Assert(nparts > 0);
306
307 /*
308 * For each partitioning method, we first convert the partition bounds
309 * from their parser node representation to the internal representation,
310 * along with any additional preprocessing (such as de-duplicating range
311 * bounds). Resulting bound datums are then added to the 'datums' array
312 * in PartitionBoundInfo. For each datum added, an integer indicating the
313 * canonical partition index is added to the 'indexes' array.
314 *
315 * For each bound, we remember its partition's position (0-based) in the
316 * original list to later map it to the canonical index.
317 */
318
319 /*
320 * Initialize mapping array with invalid values, this is filled within
321 * each sub-routine below depending on the bound type.
322 */
323 *mapping = palloc_array(int, nparts);
324 for (i = 0; i < nparts; i++)
325 (*mapping)[i] = -1;
326
327 switch (key->strategy)
328 {
330 return create_hash_bounds(boundspecs, nparts, key, mapping);
331
333 return create_list_bounds(boundspecs, nparts, key, mapping);
334
336 return create_range_bounds(boundspecs, nparts, key, mapping);
337 }
338
339 Assert(false);
340 return NULL; /* keep compiler quiet */
341}

References Assert, create_hash_bounds(), create_list_bounds(), create_range_bounds(), fb(), i, palloc_array, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, and PARTITION_STRATEGY_RANGE.

Referenced by RelationBuildPartitionDesc().

◆ partition_bounds_equal()

bool partition_bounds_equal ( int  partnatts,
int16 parttyplen,
bool parttypbyval,
PartitionBoundInfo  b1,
PartitionBoundInfo  b2 
)

Definition at line 889 of file partbounds.c.

891{
892 int i;
893
894 if (b1->strategy != b2->strategy)
895 return false;
896
897 if (b1->ndatums != b2->ndatums)
898 return false;
899
900 if (b1->nindexes != b2->nindexes)
901 return false;
902
903 if (b1->null_index != b2->null_index)
904 return false;
905
906 if (b1->default_index != b2->default_index)
907 return false;
908
909 /* For all partition strategies, the indexes[] arrays have to match */
910 for (i = 0; i < b1->nindexes; i++)
911 {
912 if (b1->indexes[i] != b2->indexes[i])
913 return false;
914 }
915
916 /* Finally, compare the datums[] arrays */
917 if (b1->strategy == PARTITION_STRATEGY_HASH)
918 {
919 /*
920 * We arrange the partitions in the ascending order of their moduli
921 * and remainders. Also every modulus is factor of next larger
922 * modulus. Therefore we can safely store index of a given partition
923 * in indexes array at remainder of that partition. Also entries at
924 * (remainder + N * modulus) positions in indexes array are all same
925 * for (modulus, remainder) specification for any partition. Thus the
926 * datums arrays from the given bounds are the same, if and only if
927 * their indexes arrays are the same. So, it suffices to compare the
928 * indexes arrays.
929 *
930 * Nonetheless make sure that the bounds are indeed the same when the
931 * indexes match. Hash partition bound stores modulus and remainder
932 * at b1->datums[i][0] and b1->datums[i][1] position respectively.
933 */
934#ifdef USE_ASSERT_CHECKING
935 for (i = 0; i < b1->ndatums; i++)
936 Assert((b1->datums[i][0] == b2->datums[i][0] &&
937 b1->datums[i][1] == b2->datums[i][1]));
938#endif
939 }
940 else
941 {
942 for (i = 0; i < b1->ndatums; i++)
943 {
944 int j;
945
946 for (j = 0; j < partnatts; j++)
947 {
948 /* For range partitions, the bounds might not be finite. */
949 if (b1->kind != NULL)
950 {
951 /* The different kinds of bound all differ from each other */
952 if (b1->kind[i][j] != b2->kind[i][j])
953 return false;
954
955 /*
956 * Non-finite bounds are equal without further
957 * examination.
958 */
959 if (b1->kind[i][j] != PARTITION_RANGE_DATUM_VALUE)
960 continue;
961 }
962
963 /*
964 * Compare the actual values. Note that it would be both
965 * incorrect and unsafe to invoke the comparison operator
966 * derived from the partitioning specification here. It would
967 * be incorrect because we want the relcache entry to be
968 * updated for ANY change to the partition bounds, not just
969 * those that the partitioning operator thinks are
970 * significant. It would be unsafe because we might reach
971 * this code in the context of an aborted transaction, and an
972 * arbitrary partitioning operator might not be safe in that
973 * context. datumIsEqual() should be simple enough to be
974 * safe.
975 */
976 if (!datumIsEqual(b1->datums[i][j], b2->datums[i][j],
977 parttypbyval[j], parttyplen[j]))
978 return false;
979 }
980 }
981 }
982 return true;
983}

References Assert, datumIsEqual(), fb(), i, j, PARTITION_RANGE_DATUM_VALUE, and PARTITION_STRATEGY_HASH.

Referenced by compute_partition_bounds().

◆ partition_bounds_merge()

PartitionBoundInfo partition_bounds_merge ( int  partnatts,
FmgrInfo partsupfunc,
Oid partcollation,
RelOptInfo outer_rel,
RelOptInfo inner_rel,
JoinType  jointype,
List **  outer_parts,
List **  inner_parts 
)

Definition at line 1112 of file partbounds.c.

1117{
1118 /*
1119 * Currently, this function is called only from try_partitionwise_join(),
1120 * so the join type should be INNER, LEFT, FULL, SEMI, or ANTI.
1121 */
1122 Assert(jointype == JOIN_INNER || jointype == JOIN_LEFT ||
1123 jointype == JOIN_FULL || jointype == JOIN_SEMI ||
1124 jointype == JOIN_ANTI);
1125
1126 /* The partitioning strategies should be the same. */
1127 Assert(outer_rel->boundinfo->strategy == inner_rel->boundinfo->strategy);
1128
1130 switch (outer_rel->boundinfo->strategy)
1131 {
1133
1134 /*
1135 * For hash partitioned tables, we currently support partitioned
1136 * join only when they have exactly the same partition bounds.
1137 *
1138 * XXX: it might be possible to relax the restriction to support
1139 * cases where hash partitioned tables have missing partitions
1140 * and/or different moduli, but it's not clear if it would be
1141 * useful to support the former case since it's unusual to have
1142 * missing partitions. On the other hand, it would be useful to
1143 * support the latter case, but in that case, there is a high
1144 * probability that a partition on one side will match multiple
1145 * partitions on the other side, which is the scenario the current
1146 * implementation of partitioned join can't handle.
1147 */
1148 return NULL;
1149
1151 return merge_list_bounds(partsupfunc,
1152 partcollation,
1153 outer_rel,
1154 inner_rel,
1155 jointype,
1157 inner_parts);
1158
1160 return merge_range_bounds(partnatts,
1161 partsupfunc,
1162 partcollation,
1163 outer_rel,
1164 inner_rel,
1165 jointype,
1167 inner_parts);
1168 }
1169
1170 return NULL;
1171}

References Assert, fb(), JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_SEMI, merge_list_bounds(), merge_range_bounds(), NIL, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, and PARTITION_STRATEGY_RANGE.

Referenced by compute_partition_bounds().

◆ partition_hash_bsearch()

int partition_hash_bsearch ( PartitionBoundInfo  boundinfo,
int  modulus,
int  remainder 
)

Definition at line 3730 of file partbounds.c.

3732{
3733 int lo,
3734 hi,
3735 mid;
3736
3737 lo = -1;
3738 hi = boundinfo->ndatums - 1;
3739 while (lo < hi)
3740 {
3741 int32 cmpval,
3744
3745 mid = (lo + hi + 1) / 2;
3746 bound_modulus = DatumGetInt32(boundinfo->datums[mid][0]);
3747 bound_remainder = DatumGetInt32(boundinfo->datums[mid][1]);
3749 modulus, remainder);
3750 if (cmpval <= 0)
3751 {
3752 lo = mid;
3753
3754 if (cmpval == 0)
3755 break;
3756 }
3757 else
3758 hi = mid - 1;
3759 }
3760
3761 return lo;
3762}

References DatumGetInt32(), PartitionBoundInfoData::datums, fb(), PartitionBoundInfoData::ndatums, partition_hbound_cmp(), and remainder.

Referenced by check_new_partition_bound().

◆ partition_hbound_cmp()

static int32 partition_hbound_cmp ( int  modulus1,
int  remainder1,
int  modulus2,
int  remainder2 
)
static

Definition at line 3579 of file partbounds.c.

3580{
3581 if (modulus1 < modulus2)
3582 return -1;
3583 if (modulus1 > modulus2)
3584 return 1;
3586 return (remainder1 > remainder2) ? 1 : -1;
3587 return 0;
3588}

References fb().

Referenced by partition_hash_bsearch(), and qsort_partition_hbound_cmp().

◆ partition_list_bsearch()

int partition_list_bsearch ( FmgrInfo partsupfunc,
Oid partcollation,
PartitionBoundInfo  boundinfo,
Datum  value,
bool is_equal 
)

Definition at line 3599 of file partbounds.c.

3602{
3603 int lo,
3604 hi,
3605 mid;
3606
3607 lo = -1;
3608 hi = boundinfo->ndatums - 1;
3609 while (lo < hi)
3610 {
3611 int32 cmpval;
3612
3613 mid = (lo + hi + 1) / 2;
3614 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
3615 partcollation[0],
3616 boundinfo->datums[mid][0],
3617 value));
3618 if (cmpval <= 0)
3619 {
3620 lo = mid;
3621 *is_equal = (cmpval == 0);
3622 if (*is_equal)
3623 break;
3624 }
3625 else
3626 hi = mid - 1;
3627 }
3628
3629 return lo;
3630}

References DatumGetInt32(), PartitionBoundInfoData::datums, fb(), FunctionCall2Coll(), PartitionBoundInfoData::ndatums, and value.

Referenced by check_new_partition_bound(), check_partition_bounds_for_split_list(), get_matching_list_bounds(), and get_partition_for_tuple().

◆ partition_range_bsearch()

static int partition_range_bsearch ( int  partnatts,
FmgrInfo partsupfunc,
Oid partcollation,
PartitionBoundInfo  boundinfo,
PartitionRangeBound probe,
int32 cmpval 
)
static

Definition at line 3645 of file partbounds.c.

3649{
3650 int lo,
3651 hi,
3652 mid;
3653
3654 lo = -1;
3655 hi = boundinfo->ndatums - 1;
3656 while (lo < hi)
3657 {
3658 mid = (lo + hi + 1) / 2;
3659 *cmpval = partition_rbound_cmp(partnatts, partsupfunc,
3660 partcollation,
3661 boundinfo->datums[mid],
3662 boundinfo->kind[mid],
3663 (boundinfo->indexes[mid] == -1),
3664 probe);
3665 if (*cmpval <= 0)
3666 {
3667 lo = mid;
3668 if (*cmpval == 0)
3669 break;
3670 }
3671 else
3672 hi = mid - 1;
3673 }
3674
3675 return lo;
3676}

References PartitionBoundInfoData::datums, fb(), PartitionBoundInfoData::indexes, PartitionBoundInfoData::kind, PartitionBoundInfoData::ndatums, and partition_rbound_cmp().

Referenced by check_new_partition_bound().

◆ partition_range_datum_bsearch()

int partition_range_datum_bsearch ( FmgrInfo partsupfunc,
Oid partcollation,
PartitionBoundInfo  boundinfo,
int  nvalues,
const Datum values,
bool is_equal 
)

Definition at line 3687 of file partbounds.c.

3690{
3691 int lo,
3692 hi,
3693 mid;
3694
3695 lo = -1;
3696 hi = boundinfo->ndatums - 1;
3697 while (lo < hi)
3698 {
3699 int32 cmpval;
3700
3701 mid = (lo + hi + 1) / 2;
3702 cmpval = partition_rbound_datum_cmp(partsupfunc,
3703 partcollation,
3704 boundinfo->datums[mid],
3705 boundinfo->kind[mid],
3706 values,
3707 nvalues);
3708 if (cmpval <= 0)
3709 {
3710 lo = mid;
3711 *is_equal = (cmpval == 0);
3712
3713 if (*is_equal)
3714 break;
3715 }
3716 else
3717 hi = mid - 1;
3718 }
3719
3720 return lo;
3721}

References PartitionBoundInfoData::datums, fb(), PartitionBoundInfoData::kind, PartitionBoundInfoData::ndatums, partition_rbound_datum_cmp(), and values.

Referenced by get_matching_range_bounds(), and get_partition_for_tuple().

◆ partition_rbound_cmp()

static int32 partition_rbound_cmp ( int  partnatts,
FmgrInfo partsupfunc,
Oid partcollation,
Datum datums1,
PartitionRangeDatumKind kind1,
bool  lower1,
PartitionRangeBound b2 
)
static

Definition at line 3480 of file partbounds.c.

3484{
3485 int32 colnum = 0;
3486 int32 cmpval = 0; /* placate compiler */
3487 int i;
3488 Datum *datums2 = b2->datums;
3490 bool lower2 = b2->lower;
3491
3492 for (i = 0; i < partnatts; i++)
3493 {
3494 /* Track column number in case we need it for result */
3495 colnum++;
3496
3497 /*
3498 * First, handle cases where the column is unbounded, which should not
3499 * invoke the comparison procedure, and should not consider any later
3500 * columns. Note that the PartitionRangeDatumKind enum elements
3501 * compare the same way as the values they represent.
3502 */
3503 if (kind1[i] < kind2[i])
3504 return -colnum;
3505 else if (kind1[i] > kind2[i])
3506 return colnum;
3507 else if (kind1[i] != PARTITION_RANGE_DATUM_VALUE)
3508 {
3509 /*
3510 * The column bounds are both MINVALUE or both MAXVALUE. No later
3511 * columns should be considered, but we still need to compare
3512 * whether they are upper or lower bounds.
3513 */
3514 break;
3515 }
3516
3517 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[i],
3518 partcollation[i],
3519 datums1[i],
3520 datums2[i]));
3521 if (cmpval != 0)
3522 break;
3523 }
3524
3525 /*
3526 * If the comparison is anything other than equal, we're done. If they
3527 * compare equal though, we still have to consider whether the boundaries
3528 * are inclusive or exclusive. Exclusive one is considered smaller of the
3529 * two.
3530 */
3531 if (cmpval == 0 && lower1 != lower2)
3532 cmpval = lower1 ? 1 : -1;
3533
3534 return cmpval == 0 ? 0 : (cmpval < 0 ? -colnum : colnum);
3535}

References DatumGetInt32(), PartitionRangeBound::datums, fb(), FunctionCall2Coll(), i, and PARTITION_RANGE_DATUM_VALUE.

Referenced by add_merged_range_bounds(), check_new_partition_bound(), check_partition_bounds_for_split_range(), check_two_partitions_bounds_range(), and partition_range_bsearch().

◆ partition_rbound_datum_cmp()

int32 partition_rbound_datum_cmp ( FmgrInfo partsupfunc,
Oid partcollation,
const Datum rb_datums,
PartitionRangeDatumKind rb_kind,
const Datum tuple_datums,
int  n_tuple_datums 
)

Definition at line 3548 of file partbounds.c.

3551{
3552 int i;
3553 int32 cmpval = -1;
3554
3555 for (i = 0; i < n_tuple_datums; i++)
3556 {
3558 return -1;
3560 return 1;
3561
3562 cmpval = DatumGetInt32(FunctionCall2Coll(&partsupfunc[i],
3563 partcollation[i],
3564 rb_datums[i],
3565 tuple_datums[i]));
3566 if (cmpval != 0)
3567 break;
3568 }
3569
3570 return cmpval;
3571}

References DatumGetInt32(), fb(), FunctionCall2Coll(), i, PARTITION_RANGE_DATUM_MAXVALUE, and PARTITION_RANGE_DATUM_MINVALUE.

Referenced by get_matching_range_bounds(), get_partition_for_tuple(), and partition_range_datum_bsearch().

◆ partitions_are_ordered()

bool partitions_are_ordered ( PartitionBoundInfo  boundinfo,
Bitmapset live_parts 
)

Definition at line 2845 of file partbounds.c.

2846{
2847 Assert(boundinfo != NULL);
2848
2849 switch (boundinfo->strategy)
2850 {
2852
2853 /*
2854 * RANGE-type partitioning guarantees that the partitions can be
2855 * scanned in the order that they're defined in the PartitionDesc
2856 * to provide sequential, non-overlapping ranges of tuples.
2857 * However, if a DEFAULT partition exists and it's contained
2858 * within live_parts, then the partitions are not ordered.
2859 */
2860 if (!partition_bound_has_default(boundinfo) ||
2861 !bms_is_member(boundinfo->default_index, live_parts))
2862 return true;
2863 break;
2864
2866
2867 /*
2868 * LIST partitioned are ordered providing none of live_parts
2869 * overlap with the partitioned table's interleaved partitions.
2870 */
2871 if (!bms_overlap(live_parts, boundinfo->interleaved_parts))
2872 return true;
2873
2874 break;
2876 break;
2877 }
2878
2879 return false;
2880}

References Assert, bms_is_member(), bms_overlap(), PartitionBoundInfoData::default_index, fb(), PartitionBoundInfoData::interleaved_parts, partition_bound_has_default, PARTITION_STRATEGY_HASH, PARTITION_STRATEGY_LIST, PARTITION_STRATEGY_RANGE, and PartitionBoundInfoData::strategy.

Referenced by build_partition_pathkeys(), and generate_orderedappend_paths().

◆ partitions_listdatum_intersection()

static List * partitions_listdatum_intersection ( FmgrInfo partsupfunc,
Oid partcollation,
const List list1,
const List list2 
)
static

Definition at line 5204 of file partbounds.c.

5206{
5207 List *result = NIL;
5208
5209 if (list1 == NIL || list2 == NIL)
5210 return result;
5211
5213 {
5214 bool isnull1 = val1->constisnull;
5215
5217 {
5218 if (val2->constisnull)
5219 {
5220 if (isnull1)
5221 {
5222 result = lappend(result, val1);
5223 return result;
5224 }
5225 continue;
5226 }
5227 else if (isnull1)
5228 continue;
5229
5230 /* Compare two datum values. */
5231 if (DatumGetInt32(FunctionCall2Coll(&partsupfunc[0],
5232 partcollation[0],
5233 val1->constvalue,
5234 val2->constvalue)) == 0)
5235 {
5236 result = lappend(result, val1);
5237 return result;
5238 }
5239 }
5240 }
5241
5242 return result;
5243}

References DatumGetInt32(), fb(), foreach_node, FunctionCall2Coll(), lappend(), and NIL.

Referenced by check_partitions_not_overlap_list().

◆ process_inner_partition()

static int process_inner_partition ( PartitionMap outer_map,
PartitionMap inner_map,
bool  outer_has_default,
bool  inner_has_default,
int  inner_index,
int  outer_default,
JoinType  jointype,
int next_index,
int default_index 
)
static

Definition at line 2056 of file partbounds.c.

2065{
2066 int merged_index = -1;
2067
2068 Assert(inner_index >= 0);
2069
2070 /*
2071 * If the outer side has the default partition, a row from the inner
2072 * partition might find its join partner in the default partition; try
2073 * merging the inner partition with the default partition. Otherwise,
2074 * this should be a FULL join, in which case the inner partition has to be
2075 * scanned all the way anyway; merge the inner partition with a dummy
2076 * partition on the other side.
2077 */
2079 {
2080 Assert(outer_default >= 0);
2081
2082 /*
2083 * If the inner side has the default partition as well, the default
2084 * partition on the outer side will have two matching partitions on
2085 * the other side: the inner partition and the default partition on
2086 * the inner side. Partitionwise join doesn't handle this scenario
2087 * yet.
2088 */
2090 return -1;
2091
2094 next_index);
2095 if (merged_index == -1)
2096 return -1;
2097
2098 /*
2099 * If this is an outer join, the default partition on the outer side
2100 * has to be scanned all the way anyway, so the resulting partition
2101 * will contain all key values from the default partition, which any
2102 * other partition of the join relation will not contain. Thus the
2103 * resulting partition will act as the default partition of the join
2104 * relation; record the index in *default_index if not already done.
2105 */
2106 if (IS_OUTER_JOIN(jointype))
2107 {
2108 Assert(jointype != JOIN_RIGHT);
2109 if (*default_index == -1)
2110 *default_index = merged_index;
2111 else
2112 Assert(*default_index == merged_index);
2113 }
2114 }
2115 else
2116 {
2117 Assert(jointype == JOIN_FULL);
2118
2119 /* If we have already assigned a partition, no need to do anything. */
2120 merged_index = inner_map->merged_indexes[inner_index];
2121 if (merged_index == -1)
2123 next_index);
2124 }
2125 return merged_index;
2126}

References Assert, fb(), IS_OUTER_JOIN, JOIN_FULL, JOIN_RIGHT, merge_matching_partitions(), and merge_partition_with_dummy().

Referenced by merge_list_bounds(), and merge_range_bounds().

◆ process_outer_partition()

static int process_outer_partition ( PartitionMap outer_map,
PartitionMap inner_map,
bool  outer_has_default,
bool  inner_has_default,
int  outer_index,
int  inner_default,
JoinType  jointype,
int next_index,
int default_index 
)
static

Definition at line 1974 of file partbounds.c.

1983{
1984 int merged_index = -1;
1985
1986 Assert(outer_index >= 0);
1987
1988 /*
1989 * If the inner side has the default partition, a row from the outer
1990 * partition might find its join partner in the default partition; try
1991 * merging the outer partition with the default partition. Otherwise,
1992 * this should be an outer join, in which case the outer partition has to
1993 * be scanned all the way anyway; merge the outer partition with a dummy
1994 * partition on the other side.
1995 */
1997 {
1998 Assert(inner_default >= 0);
1999
2000 /*
2001 * If the outer side has the default partition as well, the default
2002 * partition on the inner side will have two matching partitions on
2003 * the other side: the outer partition and the default partition on
2004 * the outer side. Partitionwise join doesn't handle this scenario
2005 * yet.
2006 */
2008 return -1;
2009
2012 next_index);
2013 if (merged_index == -1)
2014 return -1;
2015
2016 /*
2017 * If this is a FULL join, the default partition on the inner side has
2018 * to be scanned all the way anyway, so the resulting partition will
2019 * contain all key values from the default partition, which any other
2020 * partition of the join relation will not contain. Thus the
2021 * resulting partition will act as the default partition of the join
2022 * relation; record the index in *default_index if not already done.
2023 */
2024 if (jointype == JOIN_FULL)
2025 {
2026 if (*default_index == -1)
2027 *default_index = merged_index;
2028 else
2029 Assert(*default_index == merged_index);
2030 }
2031 }
2032 else
2033 {
2034 Assert(IS_OUTER_JOIN(jointype));
2035 Assert(jointype != JOIN_RIGHT);
2036
2037 /* If we have already assigned a partition, no need to do anything. */
2038 merged_index = outer_map->merged_indexes[outer_index];
2039 if (merged_index == -1)
2041 next_index);
2042 }
2043 return merged_index;
2044}

References Assert, fb(), IS_OUTER_JOIN, JOIN_FULL, JOIN_RIGHT, merge_matching_partitions(), and merge_partition_with_dummy().

Referenced by merge_list_bounds(), and merge_range_bounds().

◆ qsort_partition_hbound_cmp()

static int32 qsort_partition_hbound_cmp ( const void a,
const void b 
)
static

Definition at line 3770 of file partbounds.c.

3771{
3772 const PartitionHashBound *h1 = (const PartitionHashBound *) a;
3773 const PartitionHashBound *h2 = (const PartitionHashBound *) b;
3774
3775 return partition_hbound_cmp(h1->modulus, h1->remainder,
3776 h2->modulus, h2->remainder);
3777}

References a, b, fb(), and partition_hbound_cmp().

Referenced by create_hash_bounds().

◆ qsort_partition_list_value_cmp()

static int32 qsort_partition_list_value_cmp ( const void a,
const void b,
void arg 
)
static

Definition at line 3785 of file partbounds.c.

3786{
3787 Datum val1 = ((const PartitionListValue *) a)->value,
3788 val2 = ((const PartitionListValue *) b)->value;
3790
3791 return DatumGetInt32(FunctionCall2Coll(&key->partsupfunc[0],
3792 key->partcollation[0],
3793 val1, val2));
3794}

References a, arg, b, DatumGetInt32(), fb(), and FunctionCall2Coll().

Referenced by create_list_bounds().

◆ qsort_partition_rbound_cmp()

static int32 qsort_partition_rbound_cmp ( const void a,
const void b,
void arg 
)
static

Definition at line 3802 of file partbounds.c.

3803{
3807
3808 return compare_range_bounds(key->partnatts, key->partsupfunc,
3809 key->partcollation,
3810 b1, b2);
3811}

References a, arg, b, compare_range_bounds, and fb().

Referenced by calculate_partition_bound_for_merge(), check_partitions_for_split(), and create_range_bounds().

◆ satisfies_hash_partition()

Datum satisfies_hash_partition ( PG_FUNCTION_ARGS  )

Definition at line 4763 of file partbounds.c.

4764{
4765 typedef struct ColumnsHashData
4766 {
4767 Oid relid;
4768 int nkeys;
4771 bool variadic_typbyval;
4772 char variadic_typalign;
4774 FmgrInfo partsupfunc[FLEXIBLE_ARRAY_MEMBER];
4776 Oid parentId;
4777 int modulus;
4778 int remainder;
4781 uint64 rowHash = 0;
4782
4783 /* Return false if the parent OID, modulus, or remainder is NULL. */
4784 if (PG_ARGISNULL(0) || PG_ARGISNULL(1) || PG_ARGISNULL(2))
4785 PG_RETURN_BOOL(false);
4787 modulus = PG_GETARG_INT32(1);
4789
4790 /* Sanity check modulus and remainder. */
4791 if (modulus <= 0)
4792 ereport(ERROR,
4794 errmsg("modulus for hash partition must be an integer value greater than zero")));
4795 if (remainder < 0)
4796 ereport(ERROR,
4798 errmsg("remainder for hash partition must be an integer value greater than or equal to zero")));
4799 if (remainder >= modulus)
4800 ereport(ERROR,
4802 errmsg("remainder for hash partition must be less than modulus")));
4803
4804 /*
4805 * Cache hash function information.
4806 */
4807 my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
4808 if (my_extra == NULL || my_extra->relid != parentId)
4809 {
4810 Relation parent;
4812 int j;
4813
4814 /* Open parent relation and fetch partition key info */
4816 key = RelationGetPartitionKey(parent);
4817
4818 /* Reject parent table that is not hash-partitioned. */
4819 if (key == NULL || key->strategy != PARTITION_STRATEGY_HASH)
4820 ereport(ERROR,
4822 errmsg("\"%s\" is not a hash partitioned table",
4824
4825 if (!get_fn_expr_variadic(fcinfo->flinfo))
4826 {
4827 int nargs = PG_NARGS() - 3;
4828
4829 /* complain if wrong number of column values */
4830 if (key->partnatts != nargs)
4831 ereport(ERROR,
4833 errmsg("number of partitioning columns (%d) does not match number of partition keys provided (%d)",
4834 key->partnatts, nargs)));
4835
4836 /* allocate space for our cache */
4837 fcinfo->flinfo->fn_extra =
4838 MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
4839 offsetof(ColumnsHashData, partsupfunc) +
4840 sizeof(FmgrInfo) * nargs);
4841 my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
4842 my_extra->relid = parentId;
4843 my_extra->nkeys = key->partnatts;
4844 memcpy(my_extra->partcollid, key->partcollation,
4845 key->partnatts * sizeof(Oid));
4846
4847 /* check argument types and save fmgr_infos */
4848 for (j = 0; j < key->partnatts; ++j)
4849 {
4850 Oid argtype = get_fn_expr_argtype(fcinfo->flinfo, j + 3);
4851
4852 if (argtype != key->parttypid[j] && !IsBinaryCoercible(argtype, key->parttypid[j]))
4853 ereport(ERROR,
4855 errmsg("column %d of the partition key has type %s, but supplied value is of type %s",
4856 j + 1, format_type_be(key->parttypid[j]), format_type_be(argtype))));
4857
4858 fmgr_info_copy(&my_extra->partsupfunc[j],
4859 &key->partsupfunc[j],
4860 fcinfo->flinfo->fn_mcxt);
4861 }
4862 }
4863 else
4864 {
4866
4867 /* allocate space for our cache -- just one FmgrInfo in this case */
4868 fcinfo->flinfo->fn_extra =
4869 MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
4870 offsetof(ColumnsHashData, partsupfunc) +
4871 sizeof(FmgrInfo));
4872 my_extra = (ColumnsHashData *) fcinfo->flinfo->fn_extra;
4873 my_extra->relid = parentId;
4874 my_extra->nkeys = key->partnatts;
4875 my_extra->variadic_type = ARR_ELEMTYPE(variadic_array);
4876 get_typlenbyvalalign(my_extra->variadic_type,
4877 &my_extra->variadic_typlen,
4878 &my_extra->variadic_typbyval,
4879 &my_extra->variadic_typalign);
4880 my_extra->partcollid[0] = key->partcollation[0];
4881
4882 /* check argument types */
4883 for (j = 0; j < key->partnatts; ++j)
4884 if (key->parttypid[j] != my_extra->variadic_type)
4885 ereport(ERROR,
4887 errmsg("column %d of the partition key has type \"%s\", but supplied value is of type \"%s\"",
4888 j + 1,
4889 format_type_be(key->parttypid[j]),
4890 format_type_be(my_extra->variadic_type))));
4891
4892 fmgr_info_copy(&my_extra->partsupfunc[0],
4893 &key->partsupfunc[0],
4894 fcinfo->flinfo->fn_mcxt);
4895 }
4896
4897 /* Hold lock until commit */
4898 relation_close(parent, NoLock);
4899 }
4900
4901 if (!OidIsValid(my_extra->variadic_type))
4902 {
4903 int nkeys = my_extra->nkeys;
4904 int i;
4905
4906 /*
4907 * For a non-variadic call, neither the number of arguments nor their
4908 * types can change across calls, so avoid the expense of rechecking
4909 * here.
4910 */
4911
4912 for (i = 0; i < nkeys; i++)
4913 {
4914 Datum hash;
4915
4916 /* keys start from fourth argument of function. */
4917 int argno = i + 3;
4918
4919 if (PG_ARGISNULL(argno))
4920 continue;
4921
4922 hash = FunctionCall2Coll(&my_extra->partsupfunc[i],
4923 my_extra->partcollid[i],
4925 seed);
4926
4927 /* Form a single 64-bit hash value */
4929 }
4930 }
4931 else
4932 {
4934 int i;
4935 int nelems;
4936 Datum *datum;
4937 bool *isnull;
4938
4940 my_extra->variadic_type,
4941 my_extra->variadic_typlen,
4942 my_extra->variadic_typbyval,
4943 my_extra->variadic_typalign,
4944 &datum, &isnull, &nelems);
4945
4946 /* complain if wrong number of column values */
4947 if (nelems != my_extra->nkeys)
4948 ereport(ERROR,
4950 errmsg("number of partitioning columns (%d) does not match number of partition keys provided (%d)",
4951 my_extra->nkeys, nelems)));
4952
4953 for (i = 0; i < nelems; i++)
4954 {
4955 Datum hash;
4956
4957 if (isnull[i])
4958 continue;
4959
4960 hash = FunctionCall2Coll(&my_extra->partsupfunc[0],
4961 my_extra->partcollid[0],
4962 datum[i],
4963 seed);
4964
4965 /* Form a single 64-bit hash value */
4967 }
4968 }
4969
4970 PG_RETURN_BOOL(rowHash % modulus == remainder);
4971}

References AccessShareLock, ARR_ELEMTYPE, DatumGetUInt64(), deconstruct_array(), ereport, errcode(), errmsg(), ERROR, fb(), FLEXIBLE_ARRAY_MEMBER, fmgr_info_copy(), format_type_be(), FunctionCall2Coll(), get_fn_expr_argtype(), get_fn_expr_variadic(), get_rel_name(), get_typlenbyvalalign(), hash(), hash_combine64(), HASH_PARTITION_SEED, i, IsBinaryCoercible(), j, MemoryContextAllocZero(), NoLock, OidIsValid, PARTITION_MAX_KEYS, PARTITION_STRATEGY_HASH, PG_ARGISNULL, PG_GETARG_ARRAYTYPE_P, PG_GETARG_DATUM, PG_GETARG_INT32, PG_GETARG_OID, PG_NARGS, PG_RETURN_BOOL, relation_close(), relation_open(), RelationGetPartitionKey(), remainder, and UInt64GetDatum().