Coverage Report

Created: 2026-12-01 07:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/postgres/src/backend/executor/nodeMergejoin.c
Line
Count
Source
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
0
#define EXEC_MJ_INITIALIZE_OUTER    1
108
0
#define EXEC_MJ_INITIALIZE_INNER    2
109
0
#define EXEC_MJ_JOINTUPLES        3
110
0
#define EXEC_MJ_NEXTOUTER       4
111
0
#define EXEC_MJ_TESTOUTER       5
112
0
#define EXEC_MJ_NEXTINNER       6
113
0
#define EXEC_MJ_SKIP_TEST       7
114
0
#define EXEC_MJ_SKIPOUTER_ADVANCE   8
115
0
#define EXEC_MJ_SKIPINNER_ADVANCE   9
116
0
#define EXEC_MJ_ENDOUTER        10
117
0
#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
0
  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
MJExamineQuals(List *mergeclauses,
178
         Oid *mergefamilies,
179
         Oid *mergecollations,
180
         bool *mergereversals,
181
         bool *mergenullsfirst,
182
         PlanState *parent)
183
0
{
184
0
  MergeJoinClause clauses;
185
0
  int     nClauses = list_length(mergeclauses);
186
0
  int     iClause;
187
0
  ListCell   *cl;
188
189
0
  clauses = palloc0_array(MergeJoinClauseData, nClauses);
190
191
0
  iClause = 0;
192
0
  foreach(cl, mergeclauses)
193
0
  {
194
0
    OpExpr     *qual = (OpExpr *) lfirst(cl);
195
0
    MergeJoinClause clause = &clauses[iClause];
196
0
    Oid     opfamily = mergefamilies[iClause];
197
0
    Oid     collation = mergecollations[iClause];
198
0
    bool    reversed = mergereversals[iClause];
199
0
    bool    nulls_first = mergenullsfirst[iClause];
200
0
    int     op_strategy;
201
0
    Oid     op_lefttype;
202
0
    Oid     op_righttype;
203
0
    Oid     sortfunc;
204
205
0
    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
0
    clause->lexpr = ExecInitExpr((Expr *) linitial(qual->args), parent);
212
0
    clause->rexpr = ExecInitExpr((Expr *) lsecond(qual->args), parent);
213
214
    /* Set up sort support data */
215
0
    clause->ssup.ssup_cxt = CurrentMemoryContext;
216
0
    clause->ssup.ssup_collation = collation;
217
0
    clause->ssup.ssup_reverse = reversed;
218
0
    clause->ssup.ssup_nulls_first = nulls_first;
219
220
    /* Extract the operator's declared left/right datatypes */
221
0
    get_op_opfamily_properties(qual->opno, opfamily, false,
222
0
                   &op_strategy,
223
0
                   &op_lefttype,
224
0
                   &op_righttype);
225
0
    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
0
         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
0
    clause->ssup.abbreviate = false;
236
237
    /* And get the matching support or comparison function */
238
0
    Assert(clause->ssup.comparator == NULL);
239
0
    sortfunc = get_opfamily_proc(opfamily,
240
0
                   op_lefttype,
241
0
                   op_righttype,
242
0
                   BTSORTSUPPORT_PROC);
243
0
    if (OidIsValid(sortfunc))
244
0
    {
245
      /* The sort support function can provide a comparator */
246
0
      OidFunctionCall1(sortfunc, PointerGetDatum(&clause->ssup));
247
0
    }
248
0
    if (clause->ssup.comparator == NULL)
249
0
    {
250
      /* support not available, get comparison func */
251
0
      sortfunc = get_opfamily_proc(opfamily,
252
0
                     op_lefttype,
253
0
                     op_righttype,
254
0
                     BTORDER_PROC);
255
0
      if (!OidIsValid(sortfunc)) /* should not happen */
256
0
        elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
257
0
           BTORDER_PROC, op_lefttype, op_righttype, opfamily);
258
      /* We'll use a shim to call the old-style btree comparator */
259
0
      PrepareSortSupportComparisonShim(sortfunc, &clause->ssup);
260
0
    }
261
262
0
    iClause++;
263
0
  }
264
265
0
  return clauses;
266
0
}
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
MJEvalOuterValues(MergeJoinState *mergestate)
292
0
{
293
0
  ExprContext *econtext = mergestate->mj_OuterEContext;
294
0
  MJEvalResult result = MJEVAL_MATCHABLE;
295
0
  int     i;
296
0
  MemoryContext oldContext;
297
298
  /* Check for end of outer subplan */
299
0
  if (TupIsNull(mergestate->mj_OuterTupleSlot))
300
0
    return MJEVAL_ENDOFJOIN;
301
302
0
  ResetExprContext(econtext);
303
304
0
  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
305
306
0
  econtext->ecxt_outertuple = mergestate->mj_OuterTupleSlot;
307
308
0
  for (i = 0; i < mergestate->mj_NumClauses; i++)
309
0
  {
310
0
    MergeJoinClause clause = &mergestate->mj_Clauses[i];
311
312
0
    clause->ldatum = ExecEvalExpr(clause->lexpr, econtext,
313
0
                    &clause->lisnull);
314
0
    if (clause->lisnull)
315
0
    {
316
      /* match is impossible; can we end the join early? */
317
0
      if (i == 0 && !clause->ssup.ssup_nulls_first &&
318
0
        !mergestate->mj_FillOuter)
319
0
        result = MJEVAL_ENDOFJOIN;
320
0
      else if (result == MJEVAL_MATCHABLE)
321
0
        result = MJEVAL_NONMATCHABLE;
322
0
    }
323
0
  }
324
325
0
  MemoryContextSwitchTo(oldContext);
326
327
0
  return result;
328
0
}
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
MJEvalInnerValues(MergeJoinState *mergestate, TupleTableSlot *innerslot)
339
0
{
340
0
  ExprContext *econtext = mergestate->mj_InnerEContext;
341
0
  MJEvalResult result = MJEVAL_MATCHABLE;
342
0
  int     i;
343
0
  MemoryContext oldContext;
344
345
  /* Check for end of inner subplan */
346
0
  if (TupIsNull(innerslot))
347
0
    return MJEVAL_ENDOFJOIN;
348
349
0
  ResetExprContext(econtext);
350
351
0
  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
352
353
0
  econtext->ecxt_innertuple = innerslot;
354
355
0
  for (i = 0; i < mergestate->mj_NumClauses; i++)
356
0
  {
357
0
    MergeJoinClause clause = &mergestate->mj_Clauses[i];
358
359
0
    clause->rdatum = ExecEvalExpr(clause->rexpr, econtext,
360
0
                    &clause->risnull);
361
0
    if (clause->risnull)
362
0
    {
363
      /* match is impossible; can we end the join early? */
364
0
      if (i == 0 && !clause->ssup.ssup_nulls_first &&
365
0
        !mergestate->mj_FillInner)
366
0
        result = MJEVAL_ENDOFJOIN;
367
0
      else if (result == MJEVAL_MATCHABLE)
368
0
        result = MJEVAL_NONMATCHABLE;
369
0
    }
370
0
  }
371
372
0
  MemoryContextSwitchTo(oldContext);
373
374
0
  return result;
375
0
}
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
MJCompare(MergeJoinState *mergestate)
389
0
{
390
0
  int     result = 0;
391
0
  bool    nulleqnull = false;
392
0
  ExprContext *econtext = mergestate->js.ps.ps_ExprContext;
393
0
  int     i;
394
0
  MemoryContext oldContext;
395
396
  /*
397
   * Call the comparison functions in short-lived context, in case they leak
398
   * memory.
399
   */
400
0
  ResetExprContext(econtext);
401
402
0
  oldContext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
403
404
0
  for (i = 0; i < mergestate->mj_NumClauses; i++)
405
0
  {
406
0
    MergeJoinClause clause = &mergestate->mj_Clauses[i];
407
408
    /*
409
     * Special case for NULL-vs-NULL, else use standard comparison.
410
     */
411
0
    if (clause->lisnull && clause->risnull)
412
0
    {
413
0
      nulleqnull = true; /* NULL "=" NULL */
414
0
      continue;
415
0
    }
416
417
0
    result = ApplySortComparator(clause->ldatum, clause->lisnull,
418
0
                   clause->rdatum, clause->risnull,
419
0
                   &clause->ssup);
420
421
0
    if (result != 0)
422
0
      break;
423
0
  }
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
0
  if (result == 0 &&
435
0
    (nulleqnull || mergestate->mj_ConstFalseJoin))
436
0
    result = 1;
437
438
0
  MemoryContextSwitchTo(oldContext);
439
440
0
  return result;
441
0
}
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
MJFillOuter(MergeJoinState *node)
450
0
{
451
0
  ExprContext *econtext = node->js.ps.ps_ExprContext;
452
0
  ExprState  *otherqual = node->js.ps.qual;
453
454
0
  ResetExprContext(econtext);
455
456
0
  econtext->ecxt_outertuple = node->mj_OuterTupleSlot;
457
0
  econtext->ecxt_innertuple = node->mj_NullInnerTupleSlot;
458
459
0
  if (ExecQual(otherqual, econtext))
460
0
  {
461
    /*
462
     * qualification succeeded.  now form the desired projection tuple and
463
     * return the slot containing it.
464
     */
465
0
    return ExecProject(node->js.ps.ps_ProjInfo);
466
0
  }
467
0
  else
468
0
    InstrCountFiltered2(node, 1);
469
470
0
  return NULL;
471
0
}
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
MJFillInner(MergeJoinState *node)
479
0
{
480
0
  ExprContext *econtext = node->js.ps.ps_ExprContext;
481
0
  ExprState  *otherqual = node->js.ps.qual;
482
483
0
  ResetExprContext(econtext);
484
485
0
  econtext->ecxt_outertuple = node->mj_NullOuterTupleSlot;
486
0
  econtext->ecxt_innertuple = node->mj_InnerTupleSlot;
487
488
0
  if (ExecQual(otherqual, econtext))
489
0
  {
490
    /*
491
     * qualification succeeded.  now form the desired projection tuple and
492
     * return the slot containing it.
493
     */
494
0
    return ExecProject(node->js.ps.ps_ProjInfo);
495
0
  }
496
0
  else
497
0
    InstrCountFiltered2(node, 1);
498
499
0
  return NULL;
500
0
}
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
check_constant_qual(List *qual, bool *is_const_false)
513
0
{
514
0
  ListCell   *lc;
515
516
0
  foreach(lc, qual)
517
0
  {
518
0
    Const    *con = (Const *) lfirst(lc);
519
520
0
    if (!con || !IsA(con, Const))
521
0
      return false;
522
0
    if (con->constisnull || !DatumGetBool(con->constvalue))
523
0
      *is_const_false = true;
524
0
  }
525
0
  return true;
526
0
}
527
528
529
/* ----------------------------------------------------------------
530
 *    ExecMergeJoin
531
 * ----------------------------------------------------------------
532
 */
533
static TupleTableSlot *
534
ExecMergeJoin(PlanState *pstate)
535
0
{
536
0
  MergeJoinState *node = castNode(MergeJoinState, pstate);
537
0
  ExprState  *joinqual;
538
0
  ExprState  *otherqual;
539
0
  bool    qualResult;
540
0
  int     compareResult;
541
0
  PlanState  *innerPlan;
542
0
  TupleTableSlot *innerTupleSlot;
543
0
  PlanState  *outerPlan;
544
0
  TupleTableSlot *outerTupleSlot;
545
0
  ExprContext *econtext;
546
0
  bool    doFillOuter;
547
0
  bool    doFillInner;
548
549
0
  CHECK_FOR_INTERRUPTS();
550
551
  /*
552
   * get information from node
553
   */
554
0
  innerPlan = innerPlanState(node);
555
0
  outerPlan = outerPlanState(node);
556
0
  econtext = node->js.ps.ps_ExprContext;
557
0
  joinqual = node->js.joinqual;
558
0
  otherqual = node->js.ps.qual;
559
0
  doFillOuter = node->mj_FillOuter;
560
0
  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
0
  ResetExprContext(econtext);
567
568
  /*
569
   * ok, everything is setup.. let's go to work
570
   */
571
0
  for (;;)
572
0
  {
573
    /*
574
     * get the current state of the join and do things accordingly.
575
     */
576
0
    switch (node->mj_JoinState)
577
0
    {
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
0
      case EXEC_MJ_INITIALIZE_OUTER:
586
0
        outerTupleSlot = ExecProcNode(outerPlan);
587
0
        node->mj_OuterTupleSlot = outerTupleSlot;
588
589
        /* Compute join values and check for unmatchability */
590
0
        switch (MJEvalOuterValues(node))
591
0
        {
592
0
          case MJEVAL_MATCHABLE:
593
            /* OK to go get the first inner tuple */
594
0
            node->mj_JoinState = EXEC_MJ_INITIALIZE_INNER;
595
0
            break;
596
0
          case MJEVAL_NONMATCHABLE:
597
            /* Stay in same state to fetch next outer tuple */
598
0
            if (doFillOuter)
599
0
            {
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
0
              TupleTableSlot *result;
606
607
0
              result = MJFillOuter(node);
608
0
              if (result)
609
0
                return result;
610
0
            }
611
0
            break;
612
0
          case MJEVAL_ENDOFJOIN:
613
            /* No more outer tuples */
614
0
            if (doFillInner)
615
0
            {
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
0
              node->mj_JoinState = EXEC_MJ_ENDOUTER;
622
0
              node->mj_MatchedInner = true;
623
0
              break;
624
0
            }
625
            /* Otherwise we're done. */
626
0
            return NULL;
627
0
        }
628
0
        break;
629
630
0
      case EXEC_MJ_INITIALIZE_INNER:
631
0
        innerTupleSlot = ExecProcNode(innerPlan);
632
0
        node->mj_InnerTupleSlot = innerTupleSlot;
633
634
        /* Compute join values and check for unmatchability */
635
0
        switch (MJEvalInnerValues(node, innerTupleSlot))
636
0
        {
637
0
          case MJEVAL_MATCHABLE:
638
639
            /*
640
             * OK, we have the initial tuples.  Begin by skipping
641
             * non-matching tuples.
642
             */
643
0
            node->mj_JoinState = EXEC_MJ_SKIP_TEST;
644
0
            break;
645
0
          case MJEVAL_NONMATCHABLE:
646
            /* Mark before advancing, if wanted */
647
0
            if (node->mj_ExtraMarks)
648
0
              ExecMarkPos(innerPlan);
649
            /* Stay in same state to fetch next inner tuple */
650
0
            if (doFillInner)
651
0
            {
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
0
              TupleTableSlot *result;
658
659
0
              result = MJFillInner(node);
660
0
              if (result)
661
0
                return result;
662
0
            }
663
0
            break;
664
0
          case MJEVAL_ENDOFJOIN:
665
            /* No more inner tuples */
666
0
            if (doFillOuter)
667
0
            {
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
0
              node->mj_JoinState = EXEC_MJ_ENDINNER;
676
0
              node->mj_MatchedOuter = false;
677
0
              break;
678
0
            }
679
            /* Otherwise we're done. */
680
0
            return NULL;
681
0
        }
682
0
        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
0
      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
0
        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
0
        outerTupleSlot = node->mj_OuterTupleSlot;
713
0
        econtext->ecxt_outertuple = outerTupleSlot;
714
0
        innerTupleSlot = node->mj_InnerTupleSlot;
715
0
        econtext->ecxt_innertuple = innerTupleSlot;
716
717
0
        qualResult = (joinqual == NULL ||
718
0
                ExecQual(joinqual, econtext));
719
720
0
        if (qualResult)
721
0
        {
722
0
          node->mj_MatchedOuter = true;
723
0
          node->mj_MatchedInner = true;
724
725
          /* In an antijoin, we never return a matched tuple */
726
0
          if (node->js.jointype == JOIN_ANTI)
727
0
          {
728
0
            node->mj_JoinState = EXEC_MJ_NEXTOUTER;
729
0
            break;
730
0
          }
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
0
          if (node->js.single_match)
738
0
            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
0
          if (node->js.jointype == JOIN_RIGHT_ANTI)
747
0
            break;
748
749
0
          qualResult = (otherqual == NULL ||
750
0
                  ExecQual(otherqual, econtext));
751
752
0
          if (qualResult)
753
0
          {
754
            /*
755
             * qualification succeeded.  now form the desired
756
             * projection tuple and return the slot containing it.
757
             */
758
0
            return ExecProject(node->js.ps.ps_ProjInfo);
759
0
          }
760
0
          else
761
0
            InstrCountFiltered2(node, 1);
762
0
        }
763
0
        else
764
0
          InstrCountFiltered1(node, 1);
765
0
        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
0
      case EXEC_MJ_NEXTINNER:
776
0
        if (doFillInner && !node->mj_MatchedInner)
777
0
        {
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
0
          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
0
        }
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
0
        innerTupleSlot = ExecProcNode(innerPlan);
800
0
        node->mj_InnerTupleSlot = innerTupleSlot;
801
0
        node->mj_MatchedInner = false;
802
803
        /* Compute join values and check for unmatchability */
804
0
        switch (MJEvalInnerValues(node, innerTupleSlot))
805
0
        {
806
0
          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
0
            compareResult = MJCompare(node);
819
820
0
            if (compareResult == 0)
821
0
              node->mj_JoinState = EXEC_MJ_JOINTUPLES;
822
0
            else if (compareResult < 0)
823
0
              node->mj_JoinState = EXEC_MJ_NEXTOUTER;
824
0
            else  /* compareResult > 0 should not happen */
825
0
              elog(ERROR, "mergejoin input data is out of order");
826
0
            break;
827
0
          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
0
            node->mj_JoinState = EXEC_MJ_NEXTOUTER;
835
0
            break;
836
0
          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
0
            node->mj_InnerTupleSlot = NULL;
847
0
            node->mj_JoinState = EXEC_MJ_NEXTOUTER;
848
0
            break;
849
0
        }
850
0
        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
0
      case EXEC_MJ_NEXTOUTER:
873
0
        if (doFillOuter && !node->mj_MatchedOuter)
874
0
        {
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
0
          TupleTableSlot *result;
880
881
0
          node->mj_MatchedOuter = true; /* do it only once */
882
883
0
          result = MJFillOuter(node);
884
0
          if (result)
885
0
            return result;
886
0
        }
887
888
        /*
889
         * now we get the next outer tuple, if any
890
         */
891
0
        outerTupleSlot = ExecProcNode(outerPlan);
892
0
        node->mj_OuterTupleSlot = outerTupleSlot;
893
0
        node->mj_MatchedOuter = false;
894
895
        /* Compute join values and check for unmatchability */
896
0
        switch (MJEvalOuterValues(node))
897
0
        {
898
0
          case MJEVAL_MATCHABLE:
899
            /* Go test the new tuple against the marked tuple */
900
0
            node->mj_JoinState = EXEC_MJ_TESTOUTER;
901
0
            break;
902
0
          case MJEVAL_NONMATCHABLE:
903
            /* Can't match, so fetch next outer tuple */
904
0
            node->mj_JoinState = EXEC_MJ_NEXTOUTER;
905
0
            break;
906
0
          case MJEVAL_ENDOFJOIN:
907
            /* No more outer tuples */
908
0
            innerTupleSlot = node->mj_InnerTupleSlot;
909
0
            if (doFillInner && !TupIsNull(innerTupleSlot))
910
0
            {
911
              /*
912
               * Need to emit right-join tuples for remaining
913
               * inner tuples.
914
               */
915
0
              node->mj_JoinState = EXEC_MJ_ENDOUTER;
916
0
              break;
917
0
            }
918
            /* Otherwise we're done. */
919
0
            return NULL;
920
0
        }
921
0
        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
0
      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
0
        innerTupleSlot = node->mj_MarkedTupleSlot;
966
0
        (void) MJEvalInnerValues(node, innerTupleSlot);
967
968
0
        compareResult = MJCompare(node);
969
970
0
        if (compareResult == 0)
971
0
        {
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
0
          if (!node->mj_SkipMarkRestore)
994
0
          {
995
0
            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
0
            node->mj_InnerTupleSlot = innerTupleSlot;
1004
            /* we need not do MJEvalInnerValues again */
1005
0
          }
1006
1007
0
          node->mj_JoinState = EXEC_MJ_JOINTUPLES;
1008
0
        }
1009
0
        else if (compareResult > 0)
1010
0
        {
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
0
          innerTupleSlot = node->mj_InnerTupleSlot;
1029
1030
          /* reload comparison data for current inner */
1031
0
          switch (MJEvalInnerValues(node, innerTupleSlot))
1032
0
          {
1033
0
            case MJEVAL_MATCHABLE:
1034
              /* proceed to compare it to the current outer */
1035
0
              node->mj_JoinState = EXEC_MJ_SKIP_TEST;
1036
0
              break;
1037
0
            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
0
              node->mj_JoinState = EXEC_MJ_SKIPINNER_ADVANCE;
1045
0
              break;
1046
0
            case MJEVAL_ENDOFJOIN:
1047
              /* No more inner tuples */
1048
0
              if (doFillOuter)
1049
0
              {
1050
                /*
1051
                 * Need to emit left-join tuples for remaining
1052
                 * outer tuples.
1053
                 */
1054
0
                node->mj_JoinState = EXEC_MJ_ENDINNER;
1055
0
                break;
1056
0
              }
1057
              /* Otherwise we're done. */
1058
0
              return NULL;
1059
0
          }
1060
0
        }
1061
0
        else      /* compareResult < 0 should not happen */
1062
0
          elog(ERROR, "mergejoin input data is out of order");
1063
0
        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
0
      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
0
        compareResult = MJCompare(node);
1102
1103
0
        if (compareResult == 0)
1104
0
        {
1105
0
          if (!node->mj_SkipMarkRestore)
1106
0
            ExecMarkPos(innerPlan);
1107
1108
0
          MarkInnerTuple(node->mj_InnerTupleSlot, node);
1109
1110
0
          node->mj_JoinState = EXEC_MJ_JOINTUPLES;
1111
0
        }
1112
0
        else if (compareResult < 0)
1113
0
          node->mj_JoinState = EXEC_MJ_SKIPOUTER_ADVANCE;
1114
0
        else
1115
          /* compareResult > 0 */
1116
0
          node->mj_JoinState = EXEC_MJ_SKIPINNER_ADVANCE;
1117
0
        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
0
      case EXEC_MJ_SKIPOUTER_ADVANCE:
1127
0
        if (doFillOuter && !node->mj_MatchedOuter)
1128
0
        {
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
0
          TupleTableSlot *result;
1134
1135
0
          node->mj_MatchedOuter = true; /* do it only once */
1136
1137
0
          result = MJFillOuter(node);
1138
0
          if (result)
1139
0
            return result;
1140
0
        }
1141
1142
        /*
1143
         * now we get the next outer tuple, if any
1144
         */
1145
0
        outerTupleSlot = ExecProcNode(outerPlan);
1146
0
        node->mj_OuterTupleSlot = outerTupleSlot;
1147
0
        node->mj_MatchedOuter = false;
1148
1149
        /* Compute join values and check for unmatchability */
1150
0
        switch (MJEvalOuterValues(node))
1151
0
        {
1152
0
          case MJEVAL_MATCHABLE:
1153
            /* Go test the new tuple against the current inner */
1154
0
            node->mj_JoinState = EXEC_MJ_SKIP_TEST;
1155
0
            break;
1156
0
          case MJEVAL_NONMATCHABLE:
1157
            /* Can't match, so fetch next outer tuple */
1158
0
            node->mj_JoinState = EXEC_MJ_SKIPOUTER_ADVANCE;
1159
0
            break;
1160
0
          case MJEVAL_ENDOFJOIN:
1161
            /* No more outer tuples */
1162
0
            innerTupleSlot = node->mj_InnerTupleSlot;
1163
0
            if (doFillInner && !TupIsNull(innerTupleSlot))
1164
0
            {
1165
              /*
1166
               * Need to emit right-join tuples for remaining
1167
               * inner tuples.
1168
               */
1169
0
              node->mj_JoinState = EXEC_MJ_ENDOUTER;
1170
0
              break;
1171
0
            }
1172
            /* Otherwise we're done. */
1173
0
            return NULL;
1174
0
        }
1175
0
        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
0
      case EXEC_MJ_SKIPINNER_ADVANCE:
1185
0
        if (doFillInner && !node->mj_MatchedInner)
1186
0
        {
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
0
          TupleTableSlot *result;
1192
1193
0
          node->mj_MatchedInner = true; /* do it only once */
1194
1195
0
          result = MJFillInner(node);
1196
0
          if (result)
1197
0
            return result;
1198
0
        }
1199
1200
        /* Mark before advancing, if wanted */
1201
0
        if (node->mj_ExtraMarks)
1202
0
          ExecMarkPos(innerPlan);
1203
1204
        /*
1205
         * now we get the next inner tuple, if any
1206
         */
1207
0
        innerTupleSlot = ExecProcNode(innerPlan);
1208
0
        node->mj_InnerTupleSlot = innerTupleSlot;
1209
0
        node->mj_MatchedInner = false;
1210
1211
        /* Compute join values and check for unmatchability */
1212
0
        switch (MJEvalInnerValues(node, innerTupleSlot))
1213
0
        {
1214
0
          case MJEVAL_MATCHABLE:
1215
            /* proceed to compare it to the current outer */
1216
0
            node->mj_JoinState = EXEC_MJ_SKIP_TEST;
1217
0
            break;
1218
0
          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
0
            node->mj_JoinState = EXEC_MJ_SKIPINNER_ADVANCE;
1225
0
            break;
1226
0
          case MJEVAL_ENDOFJOIN:
1227
            /* No more inner tuples */
1228
0
            outerTupleSlot = node->mj_OuterTupleSlot;
1229
0
            if (doFillOuter && !TupIsNull(outerTupleSlot))
1230
0
            {
1231
              /*
1232
               * Need to emit left-join tuples for remaining
1233
               * outer tuples.
1234
               */
1235
0
              node->mj_JoinState = EXEC_MJ_ENDINNER;
1236
0
              break;
1237
0
            }
1238
            /* Otherwise we're done. */
1239
0
            return NULL;
1240
0
        }
1241
0
        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
0
      case EXEC_MJ_ENDOUTER:
1249
0
        Assert(doFillInner);
1250
1251
0
        if (!node->mj_MatchedInner)
1252
0
        {
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
0
          TupleTableSlot *result;
1258
1259
0
          node->mj_MatchedInner = true; /* do it only once */
1260
1261
0
          result = MJFillInner(node);
1262
0
          if (result)
1263
0
            return result;
1264
0
        }
1265
1266
        /* Mark before advancing, if wanted */
1267
0
        if (node->mj_ExtraMarks)
1268
0
          ExecMarkPos(innerPlan);
1269
1270
        /*
1271
         * now we get the next inner tuple, if any
1272
         */
1273
0
        innerTupleSlot = ExecProcNode(innerPlan);
1274
0
        node->mj_InnerTupleSlot = innerTupleSlot;
1275
0
        node->mj_MatchedInner = false;
1276
1277
0
        if (TupIsNull(innerTupleSlot))
1278
0
          return NULL;
1279
1280
        /* Else remain in ENDOUTER state and process next tuple. */
1281
0
        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
0
      case EXEC_MJ_ENDINNER:
1289
0
        Assert(doFillOuter);
1290
1291
0
        if (!node->mj_MatchedOuter)
1292
0
        {
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
0
          TupleTableSlot *result;
1298
1299
0
          node->mj_MatchedOuter = true; /* do it only once */
1300
1301
0
          result = MJFillOuter(node);
1302
0
          if (result)
1303
0
            return result;
1304
0
        }
1305
1306
        /*
1307
         * now we get the next outer tuple, if any
1308
         */
1309
0
        outerTupleSlot = ExecProcNode(outerPlan);
1310
0
        node->mj_OuterTupleSlot = outerTupleSlot;
1311
0
        node->mj_MatchedOuter = false;
1312
1313
0
        if (TupIsNull(outerTupleSlot))
1314
0
          return NULL;
1315
1316
        /* Else remain in ENDINNER state and process next tuple. */
1317
0
        break;
1318
1319
        /*
1320
         * broken state value?
1321
         */
1322
0
      default:
1323
0
        elog(ERROR, "unrecognized mergejoin state: %d",
1324
0
           (int) node->mj_JoinState);
1325
0
    }
1326
0
  }
1327
0
}
1328
1329
/* ----------------------------------------------------------------
1330
 *    ExecInitMergeJoin
1331
 * ----------------------------------------------------------------
1332
 */
1333
MergeJoinState *
1334
ExecInitMergeJoin(MergeJoin *node, EState *estate, int eflags)
1335
0
{
1336
0
  MergeJoinState *mergestate;
1337
0
  TupleDesc outerDesc,
1338
0
        innerDesc;
1339
0
  const TupleTableSlotOps *innerOps;
1340
1341
  /* check for unsupported flags */
1342
0
  Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
1343
1344
  /*
1345
   * create state structure
1346
   */
1347
0
  mergestate = makeNode(MergeJoinState);
1348
0
  mergestate->js.ps.plan = (Plan *) node;
1349
0
  mergestate->js.ps.state = estate;
1350
0
  mergestate->js.ps.ExecProcNode = ExecMergeJoin;
1351
0
  mergestate->js.jointype = node->join.jointype;
1352
0
  mergestate->mj_ConstFalseJoin = false;
1353
1354
  /*
1355
   * Miscellaneous initialization
1356
   *
1357
   * create expression context for node
1358
   */
1359
0
  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
0
  mergestate->mj_OuterEContext = CreateExprContext(estate);
1367
0
  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
0
  Assert(node->join.joinqual == NIL || !node->skip_mark_restore);
1377
0
  mergestate->mj_SkipMarkRestore = node->skip_mark_restore;
1378
1379
0
  outerPlanState(mergestate) = ExecInitNode(outerPlan(node), estate, eflags);
1380
0
  outerDesc = ExecGetResultType(outerPlanState(mergestate));
1381
0
  innerPlanState(mergestate) = ExecInitNode(innerPlan(node), estate,
1382
0
                        mergestate->mj_SkipMarkRestore ?
1383
0
                        eflags :
1384
0
                        (eflags | EXEC_FLAG_MARK));
1385
0
  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
0
  if (IsA(innerPlan(node), Material) &&
1402
0
    (eflags & EXEC_FLAG_REWIND) == 0 &&
1403
0
    !mergestate->mj_SkipMarkRestore)
1404
0
    mergestate->mj_ExtraMarks = true;
1405
0
  else
1406
0
    mergestate->mj_ExtraMarks = false;
1407
1408
  /*
1409
   * Initialize result slot, type and projection.
1410
   */
1411
0
  ExecInitResultTupleSlotTL(&mergestate->js.ps, &TTSOpsVirtual);
1412
0
  ExecAssignProjectionInfo(&mergestate->js.ps, NULL);
1413
1414
  /*
1415
   * tuple table initialization
1416
   */
1417
0
  innerOps = ExecGetResultSlotOps(innerPlanState(mergestate), NULL);
1418
0
  mergestate->mj_MarkedTupleSlot = ExecInitExtraTupleSlot(estate, innerDesc,
1419
0
                              innerOps);
1420
1421
  /*
1422
   * initialize child expressions
1423
   */
1424
0
  mergestate->js.ps.qual =
1425
0
    ExecInitQual(node->join.plan.qual, (PlanState *) mergestate);
1426
0
  mergestate->js.joinqual =
1427
0
    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
0
  mergestate->js.single_match = (node->join.inner_unique ||
1434
0
                   node->join.jointype == JOIN_SEMI);
1435
1436
  /* set up null tuples for outer joins, if needed */
1437
0
  switch (node->join.jointype)
1438
0
  {
1439
0
    case JOIN_INNER:
1440
0
    case JOIN_SEMI:
1441
0
      mergestate->mj_FillOuter = false;
1442
0
      mergestate->mj_FillInner = false;
1443
0
      break;
1444
0
    case JOIN_LEFT:
1445
0
    case JOIN_ANTI:
1446
0
      mergestate->mj_FillOuter = true;
1447
0
      mergestate->mj_FillInner = false;
1448
0
      mergestate->mj_NullInnerTupleSlot =
1449
0
        ExecInitNullTupleSlot(estate, innerDesc, &TTSOpsVirtual);
1450
0
      break;
1451
0
    case JOIN_RIGHT:
1452
0
    case JOIN_RIGHT_ANTI:
1453
0
      mergestate->mj_FillOuter = false;
1454
0
      mergestate->mj_FillInner = true;
1455
0
      mergestate->mj_NullOuterTupleSlot =
1456
0
        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
0
      if (!check_constant_qual(node->join.joinqual,
1463
0
                   &mergestate->mj_ConstFalseJoin))
1464
0
        ereport(ERROR,
1465
0
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1466
0
             errmsg("RIGHT JOIN is only supported with merge-joinable join conditions")));
1467
0
      break;
1468
0
    case JOIN_FULL:
1469
0
      mergestate->mj_FillOuter = true;
1470
0
      mergestate->mj_FillInner = true;
1471
0
      mergestate->mj_NullOuterTupleSlot =
1472
0
        ExecInitNullTupleSlot(estate, outerDesc, &TTSOpsVirtual);
1473
0
      mergestate->mj_NullInnerTupleSlot =
1474
0
        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
0
      if (!check_constant_qual(node->join.joinqual,
1481
0
                   &mergestate->mj_ConstFalseJoin))
1482
0
        ereport(ERROR,
1483
0
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1484
0
             errmsg("FULL JOIN is only supported with merge-joinable join conditions")));
1485
0
      break;
1486
0
    default:
1487
0
      elog(ERROR, "unrecognized join type: %d",
1488
0
         (int) node->join.jointype);
1489
0
  }
1490
1491
  /*
1492
   * preprocess the merge clauses
1493
   */
1494
0
  mergestate->mj_NumClauses = list_length(node->mergeclauses);
1495
0
  mergestate->mj_Clauses = MJExamineQuals(node->mergeclauses,
1496
0
                      node->mergeFamilies,
1497
0
                      node->mergeCollations,
1498
0
                      node->mergeReversals,
1499
0
                      node->mergeNullsFirst,
1500
0
                      (PlanState *) mergestate);
1501
1502
  /*
1503
   * initialize join state
1504
   */
1505
0
  mergestate->mj_JoinState = EXEC_MJ_INITIALIZE_OUTER;
1506
0
  mergestate->mj_MatchedOuter = false;
1507
0
  mergestate->mj_MatchedInner = false;
1508
0
  mergestate->mj_OuterTupleSlot = NULL;
1509
0
  mergestate->mj_InnerTupleSlot = NULL;
1510
1511
  /*
1512
   * initialization successful
1513
   */
1514
0
  return mergestate;
1515
0
}
1516
1517
/* ----------------------------------------------------------------
1518
 *    ExecEndMergeJoin
1519
 *
1520
 * old comments
1521
 *    frees storage allocated through C routines.
1522
 * ----------------------------------------------------------------
1523
 */
1524
void
1525
ExecEndMergeJoin(MergeJoinState *node)
1526
0
{
1527
  /*
1528
   * shut down the subplans
1529
   */
1530
0
  ExecEndNode(innerPlanState(node));
1531
0
  ExecEndNode(outerPlanState(node));
1532
0
}
1533
1534
void
1535
ExecReScanMergeJoin(MergeJoinState *node)
1536
0
{
1537
0
  PlanState  *outerPlan = outerPlanState(node);
1538
0
  PlanState  *innerPlan = innerPlanState(node);
1539
1540
0
  ExecClearTuple(node->mj_MarkedTupleSlot);
1541
1542
0
  node->mj_JoinState = EXEC_MJ_INITIALIZE_OUTER;
1543
0
  node->mj_MatchedOuter = false;
1544
0
  node->mj_MatchedInner = false;
1545
0
  node->mj_OuterTupleSlot = NULL;
1546
0
  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
0
  if (outerPlan->chgParam == NULL)
1553
0
    ExecReScan(outerPlan);
1554
0
  if (innerPlan->chgParam == NULL)
1555
0
    ExecReScan(innerPlan);
1556
0
}