-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathrelation_info.c
1737 lines (1421 loc) · 41.7 KB
/
relation_info.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
/* ------------------------------------------------------------------------
*
* relation_info.c
* Data structures describing partitioned relations
*
* Copyright (c) 2016-2020, Postgres Professional
*
* ------------------------------------------------------------------------
*/
#include "compat/pg_compat.h"
#include "relation_info.h"
#include "init.h"
#include "utils.h"
#include "xact_handling.h"
#include "access/htup_details.h"
#if PG_VERSION_NUM >= 120000
#include "access/genam.h"
#include "access/table.h"
#endif
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/indexing.h"
#include "catalog/pg_constraint.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#if PG_VERSION_NUM >= 120000
#include "optimizer/optimizer.h"
#else
#include "optimizer/clauses.h"
#include "optimizer/var.h"
#endif
#include "parser/analyze.h"
#include "parser/parser.h"
#include "storage/lmgr.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/hsearch.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/resowner.h"
#include "utils/ruleutils.h"
#include "utils/syscache.h"
#include "utils/lsyscache.h"
#include "utils/typcache.h"
#if PG_VERSION_NUM < 90600
#include "optimizer/planmain.h"
#endif
#if PG_VERSION_NUM < 110000 && PG_VERSION_NUM >= 90600
#include "catalog/pg_constraint_fn.h"
#endif
/* Error messages for partitioning expression */
#define PARSE_PART_EXPR_ERROR "failed to parse partitioning expression \"%s\""
#define COOK_PART_EXPR_ERROR "failed to analyze partitioning expression \"%s\""
#ifdef USE_RELINFO_LEAK_TRACKER
#undef get_pathman_relation_info
#undef close_pathman_relation_info
const char *prel_resowner_function = NULL;
int prel_resowner_line = 0;
#define LeakTrackerAdd(prel) \
do { \
MemoryContext leak_tracker_add_old_mcxt = MemoryContextSwitchTo((prel)->mcxt); \
(prel)->owners = \
list_append_unique( \
(prel)->owners, \
list_make2(makeString((char *) prel_resowner_function), \
makeInteger(prel_resowner_line))); \
MemoryContextSwitchTo(leak_tracker_add_old_mcxt); \
\
(prel)->access_total++; \
} while (0)
#define LeakTrackerPrint(prel) \
do { \
ListCell *leak_tracker_print_lc; \
foreach (leak_tracker_print_lc, (prel)->owners) \
{ \
char *fun = strVal(linitial(lfirst(leak_tracker_print_lc))); \
int line = intVal(lsecond(lfirst(leak_tracker_print_lc))); \
elog(WARNING, "PartRelationInfo referenced in %s:%d", fun, line); \
} \
} while (0)
#define LeakTrackerFree(prel) \
do { \
ListCell *leak_tracker_free_lc; \
foreach (leak_tracker_free_lc, (prel)->owners) \
{ \
list_free_deep(lfirst(leak_tracker_free_lc)); \
} \
list_free((prel)->owners); \
(prel)->owners = NIL; \
} while (0)
#else
#define LeakTrackerAdd(prel)
#define LeakTrackerPrint(prel)
#define LeakTrackerFree(prel)
#endif
/* Comparison function info */
typedef struct cmp_func_info
{
FmgrInfo flinfo;
Oid collid;
} cmp_func_info;
typedef struct prel_resowner_info
{
ResourceOwner owner;
List *prels;
} prel_resowner_info;
/*
* For pg_pathman.enable_bounds_cache GUC.
*/
bool pg_pathman_enable_bounds_cache = true;
/*
* We delay all invalidation jobs received in relcache hook.
*/
static bool delayed_shutdown = false; /* pathman was dropped */
/*
* PartRelationInfo is controlled by ResourceOwner;
* resowner -> List of controlled PartRelationInfos by this ResourceOwner
*/
HTAB *prel_resowner = NULL;
/* Handy wrappers for Oids */
#define bsearch_oid(key, array, array_size) \
bsearch((const void *) &(key), (array), (array_size), sizeof(Oid), oid_cmp)
static PartRelationInfo *build_pathman_relation_info(Oid relid, Datum *values);
static void free_pathman_relation_info(PartRelationInfo *prel);
static void invalidate_psin_entries_using_relid(Oid relid);
static void invalidate_psin_entry(PartStatusInfo *psin);
static PartRelationInfo *resowner_prel_add(PartRelationInfo *prel);
static PartRelationInfo *resowner_prel_del(PartRelationInfo *prel);
static void resonwner_prel_callback(ResourceReleasePhase phase,
bool isCommit,
bool isTopLevel,
void *arg);
static void fill_prel_with_partitions(PartRelationInfo *prel,
const Oid *partitions,
const uint32 parts_count);
static void fill_pbin_with_bounds(PartBoundInfo *pbin,
const PartRelationInfo *prel,
const Expr *constraint_expr);
static int cmp_range_entries(const void *p1, const void *p2, void *arg);
static void forget_bounds_of_partition(Oid partition);
static bool query_contains_subqueries(Node *node, void *context);
void
init_relation_info_static_data(void)
{
DefineCustomBoolVariable("pg_pathman.enable_bounds_cache",
"Make updates of partition dispatch cache faster",
NULL,
&pg_pathman_enable_bounds_cache,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
}
/*
* Status cache routines.
*/
/* Invalidate PartStatusInfo for 'relid' */
void
forget_status_of_relation(Oid relid)
{
PartStatusInfo *psin;
PartParentInfo *ppar;
/* Find status cache entry for this relation */
psin = pathman_cache_search_relid(status_cache,
relid, HASH_FIND,
NULL);
if (psin)
invalidate_psin_entry(psin);
/*
* Find parent of this relation.
*
* We don't want to use get_parent_of_partition()
* since it relies upon the syscache.
*/
ppar = pathman_cache_search_relid(parents_cache,
relid, HASH_FIND,
NULL);
/* Invalidate parent directly */
if (ppar)
{
/* Find status cache entry for parent */
psin = pathman_cache_search_relid(status_cache,
ppar->parent_relid, HASH_FIND,
NULL);
if (psin)
invalidate_psin_entry(psin);
}
/* Otherwise, look through all entries */
else invalidate_psin_entries_using_relid(relid);
}
/* Invalidate all PartStatusInfo entries */
void
invalidate_status_cache(void)
{
invalidate_psin_entries_using_relid(InvalidOid);
}
/* Invalidate PartStatusInfo entry referencing 'relid' */
static void
invalidate_psin_entries_using_relid(Oid relid)
{
HASH_SEQ_STATUS status;
PartStatusInfo *psin;
hash_seq_init(&status, status_cache);
while ((psin = (PartStatusInfo *) hash_seq_search(&status)) != NULL)
{
if (!OidIsValid(relid) ||
psin->relid == relid ||
(psin->prel && PrelHasPartition(psin->prel, relid)))
{
/* Perform invalidation */
invalidate_psin_entry(psin);
/* Exit if exact match */
if (OidIsValid(relid))
{
hash_seq_term(&status);
break;
}
}
}
}
/* Invalidate single PartStatusInfo entry */
static void
invalidate_psin_entry(PartStatusInfo *psin)
{
#ifdef USE_RELINFO_LOGGING
elog(DEBUG2, "invalidation message for relation %u [%u]",
psin->relid, MyProcPid);
#endif
if (psin->prel)
{
if (PrelReferenceCount(psin->prel) > 0)
{
/* Mark entry as outdated and detach it */
PrelIsFresh(psin->prel) = false;
}
else
{
free_pathman_relation_info(psin->prel);
}
}
(void) pathman_cache_search_relid(status_cache,
psin->relid,
HASH_REMOVE,
NULL);
}
/*
* Dispatch cache routines.
*/
/* Close PartRelationInfo entry */
void
close_pathman_relation_info(PartRelationInfo *prel)
{
Assert(prel);
(void) resowner_prel_del(prel);
}
/* Check if relation is partitioned by pg_pathman */
bool
has_pathman_relation_info(Oid relid)
{
PartRelationInfo *prel;
if ((prel = get_pathman_relation_info(relid)) != NULL)
{
close_pathman_relation_info(prel);
return true;
}
return false;
}
/* Get PartRelationInfo from local cache */
PartRelationInfo *
get_pathman_relation_info(Oid relid)
{
PartStatusInfo *psin;
if (!IsPathmanReady())
elog(ERROR, "pg_pathman is disabled");
/* Should always be called in transaction */
Assert(IsTransactionState());
/* We don't create entries for catalog */
if (relid < FirstNormalObjectId)
return NULL;
/* Do we know anything about this relation? */
psin = pathman_cache_search_relid(status_cache,
relid, HASH_FIND,
NULL);
if (!psin)
{
PartRelationInfo *prel = NULL;
ItemPointerData iptr;
Datum values[Natts_pathman_config];
bool isnull[Natts_pathman_config];
bool found;
/*
* Check if PATHMAN_CONFIG table contains this relation and
* build a partitioned table cache entry (might emit ERROR).
*/
if (pathman_config_contains_relation(relid, values, isnull, NULL, &iptr))
prel = build_pathman_relation_info(relid, values);
/* Create a new entry for this relation */
psin = pathman_cache_search_relid(status_cache,
relid, HASH_ENTER,
&found);
Assert(!found); /* it shouldn't just appear out of thin air */
/* Cache fresh entry */
psin->prel = prel;
}
/* Check invariants */
Assert(!psin->prel || PrelIsFresh(psin->prel));
#ifdef USE_RELINFO_LOGGING
elog(DEBUG2,
"fetching %s record for parent %u [%u]",
(psin->prel ? "live" : "NULL"), relid, MyProcPid);
#endif
return resowner_prel_add(psin->prel);
}
/* Build a new PartRelationInfo for partitioned relation */
static PartRelationInfo *
build_pathman_relation_info(Oid relid, Datum *values)
{
const LOCKMODE lockmode = AccessShareLock;
MemoryContext prel_mcxt;
PartRelationInfo *prel;
AssertTemporaryContext();
/* Lock parent table */
LockRelationOid(relid, lockmode);
/* Check if parent exists */
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(relid)))
{
/* Nope, it doesn't, remove this entry and exit */
UnlockRelationOid(relid, lockmode);
return NULL; /* exit */
}
/* Create a new memory context to store expression tree etc */
prel_mcxt = AllocSetContextCreate(PathmanParentsCacheContext,
"build_pathman_relation_info",
ALLOCSET_SMALL_SIZES);
/* Create a new PartRelationInfo */
prel = MemoryContextAllocZero(prel_mcxt, sizeof(PartRelationInfo));
prel->relid = relid;
prel->refcount = 0;
prel->fresh = true;
prel->mcxt = prel_mcxt;
/* Memory leak and cache protection */
PG_TRY();
{
MemoryContext old_mcxt;
const TypeCacheEntry *typcache;
Datum param_values[Natts_pathman_config_params];
bool param_isnull[Natts_pathman_config_params];
Oid *prel_children;
uint32 prel_children_count = 0,
i;
/* Make both arrays point to NULL */
prel->children = NULL;
prel->ranges = NULL;
/* Set partitioning type */
prel->parttype = DatumGetPartType(values[Anum_pathman_config_parttype - 1]);
/* Switch to persistent memory context */
old_mcxt = MemoryContextSwitchTo(prel->mcxt);
/* Build partitioning expression tree */
prel->expr_cstr = TextDatumGetCString(values[Anum_pathman_config_expr - 1]);
prel->expr = cook_partitioning_expression(relid, prel->expr_cstr, NULL);
fix_opfuncids(prel->expr);
/* Extract Vars and varattnos of partitioning expression */
prel->expr_vars = NIL;
prel->expr_atts = NULL;
prel->expr_vars = pull_var_clause_compat(prel->expr, 0, 0);
pull_varattnos((Node *) prel->expr_vars, PART_EXPR_VARNO, &prel->expr_atts);
MemoryContextSwitchTo(old_mcxt);
/* First, fetch type of partitioning expression */
prel->ev_type = exprType(prel->expr);
prel->ev_typmod = exprTypmod(prel->expr);
prel->ev_collid = exprCollation(prel->expr);
/* Fetch HASH & CMP fuctions and other stuff from type cache */
typcache = lookup_type_cache(prel->ev_type,
TYPECACHE_CMP_PROC | TYPECACHE_HASH_PROC);
prel->ev_byval = typcache->typbyval;
prel->ev_len = typcache->typlen;
prel->ev_align = typcache->typalign;
prel->cmp_proc = typcache->cmp_proc;
prel->hash_proc = typcache->hash_proc;
/* Try searching for children */
(void) find_inheritance_children_array(relid, lockmode, false,
&prel_children_count,
&prel_children);
/* Fill 'prel' with partition info, raise ERROR if anything is wrong */
fill_prel_with_partitions(prel, prel_children, prel_children_count);
/* Unlock the parent */
UnlockRelationOid(relid, lockmode);
/* Now it's time to take care of children */
for (i = 0; i < prel_children_count; i++)
{
/* Cache this child */
cache_parent_of_partition(prel_children[i], relid);
/* Unlock this child */
UnlockRelationOid(prel_children[i], lockmode);
}
if (prel_children)
pfree(prel_children);
/* Read additional parameters ('enable_parent' at the moment) */
if (read_pathman_params(relid, param_values, param_isnull))
{
prel->enable_parent =
param_values[Anum_pathman_config_params_enable_parent - 1];
}
/* Else set default values if they cannot be found */
else
{
prel->enable_parent = DEFAULT_PATHMAN_ENABLE_PARENT;
}
}
PG_CATCH();
{
/*
* If we managed to create some children but failed later, bounds
* cache now might have obsolete data for something that probably is
* not a partitioned table at all. Remove it.
*/
if (!IsPathmanInitialized())
/*
* ... unless failure was so hard that caches were already destoyed,
* i.e. extension disabled
*/
PG_RE_THROW();
if (prel->children != NULL)
{
uint32 i;
for (i = 0; i < PrelChildrenCount(prel); i++)
{
Oid child;
/*
* We rely on children and ranges array allocated with 0s, not
* random data
*/
if (prel->parttype == PT_HASH)
child = prel->children[i];
else
{
Assert(prel->parttype == PT_RANGE);
child = prel->ranges[i].child_oid;
}
forget_bounds_of_partition(child);
}
}
/* Free this entry */
free_pathman_relation_info(prel);
/* Rethrow ERROR further */
PG_RE_THROW();
}
PG_END_TRY();
/* Free trivial entries */
if (PrelChildrenCount(prel) == 0)
{
free_pathman_relation_info(prel);
prel = NULL;
}
return prel;
}
/* Free PartRelationInfo struct safely */
static void
free_pathman_relation_info(PartRelationInfo *prel)
{
MemoryContextDelete(prel->mcxt);
}
static PartRelationInfo *
resowner_prel_add(PartRelationInfo *prel)
{
if (!prel_resowner)
{
HASHCTL ctl;
memset(&ctl, 0, sizeof(ctl));
ctl.keysize = sizeof(ResourceOwner);
ctl.entrysize = sizeof(prel_resowner_info);
ctl.hcxt = TopPathmanContext;
prel_resowner = hash_create("prel resowner",
PART_RELS_SIZE, &ctl,
HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
RegisterResourceReleaseCallback(resonwner_prel_callback, NULL);
}
if (prel)
{
ResourceOwner resowner = CurrentResourceOwner;
prel_resowner_info *info;
bool found;
MemoryContext old_mcxt;
info = hash_search(prel_resowner,
(void *) &resowner,
HASH_ENTER,
&found);
if (!found)
info->prels = NIL;
/* Register this 'prel' */
old_mcxt = MemoryContextSwitchTo(TopPathmanContext);
info->prels = lappend(info->prels, prel);
MemoryContextSwitchTo(old_mcxt);
/* Save current caller (function:line) */
LeakTrackerAdd(prel);
/* Finally, increment refcount */
PrelReferenceCount(prel) += 1;
}
return prel;
}
static PartRelationInfo *
resowner_prel_del(PartRelationInfo *prel)
{
/* Must be active! */
Assert(prel_resowner);
if (prel)
{
ResourceOwner resowner = CurrentResourceOwner;
prel_resowner_info *info;
info = hash_search(prel_resowner,
(void *) &resowner,
HASH_FIND,
NULL);
if (info)
{
/* Check that 'prel' is registered! */
Assert(list_member_ptr(info->prels, prel));
/* Remove it from list */
info->prels = list_delete_ptr(info->prels, prel);
}
/* Check that refcount is valid */
Assert(PrelReferenceCount(prel) > 0);
/* Decrease refcount */
PrelReferenceCount(prel) -= 1;
/* Free list of owners */
if (PrelReferenceCount(prel) == 0)
{
LeakTrackerFree(prel);
}
/* Free this entry if it's time */
if (PrelReferenceCount(prel) == 0 && !PrelIsFresh(prel))
{
free_pathman_relation_info(prel);
}
}
return prel;
}
static void
resonwner_prel_callback(ResourceReleasePhase phase,
bool isCommit,
bool isTopLevel,
void *arg)
{
ResourceOwner resowner = CurrentResourceOwner;
prel_resowner_info *info;
if (prel_resowner)
{
ListCell *lc;
info = hash_search(prel_resowner,
(void *) &resowner,
HASH_FIND,
NULL);
if (info)
{
foreach (lc, info->prels)
{
PartRelationInfo *prel = lfirst(lc);
if (isCommit)
{
/* Print verbose list of *possible* owners */
LeakTrackerPrint(prel);
elog(WARNING,
"cache reference leak: PartRelationInfo(%d) has count %d",
PrelParentRelid(prel), PrelReferenceCount(prel));
}
/* Check that refcount is valid */
Assert(PrelReferenceCount(prel) > 0);
/* Decrease refcount */
PrelReferenceCount(prel) -= 1;
/* Free list of owners */
LeakTrackerFree(prel);
/* Free this entry if it's time */
if (PrelReferenceCount(prel) == 0 && !PrelIsFresh(prel))
{
free_pathman_relation_info(prel);
}
}
list_free(info->prels);
hash_search(prel_resowner,
(void *) &resowner,
HASH_REMOVE,
NULL);
}
}
}
/* Fill PartRelationInfo with partition-related info */
static void
fill_prel_with_partitions(PartRelationInfo *prel,
const Oid *partitions,
const uint32 parts_count)
{
/* Allocate array if partitioning type matches 'prel' (or "ANY") */
#define AllocZeroArray(part_type, context, elem_num, elem_type) \
( \
((part_type) == PT_ANY || (part_type) == prel->parttype) ? \
MemoryContextAllocZero((context), (elem_num) * sizeof(elem_type)) : \
NULL \
)
uint32 i;
MemoryContext temp_mcxt, /* reference temporary mcxt */
old_mcxt; /* reference current mcxt */
AssertTemporaryContext();
/* Allocate memory for 'prel->children' & 'prel->ranges' (if needed) */
prel->children = AllocZeroArray(PT_ANY, prel->mcxt, parts_count, Oid);
prel->ranges = AllocZeroArray(PT_RANGE, prel->mcxt, parts_count, RangeEntry);
/* Set number of children */
PrelChildrenCount(prel) = parts_count;
/* Create temporary memory context for loop */
temp_mcxt = AllocSetContextCreate(CurrentMemoryContext,
CppAsString(fill_prel_with_partitions),
ALLOCSET_SMALL_SIZES);
/* Initialize bounds of partitions */
for (i = 0; i < PrelChildrenCount(prel); i++)
{
PartBoundInfo *pbin;
/* Clear all previous allocations */
MemoryContextReset(temp_mcxt);
/* Switch to the temporary memory context */
old_mcxt = MemoryContextSwitchTo(temp_mcxt);
{
/* Fetch constraint's expression tree */
pbin = get_bounds_of_partition(partitions[i], prel);
}
MemoryContextSwitchTo(old_mcxt);
/* Copy bounds from bound cache */
switch (prel->parttype)
{
case PT_HASH:
/*
* This might be the case if hash part was dropped, and thus
* children array alloc'ed smaller than needed, but parts
* bound cache still keeps entries with high indexes.
*/
if (pbin->part_idx >= PrelChildrenCount(prel))
{
/* purged caches will destoy prel, save oid for reporting */
Oid parent_relid = PrelParentRelid(prel);
DisablePathman(); /* disable pg_pathman since config is broken */
ereport(ERROR, (errmsg("pg_pathman's cache for relation %d "
"has not been properly initialized. "
"Looks like one of hash partitions was dropped.",
parent_relid),
errhint(INIT_ERROR_HINT)));
}
prel->children[pbin->part_idx] = pbin->child_relid;
break;
case PT_RANGE:
{
/* Copy child's Oid */
prel->ranges[i].child_oid = pbin->child_relid;
/* Copy all min & max Datums to the persistent mcxt */
old_mcxt = MemoryContextSwitchTo(prel->mcxt);
{
prel->ranges[i].min = CopyBound(&pbin->range_min,
prel->ev_byval,
prel->ev_len);
prel->ranges[i].max = CopyBound(&pbin->range_max,
prel->ev_byval,
prel->ev_len);
}
MemoryContextSwitchTo(old_mcxt);
}
break;
default:
{
DisablePathman(); /* disable pg_pathman since config is broken */
WrongPartType(prel->parttype);
}
break;
}
}
/* Drop temporary memory context */
MemoryContextDelete(temp_mcxt);
/* Finalize 'prel' for a RANGE-partitioned table */
if (prel->parttype == PT_RANGE)
{
qsort_range_entries(PrelGetRangesArray(prel),
PrelChildrenCount(prel),
prel);
/* Initialize 'prel->children' array */
for (i = 0; i < PrelChildrenCount(prel); i++)
prel->children[i] = prel->ranges[i].child_oid;
}
/* Check that each partition Oid has been assigned properly */
if (prel->parttype == PT_HASH)
for (i = 0; i < PrelChildrenCount(prel); i++)
{
if (!OidIsValid(prel->children[i]))
{
DisablePathman(); /* disable pg_pathman since config is broken */
ereport(ERROR, (errmsg("pg_pathman's cache for relation \"%s\" "
"has not been properly initialized",
get_rel_name_or_relid(PrelParentRelid(prel))),
errhint(INIT_ERROR_HINT)));
}
}
}
/* qsort() comparison function for RangeEntries */
static int
cmp_range_entries(const void *p1, const void *p2, void *arg)
{
const RangeEntry *v1 = (const RangeEntry *) p1;
const RangeEntry *v2 = (const RangeEntry *) p2;
cmp_func_info *info = (cmp_func_info *) arg;
return cmp_bounds(&info->flinfo, info->collid, &v1->min, &v2->min);
}
void
qsort_range_entries(RangeEntry *entries, int nentries,
const PartRelationInfo *prel)
{
cmp_func_info cmp_info;
/* Prepare function info */
fmgr_info(prel->cmp_proc, &cmp_info.flinfo);
cmp_info.collid = prel->ev_collid;
/* Sort partitions by RangeEntry->min asc */
qsort_arg(entries, nentries,
sizeof(RangeEntry),
cmp_range_entries,
(void *) &cmp_info);
}
/*
* Common PartRelationInfo checks. Emit ERROR if anything is wrong.
*/
void
shout_if_prel_is_invalid(const Oid parent_oid,
const PartRelationInfo *prel,
const PartType expected_part_type)
{
if (!prel)
elog(ERROR, "relation \"%s\" has no partitions",
get_rel_name_or_relid(parent_oid));
/* Check partitioning type unless it's "ANY" */
if (expected_part_type != PT_ANY &&
expected_part_type != prel->parttype)
{
char *expected_str;
switch (expected_part_type)
{
case PT_HASH:
expected_str = "HASH";
break;
case PT_RANGE:
expected_str = "RANGE";
break;
default:
WrongPartType(expected_part_type);
expected_str = NULL; /* keep compiler happy */
}
elog(ERROR, "relation \"%s\" is not partitioned by %s",
get_rel_name_or_relid(parent_oid),
expected_str);
}
}
/*
* Remap partitioning expression columns for tuple source relation.
* This is a simplified version of functions that return TupleConversionMap.
* It should be faster if expression uses a few fields of relation.
*/
#if PG_VERSION_NUM >= 130000
AttrMap *
PrelExpressionAttributesMap(const PartRelationInfo *prel,
TupleDesc source_tupdesc)
#else
AttrNumber *
PrelExpressionAttributesMap(const PartRelationInfo *prel,
TupleDesc source_tupdesc,
int *map_length)
#endif
{
Oid parent_relid = PrelParentRelid(prel);
int source_natts = source_tupdesc->natts,
expr_natts = 0;
#if PG_VERSION_NUM >= 130000
AttrMap *result;
#else
AttrNumber *result;
#endif
AttrNumber i;
bool is_trivial = true;
/* Get largest attribute number used in expression */
i = -1;
while ((i = bms_next_member(prel->expr_atts, i)) >= 0)
expr_natts = i;
#if PG_VERSION_NUM >= 130000
result = make_attrmap(expr_natts);
#else
/* Allocate array for map */
result = (AttrNumber *) palloc0(expr_natts * sizeof(AttrNumber));
#endif
/* Find a match for each attribute */
i = -1;
while ((i = bms_next_member(prel->expr_atts, i)) >= 0)
{
AttrNumber attnum = i + FirstLowInvalidHeapAttributeNumber;
char *attname = get_attname_compat(parent_relid, attnum);
int j;
Assert(attnum <= expr_natts);
for (j = 0; j < source_natts; j++)
{
Form_pg_attribute att = TupleDescAttr(source_tupdesc, j);
if (att->attisdropped)
continue; /* attrMap[attnum - 1] is already 0 */
if (strcmp(NameStr(att->attname), attname) == 0)
{
#if PG_VERSION_NUM >= 130000
result->attnums[attnum - 1] = (AttrNumber) (j + 1);
#else
result[attnum - 1] = (AttrNumber) (j + 1);
#endif
break;
}
}
#if PG_VERSION_NUM >= 130000
if (result->attnums[attnum - 1] == 0)
#else
if (result[attnum - 1] == 0)
#endif
elog(ERROR, "cannot find column \"%s\" in child relation", attname);
#if PG_VERSION_NUM >= 130000
if (result->attnums[attnum - 1] != attnum)
#else
if (result[attnum - 1] != attnum)