-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathpartition_filter.c
1614 lines (1338 loc) · 47.8 KB
/
partition_filter.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
/* ------------------------------------------------------------------------
*
* partition_filter.c
* Select partition for INSERT operation
*
* Copyright (c) 2016-2020, Postgres Professional
*
* ------------------------------------------------------------------------
*/
#include "compat/pg_compat.h"
#include "init.h"
#include "nodes_common.h"
#include "pathman.h"
#include "partition_creation.h"
#include "partition_filter.h"
#include "partition_router.h"
#include "utils.h"
#include "access/htup_details.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "access/xact.h"
#include "catalog/pg_class.h"
#include "catalog/pg_type.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "nodes/nodeFuncs.h"
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
#include "parser/parse_relation.h"
#endif
#include "rewrite/rewriteManip.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
#define ALLOC_EXP 2
/*
* HACK: 'estate->es_query_cxt' as data storage
*
* We use this struct as an argument for fake
* MemoryContextCallback pf_memcxt_callback()
* in order to attach some additional info to
* EState (estate->es_query_cxt is involved).
*/
typedef struct
{
int estate_alloc_result_rels; /* number of allocated result rels */
bool estate_not_modified; /* did we modify EState somehow? */
} estate_mod_data;
/*
* Allow INSERTs into any FDW \ postgres_fdw \ no FDWs at all.
*/
typedef enum
{
PF_FDW_INSERT_DISABLED = 0, /* INSERTs into FDWs are prohibited */
PF_FDW_INSERT_POSTGRES, /* INSERTs into postgres_fdw are OK */
PF_FDW_INSERT_ANY_FDW /* INSERTs into any FDWs are OK */
} PF_insert_fdw_mode;
static const struct config_enum_entry pg_pathman_insert_into_fdw_options[] = {
{ "disabled", PF_FDW_INSERT_DISABLED, false },
{ "postgres", PF_FDW_INSERT_POSTGRES, false },
{ "any_fdw", PF_FDW_INSERT_ANY_FDW, false },
{ NULL, 0, false }
};
bool pg_pathman_enable_partition_filter = true;
int pg_pathman_insert_into_fdw = PF_FDW_INSERT_POSTGRES;
CustomScanMethods partition_filter_plan_methods;
CustomExecMethods partition_filter_exec_methods;
static ExprState *prepare_expr_state(const PartRelationInfo *prel,
Relation source_rel,
EState *estate);
static void prepare_rri_for_insert(ResultRelInfoHolder *rri_holder,
const ResultPartsStorage *rps_storage);
static void prepare_rri_returning_for_insert(ResultRelInfoHolder *rri_holder,
const ResultPartsStorage *rps_storage);
static void prepare_rri_fdw_for_insert(ResultRelInfoHolder *rri_holder,
const ResultPartsStorage *rps_storage);
static Node *fix_returning_list_mutator(Node *node, void *state);
static Index append_rte_to_estate(EState *estate, RangeTblEntry *rte, Relation child_rel);
static int append_rri_to_estate(EState *estate, ResultRelInfo *rri);
static void pf_memcxt_callback(void *arg);
static estate_mod_data * fetch_estate_mod_data(EState *estate);
void
init_partition_filter_static_data(void)
{
partition_filter_plan_methods.CustomName = INSERT_NODE_NAME;
partition_filter_plan_methods.CreateCustomScanState = partition_filter_create_scan_state;
partition_filter_exec_methods.CustomName = INSERT_NODE_NAME;
partition_filter_exec_methods.BeginCustomScan = partition_filter_begin;
partition_filter_exec_methods.ExecCustomScan = partition_filter_exec;
partition_filter_exec_methods.EndCustomScan = partition_filter_end;
partition_filter_exec_methods.ReScanCustomScan = partition_filter_rescan;
partition_filter_exec_methods.MarkPosCustomScan = NULL;
partition_filter_exec_methods.RestrPosCustomScan = NULL;
partition_filter_exec_methods.ExplainCustomScan = partition_filter_explain;
DefineCustomBoolVariable("pg_pathman.enable_partitionfilter",
"Enables the planner's use of " INSERT_NODE_NAME " custom node.",
NULL,
&pg_pathman_enable_partition_filter,
true,
PGC_USERSET,
0,
NULL,
NULL,
NULL);
DefineCustomEnumVariable("pg_pathman.insert_into_fdw",
"Allow INSERTS into FDW partitions.",
NULL,
&pg_pathman_insert_into_fdw,
PF_FDW_INSERT_POSTGRES,
pg_pathman_insert_into_fdw_options,
PGC_SUSET,
0,
NULL,
NULL,
NULL);
RegisterCustomScanMethods(&partition_filter_plan_methods);
}
/*
* ---------------------------
* Partition Storage (cache)
* ---------------------------
*/
/* Initialize ResultPartsStorage (hash table etc) */
void
init_result_parts_storage(ResultPartsStorage *parts_storage,
Oid parent_relid,
ResultRelInfo *current_rri,
EState *estate,
CmdType cmd_type,
bool close_relations,
bool speculative_inserts,
rri_holder_cb init_rri_holder_cb,
void *init_rri_holder_cb_arg,
rri_holder_cb fini_rri_holder_cb,
void *fini_rri_holder_cb_arg)
{
HASHCTL *result_rels_table_config = &parts_storage->result_rels_table_config;
memset(result_rels_table_config, 0, sizeof(HASHCTL));
result_rels_table_config->keysize = sizeof(Oid);
result_rels_table_config->entrysize = sizeof(ResultPartsStorage);
parts_storage->result_rels_table = hash_create("ResultRelInfo storage", 10,
result_rels_table_config,
HASH_ELEM | HASH_BLOBS);
Assert(current_rri);
parts_storage->base_rri = current_rri;
Assert(estate);
parts_storage->estate = estate;
/* ResultRelInfoHolder initialization callback */
parts_storage->init_rri_holder_cb = init_rri_holder_cb;
parts_storage->init_rri_holder_cb_arg = init_rri_holder_cb_arg;
/* ResultRelInfoHolder finalization callback */
parts_storage->fini_rri_holder_cb = fini_rri_holder_cb;
parts_storage->fini_rri_holder_cb_arg = fini_rri_holder_cb_arg;
Assert(cmd_type == CMD_INSERT || cmd_type == CMD_UPDATE);
parts_storage->command_type = cmd_type;
parts_storage->speculative_inserts = speculative_inserts;
/*
* Should ResultPartsStorage do ExecCloseIndices and heap_close on
* finalization?
*/
parts_storage->close_relations = close_relations;
parts_storage->head_open_lock_mode = RowExclusiveLock;
/* Fetch PartRelationInfo for this partitioned relation */
parts_storage->prel = get_pathman_relation_info(parent_relid);
shout_if_prel_is_invalid(parent_relid, parts_storage->prel, PT_ANY);
/* Build a partitioning expression state */
parts_storage->prel_expr_state = prepare_expr_state(parts_storage->prel,
parts_storage->base_rri->ri_RelationDesc,
parts_storage->estate);
/* Build expression context */
parts_storage->prel_econtext = CreateExprContext(parts_storage->estate);
}
/* Free ResultPartsStorage (close relations etc) */
void
fini_result_parts_storage(ResultPartsStorage *parts_storage)
{
HASH_SEQ_STATUS stat;
ResultRelInfoHolder *rri_holder; /* ResultRelInfo holder */
hash_seq_init(&stat, parts_storage->result_rels_table);
while ((rri_holder = (ResultRelInfoHolder *) hash_seq_search(&stat)) != NULL)
{
/* Call finalization callback if needed */
if (parts_storage->fini_rri_holder_cb)
parts_storage->fini_rri_holder_cb(rri_holder, parts_storage);
/*
* Close indices, unless ExecEndPlan won't do that for us (this is
* is CopyFrom which misses it, not usual executor run, essentially).
* Otherwise, it is always automaticaly closed; in <= 11, relcache
* refs of rris managed heap_open/close on their own, and ExecEndPlan
* closed them directly. Since 9ddef3, relcache management
* of executor was centralized; now rri refs are copies of ones in
* estate->es_relations, which are closed in ExecEndPlan.
* So we push our rel there, and it is also automatically closed.
*/
if (parts_storage->close_relations)
{
ExecCloseIndices(rri_holder->result_rel_info);
/* And relation itself */
heap_close_compat(rri_holder->result_rel_info->ri_RelationDesc,
NoLock);
}
/* Free conversion-related stuff */
destroy_tuple_map(rri_holder->tuple_map);
destroy_tuple_map(rri_holder->tuple_map_child);
/* Don't forget to close 'prel'! */
if (rri_holder->prel)
close_pathman_relation_info(rri_holder->prel);
}
/* Finally destroy hash table */
hash_destroy(parts_storage->result_rels_table);
/* Don't forget to close 'prel'! */
close_pathman_relation_info(parts_storage->prel);
}
/* Find a ResultRelInfo for the partition using ResultPartsStorage */
ResultRelInfoHolder *
scan_result_parts_storage(EState *estate, ResultPartsStorage *parts_storage,
Oid partid)
{
#define CopyToResultRelInfo(field_name) \
( child_result_rel_info->field_name = parts_storage->base_rri->field_name )
ResultRelInfoHolder *rri_holder;
bool found;
rri_holder = hash_search(parts_storage->result_rels_table,
(const void *) &partid,
HASH_FIND, &found);
/* If not found, create & cache new ResultRelInfo */
if (!found)
{
Relation child_rel,
base_rel;
RangeTblEntry *child_rte,
*parent_rte;
Index child_rte_idx;
ResultRelInfo *child_result_rel_info;
List *translated_vars;
MemoryContext old_mcxt;
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
RTEPermissionInfo *parent_perminfo,
*child_perminfo;
/* ResultRelInfo of partitioned table. */
RangeTblEntry *init_rte;
#endif
/* Lock partition and check if it exists */
LockRelationOid(partid, parts_storage->head_open_lock_mode);
if (!SearchSysCacheExists1(RELOID, ObjectIdGetDatum(partid)))
{
UnlockRelationOid(partid, parts_storage->head_open_lock_mode);
return NULL;
}
/* Switch to query-level mcxt for allocations */
old_mcxt = MemoryContextSwitchTo(parts_storage->estate->es_query_cxt);
/* Create a new cache entry for this partition */
rri_holder = hash_search(parts_storage->result_rels_table,
(const void *) &partid,
HASH_ENTER, NULL);
parent_rte = rt_fetch(parts_storage->base_rri->ri_RangeTableIndex,
parts_storage->estate->es_range_table);
/* Get base relation */
base_rel = parts_storage->base_rri->ri_RelationDesc;
/* Open child relation and check if it is a valid target */
child_rel = heap_open_compat(partid, NoLock);
/* Create RangeTblEntry for partition */
child_rte = makeNode(RangeTblEntry);
child_rte->rtekind = RTE_RELATION;
child_rte->relid = partid;
child_rte->relkind = child_rel->rd_rel->relkind;
child_rte->eref = parent_rte->eref;
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
/* Build Var translation list for 'inserted_cols' */
make_inh_translation_list(parts_storage->init_rri->ri_RelationDesc,
child_rel, 0, &translated_vars, NULL);
/*
* Need to use ResultRelInfo of partitioned table 'init_rri' because
* 'base_rri' can be ResultRelInfo of partition without any
* ResultRelInfo, see expand_single_inheritance_child().
*/
init_rte = rt_fetch(parts_storage->init_rri->ri_RangeTableIndex,
parts_storage->estate->es_range_table);
parent_perminfo = getRTEPermissionInfo(estate->es_rteperminfos, init_rte);
child_rte->perminfoindex = 0; /* expected by addRTEPermissionInfo() */
child_perminfo = addRTEPermissionInfo(&estate->es_rteperminfos, child_rte);
child_perminfo->requiredPerms = parent_perminfo->requiredPerms;
child_perminfo->checkAsUser = parent_perminfo->checkAsUser;
child_perminfo->insertedCols = translate_col_privs(parent_perminfo->insertedCols,
translated_vars);
child_perminfo->updatedCols = translate_col_privs(parent_perminfo->updatedCols,
translated_vars);
/* Check permissions for one partition */
ExecCheckOneRtePermissions(child_rte, child_perminfo, true);
#else
/* Build Var translation list for 'inserted_cols' */
make_inh_translation_list(base_rel, child_rel, 0, &translated_vars, NULL);
child_rte->requiredPerms = parent_rte->requiredPerms;
child_rte->checkAsUser = parent_rte->checkAsUser;
child_rte->insertedCols = translate_col_privs(parent_rte->insertedCols,
translated_vars);
child_rte->updatedCols = translate_col_privs(parent_rte->updatedCols,
translated_vars);
/* Check permissions for partition */
ExecCheckRTPerms(list_make1(child_rte), true);
#endif
/* Append RangeTblEntry to estate->es_range_table */
child_rte_idx = append_rte_to_estate(parts_storage->estate, child_rte, child_rel);
/* Create ResultRelInfo for partition */
child_result_rel_info = makeNode(ResultRelInfo);
InitResultRelInfoCompat(child_result_rel_info,
child_rel,
child_rte_idx,
parts_storage->estate->es_instrument);
if (parts_storage->command_type != CMD_DELETE)
ExecOpenIndices(child_result_rel_info, parts_storage->speculative_inserts);
/* Copy necessary fields from saved ResultRelInfo */
CopyToResultRelInfo(ri_WithCheckOptions);
CopyToResultRelInfo(ri_WithCheckOptionExprs);
CopyToResultRelInfo(ri_projectReturning);
#if PG_VERSION_NUM >= 110000
CopyToResultRelInfo(ri_onConflict);
#else
CopyToResultRelInfo(ri_onConflictSetProj);
CopyToResultRelInfo(ri_onConflictSetWhere);
#endif
#if PG_VERSION_NUM < 140000
/* field "ri_junkFilter" removed in 86dc90056dfd */
if (parts_storage->command_type != CMD_UPDATE)
CopyToResultRelInfo(ri_junkFilter);
else
child_result_rel_info->ri_junkFilter = NULL;
#endif
/* ri_ConstraintExprs will be initialized by ExecRelCheck() */
child_result_rel_info->ri_ConstraintExprs = NULL;
/* Check that this partition is a valid result relation */
CheckValidResultRelCompat(child_result_rel_info,
parts_storage->command_type);
/* Fill the ResultRelInfo holder */
rri_holder->partid = partid;
rri_holder->result_rel_info = child_result_rel_info;
/*
* Generate parent->child tuple transformation map. We need to
* convert tuples because e.g. parent's TupleDesc might have dropped
* columns which child doesn't have at all because it was created after
* the drop.
*/
rri_holder->tuple_map = build_part_tuple_map(base_rel, child_rel);
/*
* Field for child->child tuple transformation map. We need to
* convert tuples because child TupleDesc might have extra
* columns ('ctid' etc.) and need remove them.
*/
rri_holder->tuple_map_child = NULL;
/* Default values */
rri_holder->prel = NULL;
rri_holder->prel_expr_state = NULL;
if ((rri_holder->prel = get_pathman_relation_info(partid)) != NULL)
{
rri_holder->prel_expr_state =
prepare_expr_state(rri_holder->prel, /* NOTE: this prel! */
parts_storage->base_rri->ri_RelationDesc,
parts_storage->estate);
}
/* Call initialization callback if needed */
if (parts_storage->init_rri_holder_cb)
parts_storage->init_rri_holder_cb(rri_holder, parts_storage);
/* Append ResultRelInfo to storage->es_alloc_result_rels */
append_rri_to_estate(parts_storage->estate, child_result_rel_info);
/* Don't forget to switch back! */
MemoryContextSwitchTo(old_mcxt);
}
return rri_holder;
}
/* Refresh PartRelationInfo for the partition in storage */
PartRelationInfo *
refresh_result_parts_storage(ResultPartsStorage *parts_storage, Oid partid)
{
if (partid == PrelParentRelid(parts_storage->prel))
{
close_pathman_relation_info(parts_storage->prel);
parts_storage->prel = get_pathman_relation_info(partid);
shout_if_prel_is_invalid(partid, parts_storage->prel, PT_ANY);
return parts_storage->prel;
}
else
{
ResultRelInfoHolder *rri_holder;
rri_holder = hash_search(parts_storage->result_rels_table,
(const void *) &partid,
HASH_FIND, NULL);
/* We must have entry (since we got 'prel' from it) */
Assert(rri_holder && rri_holder->prel);
close_pathman_relation_info(rri_holder->prel);
rri_holder->prel = get_pathman_relation_info(partid);
shout_if_prel_is_invalid(partid, rri_holder->prel, PT_ANY);
return rri_holder->prel;
}
}
/* Build tuple conversion map (e.g. parent has a dropped column) */
TupleConversionMap *
build_part_tuple_map(Relation base_rel, Relation child_rel)
{
TupleConversionMap *tuple_map;
TupleDesc child_tupdesc,
parent_tupdesc;
/* HACK: use fake 'tdtypeid' in order to fool convert_tuples_by_name() */
child_tupdesc = CreateTupleDescCopy(RelationGetDescr(child_rel));
child_tupdesc->tdtypeid = InvalidOid;
parent_tupdesc = CreateTupleDescCopy(RelationGetDescr(base_rel));
parent_tupdesc->tdtypeid = InvalidOid;
/* Generate tuple transformation map and some other stuff */
tuple_map = convert_tuples_by_name_compat(parent_tupdesc,
child_tupdesc,
ERR_PART_DESC_CONVERT);
/* If map is one-to-one, free unused TupleDescs */
if (!tuple_map)
{
FreeTupleDesc(child_tupdesc);
FreeTupleDesc(parent_tupdesc);
}
return tuple_map;
}
/*
* Build tuple conversion map (e.g. partition tuple has extra column(s)).
* We create a special tuple map (tuple_map_child), which, when applied to the
* tuple of partition, translates the tuple attributes into the tuple
* attributes of the same partition, discarding service attributes like "ctid"
* (i.e. working like junkFilter).
*/
TupleConversionMap *
build_part_tuple_map_child(Relation child_rel)
{
TupleConversionMap *tuple_map;
TupleDesc child_tupdesc1;
TupleDesc child_tupdesc2;
int n;
#if PG_VERSION_NUM >= 130000
AttrMap *attrMap;
#else
AttrNumber *attrMap;
#endif
child_tupdesc1 = CreateTupleDescCopy(RelationGetDescr(child_rel));
child_tupdesc1->tdtypeid = InvalidOid;
child_tupdesc2 = CreateTupleDescCopy(RelationGetDescr(child_rel));
child_tupdesc2->tdtypeid = InvalidOid;
/* Generate tuple transformation map */
#if PG_VERSION_NUM >= 160000 /* for commit ad86d159b6ab */
attrMap = build_attrmap_by_name(child_tupdesc1, child_tupdesc2, false);
#elif PG_VERSION_NUM >= 130000
attrMap = build_attrmap_by_name(child_tupdesc1, child_tupdesc2);
#else
attrMap = convert_tuples_by_name_map(child_tupdesc1, child_tupdesc2,
ERR_PART_DESC_CONVERT);
#endif
/* Prepare the map structure */
tuple_map = (TupleConversionMap *) palloc(sizeof(TupleConversionMap));
tuple_map->indesc = child_tupdesc1;
tuple_map->outdesc = child_tupdesc2;
tuple_map->attrMap = attrMap;
/* preallocate workspace for Datum arrays */
n = child_tupdesc1->natts;
tuple_map->outvalues = (Datum *) palloc(n * sizeof(Datum));
tuple_map->outisnull = (bool *) palloc(n * sizeof(bool));
n = child_tupdesc1->natts + 1; /* +1 for NULL */
tuple_map->invalues = (Datum *) palloc(n * sizeof(Datum));
tuple_map->inisnull = (bool *) palloc(n * sizeof(bool));
tuple_map->invalues[0] = (Datum) 0; /* set up the NULL entry */
tuple_map->inisnull[0] = true;
return tuple_map;
}
/* Destroy tuple conversion map */
void
destroy_tuple_map(TupleConversionMap *tuple_map)
{
if (tuple_map)
{
FreeTupleDesc(tuple_map->indesc);
FreeTupleDesc(tuple_map->outdesc);
free_conversion_map(tuple_map);
}
}
/*
* -----------------------------------
* Partition search helper functions
* -----------------------------------
*/
/*
* Find matching partitions for 'value' using PartRelationInfo.
*/
Oid *
find_partitions_for_value(Datum value, Oid value_type,
const PartRelationInfo *prel,
int *nparts)
{
#define CopyToTempConst(const_field, attr_field) \
( temp_const.const_field = prel->attr_field )
Const temp_const; /* temporary const for expr walker */
WalkerContext wcxt;
List *ranges = NIL;
/* Prepare dummy Const node */
NodeSetTag(&temp_const, T_Const);
temp_const.location = -1;
/* Fill const with value ... */
temp_const.constvalue = value;
temp_const.consttype = value_type;
temp_const.constisnull = false;
/* ... and some other important data */
CopyToTempConst(consttypmod, ev_typmod);
CopyToTempConst(constcollid, ev_collid);
CopyToTempConst(constlen, ev_len);
CopyToTempConst(constbyval, ev_byval);
/* We use 0 since varno doesn't matter for Const */
InitWalkerContext(&wcxt, 0, prel, NULL);
ranges = walk_expr_tree((Expr *) &temp_const, &wcxt)->rangeset;
return get_partition_oids(ranges, nparts, prel, false);
}
/*
* Smart wrapper for scan_result_parts_storage().
*/
ResultRelInfoHolder *
select_partition_for_insert(EState *estate,
ResultPartsStorage *parts_storage,
TupleTableSlot *slot)
{
PartRelationInfo *prel = parts_storage->prel;
ExprState *expr_state = parts_storage->prel_expr_state;
ExprContext *expr_context = parts_storage->prel_econtext;
Oid parent_relid = PrelParentRelid(prel),
partition_relid = InvalidOid;
Datum value;
bool isnull;
bool compute_value = true;
Oid *parts;
int nparts;
ResultRelInfoHolder *result;
do
{
if (compute_value)
{
/* Prepare expression context */
ResetExprContext(expr_context);
expr_context->ecxt_scantuple = slot;
/* Execute expression */
value = ExecEvalExprCompat(expr_state, expr_context, &isnull);
if (isnull)
elog(ERROR, ERR_PART_ATTR_NULL);
/* Ok, we have a value */
compute_value = false;
}
/* Search for matching partitions */
parts = find_partitions_for_value(value, prel->ev_type, prel, &nparts);
if (nparts > 1)
{
elog(ERROR, ERR_PART_ATTR_MULTIPLE);
}
else if (nparts == 0)
{
partition_relid = create_partitions_for_value(parent_relid,
value, prel->ev_type);
}
else partition_relid = parts[0];
/* Get ResultRelationInfo holder for the selected partition */
result = scan_result_parts_storage(estate, parts_storage, partition_relid);
/* Somebody has dropped or created partitions */
if ((nparts == 0 || result == NULL) && !PrelIsFresh(prel))
{
/* Try building a new 'prel' for this relation */
prel = refresh_result_parts_storage(parts_storage, parent_relid);
}
/* This partition is a parent itself */
if (result && result->prel)
{
prel = result->prel;
expr_state = result->prel_expr_state;
parent_relid = result->partid;
compute_value = true;
/* Repeat with a new dispatch */
result = NULL;
}
Assert(prel);
}
/* Loop until we get some result */
while (result == NULL);
return result;
}
/*
* Since 13 (e1551f96e64) AttrNumber[] and map_length was combined
* into one struct AttrMap
*/
static ExprState *
prepare_expr_state(const PartRelationInfo *prel,
Relation source_rel,
EState *estate)
{
ExprState *expr_state;
MemoryContext old_mcxt;
Node *expr;
/* Make sure we use query memory context */
old_mcxt = MemoryContextSwitchTo(estate->es_query_cxt);
/* Fetch partitioning expression (we don't care about varno) */
expr = PrelExpressionForRelid(prel, PART_EXPR_VARNO);
/* Should we try using map? */
if (PrelParentRelid(prel) != RelationGetRelid(source_rel))
{
#if PG_VERSION_NUM >= 130000
AttrMap *map;
#else
AttrNumber *map;
int map_length;
#endif
TupleDesc source_tupdesc = RelationGetDescr(source_rel);
/* Remap expression attributes for source relation */
#if PG_VERSION_NUM >= 130000
map = PrelExpressionAttributesMap(prel, source_tupdesc);
#else
map = PrelExpressionAttributesMap(prel, source_tupdesc, &map_length);
#endif
if (map)
{
bool found_whole_row;
#if PG_VERSION_NUM >= 130000
expr = map_variable_attnos(expr, PART_EXPR_VARNO, 0, map,
InvalidOid,
&found_whole_row);
#else
expr = map_variable_attnos_compat(expr, PART_EXPR_VARNO, 0, map,
map_length, InvalidOid,
&found_whole_row);
#endif
if (found_whole_row)
elog(ERROR, "unexpected whole-row reference"
" found in partition key");
#if PG_VERSION_NUM >= 130000
free_attrmap(map);
#else
pfree(map);
#endif
}
}
/* Prepare state for expression execution */
expr_state = ExecInitExpr((Expr *) expr, NULL);
MemoryContextSwitchTo(old_mcxt);
return expr_state;
}
/*
* --------------------------------
* PartitionFilter implementation
* --------------------------------
*/
Plan *
make_partition_filter(Plan *subplan,
Oid parent_relid,
Index parent_rti,
OnConflictAction conflict_action,
CmdType command_type,
List *returning_list)
{
CustomScan *cscan = makeNode(CustomScan);
/* Currently we don't support ON CONFLICT clauses */
if (conflict_action != ONCONFLICT_NONE)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("ON CONFLICT clause is not supported with partitioned tables")));
/* Copy costs etc */
cscan->scan.plan.startup_cost = subplan->startup_cost;
cscan->scan.plan.total_cost = subplan->total_cost;
cscan->scan.plan.plan_rows = subplan->plan_rows;
cscan->scan.plan.plan_width = subplan->plan_width;
/* Setup methods and child plan */
cscan->methods = &partition_filter_plan_methods;
cscan->custom_plans = list_make1(subplan);
/* No physical relation will be scanned */
cscan->scan.scanrelid = 0;
/* Build an appropriate target list */
cscan->scan.plan.targetlist = pfilter_build_tlist(subplan, parent_rti);
/* Pack partitioned table's Oid and conflict_action */
#if PG_VERSION_NUM >= 160000 /* for commit 178ee1d858 */
cscan->custom_private = list_make5(makeInteger(parent_relid),
makeInteger(conflict_action),
returning_list,
makeInteger(command_type),
makeInteger(parent_rti));
#else
cscan->custom_private = list_make4(makeInteger(parent_relid),
makeInteger(conflict_action),
returning_list,
makeInteger(command_type));
#endif
return &cscan->scan.plan;
}
Node *
partition_filter_create_scan_state(CustomScan *node)
{
PartitionFilterState *state;
state = (PartitionFilterState *) palloc0(sizeof(PartitionFilterState));
NodeSetTag(state, T_CustomScanState);
/* Initialize base CustomScanState */
state->css.flags = node->flags;
state->css.methods = &partition_filter_exec_methods;
/* Extract necessary variables */
state->subplan = (Plan *) linitial(node->custom_plans);
state->partitioned_table = (Oid) intVal(linitial(node->custom_private));
state->on_conflict_action = intVal(lsecond(node->custom_private));
state->returning_list = (List *) lthird(node->custom_private);
state->command_type = (CmdType) intVal(lfourth(node->custom_private));
#if PG_VERSION_NUM >= 160000 /* for commit 178ee1d858 */
state->parent_rti = (Index) intVal(lfirst(list_nth_cell(node->custom_private, 4)));
#endif
/* Check boundaries */
Assert(state->on_conflict_action >= ONCONFLICT_NONE ||
state->on_conflict_action <= ONCONFLICT_UPDATE);
/* There should be exactly one subplan */
Assert(list_length(node->custom_plans) == 1);
return (Node *) state;
}
void
partition_filter_begin(CustomScanState *node, EState *estate, int eflags)
{
PartitionFilterState *state = (PartitionFilterState *) node;
Oid parent_relid = state->partitioned_table;
ResultRelInfo *current_rri;
/* It's convenient to store PlanState in 'custom_ps' */
node->custom_ps = list_make1(ExecInitNode(state->subplan, estate, eflags));
/* Fetch current result relation (rri + rel) */
current_rri = estate->es_result_relation_info;
/* Init ResultRelInfo cache */
init_result_parts_storage(&state->result_parts,
parent_relid, current_rri,
estate, state->command_type,
RPS_SKIP_RELATIONS,
state->on_conflict_action != ONCONFLICT_NONE,
RPS_RRI_CB(prepare_rri_for_insert, state),
RPS_RRI_CB(NULL, NULL));
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
/* ResultRelInfo of partitioned table. */
{
RangeTblEntry *rte = rt_fetch(current_rri->ri_RangeTableIndex, estate->es_range_table);
if (rte->perminfoindex > 0)
state->result_parts.init_rri = current_rri;
else
{
/*
* Additional changes for 178ee1d858d: we cannot use current_rri
* because RTE for this ResultRelInfo has perminfoindex = 0. Need
* to use parent_rti (modify_table->nominalRelation) instead.
*/
Assert(state->parent_rti > 0);
state->result_parts.init_rri = estate->es_result_relations[state->parent_rti - 1];
if (!state->result_parts.init_rri)
elog(ERROR, "cannot determine result info for partitioned table");
}
}
#endif
}
#if PG_VERSION_NUM >= 140000
/*
* Re-initialization of PartitionFilterState for using new partition with new
* "current_rri"
*/
static void
reint_partition_filter_state(PartitionFilterState *state, ResultRelInfo *current_rri)
{
Oid parent_relid = state->partitioned_table;
EState *estate = state->result_parts.estate;
fini_result_parts_storage(&state->result_parts);
state->returning_list = current_rri->ri_returningList;
/* Init ResultRelInfo cache */
init_result_parts_storage(&state->result_parts,
parent_relid, current_rri,
estate, state->command_type,
RPS_SKIP_RELATIONS,
state->on_conflict_action != ONCONFLICT_NONE,
RPS_RRI_CB(prepare_rri_for_insert, state),
RPS_RRI_CB(NULL, NULL));
}
#endif
TupleTableSlot *
partition_filter_exec(CustomScanState *node)
{
PartitionFilterState *state = (PartitionFilterState *) node;
ExprContext *econtext = node->ss.ps.ps_ExprContext;
EState *estate = node->ss.ps.state;
PlanState *child_ps = (PlanState *) linitial(node->custom_ps);
TupleTableSlot *slot;
slot = ExecProcNode(child_ps);
if (!TupIsNull(slot))
{
MemoryContext old_mcxt;
ResultRelInfoHolder *rri_holder;
ResultRelInfo *rri;
JunkFilter *junkfilter = NULL;
#if PG_VERSION_NUM >= 140000
PartitionRouterState *pr_state = linitial(node->custom_ps);
/*
* For 14: in case UPDATE command, we can scanning several partitions
* in one plan. Need to switch context each time partition is switched.
*/
if (IsPartitionRouterState(pr_state) &&
state->result_parts.base_rri != pr_state->current_rri)
{ /*
* Slot switched to new partition: need to
* reinitialize some PartitionFilterState variables
*/
reint_partition_filter_state(state, pr_state->current_rri);
}
#else
junkfilter = estate->es_result_relation_info->ri_junkFilter;
#endif
/* Switch to per-tuple context */
old_mcxt = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
/* Search for a matching partition */
rri_holder = select_partition_for_insert(estate, &state->result_parts, slot);
/* Switch back and clean up per-tuple context */
MemoryContextSwitchTo(old_mcxt);
ResetExprContext(econtext);
rri = rri_holder->result_rel_info;
/* Magic: replace parent's ResultRelInfo with ours */
estate->es_result_relation_info = rri;
/*
* Besides 'transform map' we should process two cases:
* 1) CMD_UPDATE, row moved to other partition, junkfilter == NULL
* (filled in router_set_slot() for SELECT + INSERT);
* we should clear attribute 'ctid' (do not insert it into database);
* 2) CMD_INSERT/CMD_UPDATE operations for partitions with deleted column(s),
* junkfilter == NULL.
*/
/* If there's a transform map, rebuild the tuple */
if (rri_holder->tuple_map ||
(!junkfilter &&
(state->command_type == CMD_INSERT || state->command_type == CMD_UPDATE) &&
(slot->tts_tupleDescriptor->natts > rri->ri_RelationDesc->rd_att->natts /* extra fields */