-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathpl_range_funcs.c
1407 lines (1148 loc) · 36.4 KB
/
pl_range_funcs.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ------------------------------------------------------------------------
*
* pl_range_funcs.c
* Utility C functions for stored RANGE procedures
*
* Copyright (c) 2016-2020, Postgres Professional
*
* ------------------------------------------------------------------------
*/
#include "init.h"
#include "pathman.h"
#include "partition_creation.h"
#include "relation_info.h"
#include "utils.h"
#include "xact_handling.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "access/transam.h"
#include "access/xact.h"
#include "catalog/heap.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "commands/tablecmds.h"
#include "executor/spi.h"
#include "nodes/nodeFuncs.h"
#include "parser/parse_relation.h"
#include "parser/parse_expr.h"
#include "utils/array.h"
#if PG_VERSION_NUM >= 120000
#include "utils/float.h"
#endif
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/numeric.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "utils/snapmgr.h"
#if PG_VERSION_NUM < 110000
#include "catalog/pg_inherits_fn.h"
#endif
#if PG_VERSION_NUM >= 100000
#include "utils/regproc.h"
#include "utils/varlena.h"
#include <math.h>
#endif
/* Function declarations */
PG_FUNCTION_INFO_V1( create_single_range_partition_pl );
PG_FUNCTION_INFO_V1( create_range_partitions_internal );
PG_FUNCTION_INFO_V1( check_range_available_pl );
PG_FUNCTION_INFO_V1( generate_range_bounds_pl );
PG_FUNCTION_INFO_V1( validate_interval_value );
PG_FUNCTION_INFO_V1( split_range_partition );
PG_FUNCTION_INFO_V1( merge_range_partitions );
PG_FUNCTION_INFO_V1( drop_range_partition_expand_next );
PG_FUNCTION_INFO_V1( get_part_range_by_oid );
PG_FUNCTION_INFO_V1( get_part_range_by_idx );
PG_FUNCTION_INFO_V1( build_range_condition );
PG_FUNCTION_INFO_V1( build_sequence_name );
static ArrayType *construct_bounds_array(Bound *elems,
int nelems,
Oid elmtype,
int elmlen,
bool elmbyval,
char elmalign);
static char *deparse_constraint(Oid relid, Node *expr);
static void modify_range_constraint(Oid partition_relid,
const char *expression,
Oid expression_type,
const Bound *lower,
const Bound *upper);
static bool interval_is_trivial(Oid atttype,
Datum interval,
Oid interval_type);
/*
* -----------------------------
* Partition creation & checks
* -----------------------------
*/
/* pl/PgSQL wrapper for the create_single_range_partition(). */
Datum
create_single_range_partition_pl(PG_FUNCTION_ARGS)
{
Oid parent_relid,
partition_relid;
/* RANGE boundaries + value type */
Bound start,
end;
Oid bounds_type;
/* Optional: name & tablespace */
RangeVar *partition_name_rv;
char *tablespace;
Datum values[Natts_pathman_config];
bool isnull[Natts_pathman_config];
/* Handle 'parent_relid' */
if (!PG_ARGISNULL(0))
{
parent_relid = PG_GETARG_OID(0);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'parent_relid' should not be NULL")));
/* Check that table is partitioned by RANGE */
if (!pathman_config_contains_relation(parent_relid, values, isnull, NULL, NULL) ||
DatumGetPartType(values[Anum_pathman_config_parttype - 1]) != PT_RANGE)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("table \"%s\" is not partitioned by RANGE",
get_rel_name_or_relid(parent_relid))));
}
bounds_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
start = PG_ARGISNULL(1) ?
MakeBoundInf(MINUS_INFINITY) :
MakeBound(PG_GETARG_DATUM(1));
end = PG_ARGISNULL(2) ?
MakeBoundInf(PLUS_INFINITY) :
MakeBound(PG_GETARG_DATUM(2));
/* Fetch 'partition_name' */
if (!PG_ARGISNULL(3))
{
List *qualified_name;
text *partition_name;
partition_name = PG_GETARG_TEXT_P(3);
qualified_name = textToQualifiedNameList(partition_name);
partition_name_rv = makeRangeVarFromNameList(qualified_name);
}
else partition_name_rv = NULL; /* default */
/* Fetch 'tablespace' */
if (!PG_ARGISNULL(4))
{
tablespace = TextDatumGetCString(PG_GETARG_DATUM(4));
}
else tablespace = NULL; /* default */
/* Create a new RANGE partition and return its Oid */
partition_relid = create_single_range_partition_internal(parent_relid,
&start,
&end,
bounds_type,
partition_name_rv,
tablespace);
PG_RETURN_OID(partition_relid);
}
Datum
create_range_partitions_internal(PG_FUNCTION_ARGS)
{
Oid parent_relid;
int16 typlen;
bool typbyval;
char typalign;
FmgrInfo cmp_func;
/* Partition names and tablespaces */
char **partnames = NULL;
RangeVar **rangevars = NULL;
char **tablespaces = NULL;
int npartnames = 0;
int ntablespaces = 0;
/* Bounds */
ArrayType *bounds;
Oid bounds_type;
Datum *datums;
bool *nulls;
int ndatums;
int i;
/* Extract parent's Oid */
if (!PG_ARGISNULL(0))
{
parent_relid = PG_GETARG_OID(0);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'parent_relid' should not be NULL")));
/* Extract array of bounds */
if (!PG_ARGISNULL(1))
{
bounds = PG_GETARG_ARRAYTYPE_P(1);
bounds_type = ARR_ELEMTYPE(bounds);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'bounds' should not be NULL")));
/* Extract partition names */
if (!PG_ARGISNULL(2))
{
partnames = deconstruct_text_array(PG_GETARG_DATUM(2), &npartnames);
rangevars = qualified_relnames_to_rangevars(partnames, npartnames);
}
/* Extract partition tablespaces */
if (!PG_ARGISNULL(3))
tablespaces = deconstruct_text_array(PG_GETARG_DATUM(3), &ntablespaces);
/* Extract bounds */
get_typlenbyvalalign(bounds_type, &typlen, &typbyval, &typalign);
deconstruct_array(bounds, bounds_type,
typlen, typbyval, typalign,
&datums, &nulls, &ndatums);
if (partnames && npartnames != ndatums - 1)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("wrong length of 'partition_names' array"),
errdetail("number of 'partition_names' must be less than "
"'bounds' array length by one")));
if (tablespaces && ntablespaces != ndatums - 1)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("wrong length of 'tablespaces' array"),
errdetail("number of 'tablespaces' must be less than "
"'bounds' array length by one")));
/* Check if bounds array is ascending */
fill_type_cmp_fmgr_info(&cmp_func,
getBaseType(bounds_type),
getBaseType(bounds_type));
/* Validate bounds */
for (i = 0; i < ndatums; i++)
{
/* Disregard 1st bound */
if (i == 0) continue;
/* Check that bound is valid */
if (nulls[i])
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("only first bound can be NULL")));
/* Check that bounds are ascending */
if (!nulls[i - 1] && !check_le(&cmp_func, InvalidOid,
datums[i - 1], datums[i]))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'bounds' array must be ascending")));
}
/* Create partitions using provided bounds */
for (i = 0; i < ndatums - 1; i++)
{
Bound start = nulls[i] ?
MakeBoundInf(MINUS_INFINITY) :
MakeBound(datums[i]),
end = nulls[i + 1] ?
MakeBoundInf(PLUS_INFINITY) :
MakeBound(datums[i + 1]);
RangeVar *name = rangevars ? rangevars[i] : NULL;
char *tablespace = tablespaces ? tablespaces[i] : NULL;
(void) create_single_range_partition_internal(parent_relid,
&start,
&end,
bounds_type,
name,
tablespace);
}
/* Return number of partitions */
PG_RETURN_INT32(ndatums - 1);
}
/* Checks if range overlaps with existing partitions. */
Datum
check_range_available_pl(PG_FUNCTION_ARGS)
{
Oid parent_relid;
Bound start,
end;
Oid value_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
if (PG_ARGISNULL(0))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'parent_relid' should not be NULL")));
parent_relid = PG_GETARG_OID(0);
start = PG_ARGISNULL(1) ?
MakeBoundInf(MINUS_INFINITY) :
MakeBound(PG_GETARG_DATUM(1));
end = PG_ARGISNULL(2) ?
MakeBoundInf(PLUS_INFINITY) :
MakeBound(PG_GETARG_DATUM(2));
/* Raise ERROR if range overlaps with any partition */
check_range_available(parent_relid,
&start,
&end,
value_type,
true);
PG_RETURN_VOID();
}
/* Generate range bounds starting with 'value' using 'interval'. */
Datum
generate_range_bounds_pl(PG_FUNCTION_ARGS)
{
/* Input params */
Datum value = PG_GETARG_DATUM(0);
Oid value_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
Datum interval = PG_GETARG_DATUM(1);
Oid interval_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
int count = PG_GETARG_INT32(2);
int i;
/* Operator */
Oid plus_op_func;
Datum plus_op_result;
Oid plus_op_result_type;
/* Array */
ArrayType *array;
int16 elemlen;
bool elembyval;
char elemalign;
Datum *datums;
Assert(!PG_ARGISNULL(0));
Assert(!PG_ARGISNULL(1));
Assert(!PG_ARGISNULL(2));
if (count < 1)
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'p_count' must be greater than zero")));
/* We must provide count+1 bounds */
count += 1;
/* Find suitable addition operator for given value and interval */
extract_op_func_and_ret_type("+", value_type, interval_type,
&plus_op_func,
&plus_op_result_type);
/* Fetch type's information for array */
get_typlenbyvalalign(value_type, &elemlen, &elembyval, &elemalign);
datums = palloc(sizeof(Datum) * count);
datums[0] = value;
/* Calculate bounds */
for (i = 1; i < count; i++)
{
/* Invoke addition operator and get a result */
plus_op_result = OidFunctionCall2(plus_op_func, value, interval);
/* Cast result to 'value_type' if needed */
if (plus_op_result_type != value_type)
plus_op_result = perform_type_cast(plus_op_result,
plus_op_result_type,
value_type, NULL);
/* Update 'value' and store current bound */
value = datums[i] = plus_op_result;
}
/* build an array based on calculated datums */
array = construct_array(datums, count, value_type,
elemlen, elembyval, elemalign);
pfree(datums);
PG_RETURN_ARRAYTYPE_P(array);
}
/*
* Takes text representation of interval value and checks
* if it corresponds to partitioning expression.
* NOTE: throws an ERROR if it fails to convert text to Datum.
*/
Datum
validate_interval_value(PG_FUNCTION_ARGS)
{
#define ARG_PARTREL 0
#define ARG_EXPRESSION 1
#define ARG_PARTTYPE 2
#define ARG_RANGE_INTERVAL 3
Oid partrel;
PartType parttype;
char *expr_cstr;
Oid expr_type;
if (PG_ARGISNULL(ARG_PARTREL))
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'partrel' should not be NULL")));
}
else partrel = PG_GETARG_OID(ARG_PARTREL);
/* Check that relation exists */
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(partrel)))
elog(ERROR, "relation \"%u\" does not exist", partrel);
if (PG_ARGISNULL(ARG_EXPRESSION))
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'expression' should not be NULL")));
}
else expr_cstr = TextDatumGetCString(PG_GETARG_DATUM(ARG_EXPRESSION));
if (PG_ARGISNULL(ARG_PARTTYPE))
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'parttype' should not be NULL")));
}
else parttype = DatumGetPartType(PG_GETARG_DATUM(ARG_PARTTYPE));
/*
* Try to parse partitioning expression, could fail with ERROR.
*/
cook_partitioning_expression(partrel, expr_cstr, &expr_type);
/*
* NULL interval is fine for both HASH and RANGE.
* But for RANGE we need to make some additional checks.
*/
if (!PG_ARGISNULL(ARG_RANGE_INTERVAL))
{
Datum interval_text = PG_GETARG_DATUM(ARG_RANGE_INTERVAL),
interval_value;
Oid interval_type;
if (parttype == PT_HASH)
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("interval should be NULL for HASH partitioned table")));
/* Try converting textual representation */
interval_value = extract_binary_interval_from_text(interval_text,
expr_type,
&interval_type);
/* Check that interval isn't trivial */
if (interval_is_trivial(expr_type, interval_value, interval_type))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("interval should not be trivial")));
}
PG_RETURN_BOOL(true);
}
Datum
split_range_partition(PG_FUNCTION_ARGS)
{
Oid parent = InvalidOid,
partition1,
partition2;
RangeVar *part_name = NULL;
char *tablespace_name = NULL;
Datum pivot_value;
Oid pivot_type;
PartRelationInfo *prel;
Bound min_bound,
max_bound,
split_bound;
Snapshot fresh_snapshot;
FmgrInfo finfo;
SPIPlanPtr plan;
char *query;
int i;
if (!PG_ARGISNULL(0))
{
partition1 = PG_GETARG_OID(0);
check_relation_oid(partition1);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'partition1' should not be NULL")));
if (!PG_ARGISNULL(1))
{
pivot_value = PG_GETARG_DATUM(1);
pivot_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'split_value' should not be NULL")));
LockRelationOid(partition1, ExclusiveLock);
/* Get parent of partition */
parent = get_parent_of_partition(partition1);
if (!OidIsValid(parent))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%s\" is not a partition",
get_rel_name_or_relid(partition1))));
/* This partition should not have children */
if (has_pathman_relation_info(partition1))
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot split partition that has children")));
/* Prevent changes in partitioning scheme */
LockRelationOid(parent, ShareUpdateExclusiveLock);
/* Emit an error if it is not partitioned by RANGE */
prel = get_pathman_relation_info(parent);
shout_if_prel_is_invalid(parent, prel, PT_RANGE);
i = PrelHasPartition(prel, partition1) - 1;
Assert(i >= 0 && i < PrelChildrenCount(prel));
min_bound = PrelGetRangesArray(prel)[i].min;
max_bound = PrelGetRangesArray(prel)[i].max;
split_bound = MakeBound(perform_type_cast(pivot_value,
getBaseType(pivot_type),
getBaseType(prel->ev_type),
NULL));
fmgr_info(prel->cmp_proc, &finfo);
/* Validate pivot's value */
if (cmp_bounds(&finfo, prel->ev_collid, &split_bound, &min_bound) <= 0 ||
cmp_bounds(&finfo, prel->ev_collid, &split_bound, &max_bound) >= 0)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("specified value does not fit into the range (%s, %s)",
BoundToCString(&min_bound, prel->ev_type),
BoundToCString(&max_bound, prel->ev_type))));
}
if (!PG_ARGISNULL(2))
{
part_name = makeRangeVar(get_namespace_name(get_rel_namespace(parent)),
TextDatumGetCString(PG_GETARG_DATUM(2)),
0);
}
if (!PG_ARGISNULL(3))
{
tablespace_name = TextDatumGetCString(PG_GETARG_DATUM(3));
}
/* Create a new partition */
partition2 = create_single_range_partition_internal(parent,
&split_bound,
&max_bound,
prel->ev_type,
part_name,
tablespace_name);
/* Make constraint visible */
CommandCounterIncrement();
if (SPI_connect() != SPI_OK_CONNECT)
elog(ERROR, "could not connect using SPI");
/*
* Get latest snapshot to see data that might have been
* added to partitions before this transaction has started,
* but was committed a moment before we acquired the locks.
*/
fresh_snapshot = RegisterSnapshot(GetLatestSnapshot());
query = psprintf("WITH part_data AS ( "
"DELETE FROM %1$s WHERE (%3$s) >= $1 RETURNING "
"*) "
"INSERT INTO %2$s SELECT * FROM part_data",
get_qualified_rel_name(partition1),
get_qualified_rel_name(partition2),
prel->expr_cstr);
plan = SPI_prepare(query, 1, &prel->ev_type);
if (!plan)
elog(ERROR, "%s: SPI_prepare returned %d",
__FUNCTION__, SPI_result);
SPI_execute_snapshot(plan,
&split_bound.value, NULL,
fresh_snapshot,
InvalidSnapshot,
false, true, 0);
/* Free snapshot */
UnregisterSnapshot(fresh_snapshot);
SPI_finish();
/* Drop old constraint and create a new one */
modify_range_constraint(partition1,
prel->expr_cstr,
prel->ev_type,
&min_bound,
&split_bound);
/* Make constraint visible */
CommandCounterIncrement();
/* Don't forget to close 'prel'! */
close_pathman_relation_info(prel);
PG_RETURN_OID(partition2);
}
/*
* Merge multiple partitions.
* All data will be copied to the first one.
* The rest of partitions will be dropped.
*/
Datum
merge_range_partitions(PG_FUNCTION_ARGS)
{
Oid parent = InvalidOid,
partition = InvalidOid;
ArrayType *arr = PG_GETARG_ARRAYTYPE_P(0);
Oid *parts;
int nparts;
Datum *datums;
bool *nulls;
int16 typlen;
bool typbyval;
char typalign;
PartRelationInfo *prel;
Bound min_bound,
max_bound;
RangeEntry *bounds;
ObjectAddresses *objects = new_object_addresses();
Snapshot fresh_snapshot;
FmgrInfo finfo;
int i;
/* Validate array type */
Assert(ARR_ELEMTYPE(arr) == REGCLASSOID);
/* Extract Oids */
get_typlenbyvalalign(REGCLASSOID, &typlen, &typbyval, &typalign);
deconstruct_array(arr, REGCLASSOID,
typlen, typbyval, typalign,
&datums, &nulls, &nparts);
if (nparts < 2)
ereport(ERROR, (errmsg("cannot merge partitions"),
errdetail("there must be at least two partitions")));
/* Allocate arrays */
parts = palloc(nparts * sizeof(Oid));
bounds = palloc(nparts * sizeof(RangeEntry));
for (i = 0; i < nparts; i++)
{
Oid cur_parent;
/* Extract partition Oids from array */
parts[i] = DatumGetObjectId(datums[i]);
/* Check if all partitions are from the same parent */
cur_parent = get_parent_of_partition(parts[i]);
/* If we couldn't find a parent, it's not a partition */
if (!OidIsValid(cur_parent))
ereport(ERROR, (errmsg("cannot merge partitions"),
errdetail("relation \"%s\" is not a partition",
get_rel_name_or_relid(parts[i]))));
/* 'parent' is not initialized */
if (parent == InvalidOid)
parent = cur_parent; /* save parent */
/* Oops, parent mismatch! */
if (cur_parent != parent)
ereport(ERROR, (errmsg("cannot merge partitions"),
errdetail("all relations must share the same parent")));
}
/* Prevent changes in partitioning scheme */
LockRelationOid(parent, ShareUpdateExclusiveLock);
/* Prevent modification of partitions */
for (i = 0; i < nparts; i++)
LockRelationOid(parts[i], AccessExclusiveLock);
/* Emit an error if it is not partitioned by RANGE */
prel = get_pathman_relation_info(parent);
shout_if_prel_is_invalid(parent, prel, PT_RANGE);
/* Copy rentries from 'prel' */
for (i = 0; i < nparts; i++)
{
uint32 idx = PrelHasPartition(prel, parts[i]);
Assert(idx > 0);
bounds[i] = PrelGetRangesArray(prel)[idx - 1];
}
/* Sort rentries by increasing bound */
qsort_range_entries(bounds, nparts, prel);
fmgr_info(prel->cmp_proc, &finfo);
/* Check that partitions are adjacent */
for (i = 1; i < nparts; i++)
{
Bound cur_min = bounds[i].min,
prev_max = bounds[i - 1].max;
if (cmp_bounds(&finfo, prel->ev_collid, &cur_min, &prev_max) != 0)
{
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("partitions \"%s\" and \"%s\" are not adjacent",
get_rel_name(bounds[i - 1].child_oid),
get_rel_name(bounds[i].child_oid))));
}
}
/* First determine the bounds of a new constraint */
min_bound = bounds[0].min;
max_bound = bounds[nparts - 1].max;
partition = parts[0];
/* Drop old constraint and create a new one */
modify_range_constraint(partition,
prel->expr_cstr,
prel->ev_type,
&min_bound,
&max_bound);
/* Make constraint visible */
CommandCounterIncrement();
if (SPI_connect() != SPI_OK_CONNECT)
elog(ERROR, "could not connect using SPI");
/*
* Get latest snapshot to see data that might have been
* added to partitions before this transaction has started,
* but was committed a moment before we acquired the locks.
*/
fresh_snapshot = RegisterSnapshot(GetLatestSnapshot());
/* Migrate the data from all partition to the first one */
for (i = 1; i < nparts; i++)
{
ObjectAddress object;
char *query = psprintf("WITH part_data AS ( "
"DELETE FROM %1$s RETURNING "
"*) "
"INSERT INTO %2$s SELECT * FROM part_data",
get_qualified_rel_name(parts[i]),
get_qualified_rel_name(parts[0]));
SPIPlanPtr plan = SPI_prepare(query, 0, NULL);
if (!plan)
elog(ERROR, "%s: SPI_prepare returned %d",
__FUNCTION__, SPI_result);
SPI_execute_snapshot(plan, NULL, NULL,
fresh_snapshot,
InvalidSnapshot,
false, true, 0);
pfree(query);
/* To be deleted */
ObjectAddressSet(object, RelationRelationId, parts[i]);
add_exact_object_address(&object, objects);
}
/* Free snapshot */
UnregisterSnapshot(fresh_snapshot);
SPI_finish();
/* Drop obsolete partitions */
performMultipleDeletions(objects, DROP_CASCADE, 0);
free_object_addresses(objects);
pfree(bounds);
pfree(parts);
/* Don't forget to close 'prel'! */
close_pathman_relation_info(prel);
PG_RETURN_OID(partition);
}
/*
* Drops partition and expands the next partition
* so that it could cover the dropped one.
*
* This function was written in order to support
* Oracle-like ALTER TABLE ... DROP PARTITION.
*
* In Oracle partitions only have upper bound and when partition
* is dropped the next one automatically covers freed range.
*/
Datum
drop_range_partition_expand_next(PG_FUNCTION_ARGS)
{
Oid partition = PG_GETARG_OID(0),
parent;
PartRelationInfo *prel;
ObjectAddress object;
RangeEntry *ranges;
int i;
check_relation_oid(partition);
/* Lock the partition we're going to drop */
LockRelationOid(partition, AccessExclusiveLock);
/* Get parent's relid */
parent = get_parent_of_partition(partition);
if (!OidIsValid(parent))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%s\" is not a partition",
get_rel_name_or_relid(partition))));
/* Prevent changes in partitioning scheme */
LockRelationOid(parent, ShareUpdateExclusiveLock);
/* Emit an error if it is not partitioned by RANGE */
prel = get_pathman_relation_info(parent);
shout_if_prel_is_invalid(parent, prel, PT_RANGE);
/* Fetch ranges array */
ranges = PrelGetRangesArray(prel);
/* Looking for partition in child relations */
i = PrelHasPartition(prel, partition) - 1;
Assert(i >= 0 && i < PrelChildrenCount(prel));
/* Expand next partition if it exists */
if (i < PrelLastChild(prel))
{
RangeEntry *cur = &ranges[i],
*next = &ranges[i + 1];
Oid next_partition = next->child_oid;
LOCKMODE lockmode = AccessExclusiveLock;
/* Lock next partition */
LockRelationOid(next_partition, lockmode);
/* Does next partition exist? */
if (SearchSysCacheExists1(RELOID, ObjectIdGetDatum(next_partition)))
{
/* Stretch next partition to cover range */
modify_range_constraint(next_partition,
prel->expr_cstr,
prel->ev_type,
&cur->min,
&next->max);
}
/* Bad luck, unlock missing partition */
else UnlockRelationOid(next_partition, lockmode);
}
/* Drop partition */
ObjectAddressSet(object, RelationRelationId, partition);
performDeletion(&object, DROP_CASCADE, 0);
/* Don't forget to close 'prel'! */
close_pathman_relation_info(prel);
PG_RETURN_VOID();
}
/*
* ------------------------
* Various useful getters
* ------------------------
*/
/*
* Returns range entry (min, max) (in form of array).
*
* arg #1 is the parent's Oid.
* arg #2 is the partition's Oid.
*/
Datum
get_part_range_by_oid(PG_FUNCTION_ARGS)
{
Oid partition_relid,
parent_relid;
Oid arg_type;
RangeEntry *ranges;
PartRelationInfo *prel;
uint32 idx;
if (!PG_ARGISNULL(0))
{
partition_relid = PG_GETARG_OID(0);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'partition_relid' should not be NULL")));
parent_relid = get_parent_of_partition(partition_relid);
if (!OidIsValid(parent_relid))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%s\" is not a partition",
get_rel_name_or_relid(partition_relid))));
/* Emit an error if it is not partitioned by RANGE */
prel = get_pathman_relation_info(parent_relid);
shout_if_prel_is_invalid(parent_relid, prel, PT_RANGE);
/* Check type of 'dummy' (for correct output) */
arg_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
if (getBaseType(arg_type) != getBaseType(prel->ev_type))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("pg_typeof(dummy) should be %s",
format_type_be(getBaseType(prel->ev_type)))));
ranges = PrelGetRangesArray(prel);
/* Look for the specified partition */
if ((idx = PrelHasPartition(prel, partition_relid)) > 0)
{
ArrayType *arr;
Bound elems[2];
elems[0] = ranges[idx - 1].min;
elems[1] = ranges[idx - 1].max;
arr = construct_bounds_array(elems, 2,
prel->ev_type,
prel->ev_len,
prel->ev_byval,
prel->ev_align);
/* Don't forget to close 'prel'! */
close_pathman_relation_info(prel);
PG_RETURN_ARRAYTYPE_P(arr);
}
/* No partition found, report error */
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%s\" has no partition \"%s\"",
get_rel_name_or_relid(parent_relid),
get_rel_name_or_relid(partition_relid))));
PG_RETURN_NULL(); /* keep compiler happy */
}
/*
* Returns N-th range entry (min, max) (in form of array).
*
* arg #1 is the parent's Oid.
* arg #2 is the index of the range
* (if it is negative then the last range will be returned).
*/
Datum
get_part_range_by_idx(PG_FUNCTION_ARGS)
{
Oid parent_relid;
int partition_idx = 0;
Oid arg_type;
Bound elems[2];
RangeEntry *ranges;
PartRelationInfo *prel;
ArrayType *arr;
if (!PG_ARGISNULL(0))
{
parent_relid = PG_GETARG_OID(0);
}