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