PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
nodeMergejoin.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * nodeMergejoin.c
4  * routines supporting merge joins
5  *
6  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/executor/nodeMergejoin.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 /*
16  * INTERFACE ROUTINES
17  * ExecMergeJoin mergejoin outer and inner relations.
18  * ExecInitMergeJoin creates and initializes run time states
19  * ExecEndMergeJoin cleans up the node.
20  *
21  * NOTES
22  *
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).
27  *
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
31  * relations:
32  *
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
35  *
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.
41  *
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.
49  *
50  *
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.
59  *
60  *
61  * Essential operation of the merge join algorithm is as follows:
62  *
63  * Join {
64  * get initial outer and inner tuples INITIALIZE
65  * do forever {
66  * while (outer != inner) { SKIP_TEST
67  * if (outer < inner)
68  * advance outer SKIPOUTER_ADVANCE
69  * else
70  * advance inner SKIPINNER_ADVANCE
71  * }
72  * mark inner position SKIP_TEST
73  * do forever {
74  * while (outer == inner) {
75  * join tuples JOINTUPLES
76  * advance inner position NEXTINNER
77  * }
78  * advance outer position NEXTOUTER
79  * if (outer == mark) TESTOUTER
80  * restore inner position to mark TESTOUTER
81  * else
82  * break // return to top of outer loop
83  * }
84  * }
85  * }
86  *
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
92  */
93 #include "postgres.h"
94 
95 #include "access/nbtree.h"
96 #include "executor/execdebug.h"
97 #include "executor/nodeMergejoin.h"
98 #include "utils/lsyscache.h"
99 #include "utils/memutils.h"
100 
101 
102 /*
103  * States of the ExecMergeJoin state machine
104  */
105 #define EXEC_MJ_INITIALIZE_OUTER 1
106 #define EXEC_MJ_INITIALIZE_INNER 2
107 #define EXEC_MJ_JOINTUPLES 3
108 #define EXEC_MJ_NEXTOUTER 4
109 #define EXEC_MJ_TESTOUTER 5
110 #define EXEC_MJ_NEXTINNER 6
111 #define EXEC_MJ_SKIP_TEST 7
112 #define EXEC_MJ_SKIPOUTER_ADVANCE 8
113 #define EXEC_MJ_SKIPINNER_ADVANCE 9
114 #define EXEC_MJ_ENDOUTER 10
115 #define EXEC_MJ_ENDINNER 11
116 
117 /*
118  * Runtime data for each mergejoin clause
119  */
120 typedef struct MergeJoinClauseData
121 {
122  /* Executable expression trees */
123  ExprState *lexpr; /* left-hand (outer) input expression */
124  ExprState *rexpr; /* right-hand (inner) input expression */
125 
126  /*
127  * If we have a current left or right input tuple, the values of the
128  * expressions are loaded into these fields:
129  */
130  Datum ldatum; /* current left-hand value */
131  Datum rdatum; /* current right-hand value */
132  bool lisnull; /* and their isnull flags */
133  bool risnull;
134 
135  /*
136  * Everything we need to know to compare the left and right values is
137  * stored here.
138  */
141 
142 /* Result type for MJEvalOuterValues and MJEvalInnerValues */
143 typedef enum
144 {
145  MJEVAL_MATCHABLE, /* normal, potentially matchable tuple */
146  MJEVAL_NONMATCHABLE, /* tuple cannot join because it has a null */
147  MJEVAL_ENDOFJOIN /* end of input (physical or effective) */
148 } MJEvalResult;
149 
150 
151 #define MarkInnerTuple(innerTupleSlot, mergestate) \
152  ExecCopySlot((mergestate)->mj_MarkedTupleSlot, (innerTupleSlot))
153 
154 
155 /*
156  * MJExamineQuals
157  *
158  * This deconstructs the list of mergejoinable expressions, which is given
159  * to us by the planner in the form of a list of "leftexpr = rightexpr"
160  * expression trees in the order matching the sort columns of the inputs.
161  * We build an array of MergeJoinClause structs containing the information
162  * we will need at runtime. Each struct essentially tells us how to compare
163  * the two expressions from the original clause.
164  *
165  * In addition to the expressions themselves, the planner passes the btree
166  * opfamily OID, collation OID, btree strategy number (BTLessStrategyNumber or
167  * BTGreaterStrategyNumber), and nulls-first flag that identify the intended
168  * sort ordering for each merge key. The mergejoinable operator is an
169  * equality operator in the opfamily, and the two inputs are guaranteed to be
170  * ordered in either increasing or decreasing (respectively) order according
171  * to the opfamily and collation, with nulls at the indicated end of the range.
172  * This allows us to obtain the needed comparison function from the opfamily.
173  */
174 static MergeJoinClause
175 MJExamineQuals(List *mergeclauses,
176  Oid *mergefamilies,
177  Oid *mergecollations,
178  int *mergestrategies,
179  bool *mergenullsfirst,
180  PlanState *parent)
181 {
182  MergeJoinClause clauses;
183  int nClauses = list_length(mergeclauses);
184  int iClause;
185  ListCell *cl;
186 
187  clauses = (MergeJoinClause) palloc0(nClauses * sizeof(MergeJoinClauseData));
188 
189  iClause = 0;
190  foreach(cl, mergeclauses)
191  {
192  OpExpr *qual = (OpExpr *) lfirst(cl);
193  MergeJoinClause clause = &clauses[iClause];
194  Oid opfamily = mergefamilies[iClause];
195  Oid collation = mergecollations[iClause];
196  StrategyNumber opstrategy = mergestrategies[iClause];
197  bool nulls_first = mergenullsfirst[iClause];
198  int op_strategy;
199  Oid op_lefttype;
200  Oid op_righttype;
201  Oid sortfunc;
202 
203  if (!IsA(qual, OpExpr))
204  elog(ERROR, "mergejoin clause is not an OpExpr");
205 
206  /*
207  * Prepare the input expressions for execution.
208  */
209  clause->lexpr = ExecInitExpr((Expr *) linitial(qual->args), parent);
210  clause->rexpr = ExecInitExpr((Expr *) lsecond(qual->args), parent);
211 
212  /* Set up sort support data */
214  clause->ssup.ssup_collation = collation;
215  if (opstrategy == BTLessStrategyNumber)
216  clause->ssup.ssup_reverse = false;
217  else if (opstrategy == BTGreaterStrategyNumber)
218  clause->ssup.ssup_reverse = true;
219  else /* planner screwed up */
220  elog(ERROR, "unsupported mergejoin strategy %d", opstrategy);
221  clause->ssup.ssup_nulls_first = nulls_first;
222 
223  /* Extract the operator's declared left/right datatypes */
224  get_op_opfamily_properties(qual->opno, opfamily, false,
225  &op_strategy,
226  &op_lefttype,
227  &op_righttype);
228  if (op_strategy != BTEqualStrategyNumber) /* should not happen */
229  elog(ERROR, "cannot merge using non-equality operator %u",
230  qual->opno);
231 
232  /*
233  * sortsupport routine must know if abbreviation optimization is
234  * applicable in principle. It is never applicable for merge joins
235  * because there is no convenient opportunity to convert to
236  * alternative representation.
237  */
238  clause->ssup.abbreviate = false;
239 
240  /* And get the matching support or comparison function */
241  Assert(clause->ssup.comparator == NULL);
242  sortfunc = get_opfamily_proc(opfamily,
243  op_lefttype,
244  op_righttype,
246  if (OidIsValid(sortfunc))
247  {
248  /* The sort support function can provide a comparator */
249  OidFunctionCall1(sortfunc, PointerGetDatum(&clause->ssup));
250  }
251  if (clause->ssup.comparator == NULL)
252  {
253  /* support not available, get comparison func */
254  sortfunc = get_opfamily_proc(opfamily,
255  op_lefttype,
256  op_righttype,
257  BTORDER_PROC);
258  if (!OidIsValid(sortfunc)) /* should not happen */
259  elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
260  BTORDER_PROC, op_lefttype, op_righttype, opfamily);
261  /* We'll use a shim to call the old-style btree comparator */
262  PrepareSortSupportComparisonShim(sortfunc, &clause->ssup);
263  }
264 
265  iClause++;
266  }
267 
268  return clauses;
269 }
270 
271 /*
272  * MJEvalOuterValues
273  *
274  * Compute the values of the mergejoined expressions for the current
275  * outer tuple. We also detect whether it's impossible for the current
276  * outer tuple to match anything --- this is true if it yields a NULL
277  * input, since we assume mergejoin operators are strict. If the NULL
278  * is in the first join column, and that column sorts nulls last, then
279  * we can further conclude that no following tuple can match anything
280  * either, since they must all have nulls in the first column. However,
281  * that case is only interesting if we're not in FillOuter mode, else
282  * we have to visit all the tuples anyway.
283  *
284  * For the convenience of callers, we also make this routine responsible
285  * for testing for end-of-input (null outer tuple), and returning
286  * MJEVAL_ENDOFJOIN when that's seen. This allows the same code to be used
287  * for both real end-of-input and the effective end-of-input represented by
288  * a first-column NULL.
289  *
290  * We evaluate the values in OuterEContext, which can be reset each
291  * time we move to a new tuple.
292  */
293 static MJEvalResult
295 {
296  ExprContext *econtext = mergestate->mj_OuterEContext;
298  int i;
299  MemoryContext oldContext;
300 
301  /* Check for end of outer subplan */
302  if (TupIsNull(mergestate->mj_OuterTupleSlot))
303  return MJEVAL_ENDOFJOIN;
304 
305  ResetExprContext(econtext);
306 
307  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
308 
309  econtext->ecxt_outertuple = mergestate->mj_OuterTupleSlot;
310 
311  for (i = 0; i < mergestate->mj_NumClauses; i++)
312  {
313  MergeJoinClause clause = &mergestate->mj_Clauses[i];
314 
315  clause->ldatum = ExecEvalExpr(clause->lexpr, econtext,
316  &clause->lisnull);
317  if (clause->lisnull)
318  {
319  /* match is impossible; can we end the join early? */
320  if (i == 0 && !clause->ssup.ssup_nulls_first &&
321  !mergestate->mj_FillOuter)
322  result = MJEVAL_ENDOFJOIN;
323  else if (result == MJEVAL_MATCHABLE)
324  result = MJEVAL_NONMATCHABLE;
325  }
326  }
327 
328  MemoryContextSwitchTo(oldContext);
329 
330  return result;
331 }
332 
333 /*
334  * MJEvalInnerValues
335  *
336  * Same as above, but for the inner tuple. Here, we have to be prepared
337  * to load data from either the true current inner, or the marked inner,
338  * so caller must tell us which slot to load from.
339  */
340 static MJEvalResult
342 {
343  ExprContext *econtext = mergestate->mj_InnerEContext;
345  int i;
346  MemoryContext oldContext;
347 
348  /* Check for end of inner subplan */
349  if (TupIsNull(innerslot))
350  return MJEVAL_ENDOFJOIN;
351 
352  ResetExprContext(econtext);
353 
354  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
355 
356  econtext->ecxt_innertuple = innerslot;
357 
358  for (i = 0; i < mergestate->mj_NumClauses; i++)
359  {
360  MergeJoinClause clause = &mergestate->mj_Clauses[i];
361 
362  clause->rdatum = ExecEvalExpr(clause->rexpr, econtext,
363  &clause->risnull);
364  if (clause->risnull)
365  {
366  /* match is impossible; can we end the join early? */
367  if (i == 0 && !clause->ssup.ssup_nulls_first &&
368  !mergestate->mj_FillInner)
369  result = MJEVAL_ENDOFJOIN;
370  else if (result == MJEVAL_MATCHABLE)
371  result = MJEVAL_NONMATCHABLE;
372  }
373  }
374 
375  MemoryContextSwitchTo(oldContext);
376 
377  return result;
378 }
379 
380 /*
381  * MJCompare
382  *
383  * Compare the mergejoinable values of the current two input tuples
384  * and return 0 if they are equal (ie, the mergejoin equalities all
385  * succeed), >0 if outer > inner, <0 if outer < inner.
386  *
387  * MJEvalOuterValues and MJEvalInnerValues must already have been called
388  * for the current outer and inner tuples, respectively.
389  */
390 static int
392 {
393  int result = 0;
394  bool nulleqnull = false;
395  ExprContext *econtext = mergestate->js.ps.ps_ExprContext;
396  int i;
397  MemoryContext oldContext;
398 
399  /*
400  * Call the comparison functions in short-lived context, in case they leak
401  * memory.
402  */
403  ResetExprContext(econtext);
404 
405  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
406 
407  for (i = 0; i < mergestate->mj_NumClauses; i++)
408  {
409  MergeJoinClause clause = &mergestate->mj_Clauses[i];
410 
411  /*
412  * Special case for NULL-vs-NULL, else use standard comparison.
413  */
414  if (clause->lisnull && clause->risnull)
415  {
416  nulleqnull = true; /* NULL "=" NULL */
417  continue;
418  }
419 
420  result = ApplySortComparator(clause->ldatum, clause->lisnull,
421  clause->rdatum, clause->risnull,
422  &clause->ssup);
423 
424  if (result != 0)
425  break;
426  }
427 
428  /*
429  * If we had any NULL-vs-NULL inputs, we do not want to report that the
430  * tuples are equal. Instead, if result is still 0, change it to +1. This
431  * will result in advancing the inner side of the join.
432  *
433  * Likewise, if there was a constant-false joinqual, do not report
434  * equality. We have to check this as part of the mergequals, else the
435  * rescan logic will do the wrong thing.
436  */
437  if (result == 0 &&
438  (nulleqnull || mergestate->mj_ConstFalseJoin))
439  result = 1;
440 
441  MemoryContextSwitchTo(oldContext);
442 
443  return result;
444 }
445 
446 
447 /*
448  * Generate a fake join tuple with nulls for the inner tuple,
449  * and return it if it passes the non-join quals.
450  */
451 static TupleTableSlot *
453 {
454  ExprContext *econtext = node->js.ps.ps_ExprContext;
455  List *otherqual = node->js.ps.qual;
456 
457  ResetExprContext(econtext);
458 
459  econtext->ecxt_outertuple = node->mj_OuterTupleSlot;
460  econtext->ecxt_innertuple = node->mj_NullInnerTupleSlot;
461 
462  if (ExecQual(otherqual, econtext, false))
463  {
464  /*
465  * qualification succeeded. now form the desired projection tuple and
466  * return the slot containing it.
467  */
468  MJ_printf("ExecMergeJoin: returning outer fill tuple\n");
469 
470  return ExecProject(node->js.ps.ps_ProjInfo);
471  }
472  else
473  InstrCountFiltered2(node, 1);
474 
475  return NULL;
476 }
477 
478 /*
479  * Generate a fake join tuple with nulls for the outer tuple,
480  * and return it if it passes the non-join quals.
481  */
482 static TupleTableSlot *
484 {
485  ExprContext *econtext = node->js.ps.ps_ExprContext;
486  List *otherqual = node->js.ps.qual;
487 
488  ResetExprContext(econtext);
489 
490  econtext->ecxt_outertuple = node->mj_NullOuterTupleSlot;
491  econtext->ecxt_innertuple = node->mj_InnerTupleSlot;
492 
493  if (ExecQual(otherqual, econtext, false))
494  {
495  /*
496  * qualification succeeded. now form the desired projection tuple and
497  * return the slot containing it.
498  */
499  MJ_printf("ExecMergeJoin: returning inner fill tuple\n");
500 
501  return ExecProject(node->js.ps.ps_ProjInfo);
502  }
503  else
504  InstrCountFiltered2(node, 1);
505 
506  return NULL;
507 }
508 
509 
510 /*
511  * Check that a qual condition is constant true or constant false.
512  * If it is constant false (or null), set *is_const_false to TRUE.
513  *
514  * Constant true would normally be represented by a NIL list, but we allow an
515  * actual bool Const as well. We do expect that the planner will have thrown
516  * away any non-constant terms that have been ANDed with a constant false.
517  */
518 static bool
519 check_constant_qual(List *qual, bool *is_const_false)
520 {
521  ListCell *lc;
522 
523  foreach(lc, qual)
524  {
525  Const *con = (Const *) lfirst(lc);
526 
527  if (!con || !IsA(con, Const))
528  return false;
529  if (con->constisnull || !DatumGetBool(con->constvalue))
530  *is_const_false = true;
531  }
532  return true;
533 }
534 
535 
536 /* ----------------------------------------------------------------
537  * ExecMergeTupleDump
538  *
539  * This function is called through the MJ_dump() macro
540  * when EXEC_MERGEJOINDEBUG is defined
541  * ----------------------------------------------------------------
542  */
543 #ifdef EXEC_MERGEJOINDEBUG
544 
545 static void
546 ExecMergeTupleDumpOuter(MergeJoinState *mergestate)
547 {
548  TupleTableSlot *outerSlot = mergestate->mj_OuterTupleSlot;
549 
550  printf("==== outer tuple ====\n");
551  if (TupIsNull(outerSlot))
552  printf("(nil)\n");
553  else
554  MJ_debugtup(outerSlot);
555 }
556 
557 static void
558 ExecMergeTupleDumpInner(MergeJoinState *mergestate)
559 {
560  TupleTableSlot *innerSlot = mergestate->mj_InnerTupleSlot;
561 
562  printf("==== inner tuple ====\n");
563  if (TupIsNull(innerSlot))
564  printf("(nil)\n");
565  else
566  MJ_debugtup(innerSlot);
567 }
568 
569 static void
570 ExecMergeTupleDumpMarked(MergeJoinState *mergestate)
571 {
572  TupleTableSlot *markedSlot = mergestate->mj_MarkedTupleSlot;
573 
574  printf("==== marked tuple ====\n");
575  if (TupIsNull(markedSlot))
576  printf("(nil)\n");
577  else
578  MJ_debugtup(markedSlot);
579 }
580 
581 static void
582 ExecMergeTupleDump(MergeJoinState *mergestate)
583 {
584  printf("******** ExecMergeTupleDump ********\n");
585 
586  ExecMergeTupleDumpOuter(mergestate);
587  ExecMergeTupleDumpInner(mergestate);
588  ExecMergeTupleDumpMarked(mergestate);
589 
590  printf("******** \n");
591 }
592 #endif
593 
594 /* ----------------------------------------------------------------
595  * ExecMergeJoin
596  * ----------------------------------------------------------------
597  */
600 {
601  List *joinqual;
602  List *otherqual;
603  bool qualResult;
604  int compareResult;
606  TupleTableSlot *innerTupleSlot;
608  TupleTableSlot *outerTupleSlot;
609  ExprContext *econtext;
610  bool doFillOuter;
611  bool doFillInner;
612 
613  /*
614  * get information from node
615  */
616  innerPlan = innerPlanState(node);
617  outerPlan = outerPlanState(node);
618  econtext = node->js.ps.ps_ExprContext;
619  joinqual = node->js.joinqual;
620  otherqual = node->js.ps.qual;
621  doFillOuter = node->mj_FillOuter;
622  doFillInner = node->mj_FillInner;
623 
624  /*
625  * Reset per-tuple memory context to free any expression evaluation
626  * storage allocated in the previous tuple cycle.
627  */
628  ResetExprContext(econtext);
629 
630  /*
631  * ok, everything is setup.. let's go to work
632  */
633  for (;;)
634  {
635  MJ_dump(node);
636 
637  /*
638  * get the current state of the join and do things accordingly.
639  */
640  switch (node->mj_JoinState)
641  {
642  /*
643  * EXEC_MJ_INITIALIZE_OUTER means that this is the first time
644  * ExecMergeJoin() has been called and so we have to fetch the
645  * first matchable tuple for both outer and inner subplans. We
646  * do the outer side in INITIALIZE_OUTER state, then advance
647  * to INITIALIZE_INNER state for the inner subplan.
648  */
650  MJ_printf("ExecMergeJoin: EXEC_MJ_INITIALIZE_OUTER\n");
651 
652  outerTupleSlot = ExecProcNode(outerPlan);
653  node->mj_OuterTupleSlot = outerTupleSlot;
654 
655  /* Compute join values and check for unmatchability */
656  switch (MJEvalOuterValues(node))
657  {
658  case MJEVAL_MATCHABLE:
659  /* OK to go get the first inner tuple */
661  break;
662  case MJEVAL_NONMATCHABLE:
663  /* Stay in same state to fetch next outer tuple */
664  if (doFillOuter)
665  {
666  /*
667  * Generate a fake join tuple with nulls for the
668  * inner tuple, and return it if it passes the
669  * non-join quals.
670  */
672 
673  result = MJFillOuter(node);
674  if (result)
675  return result;
676  }
677  break;
678  case MJEVAL_ENDOFJOIN:
679  /* No more outer tuples */
680  MJ_printf("ExecMergeJoin: nothing in outer subplan\n");
681  if (doFillInner)
682  {
683  /*
684  * Need to emit right-join tuples for remaining
685  * inner tuples. We set MatchedInner = true to
686  * force the ENDOUTER state to advance inner.
687  */
689  node->mj_MatchedInner = true;
690  break;
691  }
692  /* Otherwise we're done. */
693  return NULL;
694  }
695  break;
696 
698  MJ_printf("ExecMergeJoin: EXEC_MJ_INITIALIZE_INNER\n");
699 
700  innerTupleSlot = ExecProcNode(innerPlan);
701  node->mj_InnerTupleSlot = innerTupleSlot;
702 
703  /* Compute join values and check for unmatchability */
704  switch (MJEvalInnerValues(node, innerTupleSlot))
705  {
706  case MJEVAL_MATCHABLE:
707 
708  /*
709  * OK, we have the initial tuples. Begin by skipping
710  * non-matching tuples.
711  */
713  break;
714  case MJEVAL_NONMATCHABLE:
715  /* Mark before advancing, if wanted */
716  if (node->mj_ExtraMarks)
717  ExecMarkPos(innerPlan);
718  /* Stay in same state to fetch next inner tuple */
719  if (doFillInner)
720  {
721  /*
722  * Generate a fake join tuple with nulls for the
723  * outer tuple, and return it if it passes the
724  * non-join quals.
725  */
727 
728  result = MJFillInner(node);
729  if (result)
730  return result;
731  }
732  break;
733  case MJEVAL_ENDOFJOIN:
734  /* No more inner tuples */
735  MJ_printf("ExecMergeJoin: nothing in inner subplan\n");
736  if (doFillOuter)
737  {
738  /*
739  * Need to emit left-join tuples for all outer
740  * tuples, including the one we just fetched. We
741  * set MatchedOuter = false to force the ENDINNER
742  * state to emit first tuple before advancing
743  * outer.
744  */
746  node->mj_MatchedOuter = false;
747  break;
748  }
749  /* Otherwise we're done. */
750  return NULL;
751  }
752  break;
753 
754  /*
755  * EXEC_MJ_JOINTUPLES means we have two tuples which satisfied
756  * the merge clause so we join them and then proceed to get
757  * the next inner tuple (EXEC_MJ_NEXTINNER).
758  */
759  case EXEC_MJ_JOINTUPLES:
760  MJ_printf("ExecMergeJoin: EXEC_MJ_JOINTUPLES\n");
761 
762  /*
763  * Set the next state machine state. The right things will
764  * happen whether we return this join tuple or just fall
765  * through to continue the state machine execution.
766  */
768 
769  /*
770  * Check the extra qual conditions to see if we actually want
771  * to return this join tuple. If not, can proceed with merge.
772  * We must distinguish the additional joinquals (which must
773  * pass to consider the tuples "matched" for outer-join logic)
774  * from the otherquals (which must pass before we actually
775  * return the tuple).
776  *
777  * We don't bother with a ResetExprContext here, on the
778  * assumption that we just did one while checking the merge
779  * qual. One per tuple should be sufficient. We do have to
780  * set up the econtext links to the tuples for ExecQual to
781  * use.
782  */
783  outerTupleSlot = node->mj_OuterTupleSlot;
784  econtext->ecxt_outertuple = outerTupleSlot;
785  innerTupleSlot = node->mj_InnerTupleSlot;
786  econtext->ecxt_innertuple = innerTupleSlot;
787 
788  qualResult = (joinqual == NIL ||
789  ExecQual(joinqual, econtext, false));
790  MJ_DEBUG_QUAL(joinqual, qualResult);
791 
792  if (qualResult)
793  {
794  node->mj_MatchedOuter = true;
795  node->mj_MatchedInner = true;
796 
797  /* In an antijoin, we never return a matched tuple */
798  if (node->js.jointype == JOIN_ANTI)
799  {
801  break;
802  }
803 
804  /*
805  * In a semijoin, we'll consider returning the first
806  * match, but after that we're done with this outer tuple.
807  */
808  if (node->js.jointype == JOIN_SEMI)
810 
811  qualResult = (otherqual == NIL ||
812  ExecQual(otherqual, econtext, false));
813  MJ_DEBUG_QUAL(otherqual, qualResult);
814 
815  if (qualResult)
816  {
817  /*
818  * qualification succeeded. now form the desired
819  * projection tuple and return the slot containing it.
820  */
821  MJ_printf("ExecMergeJoin: returning tuple\n");
822 
823  return ExecProject(node->js.ps.ps_ProjInfo);
824  }
825  else
826  InstrCountFiltered2(node, 1);
827  }
828  else
829  InstrCountFiltered1(node, 1);
830  break;
831 
832  /*
833  * EXEC_MJ_NEXTINNER means advance the inner scan to the next
834  * tuple. If the tuple is not nil, we then proceed to test it
835  * against the join qualification.
836  *
837  * Before advancing, we check to see if we must emit an
838  * outer-join fill tuple for this inner tuple.
839  */
840  case EXEC_MJ_NEXTINNER:
841  MJ_printf("ExecMergeJoin: EXEC_MJ_NEXTINNER\n");
842 
843  if (doFillInner && !node->mj_MatchedInner)
844  {
845  /*
846  * Generate a fake join tuple with nulls for the outer
847  * tuple, and return it if it passes the non-join quals.
848  */
850 
851  node->mj_MatchedInner = true; /* do it only once */
852 
853  result = MJFillInner(node);
854  if (result)
855  return result;
856  }
857 
858  /*
859  * now we get the next inner tuple, if any. If there's none,
860  * advance to next outer tuple (which may be able to join to
861  * previously marked tuples).
862  *
863  * NB: must NOT do "extraMarks" here, since we may need to
864  * return to previously marked tuples.
865  */
866  innerTupleSlot = ExecProcNode(innerPlan);
867  node->mj_InnerTupleSlot = innerTupleSlot;
868  MJ_DEBUG_PROC_NODE(innerTupleSlot);
869  node->mj_MatchedInner = false;
870 
871  /* Compute join values and check for unmatchability */
872  switch (MJEvalInnerValues(node, innerTupleSlot))
873  {
874  case MJEVAL_MATCHABLE:
875 
876  /*
877  * Test the new inner tuple to see if it matches
878  * outer.
879  *
880  * If they do match, then we join them and move on to
881  * the next inner tuple (EXEC_MJ_JOINTUPLES).
882  *
883  * If they do not match then advance to next outer
884  * tuple.
885  */
886  compareResult = MJCompare(node);
887  MJ_DEBUG_COMPARE(compareResult);
888 
889  if (compareResult == 0)
891  else
892  {
893  Assert(compareResult < 0);
895  }
896  break;
897  case MJEVAL_NONMATCHABLE:
898 
899  /*
900  * It contains a NULL and hence can't match any outer
901  * tuple, so we can skip the comparison and assume the
902  * new tuple is greater than current outer.
903  */
905  break;
906  case MJEVAL_ENDOFJOIN:
907 
908  /*
909  * No more inner tuples. However, this might be only
910  * effective and not physical end of inner plan, so
911  * force mj_InnerTupleSlot to null to make sure we
912  * don't fetch more inner tuples. (We need this hack
913  * because we are not transiting to a state where the
914  * inner plan is assumed to be exhausted.)
915  */
916  node->mj_InnerTupleSlot = NULL;
918  break;
919  }
920  break;
921 
922  /*-------------------------------------------
923  * EXEC_MJ_NEXTOUTER means
924  *
925  * outer inner
926  * outer tuple - 5 5 - marked tuple
927  * 5 5
928  * 6 6 - inner tuple
929  * 7 7
930  *
931  * we know we just bumped into the
932  * first inner tuple > current outer tuple (or possibly
933  * the end of the inner stream)
934  * so get a new outer tuple and then
935  * proceed to test it against the marked tuple
936  * (EXEC_MJ_TESTOUTER)
937  *
938  * Before advancing, we check to see if we must emit an
939  * outer-join fill tuple for this outer tuple.
940  *------------------------------------------------
941  */
942  case EXEC_MJ_NEXTOUTER:
943  MJ_printf("ExecMergeJoin: EXEC_MJ_NEXTOUTER\n");
944 
945  if (doFillOuter && !node->mj_MatchedOuter)
946  {
947  /*
948  * Generate a fake join tuple with nulls for the inner
949  * tuple, and return it if it passes the non-join quals.
950  */
952 
953  node->mj_MatchedOuter = true; /* do it only once */
954 
955  result = MJFillOuter(node);
956  if (result)
957  return result;
958  }
959 
960  /*
961  * now we get the next outer tuple, if any
962  */
963  outerTupleSlot = ExecProcNode(outerPlan);
964  node->mj_OuterTupleSlot = outerTupleSlot;
965  MJ_DEBUG_PROC_NODE(outerTupleSlot);
966  node->mj_MatchedOuter = false;
967 
968  /* Compute join values and check for unmatchability */
969  switch (MJEvalOuterValues(node))
970  {
971  case MJEVAL_MATCHABLE:
972  /* Go test the new tuple against the marked tuple */
974  break;
975  case MJEVAL_NONMATCHABLE:
976  /* Can't match, so fetch next outer tuple */
978  break;
979  case MJEVAL_ENDOFJOIN:
980  /* No more outer tuples */
981  MJ_printf("ExecMergeJoin: end of outer subplan\n");
982  innerTupleSlot = node->mj_InnerTupleSlot;
983  if (doFillInner && !TupIsNull(innerTupleSlot))
984  {
985  /*
986  * Need to emit right-join tuples for remaining
987  * inner tuples.
988  */
990  break;
991  }
992  /* Otherwise we're done. */
993  return NULL;
994  }
995  break;
996 
997  /*--------------------------------------------------------
998  * EXEC_MJ_TESTOUTER If the new outer tuple and the marked
999  * tuple satisfy the merge clause then we know we have
1000  * duplicates in the outer scan so we have to restore the
1001  * inner scan to the marked tuple and proceed to join the
1002  * new outer tuple with the inner tuples.
1003  *
1004  * This is the case when
1005  * outer inner
1006  * 4 5 - marked tuple
1007  * outer tuple - 5 5
1008  * new outer tuple - 5 5
1009  * 6 8 - inner tuple
1010  * 7 12
1011  *
1012  * new outer tuple == marked tuple
1013  *
1014  * If the outer tuple fails the test, then we are done
1015  * with the marked tuples, and we have to look for a
1016  * match to the current inner tuple. So we will
1017  * proceed to skip outer tuples until outer >= inner
1018  * (EXEC_MJ_SKIP_TEST).
1019  *
1020  * This is the case when
1021  *
1022  * outer inner
1023  * 5 5 - marked tuple
1024  * outer tuple - 5 5
1025  * new outer tuple - 6 8 - inner tuple
1026  * 7 12
1027  *
1028  * new outer tuple > marked tuple
1029  *
1030  *---------------------------------------------------------
1031  */
1032  case EXEC_MJ_TESTOUTER:
1033  MJ_printf("ExecMergeJoin: EXEC_MJ_TESTOUTER\n");
1034 
1035  /*
1036  * Here we must compare the outer tuple with the marked inner
1037  * tuple. (We can ignore the result of MJEvalInnerValues,
1038  * since the marked inner tuple is certainly matchable.)
1039  */
1040  innerTupleSlot = node->mj_MarkedTupleSlot;
1041  (void) MJEvalInnerValues(node, innerTupleSlot);
1042 
1043  compareResult = MJCompare(node);
1044  MJ_DEBUG_COMPARE(compareResult);
1045 
1046  if (compareResult == 0)
1047  {
1048  /*
1049  * the merge clause matched so now we restore the inner
1050  * scan position to the first mark, and go join that tuple
1051  * (and any following ones) to the new outer.
1052  *
1053  * NOTE: we do not need to worry about the MatchedInner
1054  * state for the rescanned inner tuples. We know all of
1055  * them will match this new outer tuple and therefore
1056  * won't be emitted as fill tuples. This works *only*
1057  * because we require the extra joinquals to be constant
1058  * when doing a right or full join --- otherwise some of
1059  * the rescanned tuples might fail the extra joinquals.
1060  * This obviously won't happen for a constant-true extra
1061  * joinqual, while the constant-false case is handled by
1062  * forcing the merge clause to never match, so we never
1063  * get here.
1064  */
1065  ExecRestrPos(innerPlan);
1066 
1067  /*
1068  * ExecRestrPos probably should give us back a new Slot,
1069  * but since it doesn't, use the marked slot. (The
1070  * previously returned mj_InnerTupleSlot cannot be assumed
1071  * to hold the required tuple.)
1072  */
1073  node->mj_InnerTupleSlot = innerTupleSlot;
1074  /* we need not do MJEvalInnerValues again */
1075 
1077  }
1078  else
1079  {
1080  /* ----------------
1081  * if the new outer tuple didn't match the marked inner
1082  * tuple then we have a case like:
1083  *
1084  * outer inner
1085  * 4 4 - marked tuple
1086  * new outer - 5 4
1087  * 6 5 - inner tuple
1088  * 7
1089  *
1090  * which means that all subsequent outer tuples will be
1091  * larger than our marked inner tuples. So we need not
1092  * revisit any of the marked tuples but can proceed to
1093  * look for a match to the current inner. If there's
1094  * no more inners, no more matches are possible.
1095  * ----------------
1096  */
1097  Assert(compareResult > 0);
1098  innerTupleSlot = node->mj_InnerTupleSlot;
1099 
1100  /* reload comparison data for current inner */
1101  switch (MJEvalInnerValues(node, innerTupleSlot))
1102  {
1103  case MJEVAL_MATCHABLE:
1104  /* proceed to compare it to the current outer */
1106  break;
1107  case MJEVAL_NONMATCHABLE:
1108 
1109  /*
1110  * current inner can't possibly match any outer;
1111  * better to advance the inner scan than the
1112  * outer.
1113  */
1115  break;
1116  case MJEVAL_ENDOFJOIN:
1117  /* No more inner tuples */
1118  if (doFillOuter)
1119  {
1120  /*
1121  * Need to emit left-join tuples for remaining
1122  * outer tuples.
1123  */
1125  break;
1126  }
1127  /* Otherwise we're done. */
1128  return NULL;
1129  }
1130  }
1131  break;
1132 
1133  /*----------------------------------------------------------
1134  * EXEC_MJ_SKIP means compare tuples and if they do not
1135  * match, skip whichever is lesser.
1136  *
1137  * For example:
1138  *
1139  * outer inner
1140  * 5 5
1141  * 5 5
1142  * outer tuple - 6 8 - inner tuple
1143  * 7 12
1144  * 8 14
1145  *
1146  * we have to advance the outer scan
1147  * until we find the outer 8.
1148  *
1149  * On the other hand:
1150  *
1151  * outer inner
1152  * 5 5
1153  * 5 5
1154  * outer tuple - 12 8 - inner tuple
1155  * 14 10
1156  * 17 12
1157  *
1158  * we have to advance the inner scan
1159  * until we find the inner 12.
1160  *----------------------------------------------------------
1161  */
1162  case EXEC_MJ_SKIP_TEST:
1163  MJ_printf("ExecMergeJoin: EXEC_MJ_SKIP_TEST\n");
1164 
1165  /*
1166  * before we advance, make sure the current tuples do not
1167  * satisfy the mergeclauses. If they do, then we update the
1168  * marked tuple position and go join them.
1169  */
1170  compareResult = MJCompare(node);
1171  MJ_DEBUG_COMPARE(compareResult);
1172 
1173  if (compareResult == 0)
1174  {
1175  ExecMarkPos(innerPlan);
1176 
1177  MarkInnerTuple(node->mj_InnerTupleSlot, node);
1178 
1180  }
1181  else if (compareResult < 0)
1183  else
1184  /* compareResult > 0 */
1186  break;
1187 
1188  /*
1189  * SKIPOUTER_ADVANCE: advance over an outer tuple that is
1190  * known not to join to any inner tuple.
1191  *
1192  * Before advancing, we check to see if we must emit an
1193  * outer-join fill tuple for this outer tuple.
1194  */
1196  MJ_printf("ExecMergeJoin: EXEC_MJ_SKIPOUTER_ADVANCE\n");
1197 
1198  if (doFillOuter && !node->mj_MatchedOuter)
1199  {
1200  /*
1201  * Generate a fake join tuple with nulls for the inner
1202  * tuple, and return it if it passes the non-join quals.
1203  */
1205 
1206  node->mj_MatchedOuter = true; /* do it only once */
1207 
1208  result = MJFillOuter(node);
1209  if (result)
1210  return result;
1211  }
1212 
1213  /*
1214  * now we get the next outer tuple, if any
1215  */
1216  outerTupleSlot = ExecProcNode(outerPlan);
1217  node->mj_OuterTupleSlot = outerTupleSlot;
1218  MJ_DEBUG_PROC_NODE(outerTupleSlot);
1219  node->mj_MatchedOuter = false;
1220 
1221  /* Compute join values and check for unmatchability */
1222  switch (MJEvalOuterValues(node))
1223  {
1224  case MJEVAL_MATCHABLE:
1225  /* Go test the new tuple against the current inner */
1227  break;
1228  case MJEVAL_NONMATCHABLE:
1229  /* Can't match, so fetch next outer tuple */
1231  break;
1232  case MJEVAL_ENDOFJOIN:
1233  /* No more outer tuples */
1234  MJ_printf("ExecMergeJoin: end of outer subplan\n");
1235  innerTupleSlot = node->mj_InnerTupleSlot;
1236  if (doFillInner && !TupIsNull(innerTupleSlot))
1237  {
1238  /*
1239  * Need to emit right-join tuples for remaining
1240  * inner tuples.
1241  */
1243  break;
1244  }
1245  /* Otherwise we're done. */
1246  return NULL;
1247  }
1248  break;
1249 
1250  /*
1251  * SKIPINNER_ADVANCE: advance over an inner tuple that is
1252  * known not to join to any outer tuple.
1253  *
1254  * Before advancing, we check to see if we must emit an
1255  * outer-join fill tuple for this inner tuple.
1256  */
1258  MJ_printf("ExecMergeJoin: EXEC_MJ_SKIPINNER_ADVANCE\n");
1259 
1260  if (doFillInner && !node->mj_MatchedInner)
1261  {
1262  /*
1263  * Generate a fake join tuple with nulls for the outer
1264  * tuple, and return it if it passes the non-join quals.
1265  */
1267 
1268  node->mj_MatchedInner = true; /* do it only once */
1269 
1270  result = MJFillInner(node);
1271  if (result)
1272  return result;
1273  }
1274 
1275  /* Mark before advancing, if wanted */
1276  if (node->mj_ExtraMarks)
1277  ExecMarkPos(innerPlan);
1278 
1279  /*
1280  * now we get the next inner tuple, if any
1281  */
1282  innerTupleSlot = ExecProcNode(innerPlan);
1283  node->mj_InnerTupleSlot = innerTupleSlot;
1284  MJ_DEBUG_PROC_NODE(innerTupleSlot);
1285  node->mj_MatchedInner = false;
1286 
1287  /* Compute join values and check for unmatchability */
1288  switch (MJEvalInnerValues(node, innerTupleSlot))
1289  {
1290  case MJEVAL_MATCHABLE:
1291  /* proceed to compare it to the current outer */
1293  break;
1294  case MJEVAL_NONMATCHABLE:
1295 
1296  /*
1297  * current inner can't possibly match any outer;
1298  * better to advance the inner scan than the outer.
1299  */
1301  break;
1302  case MJEVAL_ENDOFJOIN:
1303  /* No more inner tuples */
1304  MJ_printf("ExecMergeJoin: end of inner subplan\n");
1305  outerTupleSlot = node->mj_OuterTupleSlot;
1306  if (doFillOuter && !TupIsNull(outerTupleSlot))
1307  {
1308  /*
1309  * Need to emit left-join tuples for remaining
1310  * outer tuples.
1311  */
1313  break;
1314  }
1315  /* Otherwise we're done. */
1316  return NULL;
1317  }
1318  break;
1319 
1320  /*
1321  * EXEC_MJ_ENDOUTER means we have run out of outer tuples, but
1322  * are doing a right/full join and therefore must null-fill
1323  * any remaining unmatched inner tuples.
1324  */
1325  case EXEC_MJ_ENDOUTER:
1326  MJ_printf("ExecMergeJoin: EXEC_MJ_ENDOUTER\n");
1327 
1328  Assert(doFillInner);
1329 
1330  if (!node->mj_MatchedInner)
1331  {
1332  /*
1333  * Generate a fake join tuple with nulls for the outer
1334  * tuple, and return it if it passes the non-join quals.
1335  */
1337 
1338  node->mj_MatchedInner = true; /* do it only once */
1339 
1340  result = MJFillInner(node);
1341  if (result)
1342  return result;
1343  }
1344 
1345  /* Mark before advancing, if wanted */
1346  if (node->mj_ExtraMarks)
1347  ExecMarkPos(innerPlan);
1348 
1349  /*
1350  * now we get the next inner tuple, if any
1351  */
1352  innerTupleSlot = ExecProcNode(innerPlan);
1353  node->mj_InnerTupleSlot = innerTupleSlot;
1354  MJ_DEBUG_PROC_NODE(innerTupleSlot);
1355  node->mj_MatchedInner = false;
1356 
1357  if (TupIsNull(innerTupleSlot))
1358  {
1359  MJ_printf("ExecMergeJoin: end of inner subplan\n");
1360  return NULL;
1361  }
1362 
1363  /* Else remain in ENDOUTER state and process next tuple. */
1364  break;
1365 
1366  /*
1367  * EXEC_MJ_ENDINNER means we have run out of inner tuples, but
1368  * are doing a left/full join and therefore must null- fill
1369  * any remaining unmatched outer tuples.
1370  */
1371  case EXEC_MJ_ENDINNER:
1372  MJ_printf("ExecMergeJoin: EXEC_MJ_ENDINNER\n");
1373 
1374  Assert(doFillOuter);
1375 
1376  if (!node->mj_MatchedOuter)
1377  {
1378  /*
1379  * Generate a fake join tuple with nulls for the inner
1380  * tuple, and return it if it passes the non-join quals.
1381  */
1383 
1384  node->mj_MatchedOuter = true; /* do it only once */
1385 
1386  result = MJFillOuter(node);
1387  if (result)
1388  return result;
1389  }
1390 
1391  /*
1392  * now we get the next outer tuple, if any
1393  */
1394  outerTupleSlot = ExecProcNode(outerPlan);
1395  node->mj_OuterTupleSlot = outerTupleSlot;
1396  MJ_DEBUG_PROC_NODE(outerTupleSlot);
1397  node->mj_MatchedOuter = false;
1398 
1399  if (TupIsNull(outerTupleSlot))
1400  {
1401  MJ_printf("ExecMergeJoin: end of outer subplan\n");
1402  return NULL;
1403  }
1404 
1405  /* Else remain in ENDINNER state and process next tuple. */
1406  break;
1407 
1408  /*
1409  * broken state value?
1410  */
1411  default:
1412  elog(ERROR, "unrecognized mergejoin state: %d",
1413  (int) node->mj_JoinState);
1414  }
1415  }
1416 }
1417 
1418 /* ----------------------------------------------------------------
1419  * ExecInitMergeJoin
1420  * ----------------------------------------------------------------
1421  */
1423 ExecInitMergeJoin(MergeJoin *node, EState *estate, int eflags)
1424 {
1425  MergeJoinState *mergestate;
1426 
1427  /* check for unsupported flags */
1428  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
1429 
1430  MJ1_printf("ExecInitMergeJoin: %s\n",
1431  "initializing node");
1432 
1433  /*
1434  * create state structure
1435  */
1436  mergestate = makeNode(MergeJoinState);
1437  mergestate->js.ps.plan = (Plan *) node;
1438  mergestate->js.ps.state = estate;
1439 
1440  /*
1441  * Miscellaneous initialization
1442  *
1443  * create expression context for node
1444  */
1445  ExecAssignExprContext(estate, &mergestate->js.ps);
1446 
1447  /*
1448  * we need two additional econtexts in which we can compute the join
1449  * expressions from the left and right input tuples. The node's regular
1450  * econtext won't do because it gets reset too often.
1451  */
1452  mergestate->mj_OuterEContext = CreateExprContext(estate);
1453  mergestate->mj_InnerEContext = CreateExprContext(estate);
1454 
1455  /*
1456  * initialize child expressions
1457  */
1458  mergestate->js.ps.targetlist = (List *)
1459  ExecInitExpr((Expr *) node->join.plan.targetlist,
1460  (PlanState *) mergestate);
1461  mergestate->js.ps.qual = (List *)
1462  ExecInitExpr((Expr *) node->join.plan.qual,
1463  (PlanState *) mergestate);
1464  mergestate->js.jointype = node->join.jointype;
1465  mergestate->js.joinqual = (List *)
1466  ExecInitExpr((Expr *) node->join.joinqual,
1467  (PlanState *) mergestate);
1468  mergestate->mj_ConstFalseJoin = false;
1469  /* mergeclauses are handled below */
1470 
1471  /*
1472  * initialize child nodes
1473  *
1474  * inner child must support MARK/RESTORE.
1475  */
1476  outerPlanState(mergestate) = ExecInitNode(outerPlan(node), estate, eflags);
1477  innerPlanState(mergestate) = ExecInitNode(innerPlan(node), estate,
1478  eflags | EXEC_FLAG_MARK);
1479 
1480  /*
1481  * For certain types of inner child nodes, it is advantageous to issue
1482  * MARK every time we advance past an inner tuple we will never return to.
1483  * For other types, MARK on a tuple we cannot return to is a waste of
1484  * cycles. Detect which case applies and set mj_ExtraMarks if we want to
1485  * issue "unnecessary" MARK calls.
1486  *
1487  * Currently, only Material wants the extra MARKs, and it will be helpful
1488  * only if eflags doesn't specify REWIND.
1489  */
1490  if (IsA(innerPlan(node), Material) &&
1491  (eflags & EXEC_FLAG_REWIND) == 0)
1492  mergestate->mj_ExtraMarks = true;
1493  else
1494  mergestate->mj_ExtraMarks = false;
1495 
1496  /*
1497  * tuple table initialization
1498  */
1499  ExecInitResultTupleSlot(estate, &mergestate->js.ps);
1500 
1501  mergestate->mj_MarkedTupleSlot = ExecInitExtraTupleSlot(estate);
1503  ExecGetResultType(innerPlanState(mergestate)));
1504 
1505  switch (node->join.jointype)
1506  {
1507  case JOIN_INNER:
1508  case JOIN_SEMI:
1509  mergestate->mj_FillOuter = false;
1510  mergestate->mj_FillInner = false;
1511  break;
1512  case JOIN_LEFT:
1513  case JOIN_ANTI:
1514  mergestate->mj_FillOuter = true;
1515  mergestate->mj_FillInner = false;
1516  mergestate->mj_NullInnerTupleSlot =
1517  ExecInitNullTupleSlot(estate,
1518  ExecGetResultType(innerPlanState(mergestate)));
1519  break;
1520  case JOIN_RIGHT:
1521  mergestate->mj_FillOuter = false;
1522  mergestate->mj_FillInner = true;
1523  mergestate->mj_NullOuterTupleSlot =
1524  ExecInitNullTupleSlot(estate,
1525  ExecGetResultType(outerPlanState(mergestate)));
1526 
1527  /*
1528  * Can't handle right or full join with non-constant extra
1529  * joinclauses. This should have been caught by planner.
1530  */
1531  if (!check_constant_qual(node->join.joinqual,
1532  &mergestate->mj_ConstFalseJoin))
1533  ereport(ERROR,
1534  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1535  errmsg("RIGHT JOIN is only supported with merge-joinable join conditions")));
1536  break;
1537  case JOIN_FULL:
1538  mergestate->mj_FillOuter = true;
1539  mergestate->mj_FillInner = true;
1540  mergestate->mj_NullOuterTupleSlot =
1541  ExecInitNullTupleSlot(estate,
1542  ExecGetResultType(outerPlanState(mergestate)));
1543  mergestate->mj_NullInnerTupleSlot =
1544  ExecInitNullTupleSlot(estate,
1545  ExecGetResultType(innerPlanState(mergestate)));
1546 
1547  /*
1548  * Can't handle right or full join with non-constant extra
1549  * joinclauses. This should have been caught by planner.
1550  */
1551  if (!check_constant_qual(node->join.joinqual,
1552  &mergestate->mj_ConstFalseJoin))
1553  ereport(ERROR,
1554  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1555  errmsg("FULL JOIN is only supported with merge-joinable join conditions")));
1556  break;
1557  default:
1558  elog(ERROR, "unrecognized join type: %d",
1559  (int) node->join.jointype);
1560  }
1561 
1562  /*
1563  * initialize tuple type and projection info
1564  */
1565  ExecAssignResultTypeFromTL(&mergestate->js.ps);
1566  ExecAssignProjectionInfo(&mergestate->js.ps, NULL);
1567 
1568  /*
1569  * preprocess the merge clauses
1570  */
1571  mergestate->mj_NumClauses = list_length(node->mergeclauses);
1572  mergestate->mj_Clauses = MJExamineQuals(node->mergeclauses,
1573  node->mergeFamilies,
1574  node->mergeCollations,
1575  node->mergeStrategies,
1576  node->mergeNullsFirst,
1577  (PlanState *) mergestate);
1578 
1579  /*
1580  * initialize join state
1581  */
1582  mergestate->mj_JoinState = EXEC_MJ_INITIALIZE_OUTER;
1583  mergestate->mj_MatchedOuter = false;
1584  mergestate->mj_MatchedInner = false;
1585  mergestate->mj_OuterTupleSlot = NULL;
1586  mergestate->mj_InnerTupleSlot = NULL;
1587 
1588  /*
1589  * initialization successful
1590  */
1591  MJ1_printf("ExecInitMergeJoin: %s\n",
1592  "node initialized");
1593 
1594  return mergestate;
1595 }
1596 
1597 /* ----------------------------------------------------------------
1598  * ExecEndMergeJoin
1599  *
1600  * old comments
1601  * frees storage allocated through C routines.
1602  * ----------------------------------------------------------------
1603  */
1604 void
1606 {
1607  MJ1_printf("ExecEndMergeJoin: %s\n",
1608  "ending node processing");
1609 
1610  /*
1611  * Free the exprcontext
1612  */
1613  ExecFreeExprContext(&node->js.ps);
1614 
1615  /*
1616  * clean out the tuple table
1617  */
1620 
1621  /*
1622  * shut down the subplans
1623  */
1624  ExecEndNode(innerPlanState(node));
1625  ExecEndNode(outerPlanState(node));
1626 
1627  MJ1_printf("ExecEndMergeJoin: %s\n",
1628  "node processing ended");
1629 }
1630 
1631 void
1633 {
1635 
1637  node->mj_MatchedOuter = false;
1638  node->mj_MatchedInner = false;
1639  node->mj_OuterTupleSlot = NULL;
1640  node->mj_InnerTupleSlot = NULL;
1641 
1642  /*
1643  * if chgParam of subnodes is not null then plans will be re-scanned by
1644  * first ExecProcNode.
1645  */
1646  if (node->js.ps.lefttree->chgParam == NULL)
1647  ExecReScan(node->js.ps.lefttree);
1648  if (node->js.ps.righttree->chgParam == NULL)
1649  ExecReScan(node->js.ps.righttree);
1650 
1651 }
Datum constvalue
Definition: primnodes.h:196
#define EXEC_MJ_NEXTOUTER
JoinType jointype
Definition: execnodes.h:1761
MergeJoinState * ExecInitMergeJoin(MergeJoin *node, EState *estate, int eflags)
int(* comparator)(Datum x, Datum y, SortSupport ssup)
Definition: sortsupport.h:107
bool ssup_nulls_first
Definition: sortsupport.h:75
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:133
SortSupportData ssup
TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: execQual.c:5215
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:392
#define IsA(nodeptr, _type_)
Definition: nodes.h:573
#define EXEC_MJ_SKIPOUTER_ADVANCE
#define BTORDER_PROC
Definition: nbtree.h:229
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
#define MJ1_printf(s, p)
Definition: execdebug.h:140
#define BTGreaterStrategyNumber
Definition: stratnum.h:33
ProjectionInfo * ps_ProjInfo
Definition: execnodes.h:1081
ExprContext * mj_InnerEContext
Definition: execnodes.h:1823
#define EXEC_MJ_TESTOUTER
bool mj_ConstFalseJoin
Definition: execnodes.h:1812
#define MJ_DEBUG_COMPARE(res)
Definition: execdebug.h:144
#define BTSORTSUPPORT_PROC
Definition: nbtree.h:230
#define MJ_dump(state)
Definition: execdebug.h:143
PlanState ps
Definition: execnodes.h:1760
void ExecEndNode(PlanState *node)
Definition: execProcnode.c:644
static MJEvalResult MJEvalInnerValues(MergeJoinState *mergestate, TupleTableSlot *innerslot)
void PrepareSortSupportComparisonShim(Oid cmpFunc, SortSupport ssup)
Definition: sortsupport.c:67
#define PointerGetDatum(X)
Definition: postgres.h:562
static int MJCompare(MergeJoinState *mergestate)
ExprContext * ps_ExprContext
Definition: execnodes.h:1080
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:136
MJEvalResult
void ExecReScan(PlanState *node)
Definition: execAmi.c:74
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
#define EXEC_MJ_ENDOUTER
TupleTableSlot * mj_MarkedTupleSlot
Definition: execnodes.h:1819
#define MJ_printf(s)
Definition: execdebug.h:139
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * qual
Definition: execnodes.h:1064
uint16 StrategyNumber
Definition: stratnum.h:22
TupleTableSlot * mj_NullInnerTupleSlot
Definition: execnodes.h:1821
int errcode(int sqlerrcode)
Definition: elog.c:575
#define EXEC_MJ_INITIALIZE_INNER
#define EXEC_MJ_SKIP_TEST
List * targetlist
Definition: execnodes.h:1063
return result
Definition: formatting.c:1618
EState * state
Definition: execnodes.h:1051
List * joinqual
Definition: execnodes.h:1762
struct PlanState * righttree
Definition: execnodes.h:1066
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
void ExecFreeExprContext(PlanState *planstate)
Definition: execUtils.c:686
#define lsecond(l)
Definition: pg_list.h:114
void ExecAssignResultTypeFromTL(PlanState *planstate)
Definition: execUtils.c:431
static TupleTableSlot * MJFillInner(MergeJoinState *node)
struct PlanState * lefttree
Definition: execnodes.h:1065
List * mergeclauses
Definition: plannodes.h:682
static MJEvalResult MJEvalOuterValues(MergeJoinState *mergestate)
JoinType jointype
Definition: plannodes.h:640
void ExecRestrPos(PlanState *node)
Definition: execAmi.c:353
TupleTableSlot * ps_ResultTupleSlot
Definition: execnodes.h:1079
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execQual.c:4267
bool mj_MatchedOuter
Definition: execnodes.h:1815
TupleTableSlot * ExecInitNullTupleSlot(EState *estate, TupleDesc tupType)
Definition: execTuples.c:866
#define linitial(l)
Definition: pg_list.h:110
static MergeJoinClause MJExamineQuals(List *mergeclauses, Oid *mergefamilies, Oid *mergecollations, int *mergestrategies, bool *mergenullsfirst, PlanState *parent)
#define ExecEvalExpr(expr, econtext, isNull)
Definition: executor.h:73
#define ERROR
Definition: elog.h:43
#define EXEC_MJ_NEXTINNER
void ExecInitResultTupleSlot(EState *estate, PlanState *planstate)
Definition: execTuples.c:832
MemoryContext ssup_cxt
Definition: sortsupport.h:66
bool mj_MatchedInner
Definition: execnodes.h:1816
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:614
#define MarkInnerTuple(innerTupleSlot, mergestate)
#define EXEC_FLAG_BACKWARD
Definition: executor.h:60
#define outerPlanState(node)
Definition: execnodes.h:1092
#define innerPlan(node)
Definition: plannodes.h:161
struct MergeJoinClauseData * MergeJoinClause
Definition: execnodes.h:1803
void ExecAssignProjectionInfo(PlanState *planstate, TupleDesc inputDesc)
Definition: execUtils.c:658
#define DatumGetBool(X)
Definition: postgres.h:399
TupleTableSlot * ecxt_innertuple
Definition: execnodes.h:131
void ExecEndMergeJoin(MergeJoinState *node)
bool ExecQual(List *qual, ExprContext *econtext, bool resultForNull)
Definition: execQual.c:5056
#define TupIsNull(slot)
Definition: tuptable.h:138
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
MergeJoinClause mj_Clauses
Definition: execnodes.h:1809
#define InstrCountFiltered1(node, delta)
Definition: execnodes.h:1095
#define EXEC_FLAG_REWIND
Definition: executor.h:59
#define ereport(elevel, rest)
Definition: elog.h:122
#define EXEC_MJ_INITIALIZE_OUTER
Bitmapset * chgParam
Definition: execnodes.h:1074
#define outerPlan(node)
Definition: plannodes.h:162
static bool check_constant_qual(List *qual, bool *is_const_false)
#define EXEC_MJ_JOINTUPLES
#define EXEC_MJ_ENDINNER
void * palloc0(Size size)
Definition: mcxt.c:878
#define MJ_DEBUG_PROC_NODE(slot)
Definition: execdebug.h:146
uintptr_t Datum
Definition: postgres.h:372
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
Oid * mergeFamilies
Definition: plannodes.h:684
Oid * mergeCollations
Definition: plannodes.h:685
struct MergeJoinClauseData MergeJoinClauseData
Plan * plan
Definition: execnodes.h:1049
void ExecMarkPos(PlanState *node)
Definition: execAmi.c:304
JoinState js
Definition: execnodes.h:1807
bool * mergeNullsFirst
Definition: plannodes.h:687
#define makeNode(_type_)
Definition: nodes.h:570
TupleTableSlot * ecxt_outertuple
Definition: execnodes.h:132
#define NULL
Definition: c.h:229
int * mergeStrategies
Definition: plannodes.h:686
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
#define EXEC_FLAG_MARK
Definition: executor.h:61
TupleTableSlot * mj_InnerTupleSlot
Definition: execnodes.h:1818
#define MJ_debugtup(slot)
Definition: execdebug.h:142
Oid get_opfamily_proc(Oid opfamily, Oid lefttype, Oid righttype, int16 procnum)
Definition: lsyscache.c:744
TupleTableSlot * ExecMergeJoin(MergeJoinState *node)
#define InstrCountFiltered2(node, delta)
Definition: execnodes.h:1100
void ExecAssignExprContext(EState *estate, PlanState *planstate)
Definition: execUtils.c:409
ExprContext * mj_OuterEContext
Definition: execnodes.h:1822
static int list_length(const List *l)
Definition: pg_list.h:89
#define MJ_DEBUG_QUAL(clause, res)
Definition: execdebug.h:145
TupleTableSlot * mj_NullOuterTupleSlot
Definition: execnodes.h:1820
TupleDesc ExecGetResultType(PlanState *planstate)
Definition: execUtils.c:460
List * targetlist
Definition: plannodes.h:132
#define EXEC_MJ_SKIPINNER_ADVANCE
void get_op_opfamily_properties(Oid opno, Oid opfamily, bool ordering_op, int *strategy, Oid *lefttype, Oid *righttype)
Definition: lsyscache.c:133
int errmsg(const char *fmt,...)
Definition: elog.c:797
Join join
Definition: plannodes.h:681
int i
ExprContext * CreateExprContext(EState *estate)
Definition: execUtils.c:209
Oid opno
Definition: primnodes.h:495
#define elog
Definition: elog.h:219
bool mj_ExtraMarks
Definition: execnodes.h:1811
List * args
Definition: primnodes.h:501
#define innerPlanState(node)
Definition: execnodes.h:1091
#define BTLessStrategyNumber
Definition: stratnum.h:29
static int ApplySortComparator(Datum datum1, bool isNull1, Datum datum2, bool isNull2, SortSupport ssup)
Definition: sortsupport.h:201
PlanState * ExecInitNode(Plan *node, EState *estate, int eflags)
Definition: execProcnode.c:139
Definition: pg_list.h:45
void ExecReScanMergeJoin(MergeJoinState *node)
static TupleTableSlot * MJFillOuter(MergeJoinState *node)
List * joinqual
Definition: plannodes.h:641
bool constisnull
Definition: primnodes.h:197
#define BTEqualStrategyNumber
Definition: stratnum.h:31
#define ResetExprContext(econtext)
Definition: executor.h:333
TupleTableSlot * mj_OuterTupleSlot
Definition: execnodes.h:1817
Plan plan
Definition: plannodes.h:639