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"
45 #include "utils/rel.h"
48 * It gets quite confusing having a heap array (indexed by integers) which
49 * contains integers which index into the slots array. These typedefs try to
50 * clear it up, but they're only documentation.
52 typedef int SlotNumber;
53 typedef int HeapPosition;
55 static void heap_insert_slot(MergeAppendState *node, SlotNumber new_slot);
56 static void heap_siftup_slot(MergeAppendState *node);
57 static int32 heap_compare_slots(MergeAppendState *node, SlotNumber slot1, SlotNumber slot2);
60 /* ----------------------------------------------------------------
63 * Begin all of the subscans of the MergeAppend node.
64 * ----------------------------------------------------------------
67 ExecInitMergeAppend(MergeAppend *node, EState *estate, int eflags)
69 MergeAppendState *mergestate = makeNode(MergeAppendState);
70 PlanState **mergeplanstates;
75 /* check for unsupported flags */
76 Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
79 * Set up empty vector of subplan states
81 nplans = list_length(node->mergeplans);
83 mergeplanstates = (PlanState **) palloc0(nplans * sizeof(PlanState *));
86 * create new MergeAppendState for our node
88 mergestate->ps.plan = (Plan *) node;
89 mergestate->ps.state = estate;
90 mergestate->mergeplans = mergeplanstates;
91 mergestate->ms_nplans = nplans;
93 mergestate->ms_slots = (TupleTableSlot **) palloc0(sizeof(TupleTableSlot *) * nplans);
94 mergestate->ms_heap = (int *) palloc0(sizeof(int) * nplans);
97 * Miscellaneous initialization
99 * MergeAppend plans don't have expression contexts because they never
100 * call ExecQual or ExecProject.
104 * MergeAppend nodes do have Result slots, which hold pointers to tuples,
105 * so we have to initialize them.
107 ExecInitResultTupleSlot(estate, &mergestate->ps);
110 * call ExecInitNode on each of the plans to be executed and save the
111 * results into the array "mergeplans".
114 foreach(lc, node->mergeplans)
116 Plan *initNode = (Plan *) lfirst(lc);
118 mergeplanstates[i] = ExecInitNode(initNode, estate, eflags);
123 * initialize output tuple type
125 ExecAssignResultTypeFromTL(&mergestate->ps);
126 mergestate->ps.ps_ProjInfo = NULL;
129 * initialize sort-key information
131 mergestate->ms_nkeys = node->numCols;
132 mergestate->ms_scankeys = palloc0(sizeof(ScanKeyData) * node->numCols);
134 for (i = 0; i < node->numCols; i++)
140 if (!get_compare_function_for_ordering_op(node->sortOperators[i],
141 &sortFunction, &reverse))
142 elog(ERROR, "operator %u is not a valid ordering operator",
143 node->sortOperators[i]);
145 /* We use btree's conventions for encoding directionality */
149 if (node->nullsFirst[i])
150 flags |= SK_BT_NULLS_FIRST;
153 * We needn't fill in sk_strategy or sk_subtype since these scankeys
154 * will never be passed to an index.
156 ScanKeyEntryInitialize(&mergestate->ms_scankeys[i],
167 * initialize to show we have not run the subplans yet
169 mergestate->ms_heap_size = 0;
170 mergestate->ms_initialized = false;
171 mergestate->ms_last_slot = -1;
176 /* ----------------------------------------------------------------
179 * Handles iteration over multiple subplans.
180 * ----------------------------------------------------------------
183 ExecMergeAppend(MergeAppendState *node)
185 TupleTableSlot *result;
188 if (!node->ms_initialized)
191 * First time through: pull the first tuple from each subplan, and set
194 for (i = 0; i < node->ms_nplans; i++)
196 node->ms_slots[i] = ExecProcNode(node->mergeplans[i]);
197 if (!TupIsNull(node->ms_slots[i]))
198 heap_insert_slot(node, i);
200 node->ms_initialized = true;
205 * Otherwise, pull the next tuple from whichever subplan we returned
206 * from last time, and insert it into the heap. (We could simplify
207 * the logic a bit by doing this before returning from the prior call,
208 * but it's better to not pull tuples until necessary.)
210 i = node->ms_last_slot;
211 node->ms_slots[i] = ExecProcNode(node->mergeplans[i]);
212 if (!TupIsNull(node->ms_slots[i]))
213 heap_insert_slot(node, i);
216 if (node->ms_heap_size > 0)
218 /* Return the topmost heap node, and sift up the remaining nodes */
219 i = node->ms_heap[0];
220 result = node->ms_slots[i];
221 node->ms_last_slot = i;
222 heap_siftup_slot(node);
226 /* All the subplans are exhausted, and so is the heap */
227 result = ExecClearTuple(node->ps.ps_ResultTupleSlot);
234 * Insert a new slot into the heap. The slot must contain a valid tuple.
237 heap_insert_slot(MergeAppendState *node, SlotNumber new_slot)
239 SlotNumber *heap = node->ms_heap;
242 Assert(!TupIsNull(node->ms_slots[new_slot]));
244 j = node->ms_heap_size++; /* j is where the "hole" is */
249 if (heap_compare_slots(node, new_slot, node->ms_heap[i]) >= 0)
258 * Delete the heap top (the slot in heap[0]), and sift up.
261 heap_siftup_slot(MergeAppendState *node)
263 SlotNumber *heap = node->ms_heap;
267 if (--node->ms_heap_size <= 0)
269 n = node->ms_heap_size; /* heap[n] needs to be reinserted */
270 i = 0; /* i is where the "hole" is */
277 if (j + 1 < n && heap_compare_slots(node, heap[j], heap[j + 1]) > 0)
279 if (heap_compare_slots(node, heap[n], heap[j]) <= 0)
288 * Compare the tuples in the two given slots.
291 heap_compare_slots(MergeAppendState *node, SlotNumber slot1, SlotNumber slot2)
293 TupleTableSlot *s1 = node->ms_slots[slot1];
294 TupleTableSlot *s2 = node->ms_slots[slot2];
297 Assert(!TupIsNull(s1));
298 Assert(!TupIsNull(s2));
300 for (nkey = 0; nkey < node->ms_nkeys; nkey++)
302 ScanKey scankey = node->ms_scankeys + nkey;
303 AttrNumber attno = scankey->sk_attno;
310 datum1 = slot_getattr(s1, attno, &isNull1);
311 datum2 = slot_getattr(s2, attno, &isNull2);
316 continue; /* NULL "=" NULL */
317 else if (scankey->sk_flags & SK_BT_NULLS_FIRST)
318 return -1; /* NULL "<" NOT_NULL */
320 return 1; /* NULL ">" NOT_NULL */
324 if (scankey->sk_flags & SK_BT_NULLS_FIRST)
325 return 1; /* NOT_NULL ">" NULL */
327 return -1; /* NOT_NULL "<" NULL */
331 compare = DatumGetInt32(FunctionCall2Coll(&scankey->sk_func,
332 scankey->sk_collation,
336 if (scankey->sk_flags & SK_BT_DESC)
345 /* ----------------------------------------------------------------
348 * Shuts down the subscans of the MergeAppend node.
350 * Returns nothing of interest.
351 * ----------------------------------------------------------------
354 ExecEndMergeAppend(MergeAppendState *node)
356 PlanState **mergeplans;
361 * get information from the node
363 mergeplans = node->mergeplans;
364 nplans = node->ms_nplans;
367 * shut down each of the subscans
369 for (i = 0; i < nplans; i++)
370 ExecEndNode(mergeplans[i]);
374 ExecReScanMergeAppend(MergeAppendState *node)
378 for (i = 0; i < node->ms_nplans; i++)
380 PlanState *subnode = node->mergeplans[i];
383 * ExecReScan doesn't know about my subplans, so I have to do
384 * changed-parameter signaling myself.
386 if (node->ps.chgParam != NULL)
387 UpdateChangedParamSet(subnode, node->ps.chgParam);
390 * If chgParam of subnode is not null then plan will be re-scanned by
391 * first ExecProcNode.
393 if (subnode->chgParam == NULL)
396 node->ms_heap_size = 0;
397 node->ms_initialized = false;
398 node->ms_last_slot = -1;