-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathplanner_tree_modification.c
1211 lines (992 loc) · 30.6 KB
/
planner_tree_modification.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
/* ------------------------------------------------------------------------
*
* planner_tree_modification.c
* Functions for query- and plan- tree modification
*
* Copyright (c) 2016-2020, Postgres Professional
* Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
* ------------------------------------------------------------------------
*/
#include "compat/rowmarks_fix.h"
#include "declarative.h"
#include "partition_filter.h"
#include "partition_router.h"
#include "partition_overseer.h"
#include "planner_tree_modification.h"
#include "relation_info.h"
#include "rewrite/rewriteManip.h"
#if PG_VERSION_NUM >= 120000
#include "access/table.h"
#endif
#include "access/htup_details.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "optimizer/clauses.h"
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
#include "parser/parse_relation.h"
#endif
#include "storage/lmgr.h"
#include "utils/syscache.h"
/*
* Drop conflicting macros for the sake of TRANSFORM_CONTEXT_FIELD(...).
* For instance, Windows.h contains a nasty "#define DELETE".
*/
#ifdef SELECT
#undef SELECT
#endif
#ifdef INSERT
#undef INSERT
#endif
#ifdef UPDATE
#undef UPDATE
#endif
#ifdef DELETE
#undef DELETE
#endif
/* for assign_rel_parenthood_status() */
#define PARENTHOOD_TAG CppAsString(PARENTHOOD)
/* Build transform_query_cxt field name */
#define TRANSFORM_CONTEXT_FIELD(command_type) \
has_parent_##command_type##_query
/* Check that transform_query_cxt field is TRUE */
#define TRANSFORM_CONTEXT_HAS_PARENT(context, command_type) \
( (context)->TRANSFORM_CONTEXT_FIELD(command_type) )
/* Used in switch(CmdType) statements */
#define TRANSFORM_CONTEXT_SWITCH_SET(context, command_type) \
case CMD_##command_type: \
(context)->TRANSFORM_CONTEXT_FIELD(command_type) = true; \
break; \
#define TRANSFORM_CONTEXT_QUERY_IS_CTE_CTE(context, query) \
( (context)->parent_cte && \
(context)->parent_cte->ctequery == (Node *) (query) )
#define TRANSFORM_CONTEXT_QUERY_IS_CTE_SL(context, query) \
( (context)->parent_sublink && \
(context)->parent_sublink->subselect == (Node *) (query) && \
(context)->parent_sublink->subLinkType == CTE_SUBLINK )
/* Check if 'query' is CTE according to 'context' */
#define TRANSFORM_CONTEXT_QUERY_IS_CTE(context, query) \
( TRANSFORM_CONTEXT_QUERY_IS_CTE_CTE((context), (query)) || \
TRANSFORM_CONTEXT_QUERY_IS_CTE_SL ((context), (query)) )
typedef struct
{
/* Do we have a parent CmdType query? */
bool TRANSFORM_CONTEXT_FIELD(SELECT),
TRANSFORM_CONTEXT_FIELD(INSERT),
TRANSFORM_CONTEXT_FIELD(UPDATE),
TRANSFORM_CONTEXT_FIELD(DELETE);
/* Parameters for handle_modification_query() */
ParamListInfo query_params;
/* SubLink that might contain an examined query */
SubLink *parent_sublink;
/* CommonTableExpr that might contain an examined query */
CommonTableExpr *parent_cte;
} transform_query_cxt;
typedef struct
{
Index child_varno;
Oid parent_relid,
parent_reltype,
child_reltype;
List *translated_vars;
} adjust_appendrel_varnos_cxt;
static bool pathman_transform_query_walker(Node *node, void *context);
static bool pathman_post_analyze_query_walker(Node *node, void *context);
static void disable_standard_inheritance(Query *parse, transform_query_cxt *context);
static void handle_modification_query(Query *parse, transform_query_cxt *context);
static Plan *partition_filter_visitor(Plan *plan, void *context);
static Plan *partition_router_visitor(Plan *plan, void *context);
static void state_visit_subplans(List *plans, void (*visitor) (PlanState *plan, void *context), void *context);
static void state_visit_members(PlanState **planstates, int nplans, void (*visitor) (PlanState *plan, void *context), void *context);
static Oid find_deepest_partition(Oid relid, Index rti, Expr *quals);
static Node *eval_extern_params_mutator(Node *node, ParamListInfo params);
static Node *adjust_appendrel_varnos(Node *node, adjust_appendrel_varnos_cxt *context);
static bool inh_translation_list_is_trivial(List *translated_vars);
static bool modifytable_contains_fdw(List *rtable, ModifyTable *node);
/*
* HACK: We have to mark each Query with a unique
* id in order to recognize them properly.
*/
#define QUERY_ID_INITIAL 0
static uint64 latest_query_id = QUERY_ID_INITIAL;
void
assign_query_id(Query *query)
{
uint64 prev_id = latest_query_id++;
if (prev_id > latest_query_id)
elog(WARNING, "assign_query_id(): queryId overflow");
query->queryId = latest_query_id;
}
void
reset_query_id_generator(void)
{
latest_query_id = QUERY_ID_INITIAL;
}
/*
* Basic plan tree walker.
*
* 'visitor' is applied right before return.
*/
Plan *
plan_tree_visitor(Plan *plan,
Plan *(*visitor) (Plan *plan, void *context),
void *context)
{
ListCell *l;
if (plan == NULL)
return NULL;
check_stack_depth();
/* Plan-type-specific fixes */
switch (nodeTag(plan))
{
case T_SubqueryScan:
plan_tree_visitor(((SubqueryScan *) plan)->subplan, visitor, context);
break;
case T_CustomScan:
foreach (l, ((CustomScan *) plan)->custom_plans)
plan_tree_visitor((Plan *) lfirst(l), visitor, context);
break;
#if PG_VERSION_NUM < 140000 /* reworked in commit 86dc90056dfd */
case T_ModifyTable:
foreach (l, ((ModifyTable *) plan)->plans)
plan_tree_visitor((Plan *) lfirst(l), visitor, context);
break;
#endif
case T_Append:
foreach (l, ((Append *) plan)->appendplans)
plan_tree_visitor((Plan *) lfirst(l), visitor, context);
break;
case T_MergeAppend:
foreach (l, ((MergeAppend *) plan)->mergeplans)
plan_tree_visitor((Plan *) lfirst(l), visitor, context);
break;
case T_BitmapAnd:
foreach (l, ((BitmapAnd *) plan)->bitmapplans)
plan_tree_visitor((Plan *) lfirst(l), visitor, context);
break;
case T_BitmapOr:
foreach (l, ((BitmapOr *) plan)->bitmapplans)
plan_tree_visitor((Plan *) lfirst(l), visitor, context);
break;
default:
break;
}
plan_tree_visitor(plan->lefttree, visitor, context);
plan_tree_visitor(plan->righttree, visitor, context);
/* Apply visitor to the current node */
return visitor(plan, context);
}
void
state_tree_visitor(PlanState *state,
void (*visitor) (PlanState *plan, void *context),
void *context)
{
Plan *plan;
ListCell *lc;
if (state == NULL)
return;
plan = state->plan;
check_stack_depth();
/* Plan-type-specific fixes */
switch (nodeTag(plan))
{
case T_SubqueryScan:
state_tree_visitor(((SubqueryScanState *) state)->subplan, visitor, context);
break;
case T_CustomScan:
foreach (lc, ((CustomScanState *) state)->custom_ps)
state_tree_visitor((PlanState *) lfirst(lc), visitor, context);
break;
#if PG_VERSION_NUM < 140000 /* reworked in commit 86dc90056dfd */
case T_ModifyTable:
state_visit_members(((ModifyTableState *) state)->mt_plans,
((ModifyTableState *) state)->mt_nplans,
visitor, context);
break;
#endif
case T_Append:
state_visit_members(((AppendState *) state)->appendplans,
((AppendState *) state)->as_nplans,
visitor, context);
break;
case T_MergeAppend:
state_visit_members(((MergeAppendState *) state)->mergeplans,
((MergeAppendState *) state)->ms_nplans,
visitor, context);
break;
case T_BitmapAnd:
state_visit_members(((BitmapAndState *) state)->bitmapplans,
((BitmapAndState *) state)->nplans,
visitor, context);
break;
case T_BitmapOr:
state_visit_members(((BitmapOrState *) state)->bitmapplans,
((BitmapOrState *) state)->nplans,
visitor, context);
break;
default:
break;
}
state_visit_subplans(state->initPlan, visitor, context);
state_visit_subplans(state->subPlan, visitor, context);
state_tree_visitor(state->lefttree, visitor, context);
state_tree_visitor(state->righttree, visitor, context);
/* Apply visitor to the current node */
visitor(state, context);
}
/*
* Walk a list of SubPlans (or initPlans, which also use SubPlan nodes).
*/
static void
state_visit_subplans(List *plans,
void (*visitor) (PlanState *plan, void *context),
void *context)
{
ListCell *lc;
foreach (lc, plans)
{
SubPlanState *sps = lfirst_node(SubPlanState, lc);
state_tree_visitor(sps->planstate, visitor, context);
}
}
/*
* Walk the constituent plans of a ModifyTable, Append, MergeAppend,
* BitmapAnd, or BitmapOr node.
*/
static void
state_visit_members(PlanState **planstates, int nplans,
void (*visitor) (PlanState *plan, void *context), void *context)
{
int i;
for (i = 0; i < nplans; i++)
state_tree_visitor(planstates[i], visitor, context);
}
/*
* -------------------------------
* Walker for Query modification
* -------------------------------
*/
/* Perform some transformations on Query tree */
void
pathman_transform_query(Query *parse, ParamListInfo params)
{
transform_query_cxt context;
/* Initialize context */
memset((void *) &context, 0, sizeof(context));
context.query_params = params;
pathman_transform_query_walker((Node *) parse, (void *) &context);
}
void
pathman_post_analyze_query(Query *parse)
{
pathman_post_analyze_query_walker((Node *) parse, NULL);
}
/* Walker for pathman_transform_query() */
static bool
pathman_transform_query_walker(Node *node, void *context)
{
if (node == NULL)
return false;
else if (IsA(node, SubLink) || IsA(node, CommonTableExpr))
{
transform_query_cxt *current_context = context,
next_context;
/* Initialize next context for bottom subqueries */
next_context = *current_context;
if (IsA(node, SubLink))
{
next_context.parent_sublink = (SubLink *) node;
next_context.parent_cte = NULL;
}
else
{
next_context.parent_sublink = NULL;
next_context.parent_cte = (CommonTableExpr *) node;
}
/* Handle expression subtree */
return expression_tree_walker(node,
pathman_transform_query_walker,
(void *) &next_context);
}
else if (IsA(node, Query))
{
Query *query = (Query *) node;
transform_query_cxt *current_context = context,
next_context;
/* Initialize next context for bottom subqueries */
next_context = *current_context;
switch (query->commandType)
{
TRANSFORM_CONTEXT_SWITCH_SET(&next_context, SELECT);
TRANSFORM_CONTEXT_SWITCH_SET(&next_context, INSERT);
TRANSFORM_CONTEXT_SWITCH_SET(&next_context, UPDATE);
TRANSFORM_CONTEXT_SWITCH_SET(&next_context, DELETE);
default:
break;
}
next_context.parent_sublink = NULL;
next_context.parent_cte = NULL;
/* Assign Query a 'queryId' */
assign_query_id(query);
/* Apply Query tree modifiers */
disable_standard_inheritance(query, current_context);
handle_modification_query(query, current_context);
/* Handle Query node */
return query_tree_walker(query,
pathman_transform_query_walker,
(void *) &next_context,
0);
}
/* Handle expression subtree */
return expression_tree_walker(node,
pathman_transform_query_walker,
context);
}
static bool
pathman_post_analyze_query_walker(Node *node, void *context)
{
if (node == NULL)
return false;
else if (IsA(node, Query))
{
Query *query = (Query *) node;
/* Make changes for declarative syntax */
#ifdef ENABLE_DECLARATIVE
modify_declarative_partitioning_query(query);
#endif
/* Handle Query node */
return query_tree_walker(query,
pathman_post_analyze_query_walker,
context,
0);
}
/* Handle expression subtree */
return expression_tree_walker(node,
pathman_post_analyze_query_walker,
context);
}
/*
* ----------------------
* Query tree modifiers
* ----------------------
*/
/* Disable standard inheritance if table is partitioned by pg_pathman */
static void
disable_standard_inheritance(Query *parse, transform_query_cxt *context)
{
ListCell *lc;
Index current_rti; /* current range table entry index */
#ifdef LEGACY_ROWMARKS_95
/* Don't process non-SELECT queries */
if (parse->commandType != CMD_SELECT)
return;
/* Don't process queries under UPDATE or DELETE (except for CTEs) */
if ((TRANSFORM_CONTEXT_HAS_PARENT(context, UPDATE) ||
TRANSFORM_CONTEXT_HAS_PARENT(context, DELETE)) &&
!TRANSFORM_CONTEXT_QUERY_IS_CTE(context, parse))
return;
#endif
/* Walk through RangeTblEntries list */
current_rti = 0;
foreach (lc, parse->rtable)
{
RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
current_rti++; /* increment RTE index */
Assert(current_rti != 0);
/* Process only non-result base relations */
if (rte->rtekind != RTE_RELATION ||
rte->relkind != RELKIND_RELATION ||
parse->resultRelation == current_rti) /* is it a result relation? */
{
#if PG_VERSION_NUM >= 150000 /* for commit 7103ebb7aae8 */
if (parse->commandType == CMD_MERGE &&
(rte->rtekind == RTE_RELATION ||
rte->relkind == RELKIND_RELATION) &&
rte->inh && has_pathman_relation_info(rte->relid))
elog(ERROR, "pg_pathman doesn't support MERGE command yet");
#endif
continue;
}
/* Table may be partitioned */
if (rte->inh)
{
#ifdef LEGACY_ROWMARKS_95
/* Don't process queries with RowMarks on 9.5 */
if (get_parse_rowmark(parse, current_rti))
continue;
#endif
/* Proceed if table is partitioned by pg_pathman */
if (has_pathman_relation_info(rte->relid))
{
/* HACK: unset the 'inh' flag to disable standard planning */
rte->inh = false;
/* Try marking it using PARENTHOOD_ALLOWED */
assign_rel_parenthood_status(rte, PARENTHOOD_ALLOWED);
}
}
/* Else try marking it using PARENTHOOD_DISALLOWED */
else assign_rel_parenthood_status(rte, PARENTHOOD_DISALLOWED);
}
}
/* Checks if query affects only one partition */
static void
handle_modification_query(Query *parse, transform_query_cxt *context)
{
RangeTblEntry *rte;
Oid child;
Node *quals;
Index result_rti = parse->resultRelation;
ParamListInfo params = context->query_params;
/* Exit if it's not a DELETE or UPDATE query */
if (result_rti == 0 || (parse->commandType != CMD_UPDATE &&
parse->commandType != CMD_DELETE))
return;
/* can't set earlier because CMD_UTILITY doesn't have jointree */
quals = parse->jointree->quals;
rte = rt_fetch(result_rti, parse->rtable);
/* Exit if it's ONLY table */
if (!rte->inh)
return;
/* Check if we can replace PARAMs with CONSTs */
if (params && clause_contains_params(quals))
quals = eval_extern_params_mutator(quals, params);
/* Evaluate constaint expressions */
quals = eval_const_expressions(NULL, quals);
/* Parse syntax tree and extract deepest partition if possible */
child = find_deepest_partition(rte->relid, result_rti, (Expr *) quals);
/* Substitute parent table with partition */
if (OidIsValid(child))
{
Relation child_rel,
parent_rel;
LOCKMODE lockmode = RowExclusiveLock; /* UPDATE | DELETE */
HeapTuple syscache_htup;
char child_relkind;
Oid parent = rte->relid;
List *translated_vars;
adjust_appendrel_varnos_cxt aav_cxt;
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
RTEPermissionInfo *parent_perminfo,
*child_perminfo;
#endif
/* Lock 'child' table */
LockRelationOid(child, lockmode);
/* Make sure that 'child' exists */
syscache_htup = SearchSysCache1(RELOID, ObjectIdGetDatum(child));
if (HeapTupleIsValid(syscache_htup))
{
Form_pg_class reltup = (Form_pg_class) GETSTRUCT(syscache_htup);
/* Fetch child's relkind and free cache entry */
child_relkind = reltup->relkind;
ReleaseSysCache(syscache_htup);
}
else
{
UnlockRelationOid(child, lockmode);
return; /* nothing to do here */
}
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
parent_perminfo = getRTEPermissionInfo(parse->rteperminfos, rte);
#endif
/* Update RTE's relid and relkind (for FDW) */
rte->relid = child;
rte->relkind = child_relkind;
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
/* Copy parent RTEPermissionInfo. */
rte->perminfoindex = 0; /* expected by addRTEPermissionInfo() */
child_perminfo = addRTEPermissionInfo(&parse->rteperminfos, rte);
memcpy(child_perminfo, parent_perminfo, sizeof(RTEPermissionInfo));
/* Correct RTEPermissionInfo for child. */
child_perminfo->relid = child;
child_perminfo->inh = false;
#endif
/* HACK: unset the 'inh' flag (no children) */
rte->inh = false;
/* Both tables are already locked */
child_rel = heap_open_compat(child, NoLock);
parent_rel = heap_open_compat(parent, NoLock);
make_inh_translation_list(parent_rel, child_rel, 0, &translated_vars, NULL);
/* Perform some additional adjustments */
if (!inh_translation_list_is_trivial(translated_vars))
{
/* Translate varnos for this child */
aav_cxt.child_varno = result_rti;
aav_cxt.parent_relid = parent;
aav_cxt.parent_reltype = RelationGetDescr(parent_rel)->tdtypeid;
aav_cxt.child_reltype = RelationGetDescr(child_rel)->tdtypeid;
aav_cxt.translated_vars = translated_vars;
adjust_appendrel_varnos((Node *) parse, &aav_cxt);
#if PG_VERSION_NUM >= 160000 /* for commit a61b1f74823c */
child_perminfo->selectedCols = translate_col_privs(parent_perminfo->selectedCols, translated_vars);
child_perminfo->insertedCols = translate_col_privs(parent_perminfo->insertedCols, translated_vars);
child_perminfo->updatedCols = translate_col_privs(parent_perminfo->updatedCols, translated_vars);
#else
/* Translate column privileges for this child */
rte->selectedCols = translate_col_privs(rte->selectedCols, translated_vars);
rte->insertedCols = translate_col_privs(rte->insertedCols, translated_vars);
rte->updatedCols = translate_col_privs(rte->updatedCols, translated_vars);
#endif
}
/* Close relations (should remain locked, though) */
heap_close_compat(child_rel, NoLock);
heap_close_compat(parent_rel, NoLock);
}
}
/* Remap parent's attributes to child ones */
static Node *
adjust_appendrel_varnos(Node *node, adjust_appendrel_varnos_cxt *context)
{
if (node == NULL)
return NULL;
if (IsA(node, Query))
{
Query *query = (Query *) node;
ListCell *lc;
/* FIXME: we might need to reorder TargetEntries */
foreach (lc, query->targetList)
{
TargetEntry *te = (TargetEntry *) lfirst(lc);
Var *child_var;
if (te->resjunk)
continue;
if (te->resno > list_length(context->translated_vars))
elog(ERROR, "attribute %d of relation \"%s\" does not exist",
te->resno, get_rel_name(context->parent_relid));
child_var = list_nth(context->translated_vars, te->resno - 1);
if (!child_var)
elog(ERROR, "attribute %d of relation \"%s\" does not exist",
te->resno, get_rel_name(context->parent_relid));
/* Transform attribute number */
te->resno = child_var->varattno;
}
/* NOTE: we shouldn't copy top-level Query */
return (Node *) query_tree_mutator((Query *) node,
adjust_appendrel_varnos,
context,
(QTW_IGNORE_RC_SUBQUERIES |
QTW_DONT_COPY_QUERY));
}
if (IsA(node, Var))
{
Var *var = (Var *) node;
/* See adjust_appendrel_attrs_mutator() */
if (var->varno == context->child_varno)
{
if (var->varattno > 0)
{
Var *child_var;
var = copyObject(var);
if (var->varattno > list_length(context->translated_vars))
elog(ERROR, "attribute %d of relation \"%s\" does not exist",
var->varattno, get_rel_name(context->parent_relid));
child_var = list_nth(context->translated_vars, var->varattno - 1);
if (!child_var)
elog(ERROR, "attribute %d of relation \"%s\" does not exist",
var->varattno, get_rel_name(context->parent_relid));
/* Transform attribute number */
var->varattno = child_var->varattno;
}
else if (var->varattno == 0)
{
ConvertRowtypeExpr *r = makeNode(ConvertRowtypeExpr);
Assert(var->vartype = context->parent_reltype);
r->arg = (Expr *) var;
r->resulttype = context->parent_reltype;
r->convertformat = COERCE_IMPLICIT_CAST;
r->location = -1;
/* Make sure the Var node has the right type ID, too */
var->vartype = context->child_reltype;
return (Node *) r;
}
}
return (Node *) var;
}
if (IsA(node, SubLink))
{
SubLink *sl = (SubLink *) node;
/* Examine its expression */
sl->testexpr = expression_tree_mutator_compat(sl->testexpr,
adjust_appendrel_varnos,
context);
return (Node *) sl;
}
return expression_tree_mutator_compat(node,
adjust_appendrel_varnos,
context);
}
/*
* ----------------------------------------------------
* PartitionFilter and PartitionRouter -related stuff
* ----------------------------------------------------
*/
/* Add PartitionFilter nodes to the plan tree */
Plan *
add_partition_filters(List *rtable, Plan *plan)
{
if (pg_pathman_enable_partition_filter)
return plan_tree_visitor(plan, partition_filter_visitor, rtable);
return NULL;
}
/* Add PartitionRouter nodes to the plan tree */
Plan *
add_partition_routers(List *rtable, Plan *plan)
{
if (pg_pathman_enable_partition_router)
return plan_tree_visitor(plan, partition_router_visitor, rtable);
return NULL;
}
/*
* Add PartitionFilters to ModifyTable node's children.
*
* 'context' should point to the PlannedStmt->rtable.
*/
static Plan *
partition_filter_visitor(Plan *plan, void *context)
{
List *rtable = (List *) context;
ModifyTable *modify_table = (ModifyTable *) plan;
#if PG_VERSION_NUM >= 140000 /* for changes 86dc90056dfd */
/*
* We have only one subplan for 14: need to modify it without
* using any cycle
*/
Plan *subplan = outerPlan(modify_table);
ListCell *lc2,
*lc3;
#else
ListCell *lc1,
*lc2,
*lc3;
#endif
/* Skip if not ModifyTable with 'INSERT' command */
if (!IsA(modify_table, ModifyTable) || modify_table->operation != CMD_INSERT)
return NULL;
Assert(rtable && IsA(rtable, List));
lc3 = list_head(modify_table->returningLists);
#if PG_VERSION_NUM >= 140000 /* for changes 86dc90056dfd */
lc2 = list_head(modify_table->resultRelations);
#else
forboth (lc1, modify_table->plans,
lc2, modify_table->resultRelations)
#endif
{
Index rindex = lfirst_int(lc2);
Oid relid = getrelid(rindex, rtable);
/* Check that table is partitioned */
if (has_pathman_relation_info(relid))
{
List *returning_list = NIL;
/* Extract returning list if possible */
if (lc3)
{
returning_list = lfirst(lc3);
#if PG_VERSION_NUM < 140000
lc3 = lnext_compat(modify_table->returningLists, lc3);
#endif
}
#if PG_VERSION_NUM >= 140000 /* for changes 86dc90056dfd */
outerPlan(modify_table) = make_partition_filter(subplan, relid,
modify_table->nominalRelation,
modify_table->onConflictAction,
modify_table->operation,
returning_list);
#else
lfirst(lc1) = make_partition_filter((Plan *) lfirst(lc1), relid,
modify_table->nominalRelation,
modify_table->onConflictAction,
modify_table->operation,
returning_list);
#endif
}
}
return NULL;
}
/*
* Add PartitionRouter to ModifyTable node's children.
*
* 'context' should point to the PlannedStmt->rtable.
*/
static Plan *
partition_router_visitor(Plan *plan, void *context)
{
List *rtable = (List *) context;
ModifyTable *modify_table = (ModifyTable *) plan;
#if PG_VERSION_NUM >= 140000 /* for changes 86dc90056dfd */
/*
* We have only one subplan for 14: need to modify it without
* using any cycle
*/
Plan *subplan = outerPlan(modify_table);
ListCell *lc2,
*lc3;
#else
ListCell *lc1,
*lc2,
*lc3;
#endif
bool changed = false;
/* Skip if not ModifyTable with 'UPDATE' command */
if (!IsA(modify_table, ModifyTable) || modify_table->operation != CMD_UPDATE)
return NULL;
Assert(rtable && IsA(rtable, List));
if (modifytable_contains_fdw(rtable, modify_table))
{
ereport(WARNING,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg(UPDATE_NODE_NAME " does not support foreign data wrappers")));
return NULL;
}
lc3 = list_head(modify_table->returningLists);
#if PG_VERSION_NUM >= 140000 /* for changes 86dc90056dfd */
lc2 = list_head(modify_table->resultRelations);
#else
forboth (lc1, modify_table->plans,
lc2, modify_table->resultRelations)
#endif
{
Index rindex = lfirst_int(lc2);
Oid relid = getrelid(rindex, rtable),
tmp_relid;
/* Find topmost parent */
while (OidIsValid(tmp_relid = get_parent_of_partition(relid)))
relid = tmp_relid;
/* Check that table is partitioned */
if (has_pathman_relation_info(relid))
{
List *returning_list = NIL;
Plan *prouter,
*pfilter;
/* Extract returning list if possible */
if (lc3)
{
returning_list = lfirst(lc3);
#if PG_VERSION_NUM < 140000
lc3 = lnext_compat(modify_table->returningLists, lc3);
#endif
}
#if PG_VERSION_NUM >= 140000 /* for changes 86dc90056dfd */
prouter = make_partition_router(subplan,
modify_table->epqParam,
modify_table->nominalRelation);
#else
prouter = make_partition_router((Plan *) lfirst(lc1),
modify_table->epqParam,
modify_table->nominalRelation);
#endif
pfilter = make_partition_filter((Plan *) prouter, relid,
modify_table->nominalRelation,
ONCONFLICT_NONE,
CMD_UPDATE,
returning_list);
#if PG_VERSION_NUM >= 140000 /* for changes in 86dc90056dfd */
outerPlan(modify_table) = pfilter;
#else
lfirst(lc1) = pfilter;
#endif
changed = true;
}
}
if (changed)
return make_partition_overseer(plan);
return NULL;
}
/*
* -----------------------------------------------
* Parenthood safety checks (SELECT * FROM ONLY)
* -----------------------------------------------
*/
#define RPS_STATUS_ASSIGNED ( (Index) 0x2 )
#define RPS_ENABLE_PARENT ( (Index) 0x1 )
/* Set parenthood status (per query level) */
void
assign_rel_parenthood_status(RangeTblEntry *rte,
rel_parenthood_status new_status)
{
Assert(rte->rtekind != RTE_CTE);
/* HACK: set relevant bits in RTE */
rte->ctelevelsup |= RPS_STATUS_ASSIGNED;
if (new_status == PARENTHOOD_ALLOWED)
rte->ctelevelsup |= RPS_ENABLE_PARENT;
}
/* Get parenthood status (per query level) */
rel_parenthood_status
get_rel_parenthood_status(RangeTblEntry *rte)
{
Assert(rte->rtekind != RTE_CTE);
/* HACK: check relevant bits in RTE */
if (rte->ctelevelsup & RPS_STATUS_ASSIGNED)
return (rte->ctelevelsup & RPS_ENABLE_PARENT) ?
PARENTHOOD_ALLOWED :
PARENTHOOD_DISALLOWED;