1 /*-------------------------------------------------------------------------
4 * routines to handle MergeAppend nodes.
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/executor/nodeMergeAppend.c
13 *-------------------------------------------------------------------------
16 * ExecInitMergeAppend - initialize the MergeAppend node
17 * ExecMergeAppend - retrieve the next tuple from the node
18 * ExecEndMergeAppend - shut down the MergeAppend node
19 * ExecReScanMergeAppend - rescan the MergeAppend node
22 * A MergeAppend node contains a list of one or more subplans.
23 * These are each expected to deliver tuples that are sorted according
24 * to a common sort key. The MergeAppend node merges these streams
25 * to produce output sorted the same way.
27 * MergeAppend nodes don't make use of their left and right
28 * subtrees, rather they maintain a list of subplans so
29 * a typical MergeAppend node looks like this in the plan tree:
33 * MergeAppend---+------+------+--- nil
41 #include "access/nbtree.h"
42 #include "executor/execdebug.h"
43 #include "executor/nodeMergeAppend.h"
44 #include "utils/lsyscache.h"
47 * It gets quite confusing having a heap array (indexed by integers) which
48 * contains integers which index into the slots array. These typedefs try to
49 * clear it up, but they're only documentation.
51 typedef int SlotNumber;
52 typedef int HeapPosition;
54 static void heap_insert_slot(MergeAppendState *node, SlotNumber new_slot);
55 static void heap_siftup_slot(MergeAppendState *node);
56 static int32 heap_compare_slots(MergeAppendState *node, SlotNumber slot1, SlotNumber slot2);
59 /* ----------------------------------------------------------------
62 * Begin all of the subscans of the MergeAppend node.
63 * ----------------------------------------------------------------
66 ExecInitMergeAppend(MergeAppend *node, EState *estate, int eflags)
68 MergeAppendState *mergestate = makeNode(MergeAppendState);
69 PlanState **mergeplanstates;
74 /* check for unsupported flags */
75 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
78 * Set up empty vector of subplan states
80 nplans = list_length(node->mergeplans);
82 mergeplanstates = (PlanState **) palloc0(nplans * sizeof(PlanState *));
85 * create new MergeAppendState for our node
87 mergestate->ps.plan = (Plan *) node;
88 mergestate->ps.state = estate;
89 mergestate->mergeplans = mergeplanstates;
90 mergestate->ms_nplans = nplans;
92 mergestate->ms_slots = (TupleTableSlot **) palloc0(sizeof(TupleTableSlot *) * nplans);
93 mergestate->ms_heap = (int *) palloc0(sizeof(int) * nplans);
96 * Miscellaneous initialization
98 * MergeAppend plans don't have expression contexts because they never
99 * call ExecQual or ExecProject.
103 * MergeAppend nodes do have Result slots, which hold pointers to tuples,
104 * so we have to initialize them.
106 ExecInitResultTupleSlot(estate, &mergestate->ps);
109 * call ExecInitNode on each of the plans to be executed and save the
110 * results into the array "mergeplans".
113 foreach(lc, node->mergeplans)
115 Plan *initNode = (Plan *) lfirst(lc);
117 mergeplanstates[i] = ExecInitNode(initNode, estate, eflags);
122 * initialize output tuple type
124 ExecAssignResultTypeFromTL(&mergestate->ps);
125 mergestate->ps.ps_ProjInfo = NULL;
128 * initialize sort-key information
130 mergestate->ms_nkeys = node->numCols;
131 mergestate->ms_scankeys = palloc0(sizeof(ScanKeyData) * node->numCols);
133 for (i = 0; i < node->numCols; i++)
139 if (!get_compare_function_for_ordering_op(node->sortOperators[i],
140 &sortFunction, &reverse))
141 elog(ERROR, "operator %u is not a valid ordering operator",
142 node->sortOperators[i]);
144 /* We use btree's conventions for encoding directionality */
148 if (node->nullsFirst[i])
149 flags |= SK_BT_NULLS_FIRST;
152 * We needn't fill in sk_strategy or sk_subtype since these scankeys
153 * will never be passed to an index.
155 ScanKeyEntryInitialize(&mergestate->ms_scankeys[i],
166 * initialize to show we have not run the subplans yet
168 mergestate->ms_heap_size = 0;
169 mergestate->ms_initialized = false;
170 mergestate->ms_last_slot = -1;
175 /* ----------------------------------------------------------------
178 * Handles iteration over multiple subplans.
179 * ----------------------------------------------------------------
182 ExecMergeAppend(MergeAppendState *node)
184 TupleTableSlot *result;
187 if (!node->ms_initialized)
190 * First time through: pull the first tuple from each subplan, and set
193 for (i = 0; i < node->ms_nplans; i++)
195 node->ms_slots[i] = ExecProcNode(node->mergeplans[i]);
196 if (!TupIsNull(node->ms_slots[i]))
197 heap_insert_slot(node, i);
199 node->ms_initialized = true;
204 * Otherwise, pull the next tuple from whichever subplan we returned
205 * from last time, and insert it into the heap. (We could simplify
206 * the logic a bit by doing this before returning from the prior call,
207 * but it's better to not pull tuples until necessary.)
209 i = node->ms_last_slot;
210 node->ms_slots[i] = ExecProcNode(node->mergeplans[i]);
211 if (!TupIsNull(node->ms_slots[i]))
212 heap_insert_slot(node, i);
215 if (node->ms_heap_size > 0)
217 /* Return the topmost heap node, and sift up the remaining nodes */
218 i = node->ms_heap[0];
219 result = node->ms_slots[i];
220 node->ms_last_slot = i;
221 heap_siftup_slot(node);
225 /* All the subplans are exhausted, and so is the heap */
226 result = ExecClearTuple(node->ps.ps_ResultTupleSlot);
233 * Insert a new slot into the heap. The slot must contain a valid tuple.
236 heap_insert_slot(MergeAppendState *node, SlotNumber new_slot)
238 SlotNumber *heap = node->ms_heap;
241 Assert(!TupIsNull(node->ms_slots[new_slot]));
243 j = node->ms_heap_size++; /* j is where the "hole" is */
248 if (heap_compare_slots(node, new_slot, node->ms_heap[i]) >= 0)
257 * Delete the heap top (the slot in heap[0]), and sift up.
260 heap_siftup_slot(MergeAppendState *node)
262 SlotNumber *heap = node->ms_heap;
266 if (--node->ms_heap_size <= 0)
268 n = node->ms_heap_size; /* heap[n] needs to be reinserted */
269 i = 0; /* i is where the "hole" is */
276 if (j + 1 < n && heap_compare_slots(node, heap[j], heap[j + 1]) > 0)
278 if (heap_compare_slots(node, heap[n], heap[j]) <= 0)
287 * Compare the tuples in the two given slots.
290 heap_compare_slots(MergeAppendState *node, SlotNumber slot1, SlotNumber slot2)
292 TupleTableSlot *s1 = node->ms_slots[slot1];
293 TupleTableSlot *s2 = node->ms_slots[slot2];
296 Assert(!TupIsNull(s1));
297 Assert(!TupIsNull(s2));
299 for (nkey = 0; nkey < node->ms_nkeys; nkey++)
301 ScanKey scankey = node->ms_scankeys + nkey;
302 AttrNumber attno = scankey->sk_attno;
309 datum1 = slot_getattr(s1, attno, &isNull1);
310 datum2 = slot_getattr(s2, attno, &isNull2);
315 continue; /* NULL "=" NULL */
316 else if (scankey->sk_flags & SK_BT_NULLS_FIRST)
317 return -1; /* NULL "<" NOT_NULL */
319 return 1; /* NULL ">" NOT_NULL */
323 if (scankey->sk_flags & SK_BT_NULLS_FIRST)
324 return 1; /* NOT_NULL ">" NULL */
326 return -1; /* NOT_NULL "<" NULL */
330 compare = DatumGetInt32(FunctionCall2Coll(&scankey->sk_func,
331 scankey->sk_collation,
335 if (scankey->sk_flags & SK_BT_DESC)
344 /* ----------------------------------------------------------------
347 * Shuts down the subscans of the MergeAppend node.
349 * Returns nothing of interest.
350 * ----------------------------------------------------------------
353 ExecEndMergeAppend(MergeAppendState *node)
355 PlanState **mergeplans;
360 * get information from the node
362 mergeplans = node->mergeplans;
363 nplans = node->ms_nplans;
366 * shut down each of the subscans
368 for (i = 0; i < nplans; i++)
369 ExecEndNode(mergeplans[i]);
373 ExecReScanMergeAppend(MergeAppendState *node)
377 for (i = 0; i < node->ms_nplans; i++)
379 PlanState *subnode = node->mergeplans[i];
382 * ExecReScan doesn't know about my subplans, so I have to do
383 * changed-parameter signaling myself.
385 if (node->ps.chgParam != NULL)
386 UpdateChangedParamSet(subnode, node->ps.chgParam);
389 * If chgParam of subnode is not null then plan will be re-scanned by
390 * first ExecProcNode.
392 if (subnode->chgParam == NULL)
395 node->ms_heap_size = 0;
396 node->ms_initialized = false;
397 node->ms_last_slot = -1;