summaryrefslogtreecommitdiff
path: root/src/backend/optimizer/plan/setrefs.c
blob: 78d76960f809a9627f2d4d25c577a4159056a268 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
/*-------------------------------------------------------------------------
 *
 * setrefs.c
 *	  Routines to change varno/attno entries to contain references
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $Header: /cvsroot/pgsql/src/backend/optimizer/plan/setrefs.c,v 1.39 1999/02/13 23:16:33 momjian Exp $
 *
 *-------------------------------------------------------------------------
 */
#include <sys/types.h>

#include "postgres.h"

#include "nodes/pg_list.h"
#include "nodes/plannodes.h"
#include "nodes/primnodes.h"
#include "nodes/relation.h"

#include "utils/elog.h"
#include "nodes/nodeFuncs.h"
#include "nodes/makefuncs.h"

#include "optimizer/internal.h"
#include "optimizer/clauses.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/keys.h"
#include "optimizer/planmain.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "optimizer/tlist.h"

static void set_join_tlist_references(Join *join);
static void set_nonamescan_tlist_references(SeqScan *nonamescan);
static void set_noname_tlist_references(Noname *noname);
static List *replace_clause_joinvar_refs(Expr *clause,
							List *outer_tlist, List *inner_tlist);
static List *replace_subclause_joinvar_refs(List *clauses,
							   List *outer_tlist, List *inner_tlist);
static Var *replace_joinvar_refs(Var *var, List *outer_tlist, List *inner_tlist);
static List *tlist_noname_references(Oid nonameid, List *tlist);
static void replace_result_clause(Node *clause, List *subplanTargetList);
static bool OperandIsInner(Node *opnd, int inner_relid);
static List *replace_agg_clause(Node *expr, List *targetlist);
static Node *del_agg_clause(Node *clause);
static void set_result_tlist_references(Result *resultNode);

/*****************************************************************************
 *
 *		SUBPLAN REFERENCES
 *
 *****************************************************************************/

/*
 * set_tlist_references
 *	  Modifies the target list of nodes in a plan to reference target lists
 *	  at lower levels.
 *
 * 'plan' is the plan whose target list and children's target lists will
 *		be modified
 *
 * Returns nothing of interest, but modifies internal fields of nodes.
 *
 */
void
set_tlist_references(Plan *plan)
{
	if (plan == NULL)
		return;

	if (IsA_Join(plan))
		set_join_tlist_references((Join *) plan);
	else if (IsA(plan, SeqScan) &&plan->lefttree &&
			 IsA_Noname(plan->lefttree))
		set_nonamescan_tlist_references((SeqScan *) plan);
	else if (IsA(plan, Sort))
		set_noname_tlist_references((Noname *) plan);
	else if (IsA(plan, Result))
		set_result_tlist_references((Result *) plan);
	else if (IsA(plan, Hash))
		set_tlist_references(plan->lefttree);
}

/*
 * set_join_tlist_references
 *	  Modifies the target list of a join node by setting the varnos and
 *	  varattnos to reference the target list of the outer and inner join
 *	  relations.
 *
 *	  Creates a target list for a join node to contain references by setting
 *	  varno values to OUTER or INNER and setting attno values to the
 *	  result domain number of either the corresponding outer or inner join
 *	  tuple.
 *
 * 'join' is a join plan node
 *
 * Returns nothing of interest, but modifies internal fields of nodes.
 *
 */
static void
set_join_tlist_references(Join *join)
{
	Plan	   *outer = ((Plan *) join)->lefttree;
	Plan	   *inner = ((Plan *) join)->righttree;
	List	   *new_join_targetlist = NIL;
	TargetEntry *temp = (TargetEntry *) NULL;
	List	   *entry = NIL;
	List	   *inner_tlist = NULL;
	List	   *outer_tlist = NULL;
	TargetEntry *xtl = (TargetEntry *) NULL;
	List	   *qptlist = ((Plan *) join)->targetlist;

	foreach(entry, qptlist)
	{
		List	   *joinvar;

		xtl = (TargetEntry *) lfirst(entry);
		inner_tlist = ((inner == NULL) ? NIL : inner->targetlist);
		outer_tlist = ((outer == NULL) ? NIL : outer->targetlist);
		joinvar = replace_clause_joinvar_refs((Expr *) get_expr(xtl),
											  outer_tlist,
											  inner_tlist);

		temp = makeTargetEntry(xtl->resdom, (Node *) joinvar);
		new_join_targetlist = lappend(new_join_targetlist, temp);
	}

	((Plan *) join)->targetlist = new_join_targetlist;
	if (outer != NULL)
		set_tlist_references(outer);
	if (inner != NULL)
		set_tlist_references(inner);
}

/*
 * set_nonamescan_tlist_references
 *	  Modifies the target list of a node that scans a noname relation (i.e., a
 *	  sort or hash node) so that the varnos refer to the child noname.
 *
 * 'nonamescan' is a seqscan node
 *
 * Returns nothing of interest, but modifies internal fields of nodes.
 *
 */
static void
set_nonamescan_tlist_references(SeqScan *nonamescan)
{
	Noname	   *noname = (Noname *) ((Plan *) nonamescan)->lefttree;

	((Plan *) nonamescan)->targetlist = tlist_noname_references(noname->nonameid,
							  ((Plan *) nonamescan)->targetlist);
	set_noname_tlist_references(noname);
}

/*
 * set_noname_tlist_references
 *	  The noname's vars are made consistent with (actually, identical to) the
 *	  modified version of the target list of the node from which noname node
 *	  receives its tuples.
 *
 * 'noname' is a noname (e.g., sort, hash) plan node
 *
 * Returns nothing of interest, but modifies internal fields of nodes.
 *
 */
static void
set_noname_tlist_references(Noname *noname)
{
	Plan	   *source = ((Plan *) noname)->lefttree;

	if (source != NULL)
	{
		set_tlist_references(source);
		((Plan *) noname)->targetlist = copy_vars(((Plan *) noname)->targetlist,
					  (source)->targetlist);
	}
	else
		elog(ERROR, "calling set_noname_tlist_references with empty lefttree");
}

/*
 * join_references
 *	   Creates a new set of join clauses by replacing the varno/varattno
 *	   values of variables in the clauses to reference target list values
 *	   from the outer and inner join relation target lists.
 *
 * 'clauses' is the list of join clauses
 * 'outer_tlist' is the target list of the outer join relation
 * 'inner_tlist' is the target list of the inner join relation
 *
 * Returns the new join clauses.
 *
 */
List *
join_references(List *clauses,
				List *outer_tlist,
				List *inner_tlist)
{
	return (replace_subclause_joinvar_refs(clauses,
										   outer_tlist,
										   inner_tlist));
}

/*
 * index_outerjoin_references
 *	  Given a list of join clauses, replace the operand corresponding to the
 *	  outer relation in the join with references to the corresponding target
 *	  list element in 'outer_tlist' (the outer is rather obscurely
 *	  identified as the side that doesn't contain a var whose varno equals
 *	  'inner_relid').
 *
 *	  As a side effect, the operator is replaced by the regproc id.
 *
 * 'inner_indxqual' is the list of join clauses (so-called because they
 * are used as qualifications for the inner (inbex) scan of a nestloop)
 *
 * Returns the new list of clauses.
 *
 */
List *
index_outerjoin_references(List *inner_indxqual,
						   List *outer_tlist,
						   Index inner_relid)
{
	List	   *t_list = NIL;
	Expr	   *temp = NULL;
	List	   *t_clause = NIL;
	Expr	   *clause = NULL;

	foreach(t_clause, inner_indxqual)
	{
		clause = lfirst(t_clause);

		/*
		 * if inner scan on the right.
		 */
		if (OperandIsInner((Node *) get_rightop(clause), inner_relid))
		{
			Var		   *joinvar = (Var *)
			replace_clause_joinvar_refs((Expr *) get_leftop(clause),
										outer_tlist,
										NIL);

			temp = make_opclause(replace_opid((Oper *) ((Expr *) clause)->oper),
								 joinvar,
								 get_rightop(clause));
			t_list = lappend(t_list, temp);
		}
		else
		{
			/* inner scan on left */
			Var		   *joinvar = (Var *)
			replace_clause_joinvar_refs((Expr *) get_rightop(clause),
										outer_tlist,
										NIL);

			temp = make_opclause(replace_opid((Oper *) ((Expr *) clause)->oper),
								 get_leftop(clause),
								 joinvar);
			t_list = lappend(t_list, temp);
		}

	}
	return t_list;
}

/*
 * replace_clause_joinvar_refs
 * replace_subclause_joinvar_refs
 * replace_joinvar_refs
 *
 *	  Replaces all variables within a join clause with a new var node
 *	  whose varno/varattno fields contain a reference to a target list
 *	  element from either the outer or inner join relation.
 *
 * 'clause' is the join clause
 * 'outer_tlist' is the target list of the outer join relation
 * 'inner_tlist' is the target list of the inner join relation
 *
 * Returns the new join clause.
 *
 */
static List *
replace_clause_joinvar_refs(Expr *clause,
							List *outer_tlist,
							List *inner_tlist)
{
	List	   *temp = NULL;

	if (IsA(clause, Var))
	{
		temp = (List *) replace_joinvar_refs((Var *) clause,
											 outer_tlist, inner_tlist);
		if (temp != NULL)
			return temp;
		else if (clause != NULL)
			return (List *) clause;
		else
			return NIL;
	}
	else if (single_node((Node *) clause))
		return (List *) clause;
	else if (and_clause((Node *) clause))
	{
		List	   *andclause = replace_subclause_joinvar_refs(((Expr *) clause)->args,
									   outer_tlist,
									   inner_tlist);

		return (List *) make_andclause(andclause);
	}
	else if (or_clause((Node *) clause))
	{
		List	   *orclause = replace_subclause_joinvar_refs(((Expr *) clause)->args,
									   outer_tlist,
									   inner_tlist);

		return (List *) make_orclause(orclause);
	}
	else if (IsA(clause, ArrayRef))
	{
		ArrayRef   *aref = (ArrayRef *) clause;

		temp = replace_subclause_joinvar_refs(aref->refupperindexpr,
											  outer_tlist,
											  inner_tlist);
		aref->refupperindexpr = (List *) temp;
		temp = replace_subclause_joinvar_refs(aref->reflowerindexpr,
											  outer_tlist,
											  inner_tlist);
		aref->reflowerindexpr = (List *) temp;
		temp = replace_clause_joinvar_refs((Expr *) aref->refexpr,
										   outer_tlist,
										   inner_tlist);
		aref->refexpr = (Node *) temp;

		/*
		 * no need to set refassgnexpr.  we only set that in the target
		 * list on replaces, and this is an array reference in the
		 * qualification.  if we got this far, it's 0x0 in the ArrayRef
		 * structure 'clause'.
		 */

		return (List *) clause;
	}
	else if (is_funcclause((Node *) clause))
	{
		List	   *funcclause = replace_subclause_joinvar_refs(((Expr *) clause)->args,
									   outer_tlist,
									   inner_tlist);

		return ((List *) make_funcclause((Func *) ((Expr *) clause)->oper,
										 funcclause));
	}
	else if (not_clause((Node *) clause))
	{
		List	   *notclause = replace_clause_joinvar_refs(get_notclausearg(clause),
									outer_tlist,
									inner_tlist);

		return (List *) make_notclause((Expr *) notclause);
	}
	else if (is_opclause((Node *) clause))
	{
		Var		   *leftvar = (Var *) replace_clause_joinvar_refs((Expr *) get_leftop(clause),
											outer_tlist,
											inner_tlist);
		Var		   *rightvar = (Var *) replace_clause_joinvar_refs((Expr *) get_rightop(clause),
											outer_tlist,
											inner_tlist);

		return ((List *) make_opclause(replace_opid((Oper *) ((Expr *) clause)->oper),
									   leftvar,
									   rightvar));
	}
	else if (is_subplan(clause))
	{
		((Expr *) clause)->args = replace_subclause_joinvar_refs(((Expr *) clause)->args,
										   outer_tlist,
										   inner_tlist);
		((SubPlan *) ((Expr *) clause)->oper)->sublink->oper =
			replace_subclause_joinvar_refs(((SubPlan *) ((Expr *) clause)->oper)->sublink->oper,
										   outer_tlist,
										   inner_tlist);
		return (List *) clause;
	}
	else if (IsA(clause, CaseExpr))
	{
		((CaseExpr *) clause)->args =
			(List *) replace_subclause_joinvar_refs(((CaseExpr *) clause)->args,
													outer_tlist,
													inner_tlist);

		((CaseExpr *) clause)->defresult =
			(Node *) replace_clause_joinvar_refs((Expr *) ((CaseExpr *) clause)->defresult,
												 outer_tlist,
												 inner_tlist);
		return (List *) clause;
	}
	else if (IsA(clause, CaseWhen))
	{
		((CaseWhen *) clause)->expr =
			(Node *) replace_clause_joinvar_refs((Expr *) ((CaseWhen *) clause)->expr,
												 outer_tlist,
												 inner_tlist);

		((CaseWhen *) clause)->result =
			(Node *) replace_clause_joinvar_refs((Expr *) ((CaseWhen *) clause)->result,
												 outer_tlist,
												 inner_tlist);
		return (List *) clause;
	}

	/* shouldn't reach here */
	elog(ERROR, "replace_clause_joinvar_refs: unsupported clause %d",
		 nodeTag(clause));
	return NULL;
}

static List *
replace_subclause_joinvar_refs(List *clauses,
							   List *outer_tlist,
							   List *inner_tlist)
{
	List	   *t_list = NIL;
	List	   *temp = NIL;
	List	   *clause = NIL;

	foreach(clause, clauses)
	{
		temp = replace_clause_joinvar_refs(lfirst(clause),
										   outer_tlist,
										   inner_tlist);
		t_list = lappend(t_list, temp);
	}
	return t_list;
}

static Var *
replace_joinvar_refs(Var *var, List *outer_tlist, List *inner_tlist)
{
	Resdom	   *outer_resdom = (Resdom *) NULL;

	outer_resdom = tlist_member(var, outer_tlist);

	if (outer_resdom != NULL && IsA(outer_resdom, Resdom))
	{
		return (makeVar(OUTER,
						outer_resdom->resno,
						var->vartype,
						var->vartypmod,
						0,
						var->varnoold,
						var->varoattno));
	}
	else
	{
		Resdom	   *inner_resdom;

		inner_resdom = tlist_member(var, inner_tlist);
		if (inner_resdom != NULL && IsA(inner_resdom, Resdom))
		{
			return (makeVar(INNER,
							inner_resdom->resno,
							var->vartype,
							var->vartypmod,
							0,
							var->varnoold,
							var->varoattno));
		}
	}
	return (Var *) NULL;
}

/*
 * tlist_noname_references
 *	  Creates a new target list for a node that scans a noname relation,
 *	  setting the varnos to the id of the noname relation and setting varids
 *	  if necessary (varids are only needed if this is a targetlist internal
 *	  to the tree, in which case the targetlist entry always contains a var
 *	  node, so we can just copy it from the noname).
 *
 * 'nonameid' is the id of the noname relation
 * 'tlist' is the target list to be modified
 *
 * Returns new target list
 *
 */
static List *
tlist_noname_references(Oid nonameid,
					  List *tlist)
{
	List	   *t_list = NIL;
	TargetEntry *noname = (TargetEntry *) NULL;
	TargetEntry *xtl = NULL;
	List	   *entry;

	foreach(entry, tlist)
	{
		AttrNumber	oattno;

		xtl = lfirst(entry);
		if (IsA(get_expr(xtl), Var))
			oattno = ((Var *) xtl->expr)->varoattno;
		else
			oattno = 0;

		noname = makeTargetEntry(xtl->resdom,
							   (Node *) makeVar(nonameid,
												xtl->resdom->resno,
												xtl->resdom->restype,
												xtl->resdom->restypmod,
												0,
												nonameid,
												oattno));

		t_list = lappend(t_list, noname);
	}
	return t_list;
}

/*---------------------------------------------------------
 *
 * set_result_tlist_references
 *
 * Change the target list of a Result node, so that it correctly
 * addresses the tuples returned by its left tree subplan.
 *
 * NOTE:
 *	1) we ignore the right tree! (in the current implementation
 *	   it is always nil
 *	2) this routine will probably *NOT* work with nested dot
 *	   fields....
 */
static void
set_result_tlist_references(Result *resultNode)
{
	Plan	   *subplan;
	List	   *resultTargetList;
	List	   *subplanTargetList;
	List	   *t;
	TargetEntry *entry;
	Expr	   *expr;

	resultTargetList = ((Plan *) resultNode)->targetlist;

	/*
	 * NOTE: we only consider the left tree subplan. This is usually a seq
	 * scan.
	 */
	subplan = ((Plan *) resultNode)->lefttree;
	if (subplan != NULL)
		subplanTargetList = subplan->targetlist;
	else
		subplanTargetList = NIL;

	/*
	 * now for traverse all the entris of the target list. These should be
	 * of the form (Resdom_Node Expression). For every expression clause,
	 * call "replace_result_clause()" to appropriatelly change all the Var
	 * nodes.
	 */
	foreach(t, resultTargetList)
	{
		entry = (TargetEntry *) lfirst(t);
		expr = (Expr *) get_expr(entry);
		replace_result_clause((Node *) expr, subplanTargetList);
	}
}

/*---------------------------------------------------------
 *
 * replace_result_clause
 *
 * This routine is called from set_result_tlist_references().
 * and modifies the expressions of the target list of a Result
 * node so that all Var nodes reference the target list of its subplan.
 *
 */
static void
replace_result_clause(Node *clause,
					  List *subplanTargetList)	/* target list of the
												 * subplan */
{
	List	   *t;

	if (IsA(clause, Var))
	{
		TargetEntry *subplanVar;

		/*
		 * Ha! A Var node!
		 */
		subplanVar = match_varid((Var *) clause, subplanTargetList);

		/*
		 * Change the varno & varattno fields of the var node.
		 *
		 */
		((Var *) clause)->varno = (Index) OUTER;
		((Var *) clause)->varattno = subplanVar->resdom->resno;
	}
	else if (IsA(clause, Aggref))
		replace_result_clause(((Aggref *) clause)->target, subplanTargetList);
	else if (is_funcclause(clause))
	{
		List	   *subExpr;

		/*
		 * This is a function. Recursively call this routine for its
		 * arguments...
		 */
		subExpr = ((Expr *) clause)->args;
		foreach(t, subExpr)
			replace_result_clause(lfirst(t), subplanTargetList);
	}
	else if (IsA(clause, ArrayRef))
	{
		ArrayRef   *aref = (ArrayRef *) clause;

		/*
		 * This is an arrayref. Recursively call this routine for its
		 * expression and its index expression...
		 */
		foreach(t, aref->refupperindexpr)
			replace_result_clause(lfirst(t), subplanTargetList);
		foreach(t, aref->reflowerindexpr)
			replace_result_clause(lfirst(t), subplanTargetList);
		replace_result_clause(aref->refexpr,
							  subplanTargetList);
		replace_result_clause(aref->refassgnexpr,
							  subplanTargetList);
	}
	else if (is_opclause(clause))
	{
		Node	   *subNode;

		/*
		 * This is an operator. Recursively call this routine for both its
		 * left and right operands
		 */
		subNode = (Node *) get_leftop((Expr *) clause);
		replace_result_clause(subNode, subplanTargetList);
		subNode = (Node *) get_rightop((Expr *) clause);
		replace_result_clause(subNode, subplanTargetList);
	}
	else if (IsA(clause, Param) ||IsA(clause, Const))
	{
		/* do nothing! */
	}
	else
	{

		/*
		 * Ooops! we can not handle that!
		 */
		elog(ERROR, "replace_result_clause: Can not handle this tlist!\n");
	}
}

static
bool
OperandIsInner(Node *opnd, int inner_relid)
{

	/*
	 * Can be the inner scan if its a varnode or a function and the
	 * inner_relid is equal to the varnode's var number or in the case of
	 * a function the first argument's var number (all args in a
	 * functional index are from the same relation).
	 */
	if (IsA(opnd, Var) &&
		(inner_relid == ((Var *) opnd)->varno))
		return true;
	if (is_funcclause(opnd))
	{
		List	   *firstArg = lfirst(((Expr *) opnd)->args);

		if (IsA(firstArg, Var) &&
			(inner_relid == ((Var *) firstArg)->varno))
			return true;
	}
	return false;
}

/*****************************************************************************
 *
 *****************************************************************************/

/*---------------------------------------------------------
 *
 * get_agg_tlist_references -
 *	  generates the target list of an Agg node so that it points to
 *	  the tuples returned by its left tree subplan.
 *
 *	We now also generate a linked list of Aggref pointers for Agg.
 *
 */
List *
get_agg_tlist_references(Agg *aggNode)
{
	List	   *aggTargetList;
	List	   *subplanTargetList;
	List	   *tl;
	List	   *aggreg_list = NIL;

	aggTargetList = aggNode->plan.targetlist;
	subplanTargetList = aggNode->plan.lefttree->targetlist;

	foreach(tl, aggTargetList)
	{
		TargetEntry *tle = lfirst(tl);

		aggreg_list = nconc(
		  replace_agg_clause(tle->expr, subplanTargetList), aggreg_list);
	}
	return aggreg_list;
}

static List *
replace_agg_clause(Node *clause, List *subplanTargetList)
{
	List	   *t;
	List	   *agg_list = NIL;

	if (IsA(clause, Var))
	{
		TargetEntry *subplanVar;

		/*
		 * Ha! A Var node!
		 */
		subplanVar = match_varid((Var *) clause, subplanTargetList);

		/*
		 * Change the varno & varattno fields of the var node.
		 *
		 */
		((Var *) clause)->varattno = subplanVar->resdom->resno;

		return NIL;
	}
	else if (is_funcclause(clause))
	{

		/*
		 * This is a function. Recursively call this routine for its
		 * arguments...
		 */
		foreach(t, ((Expr *) clause)->args)
		{
			agg_list = nconc(agg_list,
					   replace_agg_clause(lfirst(t), subplanTargetList));
		}
		return agg_list;
	}
	else if (IsA(clause, Aggref))
	{
		return lcons(clause,
					 replace_agg_clause(((Aggref *) clause)->target, subplanTargetList));
	}
	else if (IsA(clause, ArrayRef))
	{
		ArrayRef   *aref = (ArrayRef *) clause;

		/*
		 * This is an arrayref. Recursively call this routine for its
		 * expression and its index expression...
		 */
		foreach(t, aref->refupperindexpr)
		{
			agg_list = nconc(agg_list,
					   replace_agg_clause(lfirst(t), subplanTargetList));
		}
		foreach(t, aref->reflowerindexpr)
		{
			agg_list = nconc(agg_list,
					   replace_agg_clause(lfirst(t), subplanTargetList));
		}
		agg_list = nconc(agg_list,
				   replace_agg_clause(aref->refexpr, subplanTargetList));
		agg_list = nconc(agg_list,
			  replace_agg_clause(aref->refassgnexpr, subplanTargetList));

		return agg_list;
	}
	else if (is_opclause(clause))
	{

		/*
		 * This is an operator. Recursively call this routine for both its
		 * left and right operands
		 */
		Node	   *left = (Node *) get_leftop((Expr *) clause);
		Node	   *right = (Node *) get_rightop((Expr *) clause);

		if (left != (Node *) NULL)
			agg_list = nconc(agg_list,
							 replace_agg_clause(left, subplanTargetList));
		if (right != (Node *) NULL)
			agg_list = nconc(agg_list,
						   replace_agg_clause(right, subplanTargetList));

		return agg_list;
	}
	else if (IsA(clause, Param) ||IsA(clause, Const))
	{
		/* do nothing! */
		return NIL;
	}
	else
	{

		/*
		 * Ooops! we can not handle that!
		 */
		elog(ERROR, "replace_agg_clause: Can not handle this tlist!\n");
		return NIL;
	}
}


/*
 * del_agg_tlist_references
 *	  Remove the Agg nodes from the target list
 *	  We do this so inheritance only does aggregates in the upper node
 */
void
del_agg_tlist_references(List *tlist)
{
	List	   *tl;

	foreach(tl, tlist)
	{
		TargetEntry *tle = lfirst(tl);

		tle->expr = del_agg_clause(tle->expr);
	}
}

static Node *
del_agg_clause(Node *clause)
{
	List	   *t;

	if (IsA(clause, Var))
		return clause;
	else if (is_funcclause(clause))
	{

		/*
		 * This is a function. Recursively call this routine for its
		 * arguments...
		 */
		foreach(t, ((Expr *) clause)->args)
			lfirst(t) = del_agg_clause(lfirst(t));
	}
	else if (IsA(clause, Aggref))
	{

		/* here is the real action, to remove the Agg node */
		return del_agg_clause(((Aggref *) clause)->target);

	}
	else if (IsA(clause, ArrayRef))
	{
		ArrayRef   *aref = (ArrayRef *) clause;

		/*
		 * This is an arrayref. Recursively call this routine for its
		 * expression and its index expression...
		 */
		foreach(t, aref->refupperindexpr)
			lfirst(t) = del_agg_clause(lfirst(t));
		foreach(t, aref->reflowerindexpr)
			lfirst(t) = del_agg_clause(lfirst(t));
		aref->refexpr = del_agg_clause(aref->refexpr);
		aref->refassgnexpr = del_agg_clause(aref->refassgnexpr);
	}
	else if (is_opclause(clause))
	{

		/*
		 * This is an operator. Recursively call this routine for both its
		 * left and right operands
		 */
		Node	   *left = (Node *) get_leftop((Expr *) clause);
		Node	   *right = (Node *) get_rightop((Expr *) clause);

		if (left != (Node *) NULL)
			left = del_agg_clause(left);
		if (right != (Node *) NULL)
			right = del_agg_clause(right);
	}
	else if (IsA(clause, Param) ||IsA(clause, Const))
		return clause;
	else
	{

		/*
		 * Ooops! we can not handle that!
		 */
		elog(ERROR, "del_agg_clause: Can not handle this tlist!\n");
	}
	return NULL;
}

/***S*H***/
/* check_having_qual_for_vars takes the the havingQual and the actual targetlist as arguments
 * and recursively scans the havingQual for attributes that are not included in the targetlist
 * yet. Attributes contained in the havingQual but not in the targetlist show up with queries
 * like:
 * SELECT sid
 * FROM part
 * GROUP BY sid
 * HAVING MIN(pid) > 1;  (pid is used but never selected for!!!).
 * To be able to handle queries like that correctly we have to extend the actual targetlist
 *	(which will be the one used for the GROUP node later on) by these attributes. */
List *
check_having_qual_for_vars(Node *clause, List *targetlist_so_far)
{
	List	   *t;


	if (IsA(clause, Var))
	{
		RelOptInfo	tmp_rel;


		tmp_rel.targetlist = targetlist_so_far;

		/*
		 * Ha! A Var node!
		 */

		/* Check if the VAR is already contained in the targetlist */
		if (tlist_member((Var *) clause, (List *) targetlist_so_far) == NULL)
			add_var_to_tlist(&tmp_rel, (Var *) clause);

		return tmp_rel.targetlist;
	}

	else if (is_funcclause(clause) || not_clause(clause) ||
			 or_clause(clause) || and_clause(clause))
	{

		/*
		 * This is a function. Recursively call this routine for its
		 * arguments...
		 */
		foreach(t, ((Expr *) clause)->args)
			targetlist_so_far = check_having_qual_for_vars(lfirst(t), targetlist_so_far);
		return targetlist_so_far;
	}
	else if (IsA(clause, Aggref))
	{
		targetlist_so_far = check_having_qual_for_vars(((Aggref *) clause)->target, targetlist_so_far);
		return targetlist_so_far;
	}
	else if (IsA(clause, ArrayRef))
	{
		ArrayRef   *aref = (ArrayRef *) clause;

		/*
		 * This is an arrayref. Recursively call this routine for its
		 * expression and its index expression...
		 */
		foreach(t, aref->refupperindexpr)
			targetlist_so_far = check_having_qual_for_vars(lfirst(t), targetlist_so_far);
		foreach(t, aref->reflowerindexpr)
			targetlist_so_far = check_having_qual_for_vars(lfirst(t), targetlist_so_far);
		targetlist_so_far = check_having_qual_for_vars(aref->refexpr, targetlist_so_far);
		targetlist_so_far = check_having_qual_for_vars(aref->refassgnexpr, targetlist_so_far);

		return targetlist_so_far;
	}
	else if (is_opclause(clause))
	{

		/*
		 * This is an operator. Recursively call this routine for both its
		 * left and right operands
		 */
		Node	   *left = (Node *) get_leftop((Expr *) clause);
		Node	   *right = (Node *) get_rightop((Expr *) clause);

		if (left != (Node *) NULL)
			targetlist_so_far = check_having_qual_for_vars(left, targetlist_so_far);
		if (right != (Node *) NULL)
			targetlist_so_far = check_having_qual_for_vars(right, targetlist_so_far);

		return targetlist_so_far;
	}
	else if (IsA(clause, Param) ||IsA(clause, Const))
	{
		/* do nothing! */
		return targetlist_so_far;
	}

	/*
	 * If we get to a sublink, then we only have to check the lefthand
	 * side of the expression to see if there are any additional VARs
	 */
	else if (IsA(clause, SubLink))
	{
		foreach(t, ((List *) ((SubLink *) clause)->lefthand))
			targetlist_so_far = check_having_qual_for_vars(lfirst(t), targetlist_so_far);
		return targetlist_so_far;
	}
	else
	{

		/*
		 * Ooops! we can not handle that!
		 */
		elog(ERROR, "check_having_qual_for_vars: Can not handle this having_qual! %d\n",
			 nodeTag(clause));
		return NIL;
	}
}

/* check_having_qual_for_aggs takes the havingQual, the targetlist and the groupClause
 * as arguments and scans the havingQual recursively for aggregates. If an aggregate is
 * found it is attached to a list and returned by the function. (All the returned lists
 * are concenated to result_plan->aggs in planner.c:union_planner() */
List *
check_having_qual_for_aggs(Node *clause, List *subplanTargetList, List *groupClause)
{
	List	   *t,
			   *l1;
	List	   *agg_list = NIL;

	int			contained_in_group_clause = 0;


	if (IsA(clause, Var))
	{
		TargetEntry *subplanVar;

		/*
		 * Ha! A Var node!
		 */
		subplanVar = match_varid((Var *) clause, subplanTargetList);

		/*
		 * Change the varno & varattno fields of the var node to point to
		 * the resdom->resno fields of the subplan (lefttree)
		 */
		((Var *) clause)->varattno = subplanVar->resdom->resno;

		return NIL;

	}
	/***S*H***/
	else if (is_funcclause(clause) || not_clause(clause) ||
			 or_clause(clause) || and_clause(clause))
	{
		int			new_length = 0,
					old_length = 0;

		/*
		 * This is a function. Recursively call this routine for its
		 * arguments... (i.e. for AND, OR, ... clauses!)
		 */
		foreach(t, ((Expr *) clause)->args)
		{
			old_length = length((List *) agg_list);

			agg_list = nconc(agg_list,
				 check_having_qual_for_aggs(lfirst(t), subplanTargetList,
											groupClause));

			/*
			 * The arguments of OR or AND clauses are comparisons or
			 * relations and because we are in the havingQual there must
			 * be at least one operand using an aggregate function. If so,
			 * we will find it and the length of the agg_list will be
			 * increased after the above call to
			 * check_having_qual_for_aggs. If there are no aggregates
			 * used, the query could have been formulated using the
			 * 'where' clause
			 */
			if (((new_length = length((List *) agg_list)) == old_length) || (new_length == 0))
			{
				elog(ERROR, "This could have been done in a where clause!!");
				return NIL;
			}
		}
		return agg_list;
	}
	else if (IsA(clause, Aggref))
	{
		return lcons(clause,
					 check_having_qual_for_aggs(((Aggref *) clause)->target, subplanTargetList,
												groupClause));
	}
	else if (IsA(clause, ArrayRef))
	{
		ArrayRef   *aref = (ArrayRef *) clause;

		/*
		 * This is an arrayref. Recursively call this routine for its
		 * expression and its index expression...
		 */
		foreach(t, aref->refupperindexpr)
		{
			agg_list = nconc(agg_list,
				 check_having_qual_for_aggs(lfirst(t), subplanTargetList,
											groupClause));
		}
		foreach(t, aref->reflowerindexpr)
		{
			agg_list = nconc(agg_list,
				 check_having_qual_for_aggs(lfirst(t), subplanTargetList,
											groupClause));
		}
		agg_list = nconc(agg_list,
			 check_having_qual_for_aggs(aref->refexpr, subplanTargetList,
										groupClause));
		agg_list = nconc(agg_list,
		check_having_qual_for_aggs(aref->refassgnexpr, subplanTargetList,
								   groupClause));

		return agg_list;
	}
	else if (is_opclause(clause))
	{

		/*
		 * This is an operator. Recursively call this routine for both its
		 * left and right operands
		 */
		Node	   *left = (Node *) get_leftop((Expr *) clause);
		Node	   *right = (Node *) get_rightop((Expr *) clause);

		if (left != (Node *) NULL)
			agg_list = nconc(agg_list,
					  check_having_qual_for_aggs(left, subplanTargetList,
												 groupClause));
		if (right != (Node *) NULL)
			agg_list = nconc(agg_list,
					 check_having_qual_for_aggs(right, subplanTargetList,
												groupClause));

		return agg_list;
	}
	else if (IsA(clause, Param) ||IsA(clause, Const))
	{
		/* do nothing! */
		return NIL;
	}

	/*
	 * This is for Sublinks which show up as EXPR nodes. All the other
	 * EXPR nodes (funcclauses, and_clauses, or_clauses) were caught above
	 */
	else if (IsA(clause, Expr))
	{

		/*
		 * Only the lefthand side of the sublink has to be checked for
		 * aggregates to be attached to result_plan->aggs (see
		 * planner.c:union_planner() )
		 */
		foreach(t, ((List *) ((SubLink *) ((SubPlan *)
						   ((Expr *) clause)->oper)->sublink)->lefthand))
		{
			agg_list = nconc(agg_list,
					  check_having_qual_for_aggs(lfirst(t),
										subplanTargetList, groupClause));
		}

		/* The first argument of ...->oper has also to be checked */
		{
			List	   *tmp_ptr;

			foreach(tmp_ptr, ((SubLink *) ((SubPlan *)
								((Expr *) clause)->oper)->sublink)->oper)
			{
				agg_list = nconc(agg_list,
						 check_having_qual_for_aggs((Node *) lfirst(((Expr *)
												 lfirst(tmp_ptr))->args),
										subplanTargetList, groupClause));
			}
		}

		/*
		 * All arguments to the Sublink node are attributes from outside
		 * used within the sublink. Here we have to check that only
		 * attributes that is grouped for are used!
		 */
		foreach(t, ((Expr *) clause)->args)
		{
			contained_in_group_clause = 0;

			foreach(l1, groupClause)
			{
				if (tlist_member(lfirst(t), lcons(((GroupClause *) lfirst(l1))->entry, NIL)) !=
					NULL)
					contained_in_group_clause = 1;
			}

			/*
			 * If the use of the attribute is allowed (i.e. it is in the
			 * groupClause) we have to adjust the varnos and varattnos
			 */
			if (contained_in_group_clause)
			{
				agg_list = nconc(agg_list,
						  		 check_having_qual_for_aggs(lfirst(t),
										subplanTargetList, groupClause));
			}
			else
			{
				elog(ERROR, "You must group by the attribute used from outside!");
				return NIL;
			}
		}
		return agg_list;
	}
	else
	{
		/*
		 * Ooops! we can not handle that!
		 */
		elog(ERROR, "check_having_qual_for_aggs: Can not handle this having_qual! %d\n",
			 nodeTag(clause));
		return NIL;
	}
}

 /***S*H***//* End */