-
Notifications
You must be signed in to change notification settings - Fork 789
Expand file tree
/
Copy pathmulti_physical_planner.c
More file actions
5830 lines (4946 loc) · 179 KB
/
Copy pathmulti_physical_planner.c
File metadata and controls
5830 lines (4946 loc) · 179 KB
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
/*-------------------------------------------------------------------------
*
* multi_physical_planner.c
* Routines for creating physical plans from given multi-relational algebra
* trees.
*
* Copyright (c) Citus Data, Inc.
*
* $Id$
*
*-------------------------------------------------------------------------
*/
#include <math.h>
#include <stdint.h>
#include "postgres.h"
#include "miscadmin.h"
#include "access/genam.h"
#include "access/hash.h"
#include "access/heapam.h"
#include "access/nbtree.h"
#include "access/skey.h"
#include "access/xlog.h"
#include "catalog/pg_aggregate.h"
#include "catalog/pg_am.h"
#include "catalog/pg_collation.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "commands/sequence.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pathnodes.h"
#include "nodes/print.h"
#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "parser/parse_relation.h"
#include "parser/parse_type.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteManip.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "pg_version_constants.h"
#include "distributed/backend_data.h"
#include "distributed/citus_nodefuncs.h"
#include "distributed/citus_nodes.h"
#include "distributed/citus_ruleutils.h"
#include "distributed/colocation_utils.h"
#include "distributed/coordinator_protocol.h"
#include "distributed/deparse_shard_query.h"
#include "distributed/intermediate_results.h"
#include "distributed/listutils.h"
#include "distributed/log_utils.h"
#include "distributed/metadata_cache.h"
#include "distributed/multi_join_order.h"
#include "distributed/multi_logical_optimizer.h"
#include "distributed/multi_logical_planner.h"
#include "distributed/multi_partitioning_utils.h"
#include "distributed/multi_physical_planner.h"
#include "distributed/multi_router_planner.h"
#include "distributed/pg_dist_partition.h"
#include "distributed/pg_dist_shard.h"
#include "distributed/query_pushdown_planning.h"
#include "distributed/query_utils.h"
#include "distributed/recursive_planning.h"
#include "distributed/shard_pruning.h"
#include "distributed/shardinterval_utils.h"
#include "distributed/string_utils.h"
#include "distributed/version_compat.h"
#include "distributed/worker_manager.h"
#include "distributed/worker_protocol.h"
/* RepartitionJoinBucketCountPerNode determines bucket amount during repartitions */
int RepartitionJoinBucketCountPerNode = 4;
/* Policy to use when assigning tasks to worker nodes */
int TaskAssignmentPolicy = TASK_ASSIGNMENT_GREEDY;
bool EnableUniqueJobIds = true;
/*
* OperatorCache is used for caching operator identifiers for given typeId,
* accessMethodId and strategyNumber. It is initialized to empty list as
* there are no items in the cache.
*/
static List *OperatorCache = NIL;
/* context passed down in AddAnyValueAggregates mutator */
typedef struct AddAnyValueAggregatesContext
{
/* SortGroupClauses corresponding to the GROUP BY clause */
List *groupClauseList;
/* TargetEntry's to which the GROUP BY clauses refer */
List *groupByTargetEntryList;
/*
* haveNonVarGrouping is true if there are expressions in the
* GROUP BY target entries. We use this as an optimisation to
* skip expensive checks when possible.
*/
bool haveNonVarGrouping;
} AddAnyValueAggregatesContext;
/* Local functions forward declarations for job creation */
static Job * BuildJobTree(MultiTreeRoot *multiTree);
static MultiNode * LeftMostNode(MultiTreeRoot *multiTree);
static Oid RangePartitionJoinBaseRelationId(MultiJoin *joinNode);
static MultiTable * FindTableNode(MultiNode *multiNode, int rangeTableId);
static Query * BuildJobQuery(MultiNode *multiNode, List *dependentJobList);
static List * BaseRangeTableList(MultiNode *multiNode);
static List * QueryTargetList(MultiNode *multiNode);
static List * TargetEntryList(List *expressionList);
static Node * AddAnyValueAggregates(Node *node, AddAnyValueAggregatesContext *context);
static List * QueryGroupClauseList(MultiNode *multiNode);
static List * QuerySelectClauseList(MultiNode *multiNode);
static List * QueryFromList(List *rangeTableList);
static Node * QueryJoinTree(MultiNode *multiNode, List *dependentJobList,
List **rangeTableList);
static void SetJoinRelatedColumnsCompat(RangeTblEntry *rangeTableEntry,
Oid leftRelId,
Oid rightRelId,
List *leftColumnVars,
List *rightColumnVars);
static RangeTblEntry * JoinRangeTableEntry(JoinExpr *joinExpr, List *dependentJobList,
List *rangeTableList);
static int ExtractRangeTableId(Node *node);
static void ExtractColumns(RangeTblEntry *callingRTE, int rangeTableId,
List **columnNames, List **columnVars);
static RangeTblEntry * ConstructCallingRTE(RangeTblEntry *rangeTableEntry,
List *dependentJobList);
static Query * BuildSubqueryJobQuery(MultiNode *multiNode);
static void UpdateAllColumnAttributes(Node *columnContainer, List *rangeTableList,
List *dependentJobList);
static void UpdateColumnAttributes(Var *column, List *rangeTableList,
List *dependentJobList);
static Index NewTableId(Index originalTableId, List *rangeTableList);
static AttrNumber NewColumnId(Index originalTableId, AttrNumber originalColumnId,
RangeTblEntry *newRangeTableEntry, List *dependentJobList);
static Job * JobForRangeTable(List *jobList, RangeTblEntry *rangeTableEntry);
static Job * JobForTableIdList(List *jobList, List *searchedTableIdList);
static List * ChildNodeList(MultiNode *multiNode);
static Job * BuildJob(Query *jobQuery, List *dependentJobList);
static MapMergeJob * BuildMapMergeJob(Query *jobQuery, List *dependentJobList,
Var *partitionKey, PartitionType partitionType,
Oid baseRelationId,
BoundaryNodeJobType boundaryNodeJobType);
static uint32 HashPartitionCount(void);
/* Local functions forward declarations for task list creation and helper functions */
static Job * BuildJobTreeTaskList(Job *jobTree,
PlannerRestrictionContext *plannerRestrictionContext);
static bool IsInnerTableOfOuterJoin(RelationRestriction *relationRestriction);
static void ErrorIfUnsupportedShardDistribution(Query *query);
static Task * QueryPushdownTaskCreate(Query *originalQuery, int shardIndex,
RelationRestrictionContext *restrictionContext,
uint32 taskId,
TaskType taskType,
bool modifyRequiresCoordinatorEvaluation,
DeferredErrorMessage **planningError);
static List * SqlTaskList(Job *job);
static bool DependsOnHashPartitionJob(Job *job);
static uint32 AnchorRangeTableId(List *rangeTableList);
static List * BaseRangeTableIdList(List *rangeTableList);
static List * AnchorRangeTableIdList(List *rangeTableList, List *baseRangeTableIdList);
static void AdjustColumnOldAttributes(List *expressionList);
static List * RangeTableFragmentsList(List *rangeTableList, List *whereClauseList,
List *dependentJobList);
static OperatorCacheEntry * LookupOperatorByType(Oid typeId, Oid accessMethodId,
int16 strategyNumber);
static Oid GetOperatorByType(Oid typeId, Oid accessMethodId, int16 strategyNumber);
static List * FragmentCombinationList(List *rangeTableFragmentsList, Query *jobQuery,
List *dependentJobList);
static JoinSequenceNode * JoinSequenceArray(List *rangeTableFragmentsList,
Query *jobQuery, List *dependentJobList);
static bool PartitionedOnColumn(Var *column, List *rangeTableList,
List *dependentJobList);
static void CheckJoinBetweenColumns(OpExpr *joinClause);
static List * FindRangeTableFragmentsList(List *rangeTableFragmentsList, int taskId);
static bool JoinPrunable(RangeTableFragment *leftFragment,
RangeTableFragment *rightFragment);
static ShardInterval * FragmentInterval(RangeTableFragment *fragment);
static StringInfo FragmentIntervalString(ShardInterval *fragmentInterval);
static List * DataFetchTaskList(uint64 jobId, uint32 taskIdIndex, List *fragmentList);
static List * BuildRelationShardList(List *rangeTableList, List *fragmentList);
static void UpdateRangeTableAlias(List *rangeTableList, List *fragmentList);
static Alias * FragmentAlias(RangeTblEntry *rangeTableEntry,
RangeTableFragment *fragment);
static List * FetchTaskResultNameList(List *mapOutputFetchTaskList);
static uint64 AnchorShardId(List *fragmentList, uint32 anchorRangeTableId);
static List * PruneSqlTaskDependencies(List *sqlTaskList);
static List * AssignTaskList(List *sqlTaskList);
static bool HasMergeTaskDependencies(List *sqlTaskList);
static List * GreedyAssignTaskList(List *taskList);
static Task * GreedyAssignTask(WorkerNode *workerNode, List *taskList,
List *activeShardPlacementLists);
static List * ReorderAndAssignTaskList(List *taskList,
ReorderFunction reorderFunction);
static int CompareTasksByShardId(const void *leftElement, const void *rightElement);
static List * ActiveShardPlacementLists(List *taskList);
static List * LeftRotateList(List *list, uint32 rotateCount);
static List * FindDependentMergeTaskList(Task *sqlTask);
static List * AssignDualHashTaskList(List *taskList);
static void AssignDataFetchDependencies(List *taskList);
static uint32 TaskListHighestTaskId(List *taskList);
static List * MapTaskList(MapMergeJob *mapMergeJob, List *filterTaskList);
static StringInfo CreateMapQueryString(MapMergeJob *mapMergeJob, Task *filterTask,
uint32 partitionColumnIndex, bool useBinaryFormat);
static char * PartitionResultNamePrefix(uint64 jobId, int32 taskId);
static char * PartitionResultName(uint64 jobId, uint32 taskId, uint32 partitionId);
static ShardInterval ** RangeIntervalArrayWithNullBucket(ShardInterval **intervalArray,
int intervalCount);
static List * MergeTaskList(MapMergeJob *mapMergeJob, List *mapTaskList,
uint32 taskIdIndex);
static List * FetchEqualityAttrNumsForRTEOpExpr(OpExpr *opExpr);
static List * FetchEqualityAttrNumsForRTEBoolExpr(BoolExpr *boolExpr);
static List * FetchEqualityAttrNumsForList(List *nodeList);
static int PartitionColumnIndex(Var *targetVar, List *targetList);
static List * GetColumnOriginalIndexes(Oid relationId);
static bool QueryTreeHasImproperForDeparseNodes(Node *inputNode, void *context);
static Node * AdjustImproperForDeparseNodes(Node *inputNode, void *context);
static bool IsImproperForDeparseRelabelTypeNode(Node *inputNode);
static bool IsImproperForDeparseCoerceViaIONode(Node *inputNode);
static CollateExpr * RelabelTypeToCollateExpr(RelabelType *relabelType);
/*
* CreatePhysicalDistributedPlan is the entry point for physical plan generation. The
* function builds the physical plan; this plan includes the list of tasks to be
* executed on worker nodes, and the final query to run on the master node.
*/
DistributedPlan *
CreatePhysicalDistributedPlan(MultiTreeRoot *multiTree,
PlannerRestrictionContext *plannerRestrictionContext)
{
/* build the worker job tree and check that we only have one job in the tree */
Job *workerJob = BuildJobTree(multiTree);
/* create the tree of executable tasks for the worker job */
workerJob = BuildJobTreeTaskList(workerJob, plannerRestrictionContext);
/* build the final merge query to execute on the master */
List *masterDependentJobList = list_make1(workerJob);
Query *combineQuery = BuildJobQuery((MultiNode *) multiTree, masterDependentJobList);
DistributedPlan *distributedPlan = CitusMakeNode(DistributedPlan);
distributedPlan->workerJob = workerJob;
distributedPlan->combineQuery = combineQuery;
distributedPlan->modLevel = ROW_MODIFY_READONLY;
distributedPlan->expectResults = true;
return distributedPlan;
}
/*
* ModifyLocalTableJob returns true if the given task contains
* a modification of local table.
*/
bool
ModifyLocalTableJob(Job *job)
{
if (job == NULL)
{
return false;
}
List *taskList = job->taskList;
if (list_length(taskList) != 1)
{
return false;
}
Task *singleTask = (Task *) linitial(taskList);
return singleTask->isLocalTableModification;
}
/*
* BuildJobTree builds the physical job tree from the given logical plan tree.
* The function walks over the logical plan from the bottom up, finds boundaries
* for jobs, and creates the query structure for each job. The function also
* sets dependencies between jobs, and then returns the top level worker job.
*/
static Job *
BuildJobTree(MultiTreeRoot *multiTree)
{
/* start building the tree from the deepest left node */
MultiNode *leftMostNode = LeftMostNode(multiTree);
MultiNode *currentNode = leftMostNode;
MultiNode *parentNode = ParentNode(currentNode);
List *loopDependentJobList = NIL;
Job *topLevelJob = NULL;
while (parentNode != NULL)
{
CitusNodeTag currentNodeType = CitusNodeTag(currentNode);
CitusNodeTag parentNodeType = CitusNodeTag(parentNode);
BoundaryNodeJobType boundaryNodeJobType = JOB_INVALID_FIRST;
/* we first check if this node forms the boundary for a remote job */
if (currentNodeType == T_MultiJoin)
{
MultiJoin *joinNode = (MultiJoin *) currentNode;
if (joinNode->joinRuleType == SINGLE_HASH_PARTITION_JOIN ||
joinNode->joinRuleType == SINGLE_RANGE_PARTITION_JOIN ||
joinNode->joinRuleType == DUAL_PARTITION_JOIN)
{
boundaryNodeJobType = JOIN_MAP_MERGE_JOB;
}
}
else if (currentNodeType == T_MultiCollect &&
parentNodeType != T_MultiPartition)
{
boundaryNodeJobType = TOP_LEVEL_WORKER_JOB;
}
/*
* If this node is at the boundary for a repartition or top level worker
* job, we build the corresponding job(s) and set their dependencies.
*/
if (boundaryNodeJobType == JOIN_MAP_MERGE_JOB)
{
MultiJoin *joinNode = (MultiJoin *) currentNode;
MultiNode *leftChildNode = joinNode->binaryNode.leftChildNode;
MultiNode *rightChildNode = joinNode->binaryNode.rightChildNode;
PartitionType partitionType = PARTITION_INVALID_FIRST;
Oid baseRelationId = InvalidOid;
if (joinNode->joinRuleType == SINGLE_RANGE_PARTITION_JOIN)
{
partitionType = RANGE_PARTITION_TYPE;
baseRelationId = RangePartitionJoinBaseRelationId(joinNode);
}
else if (joinNode->joinRuleType == SINGLE_HASH_PARTITION_JOIN)
{
partitionType = SINGLE_HASH_PARTITION_TYPE;
baseRelationId = RangePartitionJoinBaseRelationId(joinNode);
}
else if (joinNode->joinRuleType == DUAL_PARTITION_JOIN)
{
partitionType = DUAL_HASH_PARTITION_TYPE;
}
if (CitusIsA(leftChildNode, MultiPartition))
{
MultiPartition *partitionNode = (MultiPartition *) leftChildNode;
MultiNode *queryNode = GrandChildNode((MultiUnaryNode *) partitionNode);
Var *partitionKey = partitionNode->partitionColumn;
/* build query and partition job */
List *dependentJobList = list_copy(loopDependentJobList);
Query *jobQuery = BuildJobQuery(queryNode, dependentJobList);
MapMergeJob *mapMergeJob = BuildMapMergeJob(jobQuery, dependentJobList,
partitionKey, partitionType,
baseRelationId,
JOIN_MAP_MERGE_JOB);
/* reset dependent job list */
loopDependentJobList = NIL;
loopDependentJobList = list_make1(mapMergeJob);
}
if (CitusIsA(rightChildNode, MultiPartition))
{
MultiPartition *partitionNode = (MultiPartition *) rightChildNode;
MultiNode *queryNode = GrandChildNode((MultiUnaryNode *) partitionNode);
Var *partitionKey = partitionNode->partitionColumn;
/*
* The right query and right partition job do not depend on any
* jobs since our logical plan tree is left deep.
*/
Query *jobQuery = BuildJobQuery(queryNode, NIL);
MapMergeJob *mapMergeJob = BuildMapMergeJob(jobQuery, NIL,
partitionKey, partitionType,
baseRelationId,
JOIN_MAP_MERGE_JOB);
/* append to the dependent job list for on-going dependencies */
loopDependentJobList = lappend(loopDependentJobList, mapMergeJob);
}
}
else if (boundaryNodeJobType == TOP_LEVEL_WORKER_JOB)
{
MultiNode *childNode = ChildNode((MultiUnaryNode *) currentNode);
List *dependentJobList = list_copy(loopDependentJobList);
bool subqueryPushdown = false;
List *subqueryMultiTableList = SubqueryMultiTableList(childNode);
int subqueryCount = list_length(subqueryMultiTableList);
if (subqueryCount > 0)
{
subqueryPushdown = true;
}
/*
* Build top level query. If subquery pushdown is set, we use
* sligthly different version of BuildJobQuery(). They are similar
* but we don't need some parts of BuildJobQuery() for subquery
* pushdown such as updating column attributes etc.
*/
if (subqueryPushdown)
{
Query *topLevelQuery = BuildSubqueryJobQuery(childNode);
topLevelJob = BuildJob(topLevelQuery, dependentJobList);
topLevelJob->subqueryPushdown = true;
}
else
{
Query *topLevelQuery = BuildJobQuery(childNode, dependentJobList);
topLevelJob = BuildJob(topLevelQuery, dependentJobList);
}
}
/* walk up the tree */
currentNode = parentNode;
parentNode = ParentNode(currentNode);
}
return topLevelJob;
}
/*
* LeftMostNode finds the deepest left node in the left-deep logical plan tree.
* We build the physical plan by traversing the logical plan from the bottom up;
* and this function helps us find the bottom of the logical tree.
*/
static MultiNode *
LeftMostNode(MultiTreeRoot *multiTree)
{
MultiNode *currentNode = (MultiNode *) multiTree;
MultiNode *leftChildNode = ChildNode((MultiUnaryNode *) multiTree);
while (leftChildNode != NULL)
{
currentNode = leftChildNode;
if (UnaryOperator(currentNode))
{
leftChildNode = ChildNode((MultiUnaryNode *) currentNode);
}
else if (BinaryOperator(currentNode))
{
MultiBinaryNode *binaryNode = (MultiBinaryNode *) currentNode;
leftChildNode = binaryNode->leftChildNode;
}
}
return currentNode;
}
/*
* RangePartitionJoinBaseRelationId finds partition node from join node, and
* returns base relation id of this node. Note that this function assumes that
* given join node is range partition join type.
*/
static Oid
RangePartitionJoinBaseRelationId(MultiJoin *joinNode)
{
MultiPartition *partitionNode = NULL;
MultiNode *leftChildNode = joinNode->binaryNode.leftChildNode;
MultiNode *rightChildNode = joinNode->binaryNode.rightChildNode;
if (CitusIsA(leftChildNode, MultiPartition))
{
partitionNode = (MultiPartition *) leftChildNode;
}
else if (CitusIsA(rightChildNode, MultiPartition))
{
partitionNode = (MultiPartition *) rightChildNode;
}
else
{
Assert(false);
}
Index baseTableId = partitionNode->splitPointTableId;
MultiTable *baseTable = FindTableNode((MultiNode *) joinNode, baseTableId);
Oid baseRelationId = baseTable->relationId;
return baseRelationId;
}
/*
* FindTableNode walks over the given logical plan tree, and returns the table
* node that corresponds to the given range tableId.
*/
static MultiTable *
FindTableNode(MultiNode *multiNode, int rangeTableId)
{
MultiTable *foundTableNode = NULL;
List *tableNodeList = FindNodesOfType(multiNode, T_MultiTable);
ListCell *tableNodeCell = NULL;
foreach(tableNodeCell, tableNodeList)
{
MultiTable *tableNode = (MultiTable *) lfirst(tableNodeCell);
if (tableNode->rangeTableId == rangeTableId)
{
foundTableNode = tableNode;
break;
}
}
Assert(foundTableNode != NULL);
return foundTableNode;
}
/*
* BuildJobQuery traverses the given logical plan tree, determines the job that
* corresponds to this part of the tree, and builds the query structure for that
* particular job. The function assumes that jobs this particular job depends on
* have already been built, as their output is needed to build the query.
*/
static Query *
BuildJobQuery(MultiNode *multiNode, List *dependentJobList)
{
bool updateColumnAttributes = false;
List *targetList = NIL;
List *sortClauseList = NIL;
Node *limitCount = NULL;
Node *limitOffset = NULL;
LimitOption limitOption = LIMIT_OPTION_DEFAULT;
Node *havingQual = NULL;
bool hasDistinctOn = false;
List *distinctClause = NIL;
bool isRepartitionJoin = false;
bool hasWindowFuncs = false;
List *windowClause = NIL;
/* we start building jobs from below the collect node */
Assert(!CitusIsA(multiNode, MultiCollect));
/*
* First check if we are building a master/worker query. If we are building
* a worker query, we update the column attributes for target entries, select
* and join columns. Because if underlying query includes repartition joins,
* then we create multiple queries from a join. In this case, range table lists
* and column lists are subject to change.
*
* Note that we don't do this for master queries, as column attributes for
* master target entries are already set during the master/worker split.
*/
MultiNode *parentNode = ParentNode(multiNode);
if (parentNode != NULL)
{
updateColumnAttributes = true;
}
/*
* If we are building this query on a repartitioned subquery job then we
* don't need to update column attributes.
*/
if (dependentJobList != NIL)
{
Job *job = (Job *) linitial(dependentJobList);
if (CitusIsA(job, MapMergeJob))
{
isRepartitionJoin = true;
}
}
/*
* If we have an extended operator, then we copy the operator's target list.
* Otherwise, we use the target list based on the MultiProject node at this
* level in the query tree.
*/
List *extendedOpNodeList = FindNodesOfType(multiNode, T_MultiExtendedOp);
if (extendedOpNodeList != NIL)
{
MultiExtendedOp *extendedOp = (MultiExtendedOp *) linitial(extendedOpNodeList);
targetList = copyObject(extendedOp->targetList);
distinctClause = extendedOp->distinctClause;
hasDistinctOn = extendedOp->hasDistinctOn;
hasWindowFuncs = extendedOp->hasWindowFuncs;
windowClause = extendedOp->windowClause;
}
else
{
targetList = QueryTargetList(multiNode);
}
/* build the join tree and the range table list */
List *rangeTableList = BaseRangeTableList(multiNode);
Node *joinRoot = QueryJoinTree(multiNode, dependentJobList, &rangeTableList);
/* update the column attributes for target entries */
if (updateColumnAttributes)
{
UpdateAllColumnAttributes((Node *) targetList, rangeTableList, dependentJobList);
}
/* extract limit count/offset and sort clauses */
if (extendedOpNodeList != NIL)
{
MultiExtendedOp *extendedOp = (MultiExtendedOp *) linitial(extendedOpNodeList);
limitCount = extendedOp->limitCount;
limitOffset = extendedOp->limitOffset;
limitOption = extendedOp->limitOption;
sortClauseList = extendedOp->sortClauseList;
havingQual = extendedOp->havingQual;
}
/* build group clauses */
List *groupClauseList = QueryGroupClauseList(multiNode);
/* build the where clause list using select predicates */
List *selectClauseList = QuerySelectClauseList(multiNode);
/* set correct column attributes for select and having clauses */
if (updateColumnAttributes)
{
UpdateAllColumnAttributes((Node *) selectClauseList, rangeTableList,
dependentJobList);
UpdateAllColumnAttributes(havingQual, rangeTableList, dependentJobList);
}
/*
* Group by on primary key allows all columns to appear in the target
* list, but after re-partitioning we will be querying an intermediate
* table that does not have the primary key. We therefore wrap all the
* columns that do not appear in the GROUP BY in an any_value aggregate.
*/
if (groupClauseList != NIL && isRepartitionJoin)
{
targetList = (List *) WrapUngroupedVarsInAnyValueAggregate(
(Node *) targetList, groupClauseList, targetList, true);
havingQual = WrapUngroupedVarsInAnyValueAggregate(
(Node *) havingQual, groupClauseList, targetList, false);
}
/*
* Build the From/Where construct. We keep the where-clause list implicitly
* AND'd, since both partition and join pruning depends on the clauses being
* expressed as a list.
*/
FromExpr *joinTree = makeNode(FromExpr);
joinTree->quals = (Node *) list_copy(selectClauseList);
joinTree->fromlist = list_make1(joinRoot);
/* build the query structure for this job */
Query *jobQuery = makeNode(Query);
jobQuery->commandType = CMD_SELECT;
jobQuery->querySource = QSRC_ORIGINAL;
jobQuery->canSetTag = true;
jobQuery->rtable = rangeTableList;
jobQuery->targetList = targetList;
jobQuery->jointree = joinTree;
jobQuery->sortClause = sortClauseList;
jobQuery->groupClause = groupClauseList;
jobQuery->limitOffset = limitOffset;
jobQuery->limitCount = limitCount;
jobQuery->limitOption = limitOption;
jobQuery->havingQual = havingQual;
jobQuery->hasAggs = contain_aggs_of_level((Node *) targetList, 0) ||
contain_aggs_of_level((Node *) havingQual, 0);
jobQuery->distinctClause = distinctClause;
jobQuery->hasDistinctOn = hasDistinctOn;
jobQuery->windowClause = windowClause;
jobQuery->hasWindowFuncs = hasWindowFuncs;
jobQuery->hasSubLinks = checkExprHasSubLink((Node *) jobQuery);
Assert(jobQuery->hasWindowFuncs == contain_window_function((Node *) jobQuery));
return jobQuery;
}
/*
* BaseRangeTableList returns the list of range table entries for base tables in
* the query. These base tables stand in contrast to derived tables generated by
* repartition jobs. Note that this function only considers base tables relevant
* to the current query, and does not visit nodes under the collect node.
*/
static List *
BaseRangeTableList(MultiNode *multiNode)
{
List *baseRangeTableList = NIL;
List *pendingNodeList = list_make1(multiNode);
while (pendingNodeList != NIL)
{
MultiNode *currMultiNode = (MultiNode *) linitial(pendingNodeList);
CitusNodeTag nodeType = CitusNodeTag(currMultiNode);
pendingNodeList = list_delete_first(pendingNodeList);
if (nodeType == T_MultiTable)
{
/*
* We represent subqueries as MultiTables, and so for base table
* entries we skip the subquery ones.
*/
MultiTable *multiTable = (MultiTable *) currMultiNode;
if (multiTable->relationId != SUBQUERY_RELATION_ID &&
multiTable->relationId != SUBQUERY_PUSHDOWN_RELATION_ID)
{
RangeTblEntry *rangeTableEntry = makeNode(RangeTblEntry);
rangeTableEntry->inFromCl = true;
rangeTableEntry->eref = multiTable->referenceNames;
rangeTableEntry->alias = multiTable->alias;
rangeTableEntry->relid = multiTable->relationId;
rangeTableEntry->inh = multiTable->includePartitions;
rangeTableEntry->tablesample = multiTable->tablesample;
SetRangeTblExtraData(rangeTableEntry, CITUS_RTE_RELATION, NULL, NULL,
list_make1_int(multiTable->rangeTableId),
NIL, NIL, NIL, NIL);
baseRangeTableList = lappend(baseRangeTableList, rangeTableEntry);
}
}
/* do not visit nodes that belong to remote queries */
if (nodeType != T_MultiCollect)
{
List *childNodeList = ChildNodeList(currMultiNode);
pendingNodeList = list_concat(pendingNodeList, childNodeList);
}
}
return baseRangeTableList;
}
/*
* DerivedRangeTableEntry builds a range table entry for the derived table. This
* derived table either represents the output of a repartition job; or the data
* on worker nodes in case of the master node query.
*/
RangeTblEntry *
DerivedRangeTableEntry(MultiNode *multiNode, List *columnList, List *tableIdList,
List *funcColumnNames, List *funcColumnTypes,
List *funcColumnTypeMods, List *funcCollations)
{
RangeTblEntry *rangeTableEntry = makeNode(RangeTblEntry);
rangeTableEntry->inFromCl = true;
rangeTableEntry->eref = makeNode(Alias);
rangeTableEntry->eref->colnames = columnList;
SetRangeTblExtraData(rangeTableEntry, CITUS_RTE_REMOTE_QUERY, NULL, NULL, tableIdList,
funcColumnNames, funcColumnTypes, funcColumnTypeMods,
funcCollations);
return rangeTableEntry;
}
/*
* DerivedColumnNameList builds a column name list for derived (intermediate)
* tables. These column names are then used when building the create stament
* query string for derived tables.
*/
List *
DerivedColumnNameList(uint32 columnCount, uint64 generatingJobId)
{
List *columnNameList = NIL;
for (uint32 columnIndex = 0; columnIndex < columnCount; columnIndex++)
{
StringInfo columnName = makeStringInfo();
appendStringInfo(columnName, "intermediate_column_");
appendStringInfo(columnName, UINT64_FORMAT "_", generatingJobId);
appendStringInfo(columnName, "%u", columnIndex);
String *columnValue = makeString(columnName->data);
columnNameList = lappend(columnNameList, columnValue);
}
return columnNameList;
}
/*
* QueryTargetList returns the target entry list for the projected columns
* needed to evaluate the operators above the given multiNode. To do this,
* the function retrieves a list of all MultiProject nodes below the given
* node and picks the columns from the top-most MultiProject node, as this
* will be the minimal list of columns needed. Note that this function relies
* on a pre-order traversal of the operator tree by the function FindNodesOfType.
*/
static List *
QueryTargetList(MultiNode *multiNode)
{
List *projectNodeList = FindNodesOfType(multiNode, T_MultiProject);
if (list_length(projectNodeList) == 0)
{
/*
* The physical planner assumes that all worker queries would have
* target list entries based on the fact that at least the column
* on the JOINs have to be on the target list. However, there is
* an exception to that if there is a cartesian product join and
* there is no additional target list entries belong to one side
* of the JOIN. Once we support cartesian product join, we should
* remove this error.
*/
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot perform distributed planning on this query"),
errdetail("Cartesian products are currently unsupported")));
}
MultiProject *topProjectNode = (MultiProject *) linitial(projectNodeList);
List *columnList = topProjectNode->columnList;
List *queryTargetList = TargetEntryList(columnList);
Assert(queryTargetList != NIL);
return queryTargetList;
}
/*
* TargetEntryList creates a target entry for each expression in the given list,
* and returns the newly created target entries in a list.
*/
static List *
TargetEntryList(List *expressionList)
{
List *targetEntryList = NIL;
ListCell *expressionCell = NULL;
foreach(expressionCell, expressionList)
{
Expr *expression = (Expr *) lfirst(expressionCell);
int columnNumber = list_length(targetEntryList) + 1;
StringInfo columnName = makeStringInfo();
appendStringInfo(columnName, "column%d", columnNumber);
TargetEntry *targetEntry = makeTargetEntry(expression, columnNumber,
columnName->data, false);
targetEntryList = lappend(targetEntryList, targetEntry);
}
return targetEntryList;
}
/*
* WrapUngroupedVarsInAnyValueAggregate finds Var nodes in the expression
* that do not refer to any GROUP BY column and wraps them in an any_value
* aggregate. These columns are allowed when the GROUP BY is on a primary
* key of a relation, but not if we wrap the relation in a subquery.
* However, since we still know the value is unique, any_value gives the
* right result.
*/
Node *
WrapUngroupedVarsInAnyValueAggregate(Node *expression, List *groupClauseList,
List *targetList, bool checkExpressionEquality)
{
if (expression == NULL)
{
return NULL;
}
AddAnyValueAggregatesContext context;
context.groupClauseList = groupClauseList;
context.groupByTargetEntryList = GroupTargetEntryList(groupClauseList, targetList);
context.haveNonVarGrouping = false;
if (checkExpressionEquality)
{
/*
* If the GROUP BY contains non-Var expressions, we need to do an expensive
* subexpression equality check.
*/
TargetEntry *targetEntry = NULL;
foreach_ptr(targetEntry, context.groupByTargetEntryList)
{
if (!IsA(targetEntry->expr, Var))
{
context.haveNonVarGrouping = true;
break;
}
}
}
/* put the result in the same memory context */
MemoryContext nodeContext = GetMemoryChunkContext(expression);
MemoryContext oldContext = MemoryContextSwitchTo(nodeContext);
Node *result = expression_tree_mutator(expression, AddAnyValueAggregates,
&context);
MemoryContextSwitchTo(oldContext);
return result;
}
/*
* AddAnyValueAggregates wraps all vars that do not appear in the GROUP BY
* clause or are inside an aggregate function in an any_value aggregate
* function. This is needed because postgres allows columns that are not
* in the GROUP BY to appear on the target list as long as the primary key
* of the table is in the GROUP BY, but we sometimes wrap the join tree
* in a subquery in which case the primary key information is lost.
*
* This function copies parts of the node tree, but may contain references
* to the original node tree.
*
* The implementation is derived from / inspired by
* check_ungrouped_columns_walker.
*/
static Node *
AddAnyValueAggregates(Node *node, AddAnyValueAggregatesContext *context)
{
if (node == NULL)
{
return node;
}
if (IsA(node, Aggref) || IsA(node, GroupingFunc))
{
/* any column is allowed to appear in an aggregate or grouping */
return node;
}
else if (IsA(node, Var))
{
Var *var = (Var *) node;
/*
* Check whether this Var appears in the GROUP BY.
*/
TargetEntry *groupByTargetEntry = NULL;
foreach_ptr(groupByTargetEntry, context->groupByTargetEntryList)
{
if (!IsA(groupByTargetEntry->expr, Var))
{
continue;
}
Var *groupByVar = (Var *) groupByTargetEntry->expr;
/* we should only be doing this at the top level of the query */
Assert(groupByVar->varlevelsup == 0);
if (var->varno == groupByVar->varno &&
var->varattno == groupByVar->varattno)
{
/* this Var is in the GROUP BY, do not wrap it */
return node;
}
}
/*
* We have found a Var that does not appear in the GROUP BY.
* Wrap it in an any_value aggregate.
*/
Aggref *agg = makeNode(Aggref);
agg->aggfnoid = CitusAnyValueFunctionId();
agg->aggtype = var->vartype;
agg->args = list_make1(makeTargetEntry((Expr *) var, 1, NULL, false));
agg->aggkind = AGGKIND_NORMAL;
agg->aggtranstype = InvalidOid;
agg->aggargtypes = list_make1_oid(var->vartype);
agg->aggsplit = AGGSPLIT_SIMPLE;
agg->aggcollid = exprCollation((Node *) var);
return (Node *) agg;
}
else if (context->haveNonVarGrouping)
{
/*
* The GROUP BY contains at least one expression. Check whether the
* current expression is equal to one of the GROUP BY expressions.
* Otherwise, continue to descend into subexpressions.
*/
TargetEntry *groupByTargetEntry = NULL;
foreach_ptr(groupByTargetEntry, context->groupByTargetEntryList)
{