-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathinit.c
1172 lines (961 loc) · 28.5 KB
/
init.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
/* ------------------------------------------------------------------------
*
* init.c
* Initialization functions
*
* Copyright (c) 2015-2020, Postgres Professional
*
* Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* ------------------------------------------------------------------------
*/
#include "compat/pg_compat.h"
#include "hooks.h"
#include "init.h"
#include "pathman.h"
#include "pathman_workers.h"
#include "relation_info.h"
#include "utils.h"
#include "access/htup_details.h"
#include "access/heapam.h"
#include "access/genam.h"
#include "access/sysattr.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "catalog/indexing.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#if PG_VERSION_NUM >= 120000
#include "nodes/nodeFuncs.h"
#endif
#include "optimizer/clauses.h"
#include "utils/inval.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/memutils.h"
#include "utils/lsyscache.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#if PG_VERSION_NUM < 110000
#include "catalog/pg_inherits_fn.h"
#endif
#include <stdlib.h>
/* Various memory contexts for caches */
MemoryContext TopPathmanContext = NULL;
MemoryContext PathmanParentsCacheContext = NULL;
MemoryContext PathmanStatusCacheContext = NULL;
MemoryContext PathmanBoundsCacheContext = NULL;
/* Storage for PartParentInfos */
HTAB *parents_cache = NULL;
/* Storage for PartStatusInfos */
HTAB *status_cache = NULL;
/* Storage for PartBoundInfos */
HTAB *bounds_cache = NULL;
/* pg_pathman's init status */
PathmanInitState pathman_init_state;
/* pg_pathman's hooks state */
bool pathman_hooks_enabled = true;
/* Functions for various local caches */
static bool init_pathman_relation_oids(void);
static void fini_pathman_relation_oids(void);
static void init_local_cache(void);
static void fini_local_cache(void);
static bool validate_range_opexpr(const Expr *expr,
const PartRelationInfo *prel,
const TypeCacheEntry *tce,
Datum *lower, Datum *upper,
bool *lower_null, bool *upper_null);
static bool read_opexpr_const(const OpExpr *opexpr,
const PartRelationInfo *prel,
Datum *value);
/* Validate SQL facade */
static uint32 build_semver_uint32(char *version_cstr);
static uint32 get_plpgsql_frontend_version(void);
static void validate_plpgsql_frontend_version(uint32 current_ver,
uint32 compatible_ver);
/*
* Safe hash search (takes care of disabled pg_pathman).
*/
void *
pathman_cache_search_relid(HTAB *cache_table,
Oid relid,
HASHACTION action,
bool *found)
{
/* Table is NULL, take some actions */
if (cache_table == NULL)
switch (action)
{
case HASH_FIND:
case HASH_ENTER:
case HASH_REMOVE:
elog(ERROR, "pg_pathman is not initialized yet");
break;
/* Something strange has just happened */
default:
elog(ERROR, "unexpected action in function "
CppAsString(pathman_cache_search_relid));
break;
}
/* Everything is fine */
return hash_search(cache_table, (const void *) &relid, action, found);
}
/*
* Save and restore main init state.
*/
void
save_pathman_init_state(volatile PathmanInitState *temp_init_state)
{
*temp_init_state = pathman_init_state;
}
void
restore_pathman_init_state(const volatile PathmanInitState *temp_init_state)
{
/*
* initialization_needed is not restored: it is not just a setting but
* internal thing, caches must be inited when it is set. Better would be
* to separate it from this struct entirely.
*/
pathman_init_state.pg_pathman_enable = temp_init_state->pg_pathman_enable;
pathman_init_state.auto_partition = temp_init_state->auto_partition;
pathman_init_state.override_copy = temp_init_state->override_copy;
}
/*
* Create main GUCs.
*/
void
init_main_pathman_toggles(void)
{
/* Main toggle, load_config() will enable it */
DefineCustomBoolVariable(PATHMAN_ENABLE,
"Enables pg_pathman's optimizations during planning stage",
NULL,
&pathman_init_state.pg_pathman_enable,
DEFAULT_PATHMAN_ENABLE,
PGC_SUSET,
0,
pathman_enable_check_hook,
pathman_enable_assign_hook,
NULL);
/* Global toggle for automatic partition creation */
DefineCustomBoolVariable(PATHMAN_ENABLE_AUTO_PARTITION,
"Enables automatic partition creation",
NULL,
&pathman_init_state.auto_partition,
DEFAULT_PATHMAN_AUTO,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
/* Global toggle for COPY stmt handling */
DefineCustomBoolVariable(PATHMAN_OVERRIDE_COPY,
"Override COPY statement handling",
NULL,
&pathman_init_state.override_copy,
DEFAULT_PATHMAN_OVERRIDE_COPY,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
}
/*
* Create local PartRelationInfo cache & load pg_pathman's config.
* Return true on success. May occasionally emit ERROR.
*/
bool
load_config(void)
{
static bool relcache_callback_needed = true;
/*
* Try to cache important relids.
*
* Once CREATE EXTENSION stmt is processed, get_pathman_schema()
* function starts returning perfectly valid schema Oid, which
* means we have to check that *ALL* pg_pathman's relations' Oids
* have been cached properly. Only then can we assume that
* initialization is not needed anymore.
*/
if (!init_pathman_relation_oids())
return false; /* remain 'uninitialized', exit before creating main caches */
/* Validate pg_pathman's Pl/PgSQL facade (might be outdated) */
validate_plpgsql_frontend_version(get_plpgsql_frontend_version(),
build_semver_uint32(LOWEST_COMPATIBLE_FRONT));
/* Create various hash tables (caches) */
init_local_cache();
/* Register pathman_relcache_hook(), currently we can't unregister it */
if (relcache_callback_needed)
{
CacheRegisterRelcacheCallback(pathman_relcache_hook, PointerGetDatum(NULL));
relcache_callback_needed = false;
}
/* Mark pg_pathman as initialized */
pathman_init_state.initialization_needed = false;
elog(DEBUG2, "pg_pathman's config has been loaded successfully [%u]", MyProcPid);
return true;
}
/*
* Destroy local caches & free memory.
*/
void
unload_config(void)
{
/* Don't forget to reset pg_pathman's cached relids */
fini_pathman_relation_oids();
/* Destroy 'partitioned_rels' & 'parent_cache' hash tables */
fini_local_cache();
/* Mark pg_pathman as uninitialized */
pathman_init_state.initialization_needed = true;
elog(DEBUG2, "pg_pathman's config has been unloaded successfully [%u]", MyProcPid);
}
/*
* Estimate total amount of shmem needed for pg_pathman to run.
*/
Size
estimate_pathman_shmem_size(void)
{
return estimate_concurrent_part_task_slots_size();
}
/*
* Cache *all* important pg_pathman's relids at once.
* We should NOT rely on any previously cached values.
*/
static bool
init_pathman_relation_oids(void)
{
Oid schema = get_pathman_schema();
if (schema == InvalidOid)
return false; /* extension can be dropped by another backend */
/* Cache PATHMAN_CONFIG relation's Oid */
pathman_config_relid = get_relname_relid(PATHMAN_CONFIG, schema);
if (pathman_config_relid == InvalidOid)
return false;
/* Cache PATHMAN_CONFIG_PARAMS relation's Oid */
pathman_config_params_relid = get_relname_relid(PATHMAN_CONFIG_PARAMS,
schema);
if (pathman_config_params_relid == InvalidOid)
return false;
/* NOTE: add more relations to be cached right here ^^^ */
/* Everything is fine, proceed */
return true;
}
/*
* Forget *all* pg_pathman's cached relids.
*/
static void
fini_pathman_relation_oids(void)
{
pathman_config_relid = InvalidOid;
pathman_config_params_relid = InvalidOid;
/* NOTE: add more relations to be forgotten right here ^^^ */
}
/*
* Initialize per-process resources.
*/
static void
init_local_cache(void)
{
HASHCTL ctl;
/* Destroy caches, just in case */
hash_destroy(parents_cache);
hash_destroy(status_cache);
hash_destroy(bounds_cache);
/* Reset pg_pathman's memory contexts */
if (TopPathmanContext)
{
/* Check that child contexts exist */
Assert(MemoryContextIsValid(PathmanParentsCacheContext));
Assert(MemoryContextIsValid(PathmanStatusCacheContext));
Assert(MemoryContextIsValid(PathmanBoundsCacheContext));
/* Clear children */
MemoryContextReset(PathmanParentsCacheContext);
MemoryContextReset(PathmanStatusCacheContext);
MemoryContextReset(PathmanBoundsCacheContext);
}
/* Initialize pg_pathman's memory contexts */
else
{
Assert(PathmanParentsCacheContext == NULL);
Assert(PathmanStatusCacheContext == NULL);
Assert(PathmanBoundsCacheContext == NULL);
TopPathmanContext =
AllocSetContextCreate(TopMemoryContext,
PATHMAN_TOP_CONTEXT,
ALLOCSET_DEFAULT_SIZES);
/* For PartParentInfo */
PathmanParentsCacheContext =
AllocSetContextCreate(TopPathmanContext,
PATHMAN_PARENTS_CACHE,
ALLOCSET_SMALL_SIZES);
/* For PartStatusInfo */
PathmanStatusCacheContext =
AllocSetContextCreate(TopPathmanContext,
PATHMAN_STATUS_CACHE,
ALLOCSET_SMALL_SIZES);
/* For PartBoundInfo */
PathmanBoundsCacheContext =
AllocSetContextCreate(TopPathmanContext,
PATHMAN_BOUNDS_CACHE,
ALLOCSET_SMALL_SIZES);
}
memset(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(Oid);
ctl.entrysize = sizeof(PartParentInfo);
ctl.hcxt = PathmanParentsCacheContext;
parents_cache = hash_create(PATHMAN_PARENTS_CACHE,
PART_RELS_SIZE, &ctl,
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
memset(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(Oid);
ctl.entrysize = sizeof(PartStatusInfo);
ctl.hcxt = PathmanStatusCacheContext;
status_cache = hash_create(PATHMAN_STATUS_CACHE,
PART_RELS_SIZE * CHILD_FACTOR, &ctl,
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
memset(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(Oid);
ctl.entrysize = sizeof(PartBoundInfo);
ctl.hcxt = PathmanBoundsCacheContext;
bounds_cache = hash_create(PATHMAN_BOUNDS_CACHE,
PART_RELS_SIZE * CHILD_FACTOR, &ctl,
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
}
/*
* Safely free per-process resources.
*/
static void
fini_local_cache(void)
{
/* First, destroy hash tables */
hash_destroy(parents_cache);
hash_destroy(status_cache);
hash_destroy(bounds_cache);
parents_cache = NULL;
status_cache = NULL;
bounds_cache = NULL;
if (prel_resowner != NULL)
{
hash_destroy(prel_resowner);
prel_resowner = NULL;
}
/* Now we can clear allocations */
if (TopPathmanContext)
{
MemoryContextReset(PathmanParentsCacheContext);
MemoryContextReset(PathmanStatusCacheContext);
MemoryContextReset(PathmanBoundsCacheContext);
}
}
/*
* find_inheritance_children
*
* Returns an array containing the OIDs of all relations which
* inherit *directly* from the relation with OID 'parent_relid'.
*
* The specified lock type is acquired on each child relation (but not on the
* given rel; caller should already have locked it). If lockmode is NoLock
* then no locks are acquired, but caller must beware of race conditions
* against possible DROPs of child relations.
*
* borrowed from pg_inherits.c
*/
find_children_status
find_inheritance_children_array(Oid parent_relid,
LOCKMODE lockmode,
bool nowait,
uint32 *children_size, /* ret value #1 */
Oid **children) /* ret value #2 */
{
Relation relation;
SysScanDesc scan;
ScanKeyData key[1];
HeapTuple inheritsTuple;
Oid *oidarr;
uint32 maxoids,
numoids;
Oid *result = NULL;
uint32 nresult = 0;
uint32 i;
/* Init safe return values */
*children_size = 0;
*children = NULL;
/*
* Can skip the scan if pg_class shows the
* relation has never had a subclass.
*/
if (!has_subclass(parent_relid))
return FCS_NO_CHILDREN;
/*
* Scan pg_inherits and build a working array of subclass OIDs.
*/
ArrayAlloc(oidarr, maxoids, numoids, 32);
relation = heap_open_compat(InheritsRelationId, AccessShareLock);
ScanKeyInit(&key[0],
Anum_pg_inherits_inhparent,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(parent_relid));
scan = systable_beginscan(relation, InheritsParentIndexId, true,
NULL, 1, key);
while ((inheritsTuple = systable_getnext(scan)) != NULL)
{
Oid inhrelid;
inhrelid = ((Form_pg_inherits) GETSTRUCT(inheritsTuple))->inhrelid;
ArrayPush(oidarr, maxoids, numoids, inhrelid);
}
systable_endscan(scan);
heap_close_compat(relation, AccessShareLock);
/*
* If we found more than one child, sort them by OID. This ensures
* reasonably consistent behavior regardless of the vagaries of an
* indexscan. This is important since we need to be sure all backends
* lock children in the same order to avoid needless deadlocks.
*/
if (numoids > 1)
qsort(oidarr, numoids, sizeof(Oid), oid_cmp);
/* Acquire locks and build the result list */
for (i = 0; i < numoids; i++)
{
Oid inhrelid = oidarr[i];
if (lockmode != NoLock)
{
/* Get the lock to synchronize against concurrent drop */
if (nowait)
{
if (!ConditionalLockRelationOid(inhrelid, lockmode))
{
uint32 j;
/* Unlock all previously locked children */
for (j = 0; j < i; j++)
UnlockRelationOid(oidarr[j], lockmode);
pfree(oidarr);
/* We couldn't lock this child, retreat! */
return FCS_COULD_NOT_LOCK;
}
}
else LockRelationOid(inhrelid, lockmode);
/*
* Now that we have the lock, double-check to see if the relation
* really exists or not. If not, assume it was dropped while we
* waited to acquire lock, and ignore it.
*/
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(inhrelid)))
{
/* Release useless lock */
UnlockRelationOid(inhrelid, lockmode);
/* And ignore this relation */
continue;
}
}
/* Alloc array if it's the first time */
if (nresult == 0)
result = palloc(numoids * sizeof(Oid));
/* Save Oid of the existing relation */
result[nresult++] = inhrelid;
}
/* Set return values */
*children_size = nresult;
*children = result;
pfree(oidarr);
/* Do we have children? */
return nresult > 0 ? FCS_FOUND : FCS_NO_CHILDREN;
}
/*
* Generate check constraint name for a partition.
* NOTE: this function does not perform sanity checks at all.
*/
char *
build_check_constraint_name_relid_internal(Oid relid)
{
Assert(OidIsValid(relid));
return build_check_constraint_name_relname_internal(get_rel_name(relid));
}
/*
* Generate check constraint name for a partition.
* NOTE: this function does not perform sanity checks at all.
*/
char *
build_check_constraint_name_relname_internal(const char *relname)
{
Assert(relname != NULL);
return psprintf("pathman_%s_check", relname);
}
/*
* Generate part sequence name for a parent.
* NOTE: this function does not perform sanity checks at all.
*/
char *
build_sequence_name_relid_internal(Oid relid)
{
Assert(OidIsValid(relid));
return build_sequence_name_relname_internal(get_rel_name(relid));
}
/*
* Generate part sequence name for a parent.
* NOTE: this function does not perform sanity checks at all.
*/
char *
build_sequence_name_relname_internal(const char *relname)
{
Assert(relname != NULL);
return psprintf("%s_seq", relname);
}
/*
* Generate name for update trigger.
* NOTE: this function does not perform sanity checks at all.
*/
char *
build_update_trigger_name_internal(Oid relid)
{
Assert(OidIsValid(relid));
return psprintf("%s_upd_trig", get_rel_name(relid));
}
/*
* Generate name for update trigger's function.
* NOTE: this function does not perform sanity checks at all.
*/
char *
build_update_trigger_func_name_internal(Oid relid)
{
Assert(OidIsValid(relid));
return psprintf("%s_upd_trig_func", get_rel_name(relid));
}
/*
* Check that relation 'relid' is partitioned by pg_pathman.
* Extract tuple into 'values', 'isnull', 'xmin', 'iptr' if they're provided.
*/
bool
pathman_config_contains_relation(Oid relid, Datum *values, bool *isnull,
TransactionId *xmin, ItemPointerData* iptr)
{
Relation rel;
#if PG_VERSION_NUM >= 120000
TableScanDesc scan;
#else
HeapScanDesc scan;
#endif
ScanKeyData key[1];
Snapshot snapshot;
HeapTuple htup;
bool contains_rel = false;
ScanKeyInit(&key[0],
Anum_pathman_config_partrel,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relid));
/* Open PATHMAN_CONFIG with latest snapshot available */
rel = heap_open_compat(get_pathman_config_relid(false), AccessShareLock);
/* Check that 'partrel' column is of regclass type */
Assert(TupleDescAttr(RelationGetDescr(rel),
Anum_pathman_config_partrel - 1)->atttypid == REGCLASSOID);
/* Check that number of columns == Natts_pathman_config */
Assert(RelationGetDescr(rel)->natts == Natts_pathman_config);
snapshot = RegisterSnapshot(GetLatestSnapshot());
#if PG_VERSION_NUM >= 120000
scan = table_beginscan(rel, snapshot, 1, key);
#else
scan = heap_beginscan(rel, snapshot, 1, key);
#endif
while ((htup = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
contains_rel = true; /* found partitioned table */
/* Extract data if necessary */
if (values && isnull)
{
htup = heap_copytuple(htup);
heap_deform_tuple(htup, RelationGetDescr(rel), values, isnull);
/* Perform checks for non-NULL columns */
Assert(!isnull[Anum_pathman_config_partrel - 1]);
Assert(!isnull[Anum_pathman_config_expr - 1]);
Assert(!isnull[Anum_pathman_config_parttype - 1]);
}
/* Set xmin if necessary */
if (xmin)
*xmin = HeapTupleGetXminCompat(htup);
/* Set ItemPointer if necessary */
if (iptr)
*iptr = htup->t_self; /* FIXME: callers should lock table beforehand */
}
/* Clean resources */
#if PG_VERSION_NUM >= 120000
table_endscan(scan);
#else
heap_endscan(scan);
#endif
UnregisterSnapshot(snapshot);
heap_close_compat(rel, AccessShareLock);
elog(DEBUG2, "PATHMAN_CONFIG %s relation %u",
(contains_rel ? "contains" : "doesn't contain"), relid);
return contains_rel;
}
/*
* Loads additional pathman parameters like 'enable_parent'
* or 'auto' from PATHMAN_CONFIG_PARAMS.
*/
bool
read_pathman_params(Oid relid, Datum *values, bool *isnull)
{
Relation rel;
#if PG_VERSION_NUM >= 120000
TableScanDesc scan;
#else
HeapScanDesc scan;
#endif
ScanKeyData key[1];
Snapshot snapshot;
HeapTuple htup;
bool row_found = false;
ScanKeyInit(&key[0],
Anum_pathman_config_params_partrel,
BTEqualStrategyNumber, F_OIDEQ,
ObjectIdGetDatum(relid));
rel = heap_open_compat(get_pathman_config_params_relid(false), AccessShareLock);
snapshot = RegisterSnapshot(GetLatestSnapshot());
#if PG_VERSION_NUM >= 120000
scan = table_beginscan(rel, snapshot, 1, key);
#else
scan = heap_beginscan(rel, snapshot, 1, key);
#endif
/* There should be just 1 row */
if ((htup = heap_getnext(scan, ForwardScanDirection)) != NULL)
{
/* Extract data if necessary */
htup = heap_copytuple(htup);
heap_deform_tuple(htup, RelationGetDescr(rel), values, isnull);
row_found = true;
/* Perform checks for non-NULL columns */
Assert(!isnull[Anum_pathman_config_params_partrel - 1]);
Assert(!isnull[Anum_pathman_config_params_enable_parent - 1]);
Assert(!isnull[Anum_pathman_config_params_auto - 1]);
Assert(!isnull[Anum_pathman_config_params_spawn_using_bgw - 1]);
}
/* Clean resources */
#if PG_VERSION_NUM >= 120000
table_endscan(scan);
#else
heap_endscan(scan);
#endif
UnregisterSnapshot(snapshot);
heap_close_compat(rel, AccessShareLock);
return row_found;
}
/*
* Validates range constraint. It MUST have one of the following formats:
* 1) EXPRESSION >= CONST AND EXPRESSION < CONST
* 2) EXPRESSION >= CONST
* 3) EXPRESSION < CONST
*
* Writes 'lower' & 'upper' and 'lower_null' & 'upper_null' values on success.
*/
bool
validate_range_constraint(const Expr *expr,
const PartRelationInfo *prel,
Datum *lower, Datum *upper,
bool *lower_null, bool *upper_null)
{
const TypeCacheEntry *tce;
if (!expr)
return false;
/* Set default values */
*lower_null = *upper_null = true;
/* Find type cache entry for partitioned expression type */
tce = lookup_type_cache(prel->ev_type, TYPECACHE_BTREE_OPFAMILY);
/* Is it an AND clause? */
if (is_andclause_compat((Node *) expr))
{
const BoolExpr *boolexpr = (const BoolExpr *) expr;
ListCell *lc;
/* Walk through boolexpr's args */
foreach (lc, boolexpr->args)
{
const OpExpr *opexpr = (const OpExpr *) lfirst(lc);
/* Exit immediately if something is wrong */
if (!validate_range_opexpr((const Expr *) opexpr, prel, tce,
lower, upper, lower_null, upper_null))
return false;
}
/* Everything seems to be fine */
return true;
}
/* It might be just an OpExpr clause */
else return validate_range_opexpr(expr, prel, tce,
lower, upper, lower_null, upper_null);
}
/*
* Validates a single expression of kind:
* 1) EXPRESSION >= CONST
* 2) EXPRESSION < CONST
*/
static bool
validate_range_opexpr(const Expr *expr,
const PartRelationInfo *prel,
const TypeCacheEntry *tce,
Datum *lower, Datum *upper,
bool *lower_null, bool *upper_null)
{
const OpExpr *opexpr;
Datum val;
if (!expr)
return false;
/* Fail fast if it's not an OpExpr node */
if (!IsA(expr, OpExpr))
return false;
/* Perform cast */
opexpr = (const OpExpr *) expr;
/* Try reading Const value */
if (!read_opexpr_const(opexpr, prel, &val))
return false;
/* Examine the strategy (expect '>=' OR '<') */
switch (get_op_opfamily_strategy(opexpr->opno, tce->btree_opf))
{
case BTGreaterEqualStrategyNumber:
{
/* Bound already exists */
if (*lower_null == false)
return false;
*lower_null = false;
*lower = val;
return true;
}
case BTLessStrategyNumber:
{
/* Bound already exists */
if (*upper_null == false)
return false;
*upper_null = false;
*upper = val;
return true;
}
default:
return false;
}
}
/*
* Reads const value from expressions of kind:
* 1) EXPRESSION >= CONST
* 2) EXPRESSION < CONST
*/
static bool
read_opexpr_const(const OpExpr *opexpr,
const PartRelationInfo *prel,
Datum *value)
{
const Node *right;
const Const *boundary;
bool cast_success;
/* There should be exactly 2 args */
if (list_length(opexpr->args) != 2)
return false;
/* Fetch args of expression */
right = lsecond(opexpr->args);
/* Examine RIGHT argument */
switch (nodeTag(right))
{
case T_FuncExpr:
{
FuncExpr *func_expr = (FuncExpr *) right;
Const *constant;
/* This node should represent a type cast */
if (func_expr->funcformat != COERCE_EXPLICIT_CAST &&
func_expr->funcformat != COERCE_IMPLICIT_CAST)
return false;
/* This node should have exactly 1 argument */
if (list_length(func_expr->args) != 1)
return false;
/* Extract single argument */
constant = linitial(func_expr->args);
/* Argument should be a Const */
if (!IsA(constant, Const))
return false;
/* Update RIGHT */
right = (Node *) constant;
}
/* FALLTHROUGH */
case T_Const:
{
boundary = (Const *) right;
/* CONST is NOT NULL */
if (boundary->constisnull)
return false;
}
break;
default:
return false;
}
/* Cast Const to a proper type if needed */
*value = perform_type_cast(boundary->constvalue,
getBaseType(boundary->consttype),
getBaseType(prel->ev_type),
&cast_success);
if (!cast_success)
{
elog(WARNING, "constant type in some check constraint "
"does not match the partitioned column's type");
return false;
}
return true;
}
/*
* Validate hash constraint. It MUST have this exact format:
*
* get_hash_part_idx(TYPE_HASH_PROC(VALUE), PARTITIONS_COUNT) = CUR_PARTITION_IDX
*
* Writes 'part_idx' hash value for this partition on success.
*/
bool
validate_hash_constraint(const Expr *expr,
const PartRelationInfo *prel,
uint32 *part_idx)
{
const TypeCacheEntry *tce;
const OpExpr *eq_expr;
const FuncExpr *get_hash_expr,
*type_hash_proc_expr;
if (!expr)
return false;
if (!IsA(expr, OpExpr))
return false;
eq_expr = (const OpExpr *) expr;
/* Check that left expression is a function call */
if (!IsA(linitial(eq_expr->args), FuncExpr))
return false;
get_hash_expr = (FuncExpr *) linitial(eq_expr->args); /* get_hash_part_idx(...) */
/* Is 'eqexpr' an equality operator? */
tce = lookup_type_cache(get_hash_expr->funcresulttype, TYPECACHE_BTREE_OPFAMILY);
if (BTEqualStrategyNumber != get_op_opfamily_strategy(eq_expr->opno,