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