Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * nodeGatherMerge.c
4 : * Scan a plan in multiple workers, and do order-preserving merge.
5 : *
6 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : * IDENTIFICATION
10 : * src/backend/executor/nodeGatherMerge.c
11 : *
12 : *-------------------------------------------------------------------------
13 : */
14 :
15 : #include "postgres.h"
16 :
17 : #include "executor/executor.h"
18 : #include "executor/execParallel.h"
19 : #include "executor/nodeGatherMerge.h"
20 : #include "executor/tqueue.h"
21 : #include "lib/binaryheap.h"
22 : #include "miscadmin.h"
23 : #include "optimizer/optimizer.h"
24 :
25 : /*
26 : * When we read tuples from workers, it's a good idea to read several at once
27 : * for efficiency when possible: this minimizes context-switching overhead.
28 : * But reading too many at a time wastes memory without improving performance.
29 : * We'll read up to MAX_TUPLE_STORE tuples (in addition to the first one).
30 : */
31 : #define MAX_TUPLE_STORE 10
32 :
33 : /*
34 : * Pending-tuple array for each worker. This holds additional tuples that
35 : * we were able to fetch from the worker, but can't process yet. In addition,
36 : * this struct holds the "done" flag indicating the worker is known to have
37 : * no more tuples. (We do not use this struct for the leader; we don't keep
38 : * any pending tuples for the leader, and the need_to_scan_locally flag serves
39 : * as its "done" indicator.)
40 : */
41 : typedef struct GMReaderTupleBuffer
42 : {
43 : MinimalTuple *tuple; /* array of length MAX_TUPLE_STORE */
44 : int nTuples; /* number of tuples currently stored */
45 : int readCounter; /* index of next tuple to extract */
46 : bool done; /* true if reader is known exhausted */
47 : } GMReaderTupleBuffer;
48 :
49 : static TupleTableSlot *ExecGatherMerge(PlanState *pstate);
50 : static int32 heap_compare_slots(Datum a, Datum b, void *arg);
51 : static TupleTableSlot *gather_merge_getnext(GatherMergeState *gm_state);
52 : static MinimalTuple gm_readnext_tuple(GatherMergeState *gm_state, int nreader,
53 : bool nowait, bool *done);
54 : static void ExecShutdownGatherMergeWorkers(GatherMergeState *node);
55 : static void gather_merge_setup(GatherMergeState *gm_state);
56 : static void gather_merge_init(GatherMergeState *gm_state);
57 : static void gather_merge_clear_tuples(GatherMergeState *gm_state);
58 : static bool gather_merge_readnext(GatherMergeState *gm_state, int reader,
59 : bool nowait);
60 : static void load_tuple_array(GatherMergeState *gm_state, int reader);
61 :
62 : /* ----------------------------------------------------------------
63 : * ExecInitGather
64 : * ----------------------------------------------------------------
65 : */
66 : GatherMergeState *
67 318 : ExecInitGatherMerge(GatherMerge *node, EState *estate, int eflags)
68 : {
69 : GatherMergeState *gm_state;
70 : Plan *outerNode;
71 : TupleDesc tupDesc;
72 :
73 : /* Gather merge node doesn't have innerPlan node. */
74 : Assert(innerPlan(node) == NULL);
75 :
76 : /*
77 : * create state structure
78 : */
79 318 : gm_state = makeNode(GatherMergeState);
80 318 : gm_state->ps.plan = (Plan *) node;
81 318 : gm_state->ps.state = estate;
82 318 : gm_state->ps.ExecProcNode = ExecGatherMerge;
83 :
84 318 : gm_state->initialized = false;
85 318 : gm_state->gm_initialized = false;
86 318 : gm_state->tuples_needed = -1;
87 :
88 : /*
89 : * Miscellaneous initialization
90 : *
91 : * create expression context for node
92 : */
93 318 : ExecAssignExprContext(estate, &gm_state->ps);
94 :
95 : /*
96 : * GatherMerge doesn't support checking a qual (it's always more efficient
97 : * to do it in the child node).
98 : */
99 : Assert(!node->plan.qual);
100 :
101 : /*
102 : * now initialize outer plan
103 : */
104 318 : outerNode = outerPlan(node);
105 318 : outerPlanState(gm_state) = ExecInitNode(outerNode, estate, eflags);
106 :
107 : /*
108 : * Leader may access ExecProcNode result directly (if
109 : * need_to_scan_locally), or from workers via tuple queue. So we can't
110 : * trivially rely on the slot type being fixed for expressions evaluated
111 : * within this node.
112 : */
113 318 : gm_state->ps.outeropsset = true;
114 318 : gm_state->ps.outeropsfixed = false;
115 :
116 : /*
117 : * Store the tuple descriptor into gather merge state, so we can use it
118 : * while initializing the gather merge slots.
119 : */
120 318 : tupDesc = ExecGetResultType(outerPlanState(gm_state));
121 318 : gm_state->tupDesc = tupDesc;
122 :
123 : /*
124 : * Initialize result type and projection.
125 : */
126 318 : ExecInitResultTypeTL(&gm_state->ps);
127 318 : ExecConditionalAssignProjectionInfo(&gm_state->ps, tupDesc, OUTER_VAR);
128 :
129 : /*
130 : * Without projections result slot type is not trivially known, see
131 : * comment above.
132 : */
133 318 : if (gm_state->ps.ps_ProjInfo == NULL)
134 : {
135 306 : gm_state->ps.resultopsset = true;
136 306 : gm_state->ps.resultopsfixed = false;
137 : }
138 :
139 : /*
140 : * initialize sort-key information
141 : */
142 318 : if (node->numCols)
143 : {
144 : int i;
145 :
146 318 : gm_state->gm_nkeys = node->numCols;
147 318 : gm_state->gm_sortkeys =
148 318 : palloc0(sizeof(SortSupportData) * node->numCols);
149 :
150 738 : for (i = 0; i < node->numCols; i++)
151 : {
152 420 : SortSupport sortKey = gm_state->gm_sortkeys + i;
153 :
154 420 : sortKey->ssup_cxt = CurrentMemoryContext;
155 420 : sortKey->ssup_collation = node->collations[i];
156 420 : sortKey->ssup_nulls_first = node->nullsFirst[i];
157 420 : sortKey->ssup_attno = node->sortColIdx[i];
158 :
159 : /*
160 : * We don't perform abbreviated key conversion here, for the same
161 : * reasons that it isn't used in MergeAppend
162 : */
163 420 : sortKey->abbreviate = false;
164 :
165 420 : PrepareSortSupportFromOrderingOp(node->sortOperators[i], sortKey);
166 : }
167 : }
168 :
169 : /* Now allocate the workspace for gather merge */
170 318 : gather_merge_setup(gm_state);
171 :
172 318 : return gm_state;
173 : }
174 :
175 : /* ----------------------------------------------------------------
176 : * ExecGatherMerge(node)
177 : *
178 : * Scans the relation via multiple workers and returns
179 : * the next qualifying tuple.
180 : * ----------------------------------------------------------------
181 : */
182 : static TupleTableSlot *
183 254190 : ExecGatherMerge(PlanState *pstate)
184 : {
185 254190 : GatherMergeState *node = castNode(GatherMergeState, pstate);
186 : TupleTableSlot *slot;
187 : ExprContext *econtext;
188 :
189 254190 : CHECK_FOR_INTERRUPTS();
190 :
191 : /*
192 : * As with Gather, we don't launch workers until this node is actually
193 : * executed.
194 : */
195 254190 : if (!node->initialized)
196 : {
197 156 : EState *estate = node->ps.state;
198 156 : GatherMerge *gm = castNode(GatherMerge, node->ps.plan);
199 :
200 : /*
201 : * Sometimes we might have to run without parallelism; but if parallel
202 : * mode is active then we can try to fire up some workers.
203 : */
204 156 : if (gm->num_workers > 0 && estate->es_use_parallel_mode)
205 : {
206 : ParallelContext *pcxt;
207 :
208 : /* Initialize, or re-initialize, shared state needed by workers. */
209 156 : if (!node->pei)
210 126 : node->pei = ExecInitParallelPlan(outerPlanState(node),
211 : estate,
212 : gm->initParam,
213 : gm->num_workers,
214 : node->tuples_needed);
215 : else
216 30 : ExecParallelReinitialize(outerPlanState(node),
217 30 : node->pei,
218 : gm->initParam);
219 :
220 : /* Try to launch workers. */
221 156 : pcxt = node->pei->pcxt;
222 156 : LaunchParallelWorkers(pcxt);
223 : /* We save # workers launched for the benefit of EXPLAIN */
224 156 : node->nworkers_launched = pcxt->nworkers_launched;
225 :
226 : /* Set up tuple queue readers to read the results. */
227 156 : if (pcxt->nworkers_launched > 0)
228 : {
229 144 : ExecParallelCreateReaders(node->pei);
230 : /* Make a working array showing the active readers */
231 144 : node->nreaders = pcxt->nworkers_launched;
232 144 : node->reader = (TupleQueueReader **)
233 144 : palloc(node->nreaders * sizeof(TupleQueueReader *));
234 144 : memcpy(node->reader, node->pei->reader,
235 144 : node->nreaders * sizeof(TupleQueueReader *));
236 : }
237 : else
238 : {
239 : /* No workers? Then never mind. */
240 12 : node->nreaders = 0;
241 12 : node->reader = NULL;
242 : }
243 : }
244 :
245 : /* allow leader to participate if enabled or no choice */
246 156 : if (parallel_leader_participation || node->nreaders == 0)
247 150 : node->need_to_scan_locally = true;
248 156 : node->initialized = true;
249 : }
250 :
251 : /*
252 : * Reset per-tuple memory context to free any expression evaluation
253 : * storage allocated in the previous tuple cycle.
254 : */
255 254190 : econtext = node->ps.ps_ExprContext;
256 254190 : ResetExprContext(econtext);
257 :
258 : /*
259 : * Get next tuple, either from one of our workers, or by running the plan
260 : * ourselves.
261 : */
262 254190 : slot = gather_merge_getnext(node);
263 254190 : if (TupIsNull(slot))
264 126 : return NULL;
265 :
266 : /* If no projection is required, we're done. */
267 254064 : if (node->ps.ps_ProjInfo == NULL)
268 254064 : return slot;
269 :
270 : /*
271 : * Form the result tuple using ExecProject(), and return it.
272 : */
273 0 : econtext->ecxt_outertuple = slot;
274 0 : return ExecProject(node->ps.ps_ProjInfo);
275 : }
276 :
277 : /* ----------------------------------------------------------------
278 : * ExecEndGatherMerge
279 : *
280 : * frees any storage allocated through C routines.
281 : * ----------------------------------------------------------------
282 : */
283 : void
284 318 : ExecEndGatherMerge(GatherMergeState *node)
285 : {
286 318 : ExecEndNode(outerPlanState(node)); /* let children clean up first */
287 318 : ExecShutdownGatherMerge(node);
288 318 : }
289 :
290 : /* ----------------------------------------------------------------
291 : * ExecShutdownGatherMerge
292 : *
293 : * Destroy the setup for parallel workers including parallel context.
294 : * ----------------------------------------------------------------
295 : */
296 : void
297 444 : ExecShutdownGatherMerge(GatherMergeState *node)
298 : {
299 444 : ExecShutdownGatherMergeWorkers(node);
300 :
301 : /* Now destroy the parallel context. */
302 444 : if (node->pei != NULL)
303 : {
304 126 : ExecParallelCleanup(node->pei);
305 126 : node->pei = NULL;
306 : }
307 444 : }
308 :
309 : /* ----------------------------------------------------------------
310 : * ExecShutdownGatherMergeWorkers
311 : *
312 : * Stop all the parallel workers.
313 : * ----------------------------------------------------------------
314 : */
315 : static void
316 492 : ExecShutdownGatherMergeWorkers(GatherMergeState *node)
317 : {
318 492 : if (node->pei != NULL)
319 156 : ExecParallelFinish(node->pei);
320 :
321 : /* Flush local copy of reader array */
322 492 : if (node->reader)
323 144 : pfree(node->reader);
324 492 : node->reader = NULL;
325 492 : }
326 :
327 : /* ----------------------------------------------------------------
328 : * ExecReScanGatherMerge
329 : *
330 : * Prepare to re-scan the result of a GatherMerge.
331 : * ----------------------------------------------------------------
332 : */
333 : void
334 48 : ExecReScanGatherMerge(GatherMergeState *node)
335 : {
336 48 : GatherMerge *gm = (GatherMerge *) node->ps.plan;
337 48 : PlanState *outerPlan = outerPlanState(node);
338 :
339 : /* Make sure any existing workers are gracefully shut down */
340 48 : ExecShutdownGatherMergeWorkers(node);
341 :
342 : /* Free any unused tuples, so we don't leak memory across rescans */
343 48 : gather_merge_clear_tuples(node);
344 :
345 : /* Mark node so that shared state will be rebuilt at next call */
346 48 : node->initialized = false;
347 48 : node->gm_initialized = false;
348 :
349 : /*
350 : * Set child node's chgParam to tell it that the next scan might deliver a
351 : * different set of rows within the leader process. (The overall rowset
352 : * shouldn't change, but the leader process's subset might; hence nodes
353 : * between here and the parallel table scan node mustn't optimize on the
354 : * assumption of an unchanging rowset.)
355 : */
356 48 : if (gm->rescan_param >= 0)
357 48 : outerPlan->chgParam = bms_add_member(outerPlan->chgParam,
358 : gm->rescan_param);
359 :
360 : /*
361 : * If chgParam of subnode is not null then plan will be re-scanned by
362 : * first ExecProcNode. Note: because this does nothing if we have a
363 : * rescan_param, it's currently guaranteed that parallel-aware child nodes
364 : * will not see a ReScan call until after they get a ReInitializeDSM call.
365 : * That ordering might not be something to rely on, though. A good rule
366 : * of thumb is that ReInitializeDSM should reset only shared state, ReScan
367 : * should reset only local state, and anything that depends on both of
368 : * those steps being finished must wait until the first ExecProcNode call.
369 : */
370 48 : if (outerPlan->chgParam == NULL)
371 0 : ExecReScan(outerPlan);
372 48 : }
373 :
374 : /*
375 : * Set up the data structures that we'll need for Gather Merge.
376 : *
377 : * We allocate these once on the basis of gm->num_workers, which is an
378 : * upper bound for the number of workers we'll actually have. During
379 : * a rescan, we reset the structures to empty. This approach simplifies
380 : * not leaking memory across rescans.
381 : *
382 : * In the gm_slots[] array, index 0 is for the leader, and indexes 1 to n
383 : * are for workers. The values placed into gm_heap correspond to indexes
384 : * in gm_slots[]. The gm_tuple_buffers[] array, however, is indexed from
385 : * 0 to n-1; it has no entry for the leader.
386 : */
387 : static void
388 318 : gather_merge_setup(GatherMergeState *gm_state)
389 : {
390 318 : GatherMerge *gm = castNode(GatherMerge, gm_state->ps.plan);
391 318 : int nreaders = gm->num_workers;
392 : int i;
393 :
394 : /*
395 : * Allocate gm_slots for the number of workers + one more slot for leader.
396 : * Slot 0 is always for the leader. Leader always calls ExecProcNode() to
397 : * read the tuple, and then stores it directly into its gm_slots entry.
398 : * For other slots, code below will call ExecInitExtraTupleSlot() to
399 : * create a slot for the worker's results. Note that during any single
400 : * scan, we might have fewer than num_workers available workers, in which
401 : * case the extra array entries go unused.
402 : */
403 318 : gm_state->gm_slots = (TupleTableSlot **)
404 318 : palloc0((nreaders + 1) * sizeof(TupleTableSlot *));
405 :
406 : /* Allocate the tuple slot and tuple array for each worker */
407 318 : gm_state->gm_tuple_buffers = (GMReaderTupleBuffer *)
408 318 : palloc0(nreaders * sizeof(GMReaderTupleBuffer));
409 :
410 1194 : for (i = 0; i < nreaders; i++)
411 : {
412 : /* Allocate the tuple array with length MAX_TUPLE_STORE */
413 1752 : gm_state->gm_tuple_buffers[i].tuple =
414 876 : (MinimalTuple *) palloc0(sizeof(MinimalTuple) * MAX_TUPLE_STORE);
415 :
416 : /* Initialize tuple slot for worker */
417 876 : gm_state->gm_slots[i + 1] =
418 876 : ExecInitExtraTupleSlot(gm_state->ps.state, gm_state->tupDesc,
419 : &TTSOpsMinimalTuple);
420 : }
421 :
422 : /* Allocate the resources for the merge */
423 318 : gm_state->gm_heap = binaryheap_allocate(nreaders + 1,
424 : heap_compare_slots,
425 : gm_state);
426 318 : }
427 :
428 : /*
429 : * Initialize the Gather Merge.
430 : *
431 : * Reset data structures to ensure they're empty. Then pull at least one
432 : * tuple from leader + each worker (or set its "done" indicator), and set up
433 : * the heap.
434 : */
435 : static void
436 156 : gather_merge_init(GatherMergeState *gm_state)
437 : {
438 156 : int nreaders = gm_state->nreaders;
439 156 : bool nowait = true;
440 : int i;
441 :
442 : /* Assert that gather_merge_setup made enough space */
443 : Assert(nreaders <= castNode(GatherMerge, gm_state->ps.plan)->num_workers);
444 :
445 : /* Reset leader's tuple slot to empty */
446 156 : gm_state->gm_slots[0] = NULL;
447 :
448 : /* Reset the tuple slot and tuple array for each worker */
449 564 : for (i = 0; i < nreaders; i++)
450 : {
451 : /* Reset tuple array to empty */
452 408 : gm_state->gm_tuple_buffers[i].nTuples = 0;
453 408 : gm_state->gm_tuple_buffers[i].readCounter = 0;
454 : /* Reset done flag to not-done */
455 408 : gm_state->gm_tuple_buffers[i].done = false;
456 : /* Ensure output slot is empty */
457 408 : ExecClearTuple(gm_state->gm_slots[i + 1]);
458 : }
459 :
460 : /* Reset binary heap to empty */
461 156 : binaryheap_reset(gm_state->gm_heap);
462 :
463 : /*
464 : * First, try to read a tuple from each worker (including leader) in
465 : * nowait mode. After this, if not all workers were able to produce a
466 : * tuple (or a "done" indication), then re-read from remaining workers,
467 : * this time using wait mode. Add all live readers (those producing at
468 : * least one tuple) to the heap.
469 : */
470 296 : reread:
471 1400 : for (i = 0; i <= nreaders; i++)
472 : {
473 1104 : CHECK_FOR_INTERRUPTS();
474 :
475 : /* skip this source if already known done */
476 1912 : if ((i == 0) ? gm_state->need_to_scan_locally :
477 808 : !gm_state->gm_tuple_buffers[i - 1].done)
478 : {
479 1084 : if (TupIsNull(gm_state->gm_slots[i]))
480 : {
481 : /* Don't have a tuple yet, try to get one */
482 944 : if (gather_merge_readnext(gm_state, i, nowait))
483 168 : binaryheap_add_unordered(gm_state->gm_heap,
484 : Int32GetDatum(i));
485 : }
486 : else
487 : {
488 : /*
489 : * We already got at least one tuple from this worker, but
490 : * might as well see if it has any more ready by now.
491 : */
492 140 : load_tuple_array(gm_state, i);
493 : }
494 : }
495 : }
496 :
497 : /* need not recheck leader, since nowait doesn't matter for it */
498 708 : for (i = 1; i <= nreaders; i++)
499 : {
500 552 : if (!gm_state->gm_tuple_buffers[i - 1].done &&
501 156 : TupIsNull(gm_state->gm_slots[i]))
502 : {
503 140 : nowait = false;
504 140 : goto reread;
505 : }
506 : }
507 :
508 : /* Now heapify the heap. */
509 156 : binaryheap_build(gm_state->gm_heap);
510 :
511 156 : gm_state->gm_initialized = true;
512 156 : }
513 :
514 : /*
515 : * Clear out the tuple table slot, and any unused pending tuples,
516 : * for each gather merge input.
517 : */
518 : static void
519 174 : gather_merge_clear_tuples(GatherMergeState *gm_state)
520 : {
521 : int i;
522 :
523 648 : for (i = 0; i < gm_state->nreaders; i++)
524 : {
525 474 : GMReaderTupleBuffer *tuple_buffer = &gm_state->gm_tuple_buffers[i];
526 :
527 474 : while (tuple_buffer->readCounter < tuple_buffer->nTuples)
528 0 : pfree(tuple_buffer->tuple[tuple_buffer->readCounter++]);
529 :
530 474 : ExecClearTuple(gm_state->gm_slots[i + 1]);
531 : }
532 174 : }
533 :
534 : /*
535 : * Read the next tuple for gather merge.
536 : *
537 : * Fetch the sorted tuple out of the heap.
538 : */
539 : static TupleTableSlot *
540 254190 : gather_merge_getnext(GatherMergeState *gm_state)
541 : {
542 : int i;
543 :
544 254190 : if (!gm_state->gm_initialized)
545 : {
546 : /*
547 : * First time through: pull the first tuple from each participant, and
548 : * set up the heap.
549 : */
550 156 : gather_merge_init(gm_state);
551 : }
552 : else
553 : {
554 : /*
555 : * Otherwise, pull the next tuple from whichever participant we
556 : * returned from last time, and reinsert that participant's index into
557 : * the heap, because it might now compare differently against the
558 : * other elements of the heap.
559 : */
560 254034 : i = DatumGetInt32(binaryheap_first(gm_state->gm_heap));
561 :
562 254034 : if (gather_merge_readnext(gm_state, i, false))
563 253896 : binaryheap_replace_first(gm_state->gm_heap, Int32GetDatum(i));
564 : else
565 : {
566 : /* reader exhausted, remove it from heap */
567 138 : (void) binaryheap_remove_first(gm_state->gm_heap);
568 : }
569 : }
570 :
571 254190 : if (binaryheap_empty(gm_state->gm_heap))
572 : {
573 : /* All the queues are exhausted, and so is the heap */
574 126 : gather_merge_clear_tuples(gm_state);
575 126 : return NULL;
576 : }
577 : else
578 : {
579 : /* Return next tuple from whichever participant has the leading one */
580 254064 : i = DatumGetInt32(binaryheap_first(gm_state->gm_heap));
581 254064 : return gm_state->gm_slots[i];
582 : }
583 : }
584 :
585 : /*
586 : * Read tuple(s) for given reader in nowait mode, and load into its tuple
587 : * array, until we have MAX_TUPLE_STORE of them or would have to block.
588 : */
589 : static void
590 172 : load_tuple_array(GatherMergeState *gm_state, int reader)
591 : {
592 : GMReaderTupleBuffer *tuple_buffer;
593 : int i;
594 :
595 : /* Don't do anything if this is the leader. */
596 172 : if (reader == 0)
597 134 : return;
598 :
599 38 : tuple_buffer = &gm_state->gm_tuple_buffers[reader - 1];
600 :
601 : /* If there's nothing in the array, reset the counters to zero. */
602 38 : if (tuple_buffer->nTuples == tuple_buffer->readCounter)
603 32 : tuple_buffer->nTuples = tuple_buffer->readCounter = 0;
604 :
605 : /* Try to fill additional slots in the array. */
606 294 : for (i = tuple_buffer->nTuples; i < MAX_TUPLE_STORE; i++)
607 : {
608 : MinimalTuple tuple;
609 :
610 274 : tuple = gm_readnext_tuple(gm_state,
611 : reader,
612 : true,
613 : &tuple_buffer->done);
614 274 : if (!tuple)
615 18 : break;
616 256 : tuple_buffer->tuple[i] = tuple;
617 256 : tuple_buffer->nTuples++;
618 : }
619 : }
620 :
621 : /*
622 : * Store the next tuple for a given reader into the appropriate slot.
623 : *
624 : * Returns true if successful, false if not (either reader is exhausted,
625 : * or we didn't want to wait for a tuple). Sets done flag if reader
626 : * is found to be exhausted.
627 : */
628 : static bool
629 254978 : gather_merge_readnext(GatherMergeState *gm_state, int reader, bool nowait)
630 : {
631 : GMReaderTupleBuffer *tuple_buffer;
632 : MinimalTuple tup;
633 :
634 : /*
635 : * If we're being asked to generate a tuple from the leader, then we just
636 : * call ExecProcNode as normal to produce one.
637 : */
638 254978 : if (reader == 0)
639 : {
640 253896 : if (gm_state->need_to_scan_locally)
641 : {
642 253896 : PlanState *outerPlan = outerPlanState(gm_state);
643 : TupleTableSlot *outerTupleSlot;
644 253896 : EState *estate = gm_state->ps.state;
645 :
646 : /* Install our DSA area while executing the plan. */
647 253896 : estate->es_query_dsa = gm_state->pei ? gm_state->pei->area : NULL;
648 253896 : outerTupleSlot = ExecProcNode(outerPlan);
649 253896 : estate->es_query_dsa = NULL;
650 :
651 253896 : if (!TupIsNull(outerTupleSlot))
652 : {
653 253776 : gm_state->gm_slots[0] = outerTupleSlot;
654 253776 : return true;
655 : }
656 : /* need_to_scan_locally serves as "done" flag for leader */
657 120 : gm_state->need_to_scan_locally = false;
658 : }
659 120 : return false;
660 : }
661 :
662 : /* Otherwise, check the state of the relevant tuple buffer. */
663 1082 : tuple_buffer = &gm_state->gm_tuple_buffers[reader - 1];
664 :
665 1082 : if (tuple_buffer->nTuples > tuple_buffer->readCounter)
666 : {
667 : /* Return any tuple previously read that is still buffered. */
668 256 : tup = tuple_buffer->tuple[tuple_buffer->readCounter++];
669 : }
670 826 : else if (tuple_buffer->done)
671 : {
672 : /* Reader is known to be exhausted. */
673 18 : return false;
674 : }
675 : else
676 : {
677 : /* Read and buffer next tuple. */
678 808 : tup = gm_readnext_tuple(gm_state,
679 : reader,
680 : nowait,
681 : &tuple_buffer->done);
682 808 : if (!tup)
683 776 : return false;
684 :
685 : /*
686 : * Attempt to read more tuples in nowait mode and store them in the
687 : * pending-tuple array for the reader.
688 : */
689 32 : load_tuple_array(gm_state, reader);
690 : }
691 :
692 : Assert(tup);
693 :
694 : /* Build the TupleTableSlot for the given tuple */
695 288 : ExecStoreMinimalTuple(tup, /* tuple to store */
696 288 : gm_state->gm_slots[reader], /* slot in which to
697 : * store the tuple */
698 : true); /* pfree tuple when done with it */
699 :
700 288 : return true;
701 : }
702 :
703 : /*
704 : * Attempt to read a tuple from given worker.
705 : */
706 : static MinimalTuple
707 1082 : gm_readnext_tuple(GatherMergeState *gm_state, int nreader, bool nowait,
708 : bool *done)
709 : {
710 : TupleQueueReader *reader;
711 : MinimalTuple tup;
712 :
713 : /* Check for async events, particularly messages from workers. */
714 1082 : CHECK_FOR_INTERRUPTS();
715 :
716 : /*
717 : * Attempt to read a tuple.
718 : *
719 : * Note that TupleQueueReaderNext will just return NULL for a worker which
720 : * fails to initialize. We'll treat that worker as having produced no
721 : * tuples; WaitForParallelWorkersToFinish will error out when we get
722 : * there.
723 : */
724 1082 : reader = gm_state->reader[nreader - 1];
725 1082 : tup = TupleQueueReaderNext(reader, nowait, done);
726 :
727 : /*
728 : * Since we'll be buffering these across multiple calls, we need to make a
729 : * copy.
730 : */
731 1082 : return tup ? heap_copy_minimal_tuple(tup) : NULL;
732 : }
733 :
734 : /*
735 : * We have one slot for each item in the heap array. We use SlotNumber
736 : * to store slot indexes. This doesn't actually provide any formal
737 : * type-safety, but it makes the code more self-documenting.
738 : */
739 : typedef int32 SlotNumber;
740 :
741 : /*
742 : * Compare the tuples in the two given slots.
743 : */
744 : static int32
745 536 : heap_compare_slots(Datum a, Datum b, void *arg)
746 : {
747 536 : GatherMergeState *node = (GatherMergeState *) arg;
748 536 : SlotNumber slot1 = DatumGetInt32(a);
749 536 : SlotNumber slot2 = DatumGetInt32(b);
750 :
751 536 : TupleTableSlot *s1 = node->gm_slots[slot1];
752 536 : TupleTableSlot *s2 = node->gm_slots[slot2];
753 : int nkey;
754 :
755 : Assert(!TupIsNull(s1));
756 : Assert(!TupIsNull(s2));
757 :
758 812 : for (nkey = 0; nkey < node->gm_nkeys; nkey++)
759 : {
760 536 : SortSupport sortKey = node->gm_sortkeys + nkey;
761 536 : AttrNumber attno = sortKey->ssup_attno;
762 : Datum datum1,
763 : datum2;
764 : bool isNull1,
765 : isNull2;
766 : int compare;
767 :
768 536 : datum1 = slot_getattr(s1, attno, &isNull1);
769 536 : datum2 = slot_getattr(s2, attno, &isNull2);
770 :
771 536 : compare = ApplySortComparator(datum1, isNull1,
772 : datum2, isNull2,
773 : sortKey);
774 536 : if (compare != 0)
775 : {
776 260 : INVERT_COMPARE_RESULT(compare);
777 260 : return compare;
778 : }
779 : }
780 276 : return 0;
781 : }
|