PostgreSQL Source Code  git master
nodeSubplan.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/htup_details.h"
#include "executor/executor.h"
#include "executor/nodeSubplan.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.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)
 
static bool execTuplesUnequal (TupleTableSlot *slot1, TupleTableSlot *slot2, int numCols, AttrNumber *matchColIdx, FmgrInfo *eqfunctions, const Oid *collations, MemoryContext evalContext)
 
SubPlanStateExecInitSubPlan (SubPlan *subplan, PlanState *parent)
 
void ExecSetParamPlan (SubPlanState *node, ExprContext *econtext)
 
void ExecSetParamPlanMulti (const Bitmapset *params, ExprContext *econtext)
 
void ExecReScanSetParamPlan (SubPlanState *node, PlanState *parent)
 

Function Documentation

◆ buildSubPlanHash()

static void buildSubPlanHash ( SubPlanState node,
ExprContext econtext 
)
static

Definition at line 496 of file nodeSubplan.c.

497 {
498  SubPlan *subplan = node->subplan;
499  PlanState *planstate = node->planstate;
500  int ncols = node->numCols;
501  ExprContext *innerecontext = node->innerecontext;
502  MemoryContext oldcontext;
503  long nbuckets;
504  TupleTableSlot *slot;
505 
506  Assert(subplan->subLinkType == ANY_SUBLINK);
507 
508  /*
509  * If we already had any hash tables, reset 'em; otherwise create empty
510  * hash table(s).
511  *
512  * If we need to distinguish accurately between FALSE and UNKNOWN (i.e.,
513  * NULL) results of the IN operation, then we have to store subplan output
514  * rows that are partly or wholly NULL. We store such rows in a separate
515  * hash table that we expect will be much smaller than the main table. (We
516  * can use hashing to eliminate partly-null rows that are not distinct. We
517  * keep them separate to minimize the cost of the inevitable full-table
518  * searches; see findPartialMatch.)
519  *
520  * If it's not necessary to distinguish FALSE and UNKNOWN, then we don't
521  * need to store subplan output rows that contain NULL.
522  */
524  node->havehashrows = false;
525  node->havenullrows = false;
526 
527  nbuckets = clamp_cardinality_to_long(planstate->plan->plan_rows);
528  if (nbuckets < 1)
529  nbuckets = 1;
530 
531  if (node->hashtable)
533  else
535  node->descRight,
536  ncols,
537  node->keyColIdx,
538  node->tab_eq_funcoids,
539  node->tab_hash_funcs,
540  node->tab_collations,
541  nbuckets,
542  0,
543  node->planstate->state->es_query_cxt,
544  node->hashtablecxt,
545  node->hashtempcxt,
546  false);
547 
548  if (!subplan->unknownEqFalse)
549  {
550  if (ncols == 1)
551  nbuckets = 1; /* there can only be one entry */
552  else
553  {
554  nbuckets /= 16;
555  if (nbuckets < 1)
556  nbuckets = 1;
557  }
558 
559  if (node->hashnulls)
561  else
563  node->descRight,
564  ncols,
565  node->keyColIdx,
566  node->tab_eq_funcoids,
567  node->tab_hash_funcs,
568  node->tab_collations,
569  nbuckets,
570  0,
571  node->planstate->state->es_query_cxt,
572  node->hashtablecxt,
573  node->hashtempcxt,
574  false);
575  }
576  else
577  node->hashnulls = NULL;
578 
579  /*
580  * We are probably in a short-lived expression-evaluation context. Switch
581  * to the per-query context for manipulating the child plan.
582  */
583  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
584 
585  /*
586  * Reset subplan to start.
587  */
588  ExecReScan(planstate);
589 
590  /*
591  * Scan the subplan and load the hash table(s). Note that when there are
592  * duplicate rows coming out of the sub-select, only one copy is stored.
593  */
594  for (slot = ExecProcNode(planstate);
595  !TupIsNull(slot);
596  slot = ExecProcNode(planstate))
597  {
598  int col = 1;
599  ListCell *plst;
600  bool isnew;
601 
602  /*
603  * Load up the Params representing the raw sub-select outputs, then
604  * form the projection tuple to store in the hashtable.
605  */
606  foreach(plst, subplan->paramIds)
607  {
608  int paramid = lfirst_int(plst);
609  ParamExecData *prmdata;
610 
611  prmdata = &(innerecontext->ecxt_param_exec_vals[paramid]);
612  Assert(prmdata->execPlan == NULL);
613  prmdata->value = slot_getattr(slot, col,
614  &(prmdata->isnull));
615  col++;
616  }
617  slot = ExecProject(node->projRight);
618 
619  /*
620  * If result contains any nulls, store separately or not at all.
621  */
622  if (slotNoNulls(slot))
623  {
624  (void) LookupTupleHashEntry(node->hashtable, slot, &isnew, NULL);
625  node->havehashrows = true;
626  }
627  else if (node->hashnulls)
628  {
629  (void) LookupTupleHashEntry(node->hashnulls, slot, &isnew, NULL);
630  node->havenullrows = true;
631  }
632 
633  /*
634  * Reset innerecontext after each inner tuple to free any memory used
635  * during ExecProject.
636  */
637  ResetExprContext(innerecontext);
638  }
639 
640  /*
641  * Since the projected tuples are in the sub-query's context and not the
642  * main context, we'd better clear the tuple slot before there's any
643  * chance of a reset of the sub-query's context. Else we will have the
644  * potential for a double free attempt. (XXX possibly no longer needed,
645  * but can't hurt.)
646  */
648 
649  MemoryContextSwitchTo(oldcontext);
650 }
#define Assert(condition)
Definition: c.h:858
long clamp_cardinality_to_long(Cardinality x)
Definition: costsize.c:265
void ExecReScan(PlanState *node)
Definition: execAmi.c:76
TupleHashEntry LookupTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot, bool *isnew, uint32 *hash)
Definition: execGrouping.c:305
TupleHashTable BuildTupleHashTableExt(PlanState *parent, TupleDesc inputDesc, int numCols, AttrNumber *keyColIdx, const Oid *eqfuncoids, FmgrInfo *hashfunctions, Oid *collations, long nbuckets, Size additionalsize, MemoryContext metacxt, MemoryContext tablecxt, MemoryContext tempcxt, bool use_variable_hash_iv)
Definition: execGrouping.c:153
void ResetTupleHashTable(TupleHashTable hashtable)
Definition: execGrouping.c:284
static TupleTableSlot * ExecProject(ProjectionInfo *projInfo)
Definition: executor.h:387
#define ResetExprContext(econtext)
Definition: executor.h:555
static TupleTableSlot * ExecProcNode(PlanState *node)
Definition: executor.h:273
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
static bool slotNoNulls(TupleTableSlot *slot)
Definition: nodeSubplan.c:791
#define lfirst_int(lc)
Definition: pg_list.h:173
@ ANY_SUBLINK
Definition: primnodes.h:999
MemoryContextSwitchTo(old_ctx)
MemoryContext es_query_cxt
Definition: execnodes.h:671
ParamExecData * ecxt_param_exec_vals
Definition: execnodes.h:268
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:264
TupleTableSlot * resultslot
Definition: execnodes.h:97
bool isnull
Definition: params.h:150
Datum value
Definition: params.h:149
void * execPlan
Definition: params.h:148
Plan * plan
Definition: execnodes.h:1119
EState * state
Definition: execnodes.h:1121
Cardinality plan_rows
Definition: plannodes.h:135
ExprState pi_state
Definition: execnodes.h:364
TupleHashTable hashtable
Definition: execnodes.h:974
MemoryContext hashtablecxt
Definition: execnodes.h:978
Oid * tab_eq_funcoids
Definition: execnodes.h:984
ExprContext * innerecontext
Definition: execnodes.h:980
FmgrInfo * tab_hash_funcs
Definition: execnodes.h:987
MemoryContext hashtempcxt
Definition: execnodes.h:979
AttrNumber * keyColIdx
Definition: execnodes.h:983
struct PlanState * planstate
Definition: execnodes.h:965
TupleDesc descRight
Definition: execnodes.h:971
SubPlan * subplan
Definition: execnodes.h:964
ProjectionInfo * projRight
Definition: execnodes.h:973
bool havenullrows
Definition: execnodes.h:977
struct PlanState * parent
Definition: execnodes.h:966
Oid * tab_collations
Definition: execnodes.h:986
TupleHashTable hashnulls
Definition: execnodes.h:975
bool havehashrows
Definition: execnodes.h:976
List * paramIds
Definition: primnodes.h:1068
bool unknownEqFalse
Definition: primnodes.h:1081
SubLinkType subLinkType
Definition: primnodes.h:1065
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:454
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:395
#define TupIsNull(slot)
Definition: tuptable.h:306

References ANY_SUBLINK, Assert, BuildTupleHashTableExt(), clamp_cardinality_to_long(), SubPlanState::descRight, ExprContext::ecxt_param_exec_vals, ExprContext::ecxt_per_query_memory, EState::es_query_cxt, 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, LookupTupleHashEntry(), MemoryContextReset(), MemoryContextSwitchTo(), SubPlanState::numCols, SubPlan::paramIds, SubPlanState::parent, ProjectionInfo::pi_state, PlanState::plan, Plan::plan_rows, SubPlanState::planstate, SubPlanState::projRight, ResetExprContext, ResetTupleHashTable(), ExprState::resultslot, slot_getattr(), slotNoNulls(), PlanState::state, SubPlan::subLinkType, SubPlanState::subplan, SubPlanState::tab_collations, SubPlanState::tab_eq_funcoids, SubPlanState::tab_hash_funcs, TupIsNull, SubPlan::unknownEqFalse, and ParamExecData::value.

Referenced by ExecHashSubPlan().

◆ ExecHashSubPlan()

static Datum ExecHashSubPlan ( SubPlanState node,
ExprContext econtext,
bool isNull 
)
static

Definition at line 101 of file nodeSubplan.c.

104 {
105  SubPlan *subplan = node->subplan;
106  PlanState *planstate = node->planstate;
107  TupleTableSlot *slot;
108 
109  /* Shouldn't have any direct correlation Vars */
110  if (subplan->parParam != NIL || subplan->args != NIL)
111  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  */
117  if (node->hashtable == NULL || planstate->chgParam != NULL)
118  buildSubPlanHash(node, econtext);
119 
120  /*
121  * The result for an empty subplan is always FALSE; no need to evaluate
122  * lefthand side.
123  */
124  *isNull = false;
125  if (!node->havehashrows && !node->havenullrows)
126  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  node->projLeft->pi_exprContext = econtext;
133  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  */
157  if (slotNoNulls(slot))
158  {
159  if (node->havehashrows &&
161  slot,
162  node->cur_eq_comp,
163  node->lhs_hash_funcs) != NULL)
164  {
165  ExecClearTuple(slot);
166  return BoolGetDatum(true);
167  }
168  if (node->havenullrows &&
169  findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
170  {
171  ExecClearTuple(slot);
172  *isNull = true;
173  return BoolGetDatum(false);
174  }
175  ExecClearTuple(slot);
176  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  if (node->hashnulls == NULL)
190  {
191  ExecClearTuple(slot);
192  return BoolGetDatum(false);
193  }
194  if (slotAllNulls(slot))
195  {
196  ExecClearTuple(slot);
197  *isNull = true;
198  return BoolGetDatum(false);
199  }
200  /* Scan partly-null table first, since more likely to get a match */
201  if (node->havenullrows &&
202  findPartialMatch(node->hashnulls, slot, node->cur_eq_funcs))
203  {
204  ExecClearTuple(slot);
205  *isNull = true;
206  return BoolGetDatum(false);
207  }
208  if (node->havehashrows &&
209  findPartialMatch(node->hashtable, slot, node->cur_eq_funcs))
210  {
211  ExecClearTuple(slot);
212  *isNull = true;
213  return BoolGetDatum(false);
214  }
215  ExecClearTuple(slot);
216  return BoolGetDatum(false);
217 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
TupleHashEntry FindTupleHashEntry(TupleHashTable hashtable, TupleTableSlot *slot, ExprState *eqcomp, FmgrInfo *hashfunctions)
Definition: execGrouping.c:392
static void buildSubPlanHash(SubPlanState *node, ExprContext *econtext)
Definition: nodeSubplan.c:496
static bool slotAllNulls(TupleTableSlot *slot)
Definition: nodeSubplan.c:771
static bool findPartialMatch(TupleHashTable hashtable, TupleTableSlot *slot, FmgrInfo *eqfunctions)
Definition: nodeSubplan.c:736
#define NIL
Definition: pg_list.h:68
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
Bitmapset * chgParam
Definition: execnodes.h:1151
ExprContext * pi_exprContext
Definition: execnodes.h:366
ExprState * cur_eq_comp
Definition: execnodes.h:991
FmgrInfo * cur_eq_funcs
Definition: execnodes.h:990
FmgrInfo * lhs_hash_funcs
Definition: execnodes.h:989
ProjectionInfo * projLeft
Definition: execnodes.h:972
List * args
Definition: primnodes.h:1091
List * parParam
Definition: primnodes.h:1090

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

Referenced by ExecSubPlan().

◆ ExecInitSubPlan()

SubPlanState* ExecInitSubPlan ( SubPlan subplan,
PlanState parent 
)

Definition at line 819 of file nodeSubplan.c.

820 {
822  EState *estate = parent->state;
823 
824  sstate->subplan = subplan;
825 
826  /* Link the SubPlanState to already-initialized subplan */
827  sstate->planstate = (PlanState *) list_nth(estate->es_subplanstates,
828  subplan->plan_id - 1);
829 
830  /*
831  * This check can fail if the planner mistakenly puts a parallel-unsafe
832  * subplan into a parallelized subquery; see ExecSerializePlan.
833  */
834  if (sstate->planstate == NULL)
835  elog(ERROR, "subplan \"%s\" was not initialized",
836  subplan->plan_name);
837 
838  /* Link to parent's state, too */
839  sstate->parent = parent;
840 
841  /* Initialize subexpressions */
842  sstate->testexpr = ExecInitExpr((Expr *) subplan->testexpr, parent);
843 
844  /*
845  * initialize my state
846  */
847  sstate->curTuple = NULL;
848  sstate->curArray = PointerGetDatum(NULL);
849  sstate->projLeft = NULL;
850  sstate->projRight = NULL;
851  sstate->hashtable = NULL;
852  sstate->hashnulls = NULL;
853  sstate->hashtablecxt = NULL;
854  sstate->hashtempcxt = NULL;
855  sstate->innerecontext = NULL;
856  sstate->keyColIdx = NULL;
857  sstate->tab_eq_funcoids = NULL;
858  sstate->tab_hash_funcs = NULL;
859  sstate->tab_eq_funcs = NULL;
860  sstate->tab_collations = NULL;
861  sstate->lhs_hash_funcs = NULL;
862  sstate->cur_eq_funcs = NULL;
863 
864  /*
865  * If this is an initplan, it has output parameters that the parent plan
866  * will use, so mark those parameters as needing evaluation. We don't
867  * actually run the subplan until we first need one of its outputs.
868  *
869  * A CTE subplan's output parameter is never to be evaluated in the normal
870  * way, so skip this in that case.
871  *
872  * Note that we don't set parent->chgParam here: the parent plan hasn't
873  * been run yet, so no need to force it to re-run.
874  */
875  if (subplan->setParam != NIL && subplan->parParam == NIL &&
876  subplan->subLinkType != CTE_SUBLINK)
877  {
878  ListCell *lst;
879 
880  foreach(lst, subplan->setParam)
881  {
882  int paramid = lfirst_int(lst);
883  ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
884 
885  prm->execPlan = sstate;
886  }
887  }
888 
889  /*
890  * If we are going to hash the subquery output, initialize relevant stuff.
891  * (We don't create the hashtable until needed, though.)
892  */
893  if (subplan->useHashTable)
894  {
895  int ncols,
896  i;
897  TupleDesc tupDescLeft;
898  TupleDesc tupDescRight;
899  Oid *cross_eq_funcoids;
900  TupleTableSlot *slot;
901  List *oplist,
902  *lefttlist,
903  *righttlist;
904  ListCell *l;
905 
906  /* We need a memory context to hold the hash table(s) */
907  sstate->hashtablecxt =
909  "Subplan HashTable Context",
911  /* and a small one for the hash tables to use as temp storage */
912  sstate->hashtempcxt =
914  "Subplan HashTable Temp Context",
916  /* and a short-lived exprcontext for function evaluation */
917  sstate->innerecontext = CreateExprContext(estate);
918 
919  /*
920  * We use ExecProject to evaluate the lefthand and righthand
921  * expression lists and form tuples. (You might think that we could
922  * use the sub-select's output tuples directly, but that is not the
923  * case if we had to insert any run-time coercions of the sub-select's
924  * output datatypes; anyway this avoids storing any resjunk columns
925  * that might be in the sub-select's output.) Run through the
926  * combining expressions to build tlists for the lefthand and
927  * righthand sides.
928  *
929  * We also extract the combining operators themselves to initialize
930  * the equality and hashing functions for the hash tables.
931  */
932  if (IsA(subplan->testexpr, OpExpr))
933  {
934  /* single combining operator */
935  oplist = list_make1(subplan->testexpr);
936  }
937  else if (is_andclause(subplan->testexpr))
938  {
939  /* multiple combining operators */
940  oplist = castNode(BoolExpr, subplan->testexpr)->args;
941  }
942  else
943  {
944  /* shouldn't see anything else in a hashable subplan */
945  elog(ERROR, "unrecognized testexpr type: %d",
946  (int) nodeTag(subplan->testexpr));
947  oplist = NIL; /* keep compiler quiet */
948  }
949  ncols = list_length(oplist);
950 
951  lefttlist = righttlist = NIL;
952  sstate->numCols = ncols;
953  sstate->keyColIdx = (AttrNumber *) palloc(ncols * sizeof(AttrNumber));
954  sstate->tab_eq_funcoids = (Oid *) palloc(ncols * sizeof(Oid));
955  sstate->tab_collations = (Oid *) palloc(ncols * sizeof(Oid));
956  sstate->tab_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
957  sstate->tab_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
958  sstate->lhs_hash_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
959  sstate->cur_eq_funcs = (FmgrInfo *) palloc(ncols * sizeof(FmgrInfo));
960  /* we'll need the cross-type equality fns below, but not in sstate */
961  cross_eq_funcoids = (Oid *) palloc(ncols * sizeof(Oid));
962 
963  i = 1;
964  foreach(l, oplist)
965  {
966  OpExpr *opexpr = lfirst_node(OpExpr, l);
967  Expr *expr;
968  TargetEntry *tle;
969  Oid rhs_eq_oper;
970  Oid left_hashfn;
971  Oid right_hashfn;
972 
973  Assert(list_length(opexpr->args) == 2);
974 
975  /* Process lefthand argument */
976  expr = (Expr *) linitial(opexpr->args);
977  tle = makeTargetEntry(expr,
978  i,
979  NULL,
980  false);
981  lefttlist = lappend(lefttlist, tle);
982 
983  /* Process righthand argument */
984  expr = (Expr *) lsecond(opexpr->args);
985  tle = makeTargetEntry(expr,
986  i,
987  NULL,
988  false);
989  righttlist = lappend(righttlist, tle);
990 
991  /* Lookup the equality function (potentially cross-type) */
992  cross_eq_funcoids[i - 1] = opexpr->opfuncid;
993  fmgr_info(opexpr->opfuncid, &sstate->cur_eq_funcs[i - 1]);
994  fmgr_info_set_expr((Node *) opexpr, &sstate->cur_eq_funcs[i - 1]);
995 
996  /* Look up the equality function for the RHS type */
997  if (!get_compatible_hash_operators(opexpr->opno,
998  NULL, &rhs_eq_oper))
999  elog(ERROR, "could not find compatible hash operator for operator %u",
1000  opexpr->opno);
1001  sstate->tab_eq_funcoids[i - 1] = get_opcode(rhs_eq_oper);
1002  fmgr_info(sstate->tab_eq_funcoids[i - 1],
1003  &sstate->tab_eq_funcs[i - 1]);
1004 
1005  /* Lookup the associated hash functions */
1006  if (!get_op_hash_functions(opexpr->opno,
1007  &left_hashfn, &right_hashfn))
1008  elog(ERROR, "could not find hash function for hash operator %u",
1009  opexpr->opno);
1010  fmgr_info(left_hashfn, &sstate->lhs_hash_funcs[i - 1]);
1011  fmgr_info(right_hashfn, &sstate->tab_hash_funcs[i - 1]);
1012 
1013  /* Set collation */
1014  sstate->tab_collations[i - 1] = opexpr->inputcollid;
1015 
1016  /* keyColIdx is just column numbers 1..n */
1017  sstate->keyColIdx[i - 1] = i;
1018 
1019  i++;
1020  }
1021 
1022  /*
1023  * Construct tupdescs, slots and projection nodes for left and right
1024  * sides. The lefthand expressions will be evaluated in the parent
1025  * plan node's exprcontext, which we don't have access to here.
1026  * Fortunately we can just pass NULL for now and fill it in later
1027  * (hack alert!). The righthand expressions will be evaluated in our
1028  * own innerecontext.
1029  */
1030  tupDescLeft = ExecTypeFromTL(lefttlist);
1031  slot = ExecInitExtraTupleSlot(estate, tupDescLeft, &TTSOpsVirtual);
1032  sstate->projLeft = ExecBuildProjectionInfo(lefttlist,
1033  NULL,
1034  slot,
1035  parent,
1036  NULL);
1037 
1038  sstate->descRight = tupDescRight = ExecTypeFromTL(righttlist);
1039  slot = ExecInitExtraTupleSlot(estate, tupDescRight, &TTSOpsVirtual);
1040  sstate->projRight = ExecBuildProjectionInfo(righttlist,
1041  sstate->innerecontext,
1042  slot,
1043  sstate->planstate,
1044  NULL);
1045 
1046  /*
1047  * Create comparator for lookups of rows in the table (potentially
1048  * cross-type comparisons).
1049  */
1050  sstate->cur_eq_comp = ExecBuildGroupingEqual(tupDescLeft, tupDescRight,
1052  ncols,
1053  sstate->keyColIdx,
1054  cross_eq_funcoids,
1055  sstate->tab_collations,
1056  parent);
1057  }
1058 
1059  return sstate;
1060 }
int16 AttrNumber
Definition: attnum.h:21
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:138
ProjectionInfo * ExecBuildProjectionInfo(List *targetList, ExprContext *econtext, TupleTableSlot *slot, PlanState *parent, TupleDesc inputDesc)
Definition: execExpr.c:365
ExprState * ExecBuildGroupingEqual(TupleDesc ldesc, TupleDesc rdesc, const TupleTableSlotOps *lops, const TupleTableSlotOps *rops, int numCols, const AttrNumber *keyColIdx, const Oid *eqfunctions, const Oid *collations, PlanState *parent)
Definition: execExpr.c:4125
const TupleTableSlotOps TTSOpsVirtual
Definition: execTuples.c:84
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate, TupleDesc tupledesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1918
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:86
TupleDesc ExecTypeFromTL(List *targetList)
Definition: execTuples.c:2025
ExprContext * CreateExprContext(EState *estate)
Definition: execUtils.c:304
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
#define fmgr_info_set_expr(expr, finfo)
Definition: fmgr.h:135
int i
Definition: isn.c:73
List * lappend(List *list, void *datum)
Definition: list.c:339
bool get_compatible_hash_operators(Oid opno, Oid *lhs_opno, Oid *rhs_opno)
Definition: lsyscache.c:410
RegProcedure get_opcode(Oid opno)
Definition: lsyscache.c:1285
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition: lsyscache.c:510
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
void * palloc(Size size)
Definition: mcxt.c:1317
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
static bool is_andclause(const void *clause)
Definition: nodeFuncs.h:105
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define makeNode(_type_)
Definition: nodes.h:155
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define list_make1(x1)
Definition: pg_list.h:212
#define linitial(l)
Definition: pg_list.h:178
#define lsecond(l)
Definition: pg_list.h:183
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
unsigned int Oid
Definition: postgres_ext.h:31
@ CTE_SUBLINK
Definition: primnodes.h:1004
ParamExecData * es_param_exec_vals
Definition: execnodes.h:666
List * es_subplanstates
Definition: execnodes.h:686
Definition: fmgr.h:57
Definition: pg_list.h:54
Definition: nodes.h:129
Oid opno
Definition: primnodes.h:818
List * args
Definition: primnodes.h:836
FmgrInfo * tab_eq_funcs
Definition: execnodes.h:988
HeapTuple curTuple
Definition: execnodes.h:968
ExprState * testexpr
Definition: execnodes.h:967
Datum curArray
Definition: execnodes.h:969
int plan_id
Definition: primnodes.h:1070
char * plan_name
Definition: primnodes.h:1072
bool useHashTable
Definition: primnodes.h:1079
Node * testexpr
Definition: primnodes.h:1067
List * setParam
Definition: primnodes.h:1088

References ALLOCSET_DEFAULT_SIZES, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, OpExpr::args, Assert, castNode, CreateExprContext(), CTE_SUBLINK, SubPlanState::cur_eq_comp, SubPlanState::cur_eq_funcs, SubPlanState::curArray, CurrentMemoryContext, SubPlanState::curTuple, SubPlanState::descRight, elog, ERROR, EState::es_param_exec_vals, EState::es_subplanstates, ExecBuildGroupingEqual(), ExecBuildProjectionInfo(), ExecInitExpr(), ExecInitExtraTupleSlot(), ParamExecData::execPlan, 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, is_andclause(), IsA, SubPlanState::keyColIdx, lappend(), lfirst_int, lfirst_node, SubPlanState::lhs_hash_funcs, linitial, list_length(), list_make1, list_nth(), lsecond, makeNode, makeTargetEntry(), NIL, nodeTag, SubPlanState::numCols, OpExpr::opno, palloc(), SubPlanState::parent, SubPlan::parParam, SubPlan::plan_id, SubPlan::plan_name, SubPlanState::planstate, PointerGetDatum(), SubPlanState::projLeft, SubPlanState::projRight, SubPlan::setParam, PlanState::state, SubPlan::subLinkType, SubPlanState::subplan, SubPlanState::tab_collations, SubPlanState::tab_eq_funcoids, SubPlanState::tab_eq_funcs, SubPlanState::tab_hash_funcs, SubPlanState::testexpr, SubPlan::testexpr, TTSOpsMinimalTuple, TTSOpsVirtual, and SubPlan::useHashTable.

Referenced by ExecInitNode(), and ExecInitSubPlanExpr().

◆ ExecReScanSetParamPlan()

void ExecReScanSetParamPlan ( SubPlanState node,
PlanState parent 
)

Definition at line 1286 of file nodeSubplan.c.

1287 {
1288  PlanState *planstate = node->planstate;
1289  SubPlan *subplan = node->subplan;
1290  EState *estate = parent->state;
1291  ListCell *l;
1292 
1293  /* sanity checks */
1294  if (subplan->parParam != NIL)
1295  elog(ERROR, "direct correlated subquery unsupported as initplan");
1296  if (subplan->setParam == NIL)
1297  elog(ERROR, "setParam list of initplan is empty");
1298  if (bms_is_empty(planstate->plan->extParam))
1299  elog(ERROR, "extParam set of initplan is empty");
1300 
1301  /*
1302  * Don't actually re-scan: it'll happen inside ExecSetParamPlan if needed.
1303  */
1304 
1305  /*
1306  * Mark this subplan's output parameters as needing recalculation.
1307  *
1308  * CTE subplans are never executed via parameter recalculation; instead
1309  * they get run when called by nodeCtescan.c. So don't mark the output
1310  * parameter of a CTE subplan as dirty, but do set the chgParam bit for it
1311  * so that dependent plan nodes will get told to rescan.
1312  */
1313  foreach(l, subplan->setParam)
1314  {
1315  int paramid = lfirst_int(l);
1316  ParamExecData *prm = &(estate->es_param_exec_vals[paramid]);
1317 
1318  if (subplan->subLinkType != CTE_SUBLINK)
1319  prm->execPlan = node;
1320 
1321  parent->chgParam = bms_add_member(parent->chgParam, paramid);
1322  }
1323 }
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define bms_is_empty(a)
Definition: bitmapset.h:118
Bitmapset * extParam
Definition: plannodes.h:171

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().

◆ ExecScanSubPlan()

static Datum ExecScanSubPlan ( SubPlanState node,
ExprContext econtext,
bool isNull 
)
static

Definition at line 223 of file nodeSubplan.c.

226 {
227  SubPlan *subplan = node->subplan;
228  PlanState *planstate = node->planstate;
229  SubLinkType subLinkType = subplan->subLinkType;
230  MemoryContext oldcontext;
231  TupleTableSlot *slot;
232  Datum result;
233  bool found = false; /* true if got at least one subplan tuple */
234  ListCell *l;
235  ArrayBuildStateAny *astate = NULL;
236 
237  /* Initialize ArrayBuildStateAny in caller's context, if needed */
238  if (subLinkType == ARRAY_SUBLINK)
239  astate = initArrayResultAny(subplan->firstColType,
240  CurrentMemoryContext, true);
241 
242  /*
243  * We are probably in a short-lived expression-evaluation context. Switch
244  * to the per-query context for manipulating the child plan's chgParam,
245  * calling ExecProcNode on it, etc.
246  */
247  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
248 
249  /*
250  * We rely on the caller to evaluate plan correlation values, if
251  * necessary. However we still need to record the fact that the values
252  * (might have) changed, otherwise the ExecReScan() below won't know that
253  * nodes need to be rescanned.
254  */
255  foreach(l, subplan->parParam)
256  {
257  int paramid = lfirst_int(l);
258 
259  planstate->chgParam = bms_add_member(planstate->chgParam, paramid);
260  }
261 
262  /* with that done, we can reset the subplan */
263  ExecReScan(planstate);
264 
265  /*
266  * For all sublink types except EXPR_SUBLINK and ARRAY_SUBLINK, the result
267  * is boolean as are the results of the combining operators. We combine
268  * results across tuples (if the subplan produces more than one) using OR
269  * semantics for ANY_SUBLINK or AND semantics for ALL_SUBLINK.
270  * (ROWCOMPARE_SUBLINK doesn't allow multiple tuples from the subplan.)
271  * NULL results from the combining operators are handled according to the
272  * usual SQL semantics for OR and AND. The result for no input tuples is
273  * FALSE for ANY_SUBLINK, TRUE for ALL_SUBLINK, NULL for
274  * ROWCOMPARE_SUBLINK.
275  *
276  * For EXPR_SUBLINK we require the subplan to produce no more than one
277  * tuple, else an error is raised. If zero tuples are produced, we return
278  * NULL. Assuming we get a tuple, we just use its first column (there can
279  * be only one non-junk column in this case).
280  *
281  * For MULTIEXPR_SUBLINK, we push the per-column subplan outputs out to
282  * the setParams and then return a dummy false value. There must not be
283  * multiple tuples returned from the subplan; if zero tuples are produced,
284  * set the setParams to NULL.
285  *
286  * For ARRAY_SUBLINK we allow the subplan to produce any number of tuples,
287  * and form an array of the first column's values. Note in particular
288  * that we produce a zero-element array if no tuples are produced (this is
289  * a change from pre-8.3 behavior of returning NULL).
290  */
291  result = BoolGetDatum(subLinkType == ALL_SUBLINK);
292  *isNull = false;
293 
294  for (slot = ExecProcNode(planstate);
295  !TupIsNull(slot);
296  slot = ExecProcNode(planstate))
297  {
298  TupleDesc tdesc = slot->tts_tupleDescriptor;
299  Datum rowresult;
300  bool rownull;
301  int col;
302  ListCell *plst;
303 
304  if (subLinkType == EXISTS_SUBLINK)
305  {
306  found = true;
307  result = BoolGetDatum(true);
308  break;
309  }
310 
311  if (subLinkType == EXPR_SUBLINK)
312  {
313  /* cannot allow multiple input tuples for EXPR sublink */
314  if (found)
315  ereport(ERROR,
316  (errcode(ERRCODE_CARDINALITY_VIOLATION),
317  errmsg("more than one row returned by a subquery used as an expression")));
318  found = true;
319 
320  /*
321  * We need to copy the subplan's tuple in case the result is of
322  * pass-by-ref type --- our return value will point into this
323  * copied tuple! Can't use the subplan's instance of the tuple
324  * since it won't still be valid after next ExecProcNode() call.
325  * node->curTuple keeps track of the copied tuple for eventual
326  * freeing.
327  */
328  if (node->curTuple)
329  heap_freetuple(node->curTuple);
330  node->curTuple = ExecCopySlotHeapTuple(slot);
331 
332  result = heap_getattr(node->curTuple, 1, tdesc, isNull);
333  /* keep scanning subplan to make sure there's only one tuple */
334  continue;
335  }
336 
337  if (subLinkType == MULTIEXPR_SUBLINK)
338  {
339  /* cannot allow multiple input tuples for MULTIEXPR sublink */
340  if (found)
341  ereport(ERROR,
342  (errcode(ERRCODE_CARDINALITY_VIOLATION),
343  errmsg("more than one row returned by a subquery used as an expression")));
344  found = true;
345 
346  /*
347  * We need to copy the subplan's tuple in case any result is of
348  * pass-by-ref type --- our output values will point into this
349  * copied tuple! Can't use the subplan's instance of the tuple
350  * since it won't still be valid after next ExecProcNode() call.
351  * node->curTuple keeps track of the copied tuple for eventual
352  * freeing.
353  */
354  if (node->curTuple)
355  heap_freetuple(node->curTuple);
356  node->curTuple = ExecCopySlotHeapTuple(slot);
357 
358  /*
359  * Now set all the setParam params from the columns of the tuple
360  */
361  col = 1;
362  foreach(plst, subplan->setParam)
363  {
364  int paramid = lfirst_int(plst);
365  ParamExecData *prmdata;
366 
367  prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
368  Assert(prmdata->execPlan == NULL);
369  prmdata->value = heap_getattr(node->curTuple, col, tdesc,
370  &(prmdata->isnull));
371  col++;
372  }
373 
374  /* keep scanning subplan to make sure there's only one tuple */
375  continue;
376  }
377 
378  if (subLinkType == ARRAY_SUBLINK)
379  {
380  Datum dvalue;
381  bool disnull;
382 
383  found = true;
384  /* stash away current value */
385  Assert(subplan->firstColType == TupleDescAttr(tdesc, 0)->atttypid);
386  dvalue = slot_getattr(slot, 1, &disnull);
387  astate = accumArrayResultAny(astate, dvalue, disnull,
388  subplan->firstColType, oldcontext);
389  /* keep scanning subplan to collect all values */
390  continue;
391  }
392 
393  /* cannot allow multiple input tuples for ROWCOMPARE sublink either */
394  if (subLinkType == ROWCOMPARE_SUBLINK && found)
395  ereport(ERROR,
396  (errcode(ERRCODE_CARDINALITY_VIOLATION),
397  errmsg("more than one row returned by a subquery used as an expression")));
398 
399  found = true;
400 
401  /*
402  * For ALL, ANY, and ROWCOMPARE sublinks, load up the Params
403  * representing the columns of the sub-select, and then evaluate the
404  * combining expression.
405  */
406  col = 1;
407  foreach(plst, subplan->paramIds)
408  {
409  int paramid = lfirst_int(plst);
410  ParamExecData *prmdata;
411 
412  prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
413  Assert(prmdata->execPlan == NULL);
414  prmdata->value = slot_getattr(slot, col, &(prmdata->isnull));
415  col++;
416  }
417 
418  rowresult = ExecEvalExprSwitchContext(node->testexpr, econtext,
419  &rownull);
420 
421  if (subLinkType == ANY_SUBLINK)
422  {
423  /* combine across rows per OR semantics */
424  if (rownull)
425  *isNull = true;
426  else if (DatumGetBool(rowresult))
427  {
428  result = BoolGetDatum(true);
429  *isNull = false;
430  break; /* needn't look at any more rows */
431  }
432  }
433  else if (subLinkType == ALL_SUBLINK)
434  {
435  /* combine across rows per AND semantics */
436  if (rownull)
437  *isNull = true;
438  else if (!DatumGetBool(rowresult))
439  {
440  result = BoolGetDatum(false);
441  *isNull = false;
442  break; /* needn't look at any more rows */
443  }
444  }
445  else
446  {
447  /* must be ROWCOMPARE_SUBLINK */
448  result = rowresult;
449  *isNull = rownull;
450  }
451  }
452 
453  MemoryContextSwitchTo(oldcontext);
454 
455  if (subLinkType == ARRAY_SUBLINK)
456  {
457  /* We return the result in the caller's context */
458  result = makeArrayResultAny(astate, oldcontext, true);
459  }
460  else if (!found)
461  {
462  /*
463  * deal with empty subplan result. result/isNull were previously
464  * initialized correctly for all sublink types except EXPR and
465  * ROWCOMPARE; for those, return NULL.
466  */
467  if (subLinkType == EXPR_SUBLINK ||
468  subLinkType == ROWCOMPARE_SUBLINK)
469  {
470  result = (Datum) 0;
471  *isNull = true;
472  }
473  else if (subLinkType == MULTIEXPR_SUBLINK)
474  {
475  /* We don't care about function result, but set the setParams */
476  foreach(l, subplan->setParam)
477  {
478  int paramid = lfirst_int(l);
479  ParamExecData *prmdata;
480 
481  prmdata = &(econtext->ecxt_param_exec_vals[paramid]);
482  Assert(prmdata->execPlan == NULL);
483  prmdata->value = (Datum) 0;
484  prmdata->isnull = true;
485  }
486  }
487  }
488 
489  return result;
490 }
ArrayBuildStateAny * initArrayResultAny(Oid input_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5770
ArrayBuildStateAny * accumArrayResultAny(ArrayBuildStateAny *astate, Datum dvalue, bool disnull, Oid input_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5815
Datum makeArrayResultAny(ArrayBuildStateAny *astate, MemoryContext rcontext, bool release)
Definition: arrayfuncs.c:5843
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ereport(elevel,...)
Definition: elog.h:149
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:359
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1434
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
uintptr_t Datum
Definition: postgres.h:64
SubLinkType
Definition: primnodes.h:996
@ ARRAY_SUBLINK
Definition: primnodes.h:1003
@ MULTIEXPR_SUBLINK
Definition: primnodes.h:1002
@ EXPR_SUBLINK
Definition: primnodes.h:1001
@ ROWCOMPARE_SUBLINK
Definition: primnodes.h:1000
@ ALL_SUBLINK
Definition: primnodes.h:998
@ EXISTS_SUBLINK
Definition: primnodes.h:997
Oid firstColType
Definition: primnodes.h:1074
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:123
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
static HeapTuple ExecCopySlotHeapTuple(TupleTableSlot *slot)
Definition: tuptable.h:481

References accumArrayResultAny(), ALL_SUBLINK, ANY_SUBLINK, ARRAY_SUBLINK, Assert, bms_add_member(), BoolGetDatum(), PlanState::chgParam, CurrentMemoryContext, SubPlanState::curTuple, DatumGetBool(), ExprContext::ecxt_param_exec_vals, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, ExecCopySlotHeapTuple(), ExecEvalExprSwitchContext(), ParamExecData::execPlan, ExecProcNode(), ExecReScan(), EXISTS_SUBLINK, EXPR_SUBLINK, SubPlan::firstColType, heap_freetuple(), heap_getattr(), initArrayResultAny(), ParamExecData::isnull, lfirst_int, makeArrayResultAny(), MemoryContextSwitchTo(), MULTIEXPR_SUBLINK, SubPlan::paramIds, SubPlan::parParam, SubPlanState::planstate, ROWCOMPARE_SUBLINK, SubPlan::setParam, slot_getattr(), SubPlan::subLinkType, SubPlanState::subplan, SubPlanState::testexpr, TupleTableSlot::tts_tupleDescriptor, TupIsNull, TupleDescAttr, and ParamExecData::value.

Referenced by ExecSubPlan().

◆ ExecSetParamPlan()

void ExecSetParamPlan ( SubPlanState node,
ExprContext econtext 
)

Definition at line 1087 of file nodeSubplan.c.

1088 {
1089  SubPlan *subplan = node->subplan;
1090  PlanState *planstate = node->planstate;
1091  SubLinkType subLinkType = subplan->subLinkType;
1092  EState *estate = planstate->state;
1093  ScanDirection dir = estate->es_direction;
1094  MemoryContext oldcontext;
1095  TupleTableSlot *slot;
1096  ListCell *l;
1097  bool found = false;
1098  ArrayBuildStateAny *astate = NULL;
1099 
1100  if (subLinkType == ANY_SUBLINK ||
1101  subLinkType == ALL_SUBLINK)
1102  elog(ERROR, "ANY/ALL subselect unsupported as initplan");
1103  if (subLinkType == CTE_SUBLINK)
1104  elog(ERROR, "CTE subplans should not be executed via ExecSetParamPlan");
1105  if (subplan->parParam || subplan->args)
1106  elog(ERROR, "correlated subplans should not be executed via ExecSetParamPlan");
1107 
1108  /*
1109  * Enforce forward scan direction regardless of caller. It's hard but not
1110  * impossible to get here in backward scan, so make it work anyway.
1111  */
1113 
1114  /* Initialize ArrayBuildStateAny in caller's context, if needed */
1115  if (subLinkType == ARRAY_SUBLINK)
1116  astate = initArrayResultAny(subplan->firstColType,
1117  CurrentMemoryContext, true);
1118 
1119  /*
1120  * Must switch to per-query memory context.
1121  */
1122  oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
1123 
1124  /*
1125  * Run the plan. (If it needs to be rescanned, the first ExecProcNode
1126  * call will take care of that.)
1127  */
1128  for (slot = ExecProcNode(planstate);
1129  !TupIsNull(slot);
1130  slot = ExecProcNode(planstate))
1131  {
1132  TupleDesc tdesc = slot->tts_tupleDescriptor;
1133  int i = 1;
1134 
1135  if (subLinkType == EXISTS_SUBLINK)
1136  {
1137  /* There can be only one setParam... */
1138  int paramid = linitial_int(subplan->setParam);
1139  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1140 
1141  prm->execPlan = NULL;
1142  prm->value = BoolGetDatum(true);
1143  prm->isnull = false;
1144  found = true;
1145  break;
1146  }
1147 
1148  if (subLinkType == ARRAY_SUBLINK)
1149  {
1150  Datum dvalue;
1151  bool disnull;
1152 
1153  found = true;
1154  /* stash away current value */
1155  Assert(subplan->firstColType == TupleDescAttr(tdesc, 0)->atttypid);
1156  dvalue = slot_getattr(slot, 1, &disnull);
1157  astate = accumArrayResultAny(astate, dvalue, disnull,
1158  subplan->firstColType, oldcontext);
1159  /* keep scanning subplan to collect all values */
1160  continue;
1161  }
1162 
1163  if (found &&
1164  (subLinkType == EXPR_SUBLINK ||
1165  subLinkType == MULTIEXPR_SUBLINK ||
1166  subLinkType == ROWCOMPARE_SUBLINK))
1167  ereport(ERROR,
1168  (errcode(ERRCODE_CARDINALITY_VIOLATION),
1169  errmsg("more than one row returned by a subquery used as an expression")));
1170 
1171  found = true;
1172 
1173  /*
1174  * We need to copy the subplan's tuple into our own context, in case
1175  * any of the params are pass-by-ref type --- the pointers stored in
1176  * the param structs will point at this copied tuple! node->curTuple
1177  * keeps track of the copied tuple for eventual freeing.
1178  */
1179  if (node->curTuple)
1180  heap_freetuple(node->curTuple);
1181  node->curTuple = ExecCopySlotHeapTuple(slot);
1182 
1183  /*
1184  * Now set all the setParam params from the columns of the tuple
1185  */
1186  foreach(l, subplan->setParam)
1187  {
1188  int paramid = lfirst_int(l);
1189  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1190 
1191  prm->execPlan = NULL;
1192  prm->value = heap_getattr(node->curTuple, i, tdesc,
1193  &(prm->isnull));
1194  i++;
1195  }
1196  }
1197 
1198  if (subLinkType == ARRAY_SUBLINK)
1199  {
1200  /* There can be only one setParam... */
1201  int paramid = linitial_int(subplan->setParam);
1202  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1203 
1204  /*
1205  * We build the result array in query context so it won't disappear;
1206  * to avoid leaking memory across repeated calls, we have to remember
1207  * the latest value, much as for curTuple above.
1208  */
1209  if (node->curArray != PointerGetDatum(NULL))
1210  pfree(DatumGetPointer(node->curArray));
1211  node->curArray = makeArrayResultAny(astate,
1212  econtext->ecxt_per_query_memory,
1213  true);
1214  prm->execPlan = NULL;
1215  prm->value = node->curArray;
1216  prm->isnull = false;
1217  }
1218  else if (!found)
1219  {
1220  if (subLinkType == EXISTS_SUBLINK)
1221  {
1222  /* There can be only one setParam... */
1223  int paramid = linitial_int(subplan->setParam);
1224  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1225 
1226  prm->execPlan = NULL;
1227  prm->value = BoolGetDatum(false);
1228  prm->isnull = false;
1229  }
1230  else
1231  {
1232  /* For other sublink types, set all the output params to NULL */
1233  foreach(l, subplan->setParam)
1234  {
1235  int paramid = lfirst_int(l);
1236  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1237 
1238  prm->execPlan = NULL;
1239  prm->value = (Datum) 0;
1240  prm->isnull = true;
1241  }
1242  }
1243  }
1244 
1245  MemoryContextSwitchTo(oldcontext);
1246 
1247  /* restore scan direction */
1248  estate->es_direction = dir;
1249 }
void pfree(void *pointer)
Definition: mcxt.c:1521
#define linitial_int(l)
Definition: pg_list.h:179
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
ScanDirection
Definition: sdir.h:25
@ ForwardScanDirection
Definition: sdir.h:28
ScanDirection es_direction
Definition: execnodes.h:627

References accumArrayResultAny(), ALL_SUBLINK, ANY_SUBLINK, SubPlan::args, ARRAY_SUBLINK, Assert, BoolGetDatum(), CTE_SUBLINK, SubPlanState::curArray, CurrentMemoryContext, SubPlanState::curTuple, DatumGetPointer(), ExprContext::ecxt_param_exec_vals, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, EState::es_direction, ExecCopySlotHeapTuple(), ParamExecData::execPlan, ExecProcNode(), EXISTS_SUBLINK, EXPR_SUBLINK, SubPlan::firstColType, ForwardScanDirection, heap_freetuple(), heap_getattr(), i, initArrayResultAny(), ParamExecData::isnull, lfirst_int, linitial_int, makeArrayResultAny(), MemoryContextSwitchTo(), MULTIEXPR_SUBLINK, SubPlan::parParam, pfree(), SubPlanState::planstate, PointerGetDatum(), ROWCOMPARE_SUBLINK, SubPlan::setParam, slot_getattr(), PlanState::state, SubPlan::subLinkType, SubPlanState::subplan, TupleTableSlot::tts_tupleDescriptor, TupIsNull, TupleDescAttr, and ParamExecData::value.

Referenced by ExecEvalParamExec(), and ExecSetParamPlanMulti().

◆ ExecSetParamPlanMulti()

void ExecSetParamPlanMulti ( const Bitmapset params,
ExprContext econtext 
)

Definition at line 1263 of file nodeSubplan.c.

1264 {
1265  int paramid;
1266 
1267  paramid = -1;
1268  while ((paramid = bms_next_member(params, paramid)) >= 0)
1269  {
1270  ParamExecData *prm = &(econtext->ecxt_param_exec_vals[paramid]);
1271 
1272  if (prm->execPlan != NULL)
1273  {
1274  /* Parameter not evaluated yet, so go do it */
1275  ExecSetParamPlan(prm->execPlan, econtext);
1276  /* ExecSetParamPlan should have processed this param... */
1277  Assert(prm->execPlan == NULL);
1278  }
1279  }
1280 }
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
void ExecSetParamPlan(SubPlanState *node, ExprContext *econtext)
Definition: nodeSubplan.c:1087

References Assert, bms_next_member(), ExprContext::ecxt_param_exec_vals, ParamExecData::execPlan, and ExecSetParamPlan().

Referenced by EvalPlanQualBegin(), EvalPlanQualStart(), ExecInitParallelPlan(), and ExecParallelReinitialize().

◆ ExecSubPlan()

Datum ExecSubPlan ( SubPlanState node,
ExprContext econtext,
bool isNull 
)

Definition at line 62 of file nodeSubplan.c.

65 {
66  SubPlan *subplan = node->subplan;
67  EState *estate = node->planstate->state;
68  ScanDirection dir = estate->es_direction;
69  Datum retval;
70 
72 
73  /* Set non-null as default */
74  *isNull = false;
75 
76  /* Sanity checks */
77  if (subplan->subLinkType == CTE_SUBLINK)
78  elog(ERROR, "CTE subplans should not be executed via ExecSubPlan");
79  if (subplan->setParam != NIL && subplan->subLinkType != MULTIEXPR_SUBLINK)
80  elog(ERROR, "cannot set parent params from subquery");
81 
82  /* Force forward-scan mode for evaluation */
84 
85  /* Select appropriate evaluation strategy */
86  if (subplan->useHashTable)
87  retval = ExecHashSubPlan(node, econtext, isNull);
88  else
89  retval = ExecScanSubPlan(node, econtext, isNull);
90 
91  /* restore scan direction */
92  estate->es_direction = dir;
93 
94  return retval;
95 }
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
static Datum ExecHashSubPlan(SubPlanState *node, ExprContext *econtext, bool *isNull)
Definition: nodeSubplan.c:101
static Datum ExecScanSubPlan(SubPlanState *node, ExprContext *econtext, bool *isNull)
Definition: nodeSubplan.c:223

References CHECK_FOR_INTERRUPTS, CTE_SUBLINK, elog, ERROR, EState::es_direction, ExecHashSubPlan(), ExecScanSubPlan(), ForwardScanDirection, MULTIEXPR_SUBLINK, NIL, SubPlanState::planstate, SubPlan::setParam, PlanState::state, SubPlan::subLinkType, SubPlanState::subplan, and SubPlan::useHashTable.

Referenced by ExecEvalSubPlan().

◆ execTuplesUnequal()

static bool execTuplesUnequal ( TupleTableSlot slot1,
TupleTableSlot slot2,
int  numCols,
AttrNumber matchColIdx,
FmgrInfo eqfunctions,
const Oid collations,
MemoryContext  evalContext 
)
static

Definition at line 667 of file nodeSubplan.c.

674 {
675  MemoryContext oldContext;
676  bool result;
677  int i;
678 
679  /* Reset and switch into the temp context. */
680  MemoryContextReset(evalContext);
681  oldContext = MemoryContextSwitchTo(evalContext);
682 
683  /*
684  * We cannot report a match without checking all the fields, but we can
685  * report a non-match as soon as we find unequal fields. So, start
686  * comparing at the last field (least significant sort key). That's the
687  * most likely to be different if we are dealing with sorted input.
688  */
689  result = false;
690 
691  for (i = numCols; --i >= 0;)
692  {
693  AttrNumber att = matchColIdx[i];
694  Datum attr1,
695  attr2;
696  bool isNull1,
697  isNull2;
698 
699  attr1 = slot_getattr(slot1, att, &isNull1);
700 
701  if (isNull1)
702  continue; /* can't prove anything here */
703 
704  attr2 = slot_getattr(slot2, att, &isNull2);
705 
706  if (isNull2)
707  continue; /* can't prove anything here */
708 
709  /* Apply the type-specific equality function */
710  if (!DatumGetBool(FunctionCall2Coll(&eqfunctions[i],
711  collations[i],
712  attr1, attr2)))
713  {
714  result = true; /* they are unequal */
715  break;
716  }
717  }
718 
719  MemoryContextSwitchTo(oldContext);
720 
721  return result;
722 }
Datum FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
Definition: fmgr.c:1149

References DatumGetBool(), FunctionCall2Coll(), i, MemoryContextReset(), MemoryContextSwitchTo(), and slot_getattr().

Referenced by findPartialMatch().

◆ findPartialMatch()

static bool findPartialMatch ( TupleHashTable  hashtable,
TupleTableSlot slot,
FmgrInfo eqfunctions 
)
static

Definition at line 736 of file nodeSubplan.c.

738 {
739  int numCols = hashtable->numCols;
740  AttrNumber *keyColIdx = hashtable->keyColIdx;
741  TupleHashIterator hashiter;
742  TupleHashEntry entry;
743 
744  InitTupleHashIterator(hashtable, &hashiter);
745  while ((entry = ScanTupleHashTable(hashtable, &hashiter)) != NULL)
746  {
748 
749  ExecStoreMinimalTuple(entry->firstTuple, hashtable->tableslot, false);
750  if (!execTuplesUnequal(slot, hashtable->tableslot,
751  numCols, keyColIdx,
752  eqfunctions,
753  hashtable->tab_collations,
754  hashtable->tempcxt))
755  {
756  TermTupleHashIterator(&hashiter);
757  return true;
758  }
759  }
760  /* No TermTupleHashIterator call needed here */
761  return false;
762 }
TupleTableSlot * ExecStoreMinimalTuple(MinimalTuple mtup, TupleTableSlot *slot, bool shouldFree)
Definition: execTuples.c:1533
#define ScanTupleHashTable(htable, iter)
Definition: execnodes.h:852
#define TermTupleHashIterator(iter)
Definition: execnodes.h:848
#define InitTupleHashIterator(htable, iter)
Definition: execnodes.h:846
tuplehash_iterator TupleHashIterator
Definition: execnodes.h:839
static bool execTuplesUnequal(TupleTableSlot *slot1, TupleTableSlot *slot2, int numCols, AttrNumber *matchColIdx, FmgrInfo *eqfunctions, const Oid *collations, MemoryContext evalContext)
Definition: nodeSubplan.c:667
MinimalTuple firstTuple
Definition: execnodes.h:805
AttrNumber * keyColIdx
Definition: execnodes.h:823
MemoryContext tempcxt
Definition: execnodes.h:828
TupleTableSlot * tableslot
Definition: execnodes.h:830

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

Referenced by ExecHashSubPlan().

◆ slotAllNulls()

static bool slotAllNulls ( TupleTableSlot slot)
static

Definition at line 771 of file nodeSubplan.c.

772 {
773  int ncols = slot->tts_tupleDescriptor->natts;
774  int i;
775 
776  for (i = 1; i <= ncols; i++)
777  {
778  if (!slot_attisnull(slot, i))
779  return false;
780  }
781  return true;
782 }
static bool slot_attisnull(TupleTableSlot *slot, int attnum)
Definition: tuptable.h:381

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

Referenced by ExecHashSubPlan().

◆ slotNoNulls()

static bool slotNoNulls ( TupleTableSlot slot)
static

Definition at line 791 of file nodeSubplan.c.

792 {
793  int ncols = slot->tts_tupleDescriptor->natts;
794  int i;
795 
796  for (i = 1; i <= ncols; i++)
797  {
798  if (slot_attisnull(slot, i))
799  return false;
800  }
801  return true;
802 }

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

Referenced by buildSubPlanHash(), and ExecHashSubPlan().