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