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