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