summaryrefslogtreecommitdiff
path: root/src/backend/executor/nodeMergejoin.c
blob: 6c49f9df6906a7ca1bb1a9a55b71adcb512ca3bb (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
/*-------------------------------------------------------------------------
 *
 * nodeMergejoin.c
 *	  routines supporting merge joins
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $Header: /cvsroot/pgsql/src/backend/executor/nodeMergejoin.c,v 1.21 1999/02/13 23:15:24 momjian Exp $
 *
 *-------------------------------------------------------------------------
 */
/*
 * INTERFACE ROUTINES
 *		ExecMergeJoin			mergejoin outer and inner relations.
 *		ExecInitMergeJoin		creates and initializes run time states
 *		ExecEndMergeJoin		cleand up the node.
 *
 * NOTES
 *		Essential operation of the merge join algorithm is as follows:
 *		(** indicates the tuples satisify the merge clause).
 *
 *		Join {												   -
 *			get initial outer and inner tuples				INITIALIZE
 *			Skip Inner										SKIPINNER
 *			mark inner position								JOINMARK
 *			do forever {									   -
 *				while (outer ** inner) {					JOINTEST
 *					join tuples								JOINTUPLES
 *					advance inner position					NEXTINNER
 *				}											   -
 *				advance outer position						NEXTOUTER
 *				if (outer ** mark) {						TESTOUTER
 *					restore inner position to mark			TESTOUTER
 *					continue								   -
 *				} else {									   -
 *					Skip Outer								SKIPOUTER
 *					mark inner position						JOINMARK
 *				}											   -
 *			}												   -
 *		}													   -
 *
 *		Skip Outer {										SKIPOUTER
 *			if (inner ** outer) Join Tuples					JOINTUPLES
 *			while (outer < inner)							SKIPOUTER
 *				advance outer								SKIPOUTER
 *			if (outer > inner)								SKIPOUTER
 *				Skip Inner									SKIPINNER
 *		}													   -
 *
 *		Skip Inner {										SKIPINNER
 *			if (inner ** outer) Join Tuples					JOINTUPLES
 *			while (outer > inner)							SKIPINNER
 *				advance inner								SKIPINNER
 *			if (outer < inner)								SKIPINNER
 *				Skip Outer									SKIPOUTER
 *		}													   -
 *
 *		Currently, the merge join operation is coded in the fashion
 *		of a state machine.  At each state, we do something and then
 *		proceed to another state.  This state is stored in the node's
 *		execution state information and is preserved across calls to
 *		ExecMergeJoin. -cim 10/31/89
 *
 *		Warning:  This code is known to fail for inequality operations
 *				  and is being redesigned.	Specifically, = and > work
 *				  but the logic is not correct for <.  Since mergejoins
 *				  are no better then nestloops for inequalitys, the planner
 *				  should not plan them anyways.  Alternatively, the
 *				  planner could just exchange the inner/outer relations
 *				  if it ever sees a <... -cim 7/1/90
 *
 *		Update:   The executor tuple table has long since alleviated the
 *				  problem described above -cim 4/23/91
 *
 */
#include "postgres.h"

#include "access/heapam.h"
#include "executor/executor.h"
#include "executor/execdefs.h"
#include "executor/nodeMergejoin.h"
#include "executor/execdebug.h"
#include "utils/lsyscache.h"
#include "utils/psort.h"

static bool MergeCompare(List *eqQual, List *compareQual, ExprContext *econtext);

#define MarkInnerTuple(innerTupleSlot, mergestate) \
( \
	ExecStoreTuple(heap_copytuple((innerTupleSlot)->val), \
				   (mergestate)->mj_MarkedTupleSlot, \
				   InvalidBuffer, \
				   true) \
)

/* ----------------------------------------------------------------
 *		MJFormOSortopI
 *
 *		This takes the mergeclause which is a qualification of the
 *		form ((= expr expr) (= expr expr) ...) and forms a new
 *		qualification like ((> expr expr) (> expr expr) ...) which
 *		is used by ExecMergeJoin() in order to determine if we should
 *		skip tuples.
 *
 * old comments
 *		The 'qual' must be of the form:
 *		   {(= outerkey1 innerkey1)(= outerkey2 innerkey2) ...}
 *		The "sortOp outerkey innerkey" is formed by substituting the "="
 *		by "sortOp".
 * ----------------------------------------------------------------
 */
static List *
MJFormOSortopI(List *qualList, Oid sortOp)
{
	List	   *qualCopy;
	List	   *qualcdr;
	Expr	   *qual;
	Oper	   *op;

	/* ----------------
	 *	qualList is a list: ((op .. ..) ...)
	 *	first we make a copy of it.  copyObject() makes a deep copy
	 *	so let's use it instead of the old fashoned lispCopy()...
	 * ----------------
	 */
	qualCopy = (List *) copyObject((Node *) qualList);

	foreach(qualcdr, qualCopy)
	{
		/* ----------------
		 *	 first get the current (op .. ..) list
		 * ----------------
		 */
		qual = lfirst(qualcdr);

		/* ----------------
		 *	 now get at the op
		 * ----------------
		 */
		op = (Oper *) qual->oper;
		if (!IsA(op, Oper))
		{
			elog(DEBUG, "MJFormOSortopI: op not an Oper!");
			return NIL;
		}

		/* ----------------
		 *	 change it's opid and since Op nodes now carry around a
		 *	 cached pointer to the associated op function, we have
		 *	 to make sure we invalidate this.  Otherwise you get bizarre
		 *	 behavior when someone runs a mergejoin with _exec_repeat_ > 1
		 *	 -cim 4/23/91
		 * ----------------
		 */
		op->opid = sortOp;
		op->op_fcache = NULL;
	}

	return qualCopy;
}

/* ----------------------------------------------------------------
 *		MJFormISortopO
 *
 *		This does the same thing as MJFormOSortopI() except that
 *		it also reverses the expressions in the qualifications.
 *		For example: ((= expr1 expr2)) produces ((> expr2 expr1))
 *
 * old comments
 *		The 'qual' must be of the form:
 *		   {(= outerkey1 innerkey1) (= outerkey2 innerkey2) ...}
 *		The 'sortOp innerkey1 outerkey" is formed by substituting the "="
 *		by "sortOp" and reversing the positions of the keys.
 *	----------------------------------------------------------------
 */
static List *
MJFormISortopO(List *qualList, Oid sortOp)
{
	List	   *ISortopO;
	List	   *qualcdr;

	/* ----------------
	 *	first generate OSortopI, a list of the form
	 *	((op outer inner) (op outer inner) ... )
	 * ----------------
	 */
	ISortopO = MJFormOSortopI(qualList, sortOp);

	/* ----------------
	 *	now swap the cadr and caddr of each qual to form ISortopO,
	 *	((op inner outer) (op inner outer) ... )
	 * ----------------
	 */
	foreach(qualcdr, ISortopO)
	{
		Expr	   *qual;
		List	   *inner;
		List	   *outer;

		qual = lfirst(qualcdr);

		inner = lfirst(qual->args);
		outer = lfirst(lnext(qual->args));
		lfirst(qual->args) = outer;
		lfirst(lnext(qual->args)) = inner;
	}

	return ISortopO;
}

/* ----------------------------------------------------------------
 *		MergeCompare
 *
 *		Compare the keys according to 'compareQual' which is of the
 *		form: {(key1a > key2a)(key1b > key2b) ...}.
 *
 *		(actually, it could also be the form (key1a < key2a)..)
 *
 *		This is different from calling ExecQual because ExecQual returns
 *		true only if ALL the comparisions clauses are satisfied.
 *		However, there is an order of significance among the keys with
 *		the first keys being most significant. Therefore, the clauses
 *		are evaluated in order and the 'compareQual' is satisfied
 *		if (key1i > key2i) is true and (key1j = key2j) for 0 < j < i.
 * ----------------------------------------------------------------
 */
static bool
MergeCompare(List *eqQual, List *compareQual, ExprContext *econtext)
{
	List	   *clause;
	List	   *eqclause;
	Datum		const_value;
	bool		isNull;
	bool		isDone;

	/* ----------------
	 *	if we have no compare qualification, return nil
	 * ----------------
	 */
	if (compareQual == NIL)
		return false;

	/* ----------------
	 *	for each pair of clauses, test them until
	 *	our compare conditions are satisified
	 * ----------------
	 */
	eqclause = eqQual;
	foreach(clause, compareQual)
	{
		/* ----------------
		 *	 first test if our compare clause is satisified.
		 *	 if so then return true. ignore isDone, don't iterate in
		 *	 quals.
		 * ----------------
		 */
		const_value = (Datum)
			ExecEvalExpr((Node *) lfirst(clause), econtext, &isNull, &isDone);

		if (DatumGetInt32(const_value) != 0)
			return true;

		/* ----------------
		 *	 ok, the compare clause failed so we test if the keys
		 *	 are equal... if key1 != key2, we return false.
		 *	 otherwise key1 = key2 so we move on to the next pair of keys.
		 *
		 *	 ignore isDone, don't iterate in quals.
		 * ----------------
		 */
		const_value = ExecEvalExpr((Node *) lfirst(eqclause),
								   econtext,
								   &isNull,
								   &isDone);

		if (DatumGetInt32(const_value) == 0)
			return false;
		eqclause = lnext(eqclause);
	}

	/* ----------------
	 *	if we get here then it means none of our key greater-than
	 *	conditions were satisified so we return false.
	 * ----------------
	 */
	return false;
}

/* ----------------------------------------------------------------
 *		ExecMergeTupleDump
 *
 *		This function is called through the MJ_dump() macro
 *		when EXEC_MERGEJOINDEBUG is defined
 * ----------------------------------------------------------------
 */
#ifdef EXEC_MERGEJOINDEBUG
void
ExecMergeTupleDumpInner(ExprContext *econtext)
{
	TupleTableSlot *innerSlot;

	printf("==== inner tuple ====\n");
	innerSlot = econtext->ecxt_innertuple;
	if (TupIsNull(innerSlot))
		printf("(nil)\n");
	else
		debugtup(innerSlot->val,
				 innerSlot->ttc_tupleDescriptor);
}

void
ExecMergeTupleDumpOuter(ExprContext *econtext)
{
	TupleTableSlot *outerSlot;

	printf("==== outer tuple ====\n");
	outerSlot = econtext->ecxt_outertuple;
	if (TupIsNull(outerSlot))
		printf("(nil)\n");
	else
		debugtup(outerSlot->val,
				 outerSlot->ttc_tupleDescriptor);
}

void
ExecMergeTupleDumpMarked(ExprContext *econtext,
						 MergeJoinState *mergestate)
{
	TupleTableSlot *markedSlot;

	printf("==== marked tuple ====\n");
	markedSlot = mergestate->mj_MarkedTupleSlot;

	if (TupIsNull(markedSlot))
		printf("(nil)\n");
	else
		debugtup(markedSlot->val,
				 markedSlot->ttc_tupleDescriptor);
}

void
ExecMergeTupleDump(ExprContext *econtext, MergeJoinState *mergestate)
{
	printf("******** ExecMergeTupleDump ********\n");

	ExecMergeTupleDumpInner(econtext);
	ExecMergeTupleDumpOuter(econtext);
	ExecMergeTupleDumpMarked(econtext, mergestate);

	printf("******** \n");
}

#endif

/* ----------------------------------------------------------------
 *		ExecMergeJoin
 *
 * old comments
 *		Details of the merge-join routines:
 *
 *		(1) ">" and "<" operators
 *
 *		Merge-join is done by joining the inner and outer tuples satisfying
 *		the join clauses of the form ((= outerKey innerKey) ...).
 *		The join clauses is provided by the query planner and may contain
 *		more than one (= outerKey innerKey) clauses (for composite key).
 *
 *		However, the query executor needs to know whether an outer
 *		tuple is "greater/smaller" than an inner tuple so that it can
 *		"synchronize" the two relations. For e.g., consider the following
 *		relations:
 *
 *				outer: (0 ^1 1 2 5 5 5 6 6 7)	current tuple: 1
 *				inner: (1 ^3 5 5 5 5 6)			current tuple: 3
 *
 *		To continue the merge-join, the executor needs to scan both inner
 *		and outer relations till the matching tuples 5. It needs to know
 *		that currently inner tuple 3 is "greater" than outer tuple 1 and
 *		therefore it should scan the outer relation first to find a
 *		matching tuple and so on.
 *
 *		Therefore, when initializing the merge-join node, the executor
 *		creates the "greater/smaller" clause by substituting the "="
 *		operator in the join clauses with the sort operator used to
 *		sort the outer and inner relation forming (outerKey sortOp innerKey).
 *		The sort operator is "<" if the relations are in ascending order
 *		otherwise, it is ">" if the relations are in descending order.
 *		The opposite "smaller/greater" clause is formed by reversing the
 *		outer and inner keys forming (innerKey sortOp outerKey).
 *
 *		(2) repositioning inner "cursor"
 *
 *		Consider the above relations and suppose that the executor has
 *		just joined the first outer "5" with the last inner "5". The
 *		next step is of course to join the second outer "5" with all
 *		the inner "5's". This requires repositioning the inner "cursor"
 *		to point at the first inner "5". This is done by "marking" the
 *		first inner 5 and restore the "cursor" to it before joining
 *		with the second outer 5. The access method interface provides
 *		routines to mark and restore to a tuple.
 * ----------------------------------------------------------------
 */
TupleTableSlot *
ExecMergeJoin(MergeJoin *node)
{
	EState	   *estate;
	MergeJoinState *mergestate;
	ScanDirection direction;
	List	   *innerSkipQual;
	List	   *outerSkipQual;
	List	   *mergeclauses;
	List	   *qual;
	bool		qualResult;
	bool		compareResult;

	Plan	   *innerPlan;
	TupleTableSlot *innerTupleSlot;

	Plan	   *outerPlan;
	TupleTableSlot *outerTupleSlot;

	ExprContext *econtext;

	/* ----------------
	 *	get information from node
	 * ----------------
	 */
	mergestate = node->mergestate;
	estate = node->join.state;
	direction = estate->es_direction;
	innerPlan = innerPlan((Plan *) node);
	outerPlan = outerPlan((Plan *) node);
	econtext = mergestate->jstate.cs_ExprContext;
	mergeclauses = node->mergeclauses;
	qual = node->join.qual;

	if (ScanDirectionIsForward(direction))
	{
		outerSkipQual = mergestate->mj_OSortopI;
		innerSkipQual = mergestate->mj_ISortopO;
	}
	else
	{
		outerSkipQual = mergestate->mj_ISortopO;
		innerSkipQual = mergestate->mj_OSortopI;
	}

	/* ----------------
	 *	ok, everything is setup.. let's go to work
	 * ----------------
	 */
	if (mergestate->jstate.cs_TupFromTlist)
	{
		TupleTableSlot *result;
		ProjectionInfo *projInfo;
		bool		isDone;

		projInfo = mergestate->jstate.cs_ProjInfo;
		result = ExecProject(projInfo, &isDone);
		if (!isDone)
			return result;
	}
	for (;;)
	{
		/* ----------------
		 *	get the current state of the join and do things accordingly.
		 *	Note: The join states are highlighted with 32-* comments for
		 *		  improved readability.
		 * ----------------
		 */
		MJ_dump(econtext, mergestate);

		switch (mergestate->mj_JoinState)
		{

				/*
				 * ******************************** EXEC_MJ_INITIALIZE
				 * means that this is the first time ExecMergeJoin() has
				 * been called and so we have to initialize the inner,
				 * outer and marked tuples as well as various stuff in the
				 * expression context. ********************************
				 *
				 */
			case EXEC_MJ_INITIALIZE:
				MJ_printf("ExecMergeJoin: EXEC_MJ_INITIALIZE\n");
				/* ----------------
				 *	 Note: at this point, if either of our inner or outer
				 *	 tuples are nil, then the join ends immediately because
				 *	 we know one of the subplans is empty.
				 * ----------------
				 */
				innerTupleSlot = ExecProcNode(innerPlan, (Plan *) node);
				if (TupIsNull(innerTupleSlot))
				{
					MJ_printf("ExecMergeJoin: **** inner tuple is nil ****\n");
					return NULL;
				}

				outerTupleSlot = ExecProcNode(outerPlan, (Plan *) node);
				if (TupIsNull(outerTupleSlot))
				{
					MJ_printf("ExecMergeJoin: **** outer tuple is nil ****\n");
					return NULL;
				}

				/* ----------------
				 *	 store the inner and outer tuple in the merge state
				 * ----------------
				 */
				econtext->ecxt_innertuple = innerTupleSlot;
				econtext->ecxt_outertuple = outerTupleSlot;

				mergestate->mj_MarkedTupleSlot->ttc_tupleDescriptor =
						innerTupleSlot->ttc_tupleDescriptor;

				/* ----------------
				 *	initialize merge join state to skip inner tuples.
				 * ----------------
				 */
				mergestate->mj_JoinState = EXEC_MJ_SKIPINNER;
				break;

				/*
				 * ******************************** EXEC_MJ_JOINMARK means
				 * we have just found a new outer tuple and a possible
				 * matching inner tuple. This is the case after the
				 * INITIALIZE, SKIPOUTER or SKIPINNER states. ********************************
				 *
				 */
			case EXEC_MJ_JOINMARK:
				MJ_printf("ExecMergeJoin: EXEC_MJ_JOINMARK\n");
				ExecMarkPos(innerPlan);

				MarkInnerTuple(econtext->ecxt_innertuple, mergestate);

				mergestate->mj_JoinState = EXEC_MJ_JOINTEST;
				break;

				/*
				 * ******************************** EXEC_MJ_JOINTEST means
				 * we have two tuples which might satisify the merge
				 * clause, so we test them.
				 *
				 * If they do satisify, then we join them and move on to the
				 * next inner tuple (EXEC_MJ_JOINTUPLES).
				 *
				 * If they do not satisify then advance to next outer tuple. ********************************
				 *
				 */
			case EXEC_MJ_JOINTEST:
				MJ_printf("ExecMergeJoin: EXEC_MJ_JOINTEST\n");

				qualResult = ExecQual((List *) mergeclauses, econtext);
				MJ_DEBUG_QUAL(mergeclauses, qualResult);

				if (qualResult)
					mergestate->mj_JoinState = EXEC_MJ_JOINTUPLES;
				else
					mergestate->mj_JoinState = EXEC_MJ_NEXTOUTER;
				break;

				/*
				 * ******************************** EXEC_MJ_JOINTUPLES
				 * means we have two tuples which satisified the merge
				 * clause so we join them and then proceed to get the next
				 * inner tuple (EXEC_NEXT_INNER). ********************************
				 *
				 */
			case EXEC_MJ_JOINTUPLES:
				MJ_printf("ExecMergeJoin: EXEC_MJ_JOINTUPLES\n");
				mergestate->mj_JoinState = EXEC_MJ_NEXTINNER;

				qualResult = ExecQual((List *) qual, econtext);
				MJ_DEBUG_QUAL(qual, qualResult);

				if (qualResult)
				{
					/* ----------------
					 *	qualification succeeded.  now form the desired
					 *	projection tuple and return the slot containing it.
					 * ----------------
					 */
					ProjectionInfo *projInfo;
					TupleTableSlot *result;
					bool		isDone;

					MJ_printf("ExecMergeJoin: **** returning tuple ****\n");

					projInfo = mergestate->jstate.cs_ProjInfo;

					result = ExecProject(projInfo, &isDone);
					mergestate->jstate.cs_TupFromTlist = !isDone;
					return result;
				}
				break;

				/*
				 * ******************************** EXEC_MJ_NEXTINNER
				 * means advance the inner scan to the next tuple.	If the
				 * tuple is not nil, we then proceed to test it against
				 * the join qualification. ********************************
				 *
				 */
			case EXEC_MJ_NEXTINNER:
				MJ_printf("ExecMergeJoin: EXEC_MJ_NEXTINNER\n");

				/* ----------------
				 *	now we get the next inner tuple, if any
				 * ----------------
				 */
				innerTupleSlot = ExecProcNode(innerPlan, (Plan *) node);
				MJ_DEBUG_PROC_NODE(innerTupleSlot);
				econtext->ecxt_innertuple = innerTupleSlot;

				if (TupIsNull(innerTupleSlot))
					mergestate->mj_JoinState = EXEC_MJ_NEXTOUTER;
				else
					mergestate->mj_JoinState = EXEC_MJ_JOINTEST;
				break;

				/*
				 * ******************************** EXEC_MJ_NEXTOUTER
				 * means
				 *
				 * outer inner outer tuple -  5		5  - marked tuple 5		5
				 * 6 6	- inner tuple 7		7
				 *
				 * we know we just bumped into the first inner tuple >
				 * current outer tuple so get a new outer tuple and then
				 * proceed to test it against the marked tuple
				 * (EXEC_MJ_TESTOUTER) ********************************
				 *
				 */
			case EXEC_MJ_NEXTOUTER:
				MJ_printf("ExecMergeJoin: EXEC_MJ_NEXTOUTER\n");

				outerTupleSlot = ExecProcNode(outerPlan, (Plan *) node);
				MJ_DEBUG_PROC_NODE(outerTupleSlot);
				econtext->ecxt_outertuple = outerTupleSlot;

				/* ----------------
				 *	if the outer tuple is null then we know
				 *	we are done with the join
				 * ----------------
				 */
				if (TupIsNull(outerTupleSlot))
				{
					MJ_printf("ExecMergeJoin: **** outer tuple is nil ****\n");
					return NULL;
				}

				mergestate->mj_JoinState = EXEC_MJ_TESTOUTER;
				break;

				/*
				 * ******************************** EXEC_MJ_TESTOUTER If
				 * the new outer tuple and the marked tuple satisify the
				 * merge clause then we know we have duplicates in the
				 * outer scan so we have to restore the inner scan to the
				 * marked tuple and proceed to join the new outer tuples
				 * with the inner tuples (EXEC_MJ_JOINTEST)
				 *
				 * This is the case when
				 *
				 * outer inner 4	 5	- marked tuple outer tuple -  5		5
				 * new outer tuple -  5		5 6		8  - inner tuple 7 12
				 *
				 * new outer tuple = marked tuple
				 *
				 * If the outer tuple fails the test, then we know we have to
				 * proceed to skip outer tuples until outer >= inner
				 * (EXEC_MJ_SKIPOUTER).
				 *
				 * This is the case when
				 *
				 * outer inner 5	 5	- marked tuple outer tuple -  5		5
				 * new outer tuple -  6		8  - inner tuple 7	  12
				 *
				 * new outer tuple > marked tuple
				 *
				***************************
				 *
				 *
				 */
			case EXEC_MJ_TESTOUTER:
				MJ_printf("ExecMergeJoin: EXEC_MJ_TESTOUTER\n");

				/* ----------------
				 *	here we compare the outer tuple with the marked inner tuple
				 *	by using the marked tuple in place of the inner tuple.
				 * ----------------
				 */
				innerTupleSlot = econtext->ecxt_innertuple;
				econtext->ecxt_innertuple = mergestate->mj_MarkedTupleSlot;

				qualResult = ExecQual((List *) mergeclauses, econtext);
				MJ_DEBUG_QUAL(mergeclauses, qualResult);

				if (qualResult)
				{

					/*
					 * the merge clause matched so now we juggle the slots
					 * back the way they were and proceed to JOINTEST.
					 *
					 * I can't understand why we have to go to JOINTEST and
					 * compare outer tuple with the same inner one again
					 * -> go to JOINTUPLES...	 - vadim 02/27/98
					 */

					ExecRestrPos(innerPlan);
#if 0
					mergestate->mj_JoinState = EXEC_MJ_JOINTEST;
#endif
					mergestate->mj_JoinState = EXEC_MJ_JOINTUPLES;

				}
				else
				{
					econtext->ecxt_innertuple = innerTupleSlot;
					/* ----------------
					 *	if the inner tuple was nil and the new outer
					 *	tuple didn't match the marked outer tuple then
					 *	we may have the case:
					 *
					 *				outer	inner
					 *					4	  4   - marked tuple
					 *		new outer - 5	  4
					 *					6	 nil  - inner tuple
					 *					7
					 *
					 *	which means that all subsequent outer tuples will be
					 *	larger than our inner tuples.
					 * ----------------
					 */
					if (TupIsNull(innerTupleSlot))
					{
						MJ_printf("ExecMergeJoin: **** wierd case 1 ****\n");
						return NULL;
					}

					/* continue on to skip outer tuples */
					mergestate->mj_JoinState = EXEC_MJ_SKIPOUTER;
				}
				break;

				/*
				 * ******************************** EXEC_MJ_SKIPOUTER
				 * means skip over tuples in the outer plan until we find
				 * an outer tuple > current inner tuple.
				 *
				 * For example:
				 *
				 * outer inner 5	 5 5	 5 outer tuple -  6		8  -
				 * inner tuple 7	12 8	14
				 *
				 * we have to advance the outer scan until we find the outer
				 * 8.
				 *
				**************************
				 *
				 *
				 *
				 *
				 *
				 *
				 *
				 */
			case EXEC_MJ_SKIPOUTER:
				MJ_printf("ExecMergeJoin: EXEC_MJ_SKIPOUTER\n");
				/* ----------------
				 *	before we advance, make sure the current tuples
				 *	do not satisify the mergeclauses.  If they do, then
				 *	we update the marked tuple and go join them.
				 * ----------------
				 */
				qualResult = ExecQual((List *) mergeclauses, econtext);
				MJ_DEBUG_QUAL(mergeclauses, qualResult);

				if (qualResult)
				{
					ExecMarkPos(innerPlan);

					MarkInnerTuple(econtext->ecxt_innertuple, mergestate);

					mergestate->mj_JoinState = EXEC_MJ_JOINTUPLES;
					break;
				}

				/* ----------------
				 *	ok, now test the skip qualification
				 * ----------------
				 */
				compareResult = MergeCompare(mergeclauses,
											 outerSkipQual,
											 econtext);

				MJ_DEBUG_MERGE_COMPARE(outerSkipQual, compareResult);

				/* ----------------
				 *	compareResult is true as long as we should
				 *	continue skipping tuples.
				 * ----------------
				 */
				if (compareResult)
				{

					outerTupleSlot = ExecProcNode(outerPlan, (Plan *) node);
					MJ_DEBUG_PROC_NODE(outerTupleSlot);
					econtext->ecxt_outertuple = outerTupleSlot;

					/* ----------------
					 *	if the outer tuple is null then we know
					 *	we are done with the join
					 * ----------------
					 */
					if (TupIsNull(outerTupleSlot))
					{
						MJ_printf("ExecMergeJoin: **** outerTuple is nil ****\n");
						return NULL;
					}
					/* ----------------
					 *	otherwise test the new tuple against the skip qual.
					 *	(we remain in the EXEC_MJ_SKIPOUTER state)
					 * ----------------
					 */
					break;
				}

				/* ----------------
				 *	now check the inner skip qual to see if we
				 *	should now skip inner tuples... if we fail the
				 *	inner skip qual, then we know we have a new pair
				 *	of matching tuples.
				 * ----------------
				 */
				compareResult = MergeCompare(mergeclauses,
											 innerSkipQual,
											 econtext);

				MJ_DEBUG_MERGE_COMPARE(innerSkipQual, compareResult);

				if (compareResult)
					mergestate->mj_JoinState = EXEC_MJ_SKIPINNER;
				else
					mergestate->mj_JoinState = EXEC_MJ_JOINMARK;
				break;

				/*
				 * ******************************** EXEC_MJ_SKIPINNER
				 * means skip over tuples in the inner plan until we find
				 * an inner tuple > current outer tuple.
				 *
				 * For example:
				 *
				 * outer inner 5	 5 5	 5 outer tuple - 12		8 - inner
				 * tuple 14    10 17	12
				 *
				 * we have to advance the inner scan until we find the inner
				 * 12.
				 *
				**************************
				 *
				 *
				 *
				 *
				 *
				 *
				 *
				 */
			case EXEC_MJ_SKIPINNER:
				MJ_printf("ExecMergeJoin: EXEC_MJ_SKIPINNER\n");
				/* ----------------
				 *	before we advance, make sure the current tuples
				 *	do not satisify the mergeclauses.  If they do, then
				 *	we update the marked tuple and go join them.
				 * ----------------
				 */
				qualResult = ExecQual((List *) mergeclauses, econtext);
				MJ_DEBUG_QUAL(mergeclauses, qualResult);

				if (qualResult)
				{
					ExecMarkPos(innerPlan);

					MarkInnerTuple(econtext->ecxt_innertuple, mergestate);

					mergestate->mj_JoinState = EXEC_MJ_JOINTUPLES;
					break;
				}

				/* ----------------
				 *	ok, now test the skip qualification
				 * ----------------
				 */
				compareResult = MergeCompare(mergeclauses,
											 innerSkipQual,
											 econtext);

				MJ_DEBUG_MERGE_COMPARE(innerSkipQual, compareResult);

				/* ----------------
				 *	compareResult is true as long as we should
				 *	continue skipping tuples.
				 * ----------------
				 */
				if (compareResult)
				{
					/* ----------------
					 *	now try and get a new inner tuple
					 * ----------------
					 */
					innerTupleSlot = ExecProcNode(innerPlan, (Plan *) node);
					MJ_DEBUG_PROC_NODE(innerTupleSlot);
					econtext->ecxt_innertuple = innerTupleSlot;

					/* ----------------
					 *	if the inner tuple is null then we know
					 *	we have to restore the inner scan
					 *	and advance to the next outer tuple
					 * ----------------
					 */
					if (TupIsNull(innerTupleSlot))
					{
						/* ----------------
						 *	this is an interesting case.. all our
						 *	inner tuples are smaller then our outer
						 *	tuples so we never found an inner tuple
						 *	to mark.
						 *
						 *			  outer inner
						 *	 outer tuple -	5	  4
						 *					5	  4
						 *					6	 nil  - inner tuple
						 *					7
						 *
						 *	This means the join should end.
						 * ----------------
						 */
						MJ_printf("ExecMergeJoin: **** wierd case 2 ****\n");
						return NULL;
					}

					/* ----------------
					 *	otherwise test the new tuple against the skip qual.
					 *	(we remain in the EXEC_MJ_SKIPINNER state)
					 * ----------------
					 */
					break;
				}

				/* ----------------
				 *	compare finally failed and we have stopped skipping
				 *	inner tuples so now check the outer skip qual
				 *	to see if we should now skip outer tuples...
				 * ----------------
				 */
				compareResult = MergeCompare(mergeclauses,
											 outerSkipQual,
											 econtext);

				MJ_DEBUG_MERGE_COMPARE(outerSkipQual, compareResult);

				if (compareResult)
					mergestate->mj_JoinState = EXEC_MJ_SKIPOUTER;
				else
					mergestate->mj_JoinState = EXEC_MJ_JOINMARK;

				break;

				/*
				 * ******************************** if we get here it
				 * means our code is fucked up and so we just end the join
				 * prematurely. ********************************
				 *
				 */
			default:
				elog(NOTICE, "ExecMergeJoin: invalid join state. aborting");
				return NULL;
		}
	}
}

/* ----------------------------------------------------------------
 *		ExecInitMergeJoin
 *
 * old comments
 *		Creates the run-time state information for the node and
 *		sets the relation id to contain relevant decriptors.
 * ----------------------------------------------------------------
 */
bool
ExecInitMergeJoin(MergeJoin *node, EState *estate, Plan *parent)
{
	MergeJoinState *mergestate;
	List	   *joinclauses;
	RegProcedure rightsortop;
	RegProcedure leftsortop;
	RegProcedure sortop;
	TupleTableSlot *mjSlot;

	List	   *OSortopI;
	List	   *ISortopO;

	MJ1_printf("ExecInitMergeJoin: %s\n",
			   "initializing node");

	/* ----------------
	 *	assign the node's execution state and
	 *	get the range table and direction from it
	 * ----------------
	 */
	node->join.state = estate;

	/* ----------------
	 *	create new merge state for node
	 * ----------------
	 */
	mergestate = makeNode(MergeJoinState);
	mergestate->mj_OSortopI = NIL;
	mergestate->mj_ISortopO = NIL;
	mergestate->mj_JoinState = 0;
	mergestate->mj_MarkedTupleSlot = NULL;
	node->mergestate = mergestate;

	/* ----------------
	 *	Miscellanious initialization
	 *
	 *		 +	assign node's base_id
	 *		 +	assign debugging hooks and
	 *		 +	create expression context for node
	 * ----------------
	 */
	ExecAssignNodeBaseInfo(estate, &mergestate->jstate, parent);
	ExecAssignExprContext(estate, &mergestate->jstate);

#define MERGEJOIN_NSLOTS 2
	/* ----------------
	 *	tuple table initialization
	 * ----------------
	 */
	ExecInitResultTupleSlot(estate, &mergestate->jstate);
	mjSlot = (TupleTableSlot *) palloc(sizeof(TupleTableSlot));
	mjSlot->val = NULL;
	mjSlot->ttc_shouldFree = true;
	mjSlot->ttc_tupleDescriptor = NULL;
	mjSlot->ttc_whichplan = -1;
	mjSlot->ttc_descIsNew = true;
	mergestate->mj_MarkedTupleSlot = mjSlot;

	/* ----------------
	 *	get merge sort operators.
	 *
	 *	XXX for now we assume all quals in the joinclauses were
	 *		sorted with the same operator in both the inner and
	 *		outer relations. -cim 11/2/89
	 * ----------------
	 */
	joinclauses = node->mergeclauses;

	rightsortop = get_opcode(node->mergerightorder[0]);
	leftsortop = get_opcode(node->mergeleftorder[0]);

	if (leftsortop != rightsortop)
		elog(NOTICE, "ExecInitMergeJoin: %s",
			 "left and right sortop's are unequal!");

	sortop = rightsortop;

	/* ----------------
	 *	form merge skip qualifications
	 *
	 *	XXX MJform routines need to be extended
	 *		to take a list of sortops.. -cim 11/2/89
	 * ----------------
	 */
	OSortopI = MJFormOSortopI(joinclauses, sortop);
	ISortopO = MJFormISortopO(joinclauses, sortop);
	mergestate->mj_OSortopI = OSortopI;
	mergestate->mj_ISortopO = ISortopO;

	MJ_printf("\nExecInitMergeJoin: OSortopI is ");
	MJ_nodeDisplay(OSortopI);
	MJ_printf("\nExecInitMergeJoin: ISortopO is ");
	MJ_nodeDisplay(ISortopO);
	MJ_printf("\n");

	/* ----------------
	 *	initialize join state
	 * ----------------
	 */
	mergestate->mj_JoinState = EXEC_MJ_INITIALIZE;

	/* ----------------
	 *	initialize subplans
	 * ----------------
	 */
	ExecInitNode(outerPlan((Plan *) node), estate, (Plan *) node);
	ExecInitNode(innerPlan((Plan *) node), estate, (Plan *) node);

	/* ----------------
	 *	initialize tuple type and projection info
	 * ----------------
	 */
	ExecAssignResultTypeFromTL((Plan *) node, &mergestate->jstate);
	ExecAssignProjectionInfo((Plan *) node, &mergestate->jstate);

	mergestate->jstate.cs_TupFromTlist = false;
	/* ----------------
	 *	initialization successful
	 * ----------------
	 */
	MJ1_printf("ExecInitMergeJoin: %s\n",
			   "node initialized");

	return TRUE;
}

int
ExecCountSlotsMergeJoin(MergeJoin *node)
{
	return ExecCountSlotsNode(outerPlan((Plan *) node)) +
	ExecCountSlotsNode(innerPlan((Plan *) node)) +
	MERGEJOIN_NSLOTS;
}

/* ----------------------------------------------------------------
 *		ExecEndMergeJoin
 *
 * old comments
 *		frees storage allocated through C routines.
 * ----------------------------------------------------------------
 */
void
ExecEndMergeJoin(MergeJoin *node)
{
	MergeJoinState *mergestate;

	MJ1_printf("ExecEndMergeJoin: %s\n",
			   "ending node processing");

	/* ----------------
	 *	get state information from the node
	 * ----------------
	 */
	mergestate = node->mergestate;

	/* ----------------
	 *	Free the projection info and the scan attribute info
	 *
	 *	Note: we don't ExecFreeResultType(mergestate)
	 *		  because the rule manager depends on the tupType
	 *		  returned by ExecMain().  So for now, this
	 *		  is freed at end-transaction time.  -cim 6/2/91
	 * ----------------
	 */
	ExecFreeProjectionInfo(&mergestate->jstate);

	/* ----------------
	 *	shut down the subplans
	 * ----------------
	 */
	ExecEndNode((Plan *) innerPlan((Plan *) node), (Plan *) node);
	ExecEndNode((Plan *) outerPlan((Plan *) node), (Plan *) node);

	/* ----------------
	 *	clean out the tuple table so that we don't try and
	 *	pfree the marked tuples..  see HACK ALERT at the top of
	 *	this file.
	 * ----------------
	 */
	ExecClearTuple(mergestate->jstate.cs_ResultTupleSlot);
	ExecClearTuple(mergestate->mj_MarkedTupleSlot);
	pfree(mergestate->mj_MarkedTupleSlot);
	mergestate->mj_MarkedTupleSlot = NULL;

	MJ1_printf("ExecEndMergeJoin: %s\n",
			   "node processing ended");
}

void
ExecReScanMergeJoin(MergeJoin *node, ExprContext *exprCtxt, Plan *parent)
{
	MergeJoinState *mergestate = node->mergestate;
	TupleTableSlot *mjSlot = mergestate->mj_MarkedTupleSlot;

	ExecClearTuple(mjSlot);
	mjSlot->val = NULL;
	mjSlot->ttc_shouldFree = true;
	mjSlot->ttc_tupleDescriptor = NULL;
	mjSlot->ttc_whichplan = -1;
	mjSlot->ttc_descIsNew = true;

	mergestate->mj_JoinState = EXEC_MJ_INITIALIZE;

	/*
	 * if chgParam of subnodes is not null then plans will be re-scanned
	 * by first ExecProcNode.
	 */
	if (((Plan *) node)->lefttree->chgParam == NULL)
		ExecReScan(((Plan *) node)->lefttree, exprCtxt, (Plan *) node);
	if (((Plan *) node)->righttree->chgParam == NULL)
		ExecReScan(((Plan *) node)->righttree, exprCtxt, (Plan *) node);

}