PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
nodeSubplan.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/htup_details.h"
#include "executor/executor.h"
#include "executor/nodeSubplan.h"
#include "nodes/makefuncs.h"
#include "optimizer/clauses.h"
#include "utils/array.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
Include dependency graph for nodeSubplan.c:

Go to the source code of this file.

Functions

static Datum ExecHashSubPlan (SubPlanState *node, ExprContext *econtext, bool *isNull)
 
static Datum ExecScanSubPlan (SubPlanState *node, ExprContext *econtext, bool *isNull)
 
static void buildSubPlanHash (SubPlanState *node, ExprContext *econtext)
 
static bool findPartialMatch (TupleHashTable hashtable, TupleTableSlot *slot, FmgrInfo *eqfunctions)
 
static bool slotAllNulls (TupleTableSlot *slot)
 
static bool slotNoNulls (TupleTableSlot *slot)
 
Datum ExecSubPlan (SubPlanState *node, ExprContext *econtext, bool *isNull)
 
SubPlanStateExecInitSubPlan (SubPlan *subplan, PlanState *parent)
 
void ExecSetParamPlan (SubPlanState *node, ExprContext *econtext)
 
void ExecReScanSetParamPlan (SubPlanState *node, PlanState *parent)
 
AlternativeSubPlanStateExecInitAlternativeSubPlan (AlternativeSubPlan *asplan, PlanState *parent)
 
Datum ExecAlternativeSubPlan (AlternativeSubPlanState *node, ExprContext *econtext, bool *isNull)
 

Function Documentation

static void buildSubPlanHash ( SubPlanState node,
ExprContext econtext 
)
static

Definition at line 457 of file nodeSubplan.c.

References ANY_SUBLINK, Assert, BuildTupleHashTable(), ExprContext::ecxt_param_exec_vals, ExprContext::ecxt_per_query_memory, ExecClearTuple(), ParamExecData::execPlan, ExecProcNode(), ExecProject(), ExecReScan(), SubPlanState::hashnulls, SubPlanState::hashtable, SubPlanState::hashtablecxt, SubPlanState::hashtempcxt, SubPlanState::havehashrows, SubPlanState::havenullrows, SubPlanState::innerecontext, ParamExecData::isnull, SubPlanState::keyColIdx, lfirst_int, list_length(), LookupTupleHashEntry(), MemoryContextReset(), MemoryContextSwitchTo(), Min, NULL, SubPlan::paramIds, ProjectionInfo::pi_state, PlanState::plan, Plan::plan_rows, SubPlanState::planstate, SubPlanState::projRight, ResetExprContext, ExprState::resultslot, slot_getattr(), slotNoNulls(), SubPlan::subLinkType, SubPlanState::subplan, SubPlanState::tab_eq_funcs, SubPlanState::tab_hash_funcs, TupIsNull, SubPlan::unknownEqFalse, and ParamExecData::value.

Referenced by ExecHashSubPlan().

458 {
459  SubPlan *subplan = node->subplan;
460  PlanState *planstate = node->planstate;
461  int ncols = list_length(subplan->paramIds);
462  ExprContext *innerecontext = node->innerecontext;
463  MemoryContext oldcontext;
464  long nbuckets;
465  TupleTableSlot *slot;
466 
467  Assert(subplan->subLinkType == ANY_SUBLINK);
468 
469  /*
470  * If we already had any hash tables, destroy 'em; then create empty hash
471  * table(s).
472  *
473  * If we need to distinguish accurately between FALSE and UNKNOWN (i.e.,
474  * NULL) results of the IN operation, then we have to store subplan output
475  * rows that are partly or wholly NULL. We store such rows in a separate
476  * hash table that we expect will be much smaller than the main table. (We
477  * can use hashing to eliminate partly-null rows that are not distinct. We
478  * keep them separate to minimize the cost of the inevitable full-table
479  * searches; see findPartialMatch.)
480  *
481  * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't
482  * need to store subplan output rows that contain NULL.
483  */
485  node->hashtable = NULL;
486  node->hashnulls = NULL;
487  node->havehashrows = false;
488  node->havenullrows = false;
489 
490  nbuckets = (long) Min(planstate->plan->plan_rows, (double) LONG_MAX);
491  if (nbuckets < 1)
492  nbuckets = 1;
493 
494  node->hashtable = BuildTupleHashTable(ncols,
495  node->keyColIdx,
496  node->tab_eq_funcs,
497  node->tab_hash_funcs,
498  nbuckets,
499  0,
500  node->hashtablecxt,
501  node->hashtempcxt,
502  false);
503 
504  if (!subplan->unknownEqFalse)
505  {
506  if (ncols == 1)
507  nbuckets = 1; /* there can only be one entry */
508  else
509  {
510  nbuckets /= 16;
511  if (nbuckets < 1)
512  nbuckets = 1;
513  }
514  node->hashnulls = BuildTupleHashTable(ncols,
515  node->keyColIdx,
516  node->tab_eq_funcs,
517  node->tab_hash_funcs,
518  nbuckets,
519  0,
520  node->hashtablecxt,
521  node->hashtempcxt,
522  false);
523  }
524 
525  /*
526  * We are probably in a short-lived expression-evaluation context. Switch
527  * to the per-query context for manipulating the child plan.
528  */
529  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
530 
531  /*
532  * Reset subplan to start.
533  */
534  ExecReScan(planstate);
535 
536  /*
537  * Scan the subplan and load the hash table(s). Note that when there are
538  * duplicate rows coming out of the sub-select, only one copy is stored.
539  */
540  for (slot = ExecProcNode(planstate);
541  !TupIsNull(slot);
542  slot = ExecProcNode(planstate))
543  {
544  int col = 1;
545  ListCell *plst;
546  bool isnew;
547 
548  /*
549  * Load up the Params representing the raw sub-select outputs, then
550  * form the projection tuple to store in the hashtable.
551  */
552  foreach(plst, subplan->paramIds)
553  {
554  int paramid = lfirst_int(plst);
555  ParamExecData *prmdata;
556 
557  prmdata = &(innerecontext->ecxt_param_exec_vals[paramid]);
558  Assert(prmdata->execPlan == NULL);
559  prmdata->value = slot_getattr(slot, col,
560  &(prmdata->isnull));
561  col++;
562  }
563  slot = ExecProject(node->projRight);
564 
565  /*
566  * If result contains any nulls, store separately or not at all.
567  */
568  if (slotNoNulls(slot))
569  {
570  (void) LookupTupleHashEntry(node->hashtable, slot, &isnew);
571  node->havehashrows = true;
572  }
573  else if (node->hashnulls)
574  {
575  (void) LookupTupleHashEntry(node->hashnulls, slot, &isnew);
576  node->havenullrows = true;
577  }
578 
579  /*
580  * Reset innerecontext after each inner tuple to free any memory used
581  * during ExecProject.
582  */
583  ResetExprContext(innerecontext);
584  }
585 
586  /*
587  * Since the projected tuples are in the sub-query's context and not the
588  * main context, we'd better clear the tuple slot before there's any
589  * chance of a reset of the sub-query's context. Else we will have the
590  * potential for a double free attempt. (XXX possibly no longer needed,
591  * but can't hurt.)
592  */
594 
595  MemoryContextSwitchTo(oldcontext);
596 }
double plan_rows
Definition: plannodes.h:131
void * execPlan
Definition: params.h:99
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
TupleHashTable hashtable
Definition: execnodes.h:764
ExprContext * innerecontext
Definition: execnodes.h:770
#define Min(x, y)
Definition: c.h:806
void ExecReScan(PlanState *node)
Definition: execAmi.c:75
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SubLinkType subLinkType
Definition: primnodes.h:684
List * paramIds
Definition: primnodes.h:687
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
TupleTableSlot * resultslot
Definition: execnodes.h:69
FmgrInfo * tab_hash_funcs
Definition: execnodes.h:772
struct PlanState * planstate
Definition: execnodes.h:755
SubPlan * subplan
Definition: execnodes.h:754
#define lfirst_int(lc)
Definition: pg_list.h:107
bool isnull
Definition: params.h:101
AttrNumber * keyColIdx
Definition: execnodes.h:771
ParamExecData * ecxt_param_exec_vals
Definition: execnodes.h:206
bool havenullrows
Definition: execnodes.h:767
#define TupIsNull(slot)
Definition: tuptable.h:138
TupleHashEntry LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot, bool *isnew)
Definition: execGrouping.c:351
static bool slotNoNulls(TupleTableSlot *slot)
Definition: nodeSubplan.c:662
Plan * plan
Definition: execnodes.h:832
MemoryContext hashtempcxt
Definition: execnodes.h:769
MemoryContext hashtablecxt
Definition: execnodes.h:768
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
FmgrInfo * tab_eq_funcs
Definition: execnodes.h:773
bool unknownEqFalse
Definition: primnodes.h:700
static int list_length(const List *l)
Definition: pg_list.h:89
TupleHashTable BuildTupleHashTable(int numCols, AttrNumber *keyColIdx, FmgrInfo *eqfunctions, FmgrInfo *hashfunctions, long nbuckets, Size additionalsize, MemoryContext tablecxt, MemoryContext tempcxt, bool use_variable_hash_iv)
Definition: execGrouping.c:290
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: heaptuple.c:1141
Datum value
Definition: params.h:100
ExprState pi_state
Definition: execnodes.h:296
ProjectionInfo * projRight
Definition: execnodes.h:763
bool havehashrows
Definition: execnodes.h:766
TupleHashTable hashnulls
Definition: execnodes.h:765
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:310
#define ResetExprContext(econtext)
Definition: executor.h:451
Datum ExecAlternativeSubPlan ( AlternativeSubPlanState node,
ExprContext econtext,
bool isNull 
)

Definition at line 1195 of file nodeSubplan.c.

References AlternativeSubPlanState::active, ExecSubPlan(), list_nth_node, and AlternativeSubPlanState::subplans.

Referenced by ExecEvalAlternativeSubPlan().

1198 {
1199  /* Just pass control to the active subplan */
1201  node->subplans, node->active);
1202 
1203  return ExecSubPlan(activesp, econtext, isNull);
1204 }
#define list_nth_node(type, list, n)
Definition: pg_list.h:227
Datum ExecSubPlan(SubPlanState *node, ExprContext *econtext, bool *isNull)
Definition: nodeSubplan.c:62
static Datum ExecHashSubPlan ( SubPlanState node,
ExprContext econtext,
bool isNull 
)
static

Definition at line 88 of file nodeSubplan.c.

References SubPlanState::args, BoolGetDatum, buildSubPlanHash(), PlanState::chgParam, SubPlanState::cur_eq_funcs, elog, ERROR, ExecClearTuple(), ExecProject(), findPartialMatch(), FindTupleHashEntry(), SubPlanState::hashnulls, SubPlanState::hashtable, SubPlanState::havehashrows, SubPlanState::havenullrows, SubPlanState::lhs_hash_funcs, NIL, NULL, SubPlan::parParam, ProjectionInfo::pi_exprContext, SubPlanState::planstate, SubPlanState::projLeft, slotAllNulls(), slotNoNulls(), and SubPlanState::subplan.

Referenced by ExecSubPlan().

91 {
92  SubPlan *subplan = node->subplan;
93  PlanState *planstate = node->planstate;
94  TupleTableSlot *slot;
95 
96  /* Shouldn't have any direct correlation Vars */
97  if (subplan->parParam != NIL || node->args != NIL)
98  elog(ERROR, "hashed subplan with direct correlation not supported");
99 
100  /*
101  * If first time through or we need to rescan the subplan, build the hash
102  * table.
103  */
104  if (node->hashtable == NULL || planstate->chgParam != NULL)
105  buildSubPlanHash(node, econtext);
106 
107  /*
108  * The result for an empty subplan is always FALSE; no need to evaluate
109  * lefthand side.
110  */
111  *isNull = false;
112  if (!node->havehashrows && !node->havenullrows)
113  return BoolGetDatum(false);
114 
115  /*
116  * Evaluate lefthand expressions and form a projection tuple. First we
117  * have to set the econtext to use (hack alert!).
118  */
119  node->projLeft->pi_exprContext = econtext;
120  slot = ExecProject(node->projLeft);
121 
122  /*
123  * Note: because we are typically called in a per-tuple context, we have
124  * to explicitly clear the projected tuple before returning. Otherwise,
125  * we'll have a double-free situation: the per-tuple context will probably
126  * be reset before we're called again, and then the tuple slot will think
127  * it still needs to free the tuple.
128  */
129 
130  /*
131  * If the LHS is all non-null, probe for an exact match in the main hash
132  * table. If we find one, the result is TRUE. Otherwise, scan the
133  * partly-null table to see if there are any rows that aren't provably
134  * unequal to the LHS; if so, the result is UNKNOWN. (We skip that part
135  * if we don't care about UNKNOWN.) Otherwise, the result is FALSE.
136  *
137  * Note: the reason we can avoid a full scan of the main hash table is
138  * that the combining operators are assumed never to yield NULL when both
139  * inputs are non-null. If they were to do so, we might need to produce
140  * UNKNOWN instead of FALSE because of an UNKNOWN result in comparing the
141  * LHS to some main-table entry --- which is a comparison we will not even
142  * make, unless there's a chance match of hash keys.
143  */
144  if (slotNoNulls(slot))
145  {
146  if (node->havehashrows &&
148  slot,
149  node->cur_eq_funcs,
150  node->lhs_hash_funcs) != NULL)
151  {
152  ExecClearTuple(slot);
153  return BoolGetDatum(true);
154  }
155  if (node->havenullrows &&
156  findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
157  {
158  ExecClearTuple(slot);
159  *isNull = true;
160  return BoolGetDatum(false);
161  }
162  ExecClearTuple(slot);
163  return BoolGetDatum(false);
164  }
165 
166  /*
167  * When the LHS is partly or wholly NULL, we can never return TRUE. If we
168  * don't care about UNKNOWN, just return FALSE. Otherwise, if the LHS is
169  * wholly NULL, immediately return UNKNOWN. (Since the combining
170  * operators are strict, the result could only be FALSE if the sub-select
171  * were empty, but we already handled that case.) Otherwise, we must scan
172  * both the main and partly-null tables to see if there are any rows that
173  * aren't provably unequal to the LHS; if so, the result is UNKNOWN.
174  * Otherwise, the result is FALSE.
175  */
176  if (node->hashnulls == NULL)
177  {
178  ExecClearTuple(slot);
179  return BoolGetDatum(false);
180  }
181  if (slotAllNulls(slot))
182  {
183  ExecClearTuple(slot);
184  *isNull = true;
185  return BoolGetDatum(false);
186  }
187  /* Scan partly-null table first, since more likely to get a match */
188  if (node->havenullrows &&
189  findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
190  {
191  ExecClearTuple(slot);
192  *isNull = true;
193  return BoolGetDatum(false);
194  }
195  if (node->havehashrows &&
196  findPartialMatch(node->hashtable, slot, node->cur_eq_funcs))
197  {
198  ExecClearTuple(slot);
199  *isNull = true;
200  return BoolGetDatum(false);
201  }
202  ExecClearTuple(slot);
203  return BoolGetDatum(false);
204 }
#define NIL
Definition: pg_list.h:69
ProjectionInfo * projLeft
Definition: execnodes.h:762
TupleHashTable hashtable
Definition: execnodes.h:764
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
#define ERROR
Definition: elog.h:43
struct PlanState * planstate
Definition: execnodes.h:755
List * args
Definition: execnodes.h:758
SubPlan * subplan
Definition: execnodes.h:754
bool havenullrows
Definition: execnodes.h:767
static bool slotNoNulls(TupleTableSlot *slot)
Definition: nodeSubplan.c:662
Bitmapset * chgParam
Definition: execnodes.h:856
static bool slotAllNulls(TupleTableSlot *slot)
Definition: nodeSubplan.c:642
#define BoolGetDatum(X)
Definition: postgres.h:408
#define NULL
Definition: c.h:229
List * parParam
Definition: primnodes.h:709
FmgrInfo * lhs_hash_funcs
Definition: execnodes.h:774
FmgrInfo * cur_eq_funcs
Definition: execnodes.h:775
static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot, FmgrInfo *eqfunctions)
Definition: nodeSubplan.c:610
static void buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
Definition: nodeSubplan.c:457
#define elog
Definition: elog.h:219
ExprContext * pi_exprContext
Definition: execnodes.h:298
bool havehashrows
Definition: execnodes.h:766
TupleHashEntry FindTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot, FmgrInfo *eqfunctions, FmgrInfo *hashfunctions)
Definition: execGrouping.c:425
TupleHashTable hashnulls
Definition: execnodes.h:765
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:310
AlternativeSubPlanState* ExecInitAlternativeSubPlan ( AlternativeSubPlan asplan,
PlanState parent 
)

Definition at line 1133 of file nodeSubplan.c.

References AlternativeSubPlanState::active, Assert, ExecInitSubPlan(), lappend(), lfirst_node, linitial, list_length(), lsecond, makeNode, SubPlan::per_call_cost, PlanState::plan, Plan::plan_rows, SubPlan::startup_cost, AlternativeSubPlanState::subplan, PlanState::subPlan, AlternativeSubPlan::subplans, and AlternativeSubPlanState::subplans.

Referenced by ExecInitExprRec().

1134 {
1136  double num_calls;
1137  SubPlan *subplan1;
1138  SubPlan *subplan2;
1139  Cost cost1;
1140  Cost cost2;
1141  ListCell *lc;
1142 
1143  asstate->subplan = asplan;
1144 
1145  /*
1146  * Initialize subplans. (Can we get away with only initializing the one
1147  * we're going to use?)
1148  */
1149  foreach(lc, asplan->subplans)
1150  {
1151  SubPlan *sp = lfirst_node(SubPlan, lc);
1152  SubPlanState *sps = ExecInitSubPlan(sp, parent);
1153 
1154  asstate->subplans = lappend(asstate->subplans, sps);
1155  parent->subPlan = lappend(parent->subPlan, sps);
1156  }
1157 
1158  /*
1159  * Select the one to be used. For this, we need an estimate of the number
1160  * of executions of the subplan. We use the number of output rows
1161  * expected from the parent plan node. This is a good estimate if we are
1162  * in the parent's targetlist, and an underestimate (but probably not by
1163  * more than a factor of 2) if we are in the qual.
1164  */
1165  num_calls = parent->plan->plan_rows;
1166 
1167  /*
1168  * The planner saved enough info so that we don't have to work very hard
1169  * to estimate the total cost, given the number-of-calls estimate.
1170  */
1171  Assert(list_length(asplan->subplans) == 2);
1172  subplan1 = (SubPlan *) linitial(asplan->subplans);
1173  subplan2 = (SubPlan *) lsecond(asplan->subplans);
1174 
1175  cost1 = subplan1->startup_cost + num_calls * subplan1->per_call_cost;
1176  cost2 = subplan2->startup_cost + num_calls * subplan2->per_call_cost;
1177 
1178  if (cost1 < cost2)
1179  asstate->active = 0;
1180  else
1181  asstate->active = 1;
1182 
1183  return asstate;
1184 }
double plan_rows
Definition: plannodes.h:131
List * subPlan
Definition: execnodes.h:851
#define lsecond(l)
Definition: pg_list.h:116
SubPlanState * ExecInitSubPlan(SubPlan *subplan, PlanState *parent)
Definition: nodeSubplan.c:686
#define linitial(l)
Definition: pg_list.h:111
AlternativeSubPlan * subplan
Definition: execnodes.h:785
#define lfirst_node(type, lc)
Definition: pg_list.h:109
List * lappend(List *list, void *datum)
Definition: list.c:128
Plan * plan
Definition: execnodes.h:832
Cost per_call_cost
Definition: primnodes.h:713
#define makeNode(_type_)
Definition: nodes.h:557
#define Assert(condition)
Definition: c.h:675
static int list_length(const List *l)
Definition: pg_list.h:89
Cost startup_cost
Definition: primnodes.h:712
double Cost
Definition: nodes.h:640
SubPlanState* ExecInitSubPlan ( SubPlan subplan,
PlanState parent 
)

Definition at line 686 of file nodeSubplan.c.

References ALLOCSET_DEFAULT_SIZES, ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), and_clause(), OpExpr::args, SubPlan::args, SubPlanState::args, Assert, castNode, CreateExprContext(), CTE_SUBLINK, SubPlanState::cur_eq_funcs, SubPlanState::curArray, CurrentMemoryContext, SubPlanState::curTuple, elog, ERROR, EState::es_param_exec_vals, EState::es_subplanstates, ExecBuildProjectionInfo(), ExecInitExpr(), ExecInitExprList(), ExecInitExtraTupleSlot(), ParamExecData::execPlan, ExecSetSlotDescriptor(), ExecTypeFromTL(), fmgr_info(), fmgr_info_set_expr, get_compatible_hash_operators(), get_op_hash_functions(), get_opcode(), SubPlanState::hashnulls, SubPlanState::hashtable, SubPlanState::hashtablecxt, SubPlanState::hashtempcxt, i, SubPlanState::innerecontext, IsA, SubPlanState::keyColIdx, lappend(), lfirst_int, lfirst_node, SubPlanState::lhs_hash_funcs, linitial, list_length(), list_make1, list_nth(), lsecond, makeNode, makeTargetEntry(), NIL, nodeTag, NULL, OpExpr::opfuncid, OpExpr::opno, palloc(), SubPlan::paramIds, SubPlanState::parent, SubPlan::plan_id, SubPlanState::planstate, PointerGetDatum, SubPlanState::projLeft, SubPlanState::projRight, SubPlan::setParam, PlanState::state, SubPlan::subLinkType, SubPlanState::subplan, SubPlanState::tab_eq_funcs, SubPlanState::tab_hash_funcs, SubPlan::testexpr, SubPlanState::testexpr, and SubPlan::useHashTable.

Referenced by ExecInitAlternativeSubPlan(), ExecInitExprRec(), and ExecInitNode().

687 {
689  EState *estate = parent->state;
690 
691  sstate->subplan = subplan;
692 
693  /* Link the SubPlanState to already-initialized subplan */
694  sstate->planstate = (PlanState *) list_nth(estate->es_subplanstates,
695  subplan->plan_id - 1);
696 
697  /* ... and to its parent's state */
698  sstate->parent = parent;
699 
700  /* Initialize subexpressions */
701  sstate->testexpr = ExecInitExpr((Expr *) subplan->testexpr, parent);
702  sstate->args = ExecInitExprList(subplan->args, parent);
703 
704  /*
705  * initialize my state
706  */
707  sstate->curTuple = NULL;
708  sstate->curArray = PointerGetDatum(NULL);
709  sstate->projLeft = NULL;
710  sstate->projRight = NULL;
711  sstate->hashtable = NULL;
712  sstate->hashnulls = NULL;
713  sstate->hashtablecxt = NULL;
714  sstate->hashtempcxt = NULL;
715  sstate->innerecontext = NULL;
716  sstate->keyColIdx = NULL;
717  sstate->tab_hash_funcs = NULL;
718  sstate->tab_eq_funcs = NULL;
719  sstate->lhs_hash_funcs = NULL;
720  sstate->cur_eq_funcs = NULL;
721 
722  /*
723  * If this is an initplan or MULTIEXPR subplan, it has output parameters
724  * that the parent plan will use, so mark those parameters as needing
725  * evaluation. We don't actually run the subplan until we first need one
726  * of its outputs.
727  *
728  * A CTE subplan's output parameter is never to be evaluated in the normal
729  * way, so skip this in that case.
730  *
731  * Note that we don't set parent->chgParam here: the parent plan hasn't
732  * been run yet, so no need to force it to re-run.
733  */
734  if (subplan->setParam != NIL && subplan->subLinkType != CTE_SUBLINK)
735  {
736  ListCell *lst;
737 
738  foreach(lst, subplan->setParam)
739  {
740  int paramid = lfirst_int(lst);
741  ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
742 
743  prm->execPlan = sstate;
744  }
745  }
746 
747  /*
748  * If we are going to hash the subquery output, initialize relevant stuff.
749  * (We don't create the hashtable until needed, though.)
750  */
751  if (subplan->useHashTable)
752  {
753  int ncols,
754  i;
755  TupleDesc tupDesc;
756  TupleTableSlot *slot;
757  List *oplist,
758  *lefttlist,
759  *righttlist;
760  ListCell *l;
761 
762  /* We need a memory context to hold the hash table(s) */
763  sstate->hashtablecxt =
765  "Subplan HashTable Context",
767  /* and a small one for the hash tables to use as temp storage */
768  sstate->hashtempcxt =
770  "Subplan HashTable Temp Context",
772  /* and a short-lived exprcontext for function evaluation */
773  sstate->innerecontext = CreateExprContext(estate);
774  /* Silly little array of column numbers 1..n */
775  ncols = list_length(subplan->paramIds);
776  sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
777  for (i = 0; i < ncols; i++)
778  sstate->keyColIdx[i] = i + 1;
779 
780  /*
781  * We use ExecProject to evaluate the lefthand and righthand
782  * expression lists and form tuples. (You might think that we could
783  * use the sub-select's output tuples directly, but that is not the
784  * case if we had to insert any run-time coercions of the sub-select's
785  * output datatypes; anyway this avoids storing any resjunk columns
786  * that might be in the sub-select's output.) Run through the
787  * combining expressions to build tlists for the lefthand and
788  * righthand sides.
789  *
790  * We also extract the combining operators themselves to initialize
791  * the equality and hashing functions for the hash tables.
792  */
793  if (IsA(subplan->testexpr, OpExpr))
794  {
795  /* single combining operator */
796  oplist = list_make1(subplan->testexpr);
797  }
798  else if (and_clause((Node *) subplan->testexpr))
799  {
800  /* multiple combining operators */
801  oplist = castNode(BoolExpr, subplan->testexpr)->args;
802  }
803  else
804  {
805  /* shouldn't see anything else in a hashable subplan */
806  elog(ERROR, "unrecognized testexpr type: %d",
807  (int) nodeTag(subplan->testexpr));
808  oplist = NIL; /* keep compiler quiet */
809  }
810  Assert(list_length(oplist) == ncols);
811 
812  lefttlist = righttlist = NIL;
813  sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
814  sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
815  sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
816  sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
817  i = 1;
818  foreach(l, oplist)
819  {
820  OpExpr *opexpr = lfirst_node(OpExpr, l);
821  Expr *expr;
822  TargetEntry *tle;
823  Oid rhs_eq_oper;
824  Oid left_hashfn;
825  Oid right_hashfn;
826 
827  Assert(list_length(opexpr->args) == 2);
828 
829  /* Process lefthand argument */
830  expr = (Expr *) linitial(opexpr->args);
831  tle = makeTargetEntry(expr,
832  i,
833  NULL,
834  false);
835  lefttlist = lappend(lefttlist, tle);
836 
837  /* Process righthand argument */
838  expr = (Expr *) lsecond(opexpr->args);
839  tle = makeTargetEntry(expr,
840  i,
841  NULL,
842  false);
843  righttlist = lappend(righttlist, tle);
844 
845  /* Lookup the equality function (potentially cross-type) */
846  fmgr_info(opexpr->opfuncid, &sstate->cur_eq_funcs[i - 1]);
847  fmgr_info_set_expr((Node *) opexpr, &sstate->cur_eq_funcs[i - 1]);
848 
849  /* Look up the equality function for the RHS type */
850  if (!get_compatible_hash_operators(opexpr->opno,
851  NULL, &rhs_eq_oper))
852  elog(ERROR, "could not find compatible hash operator for operator %u",
853  opexpr->opno);
854  fmgr_info(get_opcode(rhs_eq_oper), &sstate->tab_eq_funcs[i - 1]);
855 
856  /* Lookup the associated hash functions */
857  if (!get_op_hash_functions(opexpr->opno,
858  &left_hashfn, &right_hashfn))
859  elog(ERROR, "could not find hash function for hash operator %u",
860  opexpr->opno);
861  fmgr_info(left_hashfn, &sstate->lhs_hash_funcs[i - 1]);
862  fmgr_info(right_hashfn, &sstate->tab_hash_funcs[i - 1]);
863 
864  i++;
865  }
866 
867  /*
868  * Construct tupdescs, slots and projection nodes for left and right
869  * sides. The lefthand expressions will be evaluated in the parent
870  * plan node's exprcontext, which we don't have access to here.
871  * Fortunately we can just pass NULL for now and fill it in later
872  * (hack alert!). The righthand expressions will be evaluated in our
873  * own innerecontext.
874  */
875  tupDesc = ExecTypeFromTL(lefttlist, false);
876  slot = ExecInitExtraTupleSlot(estate);
877  ExecSetSlotDescriptor(slot, tupDesc);
878  sstate->projLeft = ExecBuildProjectionInfo(lefttlist,
879  NULL,
880  slot,
881  parent,
882  NULL);
883 
884  tupDesc = ExecTypeFromTL(righttlist, false);
885  slot = ExecInitExtraTupleSlot(estate);
886  ExecSetSlotDescriptor(slot, tupDesc);
887  sstate->projRight = ExecBuildProjectionInfo(righttlist,
888  sstate->innerecontext,
889  slot,
890  sstate->planstate,
891  NULL);
892  }
893 
894  return sstate;
895 }
#define NIL
Definition: pg_list.h:69
Definition: fmgr.h:56
bool get_compatible_hash_operators(Oid opno, Oid *lhs_opno, Oid *rhs_opno)
Definition: lsyscache.c:407
void * execPlan
Definition: params.h:99
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
ProjectionInfo * projLeft
Definition: execnodes.h:762
HeapTuple curTuple
Definition: execnodes.h:759
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition: lsyscache.c:507
TupleHashTable hashtable
Definition: execnodes.h:764
int plan_id
Definition: primnodes.h:689
ExprContext * innerecontext
Definition: execnodes.h:770
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
#define PointerGetDatum(X)
Definition: postgres.h:562
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
SubLinkType subLinkType
Definition: primnodes.h:684
Definition: nodes.h:509
List * paramIds
Definition: primnodes.h:687
ExprState * testexpr
Definition: execnodes.h:757
EState * state
Definition: execnodes.h:834
unsigned int Oid
Definition: postgres_ext.h:31
#define lsecond(l)
Definition: pg_list.h:116
FmgrInfo * tab_hash_funcs
Definition: execnodes.h:772
#define list_make1(x1)
Definition: pg_list.h:139
ParamExecData * es_param_exec_vals
Definition: execnodes.h:463
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
struct PlanState * planstate
Definition: execnodes.h:755
List * args
Definition: execnodes.h:758
SubPlan * subplan
Definition: execnodes.h:754
#define lfirst_int(lc)
Definition: pg_list.h:107
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
AttrNumber * keyColIdx
Definition: execnodes.h:771
#define lfirst_node(type, lc)
Definition: pg_list.h:109
bool and_clause(Node *clause)
Definition: clauses.c:314
void * list_nth(const List *list, int n)
Definition: list.c:410
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:104
List * ExecInitExprList(List *nodes, PlanState *parent)
Definition: execExpr.c:266
struct PlanState * parent
Definition: execnodes.h:756
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:235
TupleDesc ExecTypeFromTL(List *targetList, bool hasoid)
Definition: execTuples.c:888
List * lappend(List *list, void *datum)
Definition: list.c:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
Datum curArray
Definition: execnodes.h:760
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
Oid opfuncid
Definition: primnodes.h:497
Node * testexpr
Definition: primnodes.h:686
MemoryContext hashtempcxt
Definition: execnodes.h:769
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1094
MemoryContext hashtablecxt
Definition: execnodes.h:768
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
FmgrInfo * tab_eq_funcs
Definition: execnodes.h:773
List * setParam
Definition: primnodes.h:707
static int list_length(const List *l)
Definition: pg_list.h:89
List * es_subplanstates
Definition: execnodes.h:483
FmgrInfo * lhs_hash_funcs
Definition: execnodes.h:774
#define nodeTag(nodeptr)
Definition: nodes.h:514
FmgrInfo * cur_eq_funcs
Definition: execnodes.h:775
void * palloc(Size size)
Definition: mcxt.c:849
ProjectionInfo * ExecBuildProjectionInfo(List *targetList, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent, TupleDesc inputDesc)
Definition: execExpr.c:301
int i
ExprContext * CreateExprContext(EState *estate)
Definition: execUtils.c:218
bool useHashTable
Definition: primnodes.h:698
ProjectionInfo * projRight
Definition: execnodes.h:763
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:113
Oid opno
Definition: primnodes.h:496
#define elog
Definition: elog.h:219
List * args
Definition: primnodes.h:502
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
TupleHashTable hashnulls
Definition: execnodes.h:765
List * args
Definition: primnodes.h:710
void ExecReScanSetParamPlan ( SubPlanState node,
PlanState parent 
)

Definition at line 1087 of file nodeSubplan.c.

References bms_add_member(), bms_is_empty(), PlanState::chgParam, CTE_SUBLINK, elog, ERROR, EState::es_param_exec_vals, ParamExecData::execPlan, Plan::extParam, lfirst_int, NIL, SubPlan::parParam, PlanState::plan, SubPlanState::planstate, SubPlan::setParam, PlanState::state, SubPlan::subLinkType, and SubPlanState::subplan.

Referenced by ExecReScan().

1088 {
1089  PlanState *planstate = node->planstate;
1090  SubPlan *subplan = node->subplan;
1091  EState *estate = parent->state;
1092  ListCell *l;
1093 
1094  /* sanity checks */
1095  if (subplan->parParam != NIL)
1096  elog(ERROR, "direct correlated subquery unsupported as initplan");
1097  if (subplan->setParam == NIL)
1098  elog(ERROR, "setParam list of initplan is empty");
1099  if (bms_is_empty(planstate->plan->extParam))
1100  elog(ERROR, "extParam set of initplan is empty");
1101 
1102  /*
1103  * Don't actually re-scan: it'll happen inside ExecSetParamPlan if needed.
1104  */
1105 
1106  /*
1107  * Mark this subplan's output parameters as needing recalculation.
1108  *
1109  * CTE subplans are never executed via parameter recalculation; instead
1110  * they get run when called by nodeCtescan.c. So don't mark the output
1111  * parameter of a CTE subplan as dirty, but do set the chgParam bit for it
1112  * so that dependent plan nodes will get told to rescan.
1113  */
1114  foreach(l, subplan->setParam)
1115  {
1116  int paramid = lfirst_int(l);
1117  ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
1118 
1119  if (subplan->subLinkType != CTE_SUBLINK)
1120  prm->execPlan = node;
1121 
1122  parent->chgParam = bms_add_member(parent->chgParam, paramid);
1123  }
1124 }
#define NIL
Definition: pg_list.h:69
void * execPlan
Definition: params.h:99
SubLinkType subLinkType
Definition: primnodes.h:684
EState * state
Definition: execnodes.h:834
ParamExecData * es_param_exec_vals
Definition: execnodes.h:463
#define ERROR
Definition: elog.h:43
struct PlanState * planstate
Definition: execnodes.h:755
SubPlan * subplan
Definition: execnodes.h:754
#define lfirst_int(lc)
Definition: pg_list.h:107
Bitmapset * chgParam
Definition: execnodes.h:856
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
Plan * plan
Definition: execnodes.h:832
List * setParam
Definition: primnodes.h:707
Bitmapset * extParam
Definition: plannodes.h:162
List * parParam
Definition: primnodes.h:709
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
#define elog
Definition: elog.h:219
static Datum ExecScanSubPlan ( SubPlanState node,
ExprContext econtext,
bool isNull 
)
static

Definition at line 210 of file nodeSubplan.c.

References accumArrayResultAny(), ALL_SUBLINK, ANY_SUBLINK, SubPlanState::args, ARRAY_SUBLINK, Assert, tupleDesc::attrs, bms_add_member(), BoolGetDatum, PlanState::chgParam, CurrentMemoryContext, SubPlanState::curTuple, DatumGetBool, ExprContext::ecxt_param_exec_vals, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, EState::es_param_exec_vals, ExecCopySlotTuple(), ExecEvalExprSwitchContext(), ParamExecData::execPlan, ExecProcNode(), ExecReScan(), EXISTS_SUBLINK, EXPR_SUBLINK, SubPlan::firstColType, forboth, heap_freetuple(), heap_getattr, initArrayResultAny(), ParamExecData::isnull, lfirst, lfirst_int, list_length(), makeArrayResultAny(), MemoryContextSwitchTo(), MULTIEXPR_SUBLINK, NULL, SubPlan::paramIds, SubPlanState::parent, SubPlan::parParam, SubPlanState::planstate, result, ROWCOMPARE_SUBLINK, SubPlan::setParam, slot_getattr(), PlanState::state, SubPlan::subLinkType, SubPlanState::subplan, SubPlanState::testexpr, TupleTableSlot::tts_tupleDescriptor, TupIsNull, and ParamExecData::value.

Referenced by ExecSubPlan().

213 {
214  SubPlan *subplan = node->subplan;
215  PlanState *planstate = node->planstate;
216  SubLinkType subLinkType = subplan->subLinkType;
217  MemoryContext oldcontext;
218  TupleTableSlot *slot;
219  Datum result;
220  bool found = false; /* TRUE if got at least one subplan tuple */
221  ListCell *pvar;
222  ListCell *l;
223  ArrayBuildStateAny *astate = NULL;
224 
225  /*
226  * MULTIEXPR subplans, when "executed", just return NULL; but first we
227  * mark the subplan's output parameters as needing recalculation. (This
228  * is a bit of a hack: it relies on the subplan appearing later in its
229  * targetlist than any of the referencing Params, so that all the Params
230  * have been evaluated before we re-mark them for the next evaluation
231  * cycle. But in general resjunk tlist items appear after non-resjunk
232  * ones, so this should be safe.) Unlike ExecReScanSetParamPlan, we do
233  * *not* set bits in the parent plan node's chgParam, because we don't
234  * want to cause a rescan of the parent.
235  */
236  if (subLinkType == MULTIEXPR_SUBLINK)
237  {
238  EState *estate = node->parent->state;
239 
240  foreach(l, subplan->setParam)
241  {
242  int paramid = lfirst_int(l);
243  ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
244 
245  prm->execPlan = node;
246  }
247  *isNull = true;
248  return (Datum) 0;
249  }
250 
251  /* Initialize ArrayBuildStateAny in caller's context, if needed */
252  if (subLinkType == ARRAY_SUBLINK)
253  astate = initArrayResultAny(subplan->firstColType,
254  CurrentMemoryContext, true);
255 
256  /*
257  * We are probably in a short-lived expression-evaluation context. Switch
258  * to the per-query context for manipulating the child plan's chgParam,
259  * calling ExecProcNode on it, etc.
260  */
261  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
262 
263  /*
264  * Set Params of this plan from parent plan correlation values. (Any
265  * calculation we have to do is done in the parent econtext, since the
266  * Param values don't need to have per-query lifetime.)
267  */
268  Assert(list_length(subplan->parParam) == list_length(node->args));
269 
270  forboth(l, subplan->parParam, pvar, node->args)
271  {
272  int paramid = lfirst_int(l);
273  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
274 
276  econtext,
277  &(prm->isnull));
278  planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
279  }
280 
281  /*
282  * Now that we've set up its parameters, we can reset the subplan.
283  */
284  ExecReScan(planstate);
285 
286  /*
287  * For all sublink types except EXPR_SUBLINK and ARRAY_SUBLINK, the result
288  * is boolean as are the results of the combining operators. We combine
289  * results across tuples (if the subplan produces more than one) using OR
290  * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
291  * (ROWCOMPARE_SUBLINK doesn't allow multiple tuples from the subplan.)
292  * NULL results from the combining operators are handled according to the
293  * usual SQL semantics for OR and AND. The result for no input tuples is
294  * FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
295  * ROWCOMPARE_SUBLINK.
296  *
297  * For EXPR_SUBLINK we require the subplan to produce no more than one
298  * tuple, else an error is raised. If zero tuples are produced, we return
299  * NULL. Assuming we get a tuple, we just use its first column (there can
300  * be only one non-junk column in this case).
301  *
302  * For ARRAY_SUBLINK we allow the subplan to produce any number of tuples,
303  * and form an array of the first column's values. Note in particular
304  * that we produce a zero-element array if no tuples are produced (this is
305  * a change from pre-8.3 behavior of returning NULL).
306  */
307  result = BoolGetDatum(subLinkType == ALL_SUBLINK);
308  *isNull = false;
309 
310  for (slot = ExecProcNode(planstate);
311  !TupIsNull(slot);
312  slot = ExecProcNode(planstate))
313  {
314  TupleDesc tdesc = slot->tts_tupleDescriptor;
315  Datum rowresult;
316  bool rownull;
317  int col;
318  ListCell *plst;
319 
320  if (subLinkType == EXISTS_SUBLINK)
321  {
322  found = true;
323  result = BoolGetDatum(true);
324  break;
325  }
326 
327  if (subLinkType == EXPR_SUBLINK)
328  {
329  /* cannot allow multiple input tuples for EXPR sublink */
330  if (found)
331  ereport(ERROR,
332  (errcode(ERRCODE_CARDINALITY_VIOLATION),
333  errmsg("more than one row returned by a subquery used as an expression")));
334  found = true;
335 
336  /*
337  * We need to copy the subplan's tuple in case the result is of
338  * pass-by-ref type --- our return value will point into this
339  * copied tuple! Can't use the subplan's instance of the tuple
340  * since it won't still be valid after next ExecProcNode() call.
341  * node->curTuple keeps track of the copied tuple for eventual
342  * freeing.
343  */
344  if (node->curTuple)
345  heap_freetuple(node->curTuple);
346  node->curTuple = ExecCopySlotTuple(slot);
347 
348  result = heap_getattr(node->curTuple, 1, tdesc, isNull);
349  /* keep scanning subplan to make sure there's only one tuple */
350  continue;
351  }
352 
353  if (subLinkType == ARRAY_SUBLINK)
354  {
355  Datum dvalue;
356  bool disnull;
357 
358  found = true;
359  /* stash away current value */
360  Assert(subplan->firstColType == tdesc->attrs[0]->atttypid);
361  dvalue = slot_getattr(slot, 1, &disnull);
362  astate = accumArrayResultAny(astate, dvalue, disnull,
363  subplan->firstColType, oldcontext);
364  /* keep scanning subplan to collect all values */
365  continue;
366  }
367 
368  /* cannot allow multiple input tuples for ROWCOMPARE sublink either */
369  if (subLinkType == ROWCOMPARE_SUBLINK && found)
370  ereport(ERROR,
371  (errcode(ERRCODE_CARDINALITY_VIOLATION),
372  errmsg("more than one row returned by a subquery used as an expression")));
373 
374  found = true;
375 
376  /*
377  * For ALL, ANY, and ROWCOMPARE sublinks, load up the Params
378  * representing the columns of the sub-select, and then evaluate the
379  * combining expression.
380  */
381  col = 1;
382  foreach(plst, subplan->paramIds)
383  {
384  int paramid = lfirst_int(plst);
385  ParamExecData *prmdata;
386 
387  prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
388  Assert(prmdata->execPlan == NULL);
389  prmdata->value = slot_getattr(slot, col, &(prmdata->isnull));
390  col++;
391  }
392 
393  rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext,
394  &rownull);
395 
396  if (subLinkType == ANY_SUBLINK)
397  {
398  /* combine across rows per OR semantics */
399  if (rownull)
400  *isNull = true;
401  else if (DatumGetBool(rowresult))
402  {
403  result = BoolGetDatum(true);
404  *isNull = false;
405  break; /* needn't look at any more rows */
406  }
407  }
408  else if (subLinkType == ALL_SUBLINK)
409  {
410  /* combine across rows per AND semantics */
411  if (rownull)
412  *isNull = true;
413  else if (!DatumGetBool(rowresult))
414  {
415  result = BoolGetDatum(false);
416  *isNull = false;
417  break; /* needn't look at any more rows */
418  }
419  }
420  else
421  {
422  /* must be ROWCOMPARE_SUBLINK */
423  result = rowresult;
424  *isNull = rownull;
425  }
426  }
427 
428  MemoryContextSwitchTo(oldcontext);
429 
430  if (subLinkType == ARRAY_SUBLINK)
431  {
432  /* We return the result in the caller's context */
433  result = makeArrayResultAny(astate, oldcontext, true);
434  }
435  else if (!found)
436  {
437  /*
438  * deal with empty subplan result. result/isNull were previously
439  * initialized correctly for all sublink types except EXPR and
440  * ROWCOMPARE; for those, return NULL.
441  */
442  if (subLinkType == EXPR_SUBLINK ||
443  subLinkType == ROWCOMPARE_SUBLINK)
444  {
445  result = (Datum) 0;
446  *isNull = true;
447  }
448  }
449 
450  return result;
451 }
Oid firstColType
Definition: primnodes.h:693
void * execPlan
Definition: params.h:99
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
HeapTuple curTuple
Definition: execnodes.h:759
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:282
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
ArrayBuildStateAny * initArrayResultAny(Oid input_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5416
void ExecReScan(PlanState *node)
Definition: execAmi.c:75
Form_pg_attribute * attrs
Definition: tupdesc.h:74
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SubLinkType subLinkType
Definition: primnodes.h:684
int errcode(int sqlerrcode)
Definition: elog.c:575
List * paramIds
Definition: primnodes.h:687
return result
Definition: formatting.c:1633
ExprState * testexpr
Definition: execnodes.h:757
EState * state
Definition: execnodes.h:834
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
ParamExecData * es_param_exec_vals
Definition: execnodes.h:463
#define ERROR
Definition: elog.h:43
struct PlanState * planstate
Definition: execnodes.h:755
List * args
Definition: execnodes.h:758
SubPlan * subplan
Definition: execnodes.h:754
#define lfirst_int(lc)
Definition: pg_list.h:107
bool isnull
Definition: params.h:101
#define DatumGetBool(X)
Definition: postgres.h:399
ParamExecData * ecxt_param_exec_vals
Definition: execnodes.h:206
#define TupIsNull(slot)
Definition: tuptable.h:138
struct PlanState * parent
Definition: execnodes.h:756
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
Bitmapset * chgParam
Definition: execnodes.h:856
SubLinkType
Definition: primnodes.h:618
ArrayBuildStateAny * accumArrayResultAny(ArrayBuildStateAny *astate, Datum dvalue, bool disnull, Oid input_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5461
HeapTuple ExecCopySlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:545
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
uintptr_t Datum
Definition: postgres.h:372
#define BoolGetDatum(X)
Definition: postgres.h:408
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
List * setParam
Definition: primnodes.h:707
static int list_length(const List *l)
Definition: pg_list.h:89
List * parParam
Definition: primnodes.h:709
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
Datum makeArrayResultAny(ArrayBuildStateAny *astate, MemoryContext rcontext, bool release)
Definition: arrayfuncs.c:5489
int errmsg(const char *fmt,...)
Definition: elog.c:797
Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: heaptuple.c:1141
Datum value
Definition: params.h:100
void ExecSetParamPlan ( SubPlanState node,
ExprContext econtext 
)

Definition at line 911 of file nodeSubplan.c.

References accumArrayResultAny(), ALL_SUBLINK, ANY_SUBLINK, SubPlanState::args, ARRAY_SUBLINK, Assert, tupleDesc::attrs, bms_add_member(), BoolGetDatum, PlanState::chgParam, CTE_SUBLINK, SubPlanState::curArray, CurrentMemoryContext, SubPlanState::curTuple, DatumGetPointer, ExprContext::ecxt_param_exec_vals, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, ExecCopySlotTuple(), ExecEvalExprSwitchContext(), ParamExecData::execPlan, ExecProcNode(), EXISTS_SUBLINK, EXPR_SUBLINK, SubPlan::firstColType, forboth, heap_freetuple(), heap_getattr, i, initArrayResultAny(), ParamExecData::isnull, lfirst, lfirst_int, linitial_int, list_length(), makeArrayResultAny(), MemoryContextSwitchTo(), MULTIEXPR_SUBLINK, NIL, NULL, SubPlan::parParam, pfree(), SubPlanState::planstate, PointerGetDatum, ROWCOMPARE_SUBLINK, SubPlan::setParam, slot_getattr(), SubPlan::subLinkType, SubPlanState::subplan, TupleTableSlot::tts_tupleDescriptor, TupIsNull, and ParamExecData::value.

Referenced by ExecEvalParamExec().

912 {
913  SubPlan *subplan = node->subplan;
914  PlanState *planstate = node->planstate;
915  SubLinkType subLinkType = subplan->subLinkType;
916  MemoryContext oldcontext;
917  TupleTableSlot *slot;
918  ListCell *pvar;
919  ListCell *l;
920  bool found = false;
921  ArrayBuildStateAny *astate = NULL;
922 
923  if (subLinkType == ANY_SUBLINK ||
924  subLinkType == ALL_SUBLINK)
925  elog(ERROR, "ANY/ALL subselect unsupported as initplan");
926  if (subLinkType == CTE_SUBLINK)
927  elog(ERROR, "CTE subplans should not be executed via ExecSetParamPlan");
928 
929  /* Initialize ArrayBuildStateAny in caller's context, if needed */
930  if (subLinkType == ARRAY_SUBLINK)
931  astate = initArrayResultAny(subplan->firstColType,
932  CurrentMemoryContext, true);
933 
934  /*
935  * Must switch to per-query memory context.
936  */
937  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
938 
939  /*
940  * Set Params of this plan from parent plan correlation values. (Any
941  * calculation we have to do is done in the parent econtext, since the
942  * Param values don't need to have per-query lifetime.) Currently, we
943  * expect only MULTIEXPR_SUBLINK plans to have any correlation values.
944  */
945  Assert(subplan->parParam == NIL || subLinkType == MULTIEXPR_SUBLINK);
946  Assert(list_length(subplan->parParam) == list_length(node->args));
947 
948  forboth(l, subplan->parParam, pvar, node->args)
949  {
950  int paramid = lfirst_int(l);
951  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
952 
954  econtext,
955  &(prm->isnull));
956  planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
957  }
958 
959  /*
960  * Run the plan. (If it needs to be rescanned, the first ExecProcNode
961  * call will take care of that.)
962  */
963  for (slot = ExecProcNode(planstate);
964  !TupIsNull(slot);
965  slot = ExecProcNode(planstate))
966  {
967  TupleDesc tdesc = slot->tts_tupleDescriptor;
968  int i = 1;
969 
970  if (subLinkType == EXISTS_SUBLINK)
971  {
972  /* There can be only one setParam... */
973  int paramid = linitial_int(subplan->setParam);
974  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
975 
976  prm->execPlan = NULL;
977  prm->value = BoolGetDatum(true);
978  prm->isnull = false;
979  found = true;
980  break;
981  }
982 
983  if (subLinkType == ARRAY_SUBLINK)
984  {
985  Datum dvalue;
986  bool disnull;
987 
988  found = true;
989  /* stash away current value */
990  Assert(subplan->firstColType == tdesc->attrs[0]->atttypid);
991  dvalue = slot_getattr(slot, 1, &disnull);
992  astate = accumArrayResultAny(astate, dvalue, disnull,
993  subplan->firstColType, oldcontext);
994  /* keep scanning subplan to collect all values */
995  continue;
996  }
997 
998  if (found &&
999  (subLinkType == EXPR_SUBLINK ||
1000  subLinkType == MULTIEXPR_SUBLINK ||
1001  subLinkType == ROWCOMPARE_SUBLINK))
1002  ereport(ERROR,
1003  (errcode(ERRCODE_CARDINALITY_VIOLATION),
1004  errmsg("more than one row returned by a subquery used as an expression")));
1005 
1006  found = true;
1007 
1008  /*
1009  * We need to copy the subplan's tuple into our own context, in case
1010  * any of the params are pass-by-ref type --- the pointers stored in
1011  * the param structs will point at this copied tuple! node->curTuple
1012  * keeps track of the copied tuple for eventual freeing.
1013  */
1014  if (node->curTuple)
1015  heap_freetuple(node->curTuple);
1016  node->curTuple = ExecCopySlotTuple(slot);
1017 
1018  /*
1019  * Now set all the setParam params from the columns of the tuple
1020  */
1021  foreach(l, subplan->setParam)
1022  {
1023  int paramid = lfirst_int(l);
1024  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1025 
1026  prm->execPlan = NULL;
1027  prm->value = heap_getattr(node->curTuple, i, tdesc,
1028  &(prm->isnull));
1029  i++;
1030  }
1031  }
1032 
1033  if (subLinkType == ARRAY_SUBLINK)
1034  {
1035  /* There can be only one setParam... */
1036  int paramid = linitial_int(subplan->setParam);
1037  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1038 
1039  /*
1040  * We build the result array in query context so it won't disappear;
1041  * to avoid leaking memory across repeated calls, we have to remember
1042  * the latest value, much as for curTuple above.
1043  */
1044  if (node->curArray != PointerGetDatum(NULL))
1045  pfree(DatumGetPointer(node->curArray));
1046  node->curArray = makeArrayResultAny(astate,
1047  econtext->ecxt_per_query_memory,
1048  true);
1049  prm->execPlan = NULL;
1050  prm->value = node->curArray;
1051  prm->isnull = false;
1052  }
1053  else if (!found)
1054  {
1055  if (subLinkType == EXISTS_SUBLINK)
1056  {
1057  /* There can be only one setParam... */
1058  int paramid = linitial_int(subplan->setParam);
1059  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1060 
1061  prm->execPlan = NULL;
1062  prm->value = BoolGetDatum(false);
1063  prm->isnull = false;
1064  }
1065  else
1066  {
1067  /* For other sublink types, set all the output params to NULL */
1068  foreach(l, subplan->setParam)
1069  {
1070  int paramid = lfirst_int(l);
1071  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1072 
1073  prm->execPlan = NULL;
1074  prm->value = (Datum) 0;
1075  prm->isnull = true;
1076  }
1077  }
1078  }
1079 
1080  MemoryContextSwitchTo(oldcontext);
1081 }
#define NIL
Definition: pg_list.h:69
Oid firstColType
Definition: primnodes.h:693
void * execPlan
Definition: params.h:99
TupleTableSlot * ExecProcNode(PlanState *node)
Definition: execProcnode.c:398
HeapTuple curTuple
Definition: execnodes.h:759
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:282
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
ArrayBuildStateAny * initArrayResultAny(Oid input_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5416
#define PointerGetDatum(X)
Definition: postgres.h:562
Form_pg_attribute * attrs
Definition: tupdesc.h:74
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SubLinkType subLinkType
Definition: primnodes.h:684
int errcode(int sqlerrcode)
Definition: elog.c:575
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1372
#define linitial_int(l)
Definition: pg_list.h:112
void pfree(void *pointer)
Definition: mcxt.c:950
#define ERROR
Definition: elog.h:43
struct PlanState * planstate
Definition: execnodes.h:755
List * args
Definition: execnodes.h:758
SubPlan * subplan
Definition: execnodes.h:754
#define lfirst_int(lc)
Definition: pg_list.h:107
bool isnull
Definition: params.h:101
ParamExecData * ecxt_param_exec_vals
Definition: execnodes.h:206
#define TupIsNull(slot)
Definition: tuptable.h:138
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
Bitmapset * chgParam
Definition: execnodes.h:856
SubLinkType
Definition: primnodes.h:618
ArrayBuildStateAny * accumArrayResultAny(ArrayBuildStateAny *astate, Datum dvalue, bool disnull, Oid input_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5461
HeapTuple ExecCopySlotTuple(TupleTableSlot *slot)
Definition: execTuples.c:545
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
Datum curArray
Definition: execnodes.h:760
uintptr_t Datum
Definition: postgres.h:372
#define BoolGetDatum(X)
Definition: postgres.h:408
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
List * setParam
Definition: primnodes.h:707
static int list_length(const List *l)
Definition: pg_list.h:89
List * parParam
Definition: primnodes.h:709
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
#define DatumGetPointer(X)
Definition: postgres.h:555
Datum makeArrayResultAny(ArrayBuildStateAny *astate, MemoryContext rcontext, bool release)
Definition: arrayfuncs.c:5489
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: heaptuple.c:1141
Datum value
Definition: params.h:100
#define elog
Definition: elog.h:219
Datum ExecSubPlan ( SubPlanState node,
ExprContext econtext,
bool isNull 
)

Definition at line 62 of file nodeSubplan.c.

References CTE_SUBLINK, elog, ERROR, ExecHashSubPlan(), ExecScanSubPlan(), MULTIEXPR_SUBLINK, NIL, SubPlan::setParam, SubPlan::subLinkType, SubPlanState::subplan, and SubPlan::useHashTable.

Referenced by ExecAlternativeSubPlan(), and ExecEvalSubPlan().

65 {
66  SubPlan *subplan = node->subplan;
67 
68  /* Set non-null as default */
69  *isNull = false;
70 
71  /* Sanity checks */
72  if (subplan->subLinkType == CTE_SUBLINK)
73  elog(ERROR, "CTE subplans should not be executed via ExecSubPlan");
74  if (subplan->setParam != NIL && subplan->subLinkType != MULTIEXPR_SUBLINK)
75  elog(ERROR, "cannot set parent params from subquery");
76 
77  /* Select appropriate evaluation strategy */
78  if (subplan->useHashTable)
79  return ExecHashSubPlan(node, econtext, isNull);
80  else
81  return ExecScanSubPlan(node, econtext, isNull);
82 }
#define NIL
Definition: pg_list.h:69
SubLinkType subLinkType
Definition: primnodes.h:684
#define ERROR
Definition: elog.h:43
SubPlan * subplan
Definition: execnodes.h:754
static Datum ExecHashSubPlan(SubPlanState *node, ExprContext *econtext, bool *isNull)
Definition: nodeSubplan.c:88
static Datum ExecScanSubPlan(SubPlanState *node, ExprContext *econtext, bool *isNull)
Definition: nodeSubplan.c:210
List * setParam
Definition: primnodes.h:707
bool useHashTable
Definition: primnodes.h:698
#define elog
Definition: elog.h:219
static bool findPartialMatch ( TupleHashTable  hashtable,
TupleTableSlot slot,
FmgrInfo eqfunctions 
)
static

Definition at line 610 of file nodeSubplan.c.

References ExecStoreMinimalTuple(), execTuplesUnequal(), TupleHashEntryData::firstTuple, InitTupleHashIterator, TupleHashTableData::keyColIdx, NULL, TupleHashTableData::numCols, ScanTupleHashTable, TupleHashTableData::tableslot, TupleHashTableData::tempcxt, and TermTupleHashIterator.

Referenced by ExecHashSubPlan().

612 {
613  int numCols = hashtable->numCols;
614  AttrNumber *keyColIdx = hashtable->keyColIdx;
615  TupleHashIterator hashiter;
616  TupleHashEntry entry;
617 
618  InitTupleHashIterator(hashtable, &hashiter);
619  while ((entry = ScanTupleHashTable(hashtable, &hashiter)) != NULL)
620  {
621  ExecStoreMinimalTuple(entry->firstTuple, hashtable->tableslot, false);
622  if (!execTuplesUnequal(slot, hashtable->tableslot,
623  numCols, keyColIdx,
624  eqfunctions,
625  hashtable->tempcxt))
626  {
627  TermTupleHashIterator(&hashiter);
628  return true;
629  }
630  }
631  /* No TermTupleHashIterator call needed here */
632  return false;
633 }
#define ScanTupleHashTable(htable, iter)
Definition: execnodes.h:631
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:384
#define TermTupleHashIterator(iter)
Definition: execnodes.h:627
MinimalTuple firstTuple
Definition: execnodes.h:586
tuplehash_iterator TupleHashIterator
Definition: execnodes.h:618
AttrNumber * keyColIdx
Definition: execnodes.h:604
bool execTuplesUnequal(TupleTableSlot *slot1, TupleTableSlot *slot2, int numCols, AttrNumber *matchColIdx, FmgrInfo *eqfunctions, MemoryContext evalContext)
Definition: execGrouping.c:139
#define NULL
Definition: c.h:229
TupleTableSlot * tableslot
Definition: execnodes.h:610
#define InitTupleHashIterator(htable, iter)
Definition: execnodes.h:625
MemoryContext tempcxt
Definition: execnodes.h:608
int16 AttrNumber
Definition: attnum.h:21
static bool slotAllNulls ( TupleTableSlot slot)
static

Definition at line 642 of file nodeSubplan.c.

References i, tupleDesc::natts, slot_attisnull(), and TupleTableSlot::tts_tupleDescriptor.

Referenced by ExecHashSubPlan().

643 {
644  int ncols = slot->tts_tupleDescriptor->natts;
645  int i;
646 
647  for (i = 1; i <= ncols; i++)
648  {
649  if (!slot_attisnull(slot, i))
650  return false;
651  }
652  return true;
653 }
int natts
Definition: tupdesc.h:73
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: heaptuple.c:1328
int i
static bool slotNoNulls ( TupleTableSlot slot)
static

Definition at line 662 of file nodeSubplan.c.

References i, tupleDesc::natts, slot_attisnull(), and TupleTableSlot::tts_tupleDescriptor.

Referenced by buildSubPlanHash(), and ExecHashSubPlan().

663 {
664  int ncols = slot->tts_tupleDescriptor->natts;
665  int i;
666 
667  for (i = 1; i <= ncols; i++)
668  {
669  if (slot_attisnull(slot, i))
670  return false;
671  }
672  return true;
673 }
int natts
Definition: tupdesc.h:73
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: heaptuple.c:1328
int i