LCOV - code coverage report
Current view: top level - src/backend/executor - nodeGatherMerge.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 212 216 98.1 %
Date: 2024-04-16 04:11:40 Functions: 14 14 100.0 %
Legend: Lines: hit not hit

          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         320 : 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         320 :     gm_state = makeNode(GatherMergeState);
      80         320 :     gm_state->ps.plan = (Plan *) node;
      81         320 :     gm_state->ps.state = estate;
      82         320 :     gm_state->ps.ExecProcNode = ExecGatherMerge;
      83             : 
      84         320 :     gm_state->initialized = false;
      85         320 :     gm_state->gm_initialized = false;
      86         320 :     gm_state->tuples_needed = -1;
      87             : 
      88             :     /*
      89             :      * Miscellaneous initialization
      90             :      *
      91             :      * create expression context for node
      92             :      */
      93         320 :     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         320 :     outerNode = outerPlan(node);
     105         320 :     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         320 :     gm_state->ps.outeropsset = true;
     114         320 :     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         320 :     tupDesc = ExecGetResultType(outerPlanState(gm_state));
     121         320 :     gm_state->tupDesc = tupDesc;
     122             : 
     123             :     /*
     124             :      * Initialize result type and projection.
     125             :      */
     126         320 :     ExecInitResultTypeTL(&gm_state->ps);
     127         320 :     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         320 :     if (gm_state->ps.ps_ProjInfo == NULL)
     134             :     {
     135         308 :         gm_state->ps.resultopsset = true;
     136         308 :         gm_state->ps.resultopsfixed = false;
     137             :     }
     138             : 
     139             :     /*
     140             :      * initialize sort-key information
     141             :      */
     142         320 :     if (node->numCols)
     143             :     {
     144             :         int         i;
     145             : 
     146         320 :         gm_state->gm_nkeys = node->numCols;
     147         320 :         gm_state->gm_sortkeys =
     148         320 :             palloc0(sizeof(SortSupportData) * node->numCols);
     149             : 
     150         742 :         for (i = 0; i < node->numCols; i++)
     151             :         {
     152         422 :             SortSupport sortKey = gm_state->gm_sortkeys + i;
     153             : 
     154         422 :             sortKey->ssup_cxt = CurrentMemoryContext;
     155         422 :             sortKey->ssup_collation = node->collations[i];
     156         422 :             sortKey->ssup_nulls_first = node->nullsFirst[i];
     157         422 :             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         422 :             sortKey->abbreviate = false;
     164             : 
     165         422 :             PrepareSortSupportFromOrderingOp(node->sortOperators[i], sortKey);
     166             :         }
     167             :     }
     168             : 
     169             :     /* Now allocate the workspace for gather merge */
     170         320 :     gather_merge_setup(gm_state);
     171             : 
     172         320 :     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      254106 : ExecGatherMerge(PlanState *pstate)
     184             : {
     185      254106 :     GatherMergeState *node = castNode(GatherMergeState, pstate);
     186             :     TupleTableSlot *slot;
     187             :     ExprContext *econtext;
     188             : 
     189      254106 :     CHECK_FOR_INTERRUPTS();
     190             : 
     191             :     /*
     192             :      * As with Gather, we don't launch workers until this node is actually
     193             :      * executed.
     194             :      */
     195      254106 :     if (!node->initialized)
     196             :     {
     197         158 :         EState     *estate = node->ps.state;
     198         158 :         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         158 :         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         158 :             if (!node->pei)
     210         128 :                 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         158 :             pcxt = node->pei->pcxt;
     222         158 :             LaunchParallelWorkers(pcxt);
     223             :             /* We save # workers launched for the benefit of EXPLAIN */
     224         158 :             node->nworkers_launched = pcxt->nworkers_launched;
     225             : 
     226             :             /* Set up tuple queue readers to read the results. */
     227         158 :             if (pcxt->nworkers_launched > 0)
     228             :             {
     229         146 :                 ExecParallelCreateReaders(node->pei);
     230             :                 /* Make a working array showing the active readers */
     231         146 :                 node->nreaders = pcxt->nworkers_launched;
     232         146 :                 node->reader = (TupleQueueReader **)
     233         146 :                     palloc(node->nreaders * sizeof(TupleQueueReader *));
     234         146 :                 memcpy(node->reader, node->pei->reader,
     235         146 :                        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         158 :         if (parallel_leader_participation || node->nreaders == 0)
     247         152 :             node->need_to_scan_locally = true;
     248         158 :         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      254106 :     econtext = node->ps.ps_ExprContext;
     256      254106 :     ResetExprContext(econtext);
     257             : 
     258             :     /*
     259             :      * Get next tuple, either from one of our workers, or by running the plan
     260             :      * ourselves.
     261             :      */
     262      254106 :     slot = gather_merge_getnext(node);
     263      254106 :     if (TupIsNull(slot))
     264         128 :         return NULL;
     265             : 
     266             :     /* If no projection is required, we're done. */
     267      253978 :     if (node->ps.ps_ProjInfo == NULL)
     268      253978 :         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         320 : ExecEndGatherMerge(GatherMergeState *node)
     285             : {
     286         320 :     ExecEndNode(outerPlanState(node));  /* let children clean up first */
     287         320 :     ExecShutdownGatherMerge(node);
     288         320 : }
     289             : 
     290             : /* ----------------------------------------------------------------
     291             :  *      ExecShutdownGatherMerge
     292             :  *
     293             :  *      Destroy the setup for parallel workers including parallel context.
     294             :  * ----------------------------------------------------------------
     295             :  */
     296             : void
     297         448 : ExecShutdownGatherMerge(GatherMergeState *node)
     298             : {
     299         448 :     ExecShutdownGatherMergeWorkers(node);
     300             : 
     301             :     /* Now destroy the parallel context. */
     302         448 :     if (node->pei != NULL)
     303             :     {
     304         128 :         ExecParallelCleanup(node->pei);
     305         128 :         node->pei = NULL;
     306             :     }
     307         448 : }
     308             : 
     309             : /* ----------------------------------------------------------------
     310             :  *      ExecShutdownGatherMergeWorkers
     311             :  *
     312             :  *      Stop all the parallel workers.
     313             :  * ----------------------------------------------------------------
     314             :  */
     315             : static void
     316         496 : ExecShutdownGatherMergeWorkers(GatherMergeState *node)
     317             : {
     318         496 :     if (node->pei != NULL)
     319         158 :         ExecParallelFinish(node->pei);
     320             : 
     321             :     /* Flush local copy of reader array */
     322         496 :     if (node->reader)
     323         146 :         pfree(node->reader);
     324         496 :     node->reader = NULL;
     325         496 : }
     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         320 : gather_merge_setup(GatherMergeState *gm_state)
     389             : {
     390         320 :     GatherMerge *gm = castNode(GatherMerge, gm_state->ps.plan);
     391         320 :     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         320 :     gm_state->gm_slots = (TupleTableSlot **)
     404         320 :         palloc0((nreaders + 1) * sizeof(TupleTableSlot *));
     405             : 
     406             :     /* Allocate the tuple slot and tuple array for each worker */
     407         320 :     gm_state->gm_tuple_buffers = (GMReaderTupleBuffer *)
     408         320 :         palloc0(nreaders * sizeof(GMReaderTupleBuffer));
     409             : 
     410        1198 :     for (i = 0; i < nreaders; i++)
     411             :     {
     412             :         /* Allocate the tuple array with length MAX_TUPLE_STORE */
     413        1756 :         gm_state->gm_tuple_buffers[i].tuple =
     414         878 :             (MinimalTuple *) palloc0(sizeof(MinimalTuple) * MAX_TUPLE_STORE);
     415             : 
     416             :         /* Initialize tuple slot for worker */
     417         878 :         gm_state->gm_slots[i + 1] =
     418         878 :             ExecInitExtraTupleSlot(gm_state->ps.state, gm_state->tupDesc,
     419             :                                    &TTSOpsMinimalTuple);
     420             :     }
     421             : 
     422             :     /* Allocate the resources for the merge */
     423         320 :     gm_state->gm_heap = binaryheap_allocate(nreaders + 1,
     424             :                                             heap_compare_slots,
     425             :                                             gm_state);
     426         320 : }
     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         158 : gather_merge_init(GatherMergeState *gm_state)
     437             : {
     438         158 :     int         nreaders = gm_state->nreaders;
     439         158 :     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         158 :     gm_state->gm_slots[0] = NULL;
     447             : 
     448             :     /* Reset the tuple slot and tuple array for each worker */
     449         568 :     for (i = 0; i < nreaders; i++)
     450             :     {
     451             :         /* Reset tuple array to empty */
     452         410 :         gm_state->gm_tuple_buffers[i].nTuples = 0;
     453         410 :         gm_state->gm_tuple_buffers[i].readCounter = 0;
     454             :         /* Reset done flag to not-done */
     455         410 :         gm_state->gm_tuple_buffers[i].done = false;
     456             :         /* Ensure output slot is empty */
     457         410 :         ExecClearTuple(gm_state->gm_slots[i + 1]);
     458             :     }
     459             : 
     460             :     /* Reset binary heap to empty */
     461         158 :     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         304 : reread:
     471        1428 :     for (i = 0; i <= nreaders; i++)
     472             :     {
     473        1124 :         CHECK_FOR_INTERRUPTS();
     474             : 
     475             :         /* skip this source if already known done */
     476        1944 :         if ((i == 0) ? gm_state->need_to_scan_locally :
     477         820 :             !gm_state->gm_tuple_buffers[i - 1].done)
     478             :         {
     479        1102 :             if (TupIsNull(gm_state->gm_slots[i]))
     480             :             {
     481             :                 /* Don't have a tuple yet, try to get one */
     482         962 :                 if (gather_merge_readnext(gm_state, i, nowait))
     483         160 :                     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         714 :     for (i = 1; i <= nreaders; i++)
     499             :     {
     500         556 :         if (!gm_state->gm_tuple_buffers[i - 1].done &&
     501         154 :             TupIsNull(gm_state->gm_slots[i]))
     502             :         {
     503         146 :             nowait = false;
     504         146 :             goto reread;
     505             :         }
     506             :     }
     507             : 
     508             :     /* Now heapify the heap. */
     509         158 :     binaryheap_build(gm_state->gm_heap);
     510             : 
     511         158 :     gm_state->gm_initialized = true;
     512         158 : }
     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         176 : gather_merge_clear_tuples(GatherMergeState *gm_state)
     520             : {
     521             :     int         i;
     522             : 
     523         652 :     for (i = 0; i < gm_state->nreaders; i++)
     524             :     {
     525         476 :         GMReaderTupleBuffer *tuple_buffer = &gm_state->gm_tuple_buffers[i];
     526             : 
     527         476 :         while (tuple_buffer->readCounter < tuple_buffer->nTuples)
     528           0 :             pfree(tuple_buffer->tuple[tuple_buffer->readCounter++]);
     529             : 
     530         476 :         ExecClearTuple(gm_state->gm_slots[i + 1]);
     531             :     }
     532         176 : }
     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      254106 : gather_merge_getnext(GatherMergeState *gm_state)
     541             : {
     542             :     int         i;
     543             : 
     544      254106 :     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         158 :         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      253948 :         i = DatumGetInt32(binaryheap_first(gm_state->gm_heap));
     561             : 
     562      253948 :         if (gather_merge_readnext(gm_state, i, false))
     563      253818 :             binaryheap_replace_first(gm_state->gm_heap, Int32GetDatum(i));
     564             :         else
     565             :         {
     566             :             /* reader exhausted, remove it from heap */
     567         130 :             (void) binaryheap_remove_first(gm_state->gm_heap);
     568             :         }
     569             :     }
     570             : 
     571      254106 :     if (binaryheap_empty(gm_state->gm_heap))
     572             :     {
     573             :         /* All the queues are exhausted, and so is the heap */
     574         128 :         gather_merge_clear_tuples(gm_state);
     575         128 :         return NULL;
     576             :     }
     577             :     else
     578             :     {
     579             :         /* Return next tuple from whichever participant has the leading one */
     580      253978 :         i = DatumGetInt32(binaryheap_first(gm_state->gm_heap));
     581      253978 :         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         156 : 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         156 :     if (reader == 0)
     597         140 :         return;
     598             : 
     599          16 :     tuple_buffer = &gm_state->gm_tuple_buffers[reader - 1];
     600             : 
     601             :     /* If there's nothing in the array, reset the counters to zero. */
     602          16 :     if (tuple_buffer->nTuples == tuple_buffer->readCounter)
     603          16 :         tuple_buffer->nTuples = tuple_buffer->readCounter = 0;
     604             : 
     605             :     /* Try to fill additional slots in the array. */
     606         160 :     for (i = tuple_buffer->nTuples; i < MAX_TUPLE_STORE; i++)
     607             :     {
     608             :         MinimalTuple tuple;
     609             : 
     610         152 :         tuple = gm_readnext_tuple(gm_state,
     611             :                                   reader,
     612             :                                   true,
     613             :                                   &tuple_buffer->done);
     614         152 :         if (!tuple)
     615           8 :             break;
     616         144 :         tuple_buffer->tuple[i] = tuple;
     617         144 :         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      254910 : 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      254910 :     if (reader == 0)
     639             :     {
     640      253940 :         if (gm_state->need_to_scan_locally)
     641             :         {
     642      253940 :             PlanState  *outerPlan = outerPlanState(gm_state);
     643             :             TupleTableSlot *outerTupleSlot;
     644      253940 :             EState     *estate = gm_state->ps.state;
     645             : 
     646             :             /* Install our DSA area while executing the plan. */
     647      253940 :             estate->es_query_dsa = gm_state->pei ? gm_state->pei->area : NULL;
     648      253940 :             outerTupleSlot = ExecProcNode(outerPlan);
     649      253940 :             estate->es_query_dsa = NULL;
     650             : 
     651      253940 :             if (!TupIsNull(outerTupleSlot))
     652             :             {
     653      253818 :                 gm_state->gm_slots[0] = outerTupleSlot;
     654      253818 :                 return true;
     655             :             }
     656             :             /* need_to_scan_locally serves as "done" flag for leader */
     657         122 :             gm_state->need_to_scan_locally = false;
     658             :         }
     659         122 :         return false;
     660             :     }
     661             : 
     662             :     /* Otherwise, check the state of the relevant tuple buffer. */
     663         970 :     tuple_buffer = &gm_state->gm_tuple_buffers[reader - 1];
     664             : 
     665         970 :     if (tuple_buffer->nTuples > tuple_buffer->readCounter)
     666             :     {
     667             :         /* Return any tuple previously read that is still buffered. */
     668         144 :         tup = tuple_buffer->tuple[tuple_buffer->readCounter++];
     669             :     }
     670         826 :     else if (tuple_buffer->done)
     671             :     {
     672             :         /* Reader is known to be exhausted. */
     673           8 :         return false;
     674             :     }
     675             :     else
     676             :     {
     677             :         /* Read and buffer next tuple. */
     678         818 :         tup = gm_readnext_tuple(gm_state,
     679             :                                 reader,
     680             :                                 nowait,
     681             :                                 &tuple_buffer->done);
     682         818 :         if (!tup)
     683         802 :             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          16 :         load_tuple_array(gm_state, reader);
     690             :     }
     691             : 
     692             :     Assert(tup);
     693             : 
     694             :     /* Build the TupleTableSlot for the given tuple */
     695         160 :     ExecStoreMinimalTuple(tup,  /* tuple to store */
     696         160 :                           gm_state->gm_slots[reader],    /* slot in which to
     697             :                                                          * store the tuple */
     698             :                           true);    /* pfree tuple when done with it */
     699             : 
     700         160 :     return true;
     701             : }
     702             : 
     703             : /*
     704             :  * Attempt to read a tuple from given worker.
     705             :  */
     706             : static MinimalTuple
     707         970 : 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         970 :     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         970 :     reader = gm_state->reader[nreader - 1];
     725         970 :     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         970 :     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         146 : heap_compare_slots(Datum a, Datum b, void *arg)
     746             : {
     747         146 :     GatherMergeState *node = (GatherMergeState *) arg;
     748         146 :     SlotNumber  slot1 = DatumGetInt32(a);
     749         146 :     SlotNumber  slot2 = DatumGetInt32(b);
     750             : 
     751         146 :     TupleTableSlot *s1 = node->gm_slots[slot1];
     752         146 :     TupleTableSlot *s2 = node->gm_slots[slot2];
     753             :     int         nkey;
     754             : 
     755             :     Assert(!TupIsNull(s1));
     756             :     Assert(!TupIsNull(s2));
     757             : 
     758         222 :     for (nkey = 0; nkey < node->gm_nkeys; nkey++)
     759             :     {
     760         146 :         SortSupport sortKey = node->gm_sortkeys + nkey;
     761         146 :         AttrNumber  attno = sortKey->ssup_attno;
     762             :         Datum       datum1,
     763             :                     datum2;
     764             :         bool        isNull1,
     765             :                     isNull2;
     766             :         int         compare;
     767             : 
     768         146 :         datum1 = slot_getattr(s1, attno, &isNull1);
     769         146 :         datum2 = slot_getattr(s2, attno, &isNull2);
     770             : 
     771         146 :         compare = ApplySortComparator(datum1, isNull1,
     772             :                                       datum2, isNull2,
     773             :                                       sortKey);
     774         146 :         if (compare != 0)
     775             :         {
     776          70 :             INVERT_COMPARE_RESULT(compare);
     777          70 :             return compare;
     778             :         }
     779             :     }
     780          76 :     return 0;
     781             : }

Generated by: LCOV version 1.14