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

Generated by: LCOV version 1.14