LCOV - code coverage report
Current view: top level - src/backend/executor - execExpr.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 97.1 % 2008 1950
Test Date: 2026-03-14 12:15:02 Functions: 100.0 % 35 35
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /*-------------------------------------------------------------------------
       2              :  *
       3              :  * execExpr.c
       4              :  *    Expression evaluation infrastructure.
       5              :  *
       6              :  *  During executor startup, we compile each expression tree (which has
       7              :  *  previously been processed by the parser and planner) into an ExprState,
       8              :  *  using ExecInitExpr() et al.  This converts the tree into a flat array
       9              :  *  of ExprEvalSteps, which may be thought of as instructions in a program.
      10              :  *  At runtime, we'll execute steps, starting with the first, until we reach
      11              :  *  an EEOP_DONE_{RETURN|NO_RETURN} opcode.
      12              :  *
      13              :  *  This file contains the "compilation" logic.  It is independent of the
      14              :  *  specific execution technology we use (switch statement, computed goto,
      15              :  *  JIT compilation, etc).
      16              :  *
      17              :  *  See src/backend/executor/README for some background, specifically the
      18              :  *  "Expression Trees and ExprState nodes", "Expression Initialization",
      19              :  *  and "Expression Evaluation" sections.
      20              :  *
      21              :  *
      22              :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      23              :  * Portions Copyright (c) 1994, Regents of the University of California
      24              :  *
      25              :  *
      26              :  * IDENTIFICATION
      27              :  *    src/backend/executor/execExpr.c
      28              :  *
      29              :  *-------------------------------------------------------------------------
      30              :  */
      31              : #include "postgres.h"
      32              : 
      33              : #include "access/nbtree.h"
      34              : #include "catalog/objectaccess.h"
      35              : #include "catalog/pg_proc.h"
      36              : #include "catalog/pg_type.h"
      37              : #include "executor/execExpr.h"
      38              : #include "executor/nodeSubplan.h"
      39              : #include "funcapi.h"
      40              : #include "jit/jit.h"
      41              : #include "miscadmin.h"
      42              : #include "nodes/makefuncs.h"
      43              : #include "nodes/nodeFuncs.h"
      44              : #include "nodes/subscripting.h"
      45              : #include "optimizer/optimizer.h"
      46              : #include "pgstat.h"
      47              : #include "utils/acl.h"
      48              : #include "utils/array.h"
      49              : #include "utils/builtins.h"
      50              : #include "utils/jsonfuncs.h"
      51              : #include "utils/jsonpath.h"
      52              : #include "utils/lsyscache.h"
      53              : #include "utils/typcache.h"
      54              : 
      55              : 
      56              : typedef struct ExprSetupInfo
      57              : {
      58              :     /*
      59              :      * Highest attribute numbers fetched from inner/outer/scan/old/new tuple
      60              :      * slots:
      61              :      */
      62              :     AttrNumber  last_inner;
      63              :     AttrNumber  last_outer;
      64              :     AttrNumber  last_scan;
      65              :     AttrNumber  last_old;
      66              :     AttrNumber  last_new;
      67              :     /* MULTIEXPR SubPlan nodes appearing in the expression: */
      68              :     List       *multiexpr_subplans;
      69              : } ExprSetupInfo;
      70              : 
      71              : static void ExecReadyExpr(ExprState *state);
      72              : static void ExecInitExprRec(Expr *node, ExprState *state,
      73              :                             Datum *resv, bool *resnull);
      74              : static void ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args,
      75              :                          Oid funcid, Oid inputcollid,
      76              :                          ExprState *state);
      77              : static void ExecInitSubPlanExpr(SubPlan *subplan,
      78              :                                 ExprState *state,
      79              :                                 Datum *resv, bool *resnull);
      80              : static void ExecCreateExprSetupSteps(ExprState *state, Node *node);
      81              : static void ExecPushExprSetupSteps(ExprState *state, ExprSetupInfo *info);
      82              : static bool expr_setup_walker(Node *node, ExprSetupInfo *info);
      83              : static bool ExecComputeSlotInfo(ExprState *state, ExprEvalStep *op);
      84              : static void ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable,
      85              :                                 ExprState *state);
      86              : static void ExecInitSubscriptingRef(ExprEvalStep *scratch,
      87              :                                     SubscriptingRef *sbsref,
      88              :                                     ExprState *state,
      89              :                                     Datum *resv, bool *resnull);
      90              : static bool isAssignmentIndirectionExpr(Expr *expr);
      91              : static void ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
      92              :                                    ExprState *state,
      93              :                                    Datum *resv, bool *resnull);
      94              : static void ExecBuildAggTransCall(ExprState *state, AggState *aggstate,
      95              :                                   ExprEvalStep *scratch,
      96              :                                   FunctionCallInfo fcinfo, AggStatePerTrans pertrans,
      97              :                                   int transno, int setno, int setoff, bool ishash,
      98              :                                   bool nullcheck);
      99              : static void ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state,
     100              :                              Datum *resv, bool *resnull,
     101              :                              ExprEvalStep *scratch);
     102              : static void ExecInitJsonCoercion(ExprState *state, JsonReturning *returning,
     103              :                                  ErrorSaveContext *escontext, bool omit_quotes,
     104              :                                  bool exists_coerce,
     105              :                                  Datum *resv, bool *resnull);
     106              : 
     107              : 
     108              : /*
     109              :  * ExecInitExpr: prepare an expression tree for execution
     110              :  *
     111              :  * This function builds and returns an ExprState implementing the given
     112              :  * Expr node tree.  The return ExprState can then be handed to ExecEvalExpr
     113              :  * for execution.  Because the Expr tree itself is read-only as far as
     114              :  * ExecInitExpr and ExecEvalExpr are concerned, several different executions
     115              :  * of the same plan tree can occur concurrently.  (But note that an ExprState
     116              :  * does mutate at runtime, so it can't be re-used concurrently.)
     117              :  *
     118              :  * This must be called in a memory context that will last as long as repeated
     119              :  * executions of the expression are needed.  Typically the context will be
     120              :  * the same as the per-query context of the associated ExprContext.
     121              :  *
     122              :  * Any Aggref, WindowFunc, or SubPlan nodes found in the tree are added to
     123              :  * the lists of such nodes held by the parent PlanState.
     124              :  *
     125              :  * Note: there is no ExecEndExpr function; we assume that any resource
     126              :  * cleanup needed will be handled by just releasing the memory context
     127              :  * in which the state tree is built.  Functions that require additional
     128              :  * cleanup work can register a shutdown callback in the ExprContext.
     129              :  *
     130              :  *  'node' is the root of the expression tree to compile.
     131              :  *  'parent' is the PlanState node that owns the expression.
     132              :  *
     133              :  * 'parent' may be NULL if we are preparing an expression that is not
     134              :  * associated with a plan tree.  (If so, it can't have aggs or subplans.)
     135              :  * Such cases should usually come through ExecPrepareExpr, not directly here.
     136              :  *
     137              :  * Also, if 'node' is NULL, we just return NULL.  This is convenient for some
     138              :  * callers that may or may not have an expression that needs to be compiled.
     139              :  * Note that a NULL ExprState pointer *cannot* be handed to ExecEvalExpr,
     140              :  * although ExecQual and ExecCheck will accept one (and treat it as "true").
     141              :  */
     142              : ExprState *
     143       621358 : ExecInitExpr(Expr *node, PlanState *parent)
     144              : {
     145       621358 :     return ExecInitExprWithContext(node, parent, NULL);
     146              : }
     147              : 
     148              : /*
     149              :  * ExecInitExprWithContext: same as ExecInitExpr, but with an optional
     150              :  * ErrorSaveContext for soft error handling.
     151              :  *
     152              :  * When 'escontext' is non-NULL, expression nodes that support soft errors
     153              :  * (currently CoerceToDomain's NOT NULL and CHECK constraint steps) will use
     154              :  * errsave() instead of ereport(), allowing the caller to detect and handle
     155              :  * failures without a transaction abort.
     156              :  *
     157              :  * The escontext must be provided at initialization time (not after), because
     158              :  * it is copied into per-step data during expression compilation.
     159              :  *
     160              :  * Not all expression node types support soft errors.  If in doubt, pass NULL.
     161              :  */
     162              : ExprState *
     163       635292 : ExecInitExprWithContext(Expr *node, PlanState *parent, Node *escontext)
     164              : {
     165              :     ExprState  *state;
     166       635292 :     ExprEvalStep scratch = {0};
     167              : 
     168              :     /* Special case: NULL expression produces a NULL ExprState pointer */
     169       635292 :     if (node == NULL)
     170        31119 :         return NULL;
     171              : 
     172              :     /* Initialize ExprState with empty step list */
     173       604173 :     state = makeNode(ExprState);
     174       604173 :     state->expr = node;
     175       604173 :     state->parent = parent;
     176       604173 :     state->ext_params = NULL;
     177       604173 :     state->escontext = (ErrorSaveContext *) escontext;
     178              : 
     179              :     /* Insert setup steps as needed */
     180       604173 :     ExecCreateExprSetupSteps(state, (Node *) node);
     181              : 
     182              :     /* Compile the expression proper */
     183       604173 :     ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     184              : 
     185              :     /* Finally, append a DONE step */
     186       604158 :     scratch.opcode = EEOP_DONE_RETURN;
     187       604158 :     ExprEvalPushStep(state, &scratch);
     188              : 
     189       604158 :     ExecReadyExpr(state);
     190              : 
     191       604158 :     return state;
     192              : }
     193              : 
     194              : /*
     195              :  * ExecInitExprWithParams: prepare a standalone expression tree for execution
     196              :  *
     197              :  * This is the same as ExecInitExpr, except that there is no parent PlanState,
     198              :  * and instead we may have a ParamListInfo describing PARAM_EXTERN Params.
     199              :  */
     200              : ExprState *
     201        41088 : ExecInitExprWithParams(Expr *node, ParamListInfo ext_params)
     202              : {
     203              :     ExprState  *state;
     204        41088 :     ExprEvalStep scratch = {0};
     205              : 
     206              :     /* Special case: NULL expression produces a NULL ExprState pointer */
     207        41088 :     if (node == NULL)
     208            0 :         return NULL;
     209              : 
     210              :     /* Initialize ExprState with empty step list */
     211        41088 :     state = makeNode(ExprState);
     212        41088 :     state->expr = node;
     213        41088 :     state->parent = NULL;
     214        41088 :     state->ext_params = ext_params;
     215              : 
     216              :     /* Insert setup steps as needed */
     217        41088 :     ExecCreateExprSetupSteps(state, (Node *) node);
     218              : 
     219              :     /* Compile the expression proper */
     220        41088 :     ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     221              : 
     222              :     /* Finally, append a DONE step */
     223        41088 :     scratch.opcode = EEOP_DONE_RETURN;
     224        41088 :     ExprEvalPushStep(state, &scratch);
     225              : 
     226        41088 :     ExecReadyExpr(state);
     227              : 
     228        41088 :     return state;
     229              : }
     230              : 
     231              : /*
     232              :  * ExecInitQual: prepare a qual for execution by ExecQual
     233              :  *
     234              :  * Prepares for the evaluation of a conjunctive boolean expression (qual list
     235              :  * with implicit AND semantics) that returns true if none of the
     236              :  * subexpressions are false.
     237              :  *
     238              :  * We must return true if the list is empty.  Since that's a very common case,
     239              :  * we optimize it a bit further by translating to a NULL ExprState pointer
     240              :  * rather than setting up an ExprState that computes constant TRUE.  (Some
     241              :  * especially hot-spot callers of ExecQual detect this and avoid calling
     242              :  * ExecQual at all.)
     243              :  *
     244              :  * If any of the subexpressions yield NULL, then the result of the conjunction
     245              :  * is false.  This makes ExecQual primarily useful for evaluating WHERE
     246              :  * clauses, since SQL specifies that tuples with null WHERE results do not
     247              :  * get selected.
     248              :  */
     249              : ExprState *
     250      1469174 : ExecInitQual(List *qual, PlanState *parent)
     251              : {
     252              :     ExprState  *state;
     253      1469174 :     ExprEvalStep scratch = {0};
     254      1469174 :     List       *adjust_jumps = NIL;
     255              : 
     256              :     /* short-circuit (here and in ExecQual) for empty restriction list */
     257      1469174 :     if (qual == NIL)
     258       802065 :         return NULL;
     259              : 
     260              :     Assert(IsA(qual, List));
     261              : 
     262       667109 :     state = makeNode(ExprState);
     263       667109 :     state->expr = (Expr *) qual;
     264       667109 :     state->parent = parent;
     265       667109 :     state->ext_params = NULL;
     266              : 
     267              :     /* mark expression as to be used with ExecQual() */
     268       667109 :     state->flags = EEO_FLAG_IS_QUAL;
     269              : 
     270              :     /* Insert setup steps as needed */
     271       667109 :     ExecCreateExprSetupSteps(state, (Node *) qual);
     272              : 
     273              :     /*
     274              :      * ExecQual() needs to return false for an expression returning NULL. That
     275              :      * allows us to short-circuit the evaluation the first time a NULL is
     276              :      * encountered.  As qual evaluation is a hot-path this warrants using a
     277              :      * special opcode for qual evaluation that's simpler than BOOL_AND (which
     278              :      * has more complex NULL handling).
     279              :      */
     280       667109 :     scratch.opcode = EEOP_QUAL;
     281              : 
     282              :     /*
     283              :      * We can use ExprState's resvalue/resnull as target for each qual expr.
     284              :      */
     285       667109 :     scratch.resvalue = &state->resvalue;
     286       667109 :     scratch.resnull = &state->resnull;
     287              : 
     288      2063680 :     foreach_ptr(Expr, node, qual)
     289              :     {
     290              :         /* first evaluate expression */
     291       729462 :         ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
     292              : 
     293              :         /* then emit EEOP_QUAL to detect if it's false (or null) */
     294       729462 :         scratch.d.qualexpr.jumpdone = -1;
     295       729462 :         ExprEvalPushStep(state, &scratch);
     296       729462 :         adjust_jumps = lappend_int(adjust_jumps,
     297       729462 :                                    state->steps_len - 1);
     298              :     }
     299              : 
     300              :     /* adjust jump targets */
     301      2063680 :     foreach_int(jump, adjust_jumps)
     302              :     {
     303       729462 :         ExprEvalStep *as = &state->steps[jump];
     304              : 
     305              :         Assert(as->opcode == EEOP_QUAL);
     306              :         Assert(as->d.qualexpr.jumpdone == -1);
     307       729462 :         as->d.qualexpr.jumpdone = state->steps_len;
     308              :     }
     309              : 
     310              :     /*
     311              :      * At the end, we don't need to do anything more.  The last qual expr must
     312              :      * have yielded TRUE, and since its result is stored in the desired output
     313              :      * location, we're done.
     314              :      */
     315       667109 :     scratch.opcode = EEOP_DONE_RETURN;
     316       667109 :     ExprEvalPushStep(state, &scratch);
     317              : 
     318       667109 :     ExecReadyExpr(state);
     319              : 
     320       667109 :     return state;
     321              : }
     322              : 
     323              : /*
     324              :  * ExecInitCheck: prepare a check constraint for execution by ExecCheck
     325              :  *
     326              :  * This is much like ExecInitQual/ExecQual, except that a null result from
     327              :  * the conjunction is treated as TRUE.  This behavior is appropriate for
     328              :  * evaluating CHECK constraints, since SQL specifies that NULL constraint
     329              :  * conditions are not failures.
     330              :  *
     331              :  * Note that like ExecInitQual, this expects input in implicit-AND format.
     332              :  * Users of ExecCheck that have expressions in normal explicit-AND format
     333              :  * can just apply ExecInitExpr to produce suitable input for ExecCheck.
     334              :  */
     335              : ExprState *
     336         2938 : ExecInitCheck(List *qual, PlanState *parent)
     337              : {
     338              :     /* short-circuit (here and in ExecCheck) for empty restriction list */
     339         2938 :     if (qual == NIL)
     340           90 :         return NULL;
     341              : 
     342              :     Assert(IsA(qual, List));
     343              : 
     344              :     /*
     345              :      * Just convert the implicit-AND list to an explicit AND (if there's more
     346              :      * than one entry), and compile normally.  Unlike ExecQual, we can't
     347              :      * short-circuit on NULL results, so the regular AND behavior is needed.
     348              :      */
     349         2848 :     return ExecInitExpr(make_ands_explicit(qual), parent);
     350              : }
     351              : 
     352              : /*
     353              :  * Call ExecInitExpr() on a list of expressions, return a list of ExprStates.
     354              :  */
     355              : List *
     356       346891 : ExecInitExprList(List *nodes, PlanState *parent)
     357              : {
     358       346891 :     List       *result = NIL;
     359              :     ListCell   *lc;
     360              : 
     361       566091 :     foreach(lc, nodes)
     362              :     {
     363       219200 :         Expr       *e = lfirst(lc);
     364              : 
     365       219200 :         result = lappend(result, ExecInitExpr(e, parent));
     366              :     }
     367              : 
     368       346891 :     return result;
     369              : }
     370              : 
     371              : /*
     372              :  *      ExecBuildProjectionInfo
     373              :  *
     374              :  * Build a ProjectionInfo node for evaluating the given tlist in the given
     375              :  * econtext, and storing the result into the tuple slot.  (Caller must have
     376              :  * ensured that tuple slot has a descriptor matching the tlist!)
     377              :  *
     378              :  * inputDesc can be NULL, but if it is not, we check to see whether simple
     379              :  * Vars in the tlist match the descriptor.  It is important to provide
     380              :  * inputDesc for relation-scan plan nodes, as a cross check that the relation
     381              :  * hasn't been changed since the plan was made.  At higher levels of a plan,
     382              :  * there is no need to recheck.
     383              :  *
     384              :  * This is implemented by internally building an ExprState that performs the
     385              :  * whole projection in one go.
     386              :  *
     387              :  * Caution: before PG v10, the targetList was a list of ExprStates; now it
     388              :  * should be the planner-created targetlist, since we do the compilation here.
     389              :  */
     390              : ProjectionInfo *
     391       814415 : ExecBuildProjectionInfo(List *targetList,
     392              :                         ExprContext *econtext,
     393              :                         TupleTableSlot *slot,
     394              :                         PlanState *parent,
     395              :                         TupleDesc inputDesc)
     396              : {
     397       814415 :     ProjectionInfo *projInfo = makeNode(ProjectionInfo);
     398              :     ExprState  *state;
     399       814415 :     ExprEvalStep scratch = {0};
     400              :     ListCell   *lc;
     401              : 
     402       814415 :     projInfo->pi_exprContext = econtext;
     403              :     /* We embed ExprState into ProjectionInfo instead of doing extra palloc */
     404       814415 :     projInfo->pi_state.type = T_ExprState;
     405       814415 :     state = &projInfo->pi_state;
     406       814415 :     state->expr = (Expr *) targetList;
     407       814415 :     state->parent = parent;
     408       814415 :     state->ext_params = NULL;
     409              : 
     410       814415 :     state->resultslot = slot;
     411              : 
     412              :     /* Insert setup steps as needed */
     413       814415 :     ExecCreateExprSetupSteps(state, (Node *) targetList);
     414              : 
     415              :     /* Now compile each tlist column */
     416      2797071 :     foreach(lc, targetList)
     417              :     {
     418      1982690 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
     419      1982690 :         Var        *variable = NULL;
     420      1982690 :         AttrNumber  attnum = 0;
     421      1982690 :         bool        isSafeVar = false;
     422              : 
     423              :         /*
     424              :          * If tlist expression is a safe non-system Var, use the fast-path
     425              :          * ASSIGN_*_VAR opcodes.  "Safe" means that we don't need to apply
     426              :          * CheckVarSlotCompatibility() during plan startup.  If a source slot
     427              :          * was provided, we make the equivalent tests here; if a slot was not
     428              :          * provided, we assume that no check is needed because we're dealing
     429              :          * with a non-relation-scan-level expression.
     430              :          */
     431      1982690 :         if (tle->expr != NULL &&
     432      1982690 :             IsA(tle->expr, Var) &&
     433      1155618 :             ((Var *) tle->expr)->varattno > 0)
     434              :         {
     435              :             /* Non-system Var, but how safe is it? */
     436       703140 :             variable = (Var *) tle->expr;
     437       703140 :             attnum = variable->varattno;
     438              : 
     439       703140 :             if (inputDesc == NULL)
     440       409557 :                 isSafeVar = true;   /* can't check, just assume OK */
     441       293583 :             else if (attnum <= inputDesc->natts)
     442              :             {
     443       293252 :                 Form_pg_attribute attr = TupleDescAttr(inputDesc, attnum - 1);
     444              : 
     445              :                 /*
     446              :                  * If user attribute is dropped or has a type mismatch, don't
     447              :                  * use ASSIGN_*_VAR.  Instead let the normal expression
     448              :                  * machinery handle it (which'll possibly error out).
     449              :                  */
     450       293252 :                 if (!attr->attisdropped && variable->vartype == attr->atttypid)
     451              :                 {
     452       292785 :                     isSafeVar = true;
     453              :                 }
     454              :             }
     455              :         }
     456              : 
     457      1982690 :         if (isSafeVar)
     458              :         {
     459              :             /* Fast-path: just generate an EEOP_ASSIGN_*_VAR step */
     460       702342 :             switch (variable->varno)
     461              :             {
     462       121076 :                 case INNER_VAR:
     463              :                     /* get the tuple from the inner node */
     464       121076 :                     scratch.opcode = EEOP_ASSIGN_INNER_VAR;
     465       121076 :                     break;
     466              : 
     467       287809 :                 case OUTER_VAR:
     468              :                     /* get the tuple from the outer node */
     469       287809 :                     scratch.opcode = EEOP_ASSIGN_OUTER_VAR;
     470       287809 :                     break;
     471              : 
     472              :                     /* INDEX_VAR is handled by default case */
     473              : 
     474       293457 :                 default:
     475              : 
     476              :                     /*
     477              :                      * Get the tuple from the relation being scanned, or the
     478              :                      * old/new tuple slot, if old/new values were requested.
     479              :                      */
     480       293457 :                     switch (variable->varreturningtype)
     481              :                     {
     482       292510 :                         case VAR_RETURNING_DEFAULT:
     483       292510 :                             scratch.opcode = EEOP_ASSIGN_SCAN_VAR;
     484       292510 :                             break;
     485          473 :                         case VAR_RETURNING_OLD:
     486          473 :                             scratch.opcode = EEOP_ASSIGN_OLD_VAR;
     487          473 :                             state->flags |= EEO_FLAG_HAS_OLD;
     488          473 :                             break;
     489          474 :                         case VAR_RETURNING_NEW:
     490          474 :                             scratch.opcode = EEOP_ASSIGN_NEW_VAR;
     491          474 :                             state->flags |= EEO_FLAG_HAS_NEW;
     492          474 :                             break;
     493              :                     }
     494       293457 :                     break;
     495              :             }
     496              : 
     497       702342 :             scratch.d.assign_var.attnum = attnum - 1;
     498       702342 :             scratch.d.assign_var.resultnum = tle->resno - 1;
     499       702342 :             ExprEvalPushStep(state, &scratch);
     500              :         }
     501              :         else
     502              :         {
     503              :             /*
     504              :              * Otherwise, compile the column expression normally.
     505              :              *
     506              :              * We can't tell the expression to evaluate directly into the
     507              :              * result slot, as the result slot (and the exprstate for that
     508              :              * matter) can change between executions.  We instead evaluate
     509              :              * into the ExprState's resvalue/resnull and then move.
     510              :              */
     511      1280348 :             ExecInitExprRec(tle->expr, state,
     512              :                             &state->resvalue, &state->resnull);
     513              : 
     514              :             /*
     515              :              * Column might be referenced multiple times in upper nodes, so
     516              :              * force value to R/O - but only if it could be an expanded datum.
     517              :              */
     518      1280317 :             if (get_typlen(exprType((Node *) tle->expr)) == -1)
     519       170698 :                 scratch.opcode = EEOP_ASSIGN_TMP_MAKE_RO;
     520              :             else
     521      1109619 :                 scratch.opcode = EEOP_ASSIGN_TMP;
     522      1280317 :             scratch.d.assign_tmp.resultnum = tle->resno - 1;
     523      1280317 :             ExprEvalPushStep(state, &scratch);
     524              :         }
     525              :     }
     526              : 
     527       814381 :     scratch.opcode = EEOP_DONE_NO_RETURN;
     528       814381 :     ExprEvalPushStep(state, &scratch);
     529              : 
     530       814381 :     ExecReadyExpr(state);
     531              : 
     532       814381 :     return projInfo;
     533              : }
     534              : 
     535              : /*
     536              :  *      ExecBuildUpdateProjection
     537              :  *
     538              :  * Build a ProjectionInfo node for constructing a new tuple during UPDATE.
     539              :  * The projection will be executed in the given econtext and the result will
     540              :  * be stored into the given tuple slot.  (Caller must have ensured that tuple
     541              :  * slot has a descriptor matching the target rel!)
     542              :  *
     543              :  * When evalTargetList is false, targetList contains the UPDATE ... SET
     544              :  * expressions that have already been computed by a subplan node; the values
     545              :  * from this tlist are assumed to be available in the "outer" tuple slot.
     546              :  * When evalTargetList is true, targetList contains the UPDATE ... SET
     547              :  * expressions that must be computed (which could contain references to
     548              :  * the outer, inner, or scan tuple slots).
     549              :  *
     550              :  * In either case, targetColnos contains a list of the target column numbers
     551              :  * corresponding to the non-resjunk entries of targetList.  The tlist values
     552              :  * are assigned into these columns of the result tuple slot.  Target columns
     553              :  * not listed in targetColnos are filled from the UPDATE's old tuple, which
     554              :  * is assumed to be available in the "scan" tuple slot.
     555              :  *
     556              :  * targetList can also contain resjunk columns.  These must be evaluated
     557              :  * if evalTargetList is true, but their values are discarded.
     558              :  *
     559              :  * relDesc must describe the relation we intend to update.
     560              :  *
     561              :  * This is basically a specialized variant of ExecBuildProjectionInfo.
     562              :  * However, it also performs sanity checks equivalent to ExecCheckPlanOutput.
     563              :  * Since we never make a normal tlist equivalent to the whole
     564              :  * tuple-to-be-assigned, there is no convenient way to apply
     565              :  * ExecCheckPlanOutput, so we must do our safety checks here.
     566              :  */
     567              : ProjectionInfo *
     568         8436 : ExecBuildUpdateProjection(List *targetList,
     569              :                           bool evalTargetList,
     570              :                           List *targetColnos,
     571              :                           TupleDesc relDesc,
     572              :                           ExprContext *econtext,
     573              :                           TupleTableSlot *slot,
     574              :                           PlanState *parent)
     575              : {
     576         8436 :     ProjectionInfo *projInfo = makeNode(ProjectionInfo);
     577              :     ExprState  *state;
     578              :     int         nAssignableCols;
     579              :     bool        sawJunk;
     580              :     Bitmapset  *assignedCols;
     581         8436 :     ExprSetupInfo deform = {0, 0, 0, 0, 0, NIL};
     582         8436 :     ExprEvalStep scratch = {0};
     583              :     int         outerattnum;
     584              :     ListCell   *lc,
     585              :                *lc2;
     586              : 
     587         8436 :     projInfo->pi_exprContext = econtext;
     588              :     /* We embed ExprState into ProjectionInfo instead of doing extra palloc */
     589         8436 :     projInfo->pi_state.type = T_ExprState;
     590         8436 :     state = &projInfo->pi_state;
     591         8436 :     if (evalTargetList)
     592         1372 :         state->expr = (Expr *) targetList;
     593              :     else
     594         7064 :         state->expr = NULL;      /* not used */
     595         8436 :     state->parent = parent;
     596         8436 :     state->ext_params = NULL;
     597              : 
     598         8436 :     state->resultslot = slot;
     599              : 
     600              :     /*
     601              :      * Examine the targetList to see how many non-junk columns there are, and
     602              :      * to verify that the non-junk columns come before the junk ones.
     603              :      */
     604         8436 :     nAssignableCols = 0;
     605         8436 :     sawJunk = false;
     606        28212 :     foreach(lc, targetList)
     607              :     {
     608        19776 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
     609              : 
     610        19776 :         if (tle->resjunk)
     611         8866 :             sawJunk = true;
     612              :         else
     613              :         {
     614        10910 :             if (sawJunk)
     615            0 :                 elog(ERROR, "subplan target list is out of order");
     616        10910 :             nAssignableCols++;
     617              :         }
     618              :     }
     619              : 
     620              :     /* We should have one targetColnos entry per non-junk column */
     621         8436 :     if (nAssignableCols != list_length(targetColnos))
     622            0 :         elog(ERROR, "targetColnos does not match subplan target list");
     623              : 
     624              :     /*
     625              :      * Build a bitmapset of the columns in targetColnos.  (We could just use
     626              :      * list_member_int() tests, but that risks O(N^2) behavior with many
     627              :      * columns.)
     628              :      */
     629         8436 :     assignedCols = NULL;
     630        19346 :     foreach(lc, targetColnos)
     631              :     {
     632        10910 :         AttrNumber  targetattnum = lfirst_int(lc);
     633              : 
     634        10910 :         assignedCols = bms_add_member(assignedCols, targetattnum);
     635              :     }
     636              : 
     637              :     /*
     638              :      * We need to insert EEOP_*_FETCHSOME steps to ensure the input tuples are
     639              :      * sufficiently deconstructed.  The scan tuple must be deconstructed at
     640              :      * least as far as the last old column we need.
     641              :      */
     642        14170 :     for (int attnum = relDesc->natts; attnum > 0; attnum--)
     643              :     {
     644        12850 :         CompactAttribute *attr = TupleDescCompactAttr(relDesc, attnum - 1);
     645              : 
     646        12850 :         if (attr->attisdropped)
     647          111 :             continue;
     648        12739 :         if (bms_is_member(attnum, assignedCols))
     649         5623 :             continue;
     650         7116 :         deform.last_scan = attnum;
     651         7116 :         break;
     652              :     }
     653              : 
     654              :     /*
     655              :      * If we're actually evaluating the tlist, incorporate its input
     656              :      * requirements too; otherwise, we'll just need to fetch the appropriate
     657              :      * number of columns of the "outer" tuple.
     658              :      */
     659         8436 :     if (evalTargetList)
     660         1372 :         expr_setup_walker((Node *) targetList, &deform);
     661              :     else
     662         7064 :         deform.last_outer = nAssignableCols;
     663              : 
     664         8436 :     ExecPushExprSetupSteps(state, &deform);
     665              : 
     666              :     /*
     667              :      * Now generate code to evaluate the tlist's assignable expressions or
     668              :      * fetch them from the outer tuple, incidentally validating that they'll
     669              :      * be of the right data type.  The checks above ensure that the forboth()
     670              :      * will iterate over exactly the non-junk columns.  Note that we don't
     671              :      * bother evaluating any remaining resjunk columns.
     672              :      */
     673         8436 :     outerattnum = 0;
     674        19346 :     forboth(lc, targetList, lc2, targetColnos)
     675              :     {
     676        10910 :         TargetEntry *tle = lfirst_node(TargetEntry, lc);
     677        10910 :         AttrNumber  targetattnum = lfirst_int(lc2);
     678              :         Form_pg_attribute attr;
     679              : 
     680              :         Assert(!tle->resjunk);
     681              : 
     682              :         /*
     683              :          * Apply sanity checks comparable to ExecCheckPlanOutput().
     684              :          */
     685        10910 :         if (targetattnum <= 0 || targetattnum > relDesc->natts)
     686            0 :             ereport(ERROR,
     687              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     688              :                      errmsg("table row type and query-specified row type do not match"),
     689              :                      errdetail("Query has too many columns.")));
     690        10910 :         attr = TupleDescAttr(relDesc, targetattnum - 1);
     691              : 
     692        10910 :         if (attr->attisdropped)
     693            0 :             ereport(ERROR,
     694              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     695              :                      errmsg("table row type and query-specified row type do not match"),
     696              :                      errdetail("Query provides a value for a dropped column at ordinal position %d.",
     697              :                                targetattnum)));
     698        10910 :         if (exprType((Node *) tle->expr) != attr->atttypid)
     699            0 :             ereport(ERROR,
     700              :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
     701              :                      errmsg("table row type and query-specified row type do not match"),
     702              :                      errdetail("Table has type %s at ordinal position %d, but query expects %s.",
     703              :                                format_type_be(attr->atttypid),
     704              :                                targetattnum,
     705              :                                format_type_be(exprType((Node *) tle->expr)))));
     706              : 
     707              :         /* OK, generate code to perform the assignment. */
     708        10910 :         if (evalTargetList)
     709              :         {
     710              :             /*
     711              :              * We must evaluate the TLE's expression and assign it.  We do not
     712              :              * bother jumping through hoops for "safe" Vars like
     713              :              * ExecBuildProjectionInfo does; this is a relatively less-used
     714              :              * path and it doesn't seem worth expending code for that.
     715              :              */
     716         1871 :             ExecInitExprRec(tle->expr, state,
     717              :                             &state->resvalue, &state->resnull);
     718              :             /* Needn't worry about read-only-ness here, either. */
     719         1871 :             scratch.opcode = EEOP_ASSIGN_TMP;
     720         1871 :             scratch.d.assign_tmp.resultnum = targetattnum - 1;
     721         1871 :             ExprEvalPushStep(state, &scratch);
     722              :         }
     723              :         else
     724              :         {
     725              :             /* Just assign from the outer tuple. */
     726         9039 :             scratch.opcode = EEOP_ASSIGN_OUTER_VAR;
     727         9039 :             scratch.d.assign_var.attnum = outerattnum;
     728         9039 :             scratch.d.assign_var.resultnum = targetattnum - 1;
     729         9039 :             ExprEvalPushStep(state, &scratch);
     730              :         }
     731        10910 :         outerattnum++;
     732              :     }
     733              : 
     734              :     /*
     735              :      * Now generate code to copy over any old columns that were not assigned
     736              :      * to, and to ensure that dropped columns are set to NULL.
     737              :      */
     738        80566 :     for (int attnum = 1; attnum <= relDesc->natts; attnum++)
     739              :     {
     740        72130 :         CompactAttribute *attr = TupleDescCompactAttr(relDesc, attnum - 1);
     741              : 
     742        72130 :         if (attr->attisdropped)
     743              :         {
     744              :             /* Put a null into the ExprState's resvalue/resnull ... */
     745          205 :             scratch.opcode = EEOP_CONST;
     746          205 :             scratch.resvalue = &state->resvalue;
     747          205 :             scratch.resnull = &state->resnull;
     748          205 :             scratch.d.constval.value = (Datum) 0;
     749          205 :             scratch.d.constval.isnull = true;
     750          205 :             ExprEvalPushStep(state, &scratch);
     751              :             /* ... then assign it to the result slot */
     752          205 :             scratch.opcode = EEOP_ASSIGN_TMP;
     753          205 :             scratch.d.assign_tmp.resultnum = attnum - 1;
     754          205 :             ExprEvalPushStep(state, &scratch);
     755              :         }
     756        71925 :         else if (!bms_is_member(attnum, assignedCols))
     757              :         {
     758              :             /* Certainly the right type, so needn't check */
     759        61015 :             scratch.opcode = EEOP_ASSIGN_SCAN_VAR;
     760        61015 :             scratch.d.assign_var.attnum = attnum - 1;
     761        61015 :             scratch.d.assign_var.resultnum = attnum - 1;
     762        61015 :             ExprEvalPushStep(state, &scratch);
     763              :         }
     764              :     }
     765              : 
     766         8436 :     scratch.opcode = EEOP_DONE_NO_RETURN;
     767         8436 :     ExprEvalPushStep(state, &scratch);
     768              : 
     769         8436 :     ExecReadyExpr(state);
     770              : 
     771         8436 :     return projInfo;
     772              : }
     773              : 
     774              : /*
     775              :  * ExecPrepareExpr --- initialize for expression execution outside a normal
     776              :  * Plan tree context.
     777              :  *
     778              :  * This differs from ExecInitExpr in that we don't assume the caller is
     779              :  * already running in the EState's per-query context.  Also, we run the
     780              :  * passed expression tree through expression_planner() to prepare it for
     781              :  * execution.  (In ordinary Plan trees the regular planning process will have
     782              :  * made the appropriate transformations on expressions, but for standalone
     783              :  * expressions this won't have happened.)
     784              :  */
     785              : ExprState *
     786        13649 : ExecPrepareExpr(Expr *node, EState *estate)
     787              : {
     788        13649 :     return ExecPrepareExprWithContext(node, estate, NULL);
     789              : }
     790              : 
     791              : /*
     792              :  * ExecPrepareExprWithContext: same as ExecPrepareExpr, but with an optional
     793              :  * ErrorSaveContext for soft error handling.
     794              :  *
     795              :  * See ExecInitExprWithContext for details on the escontext parameter.
     796              :  */
     797              : ExprState *
     798        13937 : ExecPrepareExprWithContext(Expr *node, EState *estate, Node *escontext)
     799              : {
     800              :     ExprState  *result;
     801              :     MemoryContext oldcontext;
     802              : 
     803        13937 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     804              : 
     805        13937 :     node = expression_planner(node);
     806              : 
     807        13934 :     result = ExecInitExprWithContext(node, NULL, escontext);
     808              : 
     809        13931 :     MemoryContextSwitchTo(oldcontext);
     810              : 
     811        13931 :     return result;
     812              : }
     813              : 
     814              : /*
     815              :  * ExecPrepareQual --- initialize for qual execution outside a normal
     816              :  * Plan tree context.
     817              :  *
     818              :  * This differs from ExecInitQual in that we don't assume the caller is
     819              :  * already running in the EState's per-query context.  Also, we run the
     820              :  * passed expression tree through expression_planner() to prepare it for
     821              :  * execution.  (In ordinary Plan trees the regular planning process will have
     822              :  * made the appropriate transformations on expressions, but for standalone
     823              :  * expressions this won't have happened.)
     824              :  */
     825              : ExprState *
     826        30542 : ExecPrepareQual(List *qual, EState *estate)
     827              : {
     828              :     ExprState  *result;
     829              :     MemoryContext oldcontext;
     830              : 
     831        30542 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     832              : 
     833        30542 :     qual = (List *) expression_planner((Expr *) qual);
     834              : 
     835        30542 :     result = ExecInitQual(qual, NULL);
     836              : 
     837        30542 :     MemoryContextSwitchTo(oldcontext);
     838              : 
     839        30542 :     return result;
     840              : }
     841              : 
     842              : /*
     843              :  * ExecPrepareCheck -- initialize check constraint for execution outside a
     844              :  * normal Plan tree context.
     845              :  *
     846              :  * See ExecPrepareExpr() and ExecInitCheck() for details.
     847              :  */
     848              : ExprState *
     849         2938 : ExecPrepareCheck(List *qual, EState *estate)
     850              : {
     851              :     ExprState  *result;
     852              :     MemoryContext oldcontext;
     853              : 
     854         2938 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     855              : 
     856         2938 :     qual = (List *) expression_planner((Expr *) qual);
     857              : 
     858         2938 :     result = ExecInitCheck(qual, NULL);
     859              : 
     860         2938 :     MemoryContextSwitchTo(oldcontext);
     861              : 
     862         2938 :     return result;
     863              : }
     864              : 
     865              : /*
     866              :  * Call ExecPrepareExpr() on each member of a list of Exprs, and return
     867              :  * a list of ExprStates.
     868              :  *
     869              :  * See ExecPrepareExpr() for details.
     870              :  */
     871              : List *
     872         8793 : ExecPrepareExprList(List *nodes, EState *estate)
     873              : {
     874         8793 :     List       *result = NIL;
     875              :     MemoryContext oldcontext;
     876              :     ListCell   *lc;
     877              : 
     878              :     /* Ensure that the list cell nodes are in the right context too */
     879         8793 :     oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
     880              : 
     881        17991 :     foreach(lc, nodes)
     882              :     {
     883         9198 :         Expr       *e = (Expr *) lfirst(lc);
     884              : 
     885         9198 :         result = lappend(result, ExecPrepareExpr(e, estate));
     886              :     }
     887              : 
     888         8793 :     MemoryContextSwitchTo(oldcontext);
     889              : 
     890         8793 :     return result;
     891              : }
     892              : 
     893              : /*
     894              :  * ExecCheck - evaluate a check constraint
     895              :  *
     896              :  * For check constraints, a null result is taken as TRUE, ie the constraint
     897              :  * passes.
     898              :  *
     899              :  * The check constraint may have been prepared with ExecInitCheck
     900              :  * (possibly via ExecPrepareCheck) if the caller had it in implicit-AND
     901              :  * format, but a regular boolean expression prepared with ExecInitExpr or
     902              :  * ExecPrepareExpr works too.
     903              :  */
     904              : bool
     905        57406 : ExecCheck(ExprState *state, ExprContext *econtext)
     906              : {
     907              :     Datum       ret;
     908              :     bool        isnull;
     909              : 
     910              :     /* short-circuit (here and in ExecInitCheck) for empty restriction list */
     911        57406 :     if (state == NULL)
     912           90 :         return true;
     913              : 
     914              :     /* verify that expression was not compiled using ExecInitQual */
     915              :     Assert(!(state->flags & EEO_FLAG_IS_QUAL));
     916              : 
     917        57316 :     ret = ExecEvalExprSwitchContext(state, econtext, &isnull);
     918              : 
     919        57313 :     if (isnull)
     920         1425 :         return true;
     921              : 
     922        55888 :     return DatumGetBool(ret);
     923              : }
     924              : 
     925              : /*
     926              :  * Prepare a compiled expression for execution.  This has to be called for
     927              :  * every ExprState before it can be executed.
     928              :  *
     929              :  * NB: While this currently only calls ExecReadyInterpretedExpr(),
     930              :  * this will likely get extended to further expression evaluation methods.
     931              :  * Therefore this should be used instead of directly calling
     932              :  * ExecReadyInterpretedExpr().
     933              :  */
     934              : static void
     935      2223164 : ExecReadyExpr(ExprState *state)
     936              : {
     937      2223164 :     if (jit_compile_expr(state))
     938         3727 :         return;
     939              : 
     940      2219437 :     ExecReadyInterpretedExpr(state);
     941              : }
     942              : 
     943              : /*
     944              :  * Append the steps necessary for the evaluation of node to ExprState->steps,
     945              :  * possibly recursing into sub-expressions of node.
     946              :  *
     947              :  * node - expression to evaluate
     948              :  * state - ExprState to whose ->steps to append the necessary operations
     949              :  * resv / resnull - where to store the result of the node into
     950              :  */
     951              : static void
     952      5003917 : ExecInitExprRec(Expr *node, ExprState *state,
     953              :                 Datum *resv, bool *resnull)
     954              : {
     955      5003917 :     ExprEvalStep scratch = {0};
     956              : 
     957              :     /* Guard against stack overflow due to overly complex expressions */
     958      5003917 :     check_stack_depth();
     959              : 
     960              :     /* Step's output location is always what the caller gave us */
     961              :     Assert(resv != NULL && resnull != NULL);
     962      5003917 :     scratch.resvalue = resv;
     963      5003917 :     scratch.resnull = resnull;
     964              : 
     965              :     /* cases should be ordered as they are in enum NodeTag */
     966      5003917 :     switch (nodeTag(node))
     967              :     {
     968      1565245 :         case T_Var:
     969              :             {
     970      1565245 :                 Var        *variable = (Var *) node;
     971              : 
     972      1565245 :                 if (variable->varattno == InvalidAttrNumber)
     973              :                 {
     974              :                     /* whole-row Var */
     975         2657 :                     ExecInitWholeRowVar(&scratch, variable, state);
     976              :                 }
     977      1562588 :                 else if (variable->varattno <= 0)
     978              :                 {
     979              :                     /* system column */
     980       454187 :                     scratch.d.var.attnum = variable->varattno;
     981       454187 :                     scratch.d.var.vartype = variable->vartype;
     982       454187 :                     scratch.d.var.varreturningtype = variable->varreturningtype;
     983       454187 :                     switch (variable->varno)
     984              :                     {
     985            3 :                         case INNER_VAR:
     986            3 :                             scratch.opcode = EEOP_INNER_SYSVAR;
     987            3 :                             break;
     988            6 :                         case OUTER_VAR:
     989            6 :                             scratch.opcode = EEOP_OUTER_SYSVAR;
     990            6 :                             break;
     991              : 
     992              :                             /* INDEX_VAR is handled by default case */
     993              : 
     994       454178 :                         default:
     995       454178 :                             switch (variable->varreturningtype)
     996              :                             {
     997       453854 :                                 case VAR_RETURNING_DEFAULT:
     998       453854 :                                     scratch.opcode = EEOP_SCAN_SYSVAR;
     999       453854 :                                     break;
    1000          162 :                                 case VAR_RETURNING_OLD:
    1001          162 :                                     scratch.opcode = EEOP_OLD_SYSVAR;
    1002          162 :                                     state->flags |= EEO_FLAG_HAS_OLD;
    1003          162 :                                     break;
    1004          162 :                                 case VAR_RETURNING_NEW:
    1005          162 :                                     scratch.opcode = EEOP_NEW_SYSVAR;
    1006          162 :                                     state->flags |= EEO_FLAG_HAS_NEW;
    1007          162 :                                     break;
    1008              :                             }
    1009       454178 :                             break;
    1010              :                     }
    1011              :                 }
    1012              :                 else
    1013              :                 {
    1014              :                     /* regular user column */
    1015      1108401 :                     scratch.d.var.attnum = variable->varattno - 1;
    1016      1108401 :                     scratch.d.var.vartype = variable->vartype;
    1017      1108401 :                     scratch.d.var.varreturningtype = variable->varreturningtype;
    1018      1108401 :                     switch (variable->varno)
    1019              :                     {
    1020       100462 :                         case INNER_VAR:
    1021       100462 :                             scratch.opcode = EEOP_INNER_VAR;
    1022       100462 :                             break;
    1023       209368 :                         case OUTER_VAR:
    1024       209368 :                             scratch.opcode = EEOP_OUTER_VAR;
    1025       209368 :                             break;
    1026              : 
    1027              :                             /* INDEX_VAR is handled by default case */
    1028              : 
    1029       798571 :                         default:
    1030       798571 :                             switch (variable->varreturningtype)
    1031              :                             {
    1032       798325 :                                 case VAR_RETURNING_DEFAULT:
    1033       798325 :                                     scratch.opcode = EEOP_SCAN_VAR;
    1034       798325 :                                     break;
    1035          123 :                                 case VAR_RETURNING_OLD:
    1036          123 :                                     scratch.opcode = EEOP_OLD_VAR;
    1037          123 :                                     state->flags |= EEO_FLAG_HAS_OLD;
    1038          123 :                                     break;
    1039          123 :                                 case VAR_RETURNING_NEW:
    1040          123 :                                     scratch.opcode = EEOP_NEW_VAR;
    1041          123 :                                     state->flags |= EEO_FLAG_HAS_NEW;
    1042          123 :                                     break;
    1043              :                             }
    1044       798571 :                             break;
    1045              :                     }
    1046              :                 }
    1047              : 
    1048      1565245 :                 ExprEvalPushStep(state, &scratch);
    1049      1565245 :                 break;
    1050              :             }
    1051              : 
    1052       979260 :         case T_Const:
    1053              :             {
    1054       979260 :                 Const      *con = (Const *) node;
    1055              : 
    1056       979260 :                 scratch.opcode = EEOP_CONST;
    1057       979260 :                 scratch.d.constval.value = con->constvalue;
    1058       979260 :                 scratch.d.constval.isnull = con->constisnull;
    1059              : 
    1060       979260 :                 ExprEvalPushStep(state, &scratch);
    1061       979260 :                 break;
    1062              :             }
    1063              : 
    1064       900564 :         case T_Param:
    1065              :             {
    1066       900564 :                 Param      *param = (Param *) node;
    1067              :                 ParamListInfo params;
    1068              : 
    1069       900564 :                 switch (param->paramkind)
    1070              :                 {
    1071       139318 :                     case PARAM_EXEC:
    1072       139318 :                         scratch.opcode = EEOP_PARAM_EXEC;
    1073       139318 :                         scratch.d.param.paramid = param->paramid;
    1074       139318 :                         scratch.d.param.paramtype = param->paramtype;
    1075       139318 :                         ExprEvalPushStep(state, &scratch);
    1076       139318 :                         break;
    1077       761246 :                     case PARAM_EXTERN:
    1078              : 
    1079              :                         /*
    1080              :                          * If we have a relevant ParamCompileHook, use it;
    1081              :                          * otherwise compile a standard EEOP_PARAM_EXTERN
    1082              :                          * step.  ext_params, if supplied, takes precedence
    1083              :                          * over info from the parent node's EState (if any).
    1084              :                          */
    1085       761246 :                         if (state->ext_params)
    1086        36988 :                             params = state->ext_params;
    1087       724258 :                         else if (state->parent &&
    1088       724159 :                                  state->parent->state)
    1089       724159 :                             params = state->parent->state->es_param_list_info;
    1090              :                         else
    1091           99 :                             params = NULL;
    1092       761246 :                         if (params && params->paramCompile)
    1093              :                         {
    1094        75414 :                             params->paramCompile(params, param, state,
    1095              :                                                  resv, resnull);
    1096              :                         }
    1097              :                         else
    1098              :                         {
    1099       685832 :                             scratch.opcode = EEOP_PARAM_EXTERN;
    1100       685832 :                             scratch.d.param.paramid = param->paramid;
    1101       685832 :                             scratch.d.param.paramtype = param->paramtype;
    1102       685832 :                             ExprEvalPushStep(state, &scratch);
    1103              :                         }
    1104       761246 :                         break;
    1105            0 :                     default:
    1106            0 :                         elog(ERROR, "unrecognized paramkind: %d",
    1107              :                              (int) param->paramkind);
    1108              :                         break;
    1109              :                 }
    1110       900564 :                 break;
    1111              :             }
    1112              : 
    1113        31007 :         case T_Aggref:
    1114              :             {
    1115        31007 :                 Aggref     *aggref = (Aggref *) node;
    1116              : 
    1117        31007 :                 scratch.opcode = EEOP_AGGREF;
    1118        31007 :                 scratch.d.aggref.aggno = aggref->aggno;
    1119              : 
    1120        31007 :                 if (state->parent && IsA(state->parent, AggState))
    1121        31007 :                 {
    1122        31007 :                     AggState   *aggstate = (AggState *) state->parent;
    1123              : 
    1124        31007 :                     aggstate->aggs = lappend(aggstate->aggs, aggref);
    1125              :                 }
    1126              :                 else
    1127              :                 {
    1128              :                     /* planner messed up */
    1129            0 :                     elog(ERROR, "Aggref found in non-Agg plan node");
    1130              :                 }
    1131              : 
    1132        31007 :                 ExprEvalPushStep(state, &scratch);
    1133        31007 :                 break;
    1134              :             }
    1135              : 
    1136          185 :         case T_GroupingFunc:
    1137              :             {
    1138          185 :                 GroupingFunc *grp_node = (GroupingFunc *) node;
    1139              :                 Agg        *agg;
    1140              : 
    1141          185 :                 if (!state->parent || !IsA(state->parent, AggState) ||
    1142          185 :                     !IsA(state->parent->plan, Agg))
    1143            0 :                     elog(ERROR, "GroupingFunc found in non-Agg plan node");
    1144              : 
    1145          185 :                 scratch.opcode = EEOP_GROUPING_FUNC;
    1146              : 
    1147          185 :                 agg = (Agg *) (state->parent->plan);
    1148              : 
    1149          185 :                 if (agg->groupingSets)
    1150          136 :                     scratch.d.grouping_func.clauses = grp_node->cols;
    1151              :                 else
    1152           49 :                     scratch.d.grouping_func.clauses = NIL;
    1153              : 
    1154          185 :                 ExprEvalPushStep(state, &scratch);
    1155          185 :                 break;
    1156              :             }
    1157              : 
    1158         1854 :         case T_WindowFunc:
    1159              :             {
    1160         1854 :                 WindowFunc *wfunc = (WindowFunc *) node;
    1161         1854 :                 WindowFuncExprState *wfstate = makeNode(WindowFuncExprState);
    1162              : 
    1163         1854 :                 wfstate->wfunc = wfunc;
    1164              : 
    1165         1854 :                 if (state->parent && IsA(state->parent, WindowAggState))
    1166         1854 :                 {
    1167         1854 :                     WindowAggState *winstate = (WindowAggState *) state->parent;
    1168              :                     int         nfuncs;
    1169              : 
    1170         1854 :                     winstate->funcs = lappend(winstate->funcs, wfstate);
    1171         1854 :                     nfuncs = ++winstate->numfuncs;
    1172         1854 :                     if (wfunc->winagg)
    1173          834 :                         winstate->numaggs++;
    1174              : 
    1175              :                     /* for now initialize agg using old style expressions */
    1176         1854 :                     wfstate->args = ExecInitExprList(wfunc->args,
    1177              :                                                      state->parent);
    1178         1854 :                     wfstate->aggfilter = ExecInitExpr(wfunc->aggfilter,
    1179              :                                                       state->parent);
    1180              : 
    1181              :                     /*
    1182              :                      * Complain if the windowfunc's arguments contain any
    1183              :                      * windowfuncs; nested window functions are semantically
    1184              :                      * nonsensical.  (This should have been caught earlier,
    1185              :                      * but we defend against it here anyway.)
    1186              :                      */
    1187         1854 :                     if (nfuncs != winstate->numfuncs)
    1188            0 :                         ereport(ERROR,
    1189              :                                 (errcode(ERRCODE_WINDOWING_ERROR),
    1190              :                                  errmsg("window function calls cannot be nested")));
    1191              :                 }
    1192              :                 else
    1193              :                 {
    1194              :                     /* planner messed up */
    1195            0 :                     elog(ERROR, "WindowFunc found in non-WindowAgg plan node");
    1196              :                 }
    1197              : 
    1198         1854 :                 scratch.opcode = EEOP_WINDOW_FUNC;
    1199         1854 :                 scratch.d.window_func.wfstate = wfstate;
    1200         1854 :                 ExprEvalPushStep(state, &scratch);
    1201         1854 :                 break;
    1202              :             }
    1203              : 
    1204          123 :         case T_MergeSupportFunc:
    1205              :             {
    1206              :                 /* must be in a MERGE, else something messed up */
    1207          123 :                 if (!state->parent ||
    1208          123 :                     !IsA(state->parent, ModifyTableState) ||
    1209          123 :                     ((ModifyTableState *) state->parent)->operation != CMD_MERGE)
    1210            0 :                     elog(ERROR, "MergeSupportFunc found in non-merge plan node");
    1211              : 
    1212          123 :                 scratch.opcode = EEOP_MERGE_SUPPORT_FUNC;
    1213          123 :                 ExprEvalPushStep(state, &scratch);
    1214          123 :                 break;
    1215              :             }
    1216              : 
    1217        15928 :         case T_SubscriptingRef:
    1218              :             {
    1219        15928 :                 SubscriptingRef *sbsref = (SubscriptingRef *) node;
    1220              : 
    1221        15928 :                 ExecInitSubscriptingRef(&scratch, sbsref, state, resv, resnull);
    1222        15928 :                 break;
    1223              :             }
    1224              : 
    1225       308880 :         case T_FuncExpr:
    1226              :             {
    1227       308880 :                 FuncExpr   *func = (FuncExpr *) node;
    1228              : 
    1229       308880 :                 ExecInitFunc(&scratch, node,
    1230              :                              func->args, func->funcid, func->inputcollid,
    1231              :                              state);
    1232       308837 :                 ExprEvalPushStep(state, &scratch);
    1233       308837 :                 break;
    1234              :             }
    1235              : 
    1236       886223 :         case T_OpExpr:
    1237              :             {
    1238       886223 :                 OpExpr     *op = (OpExpr *) node;
    1239              : 
    1240       886223 :                 ExecInitFunc(&scratch, node,
    1241              :                              op->args, op->opfuncid, op->inputcollid,
    1242              :                              state);
    1243       886223 :                 ExprEvalPushStep(state, &scratch);
    1244       886223 :                 break;
    1245              :             }
    1246              : 
    1247          727 :         case T_DistinctExpr:
    1248              :             {
    1249          727 :                 DistinctExpr *op = (DistinctExpr *) node;
    1250              : 
    1251          727 :                 ExecInitFunc(&scratch, node,
    1252              :                              op->args, op->opfuncid, op->inputcollid,
    1253              :                              state);
    1254              : 
    1255              :                 /*
    1256              :                  * Change opcode of call instruction to EEOP_DISTINCT.
    1257              :                  *
    1258              :                  * XXX: historically we've not called the function usage
    1259              :                  * pgstat infrastructure - that seems inconsistent given that
    1260              :                  * we do so for normal function *and* operator evaluation.  If
    1261              :                  * we decided to do that here, we'd probably want separate
    1262              :                  * opcodes for FUSAGE or not.
    1263              :                  */
    1264          727 :                 scratch.opcode = EEOP_DISTINCT;
    1265          727 :                 ExprEvalPushStep(state, &scratch);
    1266          727 :                 break;
    1267              :             }
    1268              : 
    1269          383 :         case T_NullIfExpr:
    1270              :             {
    1271          383 :                 NullIfExpr *op = (NullIfExpr *) node;
    1272              : 
    1273          383 :                 ExecInitFunc(&scratch, node,
    1274              :                              op->args, op->opfuncid, op->inputcollid,
    1275              :                              state);
    1276              : 
    1277              :                 /*
    1278              :                  * If first argument is of varlena type, we'll need to ensure
    1279              :                  * that the value passed to the comparison function is a
    1280              :                  * read-only pointer.
    1281              :                  */
    1282          383 :                 scratch.d.func.make_ro =
    1283          383 :                     (get_typlen(exprType((Node *) linitial(op->args))) == -1);
    1284              : 
    1285              :                 /*
    1286              :                  * Change opcode of call instruction to EEOP_NULLIF.
    1287              :                  *
    1288              :                  * XXX: historically we've not called the function usage
    1289              :                  * pgstat infrastructure - that seems inconsistent given that
    1290              :                  * we do so for normal function *and* operator evaluation.  If
    1291              :                  * we decided to do that here, we'd probably want separate
    1292              :                  * opcodes for FUSAGE or not.
    1293              :                  */
    1294          383 :                 scratch.opcode = EEOP_NULLIF;
    1295          383 :                 ExprEvalPushStep(state, &scratch);
    1296          383 :                 break;
    1297              :             }
    1298              : 
    1299        19704 :         case T_ScalarArrayOpExpr:
    1300              :             {
    1301        19704 :                 ScalarArrayOpExpr *opexpr = (ScalarArrayOpExpr *) node;
    1302              :                 Expr       *scalararg;
    1303              :                 Expr       *arrayarg;
    1304              :                 FmgrInfo   *finfo;
    1305              :                 FunctionCallInfo fcinfo;
    1306              :                 AclResult   aclresult;
    1307              :                 Oid         cmpfuncid;
    1308              : 
    1309              :                 /*
    1310              :                  * Select the correct comparison function.  When we do hashed
    1311              :                  * NOT IN clauses, the opfuncid will be the inequality
    1312              :                  * comparison function and negfuncid will be set to equality.
    1313              :                  * We need to use the equality function for hash probes.
    1314              :                  */
    1315        19704 :                 if (OidIsValid(opexpr->negfuncid))
    1316              :                 {
    1317              :                     Assert(OidIsValid(opexpr->hashfuncid));
    1318           35 :                     cmpfuncid = opexpr->negfuncid;
    1319              :                 }
    1320              :                 else
    1321        19669 :                     cmpfuncid = opexpr->opfuncid;
    1322              : 
    1323              :                 Assert(list_length(opexpr->args) == 2);
    1324        19704 :                 scalararg = (Expr *) linitial(opexpr->args);
    1325        19704 :                 arrayarg = (Expr *) lsecond(opexpr->args);
    1326              : 
    1327              :                 /* Check permission to call function */
    1328        19704 :                 aclresult = object_aclcheck(ProcedureRelationId, cmpfuncid,
    1329              :                                             GetUserId(),
    1330              :                                             ACL_EXECUTE);
    1331        19704 :                 if (aclresult != ACLCHECK_OK)
    1332            0 :                     aclcheck_error(aclresult, OBJECT_FUNCTION,
    1333            0 :                                    get_func_name(cmpfuncid));
    1334        19704 :                 InvokeFunctionExecuteHook(cmpfuncid);
    1335              : 
    1336        19704 :                 if (OidIsValid(opexpr->hashfuncid))
    1337              :                 {
    1338          215 :                     aclresult = object_aclcheck(ProcedureRelationId, opexpr->hashfuncid,
    1339              :                                                 GetUserId(),
    1340              :                                                 ACL_EXECUTE);
    1341          215 :                     if (aclresult != ACLCHECK_OK)
    1342            0 :                         aclcheck_error(aclresult, OBJECT_FUNCTION,
    1343            0 :                                        get_func_name(opexpr->hashfuncid));
    1344          215 :                     InvokeFunctionExecuteHook(opexpr->hashfuncid);
    1345              :                 }
    1346              : 
    1347              :                 /* Set up the primary fmgr lookup information */
    1348        19704 :                 finfo = palloc0_object(FmgrInfo);
    1349        19704 :                 fcinfo = palloc0(SizeForFunctionCallInfo(2));
    1350        19704 :                 fmgr_info(cmpfuncid, finfo);
    1351        19704 :                 fmgr_info_set_expr((Node *) node, finfo);
    1352        19704 :                 InitFunctionCallInfoData(*fcinfo, finfo, 2,
    1353              :                                          opexpr->inputcollid, NULL, NULL);
    1354              : 
    1355              :                 /*
    1356              :                  * If hashfuncid is set, we create a EEOP_HASHED_SCALARARRAYOP
    1357              :                  * step instead of a EEOP_SCALARARRAYOP.  This provides much
    1358              :                  * faster lookup performance than the normal linear search
    1359              :                  * when the number of items in the array is anything but very
    1360              :                  * small.
    1361              :                  */
    1362        19704 :                 if (OidIsValid(opexpr->hashfuncid))
    1363              :                 {
    1364              :                     /* Evaluate scalar directly into left function argument */
    1365          215 :                     ExecInitExprRec(scalararg, state,
    1366              :                                     &fcinfo->args[0].value, &fcinfo->args[0].isnull);
    1367              : 
    1368              :                     /*
    1369              :                      * Evaluate array argument into our return value.  There's
    1370              :                      * no danger in that, because the return value is
    1371              :                      * guaranteed to be overwritten by
    1372              :                      * EEOP_HASHED_SCALARARRAYOP, and will not be passed to
    1373              :                      * any other expression.
    1374              :                      */
    1375          215 :                     ExecInitExprRec(arrayarg, state, resv, resnull);
    1376              : 
    1377              :                     /* And perform the operation */
    1378          215 :                     scratch.opcode = EEOP_HASHED_SCALARARRAYOP;
    1379          215 :                     scratch.d.hashedscalararrayop.inclause = opexpr->useOr;
    1380          215 :                     scratch.d.hashedscalararrayop.finfo = finfo;
    1381          215 :                     scratch.d.hashedscalararrayop.fcinfo_data = fcinfo;
    1382          215 :                     scratch.d.hashedscalararrayop.saop = opexpr;
    1383              : 
    1384              : 
    1385          215 :                     ExprEvalPushStep(state, &scratch);
    1386              :                 }
    1387              :                 else
    1388              :                 {
    1389              :                     /* Evaluate scalar directly into left function argument */
    1390        19489 :                     ExecInitExprRec(scalararg, state,
    1391              :                                     &fcinfo->args[0].value,
    1392              :                                     &fcinfo->args[0].isnull);
    1393              : 
    1394              :                     /*
    1395              :                      * Evaluate array argument into our return value.  There's
    1396              :                      * no danger in that, because the return value is
    1397              :                      * guaranteed to be overwritten by EEOP_SCALARARRAYOP, and
    1398              :                      * will not be passed to any other expression.
    1399              :                      */
    1400        19489 :                     ExecInitExprRec(arrayarg, state, resv, resnull);
    1401              : 
    1402              :                     /* And perform the operation */
    1403        19489 :                     scratch.opcode = EEOP_SCALARARRAYOP;
    1404        19489 :                     scratch.d.scalararrayop.element_type = InvalidOid;
    1405        19489 :                     scratch.d.scalararrayop.useOr = opexpr->useOr;
    1406        19489 :                     scratch.d.scalararrayop.finfo = finfo;
    1407        19489 :                     scratch.d.scalararrayop.fcinfo_data = fcinfo;
    1408        19489 :                     scratch.d.scalararrayop.fn_addr = finfo->fn_addr;
    1409        19489 :                     ExprEvalPushStep(state, &scratch);
    1410              :                 }
    1411        19704 :                 break;
    1412              :             }
    1413              : 
    1414        39666 :         case T_BoolExpr:
    1415              :             {
    1416        39666 :                 BoolExpr   *boolexpr = (BoolExpr *) node;
    1417        39666 :                 int         nargs = list_length(boolexpr->args);
    1418        39666 :                 List       *adjust_jumps = NIL;
    1419              :                 int         off;
    1420              :                 ListCell   *lc;
    1421              : 
    1422              :                 /* allocate scratch memory used by all steps of AND/OR */
    1423        39666 :                 if (boolexpr->boolop != NOT_EXPR)
    1424        29416 :                     scratch.d.boolexpr.anynull = palloc_object(bool);
    1425              : 
    1426              :                 /*
    1427              :                  * For each argument evaluate the argument itself, then
    1428              :                  * perform the bool operation's appropriate handling.
    1429              :                  *
    1430              :                  * We can evaluate each argument into our result area, since
    1431              :                  * the short-circuiting logic means we only need to remember
    1432              :                  * previous NULL values.
    1433              :                  *
    1434              :                  * AND/OR is split into separate STEP_FIRST (one) / STEP (zero
    1435              :                  * or more) / STEP_LAST (one) steps, as each of those has to
    1436              :                  * perform different work.  The FIRST/LAST split is valid
    1437              :                  * because AND/OR have at least two arguments.
    1438              :                  */
    1439        39666 :                 off = 0;
    1440       116043 :                 foreach(lc, boolexpr->args)
    1441              :                 {
    1442        76377 :                     Expr       *arg = (Expr *) lfirst(lc);
    1443              : 
    1444              :                     /* Evaluate argument into our output variable */
    1445        76377 :                     ExecInitExprRec(arg, state, resv, resnull);
    1446              : 
    1447              :                     /* Perform the appropriate step type */
    1448        76377 :                     switch (boolexpr->boolop)
    1449              :                     {
    1450        42326 :                         case AND_EXPR:
    1451              :                             Assert(nargs >= 2);
    1452              : 
    1453        42326 :                             if (off == 0)
    1454        18871 :                                 scratch.opcode = EEOP_BOOL_AND_STEP_FIRST;
    1455        23455 :                             else if (off + 1 == nargs)
    1456        18871 :                                 scratch.opcode = EEOP_BOOL_AND_STEP_LAST;
    1457              :                             else
    1458         4584 :                                 scratch.opcode = EEOP_BOOL_AND_STEP;
    1459        42326 :                             break;
    1460        23801 :                         case OR_EXPR:
    1461              :                             Assert(nargs >= 2);
    1462              : 
    1463        23801 :                             if (off == 0)
    1464        10545 :                                 scratch.opcode = EEOP_BOOL_OR_STEP_FIRST;
    1465        13256 :                             else if (off + 1 == nargs)
    1466        10545 :                                 scratch.opcode = EEOP_BOOL_OR_STEP_LAST;
    1467              :                             else
    1468         2711 :                                 scratch.opcode = EEOP_BOOL_OR_STEP;
    1469        23801 :                             break;
    1470        10250 :                         case NOT_EXPR:
    1471              :                             Assert(nargs == 1);
    1472              : 
    1473        10250 :                             scratch.opcode = EEOP_BOOL_NOT_STEP;
    1474        10250 :                             break;
    1475            0 :                         default:
    1476            0 :                             elog(ERROR, "unrecognized boolop: %d",
    1477              :                                  (int) boolexpr->boolop);
    1478              :                             break;
    1479              :                     }
    1480              : 
    1481        76377 :                     scratch.d.boolexpr.jumpdone = -1;
    1482        76377 :                     ExprEvalPushStep(state, &scratch);
    1483        76377 :                     adjust_jumps = lappend_int(adjust_jumps,
    1484        76377 :                                                state->steps_len - 1);
    1485        76377 :                     off++;
    1486              :                 }
    1487              : 
    1488              :                 /* adjust jump targets */
    1489       116043 :                 foreach(lc, adjust_jumps)
    1490              :                 {
    1491        76377 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1492              : 
    1493              :                     Assert(as->d.boolexpr.jumpdone == -1);
    1494        76377 :                     as->d.boolexpr.jumpdone = state->steps_len;
    1495              :                 }
    1496              : 
    1497        39666 :                 break;
    1498              :             }
    1499              : 
    1500        16200 :         case T_SubPlan:
    1501              :             {
    1502        16200 :                 SubPlan    *subplan = (SubPlan *) node;
    1503              : 
    1504              :                 /*
    1505              :                  * Real execution of a MULTIEXPR SubPlan has already been
    1506              :                  * done. What we have to do here is return a dummy NULL record
    1507              :                  * value in case this targetlist element is assigned
    1508              :                  * someplace.
    1509              :                  */
    1510        16200 :                 if (subplan->subLinkType == MULTIEXPR_SUBLINK)
    1511              :                 {
    1512           30 :                     scratch.opcode = EEOP_CONST;
    1513           30 :                     scratch.d.constval.value = (Datum) 0;
    1514           30 :                     scratch.d.constval.isnull = true;
    1515           30 :                     ExprEvalPushStep(state, &scratch);
    1516           30 :                     break;
    1517              :                 }
    1518              : 
    1519        16170 :                 ExecInitSubPlanExpr(subplan, state, resv, resnull);
    1520        16170 :                 break;
    1521              :             }
    1522              : 
    1523        22282 :         case T_FieldSelect:
    1524              :             {
    1525        22282 :                 FieldSelect *fselect = (FieldSelect *) node;
    1526              : 
    1527              :                 /* evaluate row/record argument into result area */
    1528        22282 :                 ExecInitExprRec(fselect->arg, state, resv, resnull);
    1529              : 
    1530              :                 /* and extract field */
    1531        22282 :                 scratch.opcode = EEOP_FIELDSELECT;
    1532        22282 :                 scratch.d.fieldselect.fieldnum = fselect->fieldnum;
    1533        22282 :                 scratch.d.fieldselect.resulttype = fselect->resulttype;
    1534        22282 :                 scratch.d.fieldselect.rowcache.cacheptr = NULL;
    1535              : 
    1536        22282 :                 ExprEvalPushStep(state, &scratch);
    1537        22282 :                 break;
    1538              :             }
    1539              : 
    1540          191 :         case T_FieldStore:
    1541              :             {
    1542          191 :                 FieldStore *fstore = (FieldStore *) node;
    1543              :                 TupleDesc   tupDesc;
    1544              :                 ExprEvalRowtypeCache *rowcachep;
    1545              :                 Datum      *values;
    1546              :                 bool       *nulls;
    1547              :                 int         ncolumns;
    1548              :                 ListCell   *l1,
    1549              :                            *l2;
    1550              : 
    1551              :                 /* find out the number of columns in the composite type */
    1552          191 :                 tupDesc = lookup_rowtype_tupdesc(fstore->resulttype, -1);
    1553          191 :                 ncolumns = tupDesc->natts;
    1554          191 :                 ReleaseTupleDesc(tupDesc);
    1555              : 
    1556              :                 /* create workspace for column values */
    1557          191 :                 values = palloc_array(Datum, ncolumns);
    1558          191 :                 nulls = palloc_array(bool, ncolumns);
    1559              : 
    1560              :                 /* create shared composite-type-lookup cache struct */
    1561          191 :                 rowcachep = palloc_object(ExprEvalRowtypeCache);
    1562          191 :                 rowcachep->cacheptr = NULL;
    1563              : 
    1564              :                 /* emit code to evaluate the composite input value */
    1565          191 :                 ExecInitExprRec(fstore->arg, state, resv, resnull);
    1566              : 
    1567              :                 /* next, deform the input tuple into our workspace */
    1568          191 :                 scratch.opcode = EEOP_FIELDSTORE_DEFORM;
    1569          191 :                 scratch.d.fieldstore.fstore = fstore;
    1570          191 :                 scratch.d.fieldstore.rowcache = rowcachep;
    1571          191 :                 scratch.d.fieldstore.values = values;
    1572          191 :                 scratch.d.fieldstore.nulls = nulls;
    1573          191 :                 scratch.d.fieldstore.ncolumns = ncolumns;
    1574          191 :                 ExprEvalPushStep(state, &scratch);
    1575              : 
    1576              :                 /* evaluate new field values, store in workspace columns */
    1577          445 :                 forboth(l1, fstore->newvals, l2, fstore->fieldnums)
    1578              :                 {
    1579          254 :                     Expr       *e = (Expr *) lfirst(l1);
    1580          254 :                     AttrNumber  fieldnum = lfirst_int(l2);
    1581              :                     Datum      *save_innermost_caseval;
    1582              :                     bool       *save_innermost_casenull;
    1583              : 
    1584          254 :                     if (fieldnum <= 0 || fieldnum > ncolumns)
    1585            0 :                         elog(ERROR, "field number %d is out of range in FieldStore",
    1586              :                              fieldnum);
    1587              : 
    1588              :                     /*
    1589              :                      * Use the CaseTestExpr mechanism to pass down the old
    1590              :                      * value of the field being replaced; this is needed in
    1591              :                      * case the newval is itself a FieldStore or
    1592              :                      * SubscriptingRef that has to obtain and modify the old
    1593              :                      * value.  It's safe to reuse the CASE mechanism because
    1594              :                      * there cannot be a CASE between here and where the value
    1595              :                      * would be needed, and a field assignment can't be within
    1596              :                      * a CASE either.  (So saving and restoring
    1597              :                      * innermost_caseval is just paranoia, but let's do it
    1598              :                      * anyway.)
    1599              :                      *
    1600              :                      * Another non-obvious point is that it's safe to use the
    1601              :                      * field's values[]/nulls[] entries as both the caseval
    1602              :                      * source and the result address for this subexpression.
    1603              :                      * That's okay only because (1) both FieldStore and
    1604              :                      * SubscriptingRef evaluate their arg or refexpr inputs
    1605              :                      * first, and (2) any such CaseTestExpr is directly the
    1606              :                      * arg or refexpr input.  So any read of the caseval will
    1607              :                      * occur before there's a chance to overwrite it.  Also,
    1608              :                      * if multiple entries in the newvals/fieldnums lists
    1609              :                      * target the same field, they'll effectively be applied
    1610              :                      * left-to-right which is what we want.
    1611              :                      */
    1612          254 :                     save_innermost_caseval = state->innermost_caseval;
    1613          254 :                     save_innermost_casenull = state->innermost_casenull;
    1614          254 :                     state->innermost_caseval = &values[fieldnum - 1];
    1615          254 :                     state->innermost_casenull = &nulls[fieldnum - 1];
    1616              : 
    1617          254 :                     ExecInitExprRec(e, state,
    1618          254 :                                     &values[fieldnum - 1],
    1619          254 :                                     &nulls[fieldnum - 1]);
    1620              : 
    1621          254 :                     state->innermost_caseval = save_innermost_caseval;
    1622          254 :                     state->innermost_casenull = save_innermost_casenull;
    1623              :                 }
    1624              : 
    1625              :                 /* finally, form result tuple */
    1626          191 :                 scratch.opcode = EEOP_FIELDSTORE_FORM;
    1627          191 :                 scratch.d.fieldstore.fstore = fstore;
    1628          191 :                 scratch.d.fieldstore.rowcache = rowcachep;
    1629          191 :                 scratch.d.fieldstore.values = values;
    1630          191 :                 scratch.d.fieldstore.nulls = nulls;
    1631          191 :                 scratch.d.fieldstore.ncolumns = ncolumns;
    1632          191 :                 ExprEvalPushStep(state, &scratch);
    1633          191 :                 break;
    1634              :             }
    1635              : 
    1636        65347 :         case T_RelabelType:
    1637              :             {
    1638              :                 /* relabel doesn't need to do anything at runtime */
    1639        65347 :                 RelabelType *relabel = (RelabelType *) node;
    1640              : 
    1641        65347 :                 ExecInitExprRec(relabel->arg, state, resv, resnull);
    1642        65347 :                 break;
    1643              :             }
    1644              : 
    1645        21677 :         case T_CoerceViaIO:
    1646              :             {
    1647        21677 :                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
    1648              :                 Oid         iofunc;
    1649              :                 bool        typisvarlena;
    1650              :                 Oid         typioparam;
    1651              :                 FunctionCallInfo fcinfo_in;
    1652              : 
    1653              :                 /* evaluate argument into step's result area */
    1654        21677 :                 ExecInitExprRec(iocoerce->arg, state, resv, resnull);
    1655              : 
    1656              :                 /*
    1657              :                  * Prepare both output and input function calls, to be
    1658              :                  * evaluated inside a single evaluation step for speed - this
    1659              :                  * can be a very common operation.
    1660              :                  *
    1661              :                  * We don't check permissions here as a type's input/output
    1662              :                  * function are assumed to be executable by everyone.
    1663              :                  */
    1664        21677 :                 if (state->escontext == NULL)
    1665        21671 :                     scratch.opcode = EEOP_IOCOERCE;
    1666              :                 else
    1667            6 :                     scratch.opcode = EEOP_IOCOERCE_SAFE;
    1668              : 
    1669              :                 /* lookup the source type's output function */
    1670        21677 :                 scratch.d.iocoerce.finfo_out = palloc0_object(FmgrInfo);
    1671        21677 :                 scratch.d.iocoerce.fcinfo_data_out = palloc0(SizeForFunctionCallInfo(1));
    1672              : 
    1673        21677 :                 getTypeOutputInfo(exprType((Node *) iocoerce->arg),
    1674              :                                   &iofunc, &typisvarlena);
    1675        21677 :                 fmgr_info(iofunc, scratch.d.iocoerce.finfo_out);
    1676        21677 :                 fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_out);
    1677        21677 :                 InitFunctionCallInfoData(*scratch.d.iocoerce.fcinfo_data_out,
    1678              :                                          scratch.d.iocoerce.finfo_out,
    1679              :                                          1, InvalidOid, NULL, NULL);
    1680              : 
    1681              :                 /* lookup the result type's input function */
    1682        21677 :                 scratch.d.iocoerce.finfo_in = palloc0_object(FmgrInfo);
    1683        21677 :                 scratch.d.iocoerce.fcinfo_data_in = palloc0(SizeForFunctionCallInfo(3));
    1684              : 
    1685        21677 :                 getTypeInputInfo(iocoerce->resulttype,
    1686              :                                  &iofunc, &typioparam);
    1687        21677 :                 fmgr_info(iofunc, scratch.d.iocoerce.finfo_in);
    1688        21677 :                 fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_in);
    1689        21677 :                 InitFunctionCallInfoData(*scratch.d.iocoerce.fcinfo_data_in,
    1690              :                                          scratch.d.iocoerce.finfo_in,
    1691              :                                          3, InvalidOid, NULL, NULL);
    1692              : 
    1693              :                 /*
    1694              :                  * We can preload the second and third arguments for the input
    1695              :                  * function, since they're constants.
    1696              :                  */
    1697        21677 :                 fcinfo_in = scratch.d.iocoerce.fcinfo_data_in;
    1698        21677 :                 fcinfo_in->args[1].value = ObjectIdGetDatum(typioparam);
    1699        21677 :                 fcinfo_in->args[1].isnull = false;
    1700        21677 :                 fcinfo_in->args[2].value = Int32GetDatum(-1);
    1701        21677 :                 fcinfo_in->args[2].isnull = false;
    1702              : 
    1703        21677 :                 fcinfo_in->context = (Node *) state->escontext;
    1704              : 
    1705        21677 :                 ExprEvalPushStep(state, &scratch);
    1706        21677 :                 break;
    1707              :             }
    1708              : 
    1709         3103 :         case T_ArrayCoerceExpr:
    1710              :             {
    1711         3103 :                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
    1712              :                 Oid         resultelemtype;
    1713              :                 ExprState  *elemstate;
    1714              : 
    1715              :                 /* evaluate argument into step's result area */
    1716         3103 :                 ExecInitExprRec(acoerce->arg, state, resv, resnull);
    1717              : 
    1718         3103 :                 resultelemtype = get_element_type(acoerce->resulttype);
    1719         3103 :                 if (!OidIsValid(resultelemtype))
    1720            0 :                     ereport(ERROR,
    1721              :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1722              :                              errmsg("target type is not an array")));
    1723              : 
    1724              :                 /*
    1725              :                  * Construct a sub-expression for the per-element expression;
    1726              :                  * but don't ready it until after we check it for triviality.
    1727              :                  * We assume it hasn't any Var references, but does have a
    1728              :                  * CaseTestExpr representing the source array element values.
    1729              :                  */
    1730         3103 :                 elemstate = makeNode(ExprState);
    1731         3103 :                 elemstate->expr = acoerce->elemexpr;
    1732         3103 :                 elemstate->parent = state->parent;
    1733         3103 :                 elemstate->ext_params = state->ext_params;
    1734              : 
    1735         3103 :                 elemstate->innermost_caseval = palloc_object(Datum);
    1736         3103 :                 elemstate->innermost_casenull = palloc_object(bool);
    1737              : 
    1738         3103 :                 ExecInitExprRec(acoerce->elemexpr, elemstate,
    1739              :                                 &elemstate->resvalue, &elemstate->resnull);
    1740              : 
    1741         3100 :                 if (elemstate->steps_len == 1 &&
    1742         2868 :                     elemstate->steps[0].opcode == EEOP_CASE_TESTVAL)
    1743              :                 {
    1744              :                     /* Trivial, so we need no per-element work at runtime */
    1745         2868 :                     elemstate = NULL;
    1746              :                 }
    1747              :                 else
    1748              :                 {
    1749              :                     /* Not trivial, so append a DONE step */
    1750          232 :                     scratch.opcode = EEOP_DONE_RETURN;
    1751          232 :                     ExprEvalPushStep(elemstate, &scratch);
    1752              :                     /* and ready the subexpression */
    1753          232 :                     ExecReadyExpr(elemstate);
    1754              :                 }
    1755              : 
    1756         3100 :                 scratch.opcode = EEOP_ARRAYCOERCE;
    1757         3100 :                 scratch.d.arraycoerce.elemexprstate = elemstate;
    1758         3100 :                 scratch.d.arraycoerce.resultelemtype = resultelemtype;
    1759              : 
    1760         3100 :                 if (elemstate)
    1761              :                 {
    1762              :                     /* Set up workspace for array_map */
    1763          232 :                     scratch.d.arraycoerce.amstate = palloc0_object(ArrayMapState);
    1764              :                 }
    1765              :                 else
    1766              :                 {
    1767              :                     /* Don't need workspace if there's no subexpression */
    1768         2868 :                     scratch.d.arraycoerce.amstate = NULL;
    1769              :                 }
    1770              : 
    1771         3100 :                 ExprEvalPushStep(state, &scratch);
    1772         3100 :                 break;
    1773              :             }
    1774              : 
    1775          418 :         case T_ConvertRowtypeExpr:
    1776              :             {
    1777          418 :                 ConvertRowtypeExpr *convert = (ConvertRowtypeExpr *) node;
    1778              :                 ExprEvalRowtypeCache *rowcachep;
    1779              : 
    1780              :                 /* cache structs must be out-of-line for space reasons */
    1781          418 :                 rowcachep = palloc(2 * sizeof(ExprEvalRowtypeCache));
    1782          418 :                 rowcachep[0].cacheptr = NULL;
    1783          418 :                 rowcachep[1].cacheptr = NULL;
    1784              : 
    1785              :                 /* evaluate argument into step's result area */
    1786          418 :                 ExecInitExprRec(convert->arg, state, resv, resnull);
    1787              : 
    1788              :                 /* and push conversion step */
    1789          418 :                 scratch.opcode = EEOP_CONVERT_ROWTYPE;
    1790          418 :                 scratch.d.convert_rowtype.inputtype =
    1791          418 :                     exprType((Node *) convert->arg);
    1792          418 :                 scratch.d.convert_rowtype.outputtype = convert->resulttype;
    1793          418 :                 scratch.d.convert_rowtype.incache = &rowcachep[0];
    1794          418 :                 scratch.d.convert_rowtype.outcache = &rowcachep[1];
    1795          418 :                 scratch.d.convert_rowtype.map = NULL;
    1796              : 
    1797          418 :                 ExprEvalPushStep(state, &scratch);
    1798          418 :                 break;
    1799              :             }
    1800              : 
    1801              :             /* note that CaseWhen expressions are handled within this block */
    1802        56105 :         case T_CaseExpr:
    1803              :             {
    1804        56105 :                 CaseExpr   *caseExpr = (CaseExpr *) node;
    1805        56105 :                 List       *adjust_jumps = NIL;
    1806        56105 :                 Datum      *caseval = NULL;
    1807        56105 :                 bool       *casenull = NULL;
    1808              :                 ListCell   *lc;
    1809              : 
    1810              :                 /*
    1811              :                  * If there's a test expression, we have to evaluate it and
    1812              :                  * save the value where the CaseTestExpr placeholders can find
    1813              :                  * it.
    1814              :                  */
    1815        56105 :                 if (caseExpr->arg != NULL)
    1816              :                 {
    1817              :                     /* Evaluate testexpr into caseval/casenull workspace */
    1818         2391 :                     caseval = palloc_object(Datum);
    1819         2391 :                     casenull = palloc_object(bool);
    1820              : 
    1821         2391 :                     ExecInitExprRec(caseExpr->arg, state,
    1822              :                                     caseval, casenull);
    1823              : 
    1824              :                     /*
    1825              :                      * Since value might be read multiple times, force to R/O
    1826              :                      * - but only if it could be an expanded datum.
    1827              :                      */
    1828         2391 :                     if (get_typlen(exprType((Node *) caseExpr->arg)) == -1)
    1829              :                     {
    1830              :                         /* change caseval in-place */
    1831           39 :                         scratch.opcode = EEOP_MAKE_READONLY;
    1832           39 :                         scratch.resvalue = caseval;
    1833           39 :                         scratch.resnull = casenull;
    1834           39 :                         scratch.d.make_readonly.value = caseval;
    1835           39 :                         scratch.d.make_readonly.isnull = casenull;
    1836           39 :                         ExprEvalPushStep(state, &scratch);
    1837              :                         /* restore normal settings of scratch fields */
    1838           39 :                         scratch.resvalue = resv;
    1839           39 :                         scratch.resnull = resnull;
    1840              :                     }
    1841              :                 }
    1842              : 
    1843              :                 /*
    1844              :                  * Prepare to evaluate each of the WHEN clauses in turn; as
    1845              :                  * soon as one is true we return the value of the
    1846              :                  * corresponding THEN clause.  If none are true then we return
    1847              :                  * the value of the ELSE clause, or NULL if there is none.
    1848              :                  */
    1849       161821 :                 foreach(lc, caseExpr->args)
    1850              :                 {
    1851       105716 :                     CaseWhen   *when = (CaseWhen *) lfirst(lc);
    1852              :                     Datum      *save_innermost_caseval;
    1853              :                     bool       *save_innermost_casenull;
    1854              :                     int         whenstep;
    1855              : 
    1856              :                     /*
    1857              :                      * Make testexpr result available to CaseTestExpr nodes
    1858              :                      * within the condition.  We must save and restore prior
    1859              :                      * setting of innermost_caseval fields, in case this node
    1860              :                      * is itself within a larger CASE.
    1861              :                      *
    1862              :                      * If there's no test expression, we don't actually need
    1863              :                      * to save and restore these fields; but it's less code to
    1864              :                      * just do so unconditionally.
    1865              :                      */
    1866       105716 :                     save_innermost_caseval = state->innermost_caseval;
    1867       105716 :                     save_innermost_casenull = state->innermost_casenull;
    1868       105716 :                     state->innermost_caseval = caseval;
    1869       105716 :                     state->innermost_casenull = casenull;
    1870              : 
    1871              :                     /* evaluate condition into CASE's result variables */
    1872       105716 :                     ExecInitExprRec(when->expr, state, resv, resnull);
    1873              : 
    1874       105716 :                     state->innermost_caseval = save_innermost_caseval;
    1875       105716 :                     state->innermost_casenull = save_innermost_casenull;
    1876              : 
    1877              :                     /* If WHEN result isn't true, jump to next CASE arm */
    1878       105716 :                     scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
    1879       105716 :                     scratch.d.jump.jumpdone = -1;   /* computed later */
    1880       105716 :                     ExprEvalPushStep(state, &scratch);
    1881       105716 :                     whenstep = state->steps_len - 1;
    1882              : 
    1883              :                     /*
    1884              :                      * If WHEN result is true, evaluate THEN result, storing
    1885              :                      * it into the CASE's result variables.
    1886              :                      */
    1887       105716 :                     ExecInitExprRec(when->result, state, resv, resnull);
    1888              : 
    1889              :                     /* Emit JUMP step to jump to end of CASE's code */
    1890       105716 :                     scratch.opcode = EEOP_JUMP;
    1891       105716 :                     scratch.d.jump.jumpdone = -1;   /* computed later */
    1892       105716 :                     ExprEvalPushStep(state, &scratch);
    1893              : 
    1894              :                     /*
    1895              :                      * Don't know address for that jump yet, compute once the
    1896              :                      * whole CASE expression is built.
    1897              :                      */
    1898       105716 :                     adjust_jumps = lappend_int(adjust_jumps,
    1899       105716 :                                                state->steps_len - 1);
    1900              : 
    1901              :                     /*
    1902              :                      * But we can set WHEN test's jump target now, to make it
    1903              :                      * jump to the next WHEN subexpression or the ELSE.
    1904              :                      */
    1905       105716 :                     state->steps[whenstep].d.jump.jumpdone = state->steps_len;
    1906              :                 }
    1907              : 
    1908              :                 /* transformCaseExpr always adds a default */
    1909              :                 Assert(caseExpr->defresult);
    1910              : 
    1911              :                 /* evaluate ELSE expr into CASE's result variables */
    1912        56105 :                 ExecInitExprRec(caseExpr->defresult, state,
    1913              :                                 resv, resnull);
    1914              : 
    1915              :                 /* adjust jump targets */
    1916       161821 :                 foreach(lc, adjust_jumps)
    1917              :                 {
    1918       105716 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    1919              : 
    1920              :                     Assert(as->opcode == EEOP_JUMP);
    1921              :                     Assert(as->d.jump.jumpdone == -1);
    1922       105716 :                     as->d.jump.jumpdone = state->steps_len;
    1923              :                 }
    1924              : 
    1925        56105 :                 break;
    1926              :             }
    1927              : 
    1928        13339 :         case T_CaseTestExpr:
    1929              :             {
    1930              :                 /*
    1931              :                  * Read from location identified by innermost_caseval.  Note
    1932              :                  * that innermost_caseval could be NULL, if this node isn't
    1933              :                  * actually within a CaseExpr, ArrayCoerceExpr, etc structure.
    1934              :                  * That can happen because some parts of the system abuse
    1935              :                  * CaseTestExpr to cause a read of a value externally supplied
    1936              :                  * in econtext->caseValue_datum.  We'll take care of that by
    1937              :                  * generating a specialized operation.
    1938              :                  */
    1939        13339 :                 if (state->innermost_caseval == NULL)
    1940          754 :                     scratch.opcode = EEOP_CASE_TESTVAL_EXT;
    1941              :                 else
    1942              :                 {
    1943        12585 :                     scratch.opcode = EEOP_CASE_TESTVAL;
    1944        12585 :                     scratch.d.casetest.value = state->innermost_caseval;
    1945        12585 :                     scratch.d.casetest.isnull = state->innermost_casenull;
    1946              :                 }
    1947        13339 :                 ExprEvalPushStep(state, &scratch);
    1948        13339 :                 break;
    1949              :             }
    1950              : 
    1951        15221 :         case T_ArrayExpr:
    1952              :             {
    1953        15221 :                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
    1954        15221 :                 int         nelems = list_length(arrayexpr->elements);
    1955              :                 ListCell   *lc;
    1956              :                 int         elemoff;
    1957              : 
    1958              :                 /*
    1959              :                  * Evaluate by computing each element, and then forming the
    1960              :                  * array.  Elements are computed into scratch arrays
    1961              :                  * associated with the ARRAYEXPR step.
    1962              :                  */
    1963        15221 :                 scratch.opcode = EEOP_ARRAYEXPR;
    1964        15221 :                 scratch.d.arrayexpr.elemvalues =
    1965        15221 :                     palloc_array(Datum, nelems);
    1966        15221 :                 scratch.d.arrayexpr.elemnulls =
    1967        15221 :                     palloc_array(bool, nelems);
    1968        15221 :                 scratch.d.arrayexpr.nelems = nelems;
    1969              : 
    1970              :                 /* fill remaining fields of step */
    1971        15221 :                 scratch.d.arrayexpr.multidims = arrayexpr->multidims;
    1972        15221 :                 scratch.d.arrayexpr.elemtype = arrayexpr->element_typeid;
    1973              : 
    1974              :                 /* do one-time catalog lookup for type info */
    1975        15221 :                 get_typlenbyvalalign(arrayexpr->element_typeid,
    1976              :                                      &scratch.d.arrayexpr.elemlength,
    1977              :                                      &scratch.d.arrayexpr.elembyval,
    1978              :                                      &scratch.d.arrayexpr.elemalign);
    1979              : 
    1980              :                 /* prepare to evaluate all arguments */
    1981        15221 :                 elemoff = 0;
    1982        56993 :                 foreach(lc, arrayexpr->elements)
    1983              :                 {
    1984        41772 :                     Expr       *e = (Expr *) lfirst(lc);
    1985              : 
    1986        41772 :                     ExecInitExprRec(e, state,
    1987        41772 :                                     &scratch.d.arrayexpr.elemvalues[elemoff],
    1988        41772 :                                     &scratch.d.arrayexpr.elemnulls[elemoff]);
    1989        41772 :                     elemoff++;
    1990              :                 }
    1991              : 
    1992              :                 /* and then collect all into an array */
    1993        15221 :                 ExprEvalPushStep(state, &scratch);
    1994        15221 :                 break;
    1995              :             }
    1996              : 
    1997         2885 :         case T_RowExpr:
    1998              :             {
    1999         2885 :                 RowExpr    *rowexpr = (RowExpr *) node;
    2000         2885 :                 int         nelems = list_length(rowexpr->args);
    2001              :                 TupleDesc   tupdesc;
    2002              :                 int         i;
    2003              :                 ListCell   *l;
    2004              : 
    2005              :                 /* Build tupdesc to describe result tuples */
    2006         2885 :                 if (rowexpr->row_typeid == RECORDOID)
    2007              :                 {
    2008              :                     /* generic record, use types of given expressions */
    2009         1510 :                     tupdesc = ExecTypeFromExprList(rowexpr->args);
    2010              :                     /* ... but adopt RowExpr's column aliases */
    2011         1510 :                     ExecTypeSetColNames(tupdesc, rowexpr->colnames);
    2012              :                     /* Bless the tupdesc so it can be looked up later */
    2013         1510 :                     BlessTupleDesc(tupdesc);
    2014              :                 }
    2015              :                 else
    2016              :                 {
    2017              :                     /* it's been cast to a named type, use that */
    2018         1375 :                     tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
    2019              :                 }
    2020              : 
    2021              :                 /*
    2022              :                  * In the named-type case, the tupdesc could have more columns
    2023              :                  * than are in the args list, since the type might have had
    2024              :                  * columns added since the ROW() was parsed.  We want those
    2025              :                  * extra columns to go to nulls, so we make sure that the
    2026              :                  * workspace arrays are large enough and then initialize any
    2027              :                  * extra columns to read as NULLs.
    2028              :                  */
    2029              :                 Assert(nelems <= tupdesc->natts);
    2030         2885 :                 nelems = Max(nelems, tupdesc->natts);
    2031              : 
    2032              :                 /*
    2033              :                  * Evaluate by first building datums for each field, and then
    2034              :                  * a final step forming the composite datum.
    2035              :                  */
    2036         2885 :                 scratch.opcode = EEOP_ROW;
    2037         2885 :                 scratch.d.row.tupdesc = tupdesc;
    2038              : 
    2039              :                 /* space for the individual field datums */
    2040         2885 :                 scratch.d.row.elemvalues =
    2041         2885 :                     palloc_array(Datum, nelems);
    2042         2885 :                 scratch.d.row.elemnulls =
    2043         2885 :                     palloc_array(bool, nelems);
    2044              :                 /* as explained above, make sure any extra columns are null */
    2045         2885 :                 memset(scratch.d.row.elemnulls, true, sizeof(bool) * nelems);
    2046              : 
    2047              :                 /* Set up evaluation, skipping any deleted columns */
    2048         2885 :                 i = 0;
    2049        10983 :                 foreach(l, rowexpr->args)
    2050              :                 {
    2051         8101 :                     Form_pg_attribute att = TupleDescAttr(tupdesc, i);
    2052         8101 :                     Expr       *e = (Expr *) lfirst(l);
    2053              : 
    2054         8101 :                     if (!att->attisdropped)
    2055              :                     {
    2056              :                         /*
    2057              :                          * Guard against ALTER COLUMN TYPE on rowtype since
    2058              :                          * the RowExpr was created.  XXX should we check
    2059              :                          * typmod too?  Not sure we can be sure it'll be the
    2060              :                          * same.
    2061              :                          */
    2062         8092 :                         if (exprType((Node *) e) != att->atttypid)
    2063            3 :                             ereport(ERROR,
    2064              :                                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    2065              :                                      errmsg("ROW() column has type %s instead of type %s",
    2066              :                                             format_type_be(exprType((Node *) e)),
    2067              :                                             format_type_be(att->atttypid))));
    2068              :                     }
    2069              :                     else
    2070              :                     {
    2071              :                         /*
    2072              :                          * Ignore original expression and insert a NULL. We
    2073              :                          * don't really care what type of NULL it is, so
    2074              :                          * always make an int4 NULL.
    2075              :                          */
    2076            9 :                         e = (Expr *) makeNullConst(INT4OID, -1, InvalidOid);
    2077              :                     }
    2078              : 
    2079              :                     /* Evaluate column expr into appropriate workspace slot */
    2080         8098 :                     ExecInitExprRec(e, state,
    2081         8098 :                                     &scratch.d.row.elemvalues[i],
    2082         8098 :                                     &scratch.d.row.elemnulls[i]);
    2083         8098 :                     i++;
    2084              :                 }
    2085              : 
    2086              :                 /* And finally build the row value */
    2087         2882 :                 ExprEvalPushStep(state, &scratch);
    2088         2882 :                 break;
    2089              :             }
    2090              : 
    2091          135 :         case T_RowCompareExpr:
    2092              :             {
    2093          135 :                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
    2094          135 :                 int         nopers = list_length(rcexpr->opnos);
    2095          135 :                 List       *adjust_jumps = NIL;
    2096              :                 ListCell   *l_left_expr,
    2097              :                            *l_right_expr,
    2098              :                            *l_opno,
    2099              :                            *l_opfamily,
    2100              :                            *l_inputcollid;
    2101              :                 ListCell   *lc;
    2102              : 
    2103              :                 /*
    2104              :                  * Iterate over each field, prepare comparisons.  To handle
    2105              :                  * NULL results, prepare jumps to after the expression.  If a
    2106              :                  * comparison yields a != 0 result, jump to the final step.
    2107              :                  */
    2108              :                 Assert(list_length(rcexpr->largs) == nopers);
    2109              :                 Assert(list_length(rcexpr->rargs) == nopers);
    2110              :                 Assert(list_length(rcexpr->opfamilies) == nopers);
    2111              :                 Assert(list_length(rcexpr->inputcollids) == nopers);
    2112              : 
    2113          432 :                 forfive(l_left_expr, rcexpr->largs,
    2114              :                         l_right_expr, rcexpr->rargs,
    2115              :                         l_opno, rcexpr->opnos,
    2116              :                         l_opfamily, rcexpr->opfamilies,
    2117              :                         l_inputcollid, rcexpr->inputcollids)
    2118              :                 {
    2119          297 :                     Expr       *left_expr = (Expr *) lfirst(l_left_expr);
    2120          297 :                     Expr       *right_expr = (Expr *) lfirst(l_right_expr);
    2121          297 :                     Oid         opno = lfirst_oid(l_opno);
    2122          297 :                     Oid         opfamily = lfirst_oid(l_opfamily);
    2123          297 :                     Oid         inputcollid = lfirst_oid(l_inputcollid);
    2124              :                     int         strategy;
    2125              :                     Oid         lefttype;
    2126              :                     Oid         righttype;
    2127              :                     Oid         proc;
    2128              :                     FmgrInfo   *finfo;
    2129              :                     FunctionCallInfo fcinfo;
    2130              : 
    2131          297 :                     get_op_opfamily_properties(opno, opfamily, false,
    2132              :                                                &strategy,
    2133              :                                                &lefttype,
    2134              :                                                &righttype);
    2135          297 :                     proc = get_opfamily_proc(opfamily,
    2136              :                                              lefttype,
    2137              :                                              righttype,
    2138              :                                              BTORDER_PROC);
    2139          297 :                     if (!OidIsValid(proc))
    2140            0 :                         elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
    2141              :                              BTORDER_PROC, lefttype, righttype, opfamily);
    2142              : 
    2143              :                     /* Set up the primary fmgr lookup information */
    2144          297 :                     finfo = palloc0_object(FmgrInfo);
    2145          297 :                     fcinfo = palloc0(SizeForFunctionCallInfo(2));
    2146          297 :                     fmgr_info(proc, finfo);
    2147          297 :                     fmgr_info_set_expr((Node *) node, finfo);
    2148          297 :                     InitFunctionCallInfoData(*fcinfo, finfo, 2,
    2149              :                                              inputcollid, NULL, NULL);
    2150              : 
    2151              :                     /*
    2152              :                      * If we enforced permissions checks on index support
    2153              :                      * functions, we'd need to make a check here.  But the
    2154              :                      * index support machinery doesn't do that, and thus
    2155              :                      * neither does this code.
    2156              :                      */
    2157              : 
    2158              :                     /* evaluate left and right args directly into fcinfo */
    2159          297 :                     ExecInitExprRec(left_expr, state,
    2160              :                                     &fcinfo->args[0].value, &fcinfo->args[0].isnull);
    2161          297 :                     ExecInitExprRec(right_expr, state,
    2162              :                                     &fcinfo->args[1].value, &fcinfo->args[1].isnull);
    2163              : 
    2164          297 :                     scratch.opcode = EEOP_ROWCOMPARE_STEP;
    2165          297 :                     scratch.d.rowcompare_step.finfo = finfo;
    2166          297 :                     scratch.d.rowcompare_step.fcinfo_data = fcinfo;
    2167          297 :                     scratch.d.rowcompare_step.fn_addr = finfo->fn_addr;
    2168              :                     /* jump targets filled below */
    2169          297 :                     scratch.d.rowcompare_step.jumpnull = -1;
    2170          297 :                     scratch.d.rowcompare_step.jumpdone = -1;
    2171              : 
    2172          297 :                     ExprEvalPushStep(state, &scratch);
    2173          297 :                     adjust_jumps = lappend_int(adjust_jumps,
    2174          297 :                                                state->steps_len - 1);
    2175              :                 }
    2176              : 
    2177              :                 /*
    2178              :                  * We could have a zero-column rowtype, in which case the rows
    2179              :                  * necessarily compare equal.
    2180              :                  */
    2181          135 :                 if (nopers == 0)
    2182              :                 {
    2183            0 :                     scratch.opcode = EEOP_CONST;
    2184            0 :                     scratch.d.constval.value = Int32GetDatum(0);
    2185            0 :                     scratch.d.constval.isnull = false;
    2186            0 :                     ExprEvalPushStep(state, &scratch);
    2187              :                 }
    2188              : 
    2189              :                 /* Finally, examine the last comparison result */
    2190          135 :                 scratch.opcode = EEOP_ROWCOMPARE_FINAL;
    2191          135 :                 scratch.d.rowcompare_final.cmptype = rcexpr->cmptype;
    2192          135 :                 ExprEvalPushStep(state, &scratch);
    2193              : 
    2194              :                 /* adjust jump targets */
    2195          432 :                 foreach(lc, adjust_jumps)
    2196              :                 {
    2197          297 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    2198              : 
    2199              :                     Assert(as->opcode == EEOP_ROWCOMPARE_STEP);
    2200              :                     Assert(as->d.rowcompare_step.jumpdone == -1);
    2201              :                     Assert(as->d.rowcompare_step.jumpnull == -1);
    2202              : 
    2203              :                     /* jump to comparison evaluation */
    2204          297 :                     as->d.rowcompare_step.jumpdone = state->steps_len - 1;
    2205              :                     /* jump to the following expression */
    2206          297 :                     as->d.rowcompare_step.jumpnull = state->steps_len;
    2207              :                 }
    2208              : 
    2209          135 :                 break;
    2210              :             }
    2211              : 
    2212         1910 :         case T_CoalesceExpr:
    2213              :             {
    2214         1910 :                 CoalesceExpr *coalesce = (CoalesceExpr *) node;
    2215         1910 :                 List       *adjust_jumps = NIL;
    2216              :                 ListCell   *lc;
    2217              : 
    2218              :                 /* We assume there's at least one arg */
    2219              :                 Assert(coalesce->args != NIL);
    2220              : 
    2221              :                 /*
    2222              :                  * Prepare evaluation of all coalesced arguments, after each
    2223              :                  * one push a step that short-circuits if not null.
    2224              :                  */
    2225         5736 :                 foreach(lc, coalesce->args)
    2226              :                 {
    2227         3826 :                     Expr       *e = (Expr *) lfirst(lc);
    2228              : 
    2229              :                     /* evaluate argument, directly into result datum */
    2230         3826 :                     ExecInitExprRec(e, state, resv, resnull);
    2231              : 
    2232              :                     /* if it's not null, skip to end of COALESCE expr */
    2233         3826 :                     scratch.opcode = EEOP_JUMP_IF_NOT_NULL;
    2234         3826 :                     scratch.d.jump.jumpdone = -1;   /* adjust later */
    2235         3826 :                     ExprEvalPushStep(state, &scratch);
    2236              : 
    2237         3826 :                     adjust_jumps = lappend_int(adjust_jumps,
    2238         3826 :                                                state->steps_len - 1);
    2239              :                 }
    2240              : 
    2241              :                 /*
    2242              :                  * No need to add a constant NULL return - we only can get to
    2243              :                  * the end of the expression if a NULL already is being
    2244              :                  * returned.
    2245              :                  */
    2246              : 
    2247              :                 /* adjust jump targets */
    2248         5736 :                 foreach(lc, adjust_jumps)
    2249              :                 {
    2250         3826 :                     ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    2251              : 
    2252              :                     Assert(as->opcode == EEOP_JUMP_IF_NOT_NULL);
    2253              :                     Assert(as->d.jump.jumpdone == -1);
    2254         3826 :                     as->d.jump.jumpdone = state->steps_len;
    2255              :                 }
    2256              : 
    2257         1910 :                 break;
    2258              :             }
    2259              : 
    2260         1232 :         case T_MinMaxExpr:
    2261              :             {
    2262         1232 :                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
    2263         1232 :                 int         nelems = list_length(minmaxexpr->args);
    2264              :                 TypeCacheEntry *typentry;
    2265              :                 FmgrInfo   *finfo;
    2266              :                 FunctionCallInfo fcinfo;
    2267              :                 ListCell   *lc;
    2268              :                 int         off;
    2269              : 
    2270              :                 /* Look up the btree comparison function for the datatype */
    2271         1232 :                 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
    2272              :                                              TYPECACHE_CMP_PROC);
    2273         1232 :                 if (!OidIsValid(typentry->cmp_proc))
    2274            0 :                     ereport(ERROR,
    2275              :                             (errcode(ERRCODE_UNDEFINED_FUNCTION),
    2276              :                              errmsg("could not identify a comparison function for type %s",
    2277              :                                     format_type_be(minmaxexpr->minmaxtype))));
    2278              : 
    2279              :                 /*
    2280              :                  * If we enforced permissions checks on index support
    2281              :                  * functions, we'd need to make a check here.  But the index
    2282              :                  * support machinery doesn't do that, and thus neither does
    2283              :                  * this code.
    2284              :                  */
    2285              : 
    2286              :                 /* Perform function lookup */
    2287         1232 :                 finfo = palloc0_object(FmgrInfo);
    2288         1232 :                 fcinfo = palloc0(SizeForFunctionCallInfo(2));
    2289         1232 :                 fmgr_info(typentry->cmp_proc, finfo);
    2290         1232 :                 fmgr_info_set_expr((Node *) node, finfo);
    2291         1232 :                 InitFunctionCallInfoData(*fcinfo, finfo, 2,
    2292              :                                          minmaxexpr->inputcollid, NULL, NULL);
    2293              : 
    2294         1232 :                 scratch.opcode = EEOP_MINMAX;
    2295              :                 /* allocate space to store arguments */
    2296         1232 :                 scratch.d.minmax.values = palloc_array(Datum, nelems);
    2297         1232 :                 scratch.d.minmax.nulls = palloc_array(bool, nelems);
    2298         1232 :                 scratch.d.minmax.nelems = nelems;
    2299              : 
    2300         1232 :                 scratch.d.minmax.op = minmaxexpr->op;
    2301         1232 :                 scratch.d.minmax.finfo = finfo;
    2302         1232 :                 scratch.d.minmax.fcinfo_data = fcinfo;
    2303              : 
    2304              :                 /* evaluate expressions into minmax->values/nulls */
    2305         1232 :                 off = 0;
    2306         3750 :                 foreach(lc, minmaxexpr->args)
    2307              :                 {
    2308         2518 :                     Expr       *e = (Expr *) lfirst(lc);
    2309              : 
    2310         2518 :                     ExecInitExprRec(e, state,
    2311         2518 :                                     &scratch.d.minmax.values[off],
    2312         2518 :                                     &scratch.d.minmax.nulls[off]);
    2313         2518 :                     off++;
    2314              :                 }
    2315              : 
    2316              :                 /* and push the final comparison */
    2317         1232 :                 ExprEvalPushStep(state, &scratch);
    2318         1232 :                 break;
    2319              :             }
    2320              : 
    2321         2815 :         case T_SQLValueFunction:
    2322              :             {
    2323         2815 :                 SQLValueFunction *svf = (SQLValueFunction *) node;
    2324              : 
    2325         2815 :                 scratch.opcode = EEOP_SQLVALUEFUNCTION;
    2326         2815 :                 scratch.d.sqlvaluefunction.svf = svf;
    2327              : 
    2328         2815 :                 ExprEvalPushStep(state, &scratch);
    2329         2815 :                 break;
    2330              :             }
    2331              : 
    2332          351 :         case T_XmlExpr:
    2333              :             {
    2334          351 :                 XmlExpr    *xexpr = (XmlExpr *) node;
    2335          351 :                 int         nnamed = list_length(xexpr->named_args);
    2336          351 :                 int         nargs = list_length(xexpr->args);
    2337              :                 int         off;
    2338              :                 ListCell   *arg;
    2339              : 
    2340          351 :                 scratch.opcode = EEOP_XMLEXPR;
    2341          351 :                 scratch.d.xmlexpr.xexpr = xexpr;
    2342              : 
    2343              :                 /* allocate space for storing all the arguments */
    2344          351 :                 if (nnamed)
    2345              :                 {
    2346           30 :                     scratch.d.xmlexpr.named_argvalue = palloc_array(Datum, nnamed);
    2347           30 :                     scratch.d.xmlexpr.named_argnull = palloc_array(bool, nnamed);
    2348              :                 }
    2349              :                 else
    2350              :                 {
    2351          321 :                     scratch.d.xmlexpr.named_argvalue = NULL;
    2352          321 :                     scratch.d.xmlexpr.named_argnull = NULL;
    2353              :                 }
    2354              : 
    2355          351 :                 if (nargs)
    2356              :                 {
    2357          309 :                     scratch.d.xmlexpr.argvalue = palloc_array(Datum, nargs);
    2358          309 :                     scratch.d.xmlexpr.argnull = palloc_array(bool, nargs);
    2359              :                 }
    2360              :                 else
    2361              :                 {
    2362           42 :                     scratch.d.xmlexpr.argvalue = NULL;
    2363           42 :                     scratch.d.xmlexpr.argnull = NULL;
    2364              :                 }
    2365              : 
    2366              :                 /* prepare argument execution */
    2367          351 :                 off = 0;
    2368          435 :                 foreach(arg, xexpr->named_args)
    2369              :                 {
    2370           84 :                     Expr       *e = (Expr *) lfirst(arg);
    2371              : 
    2372           84 :                     ExecInitExprRec(e, state,
    2373           84 :                                     &scratch.d.xmlexpr.named_argvalue[off],
    2374           84 :                                     &scratch.d.xmlexpr.named_argnull[off]);
    2375           84 :                     off++;
    2376              :                 }
    2377              : 
    2378          351 :                 off = 0;
    2379          819 :                 foreach(arg, xexpr->args)
    2380              :                 {
    2381          468 :                     Expr       *e = (Expr *) lfirst(arg);
    2382              : 
    2383          468 :                     ExecInitExprRec(e, state,
    2384          468 :                                     &scratch.d.xmlexpr.argvalue[off],
    2385          468 :                                     &scratch.d.xmlexpr.argnull[off]);
    2386          468 :                     off++;
    2387              :                 }
    2388              : 
    2389              :                 /* and evaluate the actual XML expression */
    2390          351 :                 ExprEvalPushStep(state, &scratch);
    2391          351 :                 break;
    2392              :             }
    2393              : 
    2394          114 :         case T_JsonValueExpr:
    2395              :             {
    2396          114 :                 JsonValueExpr *jve = (JsonValueExpr *) node;
    2397              : 
    2398              :                 Assert(jve->raw_expr != NULL);
    2399          114 :                 ExecInitExprRec(jve->raw_expr, state, resv, resnull);
    2400              :                 Assert(jve->formatted_expr != NULL);
    2401          114 :                 ExecInitExprRec(jve->formatted_expr, state, resv, resnull);
    2402          114 :                 break;
    2403              :             }
    2404              : 
    2405          683 :         case T_JsonConstructorExpr:
    2406              :             {
    2407          683 :                 JsonConstructorExpr *ctor = (JsonConstructorExpr *) node;
    2408          683 :                 List       *args = ctor->args;
    2409              :                 ListCell   *lc;
    2410          683 :                 int         nargs = list_length(args);
    2411          683 :                 int         argno = 0;
    2412              : 
    2413          683 :                 if (ctor->func)
    2414              :                 {
    2415          210 :                     ExecInitExprRec(ctor->func, state, resv, resnull);
    2416              :                 }
    2417          473 :                 else if ((ctor->type == JSCTOR_JSON_PARSE && !ctor->unique) ||
    2418          412 :                          ctor->type == JSCTOR_JSON_SERIALIZE)
    2419              :                 {
    2420              :                     /* Use the value of the first argument as result */
    2421          110 :                     ExecInitExprRec(linitial(args), state, resv, resnull);
    2422              :                 }
    2423              :                 else
    2424              :                 {
    2425              :                     JsonConstructorExprState *jcstate;
    2426              : 
    2427          363 :                     jcstate = palloc0_object(JsonConstructorExprState);
    2428              : 
    2429          363 :                     scratch.opcode = EEOP_JSON_CONSTRUCTOR;
    2430          363 :                     scratch.d.json_constructor.jcstate = jcstate;
    2431              : 
    2432          363 :                     jcstate->constructor = ctor;
    2433          363 :                     jcstate->arg_values = palloc_array(Datum, nargs);
    2434          363 :                     jcstate->arg_nulls = palloc_array(bool, nargs);
    2435          363 :                     jcstate->arg_types = palloc_array(Oid, nargs);
    2436          363 :                     jcstate->nargs = nargs;
    2437              : 
    2438         1139 :                     foreach(lc, args)
    2439              :                     {
    2440          776 :                         Expr       *arg = (Expr *) lfirst(lc);
    2441              : 
    2442          776 :                         jcstate->arg_types[argno] = exprType((Node *) arg);
    2443              : 
    2444          776 :                         if (IsA(arg, Const))
    2445              :                         {
    2446              :                             /* Don't evaluate const arguments every round */
    2447          707 :                             Const      *con = (Const *) arg;
    2448              : 
    2449          707 :                             jcstate->arg_values[argno] = con->constvalue;
    2450          707 :                             jcstate->arg_nulls[argno] = con->constisnull;
    2451              :                         }
    2452              :                         else
    2453              :                         {
    2454           69 :                             ExecInitExprRec(arg, state,
    2455           69 :                                             &jcstate->arg_values[argno],
    2456           69 :                                             &jcstate->arg_nulls[argno]);
    2457              :                         }
    2458          776 :                         argno++;
    2459              :                     }
    2460              : 
    2461              :                     /* prepare type cache for datum_to_json[b]() */
    2462          363 :                     if (ctor->type == JSCTOR_JSON_SCALAR)
    2463              :                     {
    2464           56 :                         bool        is_jsonb =
    2465           56 :                             ctor->returning->format->format_type == JS_FORMAT_JSONB;
    2466              : 
    2467           56 :                         jcstate->arg_type_cache =
    2468           56 :                             palloc(sizeof(*jcstate->arg_type_cache) * nargs);
    2469              : 
    2470          112 :                         for (int i = 0; i < nargs; i++)
    2471              :                         {
    2472              :                             JsonTypeCategory category;
    2473              :                             Oid         outfuncid;
    2474           56 :                             Oid         typid = jcstate->arg_types[i];
    2475              : 
    2476           56 :                             json_categorize_type(typid, is_jsonb,
    2477              :                                                  &category, &outfuncid);
    2478              : 
    2479           56 :                             jcstate->arg_type_cache[i].outfuncid = outfuncid;
    2480           56 :                             jcstate->arg_type_cache[i].category = (int) category;
    2481              :                         }
    2482              :                     }
    2483              : 
    2484          363 :                     ExprEvalPushStep(state, &scratch);
    2485              :                 }
    2486              : 
    2487          683 :                 if (ctor->coercion)
    2488              :                 {
    2489          187 :                     Datum      *innermost_caseval = state->innermost_caseval;
    2490          187 :                     bool       *innermost_isnull = state->innermost_casenull;
    2491              : 
    2492          187 :                     state->innermost_caseval = resv;
    2493          187 :                     state->innermost_casenull = resnull;
    2494              : 
    2495          187 :                     ExecInitExprRec(ctor->coercion, state, resv, resnull);
    2496              : 
    2497          187 :                     state->innermost_caseval = innermost_caseval;
    2498          187 :                     state->innermost_casenull = innermost_isnull;
    2499              :                 }
    2500              :             }
    2501          683 :             break;
    2502              : 
    2503          175 :         case T_JsonIsPredicate:
    2504              :             {
    2505          175 :                 JsonIsPredicate *pred = (JsonIsPredicate *) node;
    2506              : 
    2507          175 :                 ExecInitExprRec((Expr *) pred->expr, state, resv, resnull);
    2508              : 
    2509          175 :                 scratch.opcode = EEOP_IS_JSON;
    2510          175 :                 scratch.d.is_json.pred = pred;
    2511              : 
    2512          175 :                 ExprEvalPushStep(state, &scratch);
    2513          175 :                 break;
    2514              :             }
    2515              : 
    2516         1358 :         case T_JsonExpr:
    2517              :             {
    2518         1358 :                 JsonExpr   *jsexpr = castNode(JsonExpr, node);
    2519              : 
    2520              :                 /*
    2521              :                  * No need to initialize a full JsonExprState For
    2522              :                  * JSON_TABLE(), because the upstream caller tfuncFetchRows()
    2523              :                  * is only interested in the value of formatted_expr.
    2524              :                  */
    2525         1358 :                 if (jsexpr->op == JSON_TABLE_OP)
    2526          202 :                     ExecInitExprRec((Expr *) jsexpr->formatted_expr, state,
    2527              :                                     resv, resnull);
    2528              :                 else
    2529         1156 :                     ExecInitJsonExpr(jsexpr, state, resv, resnull, &scratch);
    2530         1358 :                 break;
    2531              :             }
    2532              : 
    2533        15395 :         case T_NullTest:
    2534              :             {
    2535        15395 :                 NullTest   *ntest = (NullTest *) node;
    2536              : 
    2537        15395 :                 if (ntest->nulltesttype == IS_NULL)
    2538              :                 {
    2539         4010 :                     if (ntest->argisrow)
    2540          114 :                         scratch.opcode = EEOP_NULLTEST_ROWISNULL;
    2541              :                     else
    2542         3896 :                         scratch.opcode = EEOP_NULLTEST_ISNULL;
    2543              :                 }
    2544        11385 :                 else if (ntest->nulltesttype == IS_NOT_NULL)
    2545              :                 {
    2546        11385 :                     if (ntest->argisrow)
    2547          122 :                         scratch.opcode = EEOP_NULLTEST_ROWISNOTNULL;
    2548              :                     else
    2549        11263 :                         scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
    2550              :                 }
    2551              :                 else
    2552              :                 {
    2553            0 :                     elog(ERROR, "unrecognized nulltesttype: %d",
    2554              :                          (int) ntest->nulltesttype);
    2555              :                 }
    2556              :                 /* initialize cache in case it's a row test */
    2557        15395 :                 scratch.d.nulltest_row.rowcache.cacheptr = NULL;
    2558              : 
    2559              :                 /* first evaluate argument into result variable */
    2560        15395 :                 ExecInitExprRec(ntest->arg, state,
    2561              :                                 resv, resnull);
    2562              : 
    2563              :                 /* then push the test of that argument */
    2564        15395 :                 ExprEvalPushStep(state, &scratch);
    2565        15395 :                 break;
    2566              :             }
    2567              : 
    2568          813 :         case T_BooleanTest:
    2569              :             {
    2570          813 :                 BooleanTest *btest = (BooleanTest *) node;
    2571              : 
    2572              :                 /*
    2573              :                  * Evaluate argument, directly into result datum.  That's ok,
    2574              :                  * because resv/resnull is definitely not used anywhere else,
    2575              :                  * and will get overwritten by the below EEOP_BOOLTEST_IS_*
    2576              :                  * step.
    2577              :                  */
    2578          813 :                 ExecInitExprRec(btest->arg, state, resv, resnull);
    2579              : 
    2580          813 :                 switch (btest->booltesttype)
    2581              :                 {
    2582          319 :                     case IS_TRUE:
    2583          319 :                         scratch.opcode = EEOP_BOOLTEST_IS_TRUE;
    2584          319 :                         break;
    2585          198 :                     case IS_NOT_TRUE:
    2586          198 :                         scratch.opcode = EEOP_BOOLTEST_IS_NOT_TRUE;
    2587          198 :                         break;
    2588          119 :                     case IS_FALSE:
    2589          119 :                         scratch.opcode = EEOP_BOOLTEST_IS_FALSE;
    2590          119 :                         break;
    2591           85 :                     case IS_NOT_FALSE:
    2592           85 :                         scratch.opcode = EEOP_BOOLTEST_IS_NOT_FALSE;
    2593           85 :                         break;
    2594           35 :                     case IS_UNKNOWN:
    2595              :                         /* Same as scalar IS NULL test */
    2596           35 :                         scratch.opcode = EEOP_NULLTEST_ISNULL;
    2597           35 :                         break;
    2598           57 :                     case IS_NOT_UNKNOWN:
    2599              :                         /* Same as scalar IS NOT NULL test */
    2600           57 :                         scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
    2601           57 :                         break;
    2602            0 :                     default:
    2603            0 :                         elog(ERROR, "unrecognized booltesttype: %d",
    2604              :                              (int) btest->booltesttype);
    2605              :                 }
    2606              : 
    2607          813 :                 ExprEvalPushStep(state, &scratch);
    2608          813 :                 break;
    2609              :             }
    2610              : 
    2611         4961 :         case T_CoerceToDomain:
    2612              :             {
    2613         4961 :                 CoerceToDomain *ctest = (CoerceToDomain *) node;
    2614              : 
    2615         4961 :                 ExecInitCoerceToDomain(&scratch, ctest, state,
    2616              :                                        resv, resnull);
    2617         4961 :                 break;
    2618              :             }
    2619              : 
    2620         6959 :         case T_CoerceToDomainValue:
    2621              :             {
    2622              :                 /*
    2623              :                  * Read from location identified by innermost_domainval.  Note
    2624              :                  * that innermost_domainval could be NULL, if we're compiling
    2625              :                  * a standalone domain check rather than one embedded in a
    2626              :                  * larger expression.  In that case we must read from
    2627              :                  * econtext->domainValue_datum.  We'll take care of that by
    2628              :                  * generating a specialized operation.
    2629              :                  */
    2630         6959 :                 if (state->innermost_domainval == NULL)
    2631         1409 :                     scratch.opcode = EEOP_DOMAIN_TESTVAL_EXT;
    2632              :                 else
    2633              :                 {
    2634         5550 :                     scratch.opcode = EEOP_DOMAIN_TESTVAL;
    2635              :                     /* we share instruction union variant with case testval */
    2636         5550 :                     scratch.d.casetest.value = state->innermost_domainval;
    2637         5550 :                     scratch.d.casetest.isnull = state->innermost_domainnull;
    2638              :                 }
    2639         6959 :                 ExprEvalPushStep(state, &scratch);
    2640         6959 :                 break;
    2641              :             }
    2642              : 
    2643            1 :         case T_CurrentOfExpr:
    2644              :             {
    2645            1 :                 scratch.opcode = EEOP_CURRENTOFEXPR;
    2646            1 :                 ExprEvalPushStep(state, &scratch);
    2647            1 :                 break;
    2648              :             }
    2649              : 
    2650          270 :         case T_NextValueExpr:
    2651              :             {
    2652          270 :                 NextValueExpr *nve = (NextValueExpr *) node;
    2653              : 
    2654          270 :                 scratch.opcode = EEOP_NEXTVALUEEXPR;
    2655          270 :                 scratch.d.nextvalueexpr.seqid = nve->seqid;
    2656          270 :                 scratch.d.nextvalueexpr.seqtypid = nve->typeId;
    2657              : 
    2658          270 :                 ExprEvalPushStep(state, &scratch);
    2659          270 :                 break;
    2660              :             }
    2661              : 
    2662          228 :         case T_ReturningExpr:
    2663              :             {
    2664          228 :                 ReturningExpr *rexpr = (ReturningExpr *) node;
    2665              :                 int         retstep;
    2666              : 
    2667              :                 /* Skip expression evaluation if OLD/NEW row doesn't exist */
    2668          228 :                 scratch.opcode = EEOP_RETURNINGEXPR;
    2669          228 :                 scratch.d.returningexpr.nullflag = rexpr->retold ?
    2670              :                     EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL;
    2671          228 :                 scratch.d.returningexpr.jumpdone = -1;  /* set below */
    2672          228 :                 ExprEvalPushStep(state, &scratch);
    2673          228 :                 retstep = state->steps_len - 1;
    2674              : 
    2675              :                 /* Steps to evaluate expression to return */
    2676          228 :                 ExecInitExprRec(rexpr->retexpr, state, resv, resnull);
    2677              : 
    2678              :                 /* Jump target used if OLD/NEW row doesn't exist */
    2679          228 :                 state->steps[retstep].d.returningexpr.jumpdone = state->steps_len;
    2680              : 
    2681              :                 /* Update ExprState flags */
    2682          228 :                 if (rexpr->retold)
    2683          114 :                     state->flags |= EEO_FLAG_HAS_OLD;
    2684              :                 else
    2685          114 :                     state->flags |= EEO_FLAG_HAS_NEW;
    2686              : 
    2687          228 :                 break;
    2688              :             }
    2689              : 
    2690            0 :         default:
    2691            0 :             elog(ERROR, "unrecognized node type: %d",
    2692              :                  (int) nodeTag(node));
    2693              :             break;
    2694              :     }
    2695      5003868 : }
    2696              : 
    2697              : /*
    2698              :  * Add another expression evaluation step to ExprState->steps.
    2699              :  *
    2700              :  * Note that this potentially re-allocates es->steps, therefore no pointer
    2701              :  * into that array may be used while the expression is still being built.
    2702              :  */
    2703              : void
    2704     11342141 : ExprEvalPushStep(ExprState *es, const ExprEvalStep *s)
    2705              : {
    2706     11342141 :     if (es->steps_alloc == 0)
    2707              :     {
    2708      2226041 :         es->steps_alloc = 16;
    2709      2226041 :         es->steps = palloc_array(ExprEvalStep, es->steps_alloc);
    2710              :     }
    2711      9116100 :     else if (es->steps_alloc == es->steps_len)
    2712              :     {
    2713        51907 :         es->steps_alloc *= 2;
    2714        51907 :         es->steps = repalloc(es->steps,
    2715        51907 :                              sizeof(ExprEvalStep) * es->steps_alloc);
    2716              :     }
    2717              : 
    2718     11342141 :     memcpy(&es->steps[es->steps_len++], s, sizeof(ExprEvalStep));
    2719     11342141 : }
    2720              : 
    2721              : /*
    2722              :  * Perform setup necessary for the evaluation of a function-like expression,
    2723              :  * appending argument evaluation steps to the steps list in *state, and
    2724              :  * setting up *scratch so it is ready to be pushed.
    2725              :  *
    2726              :  * *scratch is not pushed here, so that callers may override the opcode,
    2727              :  * which is useful for function-like cases like DISTINCT.
    2728              :  */
    2729              : static void
    2730      1196213 : ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args, Oid funcid,
    2731              :              Oid inputcollid, ExprState *state)
    2732              : {
    2733      1196213 :     int         nargs = list_length(args);
    2734              :     AclResult   aclresult;
    2735              :     FmgrInfo   *flinfo;
    2736              :     FunctionCallInfo fcinfo;
    2737              :     int         argno;
    2738              :     ListCell   *lc;
    2739              : 
    2740              :     /* Check permission to call function */
    2741      1196213 :     aclresult = object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE);
    2742      1196213 :     if (aclresult != ACLCHECK_OK)
    2743           43 :         aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(funcid));
    2744      1196170 :     InvokeFunctionExecuteHook(funcid);
    2745              : 
    2746              :     /*
    2747              :      * Safety check on nargs.  Under normal circumstances this should never
    2748              :      * fail, as parser should check sooner.  But possibly it might fail if
    2749              :      * server has been compiled with FUNC_MAX_ARGS smaller than some functions
    2750              :      * declared in pg_proc?
    2751              :      */
    2752      1196170 :     if (nargs > FUNC_MAX_ARGS)
    2753            0 :         ereport(ERROR,
    2754              :                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
    2755              :                  errmsg_plural("cannot pass more than %d argument to a function",
    2756              :                                "cannot pass more than %d arguments to a function",
    2757              :                                FUNC_MAX_ARGS,
    2758              :                                FUNC_MAX_ARGS)));
    2759              : 
    2760              :     /* Allocate function lookup data and parameter workspace for this call */
    2761      1196170 :     scratch->d.func.finfo = palloc0_object(FmgrInfo);
    2762      1196170 :     scratch->d.func.fcinfo_data = palloc0(SizeForFunctionCallInfo(nargs));
    2763      1196170 :     flinfo = scratch->d.func.finfo;
    2764      1196170 :     fcinfo = scratch->d.func.fcinfo_data;
    2765              : 
    2766              :     /* Set up the primary fmgr lookup information */
    2767      1196170 :     fmgr_info(funcid, flinfo);
    2768      1196170 :     fmgr_info_set_expr((Node *) node, flinfo);
    2769              : 
    2770              :     /* Initialize function call parameter structure too */
    2771      1196170 :     InitFunctionCallInfoData(*fcinfo, flinfo,
    2772              :                              nargs, inputcollid, NULL, NULL);
    2773              : 
    2774              :     /* Keep extra copies of this info to save an indirection at runtime */
    2775      1196170 :     scratch->d.func.fn_addr = flinfo->fn_addr;
    2776      1196170 :     scratch->d.func.nargs = nargs;
    2777              : 
    2778              :     /* We only support non-set functions here */
    2779      1196170 :     if (flinfo->fn_retset)
    2780            0 :         ereport(ERROR,
    2781              :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2782              :                  errmsg("set-valued function called in context that cannot accept a set"),
    2783              :                  state->parent ?
    2784              :                  executor_errposition(state->parent->state,
    2785              :                                       exprLocation((Node *) node)) : 0));
    2786              : 
    2787              :     /* Build code to evaluate arguments directly into the fcinfo struct */
    2788      1196170 :     argno = 0;
    2789      3377693 :     foreach(lc, args)
    2790              :     {
    2791      2181523 :         Expr       *arg = (Expr *) lfirst(lc);
    2792              : 
    2793      2181523 :         if (IsA(arg, Const))
    2794              :         {
    2795              :             /*
    2796              :              * Don't evaluate const arguments every round; especially
    2797              :              * interesting for constants in comparisons.
    2798              :              */
    2799       552018 :             Const      *con = (Const *) arg;
    2800              : 
    2801       552018 :             fcinfo->args[argno].value = con->constvalue;
    2802       552018 :             fcinfo->args[argno].isnull = con->constisnull;
    2803              :         }
    2804              :         else
    2805              :         {
    2806      1629505 :             ExecInitExprRec(arg, state,
    2807              :                             &fcinfo->args[argno].value,
    2808              :                             &fcinfo->args[argno].isnull);
    2809              :         }
    2810      2181523 :         argno++;
    2811              :     }
    2812              : 
    2813              :     /* Insert appropriate opcode depending on strictness and stats level */
    2814      1196170 :     if (pgstat_track_functions <= flinfo->fn_stats)
    2815              :     {
    2816      1196063 :         if (flinfo->fn_strict && nargs > 0)
    2817              :         {
    2818              :             /* Choose nargs optimized implementation if available. */
    2819      1115545 :             if (nargs == 1)
    2820       140079 :                 scratch->opcode = EEOP_FUNCEXPR_STRICT_1;
    2821       975466 :             else if (nargs == 2)
    2822       956780 :                 scratch->opcode = EEOP_FUNCEXPR_STRICT_2;
    2823              :             else
    2824        18686 :                 scratch->opcode = EEOP_FUNCEXPR_STRICT;
    2825              :         }
    2826              :         else
    2827        80518 :             scratch->opcode = EEOP_FUNCEXPR;
    2828              :     }
    2829              :     else
    2830              :     {
    2831          107 :         if (flinfo->fn_strict && nargs > 0)
    2832            3 :             scratch->opcode = EEOP_FUNCEXPR_STRICT_FUSAGE;
    2833              :         else
    2834          104 :             scratch->opcode = EEOP_FUNCEXPR_FUSAGE;
    2835              :     }
    2836      1196170 : }
    2837              : 
    2838              : /*
    2839              :  * Append the steps necessary for the evaluation of a SubPlan node to
    2840              :  * ExprState->steps.
    2841              :  *
    2842              :  * subplan - SubPlan expression to evaluate
    2843              :  * state - ExprState to whose ->steps to append the necessary operations
    2844              :  * resv / resnull - where to store the result of the node into
    2845              :  */
    2846              : static void
    2847        16233 : ExecInitSubPlanExpr(SubPlan *subplan,
    2848              :                     ExprState *state,
    2849              :                     Datum *resv, bool *resnull)
    2850              : {
    2851        16233 :     ExprEvalStep scratch = {0};
    2852              :     SubPlanState *sstate;
    2853              :     ListCell   *pvar;
    2854              :     ListCell   *l;
    2855              : 
    2856        16233 :     if (!state->parent)
    2857            0 :         elog(ERROR, "SubPlan found with no parent plan");
    2858              : 
    2859              :     /*
    2860              :      * Generate steps to evaluate input arguments for the subplan.
    2861              :      *
    2862              :      * We evaluate the argument expressions into resv/resnull, and then use
    2863              :      * PARAM_SET to update the parameter. We do that, instead of evaluating
    2864              :      * directly into the param, to avoid depending on the pointer value
    2865              :      * remaining stable / being included in the generated expression. It's ok
    2866              :      * to use resv/resnull for multiple params, as each parameter evaluation
    2867              :      * is immediately followed by an EEOP_PARAM_SET (and thus are saved before
    2868              :      * they could be overwritten again).
    2869              :      *
    2870              :      * Any calculation we have to do can be done in the parent econtext, since
    2871              :      * the Param values don't need to have per-query lifetime.
    2872              :      */
    2873              :     Assert(list_length(subplan->parParam) == list_length(subplan->args));
    2874        40199 :     forboth(l, subplan->parParam, pvar, subplan->args)
    2875              :     {
    2876        23966 :         int         paramid = lfirst_int(l);
    2877        23966 :         Expr       *arg = (Expr *) lfirst(pvar);
    2878              : 
    2879        23966 :         ExecInitExprRec(arg, state, resv, resnull);
    2880              : 
    2881        23966 :         scratch.opcode = EEOP_PARAM_SET;
    2882        23966 :         scratch.resvalue = resv;
    2883        23966 :         scratch.resnull = resnull;
    2884        23966 :         scratch.d.param.paramid = paramid;
    2885              :         /* paramtype's not actually used, but we might as well fill it */
    2886        23966 :         scratch.d.param.paramtype = exprType((Node *) arg);
    2887        23966 :         ExprEvalPushStep(state, &scratch);
    2888              :     }
    2889              : 
    2890        16233 :     sstate = ExecInitSubPlan(subplan, state->parent);
    2891              : 
    2892              :     /* add SubPlanState nodes to state->parent->subPlan */
    2893        16233 :     state->parent->subPlan = lappend(state->parent->subPlan,
    2894              :                                      sstate);
    2895              : 
    2896        16233 :     scratch.opcode = EEOP_SUBPLAN;
    2897        16233 :     scratch.resvalue = resv;
    2898        16233 :     scratch.resnull = resnull;
    2899        16233 :     scratch.d.subplan.sstate = sstate;
    2900              : 
    2901        16233 :     ExprEvalPushStep(state, &scratch);
    2902        16233 : }
    2903              : 
    2904              : /*
    2905              :  * Add expression steps performing setup that's needed before any of the
    2906              :  * main execution of the expression.
    2907              :  */
    2908              : static void
    2909      2170271 : ExecCreateExprSetupSteps(ExprState *state, Node *node)
    2910              : {
    2911      2170271 :     ExprSetupInfo info = {0, 0, 0, 0, 0, NIL};
    2912              : 
    2913              :     /* Prescan to find out what we need. */
    2914      2170271 :     expr_setup_walker(node, &info);
    2915              : 
    2916              :     /* And generate those steps. */
    2917      2170268 :     ExecPushExprSetupSteps(state, &info);
    2918      2170268 : }
    2919              : 
    2920              : /*
    2921              :  * Add steps performing expression setup as indicated by "info".
    2922              :  * This is useful when building an ExprState covering more than one expression.
    2923              :  */
    2924              : static void
    2925      2206640 : ExecPushExprSetupSteps(ExprState *state, ExprSetupInfo *info)
    2926              : {
    2927      2206640 :     ExprEvalStep scratch = {0};
    2928              :     ListCell   *lc;
    2929              : 
    2930      2206640 :     scratch.resvalue = NULL;
    2931      2206640 :     scratch.resnull = NULL;
    2932              : 
    2933              :     /*
    2934              :      * Add steps deforming the ExprState's inner/outer/scan/old/new slots as
    2935              :      * much as required by any Vars appearing in the expression.
    2936              :      */
    2937      2206640 :     if (info->last_inner > 0)
    2938              :     {
    2939       108815 :         scratch.opcode = EEOP_INNER_FETCHSOME;
    2940       108815 :         scratch.d.fetch.last_var = info->last_inner;
    2941       108815 :         scratch.d.fetch.fixed = false;
    2942       108815 :         scratch.d.fetch.kind = NULL;
    2943       108815 :         scratch.d.fetch.known_desc = NULL;
    2944       108815 :         if (ExecComputeSlotInfo(state, &scratch))
    2945        98041 :             ExprEvalPushStep(state, &scratch);
    2946              :     }
    2947      2206640 :     if (info->last_outer > 0)
    2948              :     {
    2949       200973 :         scratch.opcode = EEOP_OUTER_FETCHSOME;
    2950       200973 :         scratch.d.fetch.last_var = info->last_outer;
    2951       200973 :         scratch.d.fetch.fixed = false;
    2952       200973 :         scratch.d.fetch.kind = NULL;
    2953       200973 :         scratch.d.fetch.known_desc = NULL;
    2954       200973 :         if (ExecComputeSlotInfo(state, &scratch))
    2955       110919 :             ExprEvalPushStep(state, &scratch);
    2956              :     }
    2957      2206640 :     if (info->last_scan > 0)
    2958              :     {
    2959       750945 :         scratch.opcode = EEOP_SCAN_FETCHSOME;
    2960       750945 :         scratch.d.fetch.last_var = info->last_scan;
    2961       750945 :         scratch.d.fetch.fixed = false;
    2962       750945 :         scratch.d.fetch.kind = NULL;
    2963       750945 :         scratch.d.fetch.known_desc = NULL;
    2964       750945 :         if (ExecComputeSlotInfo(state, &scratch))
    2965       726794 :             ExprEvalPushStep(state, &scratch);
    2966              :     }
    2967      2206640 :     if (info->last_old > 0)
    2968              :     {
    2969          182 :         scratch.opcode = EEOP_OLD_FETCHSOME;
    2970          182 :         scratch.d.fetch.last_var = info->last_old;
    2971          182 :         scratch.d.fetch.fixed = false;
    2972          182 :         scratch.d.fetch.kind = NULL;
    2973          182 :         scratch.d.fetch.known_desc = NULL;
    2974          182 :         if (ExecComputeSlotInfo(state, &scratch))
    2975          182 :             ExprEvalPushStep(state, &scratch);
    2976              :     }
    2977      2206640 :     if (info->last_new > 0)
    2978              :     {
    2979          183 :         scratch.opcode = EEOP_NEW_FETCHSOME;
    2980          183 :         scratch.d.fetch.last_var = info->last_new;
    2981          183 :         scratch.d.fetch.fixed = false;
    2982          183 :         scratch.d.fetch.kind = NULL;
    2983          183 :         scratch.d.fetch.known_desc = NULL;
    2984          183 :         if (ExecComputeSlotInfo(state, &scratch))
    2985          183 :             ExprEvalPushStep(state, &scratch);
    2986              :     }
    2987              : 
    2988              :     /*
    2989              :      * Add steps to execute any MULTIEXPR SubPlans appearing in the
    2990              :      * expression.  We need to evaluate these before any of the Params
    2991              :      * referencing their outputs are used, but after we've prepared for any
    2992              :      * Var references they may contain.  (There cannot be cross-references
    2993              :      * between MULTIEXPR SubPlans, so we needn't worry about their order.)
    2994              :      */
    2995      2206703 :     foreach(lc, info->multiexpr_subplans)
    2996              :     {
    2997           63 :         SubPlan    *subplan = (SubPlan *) lfirst(lc);
    2998              : 
    2999              :         Assert(subplan->subLinkType == MULTIEXPR_SUBLINK);
    3000              : 
    3001              :         /* The result can be ignored, but we better put it somewhere */
    3002           63 :         ExecInitSubPlanExpr(subplan, state,
    3003              :                             &state->resvalue, &state->resnull);
    3004              :     }
    3005      2206640 : }
    3006              : 
    3007              : /*
    3008              :  * expr_setup_walker: expression walker for ExecCreateExprSetupSteps
    3009              :  */
    3010              : static bool
    3011     10048396 : expr_setup_walker(Node *node, ExprSetupInfo *info)
    3012              : {
    3013     10048396 :     if (node == NULL)
    3014       236386 :         return false;
    3015      9812010 :     if (IsA(node, Var))
    3016              :     {
    3017      2269276 :         Var        *variable = (Var *) node;
    3018      2269276 :         AttrNumber  attnum = variable->varattno;
    3019              : 
    3020      2269276 :         switch (variable->varno)
    3021              :         {
    3022       221634 :             case INNER_VAR:
    3023       221634 :                 info->last_inner = Max(info->last_inner, attnum);
    3024       221634 :                 break;
    3025              : 
    3026       498599 :             case OUTER_VAR:
    3027       498599 :                 info->last_outer = Max(info->last_outer, attnum);
    3028       498599 :                 break;
    3029              : 
    3030              :                 /* INDEX_VAR is handled by default case */
    3031              : 
    3032      1549043 :             default:
    3033      1549043 :                 switch (variable->varreturningtype)
    3034              :                 {
    3035      1547394 :                     case VAR_RETURNING_DEFAULT:
    3036      1547394 :                         info->last_scan = Max(info->last_scan, attnum);
    3037      1547394 :                         break;
    3038          824 :                     case VAR_RETURNING_OLD:
    3039          824 :                         info->last_old = Max(info->last_old, attnum);
    3040          824 :                         break;
    3041          825 :                     case VAR_RETURNING_NEW:
    3042          825 :                         info->last_new = Max(info->last_new, attnum);
    3043          825 :                         break;
    3044              :                 }
    3045      1549043 :                 break;
    3046              :         }
    3047      2269276 :         return false;
    3048              :     }
    3049              : 
    3050              :     /* Collect all MULTIEXPR SubPlans, too */
    3051      7542734 :     if (IsA(node, SubPlan))
    3052              :     {
    3053        16233 :         SubPlan    *subplan = (SubPlan *) node;
    3054              : 
    3055        16233 :         if (subplan->subLinkType == MULTIEXPR_SUBLINK)
    3056           63 :             info->multiexpr_subplans = lappend(info->multiexpr_subplans,
    3057              :                                                subplan);
    3058              :     }
    3059              : 
    3060              :     /*
    3061              :      * Don't examine the arguments or filters of Aggrefs or WindowFuncs,
    3062              :      * because those do not represent expressions to be evaluated within the
    3063              :      * calling expression's econtext.  GroupingFunc arguments are never
    3064              :      * evaluated at all.
    3065              :      */
    3066      7542734 :     if (IsA(node, Aggref))
    3067        31013 :         return false;
    3068      7511721 :     if (IsA(node, WindowFunc))
    3069         1854 :         return false;
    3070      7509867 :     if (IsA(node, GroupingFunc))
    3071          185 :         return false;
    3072      7509682 :     return expression_tree_walker(node, expr_setup_walker, info);
    3073              : }
    3074              : 
    3075              : /*
    3076              :  * Compute additional information for EEOP_*_FETCHSOME ops.
    3077              :  *
    3078              :  * The goal is to determine whether a slot is 'fixed', that is, every
    3079              :  * evaluation of the expression will have the same type of slot, with an
    3080              :  * equivalent descriptor.
    3081              :  *
    3082              :  * EEOP_OLD_FETCHSOME and EEOP_NEW_FETCHSOME are used to process RETURNING, if
    3083              :  * OLD/NEW columns are referred to explicitly.  In both cases, the tuple
    3084              :  * descriptor comes from the parent scan node, so we treat them the same as
    3085              :  * EEOP_SCAN_FETCHSOME.
    3086              :  *
    3087              :  * Returns true if the deforming step is required, false otherwise.
    3088              :  */
    3089              : static bool
    3090      1089180 : ExecComputeSlotInfo(ExprState *state, ExprEvalStep *op)
    3091              : {
    3092      1089180 :     PlanState  *parent = state->parent;
    3093      1089180 :     TupleDesc   desc = NULL;
    3094      1089180 :     const TupleTableSlotOps *tts_ops = NULL;
    3095      1089180 :     bool        isfixed = false;
    3096      1089180 :     ExprEvalOp  opcode = op->opcode;
    3097              : 
    3098              :     Assert(opcode == EEOP_INNER_FETCHSOME ||
    3099              :            opcode == EEOP_OUTER_FETCHSOME ||
    3100              :            opcode == EEOP_SCAN_FETCHSOME ||
    3101              :            opcode == EEOP_OLD_FETCHSOME ||
    3102              :            opcode == EEOP_NEW_FETCHSOME);
    3103              : 
    3104      1089180 :     if (op->d.fetch.known_desc != NULL)
    3105              :     {
    3106        28082 :         desc = op->d.fetch.known_desc;
    3107        28082 :         tts_ops = op->d.fetch.kind;
    3108        28082 :         isfixed = op->d.fetch.kind != NULL;
    3109              :     }
    3110      1061098 :     else if (!parent)
    3111              :     {
    3112         8913 :         isfixed = false;
    3113              :     }
    3114      1052185 :     else if (opcode == EEOP_INNER_FETCHSOME)
    3115              :     {
    3116       108759 :         PlanState  *is = innerPlanState(parent);
    3117              : 
    3118       108759 :         if (parent->inneropsset && !parent->inneropsfixed)
    3119              :         {
    3120            0 :             isfixed = false;
    3121              :         }
    3122       108759 :         else if (parent->inneropsset && parent->innerops)
    3123              :         {
    3124            0 :             isfixed = true;
    3125            0 :             tts_ops = parent->innerops;
    3126            0 :             desc = ExecGetResultType(is);
    3127              :         }
    3128       108759 :         else if (is)
    3129              :         {
    3130       107400 :             tts_ops = ExecGetResultSlotOps(is, &isfixed);
    3131       107400 :             desc = ExecGetResultType(is);
    3132              :         }
    3133              :     }
    3134       943426 :     else if (opcode == EEOP_OUTER_FETCHSOME)
    3135              :     {
    3136       200866 :         PlanState  *os = outerPlanState(parent);
    3137              : 
    3138       200866 :         if (parent->outeropsset && !parent->outeropsfixed)
    3139              :         {
    3140          623 :             isfixed = false;
    3141              :         }
    3142       200243 :         else if (parent->outeropsset && parent->outerops)
    3143              :         {
    3144        23496 :             isfixed = true;
    3145        23496 :             tts_ops = parent->outerops;
    3146        23496 :             desc = ExecGetResultType(os);
    3147              :         }
    3148       176747 :         else if (os)
    3149              :         {
    3150       176741 :             tts_ops = ExecGetResultSlotOps(os, &isfixed);
    3151       176741 :             desc = ExecGetResultType(os);
    3152              :         }
    3153              :     }
    3154       742560 :     else if (opcode == EEOP_SCAN_FETCHSOME ||
    3155          183 :              opcode == EEOP_OLD_FETCHSOME ||
    3156              :              opcode == EEOP_NEW_FETCHSOME)
    3157              :     {
    3158       742560 :         desc = parent->scandesc;
    3159              : 
    3160       742560 :         if (parent->scanops)
    3161       730017 :             tts_ops = parent->scanops;
    3162              : 
    3163       742560 :         if (parent->scanopsset)
    3164       730017 :             isfixed = parent->scanopsfixed;
    3165              :     }
    3166              : 
    3167      1089180 :     if (isfixed && desc != NULL && tts_ops != NULL)
    3168              :     {
    3169      1051385 :         op->d.fetch.fixed = true;
    3170      1051385 :         op->d.fetch.kind = tts_ops;
    3171      1051385 :         op->d.fetch.known_desc = desc;
    3172              :     }
    3173              :     else
    3174              :     {
    3175        37795 :         op->d.fetch.fixed = false;
    3176        37795 :         op->d.fetch.kind = NULL;
    3177        37795 :         op->d.fetch.known_desc = NULL;
    3178              :     }
    3179              : 
    3180              :     /* if the slot is known to always virtual we never need to deform */
    3181      1089180 :     if (op->d.fetch.fixed && op->d.fetch.kind == &TTSOpsVirtual)
    3182       129207 :         return false;
    3183              : 
    3184       959973 :     return true;
    3185              : }
    3186              : 
    3187              : /*
    3188              :  * Prepare step for the evaluation of a whole-row variable.
    3189              :  * The caller still has to push the step.
    3190              :  */
    3191              : static void
    3192         2657 : ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state)
    3193              : {
    3194         2657 :     PlanState  *parent = state->parent;
    3195              : 
    3196              :     /* fill in all but the target */
    3197         2657 :     scratch->opcode = EEOP_WHOLEROW;
    3198         2657 :     scratch->d.wholerow.var = variable;
    3199         2657 :     scratch->d.wholerow.first = true;
    3200         2657 :     scratch->d.wholerow.slow = false;
    3201         2657 :     scratch->d.wholerow.tupdesc = NULL; /* filled at runtime */
    3202         2657 :     scratch->d.wholerow.junkFilter = NULL;
    3203              : 
    3204              :     /* update ExprState flags if Var refers to OLD/NEW */
    3205         2657 :     if (variable->varreturningtype == VAR_RETURNING_OLD)
    3206           66 :         state->flags |= EEO_FLAG_HAS_OLD;
    3207         2591 :     else if (variable->varreturningtype == VAR_RETURNING_NEW)
    3208           66 :         state->flags |= EEO_FLAG_HAS_NEW;
    3209              : 
    3210              :     /*
    3211              :      * If the input tuple came from a subquery, it might contain "resjunk"
    3212              :      * columns (such as GROUP BY or ORDER BY columns), which we don't want to
    3213              :      * keep in the whole-row result.  We can get rid of such columns by
    3214              :      * passing the tuple through a JunkFilter --- but to make one, we have to
    3215              :      * lay our hands on the subquery's targetlist.  Fortunately, there are not
    3216              :      * very many cases where this can happen, and we can identify all of them
    3217              :      * by examining our parent PlanState.  We assume this is not an issue in
    3218              :      * standalone expressions that don't have parent plans.  (Whole-row Vars
    3219              :      * can occur in such expressions, but they will always be referencing
    3220              :      * table rows.)
    3221              :      */
    3222         2657 :     if (parent)
    3223              :     {
    3224         2632 :         PlanState  *subplan = NULL;
    3225              : 
    3226         2632 :         switch (nodeTag(parent))
    3227              :         {
    3228          169 :             case T_SubqueryScanState:
    3229          169 :                 subplan = ((SubqueryScanState *) parent)->subplan;
    3230          169 :                 break;
    3231           86 :             case T_CteScanState:
    3232           86 :                 subplan = ((CteScanState *) parent)->cteplanstate;
    3233           86 :                 break;
    3234         2377 :             default:
    3235         2377 :                 break;
    3236              :         }
    3237              : 
    3238         2632 :         if (subplan)
    3239              :         {
    3240          255 :             bool        junk_filter_needed = false;
    3241              :             ListCell   *tlist;
    3242              : 
    3243              :             /* Detect whether subplan tlist actually has any junk columns */
    3244          784 :             foreach(tlist, subplan->plan->targetlist)
    3245              :             {
    3246          535 :                 TargetEntry *tle = (TargetEntry *) lfirst(tlist);
    3247              : 
    3248          535 :                 if (tle->resjunk)
    3249              :                 {
    3250            6 :                     junk_filter_needed = true;
    3251            6 :                     break;
    3252              :                 }
    3253              :             }
    3254              : 
    3255              :             /* If so, build the junkfilter now */
    3256          255 :             if (junk_filter_needed)
    3257              :             {
    3258            6 :                 scratch->d.wholerow.junkFilter =
    3259            6 :                     ExecInitJunkFilter(subplan->plan->targetlist,
    3260              :                                        ExecInitExtraTupleSlot(parent->state, NULL,
    3261              :                                                               &TTSOpsVirtual));
    3262              :             }
    3263              :         }
    3264              :     }
    3265         2657 : }
    3266              : 
    3267              : /*
    3268              :  * Prepare evaluation of a SubscriptingRef expression.
    3269              :  */
    3270              : static void
    3271        15928 : ExecInitSubscriptingRef(ExprEvalStep *scratch, SubscriptingRef *sbsref,
    3272              :                         ExprState *state, Datum *resv, bool *resnull)
    3273              : {
    3274        15928 :     bool        isAssignment = (sbsref->refassgnexpr != NULL);
    3275        15928 :     int         nupper = list_length(sbsref->refupperindexpr);
    3276        15928 :     int         nlower = list_length(sbsref->reflowerindexpr);
    3277              :     const SubscriptRoutines *sbsroutines;
    3278              :     SubscriptingRefState *sbsrefstate;
    3279              :     SubscriptExecSteps methods;
    3280              :     char       *ptr;
    3281        15928 :     List       *adjust_jumps = NIL;
    3282              :     ListCell   *lc;
    3283              :     int         i;
    3284              : 
    3285              :     /* Look up the subscripting support methods */
    3286        15928 :     sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
    3287        15928 :     if (!sbsroutines)
    3288            0 :         ereport(ERROR,
    3289              :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3290              :                  errmsg("cannot subscript type %s because it does not support subscripting",
    3291              :                         format_type_be(sbsref->refcontainertype)),
    3292              :                  state->parent ?
    3293              :                  executor_errposition(state->parent->state,
    3294              :                                       exprLocation((Node *) sbsref)) : 0));
    3295              : 
    3296              :     /* Allocate sbsrefstate, with enough space for per-subscript arrays too */
    3297        15928 :     sbsrefstate = palloc0(MAXALIGN(sizeof(SubscriptingRefState)) +
    3298        15928 :                           (nupper + nlower) * (sizeof(Datum) +
    3299              :                                                2 * sizeof(bool)));
    3300              : 
    3301              :     /* Fill constant fields of SubscriptingRefState */
    3302        15928 :     sbsrefstate->isassignment = isAssignment;
    3303        15928 :     sbsrefstate->numupper = nupper;
    3304        15928 :     sbsrefstate->numlower = nlower;
    3305              :     /* Set up per-subscript arrays */
    3306        15928 :     ptr = ((char *) sbsrefstate) + MAXALIGN(sizeof(SubscriptingRefState));
    3307        15928 :     sbsrefstate->upperindex = (Datum *) ptr;
    3308        15928 :     ptr += nupper * sizeof(Datum);
    3309        15928 :     sbsrefstate->lowerindex = (Datum *) ptr;
    3310        15928 :     ptr += nlower * sizeof(Datum);
    3311        15928 :     sbsrefstate->upperprovided = (bool *) ptr;
    3312        15928 :     ptr += nupper * sizeof(bool);
    3313        15928 :     sbsrefstate->lowerprovided = (bool *) ptr;
    3314        15928 :     ptr += nlower * sizeof(bool);
    3315        15928 :     sbsrefstate->upperindexnull = (bool *) ptr;
    3316        15928 :     ptr += nupper * sizeof(bool);
    3317        15928 :     sbsrefstate->lowerindexnull = (bool *) ptr;
    3318              :     /* ptr += nlower * sizeof(bool); */
    3319              : 
    3320              :     /*
    3321              :      * Let the container-type-specific code have a chance.  It must fill the
    3322              :      * "methods" struct with function pointers for us to possibly use in
    3323              :      * execution steps below; and it can optionally set up some data pointed
    3324              :      * to by the workspace field.
    3325              :      */
    3326        15928 :     memset(&methods, 0, sizeof(methods));
    3327        15928 :     sbsroutines->exec_setup(sbsref, sbsrefstate, &methods);
    3328              : 
    3329              :     /*
    3330              :      * Evaluate array input.  It's safe to do so into resv/resnull, because we
    3331              :      * won't use that as target for any of the other subexpressions, and it'll
    3332              :      * be overwritten by the final EEOP_SBSREF_FETCH/ASSIGN step, which is
    3333              :      * pushed last.
    3334              :      */
    3335        15928 :     ExecInitExprRec(sbsref->refexpr, state, resv, resnull);
    3336              : 
    3337              :     /*
    3338              :      * If refexpr yields NULL, and the operation should be strict, then result
    3339              :      * is NULL.  We can implement this with just JUMP_IF_NULL, since we
    3340              :      * evaluated the array into the desired target location.
    3341              :      */
    3342        15928 :     if (!isAssignment && sbsroutines->fetch_strict)
    3343              :     {
    3344        15268 :         scratch->opcode = EEOP_JUMP_IF_NULL;
    3345        15268 :         scratch->d.jump.jumpdone = -1;   /* adjust later */
    3346        15268 :         ExprEvalPushStep(state, scratch);
    3347        15268 :         adjust_jumps = lappend_int(adjust_jumps,
    3348        15268 :                                    state->steps_len - 1);
    3349              :     }
    3350              : 
    3351              :     /* Evaluate upper subscripts */
    3352        15928 :     i = 0;
    3353        32151 :     foreach(lc, sbsref->refupperindexpr)
    3354              :     {
    3355        16223 :         Expr       *e = (Expr *) lfirst(lc);
    3356              : 
    3357              :         /* When slicing, individual subscript bounds can be omitted */
    3358        16223 :         if (!e)
    3359              :         {
    3360           39 :             sbsrefstate->upperprovided[i] = false;
    3361           39 :             sbsrefstate->upperindexnull[i] = true;
    3362              :         }
    3363              :         else
    3364              :         {
    3365        16184 :             sbsrefstate->upperprovided[i] = true;
    3366              :             /* Each subscript is evaluated into appropriate array entry */
    3367        16184 :             ExecInitExprRec(e, state,
    3368        16184 :                             &sbsrefstate->upperindex[i],
    3369        16184 :                             &sbsrefstate->upperindexnull[i]);
    3370              :         }
    3371        16223 :         i++;
    3372              :     }
    3373              : 
    3374              :     /* Evaluate lower subscripts similarly */
    3375        15928 :     i = 0;
    3376        16231 :     foreach(lc, sbsref->reflowerindexpr)
    3377              :     {
    3378          303 :         Expr       *e = (Expr *) lfirst(lc);
    3379              : 
    3380              :         /* When slicing, individual subscript bounds can be omitted */
    3381          303 :         if (!e)
    3382              :         {
    3383           39 :             sbsrefstate->lowerprovided[i] = false;
    3384           39 :             sbsrefstate->lowerindexnull[i] = true;
    3385              :         }
    3386              :         else
    3387              :         {
    3388          264 :             sbsrefstate->lowerprovided[i] = true;
    3389              :             /* Each subscript is evaluated into appropriate array entry */
    3390          264 :             ExecInitExprRec(e, state,
    3391          264 :                             &sbsrefstate->lowerindex[i],
    3392          264 :                             &sbsrefstate->lowerindexnull[i]);
    3393              :         }
    3394          303 :         i++;
    3395              :     }
    3396              : 
    3397              :     /* SBSREF_SUBSCRIPTS checks and converts all the subscripts at once */
    3398        15928 :     if (methods.sbs_check_subscripts)
    3399              :     {
    3400        15921 :         scratch->opcode = EEOP_SBSREF_SUBSCRIPTS;
    3401        15921 :         scratch->d.sbsref_subscript.subscriptfunc = methods.sbs_check_subscripts;
    3402        15921 :         scratch->d.sbsref_subscript.state = sbsrefstate;
    3403        15921 :         scratch->d.sbsref_subscript.jumpdone = -1;   /* adjust later */
    3404        15921 :         ExprEvalPushStep(state, scratch);
    3405        15921 :         adjust_jumps = lappend_int(adjust_jumps,
    3406        15921 :                                    state->steps_len - 1);
    3407              :     }
    3408              : 
    3409        15928 :     if (isAssignment)
    3410              :     {
    3411              :         Datum      *save_innermost_caseval;
    3412              :         bool       *save_innermost_casenull;
    3413              : 
    3414              :         /* Check for unimplemented methods */
    3415          660 :         if (!methods.sbs_assign)
    3416            0 :             ereport(ERROR,
    3417              :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3418              :                      errmsg("type %s does not support subscripted assignment",
    3419              :                             format_type_be(sbsref->refcontainertype))));
    3420              : 
    3421              :         /*
    3422              :          * We might have a nested-assignment situation, in which the
    3423              :          * refassgnexpr is itself a FieldStore or SubscriptingRef that needs
    3424              :          * to obtain and modify the previous value of the array element or
    3425              :          * slice being replaced.  If so, we have to extract that value from
    3426              :          * the array and pass it down via the CaseTestExpr mechanism.  It's
    3427              :          * safe to reuse the CASE mechanism because there cannot be a CASE
    3428              :          * between here and where the value would be needed, and an array
    3429              :          * assignment can't be within a CASE either.  (So saving and restoring
    3430              :          * innermost_caseval is just paranoia, but let's do it anyway.)
    3431              :          *
    3432              :          * Since fetching the old element might be a nontrivial expense, do it
    3433              :          * only if the argument actually needs it.
    3434              :          */
    3435          660 :         if (isAssignmentIndirectionExpr(sbsref->refassgnexpr))
    3436              :         {
    3437           93 :             if (!methods.sbs_fetch_old)
    3438            0 :                 ereport(ERROR,
    3439              :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3440              :                          errmsg("type %s does not support subscripted assignment",
    3441              :                                 format_type_be(sbsref->refcontainertype))));
    3442           93 :             scratch->opcode = EEOP_SBSREF_OLD;
    3443           93 :             scratch->d.sbsref.subscriptfunc = methods.sbs_fetch_old;
    3444           93 :             scratch->d.sbsref.state = sbsrefstate;
    3445           93 :             ExprEvalPushStep(state, scratch);
    3446              :         }
    3447              : 
    3448              :         /* SBSREF_OLD puts extracted value into prevvalue/prevnull */
    3449          660 :         save_innermost_caseval = state->innermost_caseval;
    3450          660 :         save_innermost_casenull = state->innermost_casenull;
    3451          660 :         state->innermost_caseval = &sbsrefstate->prevvalue;
    3452          660 :         state->innermost_casenull = &sbsrefstate->prevnull;
    3453              : 
    3454              :         /* evaluate replacement value into replacevalue/replacenull */
    3455          660 :         ExecInitExprRec(sbsref->refassgnexpr, state,
    3456              :                         &sbsrefstate->replacevalue, &sbsrefstate->replacenull);
    3457              : 
    3458          660 :         state->innermost_caseval = save_innermost_caseval;
    3459          660 :         state->innermost_casenull = save_innermost_casenull;
    3460              : 
    3461              :         /* and perform the assignment */
    3462          660 :         scratch->opcode = EEOP_SBSREF_ASSIGN;
    3463          660 :         scratch->d.sbsref.subscriptfunc = methods.sbs_assign;
    3464          660 :         scratch->d.sbsref.state = sbsrefstate;
    3465          660 :         ExprEvalPushStep(state, scratch);
    3466              :     }
    3467              :     else
    3468              :     {
    3469              :         /* array fetch is much simpler */
    3470        15268 :         scratch->opcode = EEOP_SBSREF_FETCH;
    3471        15268 :         scratch->d.sbsref.subscriptfunc = methods.sbs_fetch;
    3472        15268 :         scratch->d.sbsref.state = sbsrefstate;
    3473        15268 :         ExprEvalPushStep(state, scratch);
    3474              :     }
    3475              : 
    3476              :     /* adjust jump targets */
    3477        47117 :     foreach(lc, adjust_jumps)
    3478              :     {
    3479        31189 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    3480              : 
    3481        31189 :         if (as->opcode == EEOP_SBSREF_SUBSCRIPTS)
    3482              :         {
    3483              :             Assert(as->d.sbsref_subscript.jumpdone == -1);
    3484        15921 :             as->d.sbsref_subscript.jumpdone = state->steps_len;
    3485              :         }
    3486              :         else
    3487              :         {
    3488              :             Assert(as->opcode == EEOP_JUMP_IF_NULL);
    3489              :             Assert(as->d.jump.jumpdone == -1);
    3490        15268 :             as->d.jump.jumpdone = state->steps_len;
    3491              :         }
    3492              :     }
    3493        15928 : }
    3494              : 
    3495              : /*
    3496              :  * Helper for preparing SubscriptingRef expressions for evaluation: is expr
    3497              :  * a nested FieldStore or SubscriptingRef that needs the old element value
    3498              :  * passed down?
    3499              :  *
    3500              :  * (We could use this in FieldStore too, but in that case passing the old
    3501              :  * value is so cheap there's no need.)
    3502              :  *
    3503              :  * Note: it might seem that this needs to recurse, but in most cases it does
    3504              :  * not; the CaseTestExpr, if any, will be directly the arg or refexpr of the
    3505              :  * top-level node.  Nested-assignment situations give rise to expression
    3506              :  * trees in which each level of assignment has its own CaseTestExpr, and the
    3507              :  * recursive structure appears within the newvals or refassgnexpr field.
    3508              :  * There is an exception, though: if the array is an array-of-domain, we will
    3509              :  * have a CoerceToDomain or RelabelType as the refassgnexpr, and we need to
    3510              :  * be able to look through that.
    3511              :  */
    3512              : static bool
    3513          702 : isAssignmentIndirectionExpr(Expr *expr)
    3514              : {
    3515          702 :     if (expr == NULL)
    3516            0 :         return false;           /* just paranoia */
    3517          702 :     if (IsA(expr, FieldStore))
    3518              :     {
    3519           93 :         FieldStore *fstore = (FieldStore *) expr;
    3520              : 
    3521           93 :         if (fstore->arg && IsA(fstore->arg, CaseTestExpr))
    3522           93 :             return true;
    3523              :     }
    3524          609 :     else if (IsA(expr, SubscriptingRef))
    3525              :     {
    3526           16 :         SubscriptingRef *sbsRef = (SubscriptingRef *) expr;
    3527              : 
    3528           16 :         if (sbsRef->refexpr && IsA(sbsRef->refexpr, CaseTestExpr))
    3529            0 :             return true;
    3530              :     }
    3531          593 :     else if (IsA(expr, CoerceToDomain))
    3532              :     {
    3533           33 :         CoerceToDomain *cd = (CoerceToDomain *) expr;
    3534              : 
    3535           33 :         return isAssignmentIndirectionExpr(cd->arg);
    3536              :     }
    3537          560 :     else if (IsA(expr, RelabelType))
    3538              :     {
    3539            9 :         RelabelType *r = (RelabelType *) expr;
    3540              : 
    3541            9 :         return isAssignmentIndirectionExpr(r->arg);
    3542              :     }
    3543          567 :     return false;
    3544              : }
    3545              : 
    3546              : /*
    3547              :  * Prepare evaluation of a CoerceToDomain expression.
    3548              :  */
    3549              : static void
    3550         4961 : ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
    3551              :                        ExprState *state, Datum *resv, bool *resnull)
    3552              : {
    3553              :     DomainConstraintRef *constraint_ref;
    3554         4961 :     Datum      *domainval = NULL;
    3555         4961 :     bool       *domainnull = NULL;
    3556              :     ListCell   *l;
    3557              : 
    3558         4961 :     scratch->d.domaincheck.resulttype = ctest->resulttype;
    3559              :     /* we'll allocate workspace only if needed */
    3560         4961 :     scratch->d.domaincheck.checkvalue = NULL;
    3561         4961 :     scratch->d.domaincheck.checknull = NULL;
    3562         4961 :     scratch->d.domaincheck.escontext = state->escontext;
    3563              : 
    3564              :     /*
    3565              :      * Evaluate argument - it's fine to directly store it into resv/resnull,
    3566              :      * if there's constraint failures there'll be errors, otherwise it's what
    3567              :      * needs to be returned.
    3568              :      */
    3569         4961 :     ExecInitExprRec(ctest->arg, state, resv, resnull);
    3570              : 
    3571              :     /*
    3572              :      * Note: if the argument is of varlena type, it could be a R/W expanded
    3573              :      * object.  We want to return the R/W pointer as the final result, but we
    3574              :      * have to pass a R/O pointer as the value to be tested by any functions
    3575              :      * in check expressions.  We don't bother to emit a MAKE_READONLY step
    3576              :      * unless there's actually at least one check expression, though.  Until
    3577              :      * we've tested that, domainval/domainnull are NULL.
    3578              :      */
    3579              : 
    3580              :     /*
    3581              :      * Collect the constraints associated with the domain.
    3582              :      *
    3583              :      * Note: before PG v10 we'd recheck the set of constraints during each
    3584              :      * evaluation of the expression.  Now we bake them into the ExprState
    3585              :      * during executor initialization.  That means we don't need typcache.c to
    3586              :      * provide compiled exprs.
    3587              :      */
    3588         4961 :     constraint_ref = palloc_object(DomainConstraintRef);
    3589         4961 :     InitDomainConstraintRef(ctest->resulttype,
    3590              :                             constraint_ref,
    3591              :                             CurrentMemoryContext,
    3592              :                             false);
    3593              : 
    3594              :     /*
    3595              :      * Compile code to check each domain constraint.  NOTNULL constraints can
    3596              :      * just be applied on the resv/resnull value, but for CHECK constraints we
    3597              :      * need more pushups.
    3598              :      */
    3599        10424 :     foreach(l, constraint_ref->constraints)
    3600              :     {
    3601         5463 :         DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
    3602              :         Datum      *save_innermost_domainval;
    3603              :         bool       *save_innermost_domainnull;
    3604              : 
    3605         5463 :         scratch->d.domaincheck.constraintname = con->name;
    3606              : 
    3607         5463 :         switch (con->constrainttype)
    3608              :         {
    3609          210 :             case DOM_CONSTRAINT_NOTNULL:
    3610          210 :                 scratch->opcode = EEOP_DOMAIN_NOTNULL;
    3611          210 :                 ExprEvalPushStep(state, scratch);
    3612          210 :                 break;
    3613         5253 :             case DOM_CONSTRAINT_CHECK:
    3614              :                 /* Allocate workspace for CHECK output if we didn't yet */
    3615         5253 :                 if (scratch->d.domaincheck.checkvalue == NULL)
    3616              :                 {
    3617         4820 :                     scratch->d.domaincheck.checkvalue =
    3618         4820 :                         palloc_object(Datum);
    3619         4820 :                     scratch->d.domaincheck.checknull =
    3620         4820 :                         palloc_object(bool);
    3621              :                 }
    3622              : 
    3623              :                 /*
    3624              :                  * If first time through, determine where CoerceToDomainValue
    3625              :                  * nodes should read from.
    3626              :                  */
    3627         5253 :                 if (domainval == NULL)
    3628              :                 {
    3629              :                     /*
    3630              :                      * Since value might be read multiple times, force to R/O
    3631              :                      * - but only if it could be an expanded datum.
    3632              :                      */
    3633         4820 :                     if (get_typlen(ctest->resulttype) == -1)
    3634              :                     {
    3635         1554 :                         ExprEvalStep scratch2 = {0};
    3636              : 
    3637              :                         /* Yes, so make output workspace for MAKE_READONLY */
    3638         1554 :                         domainval = palloc_object(Datum);
    3639         1554 :                         domainnull = palloc_object(bool);
    3640              : 
    3641              :                         /* Emit MAKE_READONLY */
    3642         1554 :                         scratch2.opcode = EEOP_MAKE_READONLY;
    3643         1554 :                         scratch2.resvalue = domainval;
    3644         1554 :                         scratch2.resnull = domainnull;
    3645         1554 :                         scratch2.d.make_readonly.value = resv;
    3646         1554 :                         scratch2.d.make_readonly.isnull = resnull;
    3647         1554 :                         ExprEvalPushStep(state, &scratch2);
    3648              :                     }
    3649              :                     else
    3650              :                     {
    3651              :                         /* No, so it's fine to read from resv/resnull */
    3652         3266 :                         domainval = resv;
    3653         3266 :                         domainnull = resnull;
    3654              :                     }
    3655              :                 }
    3656              : 
    3657              :                 /*
    3658              :                  * Set up value to be returned by CoerceToDomainValue nodes.
    3659              :                  * We must save and restore innermost_domainval/null fields,
    3660              :                  * in case this node is itself within a check expression for
    3661              :                  * another domain.
    3662              :                  */
    3663         5253 :                 save_innermost_domainval = state->innermost_domainval;
    3664         5253 :                 save_innermost_domainnull = state->innermost_domainnull;
    3665         5253 :                 state->innermost_domainval = domainval;
    3666         5253 :                 state->innermost_domainnull = domainnull;
    3667              : 
    3668              :                 /* evaluate check expression value */
    3669         5253 :                 ExecInitExprRec(con->check_expr, state,
    3670              :                                 scratch->d.domaincheck.checkvalue,
    3671              :                                 scratch->d.domaincheck.checknull);
    3672              : 
    3673         5253 :                 state->innermost_domainval = save_innermost_domainval;
    3674         5253 :                 state->innermost_domainnull = save_innermost_domainnull;
    3675              : 
    3676              :                 /* now test result */
    3677         5253 :                 scratch->opcode = EEOP_DOMAIN_CHECK;
    3678         5253 :                 ExprEvalPushStep(state, scratch);
    3679              : 
    3680         5253 :                 break;
    3681            0 :             default:
    3682            0 :                 elog(ERROR, "unrecognized constraint type: %d",
    3683              :                      (int) con->constrainttype);
    3684              :                 break;
    3685              :         }
    3686              :     }
    3687         4961 : }
    3688              : 
    3689              : /*
    3690              :  * Build transition/combine function invocations for all aggregate transition
    3691              :  * / combination function invocations in a grouping sets phase. This has to
    3692              :  * invoke all sort based transitions in a phase (if doSort is true), all hash
    3693              :  * based transitions (if doHash is true), or both (both true).
    3694              :  *
    3695              :  * The resulting expression will, for each set of transition values, first
    3696              :  * check for filters, evaluate aggregate input, check that that input is not
    3697              :  * NULL for a strict transition function, and then finally invoke the
    3698              :  * transition for each of the concurrently computed grouping sets.
    3699              :  *
    3700              :  * If nullcheck is true, the generated code will check for a NULL pointer to
    3701              :  * the array of AggStatePerGroup, and skip evaluation if so.
    3702              :  */
    3703              : ExprState *
    3704        27936 : ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase,
    3705              :                   bool doSort, bool doHash, bool nullcheck)
    3706              : {
    3707        27936 :     ExprState  *state = makeNode(ExprState);
    3708        27936 :     PlanState  *parent = &aggstate->ss.ps;
    3709        27936 :     ExprEvalStep scratch = {0};
    3710        27936 :     bool        isCombine = DO_AGGSPLIT_COMBINE(aggstate->aggsplit);
    3711        27936 :     ExprSetupInfo deform = {0, 0, 0, 0, 0, NIL};
    3712              : 
    3713        27936 :     state->expr = (Expr *) aggstate;
    3714        27936 :     state->parent = parent;
    3715              : 
    3716        27936 :     scratch.resvalue = &state->resvalue;
    3717        27936 :     scratch.resnull = &state->resnull;
    3718              : 
    3719              :     /*
    3720              :      * First figure out which slots, and how many columns from each, we're
    3721              :      * going to need.
    3722              :      */
    3723        58846 :     for (int transno = 0; transno < aggstate->numtrans; transno++)
    3724              :     {
    3725        30910 :         AggStatePerTrans pertrans = &aggstate->pertrans[transno];
    3726              : 
    3727        30910 :         expr_setup_walker((Node *) pertrans->aggref->aggdirectargs,
    3728              :                           &deform);
    3729        30910 :         expr_setup_walker((Node *) pertrans->aggref->args,
    3730              :                           &deform);
    3731        30910 :         expr_setup_walker((Node *) pertrans->aggref->aggorder,
    3732              :                           &deform);
    3733        30910 :         expr_setup_walker((Node *) pertrans->aggref->aggdistinct,
    3734              :                           &deform);
    3735        30910 :         expr_setup_walker((Node *) pertrans->aggref->aggfilter,
    3736              :                           &deform);
    3737              :     }
    3738        27936 :     ExecPushExprSetupSteps(state, &deform);
    3739              : 
    3740              :     /*
    3741              :      * Emit instructions for each transition value / grouping set combination.
    3742              :      */
    3743        58846 :     for (int transno = 0; transno < aggstate->numtrans; transno++)
    3744              :     {
    3745        30910 :         AggStatePerTrans pertrans = &aggstate->pertrans[transno];
    3746        30910 :         FunctionCallInfo trans_fcinfo = pertrans->transfn_fcinfo;
    3747        30910 :         List       *adjust_bailout = NIL;
    3748        30910 :         NullableDatum *strictargs = NULL;
    3749        30910 :         bool       *strictnulls = NULL;
    3750              :         int         argno;
    3751              :         ListCell   *bail;
    3752              : 
    3753              :         /*
    3754              :          * If filter present, emit. Do so before evaluating the input, to
    3755              :          * avoid potentially unneeded computations, or even worse, unintended
    3756              :          * side-effects.  When combining, all the necessary filtering has
    3757              :          * already been done.
    3758              :          */
    3759        30910 :         if (pertrans->aggref->aggfilter && !isCombine)
    3760              :         {
    3761              :             /* evaluate filter expression */
    3762          380 :             ExecInitExprRec(pertrans->aggref->aggfilter, state,
    3763              :                             &state->resvalue, &state->resnull);
    3764              :             /* and jump out if false */
    3765          380 :             scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
    3766          380 :             scratch.d.jump.jumpdone = -1;   /* adjust later */
    3767          380 :             ExprEvalPushStep(state, &scratch);
    3768          380 :             adjust_bailout = lappend_int(adjust_bailout,
    3769          380 :                                          state->steps_len - 1);
    3770              :         }
    3771              : 
    3772              :         /*
    3773              :          * Evaluate arguments to aggregate/combine function.
    3774              :          */
    3775        30910 :         argno = 0;
    3776        30910 :         if (isCombine)
    3777              :         {
    3778              :             /*
    3779              :              * Combining two aggregate transition values. Instead of directly
    3780              :              * coming from a tuple the input is a, potentially deserialized,
    3781              :              * transition value.
    3782              :              */
    3783              :             TargetEntry *source_tle;
    3784              : 
    3785              :             Assert(pertrans->numSortCols == 0);
    3786              :             Assert(list_length(pertrans->aggref->args) == 1);
    3787              : 
    3788         1126 :             strictargs = trans_fcinfo->args + 1;
    3789         1126 :             source_tle = (TargetEntry *) linitial(pertrans->aggref->args);
    3790              : 
    3791              :             /*
    3792              :              * deserialfn_oid will be set if we must deserialize the input
    3793              :              * state before calling the combine function.
    3794              :              */
    3795         1126 :             if (!OidIsValid(pertrans->deserialfn_oid))
    3796              :             {
    3797              :                 /*
    3798              :                  * Start from 1, since the 0th arg will be the transition
    3799              :                  * value
    3800              :                  */
    3801         1066 :                 ExecInitExprRec(source_tle->expr, state,
    3802         1066 :                                 &trans_fcinfo->args[argno + 1].value,
    3803         1066 :                                 &trans_fcinfo->args[argno + 1].isnull);
    3804              :             }
    3805              :             else
    3806              :             {
    3807           60 :                 FunctionCallInfo ds_fcinfo = pertrans->deserialfn_fcinfo;
    3808              : 
    3809              :                 /* evaluate argument */
    3810           60 :                 ExecInitExprRec(source_tle->expr, state,
    3811              :                                 &ds_fcinfo->args[0].value,
    3812              :                                 &ds_fcinfo->args[0].isnull);
    3813              : 
    3814              :                 /* Dummy second argument for type-safety reasons */
    3815           60 :                 ds_fcinfo->args[1].value = PointerGetDatum(NULL);
    3816           60 :                 ds_fcinfo->args[1].isnull = false;
    3817              : 
    3818              :                 /*
    3819              :                  * Don't call a strict deserialization function with NULL
    3820              :                  * input
    3821              :                  */
    3822           60 :                 if (pertrans->deserialfn.fn_strict)
    3823           60 :                     scratch.opcode = EEOP_AGG_STRICT_DESERIALIZE;
    3824              :                 else
    3825            0 :                     scratch.opcode = EEOP_AGG_DESERIALIZE;
    3826              : 
    3827           60 :                 scratch.d.agg_deserialize.fcinfo_data = ds_fcinfo;
    3828           60 :                 scratch.d.agg_deserialize.jumpnull = -1;    /* adjust later */
    3829           60 :                 scratch.resvalue = &trans_fcinfo->args[argno + 1].value;
    3830           60 :                 scratch.resnull = &trans_fcinfo->args[argno + 1].isnull;
    3831              : 
    3832           60 :                 ExprEvalPushStep(state, &scratch);
    3833              :                 /* don't add an adjustment unless the function is strict */
    3834           60 :                 if (pertrans->deserialfn.fn_strict)
    3835           60 :                     adjust_bailout = lappend_int(adjust_bailout,
    3836           60 :                                                  state->steps_len - 1);
    3837              : 
    3838              :                 /* restore normal settings of scratch fields */
    3839           60 :                 scratch.resvalue = &state->resvalue;
    3840           60 :                 scratch.resnull = &state->resnull;
    3841              :             }
    3842         1126 :             argno++;
    3843              : 
    3844              :             Assert(pertrans->numInputs == argno);
    3845              :         }
    3846        29784 :         else if (!pertrans->aggsortrequired)
    3847              :         {
    3848              :             ListCell   *arg;
    3849              : 
    3850              :             /*
    3851              :              * Normal transition function without ORDER BY / DISTINCT or with
    3852              :              * ORDER BY / DISTINCT but the planner has given us pre-sorted
    3853              :              * input.
    3854              :              */
    3855        29636 :             strictargs = trans_fcinfo->args + 1;
    3856              : 
    3857        50821 :             foreach(arg, pertrans->aggref->args)
    3858              :             {
    3859        22090 :                 TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
    3860              : 
    3861              :                 /*
    3862              :                  * Don't initialize args for any ORDER BY clause that might
    3863              :                  * exist in a presorted aggregate.
    3864              :                  */
    3865        22090 :                 if (argno == pertrans->numTransInputs)
    3866          905 :                     break;
    3867              : 
    3868              :                 /*
    3869              :                  * Start from 1, since the 0th arg will be the transition
    3870              :                  * value
    3871              :                  */
    3872        21185 :                 ExecInitExprRec(source_tle->expr, state,
    3873        21185 :                                 &trans_fcinfo->args[argno + 1].value,
    3874        21185 :                                 &trans_fcinfo->args[argno + 1].isnull);
    3875        21185 :                 argno++;
    3876              :             }
    3877              :             Assert(pertrans->numTransInputs == argno);
    3878              :         }
    3879          148 :         else if (pertrans->numInputs == 1)
    3880              :         {
    3881              :             /*
    3882              :              * Non-presorted DISTINCT and/or ORDER BY case, with a single
    3883              :              * column sorted on.
    3884              :              */
    3885          124 :             TargetEntry *source_tle =
    3886          124 :                 (TargetEntry *) linitial(pertrans->aggref->args);
    3887              : 
    3888              :             Assert(list_length(pertrans->aggref->args) == 1);
    3889              : 
    3890          124 :             ExecInitExprRec(source_tle->expr, state,
    3891              :                             &state->resvalue,
    3892              :                             &state->resnull);
    3893          124 :             strictnulls = &state->resnull;
    3894          124 :             argno++;
    3895              : 
    3896              :             Assert(pertrans->numInputs == argno);
    3897              :         }
    3898              :         else
    3899              :         {
    3900              :             /*
    3901              :              * Non-presorted DISTINCT and/or ORDER BY case, with multiple
    3902              :              * columns sorted on.
    3903              :              */
    3904           24 :             Datum      *values = pertrans->sortslot->tts_values;
    3905           24 :             bool       *nulls = pertrans->sortslot->tts_isnull;
    3906              :             ListCell   *arg;
    3907              : 
    3908           24 :             strictnulls = nulls;
    3909              : 
    3910           84 :             foreach(arg, pertrans->aggref->args)
    3911              :             {
    3912           60 :                 TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
    3913              : 
    3914           60 :                 ExecInitExprRec(source_tle->expr, state,
    3915           60 :                                 &values[argno], &nulls[argno]);
    3916           60 :                 argno++;
    3917              :             }
    3918              :             Assert(pertrans->numInputs == argno);
    3919              :         }
    3920              : 
    3921              :         /*
    3922              :          * For a strict transfn, nothing happens when there's a NULL input; we
    3923              :          * just keep the prior transValue. This is true for both plain and
    3924              :          * sorted/distinct aggregates.
    3925              :          */
    3926        30910 :         if (trans_fcinfo->flinfo->fn_strict && pertrans->numTransInputs > 0)
    3927              :         {
    3928         5644 :             if (strictnulls)
    3929           81 :                 scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_NULLS;
    3930         5563 :             else if (strictargs && pertrans->numTransInputs == 1)
    3931         5449 :                 scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_ARGS_1;
    3932              :             else
    3933          114 :                 scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_ARGS;
    3934         5644 :             scratch.d.agg_strict_input_check.nulls = strictnulls;
    3935         5644 :             scratch.d.agg_strict_input_check.args = strictargs;
    3936         5644 :             scratch.d.agg_strict_input_check.jumpnull = -1; /* adjust later */
    3937         5644 :             scratch.d.agg_strict_input_check.nargs = pertrans->numTransInputs;
    3938         5644 :             ExprEvalPushStep(state, &scratch);
    3939         5644 :             adjust_bailout = lappend_int(adjust_bailout,
    3940         5644 :                                          state->steps_len - 1);
    3941              :         }
    3942              : 
    3943              :         /* Handle DISTINCT aggregates which have pre-sorted input */
    3944        30910 :         if (pertrans->numDistinctCols > 0 && !pertrans->aggsortrequired)
    3945              :         {
    3946          218 :             if (pertrans->numDistinctCols > 1)
    3947           51 :                 scratch.opcode = EEOP_AGG_PRESORTED_DISTINCT_MULTI;
    3948              :             else
    3949          167 :                 scratch.opcode = EEOP_AGG_PRESORTED_DISTINCT_SINGLE;
    3950              : 
    3951          218 :             scratch.d.agg_presorted_distinctcheck.pertrans = pertrans;
    3952          218 :             scratch.d.agg_presorted_distinctcheck.jumpdistinct = -1;    /* adjust later */
    3953          218 :             ExprEvalPushStep(state, &scratch);
    3954          218 :             adjust_bailout = lappend_int(adjust_bailout,
    3955          218 :                                          state->steps_len - 1);
    3956              :         }
    3957              : 
    3958              :         /*
    3959              :          * Call transition function (once for each concurrently evaluated
    3960              :          * grouping set). Do so for both sort and hash based computations, as
    3961              :          * applicable.
    3962              :          */
    3963        30910 :         if (doSort)
    3964              :         {
    3965        26827 :             int         processGroupingSets = Max(phase->numsets, 1);
    3966        26827 :             int         setoff = 0;
    3967              : 
    3968        54239 :             for (int setno = 0; setno < processGroupingSets; setno++)
    3969              :             {
    3970        27412 :                 ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
    3971              :                                       pertrans, transno, setno, setoff, false,
    3972              :                                       nullcheck);
    3973        27412 :                 setoff++;
    3974              :             }
    3975              :         }
    3976              : 
    3977        30910 :         if (doHash)
    3978              :         {
    3979         4272 :             int         numHashes = aggstate->num_hashes;
    3980              :             int         setoff;
    3981              : 
    3982              :             /* in MIXED mode, there'll be preceding transition values */
    3983         4272 :             if (aggstate->aggstrategy != AGG_HASHED)
    3984          201 :                 setoff = aggstate->maxsets;
    3985              :             else
    3986         4071 :                 setoff = 0;
    3987              : 
    3988         9149 :             for (int setno = 0; setno < numHashes; setno++)
    3989              :             {
    3990         4877 :                 ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
    3991              :                                       pertrans, transno, setno, setoff, true,
    3992              :                                       nullcheck);
    3993         4877 :                 setoff++;
    3994              :             }
    3995              :         }
    3996              : 
    3997              :         /* adjust early bail out jump target(s) */
    3998        37212 :         foreach(bail, adjust_bailout)
    3999              :         {
    4000         6302 :             ExprEvalStep *as = &state->steps[lfirst_int(bail)];
    4001              : 
    4002         6302 :             if (as->opcode == EEOP_JUMP_IF_NOT_TRUE)
    4003              :             {
    4004              :                 Assert(as->d.jump.jumpdone == -1);
    4005          380 :                 as->d.jump.jumpdone = state->steps_len;
    4006              :             }
    4007         5922 :             else if (as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_ARGS ||
    4008         5808 :                      as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_ARGS_1 ||
    4009          359 :                      as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_NULLS)
    4010              :             {
    4011              :                 Assert(as->d.agg_strict_input_check.jumpnull == -1);
    4012         5644 :                 as->d.agg_strict_input_check.jumpnull = state->steps_len;
    4013              :             }
    4014          278 :             else if (as->opcode == EEOP_AGG_STRICT_DESERIALIZE)
    4015              :             {
    4016              :                 Assert(as->d.agg_deserialize.jumpnull == -1);
    4017           60 :                 as->d.agg_deserialize.jumpnull = state->steps_len;
    4018              :             }
    4019          218 :             else if (as->opcode == EEOP_AGG_PRESORTED_DISTINCT_SINGLE ||
    4020           51 :                      as->opcode == EEOP_AGG_PRESORTED_DISTINCT_MULTI)
    4021              :             {
    4022              :                 Assert(as->d.agg_presorted_distinctcheck.jumpdistinct == -1);
    4023          218 :                 as->d.agg_presorted_distinctcheck.jumpdistinct = state->steps_len;
    4024              :             }
    4025              :             else
    4026              :                 Assert(false);
    4027              :         }
    4028              :     }
    4029              : 
    4030        27936 :     scratch.resvalue = NULL;
    4031        27936 :     scratch.resnull = NULL;
    4032        27936 :     scratch.opcode = EEOP_DONE_NO_RETURN;
    4033        27936 :     ExprEvalPushStep(state, &scratch);
    4034              : 
    4035        27936 :     ExecReadyExpr(state);
    4036              : 
    4037        27936 :     return state;
    4038              : }
    4039              : 
    4040              : /*
    4041              :  * Build transition/combine function invocation for a single transition
    4042              :  * value. This is separated from ExecBuildAggTrans() because there are
    4043              :  * multiple callsites (hash and sort in some grouping set cases).
    4044              :  */
    4045              : static void
    4046        32289 : ExecBuildAggTransCall(ExprState *state, AggState *aggstate,
    4047              :                       ExprEvalStep *scratch,
    4048              :                       FunctionCallInfo fcinfo, AggStatePerTrans pertrans,
    4049              :                       int transno, int setno, int setoff, bool ishash,
    4050              :                       bool nullcheck)
    4051              : {
    4052              :     ExprContext *aggcontext;
    4053        32289 :     int         adjust_jumpnull = -1;
    4054              : 
    4055        32289 :     if (ishash)
    4056         4877 :         aggcontext = aggstate->hashcontext;
    4057              :     else
    4058        27412 :         aggcontext = aggstate->aggcontexts[setno];
    4059              : 
    4060              :     /* add check for NULL pointer? */
    4061        32289 :     if (nullcheck)
    4062              :     {
    4063          210 :         scratch->opcode = EEOP_AGG_PLAIN_PERGROUP_NULLCHECK;
    4064          210 :         scratch->d.agg_plain_pergroup_nullcheck.setoff = setoff;
    4065              :         /* adjust later */
    4066          210 :         scratch->d.agg_plain_pergroup_nullcheck.jumpnull = -1;
    4067          210 :         ExprEvalPushStep(state, scratch);
    4068          210 :         adjust_jumpnull = state->steps_len - 1;
    4069              :     }
    4070              : 
    4071              :     /*
    4072              :      * Determine appropriate transition implementation.
    4073              :      *
    4074              :      * For non-ordered aggregates and ORDER BY / DISTINCT aggregates with
    4075              :      * presorted input:
    4076              :      *
    4077              :      * If the initial value for the transition state doesn't exist in the
    4078              :      * pg_aggregate table then we will let the first non-NULL value returned
    4079              :      * from the outer procNode become the initial value. (This is useful for
    4080              :      * aggregates like max() and min().) The noTransValue flag signals that we
    4081              :      * need to do so. If true, generate a
    4082              :      * EEOP_AGG_INIT_STRICT_PLAIN_TRANS{,_BYVAL} step. This step also needs to
    4083              :      * do the work described next:
    4084              :      *
    4085              :      * If the function is strict, but does have an initial value, choose
    4086              :      * EEOP_AGG_STRICT_PLAIN_TRANS{,_BYVAL}, which skips the transition
    4087              :      * function if the transition value has become NULL (because a previous
    4088              :      * transition function returned NULL). This step also needs to do the work
    4089              :      * described next:
    4090              :      *
    4091              :      * Otherwise we call EEOP_AGG_PLAIN_TRANS{,_BYVAL}, which does not have to
    4092              :      * perform either of the above checks.
    4093              :      *
    4094              :      * Having steps with overlapping responsibilities is not nice, but
    4095              :      * aggregations are very performance sensitive, making this worthwhile.
    4096              :      *
    4097              :      * For ordered aggregates:
    4098              :      *
    4099              :      * Only need to choose between the faster path for a single ordered
    4100              :      * column, and the one between multiple columns. Checking strictness etc
    4101              :      * is done when finalizing the aggregate. See
    4102              :      * process_ordered_aggregate_{single, multi} and
    4103              :      * advance_transition_function.
    4104              :      */
    4105        32289 :     if (!pertrans->aggsortrequired)
    4106              :     {
    4107        32117 :         if (pertrans->transtypeByVal)
    4108              :         {
    4109        30042 :             if (fcinfo->flinfo->fn_strict &&
    4110        15624 :                 pertrans->initValueIsNull)
    4111         2647 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL;
    4112        27395 :             else if (fcinfo->flinfo->fn_strict)
    4113        12977 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_STRICT_BYVAL;
    4114              :             else
    4115        14418 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_BYVAL;
    4116              :         }
    4117              :         else
    4118              :         {
    4119         2075 :             if (fcinfo->flinfo->fn_strict &&
    4120         1889 :                 pertrans->initValueIsNull)
    4121          543 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYREF;
    4122         1532 :             else if (fcinfo->flinfo->fn_strict)
    4123         1346 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_STRICT_BYREF;
    4124              :             else
    4125          186 :                 scratch->opcode = EEOP_AGG_PLAIN_TRANS_BYREF;
    4126              :         }
    4127              :     }
    4128          172 :     else if (pertrans->numInputs == 1)
    4129          142 :         scratch->opcode = EEOP_AGG_ORDERED_TRANS_DATUM;
    4130              :     else
    4131           30 :         scratch->opcode = EEOP_AGG_ORDERED_TRANS_TUPLE;
    4132              : 
    4133        32289 :     scratch->d.agg_trans.pertrans = pertrans;
    4134        32289 :     scratch->d.agg_trans.setno = setno;
    4135        32289 :     scratch->d.agg_trans.setoff = setoff;
    4136        32289 :     scratch->d.agg_trans.transno = transno;
    4137        32289 :     scratch->d.agg_trans.aggcontext = aggcontext;
    4138        32289 :     ExprEvalPushStep(state, scratch);
    4139              : 
    4140              :     /* fix up jumpnull */
    4141        32289 :     if (adjust_jumpnull != -1)
    4142              :     {
    4143          210 :         ExprEvalStep *as = &state->steps[adjust_jumpnull];
    4144              : 
    4145              :         Assert(as->opcode == EEOP_AGG_PLAIN_PERGROUP_NULLCHECK);
    4146              :         Assert(as->d.agg_plain_pergroup_nullcheck.jumpnull == -1);
    4147          210 :         as->d.agg_plain_pergroup_nullcheck.jumpnull = state->steps_len;
    4148              :     }
    4149        32289 : }
    4150              : 
    4151              : /*
    4152              :  * Build an ExprState that calls the given hash function(s) on the attnums
    4153              :  * given by 'keyColIdx' .  When numCols > 1, the hash values returned by each
    4154              :  * hash function are combined to produce a single hash value.
    4155              :  *
    4156              :  * desc: tuple descriptor for the to-be-hashed columns
    4157              :  * ops: TupleTableSlotOps to use for the give TupleDesc
    4158              :  * hashfunctions: FmgrInfos for each hash function to call, one per numCols.
    4159              :  * These are used directly in the returned ExprState so must remain allocated.
    4160              :  * collations: collation to use when calling the hash function.
    4161              :  * numCols: array length of hashfunctions, collations and keyColIdx.
    4162              :  * parent: PlanState node that the resulting ExprState will be evaluated at
    4163              :  * init_value: Normally 0, but can be set to other values to seed the hash
    4164              :  * with.  Non-zero is marginally slower, so best to only use if it's provably
    4165              :  * worthwhile.
    4166              :  */
    4167              : ExprState *
    4168         4594 : ExecBuildHash32FromAttrs(TupleDesc desc, const TupleTableSlotOps *ops,
    4169              :                          FmgrInfo *hashfunctions, Oid *collations,
    4170              :                          int numCols, AttrNumber *keyColIdx,
    4171              :                          PlanState *parent, uint32 init_value)
    4172              : {
    4173         4594 :     ExprState  *state = makeNode(ExprState);
    4174         4594 :     ExprEvalStep scratch = {0};
    4175         4594 :     NullableDatum *iresult = NULL;
    4176              :     intptr_t    opcode;
    4177         4594 :     AttrNumber  last_attnum = 0;
    4178              : 
    4179              :     Assert(numCols >= 0);
    4180              : 
    4181         4594 :     state->parent = parent;
    4182              : 
    4183              :     /*
    4184              :      * Make a place to store intermediate hash values between subsequent
    4185              :      * hashing of individual columns.  We only need this if there is more than
    4186              :      * one column to hash or an initial value plus one column.
    4187              :      */
    4188         4594 :     if ((int64) numCols + (init_value != 0) > 1)
    4189         1879 :         iresult = palloc_object(NullableDatum);
    4190              : 
    4191              :     /* find the highest attnum so we deform the tuple to that point */
    4192        12411 :     for (int i = 0; i < numCols; i++)
    4193         7817 :         last_attnum = Max(last_attnum, keyColIdx[i]);
    4194              : 
    4195         4594 :     scratch.opcode = EEOP_INNER_FETCHSOME;
    4196         4594 :     scratch.d.fetch.last_var = last_attnum;
    4197         4594 :     scratch.d.fetch.fixed = false;
    4198         4594 :     scratch.d.fetch.kind = ops;
    4199         4594 :     scratch.d.fetch.known_desc = desc;
    4200         4594 :     if (ExecComputeSlotInfo(state, &scratch))
    4201         2976 :         ExprEvalPushStep(state, &scratch);
    4202              : 
    4203         4594 :     if (init_value == 0)
    4204              :     {
    4205              :         /*
    4206              :          * No initial value, so we can assign the result of the hash function
    4207              :          * for the first attribute without having to concern ourselves with
    4208              :          * combining the result with any initial value.
    4209              :          */
    4210         4172 :         opcode = EEOP_HASHDATUM_FIRST;
    4211              :     }
    4212              :     else
    4213              :     {
    4214              :         /*
    4215              :          * Set up operation to set the initial value.  Normally we store this
    4216              :          * in the intermediate hash value location, but if there are no
    4217              :          * columns to hash, store it in the ExprState's result field.
    4218              :          */
    4219          422 :         scratch.opcode = EEOP_HASHDATUM_SET_INITVAL;
    4220          422 :         scratch.d.hashdatum_initvalue.init_value = UInt32GetDatum(init_value);
    4221          422 :         scratch.resvalue = numCols > 0 ? &iresult->value : &state->resvalue;
    4222          422 :         scratch.resnull = numCols > 0 ? &iresult->isnull : &state->resnull;
    4223              : 
    4224          422 :         ExprEvalPushStep(state, &scratch);
    4225              : 
    4226              :         /*
    4227              :          * When using an initial value use the NEXT32 ops as the FIRST ops
    4228              :          * would overwrite the stored initial value.
    4229              :          */
    4230          422 :         opcode = EEOP_HASHDATUM_NEXT32;
    4231              :     }
    4232              : 
    4233        12411 :     for (int i = 0; i < numCols; i++)
    4234              :     {
    4235              :         FmgrInfo   *finfo;
    4236              :         FunctionCallInfo fcinfo;
    4237         7817 :         Oid         inputcollid = collations[i];
    4238         7817 :         AttrNumber  attnum = keyColIdx[i] - 1;
    4239              : 
    4240         7817 :         finfo = &hashfunctions[i];
    4241         7817 :         fcinfo = palloc0(SizeForFunctionCallInfo(1));
    4242              : 
    4243              :         /* Initialize function call parameter structure too */
    4244         7817 :         InitFunctionCallInfoData(*fcinfo, finfo, 1, inputcollid, NULL, NULL);
    4245              : 
    4246              :         /*
    4247              :          * Fetch inner Var for this attnum and store it in the 1st arg of the
    4248              :          * hash func.
    4249              :          */
    4250         7817 :         scratch.opcode = EEOP_INNER_VAR;
    4251         7817 :         scratch.resvalue = &fcinfo->args[0].value;
    4252         7817 :         scratch.resnull = &fcinfo->args[0].isnull;
    4253         7817 :         scratch.d.var.attnum = attnum;
    4254         7817 :         scratch.d.var.vartype = TupleDescAttr(desc, attnum)->atttypid;
    4255         7817 :         scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
    4256              : 
    4257         7817 :         ExprEvalPushStep(state, &scratch);
    4258              : 
    4259              :         /* Call the hash function */
    4260         7817 :         scratch.opcode = opcode;
    4261              : 
    4262         7817 :         if (i == numCols - 1)
    4263              :         {
    4264              :             /*
    4265              :              * The result for hashing the final column is stored in the
    4266              :              * ExprState.
    4267              :              */
    4268         4594 :             scratch.resvalue = &state->resvalue;
    4269         4594 :             scratch.resnull = &state->resnull;
    4270              :         }
    4271              :         else
    4272              :         {
    4273              :             Assert(iresult != NULL);
    4274              : 
    4275              :             /* intermediate values are stored in an intermediate result */
    4276         3223 :             scratch.resvalue = &iresult->value;
    4277         3223 :             scratch.resnull = &iresult->isnull;
    4278              :         }
    4279              : 
    4280              :         /*
    4281              :          * NEXT32 opcodes need to look at the intermediate result.  We might
    4282              :          * as well just set this for all ops.  FIRSTs won't look at it.
    4283              :          */
    4284         7817 :         scratch.d.hashdatum.iresult = iresult;
    4285              : 
    4286         7817 :         scratch.d.hashdatum.finfo = finfo;
    4287         7817 :         scratch.d.hashdatum.fcinfo_data = fcinfo;
    4288         7817 :         scratch.d.hashdatum.fn_addr = finfo->fn_addr;
    4289         7817 :         scratch.d.hashdatum.jumpdone = -1;
    4290              : 
    4291         7817 :         ExprEvalPushStep(state, &scratch);
    4292              : 
    4293              :         /* subsequent attnums must be combined with the previous */
    4294         7817 :         opcode = EEOP_HASHDATUM_NEXT32;
    4295              :     }
    4296              : 
    4297         4594 :     scratch.resvalue = NULL;
    4298         4594 :     scratch.resnull = NULL;
    4299         4594 :     scratch.opcode = EEOP_DONE_RETURN;
    4300         4594 :     ExprEvalPushStep(state, &scratch);
    4301              : 
    4302         4594 :     ExecReadyExpr(state);
    4303              : 
    4304         4594 :     return state;
    4305              : }
    4306              : 
    4307              : /*
    4308              :  * Build an ExprState that calls the given hash function(s) on the given
    4309              :  * 'hash_exprs'.  When multiple expressions are present, the hash values
    4310              :  * returned by each hash function are combined to produce a single hash value.
    4311              :  *
    4312              :  * desc: tuple descriptor for the to-be-hashed expressions
    4313              :  * ops: TupleTableSlotOps for the TupleDesc
    4314              :  * hashfunc_oids: Oid for each hash function to call, one for each 'hash_expr'
    4315              :  * collations: collation to use when calling the hash function.
    4316              :  * hash_expr: list of expressions to hash the value of
    4317              :  * opstrict: array corresponding to the 'hashfunc_oids' to store op_strict()
    4318              :  * parent: PlanState node that the 'hash_exprs' will be evaluated at
    4319              :  * init_value: Normally 0, but can be set to other values to seed the hash
    4320              :  * with some other value.  Using non-zero is slightly less efficient but can
    4321              :  * be useful.
    4322              :  * keep_nulls: if true, evaluation of the returned ExprState will abort early
    4323              :  * returning NULL if the given hash function is strict and the Datum to hash
    4324              :  * is null.  When set to false, any NULL input Datums are skipped.
    4325              :  */
    4326              : ExprState *
    4327        43486 : ExecBuildHash32Expr(TupleDesc desc, const TupleTableSlotOps *ops,
    4328              :                     const Oid *hashfunc_oids, const List *collations,
    4329              :                     const List *hash_exprs, const bool *opstrict,
    4330              :                     PlanState *parent, uint32 init_value, bool keep_nulls)
    4331              : {
    4332        43486 :     ExprState  *state = makeNode(ExprState);
    4333        43486 :     ExprEvalStep scratch = {0};
    4334        43486 :     NullableDatum *iresult = NULL;
    4335        43486 :     List       *adjust_jumps = NIL;
    4336              :     ListCell   *lc;
    4337              :     ListCell   *lc2;
    4338              :     intptr_t    strict_opcode;
    4339              :     intptr_t    opcode;
    4340        43486 :     int         num_exprs = list_length(hash_exprs);
    4341              : 
    4342              :     Assert(num_exprs == list_length(collations));
    4343              : 
    4344        43486 :     state->parent = parent;
    4345              : 
    4346              :     /* Insert setup steps as needed. */
    4347        43486 :     ExecCreateExprSetupSteps(state, (Node *) hash_exprs);
    4348              : 
    4349              :     /*
    4350              :      * Make a place to store intermediate hash values between subsequent
    4351              :      * hashing of individual expressions.  We only need this if there is more
    4352              :      * than one expression to hash or an initial value plus one expression.
    4353              :      */
    4354        43486 :     if ((int64) num_exprs + (init_value != 0) > 1)
    4355         3478 :         iresult = palloc_object(NullableDatum);
    4356              : 
    4357        43486 :     if (init_value == 0)
    4358              :     {
    4359              :         /*
    4360              :          * No initial value, so we can assign the result of the hash function
    4361              :          * for the first hash_expr without having to concern ourselves with
    4362              :          * combining the result with any initial value.
    4363              :          */
    4364        43486 :         strict_opcode = EEOP_HASHDATUM_FIRST_STRICT;
    4365        43486 :         opcode = EEOP_HASHDATUM_FIRST;
    4366              :     }
    4367              :     else
    4368              :     {
    4369              :         /*
    4370              :          * Set up operation to set the initial value.  Normally we store this
    4371              :          * in the intermediate hash value location, but if there are no exprs
    4372              :          * to hash, store it in the ExprState's result field.
    4373              :          */
    4374            0 :         scratch.opcode = EEOP_HASHDATUM_SET_INITVAL;
    4375            0 :         scratch.d.hashdatum_initvalue.init_value = UInt32GetDatum(init_value);
    4376            0 :         scratch.resvalue = num_exprs > 0 ? &iresult->value : &state->resvalue;
    4377            0 :         scratch.resnull = num_exprs > 0 ? &iresult->isnull : &state->resnull;
    4378              : 
    4379            0 :         ExprEvalPushStep(state, &scratch);
    4380              : 
    4381              :         /*
    4382              :          * When using an initial value use the NEXT32/NEXT32_STRICT ops as the
    4383              :          * FIRST/FIRST_STRICT ops would overwrite the stored initial value.
    4384              :          */
    4385            0 :         strict_opcode = EEOP_HASHDATUM_NEXT32_STRICT;
    4386            0 :         opcode = EEOP_HASHDATUM_NEXT32;
    4387              :     }
    4388              : 
    4389        90546 :     forboth(lc, hash_exprs, lc2, collations)
    4390              :     {
    4391        47060 :         Expr       *expr = (Expr *) lfirst(lc);
    4392              :         FmgrInfo   *finfo;
    4393              :         FunctionCallInfo fcinfo;
    4394        47060 :         int         i = foreach_current_index(lc);
    4395              :         Oid         funcid;
    4396        47060 :         Oid         inputcollid = lfirst_oid(lc2);
    4397              : 
    4398        47060 :         funcid = hashfunc_oids[i];
    4399              : 
    4400              :         /* Allocate hash function lookup data. */
    4401        47060 :         finfo = palloc0_object(FmgrInfo);
    4402        47060 :         fcinfo = palloc0(SizeForFunctionCallInfo(1));
    4403              : 
    4404        47060 :         fmgr_info(funcid, finfo);
    4405              : 
    4406              :         /*
    4407              :          * Build the steps to evaluate the hash function's argument have it so
    4408              :          * the value of that is stored in the 0th argument of the hash func.
    4409              :          */
    4410        47060 :         ExecInitExprRec(expr,
    4411              :                         state,
    4412              :                         &fcinfo->args[0].value,
    4413              :                         &fcinfo->args[0].isnull);
    4414              : 
    4415        47060 :         if (i == num_exprs - 1)
    4416              :         {
    4417              :             /* the result for hashing the final expr is stored in the state */
    4418        43486 :             scratch.resvalue = &state->resvalue;
    4419        43486 :             scratch.resnull = &state->resnull;
    4420              :         }
    4421              :         else
    4422              :         {
    4423              :             Assert(iresult != NULL);
    4424              : 
    4425              :             /* intermediate values are stored in an intermediate result */
    4426         3574 :             scratch.resvalue = &iresult->value;
    4427         3574 :             scratch.resnull = &iresult->isnull;
    4428              :         }
    4429              : 
    4430              :         /*
    4431              :          * NEXT32 opcodes need to look at the intermediate result.  We might
    4432              :          * as well just set this for all ops.  FIRSTs won't look at it.
    4433              :          */
    4434        47060 :         scratch.d.hashdatum.iresult = iresult;
    4435              : 
    4436              :         /* Initialize function call parameter structure too */
    4437        47060 :         InitFunctionCallInfoData(*fcinfo, finfo, 1, inputcollid, NULL, NULL);
    4438              : 
    4439        47060 :         scratch.d.hashdatum.finfo = finfo;
    4440        47060 :         scratch.d.hashdatum.fcinfo_data = fcinfo;
    4441        47060 :         scratch.d.hashdatum.fn_addr = finfo->fn_addr;
    4442              : 
    4443        47060 :         scratch.opcode = opstrict[i] && !keep_nulls ? strict_opcode : opcode;
    4444        47060 :         scratch.d.hashdatum.jumpdone = -1;
    4445              : 
    4446        47060 :         ExprEvalPushStep(state, &scratch);
    4447        47060 :         adjust_jumps = lappend_int(adjust_jumps, state->steps_len - 1);
    4448              : 
    4449              :         /*
    4450              :          * For subsequent keys we must combine the hash value with the
    4451              :          * previous hashes.
    4452              :          */
    4453        47060 :         strict_opcode = EEOP_HASHDATUM_NEXT32_STRICT;
    4454        47060 :         opcode = EEOP_HASHDATUM_NEXT32;
    4455              :     }
    4456              : 
    4457              :     /* adjust jump targets */
    4458        90546 :     foreach(lc, adjust_jumps)
    4459              :     {
    4460        47060 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    4461              : 
    4462              :         Assert(as->opcode == EEOP_HASHDATUM_FIRST ||
    4463              :                as->opcode == EEOP_HASHDATUM_FIRST_STRICT ||
    4464              :                as->opcode == EEOP_HASHDATUM_NEXT32 ||
    4465              :                as->opcode == EEOP_HASHDATUM_NEXT32_STRICT);
    4466              :         Assert(as->d.hashdatum.jumpdone == -1);
    4467        47060 :         as->d.hashdatum.jumpdone = state->steps_len;
    4468              :     }
    4469              : 
    4470        43486 :     scratch.resvalue = NULL;
    4471        43486 :     scratch.resnull = NULL;
    4472        43486 :     scratch.opcode = EEOP_DONE_RETURN;
    4473        43486 :     ExprEvalPushStep(state, &scratch);
    4474              : 
    4475        43486 :     ExecReadyExpr(state);
    4476              : 
    4477        43486 :     return state;
    4478              : }
    4479              : 
    4480              : /*
    4481              :  * Build equality expression that can be evaluated using ExecQual(), returning
    4482              :  * true if the expression context's inner/outer tuple are NOT DISTINCT. I.e
    4483              :  * two nulls match, a null and a not-null don't match.
    4484              :  *
    4485              :  * desc: tuple descriptor of the to-be-compared tuples
    4486              :  * numCols: the number of attributes to be examined
    4487              :  * keyColIdx: array of attribute column numbers
    4488              :  * eqFunctions: array of function oids of the equality functions to use
    4489              :  * parent: parent executor node
    4490              :  */
    4491              : ExprState *
    4492        10752 : ExecBuildGroupingEqual(TupleDesc ldesc, TupleDesc rdesc,
    4493              :                        const TupleTableSlotOps *lops, const TupleTableSlotOps *rops,
    4494              :                        int numCols,
    4495              :                        const AttrNumber *keyColIdx,
    4496              :                        const Oid *eqfunctions,
    4497              :                        const Oid *collations,
    4498              :                        PlanState *parent)
    4499              : {
    4500        10752 :     ExprState  *state = makeNode(ExprState);
    4501        10752 :     ExprEvalStep scratch = {0};
    4502        10752 :     int         maxatt = -1;
    4503        10752 :     List       *adjust_jumps = NIL;
    4504              :     ListCell   *lc;
    4505              : 
    4506              :     /*
    4507              :      * When no columns are actually compared, the result's always true. See
    4508              :      * special case in ExecQual().
    4509              :      */
    4510        10752 :     if (numCols == 0)
    4511            0 :         return NULL;
    4512              : 
    4513        10752 :     state->expr = NULL;
    4514        10752 :     state->flags = EEO_FLAG_IS_QUAL;
    4515        10752 :     state->parent = parent;
    4516              : 
    4517        10752 :     scratch.resvalue = &state->resvalue;
    4518        10752 :     scratch.resnull = &state->resnull;
    4519              : 
    4520              :     /* compute max needed attribute */
    4521        29096 :     for (int natt = 0; natt < numCols; natt++)
    4522              :     {
    4523        18344 :         int         attno = keyColIdx[natt];
    4524              : 
    4525        18344 :         if (attno > maxatt)
    4526        18155 :             maxatt = attno;
    4527              :     }
    4528              :     Assert(maxatt >= 0);
    4529              : 
    4530              :     /* push deform steps */
    4531        10752 :     scratch.opcode = EEOP_INNER_FETCHSOME;
    4532        10752 :     scratch.d.fetch.last_var = maxatt;
    4533        10752 :     scratch.d.fetch.fixed = false;
    4534        10752 :     scratch.d.fetch.known_desc = ldesc;
    4535        10752 :     scratch.d.fetch.kind = lops;
    4536        10752 :     if (ExecComputeSlotInfo(state, &scratch))
    4537         9134 :         ExprEvalPushStep(state, &scratch);
    4538              : 
    4539        10752 :     scratch.opcode = EEOP_OUTER_FETCHSOME;
    4540        10752 :     scratch.d.fetch.last_var = maxatt;
    4541        10752 :     scratch.d.fetch.fixed = false;
    4542        10752 :     scratch.d.fetch.known_desc = rdesc;
    4543        10752 :     scratch.d.fetch.kind = rops;
    4544        10752 :     if (ExecComputeSlotInfo(state, &scratch))
    4545        10752 :         ExprEvalPushStep(state, &scratch);
    4546              : 
    4547              :     /*
    4548              :      * Start comparing at the last field (least significant sort key). That's
    4549              :      * the most likely to be different if we are dealing with sorted input.
    4550              :      */
    4551        29096 :     for (int natt = numCols; --natt >= 0;)
    4552              :     {
    4553        18344 :         int         attno = keyColIdx[natt];
    4554        18344 :         Form_pg_attribute latt = TupleDescAttr(ldesc, attno - 1);
    4555        18344 :         Form_pg_attribute ratt = TupleDescAttr(rdesc, attno - 1);
    4556        18344 :         Oid         foid = eqfunctions[natt];
    4557        18344 :         Oid         collid = collations[natt];
    4558              :         FmgrInfo   *finfo;
    4559              :         FunctionCallInfo fcinfo;
    4560              :         AclResult   aclresult;
    4561              : 
    4562              :         /* Check permission to call function */
    4563        18344 :         aclresult = object_aclcheck(ProcedureRelationId, foid, GetUserId(), ACL_EXECUTE);
    4564        18344 :         if (aclresult != ACLCHECK_OK)
    4565            0 :             aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
    4566              : 
    4567        18344 :         InvokeFunctionExecuteHook(foid);
    4568              : 
    4569              :         /* Set up the primary fmgr lookup information */
    4570        18344 :         finfo = palloc0_object(FmgrInfo);
    4571        18344 :         fcinfo = palloc0(SizeForFunctionCallInfo(2));
    4572        18344 :         fmgr_info(foid, finfo);
    4573        18344 :         fmgr_info_set_expr(NULL, finfo);
    4574        18344 :         InitFunctionCallInfoData(*fcinfo, finfo, 2,
    4575              :                                  collid, NULL, NULL);
    4576              : 
    4577              :         /* left arg */
    4578        18344 :         scratch.opcode = EEOP_INNER_VAR;
    4579        18344 :         scratch.d.var.attnum = attno - 1;
    4580        18344 :         scratch.d.var.vartype = latt->atttypid;
    4581        18344 :         scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
    4582        18344 :         scratch.resvalue = &fcinfo->args[0].value;
    4583        18344 :         scratch.resnull = &fcinfo->args[0].isnull;
    4584        18344 :         ExprEvalPushStep(state, &scratch);
    4585              : 
    4586              :         /* right arg */
    4587        18344 :         scratch.opcode = EEOP_OUTER_VAR;
    4588        18344 :         scratch.d.var.attnum = attno - 1;
    4589        18344 :         scratch.d.var.vartype = ratt->atttypid;
    4590        18344 :         scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
    4591        18344 :         scratch.resvalue = &fcinfo->args[1].value;
    4592        18344 :         scratch.resnull = &fcinfo->args[1].isnull;
    4593        18344 :         ExprEvalPushStep(state, &scratch);
    4594              : 
    4595              :         /* evaluate distinctness */
    4596        18344 :         scratch.opcode = EEOP_NOT_DISTINCT;
    4597        18344 :         scratch.d.func.finfo = finfo;
    4598        18344 :         scratch.d.func.fcinfo_data = fcinfo;
    4599        18344 :         scratch.d.func.fn_addr = finfo->fn_addr;
    4600        18344 :         scratch.d.func.nargs = 2;
    4601        18344 :         scratch.resvalue = &state->resvalue;
    4602        18344 :         scratch.resnull = &state->resnull;
    4603        18344 :         ExprEvalPushStep(state, &scratch);
    4604              : 
    4605              :         /* then emit EEOP_QUAL to detect if result is false (or null) */
    4606        18344 :         scratch.opcode = EEOP_QUAL;
    4607        18344 :         scratch.d.qualexpr.jumpdone = -1;
    4608        18344 :         scratch.resvalue = &state->resvalue;
    4609        18344 :         scratch.resnull = &state->resnull;
    4610        18344 :         ExprEvalPushStep(state, &scratch);
    4611        18344 :         adjust_jumps = lappend_int(adjust_jumps,
    4612        18344 :                                    state->steps_len - 1);
    4613              :     }
    4614              : 
    4615              :     /* adjust jump targets */
    4616        29096 :     foreach(lc, adjust_jumps)
    4617              :     {
    4618        18344 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    4619              : 
    4620              :         Assert(as->opcode == EEOP_QUAL);
    4621              :         Assert(as->d.qualexpr.jumpdone == -1);
    4622        18344 :         as->d.qualexpr.jumpdone = state->steps_len;
    4623              :     }
    4624              : 
    4625        10752 :     scratch.resvalue = NULL;
    4626        10752 :     scratch.resnull = NULL;
    4627        10752 :     scratch.opcode = EEOP_DONE_RETURN;
    4628        10752 :     ExprEvalPushStep(state, &scratch);
    4629              : 
    4630        10752 :     ExecReadyExpr(state);
    4631              : 
    4632        10752 :     return state;
    4633              : }
    4634              : 
    4635              : /*
    4636              :  * Build equality expression that can be evaluated using ExecQual(), returning
    4637              :  * true if the expression context's inner/outer tuples are equal.  Datums in
    4638              :  * the inner/outer slots are assumed to be in the same order and quantity as
    4639              :  * the 'eqfunctions' parameter.  NULLs are treated as equal.
    4640              :  *
    4641              :  * desc: tuple descriptor of the to-be-compared tuples
    4642              :  * lops: the slot ops for the inner tuple slots
    4643              :  * rops: the slot ops for the outer tuple slots
    4644              :  * eqFunctions: array of function oids of the equality functions to use
    4645              :  * this must be the same length as the 'param_exprs' list.
    4646              :  * collations: collation Oids to use for equality comparison. Must be the
    4647              :  * same length as the 'param_exprs' list.
    4648              :  * parent: parent executor node
    4649              :  */
    4650              : ExprState *
    4651          992 : ExecBuildParamSetEqual(TupleDesc desc,
    4652              :                        const TupleTableSlotOps *lops,
    4653              :                        const TupleTableSlotOps *rops,
    4654              :                        const Oid *eqfunctions,
    4655              :                        const Oid *collations,
    4656              :                        const List *param_exprs,
    4657              :                        PlanState *parent)
    4658              : {
    4659          992 :     ExprState  *state = makeNode(ExprState);
    4660          992 :     ExprEvalStep scratch = {0};
    4661          992 :     int         maxatt = list_length(param_exprs);
    4662          992 :     List       *adjust_jumps = NIL;
    4663              :     ListCell   *lc;
    4664              : 
    4665          992 :     state->expr = NULL;
    4666          992 :     state->flags = EEO_FLAG_IS_QUAL;
    4667          992 :     state->parent = parent;
    4668              : 
    4669          992 :     scratch.resvalue = &state->resvalue;
    4670          992 :     scratch.resnull = &state->resnull;
    4671              : 
    4672              :     /* push deform steps */
    4673          992 :     scratch.opcode = EEOP_INNER_FETCHSOME;
    4674          992 :     scratch.d.fetch.last_var = maxatt;
    4675          992 :     scratch.d.fetch.fixed = false;
    4676          992 :     scratch.d.fetch.known_desc = desc;
    4677          992 :     scratch.d.fetch.kind = lops;
    4678          992 :     if (ExecComputeSlotInfo(state, &scratch))
    4679          992 :         ExprEvalPushStep(state, &scratch);
    4680              : 
    4681          992 :     scratch.opcode = EEOP_OUTER_FETCHSOME;
    4682          992 :     scratch.d.fetch.last_var = maxatt;
    4683          992 :     scratch.d.fetch.fixed = false;
    4684          992 :     scratch.d.fetch.known_desc = desc;
    4685          992 :     scratch.d.fetch.kind = rops;
    4686          992 :     if (ExecComputeSlotInfo(state, &scratch))
    4687            0 :         ExprEvalPushStep(state, &scratch);
    4688              : 
    4689         2015 :     for (int attno = 0; attno < maxatt; attno++)
    4690              :     {
    4691         1023 :         Form_pg_attribute att = TupleDescAttr(desc, attno);
    4692         1023 :         Oid         foid = eqfunctions[attno];
    4693         1023 :         Oid         collid = collations[attno];
    4694              :         FmgrInfo   *finfo;
    4695              :         FunctionCallInfo fcinfo;
    4696              :         AclResult   aclresult;
    4697              : 
    4698              :         /* Check permission to call function */
    4699         1023 :         aclresult = object_aclcheck(ProcedureRelationId, foid, GetUserId(), ACL_EXECUTE);
    4700         1023 :         if (aclresult != ACLCHECK_OK)
    4701            0 :             aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
    4702              : 
    4703         1023 :         InvokeFunctionExecuteHook(foid);
    4704              : 
    4705              :         /* Set up the primary fmgr lookup information */
    4706         1023 :         finfo = palloc0_object(FmgrInfo);
    4707         1023 :         fcinfo = palloc0(SizeForFunctionCallInfo(2));
    4708         1023 :         fmgr_info(foid, finfo);
    4709         1023 :         fmgr_info_set_expr(NULL, finfo);
    4710         1023 :         InitFunctionCallInfoData(*fcinfo, finfo, 2,
    4711              :                                  collid, NULL, NULL);
    4712              : 
    4713              :         /* left arg */
    4714         1023 :         scratch.opcode = EEOP_INNER_VAR;
    4715         1023 :         scratch.d.var.attnum = attno;
    4716         1023 :         scratch.d.var.vartype = att->atttypid;
    4717         1023 :         scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
    4718         1023 :         scratch.resvalue = &fcinfo->args[0].value;
    4719         1023 :         scratch.resnull = &fcinfo->args[0].isnull;
    4720         1023 :         ExprEvalPushStep(state, &scratch);
    4721              : 
    4722              :         /* right arg */
    4723         1023 :         scratch.opcode = EEOP_OUTER_VAR;
    4724         1023 :         scratch.d.var.attnum = attno;
    4725         1023 :         scratch.d.var.vartype = att->atttypid;
    4726         1023 :         scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
    4727         1023 :         scratch.resvalue = &fcinfo->args[1].value;
    4728         1023 :         scratch.resnull = &fcinfo->args[1].isnull;
    4729         1023 :         ExprEvalPushStep(state, &scratch);
    4730              : 
    4731              :         /* evaluate distinctness */
    4732         1023 :         scratch.opcode = EEOP_NOT_DISTINCT;
    4733         1023 :         scratch.d.func.finfo = finfo;
    4734         1023 :         scratch.d.func.fcinfo_data = fcinfo;
    4735         1023 :         scratch.d.func.fn_addr = finfo->fn_addr;
    4736         1023 :         scratch.d.func.nargs = 2;
    4737         1023 :         scratch.resvalue = &state->resvalue;
    4738         1023 :         scratch.resnull = &state->resnull;
    4739         1023 :         ExprEvalPushStep(state, &scratch);
    4740              : 
    4741              :         /* then emit EEOP_QUAL to detect if result is false (or null) */
    4742         1023 :         scratch.opcode = EEOP_QUAL;
    4743         1023 :         scratch.d.qualexpr.jumpdone = -1;
    4744         1023 :         scratch.resvalue = &state->resvalue;
    4745         1023 :         scratch.resnull = &state->resnull;
    4746         1023 :         ExprEvalPushStep(state, &scratch);
    4747         1023 :         adjust_jumps = lappend_int(adjust_jumps,
    4748         1023 :                                    state->steps_len - 1);
    4749              :     }
    4750              : 
    4751              :     /* adjust jump targets */
    4752         2015 :     foreach(lc, adjust_jumps)
    4753              :     {
    4754         1023 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    4755              : 
    4756              :         Assert(as->opcode == EEOP_QUAL);
    4757              :         Assert(as->d.qualexpr.jumpdone == -1);
    4758         1023 :         as->d.qualexpr.jumpdone = state->steps_len;
    4759              :     }
    4760              : 
    4761          992 :     scratch.resvalue = NULL;
    4762          992 :     scratch.resnull = NULL;
    4763          992 :     scratch.opcode = EEOP_DONE_RETURN;
    4764          992 :     ExprEvalPushStep(state, &scratch);
    4765              : 
    4766          992 :     ExecReadyExpr(state);
    4767              : 
    4768          992 :     return state;
    4769              : }
    4770              : 
    4771              : /*
    4772              :  * Push steps to evaluate a JsonExpr and its various subsidiary expressions.
    4773              :  */
    4774              : static void
    4775         1156 : ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state,
    4776              :                  Datum *resv, bool *resnull,
    4777              :                  ExprEvalStep *scratch)
    4778              : {
    4779         1156 :     JsonExprState *jsestate = palloc0_object(JsonExprState);
    4780              :     ListCell   *argexprlc;
    4781              :     ListCell   *argnamelc;
    4782         1156 :     List       *jumps_return_null = NIL;
    4783         1156 :     List       *jumps_to_end = NIL;
    4784              :     ListCell   *lc;
    4785              :     ErrorSaveContext *escontext;
    4786         1156 :     bool        returning_domain =
    4787         1156 :         get_typtype(jsexpr->returning->typid) == TYPTYPE_DOMAIN;
    4788              : 
    4789              :     Assert(jsexpr->on_error != NULL);
    4790              : 
    4791         1156 :     jsestate->jsexpr = jsexpr;
    4792              : 
    4793              :     /*
    4794              :      * Evaluate formatted_expr storing the result into
    4795              :      * jsestate->formatted_expr.
    4796              :      */
    4797         1156 :     ExecInitExprRec((Expr *) jsexpr->formatted_expr, state,
    4798              :                     &jsestate->formatted_expr.value,
    4799              :                     &jsestate->formatted_expr.isnull);
    4800              : 
    4801              :     /* JUMP to return NULL if formatted_expr evaluates to NULL */
    4802         1156 :     jumps_return_null = lappend_int(jumps_return_null, state->steps_len);
    4803         1156 :     scratch->opcode = EEOP_JUMP_IF_NULL;
    4804         1156 :     scratch->resnull = &jsestate->formatted_expr.isnull;
    4805         1156 :     scratch->d.jump.jumpdone = -1;   /* set below */
    4806         1156 :     ExprEvalPushStep(state, scratch);
    4807              : 
    4808              :     /*
    4809              :      * Evaluate pathspec expression storing the result into
    4810              :      * jsestate->pathspec.
    4811              :      */
    4812         1156 :     ExecInitExprRec((Expr *) jsexpr->path_spec, state,
    4813              :                     &jsestate->pathspec.value,
    4814              :                     &jsestate->pathspec.isnull);
    4815              : 
    4816              :     /* JUMP to return NULL if path_spec evaluates to NULL */
    4817         1156 :     jumps_return_null = lappend_int(jumps_return_null, state->steps_len);
    4818         1156 :     scratch->opcode = EEOP_JUMP_IF_NULL;
    4819         1156 :     scratch->resnull = &jsestate->pathspec.isnull;
    4820         1156 :     scratch->d.jump.jumpdone = -1;   /* set below */
    4821         1156 :     ExprEvalPushStep(state, scratch);
    4822              : 
    4823              :     /* Steps to compute PASSING args. */
    4824         1156 :     jsestate->args = NIL;
    4825         1609 :     forboth(argexprlc, jsexpr->passing_values,
    4826              :             argnamelc, jsexpr->passing_names)
    4827              :     {
    4828          453 :         Expr       *argexpr = (Expr *) lfirst(argexprlc);
    4829          453 :         String     *argname = lfirst_node(String, argnamelc);
    4830          453 :         JsonPathVariable *var = palloc_object(JsonPathVariable);
    4831              : 
    4832          453 :         var->name = argname->sval;
    4833          453 :         var->namelen = strlen(var->name);
    4834          453 :         var->typid = exprType((Node *) argexpr);
    4835          453 :         var->typmod = exprTypmod((Node *) argexpr);
    4836              : 
    4837          453 :         ExecInitExprRec(argexpr, state, &var->value, &var->isnull);
    4838              : 
    4839          453 :         jsestate->args = lappend(jsestate->args, var);
    4840              :     }
    4841              : 
    4842              :     /* Step for jsonpath evaluation; see ExecEvalJsonExprPath(). */
    4843         1156 :     scratch->opcode = EEOP_JSONEXPR_PATH;
    4844         1156 :     scratch->resvalue = resv;
    4845         1156 :     scratch->resnull = resnull;
    4846         1156 :     scratch->d.jsonexpr.jsestate = jsestate;
    4847         1156 :     ExprEvalPushStep(state, scratch);
    4848              : 
    4849              :     /*
    4850              :      * Step to return NULL after jumping to skip the EEOP_JSONEXPR_PATH step
    4851              :      * when either formatted_expr or pathspec is NULL.  Adjust jump target
    4852              :      * addresses of JUMPs that we added above.
    4853              :      */
    4854         3468 :     foreach(lc, jumps_return_null)
    4855              :     {
    4856         2312 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    4857              : 
    4858         2312 :         as->d.jump.jumpdone = state->steps_len;
    4859              :     }
    4860         1156 :     scratch->opcode = EEOP_CONST;
    4861         1156 :     scratch->resvalue = resv;
    4862         1156 :     scratch->resnull = resnull;
    4863         1156 :     scratch->d.constval.value = (Datum) 0;
    4864         1156 :     scratch->d.constval.isnull = true;
    4865         1156 :     ExprEvalPushStep(state, scratch);
    4866              : 
    4867         2312 :     escontext = jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR ?
    4868         1156 :         &jsestate->escontext : NULL;
    4869              : 
    4870              :     /*
    4871              :      * To handle coercion errors softly, use the following ErrorSaveContext to
    4872              :      * pass to ExecInitExprRec() when initializing the coercion expressions
    4873              :      * and in the EEOP_JSONEXPR_COERCION step.
    4874              :      */
    4875         1156 :     jsestate->escontext.type = T_ErrorSaveContext;
    4876              : 
    4877              :     /*
    4878              :      * Steps to coerce the result value computed by EEOP_JSONEXPR_PATH or the
    4879              :      * NULL returned on NULL input as described above.
    4880              :      */
    4881         1156 :     jsestate->jump_eval_coercion = -1;
    4882         1156 :     if (jsexpr->use_json_coercion)
    4883              :     {
    4884          444 :         jsestate->jump_eval_coercion = state->steps_len;
    4885              : 
    4886          444 :         ExecInitJsonCoercion(state, jsexpr->returning, escontext,
    4887          444 :                              jsexpr->omit_quotes,
    4888          444 :                              jsexpr->op == JSON_EXISTS_OP,
    4889              :                              resv, resnull);
    4890              :     }
    4891          712 :     else if (jsexpr->use_io_coercion)
    4892              :     {
    4893              :         /*
    4894              :          * Here we only need to initialize the FunctionCallInfo for the target
    4895              :          * type's input function, which is called by ExecEvalJsonExprPath()
    4896              :          * itself, so no additional step is necessary.
    4897              :          */
    4898              :         Oid         typinput;
    4899              :         Oid         typioparam;
    4900              :         FmgrInfo   *finfo;
    4901              :         FunctionCallInfo fcinfo;
    4902              : 
    4903          325 :         getTypeInputInfo(jsexpr->returning->typid, &typinput, &typioparam);
    4904          325 :         finfo = palloc0_object(FmgrInfo);
    4905          325 :         fcinfo = palloc0(SizeForFunctionCallInfo(3));
    4906          325 :         fmgr_info(typinput, finfo);
    4907          325 :         fmgr_info_set_expr((Node *) jsexpr->returning, finfo);
    4908          325 :         InitFunctionCallInfoData(*fcinfo, finfo, 3, InvalidOid, NULL, NULL);
    4909              : 
    4910              :         /*
    4911              :          * We can preload the second and third arguments for the input
    4912              :          * function, since they're constants.
    4913              :          */
    4914          325 :         fcinfo->args[1].value = ObjectIdGetDatum(typioparam);
    4915          325 :         fcinfo->args[1].isnull = false;
    4916          325 :         fcinfo->args[2].value = Int32GetDatum(jsexpr->returning->typmod);
    4917          325 :         fcinfo->args[2].isnull = false;
    4918          325 :         fcinfo->context = (Node *) escontext;
    4919              : 
    4920          325 :         jsestate->input_fcinfo = fcinfo;
    4921              :     }
    4922              : 
    4923              :     /*
    4924              :      * Add a special step, if needed, to check if the coercion evaluation ran
    4925              :      * into an error but was not thrown because the ON ERROR behavior is not
    4926              :      * ERROR.  It will set jsestate->error if an error did occur.
    4927              :      */
    4928         1156 :     if (jsestate->jump_eval_coercion >= 0 && escontext != NULL)
    4929              :     {
    4930          333 :         scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
    4931          333 :         scratch->d.jsonexpr.jsestate = jsestate;
    4932          333 :         ExprEvalPushStep(state, scratch);
    4933              :     }
    4934              : 
    4935         1156 :     jsestate->jump_empty = jsestate->jump_error = -1;
    4936              : 
    4937              :     /*
    4938              :      * Step to check jsestate->error and return the ON ERROR expression if
    4939              :      * there is one.  This handles both the errors that occur during jsonpath
    4940              :      * evaluation in EEOP_JSONEXPR_PATH and subsequent coercion evaluation.
    4941              :      *
    4942              :      * Speed up common cases by avoiding extra steps for a NULL-valued ON
    4943              :      * ERROR expression unless RETURNING a domain type, where constraints must
    4944              :      * be checked. ExecEvalJsonExprPath() already returns NULL on error,
    4945              :      * making additional steps unnecessary in typical scenarios. Note that the
    4946              :      * default ON ERROR behavior for JSON_VALUE() and JSON_QUERY() is to
    4947              :      * return NULL.
    4948              :      */
    4949         1156 :     if (jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR &&
    4950          943 :         (!(IsA(jsexpr->on_error->expr, Const) &&
    4951          919 :            ((Const *) jsexpr->on_error->expr)->constisnull) ||
    4952              :          returning_domain))
    4953              :     {
    4954              :         ErrorSaveContext *saved_escontext;
    4955              : 
    4956          297 :         jsestate->jump_error = state->steps_len;
    4957              : 
    4958              :         /* JUMP to end if false, that is, skip the ON ERROR expression. */
    4959          297 :         jumps_to_end = lappend_int(jumps_to_end, state->steps_len);
    4960          297 :         scratch->opcode = EEOP_JUMP_IF_NOT_TRUE;
    4961          297 :         scratch->resvalue = &jsestate->error.value;
    4962          297 :         scratch->resnull = &jsestate->error.isnull;
    4963          297 :         scratch->d.jump.jumpdone = -1;   /* set below */
    4964          297 :         ExprEvalPushStep(state, scratch);
    4965              : 
    4966              :         /*
    4967              :          * Steps to evaluate the ON ERROR expression; handle errors softly to
    4968              :          * rethrow them in COERCION_FINISH step that will be added later.
    4969              :          */
    4970          297 :         saved_escontext = state->escontext;
    4971          297 :         state->escontext = escontext;
    4972          297 :         ExecInitExprRec((Expr *) jsexpr->on_error->expr,
    4973              :                         state, resv, resnull);
    4974          297 :         state->escontext = saved_escontext;
    4975              : 
    4976              :         /* Step to coerce the ON ERROR expression if needed */
    4977          297 :         if (jsexpr->on_error->coerce)
    4978           87 :             ExecInitJsonCoercion(state, jsexpr->returning, escontext,
    4979           87 :                                  jsexpr->omit_quotes, false,
    4980              :                                  resv, resnull);
    4981              : 
    4982              :         /*
    4983              :          * Add a COERCION_FINISH step to check for errors that may occur when
    4984              :          * coercing and rethrow them.
    4985              :          */
    4986          297 :         if (jsexpr->on_error->coerce ||
    4987          210 :             IsA(jsexpr->on_error->expr, CoerceViaIO) ||
    4988          210 :             IsA(jsexpr->on_error->expr, CoerceToDomain))
    4989              :         {
    4990          111 :             scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
    4991          111 :             scratch->resvalue = resv;
    4992          111 :             scratch->resnull = resnull;
    4993          111 :             scratch->d.jsonexpr.jsestate = jsestate;
    4994          111 :             ExprEvalPushStep(state, scratch);
    4995              :         }
    4996              : 
    4997              :         /* JUMP to end to skip the ON EMPTY steps added below. */
    4998          297 :         jumps_to_end = lappend_int(jumps_to_end, state->steps_len);
    4999          297 :         scratch->opcode = EEOP_JUMP;
    5000          297 :         scratch->d.jump.jumpdone = -1;
    5001          297 :         ExprEvalPushStep(state, scratch);
    5002              :     }
    5003              : 
    5004              :     /*
    5005              :      * Step to check jsestate->empty and return the ON EMPTY expression if
    5006              :      * there is one.
    5007              :      *
    5008              :      * See the comment above for details on the optimization for NULL-valued
    5009              :      * expressions.
    5010              :      */
    5011         1156 :     if (jsexpr->on_empty != NULL &&
    5012          994 :         jsexpr->on_empty->btype != JSON_BEHAVIOR_ERROR &&
    5013          961 :         (!(IsA(jsexpr->on_empty->expr, Const) &&
    5014          934 :            ((Const *) jsexpr->on_empty->expr)->constisnull) ||
    5015              :          returning_domain))
    5016              :     {
    5017              :         ErrorSaveContext *saved_escontext;
    5018              : 
    5019          192 :         jsestate->jump_empty = state->steps_len;
    5020              : 
    5021              :         /* JUMP to end if false, that is, skip the ON EMPTY expression. */
    5022          192 :         jumps_to_end = lappend_int(jumps_to_end, state->steps_len);
    5023          192 :         scratch->opcode = EEOP_JUMP_IF_NOT_TRUE;
    5024          192 :         scratch->resvalue = &jsestate->empty.value;
    5025          192 :         scratch->resnull = &jsestate->empty.isnull;
    5026          192 :         scratch->d.jump.jumpdone = -1;   /* set below */
    5027          192 :         ExprEvalPushStep(state, scratch);
    5028              : 
    5029              :         /*
    5030              :          * Steps to evaluate the ON EMPTY expression; handle errors softly to
    5031              :          * rethrow them in COERCION_FINISH step that will be added later.
    5032              :          */
    5033          192 :         saved_escontext = state->escontext;
    5034          192 :         state->escontext = escontext;
    5035          192 :         ExecInitExprRec((Expr *) jsexpr->on_empty->expr,
    5036              :                         state, resv, resnull);
    5037          192 :         state->escontext = saved_escontext;
    5038              : 
    5039              :         /* Step to coerce the ON EMPTY expression if needed */
    5040          192 :         if (jsexpr->on_empty->coerce)
    5041           87 :             ExecInitJsonCoercion(state, jsexpr->returning, escontext,
    5042           87 :                                  jsexpr->omit_quotes, false,
    5043              :                                  resv, resnull);
    5044              : 
    5045              :         /*
    5046              :          * Add a COERCION_FINISH step to check for errors that may occur when
    5047              :          * coercing and rethrow them.
    5048              :          */
    5049          192 :         if (jsexpr->on_empty->coerce ||
    5050          105 :             IsA(jsexpr->on_empty->expr, CoerceViaIO) ||
    5051          105 :             IsA(jsexpr->on_empty->expr, CoerceToDomain))
    5052              :         {
    5053              : 
    5054          114 :             scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
    5055          114 :             scratch->resvalue = resv;
    5056          114 :             scratch->resnull = resnull;
    5057          114 :             scratch->d.jsonexpr.jsestate = jsestate;
    5058          114 :             ExprEvalPushStep(state, scratch);
    5059              :         }
    5060              :     }
    5061              : 
    5062         1942 :     foreach(lc, jumps_to_end)
    5063              :     {
    5064          786 :         ExprEvalStep *as = &state->steps[lfirst_int(lc)];
    5065              : 
    5066          786 :         as->d.jump.jumpdone = state->steps_len;
    5067              :     }
    5068              : 
    5069         1156 :     jsestate->jump_end = state->steps_len;
    5070         1156 : }
    5071              : 
    5072              : /*
    5073              :  * Initialize a EEOP_JSONEXPR_COERCION step to coerce the value given in resv
    5074              :  * to the given RETURNING type.
    5075              :  */
    5076              : static void
    5077          618 : ExecInitJsonCoercion(ExprState *state, JsonReturning *returning,
    5078              :                      ErrorSaveContext *escontext, bool omit_quotes,
    5079              :                      bool exists_coerce,
    5080              :                      Datum *resv, bool *resnull)
    5081              : {
    5082          618 :     ExprEvalStep scratch = {0};
    5083              : 
    5084              :     /* For json_populate_type() */
    5085          618 :     scratch.opcode = EEOP_JSONEXPR_COERCION;
    5086          618 :     scratch.resvalue = resv;
    5087          618 :     scratch.resnull = resnull;
    5088          618 :     scratch.d.jsonexpr_coercion.targettype = returning->typid;
    5089          618 :     scratch.d.jsonexpr_coercion.targettypmod = returning->typmod;
    5090          618 :     scratch.d.jsonexpr_coercion.json_coercion_cache = NULL;
    5091          618 :     scratch.d.jsonexpr_coercion.escontext = escontext;
    5092          618 :     scratch.d.jsonexpr_coercion.omit_quotes = omit_quotes;
    5093          618 :     scratch.d.jsonexpr_coercion.exists_coerce = exists_coerce;
    5094          678 :     scratch.d.jsonexpr_coercion.exists_cast_to_int = exists_coerce &&
    5095           60 :         getBaseType(returning->typid) == INT4OID;
    5096          678 :     scratch.d.jsonexpr_coercion.exists_check_domain = exists_coerce &&
    5097           60 :         DomainHasConstraints(returning->typid, NULL);
    5098          618 :     ExprEvalPushStep(state, &scratch);
    5099          618 : }
        

Generated by: LCOV version 2.0-1