-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathpl_funcs.c
1259 lines (1011 loc) · 32 KB
/
pl_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_funcs.c
* Utility C functions for stored procedures
*
* Copyright (c) 2015-2020, Postgres Professional
*
* ------------------------------------------------------------------------
*/
#include "compat/pg_compat.h"
#include "init.h"
#include "pathman.h"
#include "partition_creation.h"
#include "partition_filter.h"
#include "relation_info.h"
#include "xact_handling.h"
#include "utils.h"
#include "access/htup_details.h"
#if PG_VERSION_NUM >= 120000
#include "access/heapam.h"
#include "access/relscan.h"
#include "access/table.h"
#include "access/tableam.h"
#endif
#include "access/xact.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "commands/tablespace.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "utils/builtins.h"
#include "utils/inval.h"
#include "utils/snapmgr.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#if PG_VERSION_NUM < 110000
#include "catalog/pg_inherits_fn.h"
#endif
/* Function declarations */
PG_FUNCTION_INFO_V1( get_number_of_partitions_pl );
PG_FUNCTION_INFO_V1( get_partition_key_type_pl );
PG_FUNCTION_INFO_V1( get_partition_cooked_key_pl );
PG_FUNCTION_INFO_V1( get_cached_partition_cooked_key_pl );
PG_FUNCTION_INFO_V1( get_parent_of_partition_pl );
PG_FUNCTION_INFO_V1( get_base_type_pl );
PG_FUNCTION_INFO_V1( get_tablespace_pl );
PG_FUNCTION_INFO_V1( show_cache_stats_internal );
PG_FUNCTION_INFO_V1( show_partition_list_internal );
PG_FUNCTION_INFO_V1( build_check_constraint_name );
PG_FUNCTION_INFO_V1( validate_relname );
PG_FUNCTION_INFO_V1( validate_expression );
PG_FUNCTION_INFO_V1( is_date_type );
PG_FUNCTION_INFO_V1( is_operator_supported );
PG_FUNCTION_INFO_V1( is_tuple_convertible );
PG_FUNCTION_INFO_V1( add_to_pathman_config );
PG_FUNCTION_INFO_V1( pathman_config_params_trigger_func );
PG_FUNCTION_INFO_V1( prevent_part_modification );
PG_FUNCTION_INFO_V1( prevent_data_modification );
PG_FUNCTION_INFO_V1( validate_part_callback_pl );
PG_FUNCTION_INFO_V1( invoke_on_partition_created_callback );
PG_FUNCTION_INFO_V1( check_security_policy );
PG_FUNCTION_INFO_V1( debug_capture );
PG_FUNCTION_INFO_V1( pathman_version );
/* User context for function show_partition_list_internal() */
typedef struct
{
Relation pathman_config;
#if PG_VERSION_NUM >= 120000
TableScanDesc pathman_config_scan;
#else
HeapScanDesc pathman_config_scan;
#endif
Snapshot snapshot;
PartRelationInfo *current_prel; /* selected PartRelationInfo */
Size child_number; /* child we're looking at */
SPITupleTable *tuptable; /* buffer for tuples */
} show_partition_list_cxt;
/* User context for function show_pathman_cache_stats_internal() */
typedef struct
{
MemoryContext pathman_contexts[PATHMAN_MCXT_COUNT];
HTAB *pathman_htables[PATHMAN_MCXT_COUNT];
int current_item;
} show_cache_stats_cxt;
/*
* ------------------------
* Various useful getters
* ------------------------
*/
/*
* Return parent of a specified partition.
*/
Datum
get_parent_of_partition_pl(PG_FUNCTION_ARGS)
{
Oid partition = PG_GETARG_OID(0),
parent = get_parent_of_partition(partition);
if (!OidIsValid(parent))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("\"%s\" is not a partition",
get_rel_name_or_relid(partition))));
PG_RETURN_OID(parent);
}
/*
* Return partition key type.
*/
Datum
get_partition_key_type_pl(PG_FUNCTION_ARGS)
{
Oid relid = PG_GETARG_OID(0);
Oid typid;
PartRelationInfo *prel;
prel = get_pathman_relation_info(relid);
shout_if_prel_is_invalid(relid, prel, PT_ANY);
typid = prel->ev_type;
close_pathman_relation_info(prel);
PG_RETURN_OID(typid);
}
/*
* Return cooked partition key.
*/
Datum
get_partition_cooked_key_pl(PG_FUNCTION_ARGS)
{
/* Values extracted from PATHMAN_CONFIG */
Datum values[Natts_pathman_config];
bool isnull[Natts_pathman_config];
Oid relid = PG_GETARG_OID(0);
char *expr_cstr;
Node *expr;
char *cooked_cstr;
/* Check that table is registered in PATHMAN_CONFIG */
if (!pathman_config_contains_relation(relid, values, isnull, NULL, NULL))
elog(ERROR, "table \"%s\" is not partitioned",
get_rel_name_or_relid(relid));
expr_cstr = TextDatumGetCString(values[Anum_pathman_config_expr - 1]);
expr = cook_partitioning_expression(relid, expr_cstr, NULL);
#if PG_VERSION_NUM >= 170000 /* for commit d20d8fbd3e4d */
cooked_cstr = nodeToStringWithLocations(expr);
#else
cooked_cstr = nodeToString(expr);
#endif
pfree(expr_cstr);
pfree(expr);
PG_RETURN_DATUM(CStringGetTextDatum(cooked_cstr));
}
/*
* Return cached cooked partition key.
*
* Used in tests for invalidation.
*/
Datum
get_cached_partition_cooked_key_pl(PG_FUNCTION_ARGS)
{
Oid relid = PG_GETARG_OID(0);
PartRelationInfo *prel;
Datum res;
prel = get_pathman_relation_info(relid);
shout_if_prel_is_invalid(relid, prel, PT_ANY);
#if PG_VERSION_NUM >= 170000 /* for commit d20d8fbd3e4d */
res = CStringGetTextDatum(nodeToStringWithLocations(prel->expr));
#else
res = CStringGetTextDatum(nodeToString(prel->expr));
#endif
close_pathman_relation_info(prel);
PG_RETURN_DATUM(res);
}
/*
* Extract basic type of a domain.
*/
Datum
get_base_type_pl(PG_FUNCTION_ARGS)
{
PG_RETURN_OID(getBaseType(PG_GETARG_OID(0)));
}
/*
* Return tablespace name of a specified relation which must not be
* natively partitioned.
*/
Datum
get_tablespace_pl(PG_FUNCTION_ARGS)
{
Oid relid = PG_GETARG_OID(0);
Oid tablespace_id;
char *result;
tablespace_id = get_rel_tablespace(relid);
/* If tablespace id is InvalidOid then use the default tablespace */
if (!OidIsValid(tablespace_id))
{
tablespace_id = GetDefaultTablespaceCompat(get_rel_persistence(relid), false);
/* If tablespace is still invalid then use database's default */
if (!OidIsValid(tablespace_id))
tablespace_id = MyDatabaseTableSpace;
}
result = get_tablespace_name(tablespace_id);
PG_RETURN_TEXT_P(cstring_to_text(result));
}
/*
* ----------------------
* Common purpose VIEWs
* ----------------------
*/
/*
* List stats of all existing caches (memory contexts).
*/
Datum
show_cache_stats_internal(PG_FUNCTION_ARGS)
{
show_cache_stats_cxt *usercxt;
FuncCallContext *funccxt;
/*
* Initialize tuple descriptor & function call context.
*/
if (SRF_IS_FIRSTCALL())
{
TupleDesc tupdesc;
MemoryContext old_mcxt;
funccxt = SRF_FIRSTCALL_INIT();
if (!TopPathmanContext)
{
elog(ERROR, "pg_pathman's memory contexts are not initialized yet");
}
old_mcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
usercxt = (show_cache_stats_cxt *) palloc(sizeof(show_cache_stats_cxt));
usercxt->pathman_contexts[0] = TopPathmanContext;
usercxt->pathman_contexts[1] = PathmanParentsCacheContext;
usercxt->pathman_contexts[2] = PathmanStatusCacheContext;
usercxt->pathman_contexts[3] = PathmanBoundsCacheContext;
usercxt->pathman_htables[0] = NULL; /* no HTAB for this entry */
usercxt->pathman_htables[1] = parents_cache;
usercxt->pathman_htables[2] = status_cache;
usercxt->pathman_htables[3] = bounds_cache;
usercxt->current_item = 0;
/* Create tuple descriptor */
tupdesc = CreateTemplateTupleDescCompat(Natts_pathman_cache_stats, false);
TupleDescInitEntry(tupdesc, Anum_pathman_cs_context,
"context", TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_cs_size,
"size", INT8OID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_cs_used,
"used", INT8OID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_cs_entries,
"entries", INT8OID, -1, 0);
funccxt->tuple_desc = BlessTupleDesc(tupdesc);
funccxt->user_fctx = (void *) usercxt;
MemoryContextSwitchTo(old_mcxt);
}
funccxt = SRF_PERCALL_SETUP();
usercxt = (show_cache_stats_cxt *) funccxt->user_fctx;
if (usercxt->current_item < lengthof(usercxt->pathman_contexts))
{
HTAB *current_htab;
MemoryContext current_mcxt;
HeapTuple htup;
Datum values[Natts_pathman_cache_stats];
bool isnull[Natts_pathman_cache_stats] = { 0 };
#if PG_VERSION_NUM >= 90600
MemoryContextCounters mcxt_stats;
#endif
/* Select current memory context and hash table (cache) */
current_mcxt = usercxt->pathman_contexts[usercxt->current_item];
current_htab = usercxt->pathman_htables[usercxt->current_item];
values[Anum_pathman_cs_context - 1] =
CStringGetTextDatum(simplify_mcxt_name(current_mcxt));
/* We can't check stats of mcxt prior to 9.6 */
#if PG_VERSION_NUM >= 90600
/* Prepare context counters */
memset(&mcxt_stats, 0, sizeof(mcxt_stats));
/* NOTE: we do not consider child contexts if it's TopPathmanContext */
McxtStatsInternal(current_mcxt, 0,
(current_mcxt != TopPathmanContext),
&mcxt_stats);
values[Anum_pathman_cs_size - 1] =
Int64GetDatum(mcxt_stats.totalspace);
values[Anum_pathman_cs_used - 1] =
Int64GetDatum(mcxt_stats.totalspace - mcxt_stats.freespace);
#else
/* Set unsupported fields to NULL */
isnull[Anum_pathman_cs_size - 1] = true;
isnull[Anum_pathman_cs_used - 1] = true;
#endif
values[Anum_pathman_cs_entries - 1] =
Int64GetDatum(current_htab ?
hash_get_num_entries(current_htab) :
0);
/* Switch to next item */
usercxt->current_item++;
/* Form output tuple */
htup = heap_form_tuple(funccxt->tuple_desc, values, isnull);
SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(htup));
}
SRF_RETURN_DONE(funccxt);
}
/*
* List all existing partitions and their parents.
*
* In >=13 (bc8393cf277) struct SPITupleTable was changed
* (free removed and numvals added)
*/
Datum
show_partition_list_internal(PG_FUNCTION_ARGS)
{
show_partition_list_cxt *usercxt;
FuncCallContext *funccxt;
MemoryContext old_mcxt;
SPITupleTable *tuptable;
/* Initialize tuple descriptor & function call context */
if (SRF_IS_FIRSTCALL())
{
TupleDesc tupdesc;
MemoryContext tuptab_mcxt;
funccxt = SRF_FIRSTCALL_INIT();
old_mcxt = MemoryContextSwitchTo(funccxt->multi_call_memory_ctx);
usercxt = (show_partition_list_cxt *) palloc(sizeof(show_partition_list_cxt));
/* Open PATHMAN_CONFIG with latest snapshot available */
usercxt->pathman_config = heap_open_compat(get_pathman_config_relid(false),
AccessShareLock);
usercxt->snapshot = RegisterSnapshot(GetLatestSnapshot());
#if PG_VERSION_NUM >= 120000
usercxt->pathman_config_scan = table_beginscan(usercxt->pathman_config,
usercxt->snapshot, 0, NULL);
#else
usercxt->pathman_config_scan = heap_beginscan(usercxt->pathman_config,
usercxt->snapshot, 0, NULL);
#endif
usercxt->current_prel = NULL;
/* Create tuple descriptor */
tupdesc = CreateTemplateTupleDescCompat(Natts_pathman_partition_list, false);
TupleDescInitEntry(tupdesc, Anum_pathman_pl_parent,
"parent", REGCLASSOID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_pl_partition,
"partition", REGCLASSOID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_pl_parttype,
"parttype", INT4OID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_pl_partattr,
"expr", TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_pl_range_min,
"range_min", TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, Anum_pathman_pl_range_max,
"range_max", TEXTOID, -1, 0);
funccxt->tuple_desc = BlessTupleDesc(tupdesc);
funccxt->user_fctx = (void *) usercxt;
/* initialize tuple table context */
tuptab_mcxt = AllocSetContextCreate(CurrentMemoryContext,
"tuptable for pathman_partition_list",
ALLOCSET_DEFAULT_SIZES);
MemoryContextSwitchTo(tuptab_mcxt);
/* Initialize tuple table for partitions list, we use it as buffer */
tuptable = (SPITupleTable *) palloc0(sizeof(SPITupleTable));
usercxt->tuptable = tuptable;
tuptable->tuptabcxt = tuptab_mcxt;
/* Set up initial allocations */
#if PG_VERSION_NUM >= 130000
tuptable->alloced = PART_RELS_SIZE * CHILD_FACTOR;
tuptable->numvals = 0;
#else
tuptable->alloced = tuptable->free = PART_RELS_SIZE * CHILD_FACTOR;
#endif
tuptable->vals = (HeapTuple *) palloc(tuptable->alloced * sizeof(HeapTuple));
MemoryContextSwitchTo(old_mcxt);
/* Iterate through pathman cache */
for (;;)
{
HeapTuple htup;
Datum values[Natts_pathman_partition_list];
bool isnull[Natts_pathman_partition_list] = { 0 };
PartRelationInfo *prel;
/* Fetch next PartRelationInfo if needed */
if (usercxt->current_prel == NULL)
{
HeapTuple pathman_config_htup;
Datum parent_table;
bool parent_table_isnull;
Oid parent_table_oid;
pathman_config_htup = heap_getnext(usercxt->pathman_config_scan,
ForwardScanDirection);
if (!HeapTupleIsValid(pathman_config_htup))
break;
parent_table = heap_getattr(pathman_config_htup,
Anum_pathman_config_partrel,
RelationGetDescr(usercxt->pathman_config),
&parent_table_isnull);
Assert(parent_table_isnull == false);
parent_table_oid = DatumGetObjectId(parent_table);
usercxt->current_prel = get_pathman_relation_info(parent_table_oid);
if (usercxt->current_prel == NULL)
continue;
usercxt->child_number = 0;
}
/* Alias to 'usercxt->current_prel' */
prel = usercxt->current_prel;
/* If we've run out of partitions, switch to the next 'prel' */
if (usercxt->child_number >= PrelChildrenCount(prel))
{
/* Don't forget to close 'prel'! */
close_pathman_relation_info(prel);
usercxt->current_prel = NULL;
usercxt->child_number = 0;
continue;
}
/* Fill in common values */
values[Anum_pathman_pl_parent - 1] = PrelParentRelid(prel);
values[Anum_pathman_pl_parttype - 1] = prel->parttype;
values[Anum_pathman_pl_partattr - 1] = CStringGetTextDatum(prel->expr_cstr);
switch (prel->parttype)
{
case PT_HASH:
{
Oid *children = PrelGetChildrenArray(prel),
child_oid = children[usercxt->child_number];
values[Anum_pathman_pl_partition - 1] = child_oid;
isnull[Anum_pathman_pl_range_min - 1] = true;
isnull[Anum_pathman_pl_range_max - 1] = true;
}
break;
case PT_RANGE:
{
RangeEntry *re;
re = &PrelGetRangesArray(prel)[usercxt->child_number];
values[Anum_pathman_pl_partition - 1] = re->child_oid;
/* Lower bound text */
if (!IsInfinite(&re->min))
{
Datum rmin = CStringGetTextDatum(
BoundToCString(&re->min,
prel->ev_type));
values[Anum_pathman_pl_range_min - 1] = rmin;
}
else isnull[Anum_pathman_pl_range_min - 1] = true;
/* Upper bound text */
if (!IsInfinite(&re->max))
{
Datum rmax = CStringGetTextDatum(
BoundToCString(&re->max,
prel->ev_type));
values[Anum_pathman_pl_range_max - 1] = rmax;
}
else isnull[Anum_pathman_pl_range_max - 1] = true;
}
break;
default:
WrongPartType(prel->parttype);
}
/* Fill tuptable */
old_mcxt = MemoryContextSwitchTo(tuptable->tuptabcxt);
/* Form output tuple */
htup = heap_form_tuple(funccxt->tuple_desc, values, isnull);
#if PG_VERSION_NUM >= 130000
if (tuptable->numvals == tuptable->alloced)
#else
if (tuptable->free == 0)
#endif
{
/* Double the size of the pointer array */
#if PG_VERSION_NUM >= 130000
tuptable->alloced += tuptable->alloced;
#else
tuptable->free = tuptable->alloced;
tuptable->alloced += tuptable->free;
#endif
tuptable->vals = (HeapTuple *)
repalloc_huge(tuptable->vals,
tuptable->alloced * sizeof(HeapTuple));
}
#if PG_VERSION_NUM >= 130000
/* Add tuple to table and increase 'numvals' */
tuptable->vals[tuptable->numvals] = htup;
(tuptable->numvals)++;
#else
/* Add tuple to table and decrement 'free' */
tuptable->vals[tuptable->alloced - tuptable->free] = htup;
(tuptable->free)--;
#endif
MemoryContextSwitchTo(old_mcxt);
/* Switch to the next child */
usercxt->child_number++;
}
/* Clean resources */
#if PG_VERSION_NUM >= 120000
table_endscan(usercxt->pathman_config_scan);
#else
heap_endscan(usercxt->pathman_config_scan);
#endif
UnregisterSnapshot(usercxt->snapshot);
heap_close_compat(usercxt->pathman_config, AccessShareLock);
usercxt->child_number = 0;
}
funccxt = SRF_PERCALL_SETUP();
usercxt = (show_partition_list_cxt *) funccxt->user_fctx;
tuptable = usercxt->tuptable;
/* Iterate through used slots */
#if PG_VERSION_NUM >= 130000
if (usercxt->child_number < tuptable->numvals)
#else
if (usercxt->child_number < (tuptable->alloced - tuptable->free))
#endif
{
HeapTuple htup = usercxt->tuptable->vals[usercxt->child_number++];
SRF_RETURN_NEXT(funccxt, HeapTupleGetDatum(htup));
}
SRF_RETURN_DONE(funccxt);
}
/*
* --------
* Traits
* --------
*/
/*
* Check that relation exists.
* NOTE: we pass REGCLASS as text, hence the function's name.
*/
Datum
validate_relname(PG_FUNCTION_ARGS)
{
Oid relid;
/* We don't accept NULL */
if (PG_ARGISNULL(0))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation should not be NULL"),
errdetail("function " CppAsString(validate_relname)
" received NULL argument")));
/* Fetch relation's Oid */
relid = PG_GETARG_OID(0);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%u\" does not exist", relid),
errdetail("triggered in function "
CppAsString(validate_relname))));
PG_RETURN_VOID();
}
/*
* Validate a partitioning expression.
* NOTE: We need this in range functions because
* we do many things before actual partitioning.
*/
Datum
validate_expression(PG_FUNCTION_ARGS)
{
Oid relid;
char *expression;
/* Fetch relation's Oid */
if (!PG_ARGISNULL(0))
{
relid = PG_GETARG_OID(0);
check_relation_oid(relid);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'relid' should not be NULL")));
/* Protect relation from concurrent drop */
LockRelationOid(relid, AccessShareLock);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%u\" does not exist", relid),
errdetail("triggered in function "
CppAsString(validate_expression))));
if (!PG_ARGISNULL(1))
{
expression = TextDatumGetCString(PG_GETARG_DATUM(1));
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'expression' should not be NULL")));
/* Perform some checks */
cook_partitioning_expression(relid, expression, NULL);
UnlockRelationOid(relid, AccessShareLock);
PG_RETURN_VOID();
}
Datum
is_date_type(PG_FUNCTION_ARGS)
{
PG_RETURN_BOOL(is_date_type_internal(PG_GETARG_OID(0)));
}
/*
* Bail out with ERROR if rel1 tuple can't be converted to rel2 tuple.
*/
Datum
is_tuple_convertible(PG_FUNCTION_ARGS)
{
Relation rel1,
rel2;
#if PG_VERSION_NUM >= 130000
AttrMap *map; /* we don't actually need it */
#else
void *map; /* we don't actually need it */
#endif
rel1 = heap_open_compat(PG_GETARG_OID(0), AccessShareLock);
rel2 = heap_open_compat(PG_GETARG_OID(1), AccessShareLock);
/* Try to build a conversion map */
#if PG_VERSION_NUM >= 160000 /* for commit ad86d159b6ab */
map = build_attrmap_by_name(RelationGetDescr(rel1),
RelationGetDescr(rel2), false);
#elif PG_VERSION_NUM >= 130000
map = build_attrmap_by_name(RelationGetDescr(rel1),
RelationGetDescr(rel2));
#else
map = convert_tuples_by_name_map(RelationGetDescr(rel1),
RelationGetDescr(rel2),
ERR_PART_DESC_CONVERT);
#endif
/* Now free map */
#if PG_VERSION_NUM >= 130000
free_attrmap(map);
#else
pfree(map);
#endif
heap_close_compat(rel1, AccessShareLock);
heap_close_compat(rel2, AccessShareLock);
/* still return true to avoid changing tests */
PG_RETURN_BOOL(true);
}
/*
* ------------------------
* Useful string builders
* ------------------------
*/
Datum
build_check_constraint_name(PG_FUNCTION_ARGS)
{
Oid relid = PG_GETARG_OID(0);
const char *result;
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%u\" does not exist", relid)));
result = build_check_constraint_name_relid_internal(relid);
PG_RETURN_TEXT_P(cstring_to_text(quote_identifier(result)));
}
/*
* ------------------------
* Cache & config updates
* ------------------------
*/
/*
* Try to add previously partitioned table to PATHMAN_CONFIG.
*/
Datum
add_to_pathman_config(PG_FUNCTION_ARGS)
{
Oid relid;
char *expression;
PartType parttype;
Oid *children;
uint32 children_count;
Relation pathman_config;
Datum values[Natts_pathman_config];
bool isnull[Natts_pathman_config];
HeapTuple htup;
Oid expr_type;
volatile PathmanInitState init_state;
if (!IsPathmanReady())
elog(ERROR, "pg_pathman is disabled");
if (!PG_ARGISNULL(0))
{
relid = PG_GETARG_OID(0);
check_relation_oid(relid);
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'parent_relid' should not be NULL")));
/* Protect data + definition from concurrent modification */
LockRelationOid(relid, AccessExclusiveLock);
/* Check that relation exists */
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("relation \"%u\" does not exist", relid)));
if (!PG_ARGISNULL(1))
{
expression = TextDatumGetCString(PG_GETARG_DATUM(1));
}
else ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("'expression' should not be NULL")));
/* Check current user's privileges */
if (!check_security_policy_internal(relid, GetUserId()))
{
ereport(ERROR,
(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("only the owner or superuser can change "
"partitioning configuration of table \"%s\"",
get_rel_name_or_relid(relid))));
}
/* Select partitioning type */
switch (PG_NARGS())
{
/* HASH */
case 2:
{
parttype = PT_HASH;
values[Anum_pathman_config_range_interval - 1] = (Datum) 0;
isnull[Anum_pathman_config_range_interval - 1] = true;
}
break;
/* RANGE */
case 3:
{
parttype = PT_RANGE;
values[Anum_pathman_config_range_interval - 1] = PG_GETARG_DATUM(2);
isnull[Anum_pathman_config_range_interval - 1] = PG_ARGISNULL(2);
}
break;
default:
elog(ERROR, "error in function " CppAsString(add_to_pathman_config));
PG_RETURN_BOOL(false); /* keep compiler happy */
}
/* Parse and check expression */
cook_partitioning_expression(relid, expression, &expr_type);
/* Canonicalize user's expression (trim whitespaces etc) */
expression = canonicalize_partitioning_expression(relid, expression);
/* Check hash function for HASH partitioning */
if (parttype == PT_HASH)
{
TypeCacheEntry *tce = lookup_type_cache(expr_type, TYPECACHE_HASH_PROC);
if (!OidIsValid(tce->hash_proc))
ereport(ERROR,
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
errmsg("no hash function for partitioning expression")));
}
/*
* Initialize columns (partrel, attname, parttype, range_interval).
*/
values[Anum_pathman_config_partrel - 1] = ObjectIdGetDatum(relid);
isnull[Anum_pathman_config_partrel - 1] = false;
values[Anum_pathman_config_parttype - 1] = Int32GetDatum(parttype);
isnull[Anum_pathman_config_parttype - 1] = false;
values[Anum_pathman_config_expr - 1] = CStringGetTextDatum(expression);
isnull[Anum_pathman_config_expr - 1] = false;
/* Insert new row into PATHMAN_CONFIG */
pathman_config = heap_open_compat(get_pathman_config_relid(false), RowExclusiveLock);
htup = heap_form_tuple(RelationGetDescr(pathman_config), values, isnull);
CatalogTupleInsert(pathman_config, htup);
heap_close_compat(pathman_config, RowExclusiveLock);
/* Make changes visible */
CommandCounterIncrement();
/* Update caches only if this relation has children */
if (FCS_FOUND == find_inheritance_children_array(relid, NoLock, true,
&children_count,
&children))
{
pfree(children);
PG_TRY();
{
/* Some flags might change during refresh attempt */
save_pathman_init_state(&init_state);
/* Now try to create a PartRelationInfo */
has_pathman_relation_info(relid);
}
PG_CATCH();
{
/* We have to restore changed flags */
restore_pathman_init_state(&init_state);
/* Rethrow ERROR */
PG_RE_THROW();
}
PG_END_TRY();
}
/* Check if naming sequence exists */
if (parttype == PT_RANGE)
{
RangeVar *naming_seq_rv;
Oid naming_seq;
naming_seq_rv = makeRangeVar(get_namespace_name(get_rel_namespace(relid)),
build_sequence_name_relid_internal(relid),
-1);
naming_seq = RangeVarGetRelid(naming_seq_rv, AccessShareLock, true);
if (OidIsValid(naming_seq))
{
ObjectAddress parent,
sequence;
ObjectAddressSet(parent, RelationRelationId, relid);
ObjectAddressSet(sequence, RelationRelationId, naming_seq);
/* Now this naming sequence is a "part" of partitioned relation */
recordDependencyOn(&sequence, &parent, DEPENDENCY_NORMAL);
}
}
CacheInvalidateRelcacheByRelid(relid);
PG_RETURN_BOOL(true);
}
/*
* Invalidate relcache to refresh PartRelationInfo.
*/
Datum
pathman_config_params_trigger_func(PG_FUNCTION_ARGS)
{
TriggerData *trigdata = (TriggerData *) fcinfo->context;
Oid pathman_config_params;
Oid pathman_config;
Oid partrel;
Datum partrel_datum;
bool partrel_isnull;
/* Fetch Oid of PATHMAN_CONFIG_PARAMS */
pathman_config_params = get_pathman_config_params_relid(true);
pathman_config = get_pathman_config_relid(true);
/* Handle "pg_pathman.enabled = f" case */
if (!OidIsValid(pathman_config_params))
goto pathman_config_params_trigger_func_return;
/* Handle user calls */
if (!CALLED_AS_TRIGGER(fcinfo))
elog(ERROR, "this function should not be called directly");
/* Handle wrong fire mode */