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
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
|
/*-------------------------------------------------------------------------
*
* createplan.c
* Routines to create the desired plan for processing a query.
* Planning is complete, we just need to convert the selected
* Path into a Plan.
*
* Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/optimizer/plan/createplan.c,v 1.76 1999/08/22 23:56:44 tgl Exp $
*
*-------------------------------------------------------------------------
*/
#include <sys/types.h>
#include "postgres.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/internal.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/tlist.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"
static List *switch_outer(List *clauses);
static int set_tlist_sort_info(List *tlist, List *pathkeys);
static Scan *create_scan_node(Path *best_path, List *tlist);
static Join *create_join_node(JoinPath *best_path, List *tlist);
static SeqScan *create_seqscan_node(Path *best_path, List *tlist,
List *scan_clauses);
static IndexScan *create_indexscan_node(IndexPath *best_path, List *tlist,
List *scan_clauses);
static NestLoop *create_nestloop_node(NestPath *best_path, List *tlist,
List *clauses, Plan *outer_node, List *outer_tlist,
Plan *inner_node, List *inner_tlist);
static MergeJoin *create_mergejoin_node(MergePath *best_path, List *tlist,
List *clauses, Plan *outer_node, List *outer_tlist,
Plan *inner_node, List *inner_tlist);
static HashJoin *create_hashjoin_node(HashPath *best_path, List *tlist,
List *clauses, Plan *outer_node, List *outer_tlist,
Plan *inner_node, List *inner_tlist);
static List *fix_indxqual_references(List *indexquals, IndexPath *index_path);
static List *fix_indxqual_sublist(List *indexqual, IndexPath *index_path,
Form_pg_index index);
static Node *fix_indxqual_operand(Node *node, IndexPath *index_path,
Form_pg_index index);
static IndexScan *make_indexscan(List *qptlist, List *qpqual, Index scanrelid,
List *indxid, List *indxqual, List *indxqualorig);
static NestLoop *make_nestloop(List *qptlist, List *qpqual, Plan *lefttree,
Plan *righttree);
static HashJoin *make_hashjoin(List *tlist, List *qpqual,
List *hashclauses, Plan *lefttree, Plan *righttree);
static Hash *make_hash(List *tlist, Var *hashkey, Plan *lefttree);
static MergeJoin *make_mergejoin(List *tlist, List *qpqual,
List *mergeclauses, Plan *righttree, Plan *lefttree);
static Material *make_material(List *tlist, Oid nonameid, Plan *lefttree,
int keycount);
static void copy_costsize(Plan *dest, Plan *src);
/*
* create_plan
* Creates the access plan for a query by tracing backwards through the
* desired chain of pathnodes, starting at the node 'best_path'. For
* every pathnode found:
* (1) Create a corresponding plan node containing appropriate id,
* target list, and qualification information.
* (2) Modify qual clauses of join nodes so that subplan attributes are
* referenced using relative values.
* (3) Target lists are not modified, but will be in setrefs.c.
*
* best_path is the best access path
*
* Returns the access plan.
*/
Plan *
create_plan(Path *best_path)
{
List *tlist;
Plan *plan_node = (Plan *) NULL;
RelOptInfo *parent_rel;
int size;
int width;
int pages;
int tuples;
parent_rel = best_path->parent;
tlist = parent_rel->targetlist;
size = parent_rel->size;
width = parent_rel->width;
pages = parent_rel->pages;
tuples = parent_rel->tuples;
switch (best_path->pathtype)
{
case T_IndexScan:
case T_SeqScan:
plan_node = (Plan *) create_scan_node(best_path, tlist);
break;
case T_HashJoin:
case T_MergeJoin:
case T_NestLoop:
plan_node = (Plan *) create_join_node((JoinPath *) best_path, tlist);
break;
default:
/* do nothing */
break;
}
plan_node->plan_size = size;
plan_node->plan_width = width;
if (pages == 0)
pages = 1;
plan_node->plan_tupperpage = tuples / pages;
#ifdef NOT_USED /* fix xfunc */
/* sort clauses by cost/(1-selectivity) -- JMH 2/26/92 */
if (XfuncMode != XFUNC_OFF)
{
set_qpqual((Plan) plan_node,
lisp_qsort(get_qpqual((Plan) plan_node),
xfunc_clause_compare));
if (XfuncMode != XFUNC_NOR)
/* sort the disjuncts within each clause by cost -- JMH 3/4/92 */
xfunc_disjunct_sort(plan_node->qpqual);
}
#endif
return plan_node;
}
/*
* create_scan_node
* Create a scan path for the parent relation of 'best_path'.
*
* tlist is the targetlist for the base relation scanned by 'best_path'
*
* Returns the scan node.
*/
static Scan *
create_scan_node(Path *best_path, List *tlist)
{
Scan *node = NULL;
List *scan_clauses;
/*
* Extract the relevant restriction clauses from the parent relation;
* the executor must apply all these restrictions during the scan.
*/
scan_clauses = get_actual_clauses(best_path->parent->restrictinfo);
switch (best_path->pathtype)
{
case T_SeqScan:
node = (Scan *) create_seqscan_node(best_path, tlist, scan_clauses);
break;
case T_IndexScan:
node = (Scan *) create_indexscan_node((IndexPath *) best_path,
tlist,
scan_clauses);
break;
default:
elog(ERROR, "create_scan_node: unknown node type",
best_path->pathtype);
break;
}
return node;
}
/*
* create_join_node
* Create a join path for 'best_path' and(recursively) paths for its
* inner and outer paths.
*
* 'tlist' is the targetlist for the join relation corresponding to
* 'best_path'
*
* Returns the join node.
*/
static Join *
create_join_node(JoinPath *best_path, List *tlist)
{
Plan *outer_node;
List *outer_tlist;
Plan *inner_node;
List *inner_tlist;
List *clauses;
Join *retval = NULL;
outer_node = create_plan((Path *) best_path->outerjoinpath);
outer_tlist = outer_node->targetlist;
inner_node = create_plan((Path *) best_path->innerjoinpath);
inner_tlist = inner_node->targetlist;
clauses = get_actual_clauses(best_path->pathinfo);
switch (best_path->path.pathtype)
{
case T_MergeJoin:
retval = (Join *) create_mergejoin_node((MergePath *) best_path,
tlist,
clauses,
outer_node,
outer_tlist,
inner_node,
inner_tlist);
break;
case T_HashJoin:
retval = (Join *) create_hashjoin_node((HashPath *) best_path,
tlist,
clauses,
outer_node,
outer_tlist,
inner_node,
inner_tlist);
break;
case T_NestLoop:
retval = (Join *) create_nestloop_node((NestPath *) best_path,
tlist,
clauses,
outer_node,
outer_tlist,
inner_node,
inner_tlist);
break;
default:
elog(ERROR, "create_join_node: unknown node type",
best_path->path.pathtype);
}
#ifdef NOT_USED
/*
* * Expensive function pullups may have pulled local predicates *
* into this path node. Put them in the qpqual of the plan node. *
* JMH, 6/15/92
*/
if (get_loc_restrictinfo(best_path) != NIL)
set_qpqual((Plan) retval,
nconc(get_qpqual((Plan) retval),
get_actual_clauses(get_loc_restrictinfo(best_path))));
#endif
return retval;
}
/*****************************************************************************
*
* BASE-RELATION SCAN METHODS
*
*****************************************************************************/
/*
* create_seqscan_node
* Returns a seqscan node for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*/
static SeqScan *
create_seqscan_node(Path *best_path, List *tlist, List *scan_clauses)
{
SeqScan *scan_node = (SeqScan *) NULL;
Index scan_relid = -1;
List *temp;
temp = best_path->parent->relids;
/* there should be exactly one base rel involved... */
Assert(length(temp) == 1);
scan_relid = (Index) lfirsti(temp);
scan_node = make_seqscan(tlist,
scan_clauses,
scan_relid);
scan_node->plan.cost = best_path->path_cost;
return scan_node;
}
/*
* create_indexscan_node
* Returns a indexscan node for the base relation scanned by 'best_path'
* with restriction clauses 'scan_clauses' and targetlist 'tlist'.
*
* The indexqual of the path contains a sublist of implicitly-ANDed qual
* conditions for each scan of the index(es); if there is more than one
* scan then the retrieved tuple sets are ORed together. The indexqual
* and indexid lists must have the same length, ie, the number of scans
* that will occur. Note it is possible for a qual condition sublist
* to be empty --- then no index restrictions will be applied during that
* scan.
*/
static IndexScan *
create_indexscan_node(IndexPath *best_path,
List *tlist,
List *scan_clauses)
{
List *indxqual = best_path->indexqual;
List *qpqual;
List *fixed_indxqual;
List *ixid;
IndexScan *scan_node;
bool lossy = false;
/* there should be exactly one base rel involved... */
Assert(length(best_path->path.parent->relids) == 1);
/* check and see if any of the indices are lossy */
foreach(ixid, best_path->indexid)
{
HeapTuple indexTuple;
Form_pg_index index;
indexTuple = SearchSysCacheTuple(INDEXRELID,
ObjectIdGetDatum(lfirsti(ixid)),
0, 0, 0);
if (!HeapTupleIsValid(indexTuple))
elog(ERROR, "create_plan: index %u not found", lfirsti(ixid));
index = (Form_pg_index) GETSTRUCT(indexTuple);
if (index->indislossy)
{
lossy = true;
break;
}
}
/*
* The qpqual list must contain all restrictions not automatically
* handled by the index. Note that for non-lossy indices, the
* predicates in the indxqual are checked fully by the index, while
* for lossy indices the indxqual predicates need to be double-checked
* after the index fetches the best-guess tuples.
*
* Since the indexquals were generated from the restriction clauses
* given by scan_clauses, there will normally be some duplications
* between the lists. Get rid of the duplicates, then add back if lossy.
*/
if (length(indxqual) > 1)
{
/*
* Build an expression representation of the indexqual, expanding
* the implicit OR and AND semantics of the first- and second-level
* lists. XXX Is it really necessary to do a deep copy here?
*/
List *orclauses = NIL;
List *orclause;
Expr *indxqual_expr;
foreach(orclause, indxqual)
{
orclauses = lappend(orclauses,
make_ands_explicit((List *) copyObject(lfirst(orclause))));
}
indxqual_expr = make_orclause(orclauses);
/* this set_difference is almost certainly a waste of time... */
qpqual = set_difference(scan_clauses,
lcons(indxqual_expr, NIL));
if (lossy)
qpqual = lappend(qpqual, indxqual_expr);
}
else if (indxqual != NIL)
{
/* Here, we can simply treat the first sublist as an independent
* set of qual expressions, since there is no top-level OR behavior.
*/
qpqual = set_difference(scan_clauses, lfirst(indxqual));
if (lossy)
qpqual = nconc(qpqual, (List *) copyObject(lfirst(indxqual)));
}
else
qpqual = NIL;
/* The executor needs a copy with the indexkey on the left of each clause
* and with index attr numbers substituted for table ones.
*/
fixed_indxqual = fix_indxqual_references(indxqual, best_path);
scan_node = make_indexscan(tlist,
qpqual,
lfirsti(best_path->path.parent->relids),
best_path->indexid,
fixed_indxqual,
indxqual);
scan_node->scan.plan.cost = best_path->path.path_cost;
return scan_node;
}
/*****************************************************************************
*
* JOIN METHODS
*
* A general note about join_references() processing in these routines:
* once we have changed a Var node to refer to a subplan output rather than
* the original relation, it is no longer equal() to an unmodified Var node
* for the same var. So, we cannot easily compare reference-adjusted qual
* clauses to clauses that have not been adjusted. Fortunately, that
* doesn't seem to be necessary; all the decisions are made before we do
* the reference adjustments.
*
* A cleaner solution would be to not call join_references() here at all,
* but leave it for setrefs.c to do at the end of plan tree construction.
* But that would make switch_outer() much more complicated, and some care
* would be needed to get setrefs.c to do the right thing with nestloop
* inner indexscan quals. So, we do subplan reference adjustment here for
* quals of join nodes (and *only* for quals of join nodes).
*
*****************************************************************************/
static NestLoop *
create_nestloop_node(NestPath *best_path,
List *tlist,
List *clauses,
Plan *outer_node,
List *outer_tlist,
Plan *inner_node,
List *inner_tlist)
{
NestLoop *join_node;
if (IsA(inner_node, IndexScan))
{
/*
* An index is being used to reduce the number of tuples scanned
* in the inner relation. If there are join clauses being used
* with the index, we must update their outer-rel var nodes to
* refer to the outer side of the join.
*
* We can also remove those join clauses from the list of clauses
* that have to be checked as qpquals at the join node, but only
* if there's just one indexscan in the inner path (otherwise,
* several different sets of clauses are being ORed together).
*
* Note: if the index is lossy, the same clauses may also be getting
* checked as qpquals in the indexscan. We can still remove them
* from the nestloop's qpquals, but we gotta update the outer-rel
* vars in the indexscan's qpquals too.
*
* Note: we can safely do set_difference() against my clauses and
* join_references() because the innerscan is a primitive plan,
* and therefore has not itself done join_references renumbering
* of the vars in its quals.
*/
IndexScan *innerscan = (IndexScan *) inner_node;
List *indxqualorig = innerscan->indxqualorig;
/* No work needed if indxqual refers only to its own relation... */
if (NumRelids((Node *) indxqualorig) > 1)
{
Index innerrel = innerscan->scan.scanrelid;
/* Remove redundant tests from my clauses, if possible.
* Note we must compare against indxqualorig not the "fixed"
* indxqual (which has index attnos instead of relation attnos,
* and may have been commuted as well).
*/
if (length(indxqualorig) == 1) /* single indexscan? */
clauses = set_difference(clauses, lfirst(indxqualorig));
/* only refs to outer vars get changed in the inner indexqual */
innerscan->indxqualorig = join_references(indxqualorig,
outer_tlist,
NIL,
innerrel);
innerscan->indxqual = join_references(innerscan->indxqual,
outer_tlist,
NIL,
innerrel);
/* fix the inner qpqual too, if it has join clauses */
if (NumRelids((Node *) inner_node->qual) > 1)
inner_node->qual = join_references(inner_node->qual,
outer_tlist,
NIL,
innerrel);
}
}
else if (IsA_Join(inner_node))
{
/*
* Materialize the inner join for speed reasons.
*
* XXX It is probably *not* always fastest to materialize an inner
* join --- how can we estimate whether this is a good thing to do?
*/
inner_node = (Plan *) make_noname(inner_tlist,
NIL,
inner_node);
}
join_node = make_nestloop(tlist,
join_references(clauses,
outer_tlist,
inner_tlist,
(Index) 0),
outer_node,
inner_node);
join_node->join.cost = best_path->path.path_cost;
return join_node;
}
static MergeJoin *
create_mergejoin_node(MergePath *best_path,
List *tlist,
List *clauses,
Plan *outer_node,
List *outer_tlist,
Plan *inner_node,
List *inner_tlist)
{
List *qpqual,
*mergeclauses;
MergeJoin *join_node;
/*
* Remove the mergeclauses from the list of join qual clauses,
* leaving the list of quals that must be checked as qpquals.
* Set those clauses to contain INNER/OUTER var references.
*/
qpqual = join_references(set_difference(clauses,
best_path->path_mergeclauses),
outer_tlist,
inner_tlist,
(Index) 0);
/*
* Now set the references in the mergeclauses and rearrange them so
* that the outer variable is always on the left.
*/
mergeclauses = switch_outer(join_references(best_path->path_mergeclauses,
outer_tlist,
inner_tlist,
(Index) 0));
/*
* Create explicit sort nodes for the outer and inner join paths if
* necessary. The sort cost was already accounted for in the path.
*/
if (best_path->outersortkeys)
outer_node = (Plan *) make_noname(outer_tlist,
best_path->outersortkeys,
outer_node);
if (best_path->innersortkeys)
inner_node = (Plan *) make_noname(inner_tlist,
best_path->innersortkeys,
inner_node);
join_node = make_mergejoin(tlist,
qpqual,
mergeclauses,
inner_node,
outer_node);
join_node->join.cost = best_path->jpath.path.path_cost;
return join_node;
}
static HashJoin *
create_hashjoin_node(HashPath *best_path,
List *tlist,
List *clauses,
Plan *outer_node,
List *outer_tlist,
Plan *inner_node,
List *inner_tlist)
{
List *qpqual;
List *hashclauses;
HashJoin *join_node;
Hash *hash_node;
Var *innerhashkey;
/*
* NOTE: there will always be exactly one hashclause in the list
* best_path->path_hashclauses (cf. hash_inner_and_outer()).
* We represent it as a list anyway, for convenience with routines
* that want to work on lists of clauses.
*/
/*
* Remove the hashclauses from the list of join qual clauses,
* leaving the list of quals that must be checked as qpquals.
* Set those clauses to contain INNER/OUTER var references.
*/
qpqual = join_references(set_difference(clauses,
best_path->path_hashclauses),
outer_tlist,
inner_tlist,
(Index) 0);
/*
* Now set the references in the hashclauses and rearrange them so
* that the outer variable is always on the left.
*/
hashclauses = switch_outer(join_references(best_path->path_hashclauses,
outer_tlist,
inner_tlist,
(Index) 0));
/* Now the righthand op of the sole hashclause is the inner hash key. */
innerhashkey = get_rightop(lfirst(hashclauses));
/*
* Build the hash node and hash join node.
*/
hash_node = make_hash(inner_tlist, innerhashkey, inner_node);
join_node = make_hashjoin(tlist,
qpqual,
hashclauses,
outer_node,
(Plan *) hash_node);
join_node->join.cost = best_path->jpath.path.path_cost;
return join_node;
}
/*****************************************************************************
*
* SUPPORTING ROUTINES
*
*****************************************************************************/
/*
* fix_indxqual_references
* Adjust indexqual clauses to refer to index attributes instead of the
* attributes of the original relation. Also, commute clauses if needed
* to put the indexkey on the left. (Someday the executor might not need
* that, but for now it does.)
*
* This code used to be entirely bogus for multi-index scans. Now it keeps
* track of which index applies to each subgroup of index qual clauses...
*
* Returns a modified copy of the indexqual list --- the original is not
* changed.
*/
static List *
fix_indxqual_references(List *indexquals, IndexPath *index_path)
{
List *fixed_quals = NIL;
List *indexids = index_path->indexid;
List *i;
foreach(i, indexquals)
{
List *indexqual = lfirst(i);
Oid indexid = lfirsti(indexids);
HeapTuple indexTuple;
Form_pg_index index;
indexTuple = SearchSysCacheTuple(INDEXRELID,
ObjectIdGetDatum(indexid),
0, 0, 0);
if (!HeapTupleIsValid(indexTuple))
elog(ERROR, "fix_indxqual_references: index %u not found",
indexid);
index = (Form_pg_index) GETSTRUCT(indexTuple);
fixed_quals = lappend(fixed_quals,
fix_indxqual_sublist(indexqual,
index_path,
index));
indexids = lnext(indexids);
}
return fixed_quals;
}
/*
* Fix the sublist of indexquals to be used in a particular scan.
*
* For each qual clause, commute if needed to put the indexkey operand on the
* left, and then change its varno. We do not need to change the other side
* of the clause.
*/
static List *
fix_indxqual_sublist(List *indexqual, IndexPath *index_path,
Form_pg_index index)
{
List *fixed_qual = NIL;
List *i;
foreach(i, indexqual)
{
Expr *clause = (Expr *) lfirst(i);
int relid;
AttrNumber attno;
Datum constval;
int flag;
Expr *newclause;
if (!is_opclause((Node *) clause) ||
length(clause->args) != 2)
elog(ERROR, "fix_indxqual_sublist: indexqual clause is not binary opclause");
/* Which side is the indexkey on?
*
* get_relattval sets flag&SEL_RIGHT if the indexkey is on the LEFT.
*/
get_relattval((Node *) clause,
lfirsti(index_path->path.parent->relids),
&relid, &attno, &constval, &flag);
/* Copy enough structure to allow commuting and replacing an operand
* without changing original clause.
*/
newclause = make_clause(clause->opType, clause->oper,
listCopy(clause->args));
/* If the indexkey is on the right, commute the clause. */
if ((flag & SEL_RIGHT) == 0)
CommuteClause(newclause);
/* Now, change the indexkey operand as needed. */
lfirst(newclause->args) = fix_indxqual_operand(lfirst(newclause->args),
index_path,
index);
fixed_qual = lappend(fixed_qual, newclause);
}
return fixed_qual;
}
static Node *
fix_indxqual_operand(Node *node, IndexPath *index_path,
Form_pg_index index)
{
if (IsA(node, Var))
{
if (((Var *) node)->varno == lfirsti(index_path->path.parent->relids))
{
int varatt = ((Var *) node)->varattno;
int pos;
for (pos = 0; pos < INDEX_MAX_KEYS; pos++)
{
if (index->indkey[pos] == varatt)
{
Node *newnode = copyObject(node);
((Var *) newnode)->varattno = pos + 1;
return newnode;
}
}
}
/*
* Oops, this Var isn't the indexkey!
*/
elog(ERROR, "fix_indxqual_operand: var is not index attribute");
}
/*
* Else, it must be a func expression representing a functional index.
*
* Currently, there is no need for us to do anything here for
* functional indexes. If nodeIndexscan.c sees a func clause as the left
* or right-hand toplevel operand of an indexqual, it assumes that that is
* a reference to the functional index's value and makes the appropriate
* substitution. (It would be cleaner to make the substitution here, I
* think --- suspect this issue if a join clause involving a function call
* misbehaves...)
*/
/* return the unmodified node */
return node;
}
/*
* switch_outer
* Given a list of merge or hash joinclauses, rearrange the elements within
* the clauses so the outer join variable is on the left and the inner is
* on the right. The original list is not touched; a modified list
* is returned.
*/
static List *
switch_outer(List *clauses)
{
List *t_list = NIL;
List *i;
foreach(i, clauses)
{
Expr *clause = (Expr *) lfirst(i);
Var *op;
Assert(is_opclause((Node *) clause));
op = get_rightop(clause);
Assert(op && IsA(op, Var));
if (var_is_outer(op))
{
/*
* Duplicate just enough of the structure to allow commuting
* the clause without changing the original list. Could use
* copyObject, but a complete deep copy is overkill.
*/
Expr *temp;
temp = make_clause(clause->opType, clause->oper,
listCopy(clause->args));
/* Commute it --- note this modifies the temp node in-place. */
CommuteClause(temp);
t_list = lappend(t_list, temp);
}
else
t_list = lappend(t_list, clause);
}
return t_list;
}
/*
* set_tlist_sort_info
* Sets the reskey and reskeyop fields of resdom nodes in a target list
* for a sort node.
*
* 'tlist' is the target list (which is modified in-place).
* tlist's reskey fields must be clear to start with.
* 'pathkeys' is the desired pathkeys for the sort. NIL means no sort.
*
* Returns the number of sort keys assigned (which might be less than
* length(pathkeys)!)
*/
static int
set_tlist_sort_info(List *tlist, List *pathkeys)
{
int keysassigned = 0;
List *i;
foreach(i, pathkeys)
{
List *keysublist = (List *) lfirst(i);
PathKeyItem *pathkey = NULL;
Resdom *resdom = NULL;
List *j;
/*
* We can sort by any one of the sort key items listed in this
* sublist. For now, we take the first one that corresponds to
* an available Var in the tlist.
*
* XXX if we have a choice, is there any way of figuring out which
* might be cheapest to execute? (For example, int4lt is likely
* much cheaper to execute than numericlt, but both might appear in
* the same pathkey sublist...) Not clear that we ever will have
* a choice in practice, so it may not matter.
*/
foreach(j, keysublist)
{
pathkey = lfirst(j);
Assert(IsA(pathkey, PathKeyItem));
resdom = tlist_member(pathkey->key, tlist);
if (resdom)
break;
}
if (!resdom)
elog(ERROR, "set_tlist_sort_info: cannot find tlist item to sort");
/*
* The resdom might be already marked as a sort key, if the pathkeys
* contain duplicate entries. (This can happen in scenarios where
* multiple mergejoinable clauses mention the same var, for example.)
* In that case the current pathkey is essentially a no-op, because
* only one value can be seen within any subgroup where it would be
* consulted. We can ignore it.
*/
if (resdom->reskey == 0)
{
/* OK, mark it as a sort key and set the sort operator regproc */
resdom->reskey = ++keysassigned;
resdom->reskeyop = get_opcode(pathkey->sortop);
}
}
return keysassigned;
}
/*
* Copy cost and size info from a lower plan node to an inserted node.
* This is not critical, since the decisions have already been made,
* but it helps produce more reasonable-looking EXPLAIN output.
*/
static void
copy_costsize(Plan *dest, Plan *src)
{
if (src)
{
dest->cost = src->cost;
dest->plan_size = src->plan_size;
dest->plan_width = src->plan_width;
}
else
{
dest->cost = 0;
dest->plan_size = 0;
dest->plan_width = 0;
}
}
/*****************************************************************************
*
*
*****************************************************************************/
/*
* make_noname
* Create plan node to sort or materialize relations into noname.
*
* 'tlist' is the target list of the scan to be sorted or materialized
* 'pathkeys' is the list of pathkeys by which the result is to be sorted
* (NIL implies no sort needed, just materialize it)
* 'subplan' is the node which yields input tuples
*/
Noname *
make_noname(List *tlist,
List *pathkeys,
Plan *subplan)
{
List *noname_tlist;
int numsortkeys;
Plan *retval;
/* Create a new target list for the noname, with sort keys set. */
noname_tlist = new_unsorted_tlist(tlist);
numsortkeys = set_tlist_sort_info(noname_tlist, pathkeys);
if (numsortkeys > 0)
{
/* need to sort */
retval = (Plan *) make_sort(noname_tlist,
_NONAME_RELATION_ID_,
subplan,
numsortkeys);
}
else
{
/* no sort */
retval = (Plan *) make_material(noname_tlist,
_NONAME_RELATION_ID_,
subplan,
0);
}
return (Noname *) retval;
}
SeqScan *
make_seqscan(List *qptlist,
List *qpqual,
Index scanrelid)
{
SeqScan *node = makeNode(SeqScan);
Plan *plan = &node->plan;
copy_costsize(plan, NULL);
plan->state = (EState *) NULL;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scanrelid = scanrelid;
node->scanstate = (CommonScanState *) NULL;
return node;
}
static IndexScan *
make_indexscan(List *qptlist,
List *qpqual,
Index scanrelid,
List *indxid,
List *indxqual,
List *indxqualorig)
{
IndexScan *node = makeNode(IndexScan);
Plan *plan = &node->scan.plan;
copy_costsize(plan, NULL);
plan->state = (EState *) NULL;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = NULL;
plan->righttree = NULL;
node->scan.scanrelid = scanrelid;
node->indxid = indxid;
node->indxqual = indxqual;
node->indxqualorig = indxqualorig;
node->indxorderdir = NoMovementScanDirection;
node->scan.scanstate = (CommonScanState *) NULL;
return node;
}
static NestLoop *
make_nestloop(List *qptlist,
List *qpqual,
Plan *lefttree,
Plan *righttree)
{
NestLoop *node = makeNode(NestLoop);
Plan *plan = &node->join;
/*
* this cost estimate is entirely bogus... hopefully it will be
* overwritten by caller.
*/
plan->cost = (lefttree ? lefttree->cost : 0) +
(righttree ? righttree->cost : 0);
plan->state = (EState *) NULL;
plan->targetlist = qptlist;
plan->qual = qpqual;
plan->lefttree = lefttree;
plan->righttree = righttree;
node->nlstate = (NestLoopState *) NULL;
return node;
}
static HashJoin *
make_hashjoin(List *tlist,
List *qpqual,
List *hashclauses,
Plan *lefttree,
Plan *righttree)
{
HashJoin *node = makeNode(HashJoin);
Plan *plan = &node->join;
/*
* this cost estimate is entirely bogus... hopefully it will be
* overwritten by caller.
*/
plan->cost = (lefttree ? lefttree->cost : 0) +
(righttree ? righttree->cost : 0);
plan->state = (EState *) NULL;
plan->targetlist = tlist;
plan->qual = qpqual;
plan->lefttree = lefttree;
plan->righttree = righttree;
node->hashclauses = hashclauses;
node->hashdone = false;
return node;
}
static Hash *
make_hash(List *tlist, Var *hashkey, Plan *lefttree)
{
Hash *node = makeNode(Hash);
Plan *plan = &node->plan;
copy_costsize(plan, lefttree);
plan->state = (EState *) NULL;
plan->targetlist = tlist;
plan->qual = NULL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->hashkey = hashkey;
return node;
}
static MergeJoin *
make_mergejoin(List *tlist,
List *qpqual,
List *mergeclauses,
Plan *righttree,
Plan *lefttree)
{
MergeJoin *node = makeNode(MergeJoin);
Plan *plan = &node->join;
/*
* this cost estimate is entirely bogus... hopefully it will be
* overwritten by caller.
*/
plan->cost = (lefttree ? lefttree->cost : 0) +
(righttree ? righttree->cost : 0);
plan->state = (EState *) NULL;
plan->targetlist = tlist;
plan->qual = qpqual;
plan->lefttree = lefttree;
plan->righttree = righttree;
node->mergeclauses = mergeclauses;
return node;
}
Sort *
make_sort(List *tlist, Oid nonameid, Plan *lefttree, int keycount)
{
Sort *node = makeNode(Sort);
Plan *plan = &node->plan;
copy_costsize(plan, lefttree);
plan->cost += cost_sort(NULL, plan->plan_size, plan->plan_width);
plan->state = (EState *) NULL;
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->nonameid = nonameid;
node->keycount = keycount;
return node;
}
static Material *
make_material(List *tlist,
Oid nonameid,
Plan *lefttree,
int keycount)
{
Material *node = makeNode(Material);
Plan *plan = &node->plan;
copy_costsize(plan, lefttree);
plan->state = (EState *) NULL;
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->nonameid = nonameid;
node->keycount = keycount;
return node;
}
Agg *
make_agg(List *tlist, Plan *lefttree)
{
Agg *node = makeNode(Agg);
copy_costsize(&node->plan, lefttree);
node->plan.state = (EState *) NULL;
node->plan.qual = NULL;
node->plan.targetlist = tlist;
node->plan.lefttree = lefttree;
node->plan.righttree = (Plan *) NULL;
return node;
}
Group *
make_group(List *tlist,
bool tuplePerGroup,
int ngrp,
AttrNumber *grpColIdx,
Plan *lefttree)
{
Group *node = makeNode(Group);
copy_costsize(&node->plan, lefttree);
node->plan.state = (EState *) NULL;
node->plan.qual = NULL;
node->plan.targetlist = tlist;
node->plan.lefttree = lefttree;
node->plan.righttree = (Plan *) NULL;
node->tuplePerGroup = tuplePerGroup;
node->numCols = ngrp;
node->grpColIdx = grpColIdx;
return node;
}
/*
* The uniqueAttr argument must be a null-terminated string,
* either the name of the attribute to select unique on
* or "*"
*/
Unique *
make_unique(List *tlist, Plan *lefttree, char *uniqueAttr)
{
Unique *node = makeNode(Unique);
Plan *plan = &node->plan;
copy_costsize(plan, lefttree);
plan->state = (EState *) NULL;
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = lefttree;
plan->righttree = NULL;
node->nonameid = _NONAME_RELATION_ID_;
node->keycount = 0;
if (strcmp(uniqueAttr, "*") == 0)
node->uniqueAttr = NULL;
else
node->uniqueAttr = pstrdup(uniqueAttr);
return node;
}
Result *
make_result(List *tlist,
Node *resconstantqual,
Plan *subplan)
{
Result *node = makeNode(Result);
Plan *plan = &node->plan;
#ifdef NOT_USED
tlist = generate_fjoin(tlist);
#endif
copy_costsize(plan, subplan);
plan->state = (EState *) NULL;
plan->targetlist = tlist;
plan->qual = NIL;
plan->lefttree = subplan;
plan->righttree = NULL;
node->resconstantqual = resconstantqual;
node->resstate = NULL;
return node;
}
#ifdef NOT_USED
List *
generate_fjoin(List *tlist)
{
List tlistP;
List newTlist = NIL;
List fjoinList = NIL;
int nIters = 0;
/*
* Break the target list into elements with Iter nodes, and those
* without them.
*/
foreach(tlistP, tlist)
{
List tlistElem;
tlistElem = lfirst(tlistP);
if (IsA(lsecond(tlistElem), Iter))
{
nIters++;
fjoinList = lappend(fjoinList, tlistElem);
}
else
newTlist = lappend(newTlist, tlistElem);
}
/*
* if we have an Iter node then we need to flatten.
*/
if (nIters > 0)
{
List *inner;
List *tempList;
Fjoin *fjoinNode;
DatumPtr results = (DatumPtr) palloc(nIters * sizeof(Datum));
BoolPtr alwaysDone = (BoolPtr) palloc(nIters * sizeof(bool));
inner = lfirst(fjoinList);
fjoinList = lnext(fjoinList);
fjoinNode = (Fjoin) MakeFjoin(false,
nIters,
inner,
results,
alwaysDone);
tempList = lcons(fjoinNode, fjoinList);
newTlist = lappend(newTlist, tempList);
}
return newTlist;
return tlist; /* do nothing for now - ay 10/94 */
}
#endif
|