1 /*-------------------------------------------------------------------------
4 * routines supporting merge joins
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/executor/nodeMergejoin.c,v 1.91 2008/04/13 20:51:20 tgl Exp $
13 *-------------------------------------------------------------------------
17 * ExecMergeJoin mergejoin outer and inner relations.
18 * ExecInitMergeJoin creates and initializes run time states
19 * ExecEndMergeJoin cleans up the node.
23 * Merge-join is done by joining the inner and outer tuples satisfying
24 * join clauses of the form ((= outerKey innerKey) ...).
25 * The join clause list is provided by the query planner and may contain
26 * more than one (= outerKey innerKey) clause (for composite sort key).
28 * However, the query executor needs to know whether an outer
29 * tuple is "greater/smaller" than an inner tuple so that it can
30 * "synchronize" the two relations. For example, consider the following
33 * outer: (0 ^1 1 2 5 5 5 6 6 7) current tuple: 1
34 * inner: (1 ^3 5 5 5 5 6) current tuple: 3
36 * To continue the merge-join, the executor needs to scan both inner
37 * and outer relations till the matching tuples 5. It needs to know
38 * that currently inner tuple 3 is "greater" than outer tuple 1 and
39 * therefore it should scan the outer relation first to find a
40 * matching tuple and so on.
42 * Therefore, rather than directly executing the merge join clauses,
43 * we evaluate the left and right key expressions separately and then
44 * compare the columns one at a time (see MJCompare). The planner
45 * passes us enough information about the sort ordering of the inputs
46 * to allow us to determine how to make the comparison. We may use the
47 * appropriate btree comparison function, since Postgres' only notion
48 * of ordering is specified by btree opfamilies.
51 * Consider the above relations and suppose that the executor has
52 * just joined the first outer "5" with the last inner "5". The
53 * next step is of course to join the second outer "5" with all
54 * the inner "5's". This requires repositioning the inner "cursor"
55 * to point at the first inner "5". This is done by "marking" the
56 * first inner 5 so we can restore the "cursor" to it before joining
57 * with the second outer 5. The access method interface provides
58 * routines to mark and restore to a tuple.
61 * Essential operation of the merge join algorithm is as follows:
64 * get initial outer and inner tuples INITIALIZE
66 * while (outer != inner) { SKIP_TEST
68 * advance outer SKIPOUTER_ADVANCE
70 * advance inner SKIPINNER_ADVANCE
72 * mark inner position SKIP_TEST
74 * while (outer == inner) {
75 * join tuples JOINTUPLES
76 * advance inner position NEXTINNER
78 * advance outer position NEXTOUTER
79 * if (outer == mark) TESTOUTER
80 * restore inner position to mark TESTOUTER
82 * break // return to top of outer loop
87 * The merge join operation is coded in the fashion
88 * of a state machine. At each state, we do something and then
89 * proceed to another state. This state is stored in the node's
90 * execution state information and is preserved across calls to
91 * ExecMergeJoin. -cim 10/31/89
95 #include "access/nbtree.h"
96 #include "catalog/pg_amop.h"
97 #include "executor/execdebug.h"
98 #include "executor/execdefs.h"
99 #include "executor/nodeMergejoin.h"
100 #include "miscadmin.h"
101 #include "utils/acl.h"
102 #include "utils/lsyscache.h"
103 #include "utils/memutils.h"
104 #include "utils/syscache.h"
108 * Runtime data for each mergejoin clause
110 typedef struct MergeJoinClauseData
112 /* Executable expression trees */
113 ExprState *lexpr; /* left-hand (outer) input expression */
114 ExprState *rexpr; /* right-hand (inner) input expression */
117 * If we have a current left or right input tuple, the values of the
118 * expressions are loaded into these fields:
120 Datum ldatum; /* current left-hand value */
121 Datum rdatum; /* current right-hand value */
122 bool lisnull; /* and their isnull flags */
126 * The comparison strategy in use, and the lookup info to let us call the
127 * btree comparison support function.
129 bool reverse; /* if true, negate the cmpfn's output */
130 bool nulls_first; /* if true, nulls sort low */
132 } MergeJoinClauseData;
135 #define MarkInnerTuple(innerTupleSlot, mergestate) \
136 ExecCopySlot((mergestate)->mj_MarkedTupleSlot, (innerTupleSlot))
142 * This deconstructs the list of mergejoinable expressions, which is given
143 * to us by the planner in the form of a list of "leftexpr = rightexpr"
144 * expression trees in the order matching the sort columns of the inputs.
145 * We build an array of MergeJoinClause structs containing the information
146 * we will need at runtime. Each struct essentially tells us how to compare
147 * the two expressions from the original clause.
149 * In addition to the expressions themselves, the planner passes the btree
150 * opfamily OID, btree strategy number (BTLessStrategyNumber or
151 * BTGreaterStrategyNumber), and nulls-first flag that identify the intended
152 * sort ordering for each merge key. The mergejoinable operator is an
153 * equality operator in this opfamily, and the two inputs are guaranteed to be
154 * ordered in either increasing or decreasing (respectively) order according
155 * to this opfamily, with nulls at the indicated end of the range. This
156 * allows us to obtain the needed comparison function from the opfamily.
158 static MergeJoinClause
159 MJExamineQuals(List *mergeclauses,
161 int *mergestrategies,
162 bool *mergenullsfirst,
165 MergeJoinClause clauses;
166 int nClauses = list_length(mergeclauses);
170 clauses = (MergeJoinClause) palloc0(nClauses * sizeof(MergeJoinClauseData));
173 foreach(cl, mergeclauses)
175 OpExpr *qual = (OpExpr *) lfirst(cl);
176 MergeJoinClause clause = &clauses[iClause];
177 Oid opfamily = mergefamilies[iClause];
178 StrategyNumber opstrategy = mergestrategies[iClause];
179 bool nulls_first = mergenullsfirst[iClause];
183 RegProcedure cmpproc;
186 if (!IsA(qual, OpExpr))
187 elog(ERROR, "mergejoin clause is not an OpExpr");
190 * Prepare the input expressions for execution.
192 clause->lexpr = ExecInitExpr((Expr *) linitial(qual->args), parent);
193 clause->rexpr = ExecInitExpr((Expr *) lsecond(qual->args), parent);
195 /* Extract the operator's declared left/right datatypes */
196 get_op_opfamily_properties(qual->opno, opfamily,
200 if (op_strategy != BTEqualStrategyNumber) /* should not happen */
201 elog(ERROR, "cannot merge using non-equality operator %u",
204 /* And get the matching support procedure (comparison function) */
205 cmpproc = get_opfamily_proc(opfamily,
209 if (!RegProcedureIsValid(cmpproc)) /* should not happen */
210 elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
211 BTORDER_PROC, op_lefttype, op_righttype, opfamily);
213 /* Check permission to call cmp function */
214 aclresult = pg_proc_aclcheck(cmpproc, GetUserId(), ACL_EXECUTE);
215 if (aclresult != ACLCHECK_OK)
216 aclcheck_error(aclresult, ACL_KIND_PROC,
217 get_func_name(cmpproc));
219 /* Set up the fmgr lookup information */
220 fmgr_info(cmpproc, &(clause->cmpfinfo));
222 /* Fill the additional comparison-strategy flags */
223 if (opstrategy == BTLessStrategyNumber)
224 clause->reverse = false;
225 else if (opstrategy == BTGreaterStrategyNumber)
226 clause->reverse = true;
227 else /* planner screwed up */
228 elog(ERROR, "unsupported mergejoin strategy %d", opstrategy);
230 clause->nulls_first = nulls_first;
241 * Compute the values of the mergejoined expressions for the current
242 * outer tuple. We also detect whether it's impossible for the current
243 * outer tuple to match anything --- this is true if it yields a NULL
244 * input, since we assume mergejoin operators are strict.
246 * We evaluate the values in OuterEContext, which can be reset each
247 * time we move to a new tuple.
250 MJEvalOuterValues(MergeJoinState *mergestate)
252 ExprContext *econtext = mergestate->mj_OuterEContext;
253 bool canmatch = true;
255 MemoryContext oldContext;
257 ResetExprContext(econtext);
259 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
261 econtext->ecxt_outertuple = mergestate->mj_OuterTupleSlot;
263 for (i = 0; i < mergestate->mj_NumClauses; i++)
265 MergeJoinClause clause = &mergestate->mj_Clauses[i];
267 clause->ldatum = ExecEvalExpr(clause->lexpr, econtext,
268 &clause->lisnull, NULL);
273 MemoryContextSwitchTo(oldContext);
281 * Same as above, but for the inner tuple. Here, we have to be prepared
282 * to load data from either the true current inner, or the marked inner,
283 * so caller must tell us which slot to load from.
286 MJEvalInnerValues(MergeJoinState *mergestate, TupleTableSlot *innerslot)
288 ExprContext *econtext = mergestate->mj_InnerEContext;
289 bool canmatch = true;
291 MemoryContext oldContext;
293 ResetExprContext(econtext);
295 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
297 econtext->ecxt_innertuple = innerslot;
299 for (i = 0; i < mergestate->mj_NumClauses; i++)
301 MergeJoinClause clause = &mergestate->mj_Clauses[i];
303 clause->rdatum = ExecEvalExpr(clause->rexpr, econtext,
304 &clause->risnull, NULL);
309 MemoryContextSwitchTo(oldContext);
317 * Compare the mergejoinable values of the current two input tuples
318 * and return 0 if they are equal (ie, the mergejoin equalities all
319 * succeed), +1 if outer > inner, -1 if outer < inner.
321 * MJEvalOuterValues and MJEvalInnerValues must already have been called
322 * for the current outer and inner tuples, respectively.
325 MJCompare(MergeJoinState *mergestate)
328 bool nulleqnull = false;
329 ExprContext *econtext = mergestate->js.ps.ps_ExprContext;
331 MemoryContext oldContext;
332 FunctionCallInfoData fcinfo;
335 * Call the comparison functions in short-lived context, in case they leak
338 ResetExprContext(econtext);
340 oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
342 for (i = 0; i < mergestate->mj_NumClauses; i++)
344 MergeJoinClause clause = &mergestate->mj_Clauses[i];
348 * Deal with null inputs.
354 nulleqnull = true; /* NULL "=" NULL */
357 if (clause->nulls_first)
358 result = -1; /* NULL "<" NOT_NULL */
360 result = 1; /* NULL ">" NOT_NULL */
365 if (clause->nulls_first)
366 result = 1; /* NOT_NULL ">" NULL */
368 result = -1; /* NOT_NULL "<" NULL */
373 * OK to call the comparison function.
375 InitFunctionCallInfoData(fcinfo, &(clause->cmpfinfo), 2,
377 fcinfo.arg[0] = clause->ldatum;
378 fcinfo.arg[1] = clause->rdatum;
379 fcinfo.argnull[0] = false;
380 fcinfo.argnull[1] = false;
381 fresult = FunctionCallInvoke(&fcinfo);
384 nulleqnull = true; /* treat like NULL = NULL */
387 result = DatumGetInt32(fresult);
397 * If we had any null comparison results or NULL-vs-NULL inputs, we do not
398 * want to report that the tuples are equal. Instead, if result is still
399 * 0, change it to +1. This will result in advancing the inner side of
402 if (nulleqnull && result == 0)
405 MemoryContextSwitchTo(oldContext);
412 * Generate a fake join tuple with nulls for the inner tuple,
413 * and return it if it passes the non-join quals.
415 static TupleTableSlot *
416 MJFillOuter(MergeJoinState *node)
418 ExprContext *econtext = node->js.ps.ps_ExprContext;
419 List *otherqual = node->js.ps.qual;
421 ResetExprContext(econtext);
423 econtext->ecxt_outertuple = node->mj_OuterTupleSlot;
424 econtext->ecxt_innertuple = node->mj_NullInnerTupleSlot;
426 if (ExecQual(otherqual, econtext, false))
429 * qualification succeeded. now form the desired projection tuple and
430 * return the slot containing it.
432 TupleTableSlot *result;
435 MJ_printf("ExecMergeJoin: returning outer fill tuple\n");
437 result = ExecProject(node->js.ps.ps_ProjInfo, &isDone);
439 if (isDone != ExprEndResult)
441 node->js.ps.ps_TupFromTlist =
442 (isDone == ExprMultipleResult);
451 * Generate a fake join tuple with nulls for the outer tuple,
452 * and return it if it passes the non-join quals.
454 static TupleTableSlot *
455 MJFillInner(MergeJoinState *node)
457 ExprContext *econtext = node->js.ps.ps_ExprContext;
458 List *otherqual = node->js.ps.qual;
460 ResetExprContext(econtext);
462 econtext->ecxt_outertuple = node->mj_NullOuterTupleSlot;
463 econtext->ecxt_innertuple = node->mj_InnerTupleSlot;
465 if (ExecQual(otherqual, econtext, false))
468 * qualification succeeded. now form the desired projection tuple and
469 * return the slot containing it.
471 TupleTableSlot *result;
474 MJ_printf("ExecMergeJoin: returning inner fill tuple\n");
476 result = ExecProject(node->js.ps.ps_ProjInfo, &isDone);
478 if (isDone != ExprEndResult)
480 node->js.ps.ps_TupFromTlist =
481 (isDone == ExprMultipleResult);
490 /* ----------------------------------------------------------------
493 * This function is called through the MJ_dump() macro
494 * when EXEC_MERGEJOINDEBUG is defined
495 * ----------------------------------------------------------------
497 #ifdef EXEC_MERGEJOINDEBUG
500 ExecMergeTupleDumpOuter(MergeJoinState *mergestate)
502 TupleTableSlot *outerSlot = mergestate->mj_OuterTupleSlot;
504 printf("==== outer tuple ====\n");
505 if (TupIsNull(outerSlot))
508 MJ_debugtup(outerSlot);
512 ExecMergeTupleDumpInner(MergeJoinState *mergestate)
514 TupleTableSlot *innerSlot = mergestate->mj_InnerTupleSlot;
516 printf("==== inner tuple ====\n");
517 if (TupIsNull(innerSlot))
520 MJ_debugtup(innerSlot);
524 ExecMergeTupleDumpMarked(MergeJoinState *mergestate)
526 TupleTableSlot *markedSlot = mergestate->mj_MarkedTupleSlot;
528 printf("==== marked tuple ====\n");
529 if (TupIsNull(markedSlot))
532 MJ_debugtup(markedSlot);
536 ExecMergeTupleDump(MergeJoinState *mergestate)
538 printf("******** ExecMergeTupleDump ********\n");
540 ExecMergeTupleDumpOuter(mergestate);
541 ExecMergeTupleDumpInner(mergestate);
542 ExecMergeTupleDumpMarked(mergestate);
544 printf("******** \n");
548 /* ----------------------------------------------------------------
550 * ----------------------------------------------------------------
553 ExecMergeJoin(MergeJoinState *node)
560 PlanState *innerPlan;
561 TupleTableSlot *innerTupleSlot;
562 PlanState *outerPlan;
563 TupleTableSlot *outerTupleSlot;
564 ExprContext *econtext;
569 * get information from node
571 estate = node->js.ps.state;
572 innerPlan = innerPlanState(node);
573 outerPlan = outerPlanState(node);
574 econtext = node->js.ps.ps_ExprContext;
575 joinqual = node->js.joinqual;
576 otherqual = node->js.ps.qual;
577 doFillOuter = node->mj_FillOuter;
578 doFillInner = node->mj_FillInner;
581 * Check to see if we're still projecting out tuples from a previous join
582 * tuple (because there is a function-returning-set in the projection
583 * expressions). If so, try to project another one.
585 if (node->js.ps.ps_TupFromTlist)
587 TupleTableSlot *result;
590 result = ExecProject(node->js.ps.ps_ProjInfo, &isDone);
591 if (isDone == ExprMultipleResult)
593 /* Done with that source tuple... */
594 node->js.ps.ps_TupFromTlist = false;
598 * Reset per-tuple memory context to free any expression evaluation
599 * storage allocated in the previous tuple cycle. Note this can't happen
600 * until we're done projecting out tuples from a join tuple.
602 ResetExprContext(econtext);
605 * ok, everything is setup.. let's go to work
612 * get the current state of the join and do things accordingly.
614 switch (node->mj_JoinState)
617 * EXEC_MJ_INITIALIZE_OUTER means that this is the first time
618 * ExecMergeJoin() has been called and so we have to fetch the
619 * first matchable tuple for both outer and inner subplans. We
620 * do the outer side in INITIALIZE_OUTER state, then advance
621 * to INITIALIZE_INNER state for the inner subplan.
623 case EXEC_MJ_INITIALIZE_OUTER:
624 MJ_printf("ExecMergeJoin: EXEC_MJ_INITIALIZE_OUTER\n");
626 outerTupleSlot = ExecProcNode(outerPlan);
627 node->mj_OuterTupleSlot = outerTupleSlot;
628 if (TupIsNull(outerTupleSlot))
630 MJ_printf("ExecMergeJoin: nothing in outer subplan\n");
634 * Need to emit right-join tuples for remaining inner
635 * tuples. We set MatchedInner = true to force the
636 * ENDOUTER state to advance inner.
638 node->mj_JoinState = EXEC_MJ_ENDOUTER;
639 node->mj_MatchedInner = true;
642 /* Otherwise we're done. */
646 /* Compute join values and check for unmatchability */
647 if (MJEvalOuterValues(node))
649 /* OK to go get the first inner tuple */
650 node->mj_JoinState = EXEC_MJ_INITIALIZE_INNER;
654 /* Stay in same state to fetch next outer tuple */
658 * Generate a fake join tuple with nulls for the inner
659 * tuple, and return it if it passes the non-join
662 TupleTableSlot *result;
664 result = MJFillOuter(node);
671 case EXEC_MJ_INITIALIZE_INNER:
672 MJ_printf("ExecMergeJoin: EXEC_MJ_INITIALIZE_INNER\n");
674 innerTupleSlot = ExecProcNode(innerPlan);
675 node->mj_InnerTupleSlot = innerTupleSlot;
676 if (TupIsNull(innerTupleSlot))
678 MJ_printf("ExecMergeJoin: nothing in inner subplan\n");
682 * Need to emit left-join tuples for all outer tuples,
683 * including the one we just fetched. We set
684 * MatchedOuter = false to force the ENDINNER state to
685 * emit first tuple before advancing outer.
687 node->mj_JoinState = EXEC_MJ_ENDINNER;
688 node->mj_MatchedOuter = false;
691 /* Otherwise we're done. */
695 /* Compute join values and check for unmatchability */
696 if (MJEvalInnerValues(node, innerTupleSlot))
699 * OK, we have the initial tuples. Begin by skipping
700 * non-matching tuples.
702 node->mj_JoinState = EXEC_MJ_SKIP_TEST;
706 /* Mark before advancing, if wanted */
707 if (node->mj_ExtraMarks)
708 ExecMarkPos(innerPlan);
709 /* Stay in same state to fetch next inner tuple */
713 * Generate a fake join tuple with nulls for the outer
714 * tuple, and return it if it passes the non-join
717 TupleTableSlot *result;
719 result = MJFillInner(node);
727 * EXEC_MJ_JOINTUPLES means we have two tuples which satisfied
728 * the merge clause so we join them and then proceed to get
729 * the next inner tuple (EXEC_MJ_NEXTINNER).
731 case EXEC_MJ_JOINTUPLES:
732 MJ_printf("ExecMergeJoin: EXEC_MJ_JOINTUPLES\n");
735 * Set the next state machine state. The right things will
736 * happen whether we return this join tuple or just fall
737 * through to continue the state machine execution.
739 node->mj_JoinState = EXEC_MJ_NEXTINNER;
742 * Check the extra qual conditions to see if we actually want
743 * to return this join tuple. If not, can proceed with merge.
744 * We must distinguish the additional joinquals (which must
745 * pass to consider the tuples "matched" for outer-join logic)
746 * from the otherquals (which must pass before we actually
749 * We don't bother with a ResetExprContext here, on the
750 * assumption that we just did one while checking the merge
751 * qual. One per tuple should be sufficient. We do have to
752 * set up the econtext links to the tuples for ExecQual to
755 outerTupleSlot = node->mj_OuterTupleSlot;
756 econtext->ecxt_outertuple = outerTupleSlot;
757 innerTupleSlot = node->mj_InnerTupleSlot;
758 econtext->ecxt_innertuple = innerTupleSlot;
760 if (node->js.jointype == JOIN_IN &&
761 node->mj_MatchedOuter)
765 qualResult = (joinqual == NIL ||
766 ExecQual(joinqual, econtext, false));
767 MJ_DEBUG_QUAL(joinqual, qualResult);
772 node->mj_MatchedOuter = true;
773 node->mj_MatchedInner = true;
775 qualResult = (otherqual == NIL ||
776 ExecQual(otherqual, econtext, false));
777 MJ_DEBUG_QUAL(otherqual, qualResult);
782 * qualification succeeded. now form the desired
783 * projection tuple and return the slot containing it.
785 TupleTableSlot *result;
788 MJ_printf("ExecMergeJoin: returning tuple\n");
790 result = ExecProject(node->js.ps.ps_ProjInfo,
793 if (isDone != ExprEndResult)
795 node->js.ps.ps_TupFromTlist =
796 (isDone == ExprMultipleResult);
804 * EXEC_MJ_NEXTINNER means advance the inner scan to the next
805 * tuple. If the tuple is not nil, we then proceed to test it
806 * against the join qualification.
808 * Before advancing, we check to see if we must emit an
809 * outer-join fill tuple for this inner tuple.
811 case EXEC_MJ_NEXTINNER:
812 MJ_printf("ExecMergeJoin: EXEC_MJ_NEXTINNER\n");
814 if (doFillInner && !node->mj_MatchedInner)
817 * Generate a fake join tuple with nulls for the outer
818 * tuple, and return it if it passes the non-join quals.
820 TupleTableSlot *result;
822 node->mj_MatchedInner = true; /* do it only once */
824 result = MJFillInner(node);
830 * now we get the next inner tuple, if any. If there's none,
831 * advance to next outer tuple (which may be able to join to
832 * previously marked tuples).
834 * NB: must NOT do "extraMarks" here, since we may need to
835 * return to previously marked tuples.
837 innerTupleSlot = ExecProcNode(innerPlan);
838 node->mj_InnerTupleSlot = innerTupleSlot;
839 MJ_DEBUG_PROC_NODE(innerTupleSlot);
840 node->mj_MatchedInner = false;
842 if (TupIsNull(innerTupleSlot))
844 node->mj_JoinState = EXEC_MJ_NEXTOUTER;
849 * Load up the new inner tuple's comparison values. If we see
850 * that it contains a NULL and hence can't match any outer
851 * tuple, we can skip the comparison and assume the new tuple
852 * is greater than current outer.
854 if (!MJEvalInnerValues(node, innerTupleSlot))
856 node->mj_JoinState = EXEC_MJ_NEXTOUTER;
861 * Test the new inner tuple to see if it matches outer.
863 * If they do match, then we join them and move on to the next
864 * inner tuple (EXEC_MJ_JOINTUPLES).
866 * If they do not match then advance to next outer tuple.
868 compareResult = MJCompare(node);
869 MJ_DEBUG_COMPARE(compareResult);
871 if (compareResult == 0)
872 node->mj_JoinState = EXEC_MJ_JOINTUPLES;
875 Assert(compareResult < 0);
876 node->mj_JoinState = EXEC_MJ_NEXTOUTER;
880 /*-------------------------------------------
881 * EXEC_MJ_NEXTOUTER means
884 * outer tuple - 5 5 - marked tuple
889 * we know we just bumped into the
890 * first inner tuple > current outer tuple (or possibly
891 * the end of the inner stream)
892 * so get a new outer tuple and then
893 * proceed to test it against the marked tuple
894 * (EXEC_MJ_TESTOUTER)
896 * Before advancing, we check to see if we must emit an
897 * outer-join fill tuple for this outer tuple.
898 *------------------------------------------------
900 case EXEC_MJ_NEXTOUTER:
901 MJ_printf("ExecMergeJoin: EXEC_MJ_NEXTOUTER\n");
903 if (doFillOuter && !node->mj_MatchedOuter)
906 * Generate a fake join tuple with nulls for the inner
907 * tuple, and return it if it passes the non-join quals.
909 TupleTableSlot *result;
911 node->mj_MatchedOuter = true; /* do it only once */
913 result = MJFillOuter(node);
919 * now we get the next outer tuple, if any
921 outerTupleSlot = ExecProcNode(outerPlan);
922 node->mj_OuterTupleSlot = outerTupleSlot;
923 MJ_DEBUG_PROC_NODE(outerTupleSlot);
924 node->mj_MatchedOuter = false;
927 * if the outer tuple is null then we are done with the join,
928 * unless we have inner tuples we need to null-fill.
930 if (TupIsNull(outerTupleSlot))
932 MJ_printf("ExecMergeJoin: end of outer subplan\n");
933 innerTupleSlot = node->mj_InnerTupleSlot;
934 if (doFillInner && !TupIsNull(innerTupleSlot))
937 * Need to emit right-join tuples for remaining inner
940 node->mj_JoinState = EXEC_MJ_ENDOUTER;
943 /* Otherwise we're done. */
947 /* Compute join values and check for unmatchability */
948 if (MJEvalOuterValues(node))
950 /* Go test the new tuple against the marked tuple */
951 node->mj_JoinState = EXEC_MJ_TESTOUTER;
955 /* Can't match, so fetch next outer tuple */
956 node->mj_JoinState = EXEC_MJ_NEXTOUTER;
960 /*--------------------------------------------------------
961 * EXEC_MJ_TESTOUTER If the new outer tuple and the marked
962 * tuple satisfy the merge clause then we know we have
963 * duplicates in the outer scan so we have to restore the
964 * inner scan to the marked tuple and proceed to join the
965 * new outer tuple with the inner tuples.
967 * This is the case when
971 * new outer tuple - 5 5
975 * new outer tuple == marked tuple
977 * If the outer tuple fails the test, then we are done
978 * with the marked tuples, and we have to look for a
979 * match to the current inner tuple. So we will
980 * proceed to skip outer tuples until outer >= inner
981 * (EXEC_MJ_SKIP_TEST).
983 * This is the case when
988 * new outer tuple - 6 8 - inner tuple
991 * new outer tuple > marked tuple
993 *---------------------------------------------------------
995 case EXEC_MJ_TESTOUTER:
996 MJ_printf("ExecMergeJoin: EXEC_MJ_TESTOUTER\n");
999 * Here we must compare the outer tuple with the marked inner
1000 * tuple. (We can ignore the result of MJEvalInnerValues,
1001 * since the marked inner tuple is certainly matchable.)
1003 innerTupleSlot = node->mj_MarkedTupleSlot;
1004 (void) MJEvalInnerValues(node, innerTupleSlot);
1006 compareResult = MJCompare(node);
1007 MJ_DEBUG_COMPARE(compareResult);
1009 if (compareResult == 0)
1012 * the merge clause matched so now we restore the inner
1013 * scan position to the first mark, and go join that tuple
1014 * (and any following ones) to the new outer.
1016 * NOTE: we do not need to worry about the MatchedInner
1017 * state for the rescanned inner tuples. We know all of
1018 * them will match this new outer tuple and therefore
1019 * won't be emitted as fill tuples. This works *only*
1020 * because we require the extra joinquals to be nil when
1021 * doing a right or full join --- otherwise some of the
1022 * rescanned tuples might fail the extra joinquals.
1024 ExecRestrPos(innerPlan);
1027 * ExecRestrPos probably should give us back a new Slot,
1028 * but since it doesn't, use the marked slot. (The
1029 * previously returned mj_InnerTupleSlot cannot be assumed
1030 * to hold the required tuple.)
1032 node->mj_InnerTupleSlot = innerTupleSlot;
1033 /* we need not do MJEvalInnerValues again */
1035 node->mj_JoinState = EXEC_MJ_JOINTUPLES;
1040 * if the new outer tuple didn't match the marked inner
1041 * tuple then we have a case like:
1044 * 4 4 - marked tuple
1049 * which means that all subsequent outer tuples will be
1050 * larger than our marked inner tuples. So we need not
1051 * revisit any of the marked tuples but can proceed to
1052 * look for a match to the current inner. If there's
1053 * no more inners, we are done.
1056 Assert(compareResult > 0);
1057 innerTupleSlot = node->mj_InnerTupleSlot;
1058 if (TupIsNull(innerTupleSlot))
1063 * Need to emit left-join tuples for remaining
1066 node->mj_JoinState = EXEC_MJ_ENDINNER;
1069 /* Otherwise we're done. */
1073 /* reload comparison data for current inner */
1074 if (MJEvalInnerValues(node, innerTupleSlot))
1076 /* proceed to compare it to the current outer */
1077 node->mj_JoinState = EXEC_MJ_SKIP_TEST;
1082 * current inner can't possibly match any outer;
1083 * better to advance the inner scan than the outer.
1085 node->mj_JoinState = EXEC_MJ_SKIPINNER_ADVANCE;
1090 /*----------------------------------------------------------
1091 * EXEC_MJ_SKIP means compare tuples and if they do not
1092 * match, skip whichever is lesser.
1099 * outer tuple - 6 8 - inner tuple
1103 * we have to advance the outer scan
1104 * until we find the outer 8.
1106 * On the other hand:
1111 * outer tuple - 12 8 - inner tuple
1115 * we have to advance the inner scan
1116 * until we find the inner 12.
1117 *----------------------------------------------------------
1119 case EXEC_MJ_SKIP_TEST:
1120 MJ_printf("ExecMergeJoin: EXEC_MJ_SKIP_TEST\n");
1123 * before we advance, make sure the current tuples do not
1124 * satisfy the mergeclauses. If they do, then we update the
1125 * marked tuple position and go join them.
1127 compareResult = MJCompare(node);
1128 MJ_DEBUG_COMPARE(compareResult);
1130 if (compareResult == 0)
1132 ExecMarkPos(innerPlan);
1134 MarkInnerTuple(node->mj_InnerTupleSlot, node);
1136 node->mj_JoinState = EXEC_MJ_JOINTUPLES;
1138 else if (compareResult < 0)
1139 node->mj_JoinState = EXEC_MJ_SKIPOUTER_ADVANCE;
1141 /* compareResult > 0 */
1142 node->mj_JoinState = EXEC_MJ_SKIPINNER_ADVANCE;
1146 * SKIPOUTER_ADVANCE: advance over an outer tuple that is
1147 * known not to join to any inner tuple.
1149 * Before advancing, we check to see if we must emit an
1150 * outer-join fill tuple for this outer tuple.
1152 case EXEC_MJ_SKIPOUTER_ADVANCE:
1153 MJ_printf("ExecMergeJoin: EXEC_MJ_SKIPOUTER_ADVANCE\n");
1155 if (doFillOuter && !node->mj_MatchedOuter)
1158 * Generate a fake join tuple with nulls for the inner
1159 * tuple, and return it if it passes the non-join quals.
1161 TupleTableSlot *result;
1163 node->mj_MatchedOuter = true; /* do it only once */
1165 result = MJFillOuter(node);
1171 * now we get the next outer tuple, if any
1173 outerTupleSlot = ExecProcNode(outerPlan);
1174 node->mj_OuterTupleSlot = outerTupleSlot;
1175 MJ_DEBUG_PROC_NODE(outerTupleSlot);
1176 node->mj_MatchedOuter = false;
1179 * if the outer tuple is null then we are done with the join,
1180 * unless we have inner tuples we need to null-fill.
1182 if (TupIsNull(outerTupleSlot))
1184 MJ_printf("ExecMergeJoin: end of outer subplan\n");
1185 innerTupleSlot = node->mj_InnerTupleSlot;
1186 if (doFillInner && !TupIsNull(innerTupleSlot))
1189 * Need to emit right-join tuples for remaining inner
1192 node->mj_JoinState = EXEC_MJ_ENDOUTER;
1195 /* Otherwise we're done. */
1199 /* Compute join values and check for unmatchability */
1200 if (MJEvalOuterValues(node))
1202 /* Go test the new tuple against the current inner */
1203 node->mj_JoinState = EXEC_MJ_SKIP_TEST;
1207 /* Can't match, so fetch next outer tuple */
1208 node->mj_JoinState = EXEC_MJ_SKIPOUTER_ADVANCE;
1213 * SKIPINNER_ADVANCE: advance over an inner tuple that is
1214 * known not to join to any outer tuple.
1216 * Before advancing, we check to see if we must emit an
1217 * outer-join fill tuple for this inner tuple.
1219 case EXEC_MJ_SKIPINNER_ADVANCE:
1220 MJ_printf("ExecMergeJoin: EXEC_MJ_SKIPINNER_ADVANCE\n");
1222 if (doFillInner && !node->mj_MatchedInner)
1225 * Generate a fake join tuple with nulls for the outer
1226 * tuple, and return it if it passes the non-join quals.
1228 TupleTableSlot *result;
1230 node->mj_MatchedInner = true; /* do it only once */
1232 result = MJFillInner(node);
1237 /* Mark before advancing, if wanted */
1238 if (node->mj_ExtraMarks)
1239 ExecMarkPos(innerPlan);
1242 * now we get the next inner tuple, if any
1244 innerTupleSlot = ExecProcNode(innerPlan);
1245 node->mj_InnerTupleSlot = innerTupleSlot;
1246 MJ_DEBUG_PROC_NODE(innerTupleSlot);
1247 node->mj_MatchedInner = false;
1250 * if the inner tuple is null then we are done with the join,
1251 * unless we have outer tuples we need to null-fill.
1253 if (TupIsNull(innerTupleSlot))
1255 MJ_printf("ExecMergeJoin: end of inner subplan\n");
1256 outerTupleSlot = node->mj_OuterTupleSlot;
1257 if (doFillOuter && !TupIsNull(outerTupleSlot))
1260 * Need to emit left-join tuples for remaining outer
1263 node->mj_JoinState = EXEC_MJ_ENDINNER;
1266 /* Otherwise we're done. */
1270 /* Compute join values and check for unmatchability */
1271 if (MJEvalInnerValues(node, innerTupleSlot))
1273 /* proceed to compare it to the current outer */
1274 node->mj_JoinState = EXEC_MJ_SKIP_TEST;
1279 * current inner can't possibly match any outer; better to
1280 * advance the inner scan than the outer.
1282 node->mj_JoinState = EXEC_MJ_SKIPINNER_ADVANCE;
1287 * EXEC_MJ_ENDOUTER means we have run out of outer tuples, but
1288 * are doing a right/full join and therefore must null-fill
1289 * any remaing unmatched inner tuples.
1291 case EXEC_MJ_ENDOUTER:
1292 MJ_printf("ExecMergeJoin: EXEC_MJ_ENDOUTER\n");
1294 Assert(doFillInner);
1296 if (!node->mj_MatchedInner)
1299 * Generate a fake join tuple with nulls for the outer
1300 * tuple, and return it if it passes the non-join quals.
1302 TupleTableSlot *result;
1304 node->mj_MatchedInner = true; /* do it only once */
1306 result = MJFillInner(node);
1311 /* Mark before advancing, if wanted */
1312 if (node->mj_ExtraMarks)
1313 ExecMarkPos(innerPlan);
1316 * now we get the next inner tuple, if any
1318 innerTupleSlot = ExecProcNode(innerPlan);
1319 node->mj_InnerTupleSlot = innerTupleSlot;
1320 MJ_DEBUG_PROC_NODE(innerTupleSlot);
1321 node->mj_MatchedInner = false;
1323 if (TupIsNull(innerTupleSlot))
1325 MJ_printf("ExecMergeJoin: end of inner subplan\n");
1329 /* Else remain in ENDOUTER state and process next tuple. */
1333 * EXEC_MJ_ENDINNER means we have run out of inner tuples, but
1334 * are doing a left/full join and therefore must null- fill
1335 * any remaing unmatched outer tuples.
1337 case EXEC_MJ_ENDINNER:
1338 MJ_printf("ExecMergeJoin: EXEC_MJ_ENDINNER\n");
1340 Assert(doFillOuter);
1342 if (!node->mj_MatchedOuter)
1345 * Generate a fake join tuple with nulls for the inner
1346 * tuple, and return it if it passes the non-join quals.
1348 TupleTableSlot *result;
1350 node->mj_MatchedOuter = true; /* do it only once */
1352 result = MJFillOuter(node);
1358 * now we get the next outer tuple, if any
1360 outerTupleSlot = ExecProcNode(outerPlan);
1361 node->mj_OuterTupleSlot = outerTupleSlot;
1362 MJ_DEBUG_PROC_NODE(outerTupleSlot);
1363 node->mj_MatchedOuter = false;
1365 if (TupIsNull(outerTupleSlot))
1367 MJ_printf("ExecMergeJoin: end of outer subplan\n");
1371 /* Else remain in ENDINNER state and process next tuple. */
1375 * broken state value?
1378 elog(ERROR, "unrecognized mergejoin state: %d",
1379 (int) node->mj_JoinState);
1384 /* ----------------------------------------------------------------
1386 * ----------------------------------------------------------------
1389 ExecInitMergeJoin(MergeJoin *node, EState *estate, int eflags)
1391 MergeJoinState *mergestate;
1393 /* check for unsupported flags */
1394 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
1396 MJ1_printf("ExecInitMergeJoin: %s\n",
1397 "initializing node");
1400 * create state structure
1402 mergestate = makeNode(MergeJoinState);
1403 mergestate->js.ps.plan = (Plan *) node;
1404 mergestate->js.ps.state = estate;
1407 * Miscellaneous initialization
1409 * create expression context for node
1411 ExecAssignExprContext(estate, &mergestate->js.ps);
1414 * we need two additional econtexts in which we can compute the join
1415 * expressions from the left and right input tuples. The node's regular
1416 * econtext won't do because it gets reset too often.
1418 mergestate->mj_OuterEContext = CreateExprContext(estate);
1419 mergestate->mj_InnerEContext = CreateExprContext(estate);
1422 * initialize child expressions
1424 mergestate->js.ps.targetlist = (List *)
1425 ExecInitExpr((Expr *) node->join.plan.targetlist,
1426 (PlanState *) mergestate);
1427 mergestate->js.ps.qual = (List *)
1428 ExecInitExpr((Expr *) node->join.plan.qual,
1429 (PlanState *) mergestate);
1430 mergestate->js.jointype = node->join.jointype;
1431 mergestate->js.joinqual = (List *)
1432 ExecInitExpr((Expr *) node->join.joinqual,
1433 (PlanState *) mergestate);
1434 /* mergeclauses are handled below */
1437 * initialize child nodes
1439 * inner child must support MARK/RESTORE.
1441 outerPlanState(mergestate) = ExecInitNode(outerPlan(node), estate, eflags);
1442 innerPlanState(mergestate) = ExecInitNode(innerPlan(node), estate,
1443 eflags | EXEC_FLAG_MARK);
1446 * For certain types of inner child nodes, it is advantageous to issue
1447 * MARK every time we advance past an inner tuple we will never return to.
1448 * For other types, MARK on a tuple we cannot return to is a waste of
1449 * cycles. Detect which case applies and set mj_ExtraMarks if we want to
1450 * issue "unnecessary" MARK calls.
1452 * Currently, only Material wants the extra MARKs, and it will be helpful
1453 * only if eflags doesn't specify REWIND.
1455 if (IsA(innerPlan(node), Material) &&
1456 (eflags & EXEC_FLAG_REWIND) == 0)
1457 mergestate->mj_ExtraMarks = true;
1459 mergestate->mj_ExtraMarks = false;
1461 #define MERGEJOIN_NSLOTS 4
1464 * tuple table initialization
1466 ExecInitResultTupleSlot(estate, &mergestate->js.ps);
1468 mergestate->mj_MarkedTupleSlot = ExecInitExtraTupleSlot(estate);
1469 ExecSetSlotDescriptor(mergestate->mj_MarkedTupleSlot,
1470 ExecGetResultType(innerPlanState(mergestate)));
1472 switch (node->join.jointype)
1476 mergestate->mj_FillOuter = false;
1477 mergestate->mj_FillInner = false;
1480 mergestate->mj_FillOuter = true;
1481 mergestate->mj_FillInner = false;
1482 mergestate->mj_NullInnerTupleSlot =
1483 ExecInitNullTupleSlot(estate,
1484 ExecGetResultType(innerPlanState(mergestate)));
1487 mergestate->mj_FillOuter = false;
1488 mergestate->mj_FillInner = true;
1489 mergestate->mj_NullOuterTupleSlot =
1490 ExecInitNullTupleSlot(estate,
1491 ExecGetResultType(outerPlanState(mergestate)));
1494 * Can't handle right or full join with non-nil extra joinclauses.
1495 * This should have been caught by planner.
1497 if (node->join.joinqual != NIL)
1499 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1500 errmsg("RIGHT JOIN is only supported with merge-joinable join conditions")));
1503 mergestate->mj_FillOuter = true;
1504 mergestate->mj_FillInner = true;
1505 mergestate->mj_NullOuterTupleSlot =
1506 ExecInitNullTupleSlot(estate,
1507 ExecGetResultType(outerPlanState(mergestate)));
1508 mergestate->mj_NullInnerTupleSlot =
1509 ExecInitNullTupleSlot(estate,
1510 ExecGetResultType(innerPlanState(mergestate)));
1513 * Can't handle right or full join with non-nil extra joinclauses.
1515 if (node->join.joinqual != NIL)
1517 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1518 errmsg("FULL JOIN is only supported with merge-joinable join conditions")));
1521 elog(ERROR, "unrecognized join type: %d",
1522 (int) node->join.jointype);
1526 * initialize tuple type and projection info
1528 ExecAssignResultTypeFromTL(&mergestate->js.ps);
1529 ExecAssignProjectionInfo(&mergestate->js.ps, NULL);
1532 * preprocess the merge clauses
1534 mergestate->mj_NumClauses = list_length(node->mergeclauses);
1535 mergestate->mj_Clauses = MJExamineQuals(node->mergeclauses,
1536 node->mergeFamilies,
1537 node->mergeStrategies,
1538 node->mergeNullsFirst,
1539 (PlanState *) mergestate);
1542 * initialize join state
1544 mergestate->mj_JoinState = EXEC_MJ_INITIALIZE_OUTER;
1545 mergestate->js.ps.ps_TupFromTlist = false;
1546 mergestate->mj_MatchedOuter = false;
1547 mergestate->mj_MatchedInner = false;
1548 mergestate->mj_OuterTupleSlot = NULL;
1549 mergestate->mj_InnerTupleSlot = NULL;
1552 * initialization successful
1554 MJ1_printf("ExecInitMergeJoin: %s\n",
1555 "node initialized");
1561 ExecCountSlotsMergeJoin(MergeJoin *node)
1563 return ExecCountSlotsNode(outerPlan((Plan *) node)) +
1564 ExecCountSlotsNode(innerPlan((Plan *) node)) +
1568 /* ----------------------------------------------------------------
1572 * frees storage allocated through C routines.
1573 * ----------------------------------------------------------------
1576 ExecEndMergeJoin(MergeJoinState *node)
1578 MJ1_printf("ExecEndMergeJoin: %s\n",
1579 "ending node processing");
1582 * Free the exprcontext
1584 ExecFreeExprContext(&node->js.ps);
1587 * clean out the tuple table
1589 ExecClearTuple(node->js.ps.ps_ResultTupleSlot);
1590 ExecClearTuple(node->mj_MarkedTupleSlot);
1593 * shut down the subplans
1595 ExecEndNode(innerPlanState(node));
1596 ExecEndNode(outerPlanState(node));
1598 MJ1_printf("ExecEndMergeJoin: %s\n",
1599 "node processing ended");
1603 ExecReScanMergeJoin(MergeJoinState *node, ExprContext *exprCtxt)
1605 ExecClearTuple(node->mj_MarkedTupleSlot);
1607 node->mj_JoinState = EXEC_MJ_INITIALIZE_OUTER;
1608 node->js.ps.ps_TupFromTlist = false;
1609 node->mj_MatchedOuter = false;
1610 node->mj_MatchedInner = false;
1611 node->mj_OuterTupleSlot = NULL;
1612 node->mj_InnerTupleSlot = NULL;
1615 * if chgParam of subnodes is not null then plans will be re-scanned by
1616 * first ExecProcNode.
1618 if (((PlanState *) node)->lefttree->chgParam == NULL)
1619 ExecReScan(((PlanState *) node)->lefttree, exprCtxt);
1620 if (((PlanState *) node)->righttree->chgParam == NULL)
1621 ExecReScan(((PlanState *) node)->righttree, exprCtxt);