LCOV - code coverage report
Current view: top level - src/backend/executor - nodeSubplan.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 408 440 92.7 %
Date: 2019-11-22 08:06:54 Functions: 14 14 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * nodeSubplan.c
       4             :  *    routines to support sub-selects appearing in expressions
       5             :  *
       6             :  * This module is concerned with executing SubPlan expression nodes, which
       7             :  * should not be confused with sub-SELECTs appearing in FROM.  SubPlans are
       8             :  * divided into "initplans", which are those that need only one evaluation per
       9             :  * query (among other restrictions, this requires that they don't use any
      10             :  * direct correlation variables from the parent plan level), and "regular"
      11             :  * subplans, which are re-evaluated every time their result is required.
      12             :  *
      13             :  *
      14             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
      15             :  * Portions Copyright (c) 1994, Regents of the University of California
      16             :  *
      17             :  * IDENTIFICATION
      18             :  *    src/backend/executor/nodeSubplan.c
      19             :  *
      20             :  *-------------------------------------------------------------------------
      21             :  */
      22             : /*
      23             :  *   INTERFACE ROUTINES
      24             :  *      ExecSubPlan  - process a subselect
      25             :  *      ExecInitSubPlan - initialize a subselect
      26             :  */
      27             : #include "postgres.h"
      28             : 
      29             : #include <limits.h>
      30             : #include <math.h>
      31             : 
      32             : #include "access/htup_details.h"
      33             : #include "executor/executor.h"
      34             : #include "executor/nodeSubplan.h"
      35             : #include "miscadmin.h"
      36             : #include "nodes/makefuncs.h"
      37             : #include "nodes/nodeFuncs.h"
      38             : #include "utils/array.h"
      39             : #include "utils/lsyscache.h"
      40             : #include "utils/memutils.h"
      41             : 
      42             : static Datum ExecHashSubPlan(SubPlanState *node,
      43             :                              ExprContext *econtext,
      44             :                              bool *isNull);
      45             : static Datum ExecScanSubPlan(SubPlanState *node,
      46             :                              ExprContext *econtext,
      47             :                              bool *isNull);
      48             : static void buildSubPlanHash(SubPlanState *node, ExprContext *econtext);
      49             : static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot,
      50             :                              FmgrInfo *eqfunctions);
      51             : static bool slotAllNulls(TupleTableSlot *slot);
      52             : static bool slotNoNulls(TupleTableSlot *slot);
      53             : 
      54             : 
      55             : /* ----------------------------------------------------------------
      56             :  *      ExecSubPlan
      57             :  *
      58             :  * This is the main entry point for execution of a regular SubPlan.
      59             :  * ----------------------------------------------------------------
      60             :  */
      61             : Datum
      62     2780420 : ExecSubPlan(SubPlanState *node,
      63             :             ExprContext *econtext,
      64             :             bool *isNull)
      65             : {
      66     2780420 :     SubPlan    *subplan = node->subplan;
      67     2780420 :     EState     *estate = node->planstate->state;
      68     2780420 :     ScanDirection dir = estate->es_direction;
      69             :     Datum       retval;
      70             : 
      71     2780420 :     CHECK_FOR_INTERRUPTS();
      72             : 
      73             :     /* Set non-null as default */
      74     2780420 :     *isNull = false;
      75             : 
      76             :     /* Sanity checks */
      77     2780420 :     if (subplan->subLinkType == CTE_SUBLINK)
      78           0 :         elog(ERROR, "CTE subplans should not be executed via ExecSubPlan");
      79     2780420 :     if (subplan->setParam != NIL && subplan->subLinkType != MULTIEXPR_SUBLINK)
      80           0 :         elog(ERROR, "cannot set parent params from subquery");
      81             : 
      82             :     /* Force forward-scan mode for evaluation */
      83     2780420 :     estate->es_direction = ForwardScanDirection;
      84             : 
      85             :     /* Select appropriate evaluation strategy */
      86     2780420 :     if (subplan->useHashTable)
      87      729758 :         retval = ExecHashSubPlan(node, econtext, isNull);
      88             :     else
      89     2050662 :         retval = ExecScanSubPlan(node, econtext, isNull);
      90             : 
      91             :     /* restore scan direction */
      92     2780416 :     estate->es_direction = dir;
      93             : 
      94     2780416 :     return retval;
      95             : }
      96             : 
      97             : /*
      98             :  * ExecHashSubPlan: store subselect result in an in-memory hash table
      99             :  */
     100             : static Datum
     101      729758 : ExecHashSubPlan(SubPlanState *node,
     102             :                 ExprContext *econtext,
     103             :                 bool *isNull)
     104             : {
     105      729758 :     SubPlan    *subplan = node->subplan;
     106      729758 :     PlanState  *planstate = node->planstate;
     107             :     TupleTableSlot *slot;
     108             : 
     109             :     /* Shouldn't have any direct correlation Vars */
     110      729758 :     if (subplan->parParam != NIL || node->args != NIL)
     111           0 :         elog(ERROR, "hashed subplan with direct correlation not supported");
     112             : 
     113             :     /*
     114             :      * If first time through or we need to rescan the subplan, build the hash
     115             :      * table.
     116             :      */
     117      729758 :     if (node->hashtable == NULL || planstate->chgParam != NULL)
     118         482 :         buildSubPlanHash(node, econtext);
     119             : 
     120             :     /*
     121             :      * The result for an empty subplan is always FALSE; no need to evaluate
     122             :      * lefthand side.
     123             :      */
     124      729754 :     *isNull = false;
     125      729754 :     if (!node->havehashrows && !node->havenullrows)
     126      260344 :         return BoolGetDatum(false);
     127             : 
     128             :     /*
     129             :      * Evaluate lefthand expressions and form a projection tuple. First we
     130             :      * have to set the econtext to use (hack alert!).
     131             :      */
     132      469410 :     node->projLeft->pi_exprContext = econtext;
     133      469410 :     slot = ExecProject(node->projLeft);
     134             : 
     135             :     /*
     136             :      * Note: because we are typically called in a per-tuple context, we have
     137             :      * to explicitly clear the projected tuple before returning. Otherwise,
     138             :      * we'll have a double-free situation: the per-tuple context will probably
     139             :      * be reset before we're called again, and then the tuple slot will think
     140             :      * it still needs to free the tuple.
     141             :      */
     142             : 
     143             :     /*
     144             :      * If the LHS is all non-null, probe for an exact match in the main hash
     145             :      * table.  If we find one, the result is TRUE. Otherwise, scan the
     146             :      * partly-null table to see if there are any rows that aren't provably
     147             :      * unequal to the LHS; if so, the result is UNKNOWN.  (We skip that part
     148             :      * if we don't care about UNKNOWN.) Otherwise, the result is FALSE.
     149             :      *
     150             :      * Note: the reason we can avoid a full scan of the main hash table is
     151             :      * that the combining operators are assumed never to yield NULL when both
     152             :      * inputs are non-null.  If they were to do so, we might need to produce
     153             :      * UNKNOWN instead of FALSE because of an UNKNOWN result in comparing the
     154             :      * LHS to some main-table entry --- which is a comparison we will not even
     155             :      * make, unless there's a chance match of hash keys.
     156             :      */
     157      469410 :     if (slotNoNulls(slot))
     158             :     {
     159      938772 :         if (node->havehashrows &&
     160      469378 :             FindTupleHashEntry(node->hashtable,
     161             :                                slot,
     162             :                                node->cur_eq_comp,
     163             :                                node->lhs_hash_funcs) != NULL)
     164             :         {
     165         786 :             ExecClearTuple(slot);
     166         786 :             return BoolGetDatum(true);
     167             :         }
     168      468624 :         if (node->havenullrows &&
     169          16 :             findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
     170             :         {
     171           8 :             ExecClearTuple(slot);
     172           8 :             *isNull = true;
     173           8 :             return BoolGetDatum(false);
     174             :         }
     175      468600 :         ExecClearTuple(slot);
     176      468600 :         return BoolGetDatum(false);
     177             :     }
     178             : 
     179             :     /*
     180             :      * When the LHS is partly or wholly NULL, we can never return TRUE. If we
     181             :      * don't care about UNKNOWN, just return FALSE.  Otherwise, if the LHS is
     182             :      * wholly NULL, immediately return UNKNOWN.  (Since the combining
     183             :      * operators are strict, the result could only be FALSE if the sub-select
     184             :      * were empty, but we already handled that case.) Otherwise, we must scan
     185             :      * both the main and partly-null tables to see if there are any rows that
     186             :      * aren't provably unequal to the LHS; if so, the result is UNKNOWN.
     187             :      * Otherwise, the result is FALSE.
     188             :      */
     189          16 :     if (node->hashnulls == NULL)
     190             :     {
     191           0 :         ExecClearTuple(slot);
     192           0 :         return BoolGetDatum(false);
     193             :     }
     194          16 :     if (slotAllNulls(slot))
     195             :     {
     196           0 :         ExecClearTuple(slot);
     197           0 :         *isNull = true;
     198           0 :         return BoolGetDatum(false);
     199             :     }
     200             :     /* Scan partly-null table first, since more likely to get a match */
     201          32 :     if (node->havenullrows &&
     202          16 :         findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
     203             :     {
     204           8 :         ExecClearTuple(slot);
     205           8 :         *isNull = true;
     206           8 :         return BoolGetDatum(false);
     207             :     }
     208           8 :     if (node->havehashrows &&
     209           0 :         findPartialMatch(node->hashtable, slot, node->cur_eq_funcs))
     210             :     {
     211           0 :         ExecClearTuple(slot);
     212           0 :         *isNull = true;
     213           0 :         return BoolGetDatum(false);
     214             :     }
     215           8 :     ExecClearTuple(slot);
     216           8 :     return BoolGetDatum(false);
     217             : }
     218             : 
     219             : /*
     220             :  * ExecScanSubPlan: default case where we have to rescan subplan each time
     221             :  */
     222             : static Datum
     223     2050662 : ExecScanSubPlan(SubPlanState *node,
     224             :                 ExprContext *econtext,
     225             :                 bool *isNull)
     226             : {
     227     2050662 :     SubPlan    *subplan = node->subplan;
     228     2050662 :     PlanState  *planstate = node->planstate;
     229     2050662 :     SubLinkType subLinkType = subplan->subLinkType;
     230             :     MemoryContext oldcontext;
     231             :     TupleTableSlot *slot;
     232             :     Datum       result;
     233     2050662 :     bool        found = false;  /* true if got at least one subplan tuple */
     234             :     ListCell   *pvar;
     235             :     ListCell   *l;
     236     2050662 :     ArrayBuildStateAny *astate = NULL;
     237             : 
     238             :     /*
     239             :      * MULTIEXPR subplans, when "executed", just return NULL; but first we
     240             :      * mark the subplan's output parameters as needing recalculation.  (This
     241             :      * is a bit of a hack: it relies on the subplan appearing later in its
     242             :      * targetlist than any of the referencing Params, so that all the Params
     243             :      * have been evaluated before we re-mark them for the next evaluation
     244             :      * cycle.  But in general resjunk tlist items appear after non-resjunk
     245             :      * ones, so this should be safe.)  Unlike ExecReScanSetParamPlan, we do
     246             :      * *not* set bits in the parent plan node's chgParam, because we don't
     247             :      * want to cause a rescan of the parent.
     248             :      */
     249     2050662 :     if (subLinkType == MULTIEXPR_SUBLINK)
     250             :     {
     251          52 :         EState     *estate = node->parent->state;
     252             : 
     253         156 :         foreach(l, subplan->setParam)
     254             :         {
     255         104 :             int         paramid = lfirst_int(l);
     256         104 :             ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
     257             : 
     258         104 :             prm->execPlan = node;
     259             :         }
     260          52 :         *isNull = true;
     261          52 :         return (Datum) 0;
     262             :     }
     263             : 
     264             :     /* Initialize ArrayBuildStateAny in caller's context, if needed */
     265     2050610 :     if (subLinkType == ARRAY_SUBLINK)
     266       22268 :         astate = initArrayResultAny(subplan->firstColType,
     267             :                                     CurrentMemoryContext, true);
     268             : 
     269             :     /*
     270             :      * We are probably in a short-lived expression-evaluation context. Switch
     271             :      * to the per-query context for manipulating the child plan's chgParam,
     272             :      * calling ExecProcNode on it, etc.
     273             :      */
     274     2050610 :     oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
     275             : 
     276             :     /*
     277             :      * Set Params of this plan from parent plan correlation values. (Any
     278             :      * calculation we have to do is done in the parent econtext, since the
     279             :      * Param values don't need to have per-query lifetime.)
     280             :      */
     281             :     Assert(list_length(subplan->parParam) == list_length(node->args));
     282             : 
     283     5520266 :     forboth(l, subplan->parParam, pvar, node->args)
     284             :     {
     285     3469656 :         int         paramid = lfirst_int(l);
     286     3469656 :         ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
     287             : 
     288     3469656 :         prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
     289             :                                                econtext,
     290             :                                                &(prm->isnull));
     291     3469656 :         planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
     292             :     }
     293             : 
     294             :     /*
     295             :      * Now that we've set up its parameters, we can reset the subplan.
     296             :      */
     297     2050610 :     ExecReScan(planstate);
     298             : 
     299             :     /*
     300             :      * For all sublink types except EXPR_SUBLINK and ARRAY_SUBLINK, the result
     301             :      * is boolean as are the results of the combining operators. We combine
     302             :      * results across tuples (if the subplan produces more than one) using OR
     303             :      * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
     304             :      * (ROWCOMPARE_SUBLINK doesn't allow multiple tuples from the subplan.)
     305             :      * NULL results from the combining operators are handled according to the
     306             :      * usual SQL semantics for OR and AND.  The result for no input tuples is
     307             :      * FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
     308             :      * ROWCOMPARE_SUBLINK.
     309             :      *
     310             :      * For EXPR_SUBLINK we require the subplan to produce no more than one
     311             :      * tuple, else an error is raised.  If zero tuples are produced, we return
     312             :      * NULL.  Assuming we get a tuple, we just use its first column (there can
     313             :      * be only one non-junk column in this case).
     314             :      *
     315             :      * For ARRAY_SUBLINK we allow the subplan to produce any number of tuples,
     316             :      * and form an array of the first column's values.  Note in particular
     317             :      * that we produce a zero-element array if no tuples are produced (this is
     318             :      * a change from pre-8.3 behavior of returning NULL).
     319             :      */
     320     2050610 :     result = BoolGetDatum(subLinkType == ALL_SUBLINK);
     321     2050610 :     *isNull = false;
     322             : 
     323     5611990 :     for (slot = ExecProcNode(planstate);
     324     2423176 :          !TupIsNull(slot);
     325     1510770 :          slot = ExecProcNode(planstate))
     326             :     {
     327     1511564 :         TupleDesc   tdesc = slot->tts_tupleDescriptor;
     328             :         Datum       rowresult;
     329             :         bool        rownull;
     330             :         int         col;
     331             :         ListCell   *plst;
     332             : 
     333     1511564 :         if (subLinkType == EXISTS_SUBLINK)
     334             :         {
     335         598 :             found = true;
     336         598 :             result = BoolGetDatum(true);
     337        1392 :             break;
     338             :         }
     339             : 
     340     1510966 :         if (subLinkType == EXPR_SUBLINK)
     341             :         {
     342             :             /* cannot allow multiple input tuples for EXPR sublink */
     343     1507536 :             if (found)
     344           0 :                 ereport(ERROR,
     345             :                         (errcode(ERRCODE_CARDINALITY_VIOLATION),
     346             :                          errmsg("more than one row returned by a subquery used as an expression")));
     347     1507536 :             found = true;
     348             : 
     349             :             /*
     350             :              * We need to copy the subplan's tuple in case the result is of
     351             :              * pass-by-ref type --- our return value will point into this
     352             :              * copied tuple!  Can't use the subplan's instance of the tuple
     353             :              * since it won't still be valid after next ExecProcNode() call.
     354             :              * node->curTuple keeps track of the copied tuple for eventual
     355             :              * freeing.
     356             :              */
     357     1507536 :             if (node->curTuple)
     358     1494752 :                 heap_freetuple(node->curTuple);
     359     1507536 :             node->curTuple = ExecCopySlotHeapTuple(slot);
     360             : 
     361     1507536 :             result = heap_getattr(node->curTuple, 1, tdesc, isNull);
     362             :             /* keep scanning subplan to make sure there's only one tuple */
     363     3017958 :             continue;
     364             :         }
     365             : 
     366        3430 :         if (subLinkType == ARRAY_SUBLINK)
     367             :         {
     368             :             Datum       dvalue;
     369             :             bool        disnull;
     370             : 
     371        2886 :             found = true;
     372             :             /* stash away current value */
     373             :             Assert(subplan->firstColType == TupleDescAttr(tdesc, 0)->atttypid);
     374        2886 :             dvalue = slot_getattr(slot, 1, &disnull);
     375        2886 :             astate = accumArrayResultAny(astate, dvalue, disnull,
     376             :                                          subplan->firstColType, oldcontext);
     377             :             /* keep scanning subplan to collect all values */
     378        2886 :             continue;
     379             :         }
     380             : 
     381             :         /* cannot allow multiple input tuples for ROWCOMPARE sublink either */
     382         544 :         if (subLinkType == ROWCOMPARE_SUBLINK && found)
     383           0 :             ereport(ERROR,
     384             :                     (errcode(ERRCODE_CARDINALITY_VIOLATION),
     385             :                      errmsg("more than one row returned by a subquery used as an expression")));
     386             : 
     387         544 :         found = true;
     388             : 
     389             :         /*
     390             :          * For ALL, ANY, and ROWCOMPARE sublinks, load up the Params
     391             :          * representing the columns of the sub-select, and then evaluate the
     392             :          * combining expression.
     393             :          */
     394         544 :         col = 1;
     395        1088 :         foreach(plst, subplan->paramIds)
     396             :         {
     397         544 :             int         paramid = lfirst_int(plst);
     398             :             ParamExecData *prmdata;
     399             : 
     400         544 :             prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
     401             :             Assert(prmdata->execPlan == NULL);
     402         544 :             prmdata->value = slot_getattr(slot, col, &(prmdata->isnull));
     403         544 :             col++;
     404             :         }
     405             : 
     406         544 :         rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext,
     407             :                                               &rownull);
     408             : 
     409         544 :         if (subLinkType == ANY_SUBLINK)
     410             :         {
     411             :             /* combine across rows per OR semantics */
     412         484 :             if (rownull)
     413          12 :                 *isNull = true;
     414         472 :             else if (DatumGetBool(rowresult))
     415             :             {
     416         180 :                 result = BoolGetDatum(true);
     417         180 :                 *isNull = false;
     418         180 :                 break;          /* needn't look at any more rows */
     419             :             }
     420             :         }
     421          60 :         else if (subLinkType == ALL_SUBLINK)
     422             :         {
     423             :             /* combine across rows per AND semantics */
     424          60 :             if (rownull)
     425           0 :                 *isNull = true;
     426          60 :             else if (!DatumGetBool(rowresult))
     427             :             {
     428          16 :                 result = BoolGetDatum(false);
     429          16 :                 *isNull = false;
     430          16 :                 break;          /* needn't look at any more rows */
     431             :             }
     432             :         }
     433             :         else
     434             :         {
     435             :             /* must be ROWCOMPARE_SUBLINK */
     436           0 :             result = rowresult;
     437           0 :             *isNull = rownull;
     438             :         }
     439             :     }
     440             : 
     441     2050610 :     MemoryContextSwitchTo(oldcontext);
     442             : 
     443     2050610 :     if (subLinkType == ARRAY_SUBLINK)
     444             :     {
     445             :         /* We return the result in the caller's context */
     446       22268 :         result = makeArrayResultAny(astate, oldcontext, true);
     447             :     }
     448     2028342 :     else if (!found)
     449             :     {
     450             :         /*
     451             :          * deal with empty subplan result.  result/isNull were previously
     452             :          * initialized correctly for all sublink types except EXPR and
     453             :          * ROWCOMPARE; for those, return NULL.
     454             :          */
     455      519880 :         if (subLinkType == EXPR_SUBLINK ||
     456             :             subLinkType == ROWCOMPARE_SUBLINK)
     457             :         {
     458       42654 :             result = (Datum) 0;
     459       42654 :             *isNull = true;
     460             :         }
     461             :     }
     462             : 
     463     2050610 :     return result;
     464             : }
     465             : 
     466             : /*
     467             :  * buildSubPlanHash: load hash table by scanning subplan output.
     468             :  */
     469             : static void
     470         482 : buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
     471             : {
     472         482 :     SubPlan    *subplan = node->subplan;
     473         482 :     PlanState  *planstate = node->planstate;
     474         482 :     int         ncols = list_length(subplan->paramIds);
     475         482 :     ExprContext *innerecontext = node->innerecontext;
     476             :     MemoryContext oldcontext;
     477             :     long        nbuckets;
     478             :     TupleTableSlot *slot;
     479             : 
     480             :     Assert(subplan->subLinkType == ANY_SUBLINK);
     481             : 
     482             :     /*
     483             :      * If we already had any hash tables, reset 'em; otherwise create empty
     484             :      * hash table(s).
     485             :      *
     486             :      * If we need to distinguish accurately between FALSE and UNKNOWN (i.e.,
     487             :      * NULL) results of the IN operation, then we have to store subplan output
     488             :      * rows that are partly or wholly NULL.  We store such rows in a separate
     489             :      * hash table that we expect will be much smaller than the main table. (We
     490             :      * can use hashing to eliminate partly-null rows that are not distinct. We
     491             :      * keep them separate to minimize the cost of the inevitable full-table
     492             :      * searches; see findPartialMatch.)
     493             :      *
     494             :      * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't
     495             :      * need to store subplan output rows that contain NULL.
     496             :      */
     497         482 :     MemoryContextReset(node->hashtablecxt);
     498         482 :     node->hashtable = NULL;
     499         482 :     node->hashnulls = NULL;
     500         482 :     node->havehashrows = false;
     501         482 :     node->havenullrows = false;
     502             : 
     503         482 :     nbuckets = (long) Min(planstate->plan->plan_rows, (double) LONG_MAX);
     504         482 :     if (nbuckets < 1)
     505           0 :         nbuckets = 1;
     506             : 
     507         482 :     if (node->hashtable)
     508           0 :         ResetTupleHashTable(node->hashtable);
     509             :     else
     510        1446 :         node->hashtable = BuildTupleHashTableExt(node->parent,
     511             :                                                  node->descRight,
     512             :                                                  ncols,
     513             :                                                  node->keyColIdx,
     514         482 :                                                  node->tab_eq_funcoids,
     515             :                                                  node->tab_hash_funcs,
     516             :                                                  node->tab_collations,
     517             :                                                  nbuckets,
     518             :                                                  0,
     519         482 :                                                  node->planstate->state->es_query_cxt,
     520             :                                                  node->hashtablecxt,
     521             :                                                  node->hashtempcxt,
     522             :                                                  false);
     523             : 
     524         482 :     if (!subplan->unknownEqFalse)
     525             :     {
     526          72 :         if (ncols == 1)
     527          44 :             nbuckets = 1;       /* there can only be one entry */
     528             :         else
     529             :         {
     530          28 :             nbuckets /= 16;
     531          28 :             if (nbuckets < 1)
     532           0 :                 nbuckets = 1;
     533             :         }
     534             : 
     535          72 :         if (node->hashnulls)
     536           0 :             ResetTupleHashTable(node->hashtable);
     537             :         else
     538         216 :             node->hashnulls = BuildTupleHashTableExt(node->parent,
     539             :                                                      node->descRight,
     540             :                                                      ncols,
     541             :                                                      node->keyColIdx,
     542          72 :                                                      node->tab_eq_funcoids,
     543             :                                                      node->tab_hash_funcs,
     544             :                                                      node->tab_collations,
     545             :                                                      nbuckets,
     546             :                                                      0,
     547          72 :                                                      node->planstate->state->es_query_cxt,
     548             :                                                      node->hashtablecxt,
     549             :                                                      node->hashtempcxt,
     550             :                                                      false);
     551             :     }
     552             : 
     553             :     /*
     554             :      * We are probably in a short-lived expression-evaluation context. Switch
     555             :      * to the per-query context for manipulating the child plan.
     556             :      */
     557         482 :     oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
     558             : 
     559             :     /*
     560             :      * Reset subplan to start.
     561             :      */
     562         482 :     ExecReScan(planstate);
     563             : 
     564             :     /*
     565             :      * Scan the subplan and load the hash table(s).  Note that when there are
     566             :      * duplicate rows coming out of the sub-select, only one copy is stored.
     567             :      */
     568       80418 :     for (slot = ExecProcNode(planstate);
     569       79896 :          !TupIsNull(slot);
     570       79454 :          slot = ExecProcNode(planstate))
     571             :     {
     572       79458 :         int         col = 1;
     573             :         ListCell   *plst;
     574             :         bool        isnew;
     575             : 
     576             :         /*
     577             :          * Load up the Params representing the raw sub-select outputs, then
     578             :          * form the projection tuple to store in the hashtable.
     579             :          */
     580      194932 :         foreach(plst, subplan->paramIds)
     581             :         {
     582      115474 :             int         paramid = lfirst_int(plst);
     583             :             ParamExecData *prmdata;
     584             : 
     585      115474 :             prmdata = &(innerecontext->ecxt_param_exec_vals[paramid]);
     586             :             Assert(prmdata->execPlan == NULL);
     587      115474 :             prmdata->value = slot_getattr(slot, col,
     588             :                                           &(prmdata->isnull));
     589      115474 :             col++;
     590             :         }
     591       79458 :         slot = ExecProject(node->projRight);
     592             : 
     593             :         /*
     594             :          * If result contains any nulls, store separately or not at all.
     595             :          */
     596       79458 :         if (slotNoNulls(slot))
     597             :         {
     598       79446 :             (void) LookupTupleHashEntry(node->hashtable, slot, &isnew);
     599       79442 :             node->havehashrows = true;
     600             :         }
     601          12 :         else if (node->hashnulls)
     602             :         {
     603          12 :             (void) LookupTupleHashEntry(node->hashnulls, slot, &isnew);
     604          12 :             node->havenullrows = true;
     605             :         }
     606             : 
     607             :         /*
     608             :          * Reset innerecontext after each inner tuple to free any memory used
     609             :          * during ExecProject.
     610             :          */
     611       79454 :         ResetExprContext(innerecontext);
     612             :     }
     613             : 
     614             :     /*
     615             :      * Since the projected tuples are in the sub-query's context and not the
     616             :      * main context, we'd better clear the tuple slot before there's any
     617             :      * chance of a reset of the sub-query's context.  Else we will have the
     618             :      * potential for a double free attempt.  (XXX possibly no longer needed,
     619             :      * but can't hurt.)
     620             :      */
     621         478 :     ExecClearTuple(node->projRight->pi_state.resultslot);
     622             : 
     623         478 :     MemoryContextSwitchTo(oldcontext);
     624         478 : }
     625             : 
     626             : /*
     627             :  * execTuplesUnequal
     628             :  *      Return true if two tuples are definitely unequal in the indicated
     629             :  *      fields.
     630             :  *
     631             :  * Nulls are neither equal nor unequal to anything else.  A true result
     632             :  * is obtained only if there are non-null fields that compare not-equal.
     633             :  *
     634             :  * slot1, slot2: the tuples to compare (must have same columns!)
     635             :  * numCols: the number of attributes to be examined
     636             :  * matchColIdx: array of attribute column numbers
     637             :  * eqFunctions: array of fmgr lookup info for the equality functions to use
     638             :  * evalContext: short-term memory context for executing the functions
     639             :  */
     640             : static bool
     641          32 : execTuplesUnequal(TupleTableSlot *slot1,
     642             :                   TupleTableSlot *slot2,
     643             :                   int numCols,
     644             :                   AttrNumber *matchColIdx,
     645             :                   FmgrInfo *eqfunctions,
     646             :                   const Oid *collations,
     647             :                   MemoryContext evalContext)
     648             : {
     649             :     MemoryContext oldContext;
     650             :     bool        result;
     651             :     int         i;
     652             : 
     653             :     /* Reset and switch into the temp context. */
     654          32 :     MemoryContextReset(evalContext);
     655          32 :     oldContext = MemoryContextSwitchTo(evalContext);
     656             : 
     657             :     /*
     658             :      * We cannot report a match without checking all the fields, but we can
     659             :      * report a non-match as soon as we find unequal fields.  So, start
     660             :      * comparing at the last field (least significant sort key). That's the
     661             :      * most likely to be different if we are dealing with sorted input.
     662             :      */
     663          32 :     result = false;
     664             : 
     665         112 :     for (i = numCols; --i >= 0;)
     666             :     {
     667          64 :         AttrNumber  att = matchColIdx[i];
     668             :         Datum       attr1,
     669             :                     attr2;
     670             :         bool        isNull1,
     671             :                     isNull2;
     672             : 
     673          64 :         attr1 = slot_getattr(slot1, att, &isNull1);
     674             : 
     675          64 :         if (isNull1)
     676          48 :             continue;           /* can't prove anything here */
     677             : 
     678          48 :         attr2 = slot_getattr(slot2, att, &isNull2);
     679             : 
     680          48 :         if (isNull2)
     681          16 :             continue;           /* can't prove anything here */
     682             : 
     683             :         /* Apply the type-specific equality function */
     684          32 :         if (!DatumGetBool(FunctionCall2Coll(&eqfunctions[i],
     685             :                                             collations[i],
     686             :                                             attr1, attr2)))
     687             :         {
     688          16 :             result = true;      /* they are unequal */
     689          16 :             break;
     690             :         }
     691             :     }
     692             : 
     693          32 :     MemoryContextSwitchTo(oldContext);
     694             : 
     695          32 :     return result;
     696             : }
     697             : 
     698             : /*
     699             :  * findPartialMatch: does the hashtable contain an entry that is not
     700             :  * provably distinct from the tuple?
     701             :  *
     702             :  * We have to scan the whole hashtable; we can't usefully use hashkeys
     703             :  * to guide probing, since we might get partial matches on tuples with
     704             :  * hashkeys quite unrelated to what we'd get from the given tuple.
     705             :  *
     706             :  * Caller must provide the equality functions to use, since in cross-type
     707             :  * cases these are different from the hashtable's internal functions.
     708             :  */
     709             : static bool
     710          32 : findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot,
     711             :                  FmgrInfo *eqfunctions)
     712             : {
     713          32 :     int         numCols = hashtable->numCols;
     714          32 :     AttrNumber *keyColIdx = hashtable->keyColIdx;
     715             :     TupleHashIterator hashiter;
     716             :     TupleHashEntry entry;
     717             : 
     718          32 :     InitTupleHashIterator(hashtable, &hashiter);
     719          32 :     while ((entry = ScanTupleHashTable(hashtable, &hashiter)) != NULL)
     720             :     {
     721          32 :         CHECK_FOR_INTERRUPTS();
     722             : 
     723          32 :         ExecStoreMinimalTuple(entry->firstTuple, hashtable->tableslot, false);
     724          64 :         if (!execTuplesUnequal(slot, hashtable->tableslot,
     725             :                                numCols, keyColIdx,
     726             :                                eqfunctions,
     727          32 :                                hashtable->tab_collations,
     728             :                                hashtable->tempcxt))
     729             :         {
     730             :             TermTupleHashIterator(&hashiter);
     731          16 :             return true;
     732             :         }
     733             :     }
     734             :     /* No TermTupleHashIterator call needed here */
     735          16 :     return false;
     736             : }
     737             : 
     738             : /*
     739             :  * slotAllNulls: is the slot completely NULL?
     740             :  *
     741             :  * This does not test for dropped columns, which is OK because we only
     742             :  * use it on projected tuples.
     743             :  */
     744             : static bool
     745          16 : slotAllNulls(TupleTableSlot *slot)
     746             : {
     747          16 :     int         ncols = slot->tts_tupleDescriptor->natts;
     748             :     int         i;
     749             : 
     750          16 :     for (i = 1; i <= ncols; i++)
     751             :     {
     752          16 :         if (!slot_attisnull(slot, i))
     753          16 :             return false;
     754             :     }
     755           0 :     return true;
     756             : }
     757             : 
     758             : /*
     759             :  * slotNoNulls: is the slot entirely not NULL?
     760             :  *
     761             :  * This does not test for dropped columns, which is OK because we only
     762             :  * use it on projected tuples.
     763             :  */
     764             : static bool
     765      548868 : slotNoNulls(TupleTableSlot *slot)
     766             : {
     767      548868 :     int         ncols = slot->tts_tupleDescriptor->natts;
     768             :     int         i;
     769             : 
     770     1173804 :     for (i = 1; i <= ncols; i++)
     771             :     {
     772      624964 :         if (slot_attisnull(slot, i))
     773          28 :             return false;
     774             :     }
     775      548840 :     return true;
     776             : }
     777             : 
     778             : /* ----------------------------------------------------------------
     779             :  *      ExecInitSubPlan
     780             :  *
     781             :  * Create a SubPlanState for a SubPlan; this is the SubPlan-specific part
     782             :  * of ExecInitExpr().  We split it out so that it can be used for InitPlans
     783             :  * as well as regular SubPlans.  Note that we don't link the SubPlan into
     784             :  * the parent's subPlan list, because that shouldn't happen for InitPlans.
     785             :  * Instead, ExecInitExpr() does that one part.
     786             :  * ----------------------------------------------------------------
     787             :  */
     788             : SubPlanState *
     789       49760 : ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
     790             : {
     791       49760 :     SubPlanState *sstate = makeNode(SubPlanState);
     792       49760 :     EState     *estate = parent->state;
     793             : 
     794       49760 :     sstate->subplan = subplan;
     795             : 
     796             :     /* Link the SubPlanState to already-initialized subplan */
     797       49760 :     sstate->planstate = (PlanState *) list_nth(estate->es_subplanstates,
     798       49760 :                                                subplan->plan_id - 1);
     799             : 
     800             :     /* ... and to its parent's state */
     801       49760 :     sstate->parent = parent;
     802             : 
     803             :     /* Initialize subexpressions */
     804       49760 :     sstate->testexpr = ExecInitExpr((Expr *) subplan->testexpr, parent);
     805       49760 :     sstate->args = ExecInitExprList(subplan->args, parent);
     806             : 
     807             :     /*
     808             :      * initialize my state
     809             :      */
     810       49760 :     sstate->curTuple = NULL;
     811       49760 :     sstate->curArray = PointerGetDatum(NULL);
     812       49760 :     sstate->projLeft = NULL;
     813       49760 :     sstate->projRight = NULL;
     814       49760 :     sstate->hashtable = NULL;
     815       49760 :     sstate->hashnulls = NULL;
     816       49760 :     sstate->hashtablecxt = NULL;
     817       49760 :     sstate->hashtempcxt = NULL;
     818       49760 :     sstate->innerecontext = NULL;
     819       49760 :     sstate->keyColIdx = NULL;
     820       49760 :     sstate->tab_eq_funcoids = NULL;
     821       49760 :     sstate->tab_hash_funcs = NULL;
     822       49760 :     sstate->tab_eq_funcs = NULL;
     823       49760 :     sstate->tab_collations = NULL;
     824       49760 :     sstate->lhs_hash_funcs = NULL;
     825       49760 :     sstate->cur_eq_funcs = NULL;
     826             : 
     827             :     /*
     828             :      * If this is an initplan or MULTIEXPR subplan, it has output parameters
     829             :      * that the parent plan will use, so mark those parameters as needing
     830             :      * evaluation.  We don't actually run the subplan until we first need one
     831             :      * of its outputs.
     832             :      *
     833             :      * A CTE subplan's output parameter is never to be evaluated in the normal
     834             :      * way, so skip this in that case.
     835             :      *
     836             :      * Note that we don't set parent->chgParam here: the parent plan hasn't
     837             :      * been run yet, so no need to force it to re-run.
     838             :      */
     839       49760 :     if (subplan->setParam != NIL && subplan->subLinkType != CTE_SUBLINK)
     840             :     {
     841             :         ListCell   *lst;
     842             : 
     843       24308 :         foreach(lst, subplan->setParam)
     844             :         {
     845       12180 :             int         paramid = lfirst_int(lst);
     846       12180 :             ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
     847             : 
     848       12180 :             prm->execPlan = sstate;
     849             :         }
     850             :     }
     851             : 
     852             :     /*
     853             :      * If we are going to hash the subquery output, initialize relevant stuff.
     854             :      * (We don't create the hashtable until needed, though.)
     855             :      */
     856       49760 :     if (subplan->useHashTable)
     857             :     {
     858             :         int         ncols,
     859             :                     i;
     860             :         TupleDesc   tupDescLeft;
     861             :         TupleDesc   tupDescRight;
     862             :         Oid        *cross_eq_funcoids;
     863             :         TupleTableSlot *slot;
     864             :         List       *oplist,
     865             :                    *lefttlist,
     866             :                    *righttlist;
     867             :         ListCell   *l;
     868             : 
     869             :         /* We need a memory context to hold the hash table(s) */
     870        1340 :         sstate->hashtablecxt =
     871        1340 :             AllocSetContextCreate(CurrentMemoryContext,
     872             :                                   "Subplan HashTable Context",
     873             :                                   ALLOCSET_DEFAULT_SIZES);
     874             :         /* and a small one for the hash tables to use as temp storage */
     875        1340 :         sstate->hashtempcxt =
     876        1340 :             AllocSetContextCreate(CurrentMemoryContext,
     877             :                                   "Subplan HashTable Temp Context",
     878             :                                   ALLOCSET_SMALL_SIZES);
     879             :         /* and a short-lived exprcontext for function evaluation */
     880        1340 :         sstate->innerecontext = CreateExprContext(estate);
     881             :         /* Silly little array of column numbers 1..n */
     882        1340 :         ncols = list_length(subplan->paramIds);
     883        1340 :         sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
     884        3192 :         for (i = 0; i < ncols; i++)
     885        1852 :             sstate->keyColIdx[i] = i + 1;
     886             : 
     887             :         /*
     888             :          * We use ExecProject to evaluate the lefthand and righthand
     889             :          * expression lists and form tuples.  (You might think that we could
     890             :          * use the sub-select's output tuples directly, but that is not the
     891             :          * case if we had to insert any run-time coercions of the sub-select's
     892             :          * output datatypes; anyway this avoids storing any resjunk columns
     893             :          * that might be in the sub-select's output.)  Run through the
     894             :          * combining expressions to build tlists for the lefthand and
     895             :          * righthand sides.
     896             :          *
     897             :          * We also extract the combining operators themselves to initialize
     898             :          * the equality and hashing functions for the hash tables.
     899             :          */
     900        1340 :         if (IsA(subplan->testexpr, OpExpr))
     901             :         {
     902             :             /* single combining operator */
     903         828 :             oplist = list_make1(subplan->testexpr);
     904             :         }
     905         512 :         else if (is_andclause(subplan->testexpr))
     906             :         {
     907             :             /* multiple combining operators */
     908         512 :             oplist = castNode(BoolExpr, subplan->testexpr)->args;
     909             :         }
     910             :         else
     911             :         {
     912             :             /* shouldn't see anything else in a hashable subplan */
     913           0 :             elog(ERROR, "unrecognized testexpr type: %d",
     914             :                  (int) nodeTag(subplan->testexpr));
     915             :             oplist = NIL;       /* keep compiler quiet */
     916             :         }
     917             :         Assert(list_length(oplist) == ncols);
     918             : 
     919        1340 :         lefttlist = righttlist = NIL;
     920        1340 :         sstate->tab_eq_funcoids = (Oid *) palloc(ncols * sizeof(Oid));
     921        1340 :         sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
     922        1340 :         sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
     923        1340 :         sstate->tab_collations = (Oid *) palloc(ncols * sizeof(Oid));
     924        1340 :         sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
     925        1340 :         sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
     926             :         /* we'll need the cross-type equality fns below, but not in sstate */
     927        1340 :         cross_eq_funcoids = (Oid *) palloc(ncols * sizeof(Oid));
     928             : 
     929        1340 :         i = 1;
     930        3192 :         foreach(l, oplist)
     931             :         {
     932        1852 :             OpExpr     *opexpr = lfirst_node(OpExpr, l);
     933             :             Expr       *expr;
     934             :             TargetEntry *tle;
     935             :             Oid         rhs_eq_oper;
     936             :             Oid         left_hashfn;
     937             :             Oid         right_hashfn;
     938             : 
     939             :             Assert(list_length(opexpr->args) == 2);
     940             : 
     941             :             /* Process lefthand argument */
     942        1852 :             expr = (Expr *) linitial(opexpr->args);
     943        1852 :             tle = makeTargetEntry(expr,
     944             :                                   i,
     945             :                                   NULL,
     946             :                                   false);
     947        1852 :             lefttlist = lappend(lefttlist, tle);
     948             : 
     949             :             /* Process righthand argument */
     950        1852 :             expr = (Expr *) lsecond(opexpr->args);
     951        1852 :             tle = makeTargetEntry(expr,
     952             :                                   i,
     953             :                                   NULL,
     954             :                                   false);
     955        1852 :             righttlist = lappend(righttlist, tle);
     956             : 
     957             :             /* Lookup the equality function (potentially cross-type) */
     958        1852 :             cross_eq_funcoids[i - 1] = opexpr->opfuncid;
     959        1852 :             fmgr_info(opexpr->opfuncid, &sstate->cur_eq_funcs[i - 1]);
     960        1852 :             fmgr_info_set_expr((Node *) opexpr, &sstate->cur_eq_funcs[i - 1]);
     961             : 
     962             :             /* Look up the equality function for the RHS type */
     963        1852 :             if (!get_compatible_hash_operators(opexpr->opno,
     964             :                                                NULL, &rhs_eq_oper))
     965           0 :                 elog(ERROR, "could not find compatible hash operator for operator %u",
     966             :                      opexpr->opno);
     967        1852 :             sstate->tab_eq_funcoids[i - 1] = get_opcode(rhs_eq_oper);
     968        1852 :             fmgr_info(sstate->tab_eq_funcoids[i - 1],
     969        1852 :                       &sstate->tab_eq_funcs[i - 1]);
     970             : 
     971             :             /* Lookup the associated hash functions */
     972        1852 :             if (!get_op_hash_functions(opexpr->opno,
     973             :                                        &left_hashfn, &right_hashfn))
     974           0 :                 elog(ERROR, "could not find hash function for hash operator %u",
     975             :                      opexpr->opno);
     976        1852 :             fmgr_info(left_hashfn, &sstate->lhs_hash_funcs[i - 1]);
     977        1852 :             fmgr_info(right_hashfn, &sstate->tab_hash_funcs[i - 1]);
     978             : 
     979             :             /* Set collation */
     980        1852 :             sstate->tab_collations[i - 1] = opexpr->inputcollid;
     981             : 
     982        1852 :             i++;
     983             :         }
     984             : 
     985             :         /*
     986             :          * Construct tupdescs, slots and projection nodes for left and right
     987             :          * sides.  The lefthand expressions will be evaluated in the parent
     988             :          * plan node's exprcontext, which we don't have access to here.
     989             :          * Fortunately we can just pass NULL for now and fill it in later
     990             :          * (hack alert!).  The righthand expressions will be evaluated in our
     991             :          * own innerecontext.
     992             :          */
     993        1340 :         tupDescLeft = ExecTypeFromTL(lefttlist);
     994        1340 :         slot = ExecInitExtraTupleSlot(estate, tupDescLeft, &TTSOpsVirtual);
     995        1340 :         sstate->projLeft = ExecBuildProjectionInfo(lefttlist,
     996             :                                                    NULL,
     997             :                                                    slot,
     998             :                                                    parent,
     999             :                                                    NULL);
    1000             : 
    1001        1340 :         sstate->descRight = tupDescRight = ExecTypeFromTL(righttlist);
    1002        1340 :         slot = ExecInitExtraTupleSlot(estate, tupDescRight, &TTSOpsVirtual);
    1003        1340 :         sstate->projRight = ExecBuildProjectionInfo(righttlist,
    1004             :                                                     sstate->innerecontext,
    1005             :                                                     slot,
    1006        1340 :                                                     sstate->planstate,
    1007             :                                                     NULL);
    1008             : 
    1009             :         /*
    1010             :          * Create comparator for lookups of rows in the table (potentially
    1011             :          * cross-type comparisons).
    1012             :          */
    1013        1340 :         sstate->cur_eq_comp = ExecBuildGroupingEqual(tupDescLeft, tupDescRight,
    1014             :                                                      &TTSOpsVirtual, &TTSOpsMinimalTuple,
    1015             :                                                      ncols,
    1016        1340 :                                                      sstate->keyColIdx,
    1017             :                                                      cross_eq_funcoids,
    1018        1340 :                                                      sstate->tab_collations,
    1019             :                                                      parent);
    1020             :     }
    1021             : 
    1022       49760 :     return sstate;
    1023             : }
    1024             : 
    1025             : /* ----------------------------------------------------------------
    1026             :  *      ExecSetParamPlan
    1027             :  *
    1028             :  *      Executes a subplan and sets its output parameters.
    1029             :  *
    1030             :  * This is called from ExecEvalParamExec() when the value of a PARAM_EXEC
    1031             :  * parameter is requested and the param's execPlan field is set (indicating
    1032             :  * that the param has not yet been evaluated).  This allows lazy evaluation
    1033             :  * of initplans: we don't run the subplan until/unless we need its output.
    1034             :  * Note that this routine MUST clear the execPlan fields of the plan's
    1035             :  * output parameters after evaluating them!
    1036             :  *
    1037             :  * The results of this function are stored in the EState associated with the
    1038             :  * ExprContext (particularly, its ecxt_param_exec_vals); any pass-by-ref
    1039             :  * result Datums are allocated in the EState's per-query memory.  The passed
    1040             :  * econtext can be any ExprContext belonging to that EState; which one is
    1041             :  * important only to the extent that the ExprContext's per-tuple memory
    1042             :  * context is used to evaluate any parameters passed down to the subplan.
    1043             :  * (Thus in principle, the shorter-lived the ExprContext the better, since
    1044             :  * that data isn't needed after we return.  In practice, because initplan
    1045             :  * parameters are never more complex than Vars, Aggrefs, etc, evaluating them
    1046             :  * currently never leaks any memory anyway.)
    1047             :  * ----------------------------------------------------------------
    1048             :  */
    1049             : void
    1050       10076 : ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
    1051             : {
    1052       10076 :     SubPlan    *subplan = node->subplan;
    1053       10076 :     PlanState  *planstate = node->planstate;
    1054       10076 :     SubLinkType subLinkType = subplan->subLinkType;
    1055       10076 :     EState     *estate = planstate->state;
    1056       10076 :     ScanDirection dir = estate->es_direction;
    1057             :     MemoryContext oldcontext;
    1058             :     TupleTableSlot *slot;
    1059             :     ListCell   *pvar;
    1060             :     ListCell   *l;
    1061       10076 :     bool        found = false;
    1062       10076 :     ArrayBuildStateAny *astate = NULL;
    1063             : 
    1064       10076 :     if (subLinkType == ANY_SUBLINK ||
    1065             :         subLinkType == ALL_SUBLINK)
    1066           0 :         elog(ERROR, "ANY/ALL subselect unsupported as initplan");
    1067       10076 :     if (subLinkType == CTE_SUBLINK)
    1068           0 :         elog(ERROR, "CTE subplans should not be executed via ExecSetParamPlan");
    1069             : 
    1070             :     /*
    1071             :      * Enforce forward scan direction regardless of caller. It's hard but not
    1072             :      * impossible to get here in backward scan, so make it work anyway.
    1073             :      */
    1074       10076 :     estate->es_direction = ForwardScanDirection;
    1075             : 
    1076             :     /* Initialize ArrayBuildStateAny in caller's context, if needed */
    1077       10076 :     if (subLinkType == ARRAY_SUBLINK)
    1078          58 :         astate = initArrayResultAny(subplan->firstColType,
    1079             :                                     CurrentMemoryContext, true);
    1080             : 
    1081             :     /*
    1082             :      * Must switch to per-query memory context.
    1083             :      */
    1084       10076 :     oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
    1085             : 
    1086             :     /*
    1087             :      * Set Params of this plan from parent plan correlation values. (Any
    1088             :      * calculation we have to do is done in the parent econtext, since the
    1089             :      * Param values don't need to have per-query lifetime.)  Currently, we
    1090             :      * expect only MULTIEXPR_SUBLINK plans to have any correlation values.
    1091             :      */
    1092             :     Assert(subplan->parParam == NIL || subLinkType == MULTIEXPR_SUBLINK);
    1093             :     Assert(list_length(subplan->parParam) == list_length(node->args));
    1094             : 
    1095       10160 :     forboth(l, subplan->parParam, pvar, node->args)
    1096             :     {
    1097          84 :         int         paramid = lfirst_int(l);
    1098          84 :         ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
    1099             : 
    1100          84 :         prm->value = ExecEvalExprSwitchContext((ExprState *) lfirst(pvar),
    1101             :                                                econtext,
    1102             :                                                &(prm->isnull));
    1103          84 :         planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
    1104             :     }
    1105             : 
    1106             :     /*
    1107             :      * Run the plan.  (If it needs to be rescanned, the first ExecProcNode
    1108             :      * call will take care of that.)
    1109             :      */
    1110       34670 :     for (slot = ExecProcNode(planstate);
    1111       22992 :          !TupIsNull(slot);
    1112       14518 :          slot = ExecProcNode(planstate))
    1113             :     {
    1114       14826 :         TupleDesc   tdesc = slot->tts_tupleDescriptor;
    1115       14826 :         int         i = 1;
    1116             : 
    1117       14826 :         if (subLinkType == EXISTS_SUBLINK)
    1118             :         {
    1119             :             /* There can be only one setParam... */
    1120         298 :             int         paramid = linitial_int(subplan->setParam);
    1121         298 :             ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
    1122             : 
    1123         298 :             prm->execPlan = NULL;
    1124         298 :             prm->value = BoolGetDatum(true);
    1125         298 :             prm->isnull = false;
    1126         298 :             found = true;
    1127         298 :             break;
    1128             :         }
    1129             : 
    1130       14528 :         if (subLinkType == ARRAY_SUBLINK)
    1131             :         {
    1132             :             Datum       dvalue;
    1133             :             bool        disnull;
    1134             : 
    1135        7496 :             found = true;
    1136             :             /* stash away current value */
    1137             :             Assert(subplan->firstColType == TupleDescAttr(tdesc, 0)->atttypid);
    1138        7496 :             dvalue = slot_getattr(slot, 1, &disnull);
    1139        7496 :             astate = accumArrayResultAny(astate, dvalue, disnull,
    1140             :                                          subplan->firstColType, oldcontext);
    1141             :             /* keep scanning subplan to collect all values */
    1142        7496 :             continue;
    1143             :         }
    1144             : 
    1145        7032 :         if (found &&
    1146           4 :             (subLinkType == EXPR_SUBLINK ||
    1147           0 :              subLinkType == MULTIEXPR_SUBLINK ||
    1148             :              subLinkType == ROWCOMPARE_SUBLINK))
    1149          10 :             ereport(ERROR,
    1150             :                     (errcode(ERRCODE_CARDINALITY_VIOLATION),
    1151             :                      errmsg("more than one row returned by a subquery used as an expression")));
    1152             : 
    1153        7022 :         found = true;
    1154             : 
    1155             :         /*
    1156             :          * We need to copy the subplan's tuple into our own context, in case
    1157             :          * any of the params are pass-by-ref type --- the pointers stored in
    1158             :          * the param structs will point at this copied tuple! node->curTuple
    1159             :          * keeps track of the copied tuple for eventual freeing.
    1160             :          */
    1161        7022 :         if (node->curTuple)
    1162         264 :             heap_freetuple(node->curTuple);
    1163        7022 :         node->curTuple = ExecCopySlotHeapTuple(slot);
    1164             : 
    1165             :         /*
    1166             :          * Now set all the setParam params from the columns of the tuple
    1167             :          */
    1168       14104 :         foreach(l, subplan->setParam)
    1169             :         {
    1170        7082 :             int         paramid = lfirst_int(l);
    1171        7082 :             ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
    1172             : 
    1173        7082 :             prm->execPlan = NULL;
    1174        7082 :             prm->value = heap_getattr(node->curTuple, i, tdesc,
    1175             :                                       &(prm->isnull));
    1176        7082 :             i++;
    1177             :         }
    1178             :     }
    1179             : 
    1180       10066 :     if (subLinkType == ARRAY_SUBLINK)
    1181             :     {
    1182             :         /* There can be only one setParam... */
    1183          58 :         int         paramid = linitial_int(subplan->setParam);
    1184          58 :         ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
    1185             : 
    1186             :         /*
    1187             :          * We build the result array in query context so it won't disappear;
    1188             :          * to avoid leaking memory across repeated calls, we have to remember
    1189             :          * the latest value, much as for curTuple above.
    1190             :          */
    1191          58 :         if (node->curArray != PointerGetDatum(NULL))
    1192           0 :             pfree(DatumGetPointer(node->curArray));
    1193          58 :         node->curArray = makeArrayResultAny(astate,
    1194             :                                             econtext->ecxt_per_query_memory,
    1195             :                                             true);
    1196          58 :         prm->execPlan = NULL;
    1197          58 :         prm->value = node->curArray;
    1198          58 :         prm->isnull = false;
    1199             :     }
    1200       10008 :     else if (!found)
    1201             :     {
    1202        2698 :         if (subLinkType == EXISTS_SUBLINK)
    1203             :         {
    1204             :             /* There can be only one setParam... */
    1205        2616 :             int         paramid = linitial_int(subplan->setParam);
    1206        2616 :             ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
    1207             : 
    1208        2616 :             prm->execPlan = NULL;
    1209        2616 :             prm->value = BoolGetDatum(false);
    1210        2616 :             prm->isnull = false;
    1211             :         }
    1212             :         else
    1213             :         {
    1214             :             /* For other sublink types, set all the output params to NULL */
    1215         172 :             foreach(l, subplan->setParam)
    1216             :             {
    1217          90 :                 int         paramid = lfirst_int(l);
    1218          90 :                 ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
    1219             : 
    1220          90 :                 prm->execPlan = NULL;
    1221          90 :                 prm->value = (Datum) 0;
    1222          90 :                 prm->isnull = true;
    1223             :             }
    1224             :         }
    1225             :     }
    1226             : 
    1227       10066 :     MemoryContextSwitchTo(oldcontext);
    1228             : 
    1229             :     /* restore scan direction */
    1230       10066 :     estate->es_direction = dir;
    1231       10066 : }
    1232             : 
    1233             : /*
    1234             :  * ExecSetParamPlanMulti
    1235             :  *
    1236             :  * Apply ExecSetParamPlan to evaluate any not-yet-evaluated initplan output
    1237             :  * parameters whose ParamIDs are listed in "params".  Any listed params that
    1238             :  * are not initplan outputs are ignored.
    1239             :  *
    1240             :  * As with ExecSetParamPlan, any ExprContext belonging to the current EState
    1241             :  * can be used, but in principle a shorter-lived ExprContext is better than a
    1242             :  * longer-lived one.
    1243             :  */
    1244             : void
    1245         698 : ExecSetParamPlanMulti(const Bitmapset *params, ExprContext *econtext)
    1246             : {
    1247             :     int         paramid;
    1248             : 
    1249         698 :     paramid = -1;
    1250        1594 :     while ((paramid = bms_next_member(params, paramid)) >= 0)
    1251             :     {
    1252         198 :         ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
    1253             : 
    1254         198 :         if (prm->execPlan != NULL)
    1255             :         {
    1256             :             /* Parameter not evaluated yet, so go do it */
    1257          16 :             ExecSetParamPlan(prm->execPlan, econtext);
    1258             :             /* ExecSetParamPlan should have processed this param... */
    1259             :             Assert(prm->execPlan == NULL);
    1260             :         }
    1261             :     }
    1262         698 : }
    1263             : 
    1264             : /*
    1265             :  * Mark an initplan as needing recalculation
    1266             :  */
    1267             : void
    1268         472 : ExecReScanSetParamPlan(SubPlanState *node, PlanState *parent)
    1269             : {
    1270         472 :     PlanState  *planstate = node->planstate;
    1271         472 :     SubPlan    *subplan = node->subplan;
    1272         472 :     EState     *estate = parent->state;
    1273             :     ListCell   *l;
    1274             : 
    1275             :     /* sanity checks */
    1276         472 :     if (subplan->parParam != NIL)
    1277           0 :         elog(ERROR, "direct correlated subquery unsupported as initplan");
    1278         472 :     if (subplan->setParam == NIL)
    1279           0 :         elog(ERROR, "setParam list of initplan is empty");
    1280         472 :     if (bms_is_empty(planstate->plan->extParam))
    1281           0 :         elog(ERROR, "extParam set of initplan is empty");
    1282             : 
    1283             :     /*
    1284             :      * Don't actually re-scan: it'll happen inside ExecSetParamPlan if needed.
    1285             :      */
    1286             : 
    1287             :     /*
    1288             :      * Mark this subplan's output parameters as needing recalculation.
    1289             :      *
    1290             :      * CTE subplans are never executed via parameter recalculation; instead
    1291             :      * they get run when called by nodeCtescan.c.  So don't mark the output
    1292             :      * parameter of a CTE subplan as dirty, but do set the chgParam bit for it
    1293             :      * so that dependent plan nodes will get told to rescan.
    1294             :      */
    1295         944 :     foreach(l, subplan->setParam)
    1296             :     {
    1297         472 :         int         paramid = lfirst_int(l);
    1298         472 :         ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
    1299             : 
    1300         472 :         if (subplan->subLinkType != CTE_SUBLINK)
    1301         416 :             prm->execPlan = node;
    1302             : 
    1303         472 :         parent->chgParam = bms_add_member(parent->chgParam, paramid);
    1304             :     }
    1305         472 : }
    1306             : 
    1307             : 
    1308             : /*
    1309             :  * ExecInitAlternativeSubPlan
    1310             :  *
    1311             :  * Initialize for execution of one of a set of alternative subplans.
    1312             :  */
    1313             : AlternativeSubPlanState *
    1314        1170 : ExecInitAlternativeSubPlan(AlternativeSubPlan *asplan, PlanState *parent)
    1315             : {
    1316        1170 :     AlternativeSubPlanState *asstate = makeNode(AlternativeSubPlanState);
    1317             :     double      num_calls;
    1318             :     SubPlan    *subplan1;
    1319             :     SubPlan    *subplan2;
    1320             :     Cost        cost1;
    1321             :     Cost        cost2;
    1322             :     ListCell   *lc;
    1323             : 
    1324        1170 :     asstate->subplan = asplan;
    1325             : 
    1326             :     /*
    1327             :      * Initialize subplans.  (Can we get away with only initializing the one
    1328             :      * we're going to use?)
    1329             :      */
    1330        3510 :     foreach(lc, asplan->subplans)
    1331             :     {
    1332        2340 :         SubPlan    *sp = lfirst_node(SubPlan, lc);
    1333        2340 :         SubPlanState *sps = ExecInitSubPlan(sp, parent);
    1334             : 
    1335        2340 :         asstate->subplans = lappend(asstate->subplans, sps);
    1336        2340 :         parent->subPlan = lappend(parent->subPlan, sps);
    1337             :     }
    1338             : 
    1339             :     /*
    1340             :      * Select the one to be used.  For this, we need an estimate of the number
    1341             :      * of executions of the subplan.  We use the number of output rows
    1342             :      * expected from the parent plan node.  This is a good estimate if we are
    1343             :      * in the parent's targetlist, and an underestimate (but probably not by
    1344             :      * more than a factor of 2) if we are in the qual.
    1345             :      */
    1346        1170 :     num_calls = parent->plan->plan_rows;
    1347             : 
    1348             :     /*
    1349             :      * The planner saved enough info so that we don't have to work very hard
    1350             :      * to estimate the total cost, given the number-of-calls estimate.
    1351             :      */
    1352             :     Assert(list_length(asplan->subplans) == 2);
    1353        1170 :     subplan1 = (SubPlan *) linitial(asplan->subplans);
    1354        1170 :     subplan2 = (SubPlan *) lsecond(asplan->subplans);
    1355             : 
    1356        1170 :     cost1 = subplan1->startup_cost + num_calls * subplan1->per_call_cost;
    1357        1170 :     cost2 = subplan2->startup_cost + num_calls * subplan2->per_call_cost;
    1358             : 
    1359        1170 :     if (cost1 < cost2)
    1360         284 :         asstate->active = 0;
    1361             :     else
    1362         886 :         asstate->active = 1;
    1363             : 
    1364        1170 :     return asstate;
    1365             : }
    1366             : 
    1367             : /*
    1368             :  * ExecAlternativeSubPlan
    1369             :  *
    1370             :  * Execute one of a set of alternative subplans.
    1371             :  *
    1372             :  * Note: in future we might consider changing to different subplans on the
    1373             :  * fly, in case the original rowcount estimate turns out to be way off.
    1374             :  */
    1375             : Datum
    1376      489886 : ExecAlternativeSubPlan(AlternativeSubPlanState *node,
    1377             :                        ExprContext *econtext,
    1378             :                        bool *isNull)
    1379             : {
    1380             :     /* Just pass control to the active subplan */
    1381      489886 :     SubPlanState *activesp = list_nth_node(SubPlanState,
    1382             :                                            node->subplans, node->active);
    1383             : 
    1384      489886 :     return ExecSubPlan(activesp, econtext, isNull);
    1385             : }

Generated by: LCOV version 1.13