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