forked from scarbrofair/ppg_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathppg_planner.c
1990 lines (1800 loc) · 70.5 KB
/
ppg_planner.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
#include "postgres.h"
#include <limits.h>
#include <stdlib.h>
#include "catalog/pg_type.h"
#include "catalog/pg_class.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_operator.h"
#include "access/htup_details.h"
#include "executor/executor.h"
#include "executor/nodeAgg.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodes.h"
#include "nodes/parsenodes.h"
#ifdef OPTIMIZER_DEBUG
#include "nodes/print.h"
#endif
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/prep.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "parser/analyze.h"
#include "parser/parsetree.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "rewrite/rewriteManip.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "foreign/foreign.h"
#include "foreign/fdwapi.h"
#include "postgres_fdw.h"
#include "ppg_planner.h"
#include "util.h"
/* Expression kind codes for preprocess_expression */
#define EXPRKIND_QUAL 0
#define EXPRKIND_TARGET 1
#define EXPRKIND_RTFUNC 2
#define EXPRKIND_RTFUNC_LATERAL 3
#define EXPRKIND_VALUES 4
#define EXPRKIND_VALUES_LATERAL 5
#define EXPRKIND_LIMIT 6
#define EXPRKIND_APPINFO 7
#define EXPRKIND_PHV 8
typedef struct
{
List *outerList; /* the target list of finnal result*/
List *intelList; /* the target list for data from remote database*/
List *deparseList; /*just for deparse */
AttrNumber intelResno;
AttrNumber outerResno;
} TargetListContext;
typedef struct
{
Query *parse;
Node *currentExpr;
bool changed;
} RewriteOrignalTargetContext;
FdwRoutine *FDW_handler = NULL;
static planner_hook_type next_planner_hook = NULL;
static void preprocess_rowmarks(PlannerInfo *root);
static Node *preprocess_expression(PlannerInfo *root, Node *expr, int kind);
static void preprocess_groupclause(PlannerInfo *root);
static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode);
static bool limit_needed(Query *parse);
static List *make_fullplanTargetList(PlannerInfo *root, List *tlist, AttrNumber **groupColIdx, bool *need_tlist_eval,
List** havingTlePosition, List**havingTle);
static void locate_grouping_columns(PlannerInfo *root, List *tlist, List *sub_tlist, AttrNumber *groupColIdx);
static Plan *ppg_grouping_planner(PlannerInfo *root, double tuple_fraction);
static void createNewTargetEntryList(TargetListContext *targetListContext, List *targetList);
static TargetEntry *createNewAggTargetEntry(List *funcname, List *fargs, bool agg_star, bool agg_distinct, bool func_variadic,
bool resjunk, bool is_column, int location, char*colname, AttrNumber resno);
static void updateSortGroupClause (Query *parse, List *newTlist);
static void postProcessSortList(List *sortList, List *newTlist);
static int32 getTlistWidth(List *outerTleList);
static bool opHasAgg (Node *node);
static List *handleSubquery (PlannerInfo *root);
static void rewriteOrignalTargetList (PlannerInfo *root);
static void rewriteOrignalTargetListWalker (RewriteOrignalTargetContext *context);
static ForeignScan *deparsePlan(PlannerInfo *root, List* subplanList);
static FuncDetailCode getFuncDetailCode(List *funcname, List *fargs, Oid *rettype, Oid *funcid,
bool *retset, int *nvargs, Oid **declared_arg_types, bool func_variadic, List **argdefaults);
// borrowed from PG src
static bool limit_needed(Query *parse)
{
Node *node;
node = parse->limitCount;
if (node) {
if (IsA(node, Const)) {
if (!((Const *) node)->constisnull) {
return true;
}
} else {
return true; /* non-constant LIMIT */
}
}
node = parse->limitOffset;
if (node) {
if (IsA(node, Const)) {
if (!((Const *) node)->constisnull) {
int64 offset = DatumGetInt64(((Const *) node)->constvalue);
if (offset > 0) {
return true;
}
}
} else {
return true;
}
}
return false;
}
static void
preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
{
if (jtnode == NULL)
return;
if (IsA(jtnode, RangeTblRef))
{
/* nothing to do here */
}
else if (IsA(jtnode, FromExpr))
{
FromExpr *f = (FromExpr *) jtnode;
ListCell *l;
foreach(l, f->fromlist)
preprocess_qual_conditions(root, lfirst(l));
f->quals = preprocess_expression(root, f->quals, EXPRKIND_QUAL);
}
else if (IsA(jtnode, JoinExpr))
{
JoinExpr *j = (JoinExpr *) jtnode;
preprocess_qual_conditions(root, j->larg);
preprocess_qual_conditions(root, j->rarg);
j->quals = preprocess_expression(root, j->quals, EXPRKIND_QUAL);
}
else
elog(ERROR, "unrecognized node type: %d",
(int) nodeTag(jtnode));
}
/*
* preprocess_expression ------> borrow from the source code of PG
* Do subquery_planner's preprocessing work for an expression,
* which can be a targetlist, a WHERE clause (including JOIN/ON
* conditions), a HAVING clause, or a few other things.
*/
static Node *
preprocess_expression(PlannerInfo *root, Node *expr, int kind)
{
if (expr == NULL)
return NULL;
if (root->hasJoinRTEs &&
!(kind == EXPRKIND_RTFUNC || kind == EXPRKIND_VALUES))
expr = flatten_join_alias_vars(root, expr);
/*
* Simplify constant expressions.
*/
expr = eval_const_expressions(root, expr);
/*
* If it's a qual or havingQual, canonicalize it.
*/
if (kind == EXPRKIND_QUAL)
{
expr = (Node *) canonicalize_qual((Expr *) expr);
#ifdef OPTIMIZER_DEBUG
printf("After canonicalize_qual()\n");
pprint(expr);
#endif
}
/* SubLinks to be done */
if ((root->parse->hasSubLinks) && kind == EXPRKIND_QUAL) {
//expr = ppg_process_sublinks_in_having(root, expr, true);
}
if (kind == EXPRKIND_QUAL)
expr = (Node *) make_ands_implicit((Expr *) expr);
return expr;
}
static int
get_grouping_column_index(Query *parse, TargetEntry *tle)
{
int colno = 0;
Index ressortgroupref = tle->ressortgroupref;
ListCell *gl;
/* No need to search groupClause if TLE hasn't got a sortgroupref */
if (ressortgroupref == 0)
return -1;
foreach(gl, parse->groupClause)
{
SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
if (grpcl->tleSortGroupRef == ressortgroupref)
return colno;
colno++;
}
return -1;
}
static void
preprocess_groupclause(PlannerInfo *root)
{
Query *parse = root->parse;
List *new_groupclause;
bool partial_match;
ListCell *sl;
ListCell *gl;
/* If no ORDER BY, nothing useful to do here */
if (parse->sortClause == NIL)
return;
new_groupclause = NIL;
foreach(sl, parse->sortClause)
{
SortGroupClause *sc = (SortGroupClause *) lfirst(sl);
foreach(gl, parse->groupClause)
{
SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
if (equal(gc, sc))
{
new_groupclause = lappend(new_groupclause, gc);
break;
}
}
if (gl == NULL)
break; /* no match, so stop scanning */
}
/* Did we match all of the ORDER BY list, or just some of it? */
partial_match = (sl != NULL);
/* If no match at all, no point in reordering GROUP BY */
if (new_groupclause == NIL)
return;
foreach(gl, parse->groupClause)
{
SortGroupClause *gc = (SortGroupClause *) lfirst(gl);
if (list_member_ptr(new_groupclause, gc))
continue; /* it matched an ORDER BY item */
if (partial_match)
return; /* give up, no common sort possible */
if (!OidIsValid(gc->sortop))
return; /* give up, GROUP BY can't be sorted */
new_groupclause = lappend(new_groupclause, gc);
}
/* Success --- install the rearranged GROUP BY list */
Assert(list_length(parse->groupClause) == list_length(new_groupclause));
parse->groupClause = new_groupclause;
}
static List *
make_fullplanTargetList(PlannerInfo *root, List *tlist, AttrNumber **groupColIdx,
bool *need_tlist_eval, List** havingTlePosition, List**havingTle)
{
Query *parse = root->parse;
List *full_tlist;
List *non_group_cols;
int numCols;
int next_resno ;
ListCell *tl;
*groupColIdx = NULL;
if (!parse->hasAggs && !parse->groupClause && !root->hasHavingQual &&
!parse->hasWindowFuncs)
{
*need_tlist_eval = true;
return tlist;
}
full_tlist = NIL;
non_group_cols = NIL;
*need_tlist_eval = false; /* only eval if not flat tlist */
*havingTle = NIL;
*havingTlePosition = NIL;
numCols = list_length(parse->groupClause);
if (numCols > 0)
{
AttrNumber *grpColIdx;
grpColIdx = (AttrNumber *) palloc0(sizeof(AttrNumber) * numCols);
*groupColIdx = grpColIdx;
foreach(tl, tlist)
{
TargetEntry *tle = (TargetEntry *) lfirst(tl);
int colno;
colno = get_grouping_column_index(parse, tle);
if (colno >= 0)
{
TargetEntry *newtle;
newtle = makeTargetEntry(tle->expr,
list_length(full_tlist) + 1,
tle->resname,
false);
newtle->ressortgroupref = tle->ressortgroupref;
full_tlist = lappend(full_tlist, newtle);
Assert(grpColIdx[colno] == 0); /* no dups expected */
grpColIdx[colno] = newtle->resno;
if (!(newtle->expr && IsA(newtle->expr, Var)))
*need_tlist_eval = true; /* tlist contains non Vars */
}
else
{
non_group_cols = lappend(non_group_cols, tle);
}
}
}
else
{
non_group_cols = list_copy(tlist);
}
full_tlist = list_concat(full_tlist, non_group_cols);
non_group_cols = NULL;
if (parse->havingQual) {
*havingTle = pull_var_clause((Node *) (parse->havingQual),
PVC_INCLUDE_AGGREGATES,
PVC_INCLUDE_PLACEHOLDERS);
non_group_cols = list_copy(*havingTle);
}
next_resno = list_length(full_tlist) + 1;
foreach(tl, non_group_cols)
{
Node *expr = (Node *) lfirst(tl);
TargetEntry *noGroupTl = tlist_member(expr, full_tlist);
if (noGroupTl == NULL)
{
TargetEntry *tle;
*havingTlePosition = lappend_int(*havingTlePosition, next_resno);
tle = makeTargetEntry(copyObject(expr), /* copy needed?? */
next_resno++,
NULL,
false);
full_tlist = lappend(full_tlist, tle);
} else {
*havingTlePosition = lappend_int(*havingTlePosition, noGroupTl->resno);
}
}
/* clean up cruft */
list_free(non_group_cols);
return full_tlist;
}
/*
* locate_grouping_columns
* Locate grouping columns in the tlist chosen by create_plan.
*
* This is only needed if we don't use the sub_tlist chosen by
* make_fullplanTargetList. We have to forget the column indexes found
* by that routine and re-locate the grouping exprs in the real sub_tlist.
*/
static void
locate_grouping_columns(PlannerInfo *root,
List *tlist,
List *sub_tlist,
AttrNumber *groupColIdx)
{
int keyno = 0;
ListCell *gl;
/*
* No work unless grouping.
*/
if (!root->parse->groupClause)
{
Assert(groupColIdx == NULL);
return;
}
Assert(groupColIdx != NULL);
foreach(gl, root->parse->groupClause)
{
SortGroupClause *grpcl = (SortGroupClause *) lfirst(gl);
Node *groupexpr = get_sortgroupclause_expr(grpcl, tlist);
TargetEntry *te = tlist_member(groupexpr, sub_tlist);
if (!te)
elog(ERROR, "failed to locate grouping columns");
groupColIdx[keyno++] = te->resno;
}
}
/*
* preprocess_rowmarks - set up PlanRowMarks if needed
*/
static void
preprocess_rowmarks(PlannerInfo *root)
{
// to be done
}
static FuncDetailCode getFuncDetailCode(List *funcname, List *fargs, Oid *rettype, Oid *funcid,
bool *retset, int *nvargs, Oid **declared_arg_types, bool func_variadic,
List **argdefaults)
{
ListCell *l;
ListCell *nextl;
int nargs;
Oid actual_arg_types[FUNC_MAX_ARGS];
List *argnames;
FuncDetailCode fdresult;
if (list_length(fargs) > FUNC_MAX_ARGS)
ereport(ERROR,
(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
errmsg_plural("cannot pass more than %d argument to a function",
"cannot pass more than %d arguments to a function",
FUNC_MAX_ARGS,
FUNC_MAX_ARGS)));
nargs = 0;
for (l = list_head(fargs); l != NULL; l = nextl)
{
Node *arg = lfirst(l);
Oid argtype = exprType(arg);
nextl = lnext(l);
if (argtype == VOIDOID && IsA(arg, Param) )
{
fargs = list_delete_ptr(fargs, arg);
continue;
}
actual_arg_types[nargs++] = argtype;
}
argnames = NIL;
foreach(l, fargs)
{
Node *arg = lfirst(l);
if (IsA(arg, NamedArgExpr))
{
NamedArgExpr *na = (NamedArgExpr *) arg;
ListCell *lc;
/* Reject duplicate arg names */
foreach(lc, argnames)
{
if (strcmp(na->name, (char *) lfirst(lc)) == 0)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("argument name \"%s\" used more than once",
na->name)));
}
argnames = lappend(argnames, na->name);
}
else
{
if (argnames != NIL)
ereport(ERROR,
(errcode(ERRCODE_SYNTAX_ERROR),
errmsg("positional argument cannot follow named argument")));
}
}
fdresult = func_get_detail(funcname, fargs, argnames, nargs,
actual_arg_types,
!func_variadic, true,
funcid, rettype, retset, nvargs,
declared_arg_types, argdefaults);
return fdresult;
}
static TargetEntry *createNewAggTargetEntry(List *funcname, List *fargs, bool agg_star, bool agg_distinct, bool func_variadic,
bool resjunk, bool is_column, int location, char*colname, AttrNumber resno)
{
Oid rettype;
Oid funcid;
Oid *declared_arg_types;
List *argdefaults;
bool retset;
int nvargs;
FuncDetailCode fdresult = getFuncDetailCode(funcname, fargs, &rettype, &funcid,
&retset, &nvargs, &declared_arg_types, func_variadic, &argdefaults);
Assert(fdresult == FUNCDETAIL_AGGREGATE);
Aggref *aggref = (Aggref*)makeNode(Aggref);
aggref->aggfnoid = funcid;
aggref->aggtype = rettype;
aggref->aggstar = agg_star;
aggref->location = location;
aggref->args = fargs;
return makeTargetEntry((Expr *)aggref, resno, colname, resjunk);
}
/*
* create new target list so that we can push down agg to backend nodes
* */
static void createNewTargetEntryList(TargetListContext *targetListContext, List *targetList)
{
TargetEntry * tmpTle = NULL;
TargetEntry *currentTle = NULL;
ListCell *tl = NULL;
Node * currentExpr = NULL;
AttrNumber tmpResno = 1;
foreach(tl, targetList)
{
//uptle = NULL;
if (IsA((Node*)lfirst(tl), TargetEntry)) {
currentTle = (TargetEntry *)lfirst(tl);
currentExpr = (Node*)(currentTle->expr);
} else if (IsA((Node*)lfirst(tl), Var) || IsA((Node*)lfirst(tl), Aggref) ||
IsA((Node*)lfirst(tl), OpExpr) || IsA((Node*)lfirst(tl), CaseExpr) ||
IsA((Node*)lfirst(tl), Const) || IsA((Node*)lfirst(tl), FuncExpr)) {
currentExpr = (Node*)lfirst(tl);
// set resno to be -1, will be fixed later
currentTle = makeTargetEntry((Expr *)currentExpr,-1, NULL, false);
} else {
ereport(ERROR, (errmsg("ppg_fdw does not support this node type ")));
}
if (IsA(currentExpr, Aggref)){
Aggref *aggOld = (Aggref*)(currentExpr);
char * aggname = getFuncName(aggOld->aggfnoid);
if(strcmp(aggname,"avg" ) == 0) {
/* for avg node, we need to rewrite it to be (/) (OpExpr)
/ \
/ \
(sum) (sum)
/ \
/ \
(sum) (count) the nodes on this level will be sent to remote db
*/
List* sumArg = NIL;
ListCell *lc;
foreach(lc, aggOld->args)
{
TargetEntry *aggArgTle = (TargetEntry *)lfirst(lc);
sumArg = lappend(sumArg, aggArgTle->expr);
}
// make the sum node which will be parsed and pusd down to remote database, so just make sure the semantic is right
List* sum =list_make1(makeString("sum"));
TargetEntry *targetSum = createNewAggTargetEntry(sum, sumArg, false, false, false, currentTle->resjunk, false, aggOld->location,
currentTle->resname, targetListContext->intelResno);
((Aggref*)(targetSum->expr))->args = (List *) copyObject(((Aggref*)(currentExpr))->args);
targetListContext->intelResno++;
targetListContext->deparseList = lappend(targetListContext->deparseList, targetSum);
// make the count node which will be parsed and pusd down to remote database, so just make sure the semantic is right
List* count = list_make1(makeString("count"));
List* cntArg = sumArg;
TargetEntry *targetCnt = createNewAggTargetEntry(count, cntArg,false,false,false, currentTle->resjunk, false, aggOld->location,
currentTle->resname, targetListContext->intelResno);
((Aggref*)(targetCnt->expr))->args = (List *) copyObject(((Aggref*)(currentExpr))->args);
targetListContext->intelResno++;
targetListContext->deparseList = lappend(targetListContext->deparseList, targetCnt);
// make the var node to represent the sum node created just now. And this var will be the parameter to sum node uper
// so make the uper sum node, this node is the left parameter to "/" op node
// make sure the resno is right for var node, which need some tricky
sumArg = NULL;
sumArg = lappend(sumArg, (Aggref*)(targetSum->expr));
TargetEntry *upperLeftSum = createNewAggTargetEntry(sum, sumArg, false, false, false, currentTle? currentTle->resjunk:false, false,
((Aggref*)(targetSum->expr))->location, currentTle?currentTle->resname:NULL, targetSum->resno);
Var* leftTleVar = makeVar(targetSum->resno, targetSum->resno, ((Aggref*)(targetSum->expr))->aggtype, -1,
((Aggref*)(targetSum->expr))->aggcollid, 0);
TargetEntry * intelLeftTle = (TargetEntry *)makeTargetEntry((Expr*)leftTleVar, targetSum->resno,
currentTle->resname, currentTle->resjunk);
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(intelLeftTle));
/*since we know just it is count agg, so set the resno to bt 1*/
intelLeftTle->resno = 1;
((Aggref*)(upperLeftSum->expr))->args = list_make1(intelLeftTle);
// make the var node to represent the count node created just now. And this var will be the parameter to sum node uper
// so make the uper sum node at the same time, this node is the right parameter to "/" op node
sumArg = NULL;
sumArg = lappend(sumArg, (Aggref*)(targetCnt->expr));
TargetEntry *upperRightSum = createNewAggTargetEntry(sum, sumArg, false, false, false, targetCnt->resjunk, false,
((Aggref*)(targetCnt->expr))->location, targetCnt->resname, targetCnt->resno);
Var* rightTleVar = makeVar(targetCnt->resno, targetCnt->resno, ((Aggref*)(targetCnt->expr))->aggtype, -1,
((Aggref*)(targetCnt->expr))->aggcollid, 0);
TargetEntry * intelRightTle = (TargetEntry *)makeTargetEntry((Expr*)rightTleVar, targetCnt->resno, currentTle->resname, currentTle->resjunk);
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(intelRightTle));
/*since we know just it is sum agg, so set the resno to bt 1*/
intelRightTle->resno = 1;
((Aggref*)(upperRightSum->expr))->args = list_make1(intelRightTle);
// make the "/" operator node, please make sure the parameters is right, and the resno is OK
List* devide = list_make1(makeString("/"));
Operator tup = oper(NULL,devide,((Aggref*)(upperLeftSum->expr))->aggtype,((Aggref*)(upperRightSum->expr))->aggtype,false,targetListContext->outerResno);
Form_pg_operator opform = (Form_pg_operator) GETSTRUCT(tup);
OpExpr *result = makeNode(OpExpr);
result->opno = oprid(tup);
result->opfuncid = opform->oprcode;
result->opresulttype = opform->oprresult;//rettype;
result->opretset = get_func_retset(opform->oprcode);
result->args = list_make2(upperLeftSum->expr, upperRightSum->expr);
result->location = aggOld->location;
ReleaseSysCache(tup);
tmpTle = (TargetEntry *)makeTargetEntry((Expr *)result, targetListContext->outerResno,
currentTle->resname, currentTle->resjunk);
if (currentTle->ressortgroupref > 0) {
tmpTle->ressortgroupref = currentTle->ressortgroupref ;
}
targetListContext->outerList = lappend(targetListContext->outerList,tmpTle);
targetListContext->outerResno++;
} else if(strcmp(aggname, "count") == 0 || strcmp(aggname, "sum") == 0) {
// for count/sum node, we need to rewrite the node as this:
// sum
// |
// |
// sum or count // push down to remote database
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->deparseList);
if (tmpTle != NULL) {
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->intelList);
tmpResno = tmpTle->resno;
} else {
targetListContext->deparseList = lappend(targetListContext->deparseList, (TargetEntry *)copyObject(currentTle));
tmpResno = targetListContext->intelResno;
currentTle->resno = targetListContext->intelResno;
targetListContext->intelResno++;
}
Var* tleVar = makeVar(tmpResno, tmpResno, aggOld->aggtype, -1, aggOld->aggcollid, 0);
tleVar->location = exprLocation((Node*)(currentExpr));
TargetEntry * intelTle = (TargetEntry *)makeTargetEntry((Expr*)tleVar, tmpResno, currentTle->resname, currentTle->resjunk);
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(intelTle));
// just one arg, so set the resno to be 1
intelTle->resno = 1;
List* funcname = list_make1(makeString("sum"));
List* funArg = list_make1(tleVar);
tmpTle = createNewAggTargetEntry(funcname, funArg, false, false, false, currentTle->resjunk, false,
aggOld->location, currentTle->resname, targetListContext->outerResno);
((Aggref*)(tmpTle->expr))->args = list_make1(intelTle);
//s = nodeToString(tmpTle);
//elog(INFO, "\n output top expr %s\n", pretty_format_node_dump(s));
if (currentTle->ressortgroupref > 0) {
tmpTle->ressortgroupref = currentTle->ressortgroupref ;
}
targetListContext->outerList = lappend(targetListContext->outerList, tmpTle);
targetListContext->outerResno++;
} else if(strcmp(aggname, "max") == 0 || strcmp(aggname, "min") == 0){
// for max and min, we rewrite it as following;
// max or min
// |
// |
// max or min // push down to remote database
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->deparseList);
if (tmpTle != NULL) {
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->intelList);
currentTle->resno = targetListContext->outerResno;
((Var*)currentExpr)->varattno = tmpTle->resno;
targetListContext->outerList = lappend(targetListContext->outerList, (TargetEntry *)copyObject(currentTle));
} else {
targetListContext->deparseList = lappend(targetListContext->deparseList, (TargetEntry *) copyObject(currentTle));
currentTle->resno = targetListContext->intelResno;
//targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(currentTle));
TargetEntry * newTle = (TargetEntry *)copyObject(currentTle);
Var* tleVar = makeVar(targetListContext->intelResno, targetListContext->intelResno, aggOld->aggtype, -1, aggOld->aggcollid, 0);
tleVar->location = exprLocation((Node*)(currentExpr));
TargetEntry * intelTle = (TargetEntry *)makeTargetEntry((Expr*)tleVar, targetListContext->intelResno, NULL, currentTle->resjunk);
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(intelTle));
intelTle->resno = 1;
((Aggref*)(newTle->expr))->args = list_make1(intelTle);
newTle->resno = targetListContext->outerResno;
targetListContext->outerList = lappend(targetListContext->outerList, (TargetEntry *)copyObject(newTle));
++targetListContext->intelResno;
}
targetListContext->outerResno++;
} else {
ereport(LOG, (errmsg("unkown name ")));
}
} else if (IsA(currentExpr, Var) || IsA(currentExpr, Const)){
// for var node, is simple, the var node is the same as the var node local, execpt the resno
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->deparseList);
if (tmpTle != NULL) {
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->intelList);
currentTle->resno = targetListContext->outerResno;
((Var*)currentExpr)->varattno = tmpTle->resno;
} else {
currentTle->resno = targetListContext->intelResno;
targetListContext->deparseList = lappend(targetListContext->deparseList, (TargetEntry *) copyObject(currentTle));
((Var*)currentExpr)->varattno = targetListContext->intelResno;
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(currentTle));
currentTle->resno = targetListContext->outerResno;
targetListContext->intelResno++;
}
targetListContext->outerList = lappend(targetListContext->outerList, (TargetEntry *) copyObject(currentTle));
targetListContext->outerResno++;
} else if (IsA(currentExpr, FuncExpr)) {
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->deparseList);
if (tmpTle != NULL) {
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->intelList);
currentTle->resno = targetListContext->outerResno;
((Var*)currentExpr)->varattno = tmpTle->resno;
} else {
currentTle->resno = targetListContext->intelResno;
targetListContext->deparseList = lappend(targetListContext->deparseList, (TargetEntry *) copyObject(currentTle));
Var* tleVar = makeVar(targetListContext->intelResno, targetListContext->intelResno, ((FuncExpr*)currentExpr)->funcresulttype,
-1, ((FuncExpr*)currentExpr)->funccollid, 0);
tleVar->location = exprLocation((Node*)(currentExpr));
TargetEntry * intelTle = (TargetEntry *)makeTargetEntry((Expr*)tleVar, targetListContext->intelResno, currentTle->resname, currentTle->resjunk);
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(intelTle));
if (currentTle->ressortgroupref > 0) {
intelTle->ressortgroupref = currentTle->ressortgroupref ;
}
currentTle = intelTle;
targetListContext->intelResno++;
}
currentTle->resno = targetListContext->outerResno;
targetListContext->outerList = lappend(targetListContext->outerList, (TargetEntry *) copyObject(currentTle));
targetListContext->outerResno++;
} else if (IsA(currentExpr, OpExpr)) {
// for operator node, how to rewrite the node depends on whether the parameter is Agg
// if parameters don't contan Agg, we need to rewrite it as:
// var
// |
// |
// op op push down to remote database
// else, the rewriten node is little of complicated
// op
// / \
// / \
// op op note: op can be a recurse expression
// / \ / \ for example: count(a) + sum(b)*avg(c)
// / \ / \ //
// agg agg agg agg
// / \ / \ / \ / \
// agg agg agg agg agg agg agg agg push down to remote database
OpExpr *opExpr = (OpExpr*)(currentExpr);
if (!opHasAgg((Node*)opExpr)) {
// no agg argument, just create a var
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->deparseList);
if (tmpTle != NULL) {
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->intelList);
currentTle = (TargetEntry *) copyObject(tmpTle);
} else {
currentTle->resno = targetListContext->intelResno;
targetListContext->deparseList = lappend(targetListContext->deparseList, (TargetEntry *) copyObject(currentTle));
Var* tleVar = makeVar(targetListContext->intelResno, targetListContext->intelResno, opExpr->opresulttype, -1, opExpr->opcollid, 0);
tleVar->location = exprLocation((Node*)(currentExpr));
TargetEntry * intelTle = (TargetEntry *)makeTargetEntry((Expr*)tleVar, targetListContext->intelResno, currentTle->resname, currentTle->resjunk);
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(intelTle));
if (currentTle->ressortgroupref > 0) {
intelTle->ressortgroupref = currentTle->ressortgroupref ;
}
currentTle = intelTle;
targetListContext->intelResno++;
}
currentTle->resno = targetListContext->outerResno;
targetListContext->outerList = lappend(targetListContext->outerList, currentTle);
targetListContext->outerResno++;
} else {
TargetListContext *tmpTargetListContext = (TargetListContext *)palloc0(sizeof(TargetListContext));
List *operArgs = NULL;
TargetEntry *tmpLeftTle = NULL;
TargetEntry *tmpRightTle = NULL;
char * opName = get_opname(opExpr->opno);
if (opName == NULL) {
ereport(ERROR, (errmsg("Failed to get the operator name")));
}
List* opNameStr = list_make1(makeString(opName));
tmpTargetListContext->deparseList = targetListContext->deparseList;
tmpTargetListContext->intelList = targetListContext->intelList;
tmpTargetListContext->intelResno = targetListContext->intelResno;
tmpTargetListContext->outerResno = targetListContext->intelResno;
createNewTargetEntryList(tmpTargetListContext, opExpr->args);
targetListContext->deparseList = tmpTargetListContext->deparseList;
targetListContext->intelList = tmpTargetListContext->intelList;
targetListContext->intelResno = tmpTargetListContext->outerResno;
if (length(tmpTargetListContext->outerList)==1) {
ListCell *tmpLeftCell = list_head(tmpTargetListContext->outerList);
tmpLeftTle = (TargetEntry *)lfirst(tmpLeftCell);
operArgs = list_make1((Expr *) copyObject(tmpLeftTle->expr));
} else if (length(tmpTargetListContext->outerList)==2) {
ListCell *tmpLeftCell = list_head(tmpTargetListContext->outerList);
tmpLeftTle = (TargetEntry *)lfirst(tmpLeftCell);
ListCell *tmpRightCell = lnext(tmpLeftCell);
tmpRightTle = (TargetEntry *)lfirst(tmpRightCell);
operArgs = list_make2((Expr *) copyObject(tmpLeftTle->expr),
(Expr *) copyObject(tmpRightTle->expr));
} else {
ereport(ERROR, (errmsg("the number of args should be 1 or 2")));
}
Operator tup = oper(NULL,opNameStr,exprType((Node*)(tmpLeftTle->expr)),
tmpRightTle ? exprType((Node*)(tmpRightTle->expr)) : InvalidOid,
false,targetListContext->outerResno);
Form_pg_operator opform = (Form_pg_operator) GETSTRUCT(tup);
OpExpr *result = makeNode(OpExpr);
result->opno = oprid(tup);
result->opfuncid = opform->oprcode;
result->opresulttype = opform->oprresult;//rettype;
result->opretset = get_func_retset(opform->oprcode);
result->args = operArgs;
result->location = targetListContext->outerResno;
tmpTle = (TargetEntry *)makeTargetEntry((Expr *)result, targetListContext->outerResno,
currentTle->resname, currentTle->resjunk);
if (currentTle->ressortgroupref > 0) {
tmpTle->ressortgroupref = currentTle->ressortgroupref ;
}
ReleaseSysCache(tup);
targetListContext->outerList = lappend(targetListContext->outerList, tmpTle);
targetListContext->outerResno++;
}
} else if (IsA(currentExpr, CaseExpr)) {
// for CaseExpr, we need to rewrite it as:
// var
// |
// |
// CaseExpr // CaseExpr push down to remote database
CaseExpr *caseExpr = (CaseExpr*)(currentExpr);
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->deparseList);
if (tmpTle != NULL) {
tmpTle = tlist_member((Node*)(currentExpr), targetListContext->intelList);
currentTle = (TargetEntry *) copyObject(tmpTle);
} else {
currentTle->resno = targetListContext->intelResno;
targetListContext->deparseList = lappend(targetListContext->deparseList, (TargetEntry *) copyObject(currentTle));
Var* tleVar = makeVar(targetListContext->intelResno, targetListContext->intelResno, caseExpr->casetype, -1, caseExpr->casecollid, 0);
tleVar->location = exprLocation((Node*)(currentExpr));
TargetEntry * intelTle = (TargetEntry *)makeTargetEntry((Expr*)tleVar, targetListContext->intelResno, currentTle->resname, currentTle->resjunk);
targetListContext->intelList = lappend(targetListContext->intelList, (TargetEntry *) copyObject(intelTle));
if (currentTle->ressortgroupref > 0) {
intelTle->ressortgroupref = currentTle->ressortgroupref ;
}
currentTle = intelTle;
targetListContext->intelResno++;
}
currentTle->resno = targetListContext->outerResno;
targetListContext->outerList = lappend(targetListContext->outerList, currentTle);
targetListContext->outerResno++;
} else {
ereport(ERROR, (errmsg("does not support this node type ")));
}
}
}
static bool opHasAgg (Node *node)
{
bool result = false;
Assert( IsA(node, OpExpr));
OpExpr *opExpr = (OpExpr*)(node);
ListCell *tmpCell;
foreach (tmpCell, opExpr->args) {
if (IsA((Node*)lfirst(tmpCell), Aggref)) {
result = true;
} else if (IsA((Node*)lfirst(tmpCell), OpExpr)) {
result = opHasAgg((Node*)lfirst(tmpCell));
}
if (result) {
break;
}
}
return result;
}
static int32 getTlistWidth(List *outerTleList)
{
ListCell *lc;
int32 item_width = 0;
int32 tmp = 0;
foreach(lc, outerTleList)
{
TargetEntry *tle = (TargetEntry *) lfirst(lc);
tmp= get_typavgwidth(exprType(tle->expr), exprTypmod(tle->expr));
if (tmp == 32){
item_width += 4;
} else {
item_width += tmp;
}
}
return item_width;
}
static List *handleSubquery (PlannerInfo *root)
{
List *subplanList = NULL;
ListCell *lc;
Query *parse = root->parse;
SubPlanPath planPath;
planPath.root = root;
planPath.source = NULL;
planPath.planID = 0;
planPath.subPlanList = NULL;
planPath.outRows = 0;
planPath.rowSize = 0;
getSubPlanPath(parse, &planPath);
foreach (lc, planPath.subPlanList)
{
SubPlanPath *subPath = lfirst(lc);
SubQueryPlan* subplan = (SubQueryPlan*)palloc(sizeof(SubQueryPlan));
createSubplan(subplan, subPath->source);
subplan->subplanIndex = subPath->planID;
subplan->dmethod = All;
subplanList = lappend(subplanList,subplan);
}
if (length(parse->jointree->fromlist) == 1 && length(subplanList) == 1) {
Node *fromNode = lfirst(list_head(parse->jointree->fromlist));
if (IsA(fromNode, RangeTblRef)) {
int varno = ((RangeTblRef *) fromNode)->rtindex;
RangeTblEntry *fromRte = rt_fetch(varno, parse->rtable);
Node *srcNode = ((SubPlanPath *)lfirst(list_head(planPath.subPlanList)))->source;
if (equal(fromRte, srcNode)) {
ListCell *lc1;
forboth (lc, subplanList, lc1, planPath.subPlanList)
{
SubPlanPath *subPath = lfirst(lc1);
if (subPath->type == InFrom) {
SubQueryPlan* subplan = lfirst(lc);
subplan->dmethod = RoundRobin;
}
}
}
}
}
return subplanList;
}
// It will be called when subquery exsits
static void rewriteOrignalTargetList (PlannerInfo *root)
{
Query *parse = root->parse;
ListCell *lc;
RewriteOrignalTargetContext context;
context.parse = parse;
context.currentExpr = NULL;
foreach(lc, parse->targetList) {
TargetEntry *curTe = lfirst(lc);
context.currentExpr = curTe->expr;
context.changed = false;
rewriteOrignalTargetListWalker(&context);
}
}