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 923004 : ExecInitExpr(Expr *node, PlanState *parent)
144 : {
145 : ExprState *state;
146 923004 : ExprEvalStep scratch = {0};
147 :
148 : /* Special case: NULL expression produces a NULL ExprState pointer */
149 923004 : if (node == NULL)
150 50732 : return NULL;
151 :
152 : /* Initialize ExprState with empty step list */
153 872272 : state = makeNode(ExprState);
154 872272 : state->expr = node;
155 872272 : state->parent = parent;
156 872272 : state->ext_params = NULL;
157 :
158 : /* Insert setup steps as needed */
159 872272 : ExecCreateExprSetupSteps(state, (Node *) node);
160 :
161 : /* Compile the expression proper */
162 872272 : ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
163 :
164 : /* Finally, append a DONE step */
165 872254 : scratch.opcode = EEOP_DONE;
166 872254 : ExprEvalPushStep(state, &scratch);
167 :
168 872254 : ExecReadyExpr(state);
169 :
170 872254 : 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 77378 : ExecInitExprWithParams(Expr *node, ParamListInfo ext_params)
181 : {
182 : ExprState *state;
183 77378 : ExprEvalStep scratch = {0};
184 :
185 : /* Special case: NULL expression produces a NULL ExprState pointer */
186 77378 : if (node == NULL)
187 0 : return NULL;
188 :
189 : /* Initialize ExprState with empty step list */
190 77378 : state = makeNode(ExprState);
191 77378 : state->expr = node;
192 77378 : state->parent = NULL;
193 77378 : state->ext_params = ext_params;
194 :
195 : /* Insert setup steps as needed */
196 77378 : ExecCreateExprSetupSteps(state, (Node *) node);
197 :
198 : /* Compile the expression proper */
199 77378 : ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
200 :
201 : /* Finally, append a DONE step */
202 77378 : scratch.opcode = EEOP_DONE;
203 77378 : ExprEvalPushStep(state, &scratch);
204 :
205 77378 : ExecReadyExpr(state);
206 :
207 77378 : 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 1771828 : ExecInitQual(List *qual, PlanState *parent)
230 : {
231 : ExprState *state;
232 1771828 : ExprEvalStep scratch = {0};
233 1771828 : List *adjust_jumps = NIL;
234 :
235 : /* short-circuit (here and in ExecQual) for empty restriction list */
236 1771828 : if (qual == NIL)
237 1348288 : return NULL;
238 :
239 : Assert(IsA(qual, List));
240 :
241 423540 : state = makeNode(ExprState);
242 423540 : state->expr = (Expr *) qual;
243 423540 : state->parent = parent;
244 423540 : state->ext_params = NULL;
245 :
246 : /* mark expression as to be used with ExecQual() */
247 423540 : state->flags = EEO_FLAG_IS_QUAL;
248 :
249 : /* Insert setup steps as needed */
250 423540 : 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 423540 : scratch.opcode = EEOP_QUAL;
260 :
261 : /*
262 : * We can use ExprState's resvalue/resnull as target for each qual expr.
263 : */
264 423540 : scratch.resvalue = &state->resvalue;
265 423540 : scratch.resnull = &state->resnull;
266 :
267 1362204 : foreach_ptr(Expr, node, qual)
268 : {
269 : /* first evaluate expression */
270 515124 : ExecInitExprRec(node, state, &state->resvalue, &state->resnull);
271 :
272 : /* then emit EEOP_QUAL to detect if it's false (or null) */
273 515124 : scratch.d.qualexpr.jumpdone = -1;
274 515124 : ExprEvalPushStep(state, &scratch);
275 515124 : adjust_jumps = lappend_int(adjust_jumps,
276 515124 : state->steps_len - 1);
277 : }
278 :
279 : /* adjust jump targets */
280 1362204 : foreach_int(jump, adjust_jumps)
281 : {
282 515124 : ExprEvalStep *as = &state->steps[jump];
283 :
284 : Assert(as->opcode == EEOP_QUAL);
285 : Assert(as->d.qualexpr.jumpdone == -1);
286 515124 : 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 423540 : scratch.opcode = EEOP_DONE;
295 423540 : ExprEvalPushStep(state, &scratch);
296 :
297 423540 : ExecReadyExpr(state);
298 :
299 423540 : 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 5490 : ExecInitCheck(List *qual, PlanState *parent)
316 : {
317 : /* short-circuit (here and in ExecCheck) for empty restriction list */
318 5490 : 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 5394 : 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 437404 : ExecInitExprList(List *nodes, PlanState *parent)
336 : {
337 437404 : List *result = NIL;
338 : ListCell *lc;
339 :
340 796876 : foreach(lc, nodes)
341 : {
342 359472 : Expr *e = lfirst(lc);
343 :
344 359472 : result = lappend(result, ExecInitExpr(e, parent));
345 : }
346 :
347 437404 : 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 756174 : ExecBuildProjectionInfo(List *targetList,
371 : ExprContext *econtext,
372 : TupleTableSlot *slot,
373 : PlanState *parent,
374 : TupleDesc inputDesc)
375 : {
376 756174 : ProjectionInfo *projInfo = makeNode(ProjectionInfo);
377 : ExprState *state;
378 756174 : ExprEvalStep scratch = {0};
379 : ListCell *lc;
380 :
381 756174 : projInfo->pi_exprContext = econtext;
382 : /* We embed ExprState into ProjectionInfo instead of doing extra palloc */
383 756174 : projInfo->pi_state.type = T_ExprState;
384 756174 : state = &projInfo->pi_state;
385 756174 : state->expr = (Expr *) targetList;
386 756174 : state->parent = parent;
387 756174 : state->ext_params = NULL;
388 :
389 756174 : state->resultslot = slot;
390 :
391 : /* Insert setup steps as needed */
392 756174 : ExecCreateExprSetupSteps(state, (Node *) targetList);
393 :
394 : /* Now compile each tlist column */
395 2614500 : foreach(lc, targetList)
396 : {
397 1858388 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
398 1858388 : Var *variable = NULL;
399 1858388 : AttrNumber attnum = 0;
400 1858388 : 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 1858388 : if (tle->expr != NULL &&
411 1858388 : IsA(tle->expr, Var) &&
412 1068376 : ((Var *) tle->expr)->varattno > 0)
413 : {
414 : /* Non-system Var, but how safe is it? */
415 989434 : variable = (Var *) tle->expr;
416 989434 : attnum = variable->varattno;
417 :
418 989434 : if (inputDesc == NULL)
419 578146 : isSafeVar = true; /* can't check, just assume OK */
420 411288 : else if (attnum <= inputDesc->natts)
421 : {
422 410680 : 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 410680 : if (!attr->attisdropped && variable->vartype == attr->atttypid)
430 : {
431 409782 : isSafeVar = true;
432 : }
433 : }
434 : }
435 :
436 1858388 : if (isSafeVar)
437 : {
438 : /* Fast-path: just generate an EEOP_ASSIGN_*_VAR step */
439 987928 : switch (variable->varno)
440 : {
441 186586 : case INNER_VAR:
442 : /* get the tuple from the inner node */
443 186586 : scratch.opcode = EEOP_ASSIGN_INNER_VAR;
444 186586 : break;
445 :
446 390560 : case OUTER_VAR:
447 : /* get the tuple from the outer node */
448 390560 : scratch.opcode = EEOP_ASSIGN_OUTER_VAR;
449 390560 : break;
450 :
451 : /* INDEX_VAR is handled by default case */
452 :
453 410782 : 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 410782 : switch (variable->varreturningtype)
460 : {
461 409044 : case VAR_RETURNING_DEFAULT:
462 409044 : scratch.opcode = EEOP_ASSIGN_SCAN_VAR;
463 409044 : break;
464 868 : case VAR_RETURNING_OLD:
465 868 : scratch.opcode = EEOP_ASSIGN_OLD_VAR;
466 868 : state->flags |= EEO_FLAG_HAS_OLD;
467 868 : break;
468 870 : case VAR_RETURNING_NEW:
469 870 : scratch.opcode = EEOP_ASSIGN_NEW_VAR;
470 870 : state->flags |= EEO_FLAG_HAS_NEW;
471 870 : break;
472 : }
473 410782 : break;
474 : }
475 :
476 987928 : scratch.d.assign_var.attnum = attnum - 1;
477 987928 : scratch.d.assign_var.resultnum = tle->resno - 1;
478 987928 : 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 870460 : 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 870398 : if (get_typlen(exprType((Node *) tle->expr)) == -1)
498 277410 : scratch.opcode = EEOP_ASSIGN_TMP_MAKE_RO;
499 : else
500 592988 : scratch.opcode = EEOP_ASSIGN_TMP;
501 870398 : scratch.d.assign_tmp.resultnum = tle->resno - 1;
502 870398 : ExprEvalPushStep(state, &scratch);
503 : }
504 : }
505 :
506 756112 : scratch.opcode = EEOP_DONE;
507 756112 : ExprEvalPushStep(state, &scratch);
508 :
509 756112 : ExecReadyExpr(state);
510 :
511 756112 : 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 15188 : ExecBuildUpdateProjection(List *targetList,
548 : bool evalTargetList,
549 : List *targetColnos,
550 : TupleDesc relDesc,
551 : ExprContext *econtext,
552 : TupleTableSlot *slot,
553 : PlanState *parent)
554 : {
555 15188 : ProjectionInfo *projInfo = makeNode(ProjectionInfo);
556 : ExprState *state;
557 : int nAssignableCols;
558 : bool sawJunk;
559 : Bitmapset *assignedCols;
560 15188 : ExprSetupInfo deform = {0, 0, 0, 0, 0, NIL};
561 15188 : ExprEvalStep scratch = {0};
562 : int outerattnum;
563 : ListCell *lc,
564 : *lc2;
565 :
566 15188 : projInfo->pi_exprContext = econtext;
567 : /* We embed ExprState into ProjectionInfo instead of doing extra palloc */
568 15188 : projInfo->pi_state.type = T_ExprState;
569 15188 : state = &projInfo->pi_state;
570 15188 : if (evalTargetList)
571 2528 : state->expr = (Expr *) targetList;
572 : else
573 12660 : state->expr = NULL; /* not used */
574 15188 : state->parent = parent;
575 15188 : state->ext_params = NULL;
576 :
577 15188 : 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 15188 : nAssignableCols = 0;
584 15188 : sawJunk = false;
585 50836 : foreach(lc, targetList)
586 : {
587 35648 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
588 :
589 35648 : if (tle->resjunk)
590 16144 : sawJunk = true;
591 : else
592 : {
593 19504 : if (sawJunk)
594 0 : elog(ERROR, "subplan target list is out of order");
595 19504 : nAssignableCols++;
596 : }
597 : }
598 :
599 : /* We should have one targetColnos entry per non-junk column */
600 15188 : 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 15188 : assignedCols = NULL;
609 34692 : foreach(lc, targetColnos)
610 : {
611 19504 : AttrNumber targetattnum = lfirst_int(lc);
612 :
613 19504 : 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 25730 : for (int attnum = relDesc->natts; attnum > 0; attnum--)
622 : {
623 23232 : CompactAttribute *attr = TupleDescCompactAttr(relDesc, attnum - 1);
624 :
625 23232 : if (attr->attisdropped)
626 216 : continue;
627 23016 : if (bms_is_member(attnum, assignedCols))
628 10326 : continue;
629 12690 : deform.last_scan = attnum;
630 12690 : 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 15188 : if (evalTargetList)
639 2528 : expr_setup_walker((Node *) targetList, &deform);
640 : else
641 12660 : deform.last_outer = nAssignableCols;
642 :
643 15188 : 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 15188 : outerattnum = 0;
653 34692 : forboth(lc, targetList, lc2, targetColnos)
654 : {
655 19504 : TargetEntry *tle = lfirst_node(TargetEntry, lc);
656 19504 : 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 19504 : 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 19504 : attr = TupleDescAttr(relDesc, targetattnum - 1);
670 :
671 19504 : 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 19504 : 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 19504 : 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 3430 : ExecInitExprRec(tle->expr, state,
696 : &state->resvalue, &state->resnull);
697 : /* Needn't worry about read-only-ness here, either. */
698 3430 : scratch.opcode = EEOP_ASSIGN_TMP;
699 3430 : scratch.d.assign_tmp.resultnum = targetattnum - 1;
700 3430 : ExprEvalPushStep(state, &scratch);
701 : }
702 : else
703 : {
704 : /* Just assign from the outer tuple. */
705 16074 : scratch.opcode = EEOP_ASSIGN_OUTER_VAR;
706 16074 : scratch.d.assign_var.attnum = outerattnum;
707 16074 : scratch.d.assign_var.resultnum = targetattnum - 1;
708 16074 : ExprEvalPushStep(state, &scratch);
709 : }
710 19504 : 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 135150 : for (int attnum = 1; attnum <= relDesc->natts; attnum++)
718 : {
719 119962 : CompactAttribute *attr = TupleDescCompactAttr(relDesc, attnum - 1);
720 :
721 119962 : 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 119558 : else if (!bms_is_member(attnum, assignedCols))
736 : {
737 : /* Certainly the right type, so needn't check */
738 100054 : scratch.opcode = EEOP_ASSIGN_SCAN_VAR;
739 100054 : scratch.d.assign_var.attnum = attnum - 1;
740 100054 : scratch.d.assign_var.resultnum = attnum - 1;
741 100054 : ExprEvalPushStep(state, &scratch);
742 : }
743 : }
744 :
745 15188 : scratch.opcode = EEOP_DONE;
746 15188 : ExprEvalPushStep(state, &scratch);
747 :
748 15188 : ExecReadyExpr(state);
749 :
750 15188 : 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 23594 : ExecPrepareExpr(Expr *node, EState *estate)
766 : {
767 : ExprState *result;
768 : MemoryContext oldcontext;
769 :
770 23594 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
771 :
772 23594 : node = expression_planner(node);
773 :
774 23588 : result = ExecInitExpr(node, NULL);
775 :
776 23588 : MemoryContextSwitchTo(oldcontext);
777 :
778 23588 : 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 55830 : ExecPrepareQual(List *qual, EState *estate)
794 : {
795 : ExprState *result;
796 : MemoryContext oldcontext;
797 :
798 55830 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
799 :
800 55830 : qual = (List *) expression_planner((Expr *) qual);
801 :
802 55830 : result = ExecInitQual(qual, NULL);
803 :
804 55830 : MemoryContextSwitchTo(oldcontext);
805 :
806 55830 : 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 5490 : ExecPrepareCheck(List *qual, EState *estate)
817 : {
818 : ExprState *result;
819 : MemoryContext oldcontext;
820 :
821 5490 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
822 :
823 5490 : qual = (List *) expression_planner((Expr *) qual);
824 :
825 5490 : result = ExecInitCheck(qual, NULL);
826 :
827 5490 : MemoryContextSwitchTo(oldcontext);
828 :
829 5490 : 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 15946 : ExecPrepareExprList(List *nodes, EState *estate)
840 : {
841 15946 : List *result = NIL;
842 : MemoryContext oldcontext;
843 : ListCell *lc;
844 :
845 : /* Ensure that the list cell nodes are in the right context too */
846 15946 : oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
847 :
848 32148 : foreach(lc, nodes)
849 : {
850 16202 : Expr *e = (Expr *) lfirst(lc);
851 :
852 16202 : result = lappend(result, ExecPrepareExpr(e, estate));
853 : }
854 :
855 15946 : MemoryContextSwitchTo(oldcontext);
856 :
857 15946 : 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 102930 : 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 102930 : 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 102834 : ret = ExecEvalExprSwitchContext(state, econtext, &isnull);
885 :
886 102828 : if (isnull)
887 2836 : return true;
888 :
889 99992 : 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 2274704 : ExecReadyExpr(ExprState *state)
903 : {
904 2274704 : if (jit_compile_expr(state))
905 9060 : return;
906 :
907 2265644 : 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 4979580 : ExecInitExprRec(Expr *node, ExprState *state,
920 : Datum *resv, bool *resnull)
921 : {
922 4979580 : ExprEvalStep scratch = {0};
923 :
924 : /* Guard against stack overflow due to overly complex expressions */
925 4979580 : check_stack_depth();
926 :
927 : /* Step's output location is always what the caller gave us */
928 : Assert(resv != NULL && resnull != NULL);
929 4979580 : scratch.resvalue = resv;
930 4979580 : scratch.resnull = resnull;
931 :
932 : /* cases should be ordered as they are in enum NodeTag */
933 4979580 : switch (nodeTag(node))
934 : {
935 1160928 : case T_Var:
936 : {
937 1160928 : Var *variable = (Var *) node;
938 :
939 1160928 : if (variable->varattno == InvalidAttrNumber)
940 : {
941 : /* whole-row Var */
942 4246 : ExecInitWholeRowVar(&scratch, variable, state);
943 : }
944 1156682 : else if (variable->varattno <= 0)
945 : {
946 : /* system column */
947 79244 : scratch.d.var.attnum = variable->varattno;
948 79244 : scratch.d.var.vartype = variable->vartype;
949 79244 : scratch.d.var.varreturningtype = variable->varreturningtype;
950 79244 : 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 79226 : default:
962 79226 : switch (variable->varreturningtype)
963 : {
964 78578 : case VAR_RETURNING_DEFAULT:
965 78578 : scratch.opcode = EEOP_SCAN_SYSVAR;
966 78578 : 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 79226 : break;
977 : }
978 : }
979 : else
980 : {
981 : /* regular user column */
982 1077438 : scratch.d.var.attnum = variable->varattno - 1;
983 1077438 : scratch.d.var.vartype = variable->vartype;
984 1077438 : scratch.d.var.varreturningtype = variable->varreturningtype;
985 1077438 : switch (variable->varno)
986 : {
987 123240 : case INNER_VAR:
988 123240 : scratch.opcode = EEOP_INNER_VAR;
989 123240 : break;
990 302738 : case OUTER_VAR:
991 302738 : scratch.opcode = EEOP_OUTER_VAR;
992 302738 : break;
993 :
994 : /* INDEX_VAR is handled by default case */
995 :
996 651460 : default:
997 651460 : switch (variable->varreturningtype)
998 : {
999 651052 : case VAR_RETURNING_DEFAULT:
1000 651052 : scratch.opcode = EEOP_SCAN_VAR;
1001 651052 : break;
1002 204 : case VAR_RETURNING_OLD:
1003 204 : scratch.opcode = EEOP_OLD_VAR;
1004 204 : state->flags |= EEO_FLAG_HAS_OLD;
1005 204 : break;
1006 204 : case VAR_RETURNING_NEW:
1007 204 : scratch.opcode = EEOP_NEW_VAR;
1008 204 : state->flags |= EEO_FLAG_HAS_NEW;
1009 204 : break;
1010 : }
1011 651460 : break;
1012 : }
1013 : }
1014 :
1015 1160928 : ExprEvalPushStep(state, &scratch);
1016 1160928 : break;
1017 : }
1018 :
1019 1006594 : case T_Const:
1020 : {
1021 1006594 : Const *con = (Const *) node;
1022 :
1023 1006594 : scratch.opcode = EEOP_CONST;
1024 1006594 : scratch.d.constval.value = con->constvalue;
1025 1006594 : scratch.d.constval.isnull = con->constisnull;
1026 :
1027 1006594 : ExprEvalPushStep(state, &scratch);
1028 1006594 : break;
1029 : }
1030 :
1031 787702 : case T_Param:
1032 : {
1033 787702 : Param *param = (Param *) node;
1034 : ParamListInfo params;
1035 :
1036 787702 : switch (param->paramkind)
1037 : {
1038 226028 : case PARAM_EXEC:
1039 226028 : scratch.opcode = EEOP_PARAM_EXEC;
1040 226028 : scratch.d.param.paramid = param->paramid;
1041 226028 : scratch.d.param.paramtype = param->paramtype;
1042 226028 : ExprEvalPushStep(state, &scratch);
1043 226028 : break;
1044 561674 : 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 561674 : if (state->ext_params)
1053 69932 : params = state->ext_params;
1054 491742 : else if (state->parent &&
1055 491442 : state->parent->state)
1056 491442 : params = state->parent->state->es_param_list_info;
1057 : else
1058 300 : params = NULL;
1059 561674 : if (params && params->paramCompile)
1060 : {
1061 140330 : params->paramCompile(params, param, state,
1062 : resv, resnull);
1063 : }
1064 : else
1065 : {
1066 421344 : scratch.opcode = EEOP_PARAM_EXTERN;
1067 421344 : scratch.d.param.paramid = param->paramid;
1068 421344 : scratch.d.param.paramtype = param->paramtype;
1069 421344 : ExprEvalPushStep(state, &scratch);
1070 : }
1071 561674 : break;
1072 0 : default:
1073 0 : elog(ERROR, "unrecognized paramkind: %d",
1074 : (int) param->paramkind);
1075 : break;
1076 : }
1077 787702 : break;
1078 : }
1079 :
1080 49914 : case T_Aggref:
1081 : {
1082 49914 : Aggref *aggref = (Aggref *) node;
1083 :
1084 49914 : scratch.opcode = EEOP_AGGREF;
1085 49914 : scratch.d.aggref.aggno = aggref->aggno;
1086 :
1087 49914 : if (state->parent && IsA(state->parent, AggState))
1088 49914 : {
1089 49914 : AggState *aggstate = (AggState *) state->parent;
1090 :
1091 49914 : 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 49914 : ExprEvalPushStep(state, &scratch);
1100 49914 : 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 198 : case T_MergeSupportFunc:
1172 : {
1173 : /* must be in a MERGE, else something messed up */
1174 198 : if (!state->parent ||
1175 198 : !IsA(state->parent, ModifyTableState) ||
1176 198 : ((ModifyTableState *) state->parent)->operation != CMD_MERGE)
1177 0 : elog(ERROR, "MergeSupportFunc found in non-merge plan node");
1178 :
1179 198 : scratch.opcode = EEOP_MERGE_SUPPORT_FUNC;
1180 198 : ExprEvalPushStep(state, &scratch);
1181 198 : break;
1182 : }
1183 :
1184 24618 : case T_SubscriptingRef:
1185 : {
1186 24618 : SubscriptingRef *sbsref = (SubscriptingRef *) node;
1187 :
1188 24618 : ExecInitSubscriptingRef(&scratch, sbsref, state, resv, resnull);
1189 24618 : break;
1190 : }
1191 :
1192 635308 : case T_FuncExpr:
1193 : {
1194 635308 : FuncExpr *func = (FuncExpr *) node;
1195 :
1196 635308 : ExecInitFunc(&scratch, node,
1197 : func->args, func->funcid, func->inputcollid,
1198 : state);
1199 635234 : ExprEvalPushStep(state, &scratch);
1200 635234 : break;
1201 : }
1202 :
1203 803202 : case T_OpExpr:
1204 : {
1205 803202 : OpExpr *op = (OpExpr *) node;
1206 :
1207 803202 : ExecInitFunc(&scratch, node,
1208 : op->args, op->opfuncid, op->inputcollid,
1209 : state);
1210 803202 : ExprEvalPushStep(state, &scratch);
1211 803202 : break;
1212 : }
1213 :
1214 950 : case T_DistinctExpr:
1215 : {
1216 950 : DistinctExpr *op = (DistinctExpr *) node;
1217 :
1218 950 : 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 950 : scratch.opcode = EEOP_DISTINCT;
1232 950 : ExprEvalPushStep(state, &scratch);
1233 950 : 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 32312 : case T_ScalarArrayOpExpr:
1267 : {
1268 32312 : 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 32312 : if (OidIsValid(opexpr->negfuncid))
1283 : {
1284 : Assert(OidIsValid(opexpr->hashfuncid));
1285 70 : cmpfuncid = opexpr->negfuncid;
1286 : }
1287 : else
1288 32242 : cmpfuncid = opexpr->opfuncid;
1289 :
1290 : Assert(list_length(opexpr->args) == 2);
1291 32312 : scalararg = (Expr *) linitial(opexpr->args);
1292 32312 : arrayarg = (Expr *) lsecond(opexpr->args);
1293 :
1294 : /* Check permission to call function */
1295 32312 : aclresult = object_aclcheck(ProcedureRelationId, cmpfuncid,
1296 : GetUserId(),
1297 : ACL_EXECUTE);
1298 32312 : if (aclresult != ACLCHECK_OK)
1299 0 : aclcheck_error(aclresult, OBJECT_FUNCTION,
1300 0 : get_func_name(cmpfuncid));
1301 32312 : InvokeFunctionExecuteHook(cmpfuncid);
1302 :
1303 32312 : if (OidIsValid(opexpr->hashfuncid))
1304 : {
1305 266 : aclresult = object_aclcheck(ProcedureRelationId, opexpr->hashfuncid,
1306 : GetUserId(),
1307 : ACL_EXECUTE);
1308 266 : if (aclresult != ACLCHECK_OK)
1309 0 : aclcheck_error(aclresult, OBJECT_FUNCTION,
1310 0 : get_func_name(opexpr->hashfuncid));
1311 266 : InvokeFunctionExecuteHook(opexpr->hashfuncid);
1312 : }
1313 :
1314 : /* Set up the primary fmgr lookup information */
1315 32312 : finfo = palloc0(sizeof(FmgrInfo));
1316 32312 : fcinfo = palloc0(SizeForFunctionCallInfo(2));
1317 32312 : fmgr_info(cmpfuncid, finfo);
1318 32312 : fmgr_info_set_expr((Node *) node, finfo);
1319 32312 : 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 32312 : if (OidIsValid(opexpr->hashfuncid))
1330 : {
1331 : /* Evaluate scalar directly into left function argument */
1332 266 : 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 266 : ExecInitExprRec(arrayarg, state, resv, resnull);
1343 :
1344 : /* And perform the operation */
1345 266 : scratch.opcode = EEOP_HASHED_SCALARARRAYOP;
1346 266 : scratch.d.hashedscalararrayop.inclause = opexpr->useOr;
1347 266 : scratch.d.hashedscalararrayop.finfo = finfo;
1348 266 : scratch.d.hashedscalararrayop.fcinfo_data = fcinfo;
1349 266 : scratch.d.hashedscalararrayop.saop = opexpr;
1350 :
1351 :
1352 266 : ExprEvalPushStep(state, &scratch);
1353 : }
1354 : else
1355 : {
1356 : /* Evaluate scalar directly into left function argument */
1357 32046 : 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 32046 : ExecInitExprRec(arrayarg, state, resv, resnull);
1368 :
1369 : /* And perform the operation */
1370 32046 : scratch.opcode = EEOP_SCALARARRAYOP;
1371 32046 : scratch.d.scalararrayop.element_type = InvalidOid;
1372 32046 : scratch.d.scalararrayop.useOr = opexpr->useOr;
1373 32046 : scratch.d.scalararrayop.finfo = finfo;
1374 32046 : scratch.d.scalararrayop.fcinfo_data = fcinfo;
1375 32046 : scratch.d.scalararrayop.fn_addr = finfo->fn_addr;
1376 32046 : ExprEvalPushStep(state, &scratch);
1377 : }
1378 32312 : break;
1379 : }
1380 :
1381 63634 : case T_BoolExpr:
1382 : {
1383 63634 : BoolExpr *boolexpr = (BoolExpr *) node;
1384 63634 : int nargs = list_length(boolexpr->args);
1385 63634 : List *adjust_jumps = NIL;
1386 : int off;
1387 : ListCell *lc;
1388 :
1389 : /* allocate scratch memory used by all steps of AND/OR */
1390 63634 : if (boolexpr->boolop != NOT_EXPR)
1391 51632 : 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 63634 : off = 0;
1407 191230 : foreach(lc, boolexpr->args)
1408 : {
1409 127596 : Expr *arg = (Expr *) lfirst(lc);
1410 :
1411 : /* Evaluate argument into our output variable */
1412 127596 : ExecInitExprRec(arg, state, resv, resnull);
1413 :
1414 : /* Perform the appropriate step type */
1415 127596 : switch (boolexpr->boolop)
1416 : {
1417 78768 : case AND_EXPR:
1418 : Assert(nargs >= 2);
1419 :
1420 78768 : if (off == 0)
1421 35576 : scratch.opcode = EEOP_BOOL_AND_STEP_FIRST;
1422 43192 : else if (off + 1 == nargs)
1423 35576 : scratch.opcode = EEOP_BOOL_AND_STEP_LAST;
1424 : else
1425 7616 : scratch.opcode = EEOP_BOOL_AND_STEP;
1426 78768 : break;
1427 36826 : case OR_EXPR:
1428 : Assert(nargs >= 2);
1429 :
1430 36826 : if (off == 0)
1431 16056 : scratch.opcode = EEOP_BOOL_OR_STEP_FIRST;
1432 20770 : else if (off + 1 == nargs)
1433 16056 : scratch.opcode = EEOP_BOOL_OR_STEP_LAST;
1434 : else
1435 4714 : scratch.opcode = EEOP_BOOL_OR_STEP;
1436 36826 : break;
1437 12002 : case NOT_EXPR:
1438 : Assert(nargs == 1);
1439 :
1440 12002 : scratch.opcode = EEOP_BOOL_NOT_STEP;
1441 12002 : break;
1442 0 : default:
1443 0 : elog(ERROR, "unrecognized boolop: %d",
1444 : (int) boolexpr->boolop);
1445 : break;
1446 : }
1447 :
1448 127596 : scratch.d.boolexpr.jumpdone = -1;
1449 127596 : ExprEvalPushStep(state, &scratch);
1450 127596 : adjust_jumps = lappend_int(adjust_jumps,
1451 127596 : state->steps_len - 1);
1452 127596 : off++;
1453 : }
1454 :
1455 : /* adjust jump targets */
1456 191230 : foreach(lc, adjust_jumps)
1457 : {
1458 127596 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
1459 :
1460 : Assert(as->d.boolexpr.jumpdone == -1);
1461 127596 : as->d.boolexpr.jumpdone = state->steps_len;
1462 : }
1463 :
1464 63634 : break;
1465 : }
1466 :
1467 26358 : case T_SubPlan:
1468 : {
1469 26358 : 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 26358 : 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 26298 : ExecInitSubPlanExpr(subplan, state, resv, resnull);
1487 26298 : break;
1488 : }
1489 :
1490 8708 : case T_FieldSelect:
1491 : {
1492 8708 : FieldSelect *fselect = (FieldSelect *) node;
1493 :
1494 : /* evaluate row/record argument into result area */
1495 8708 : ExecInitExprRec(fselect->arg, state, resv, resnull);
1496 :
1497 : /* and extract field */
1498 8708 : scratch.opcode = EEOP_FIELDSELECT;
1499 8708 : scratch.d.fieldselect.fieldnum = fselect->fieldnum;
1500 8708 : scratch.d.fieldselect.resulttype = fselect->resulttype;
1501 8708 : scratch.d.fieldselect.rowcache.cacheptr = NULL;
1502 :
1503 8708 : ExprEvalPushStep(state, &scratch);
1504 8708 : 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 111062 : case T_RelabelType:
1604 : {
1605 : /* relabel doesn't need to do anything at runtime */
1606 111062 : RelabelType *relabel = (RelabelType *) node;
1607 :
1608 111062 : ExecInitExprRec(relabel->arg, state, resv, resnull);
1609 111062 : break;
1610 : }
1611 :
1612 36138 : case T_CoerceViaIO:
1613 : {
1614 36138 : 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 36138 : 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 36138 : if (state->escontext == NULL)
1632 36138 : scratch.opcode = EEOP_IOCOERCE;
1633 : else
1634 0 : scratch.opcode = EEOP_IOCOERCE_SAFE;
1635 :
1636 : /* lookup the source type's output function */
1637 36138 : scratch.d.iocoerce.finfo_out = palloc0(sizeof(FmgrInfo));
1638 36138 : scratch.d.iocoerce.fcinfo_data_out = palloc0(SizeForFunctionCallInfo(1));
1639 :
1640 36138 : getTypeOutputInfo(exprType((Node *) iocoerce->arg),
1641 : &iofunc, &typisvarlena);
1642 36138 : fmgr_info(iofunc, scratch.d.iocoerce.finfo_out);
1643 36138 : fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_out);
1644 36138 : 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 36138 : scratch.d.iocoerce.finfo_in = palloc0(sizeof(FmgrInfo));
1650 36138 : scratch.d.iocoerce.fcinfo_data_in = palloc0(SizeForFunctionCallInfo(3));
1651 :
1652 36138 : getTypeInputInfo(iocoerce->resulttype,
1653 : &iofunc, &typioparam);
1654 36138 : fmgr_info(iofunc, scratch.d.iocoerce.finfo_in);
1655 36138 : fmgr_info_set_expr((Node *) node, scratch.d.iocoerce.finfo_in);
1656 36138 : 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 36138 : fcinfo_in = scratch.d.iocoerce.fcinfo_data_in;
1665 36138 : fcinfo_in->args[1].value = ObjectIdGetDatum(typioparam);
1666 36138 : fcinfo_in->args[1].isnull = false;
1667 36138 : fcinfo_in->args[2].value = Int32GetDatum(-1);
1668 36138 : fcinfo_in->args[2].isnull = false;
1669 :
1670 36138 : fcinfo_in->context = (Node *) state->escontext;
1671 :
1672 36138 : ExprEvalPushStep(state, &scratch);
1673 36138 : break;
1674 : }
1675 :
1676 5288 : case T_ArrayCoerceExpr:
1677 : {
1678 5288 : ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
1679 : Oid resultelemtype;
1680 : ExprState *elemstate;
1681 :
1682 : /* evaluate argument into step's result area */
1683 5288 : ExecInitExprRec(acoerce->arg, state, resv, resnull);
1684 :
1685 5288 : resultelemtype = get_element_type(acoerce->resulttype);
1686 5288 : 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 5288 : elemstate = makeNode(ExprState);
1698 5288 : elemstate->expr = acoerce->elemexpr;
1699 5288 : elemstate->parent = state->parent;
1700 5288 : elemstate->ext_params = state->ext_params;
1701 :
1702 5288 : elemstate->innermost_caseval = (Datum *) palloc(sizeof(Datum));
1703 5288 : elemstate->innermost_casenull = (bool *) palloc(sizeof(bool));
1704 :
1705 5288 : ExecInitExprRec(acoerce->elemexpr, elemstate,
1706 : &elemstate->resvalue, &elemstate->resnull);
1707 :
1708 5282 : if (elemstate->steps_len == 1 &&
1709 4846 : elemstate->steps[0].opcode == EEOP_CASE_TESTVAL)
1710 : {
1711 : /* Trivial, so we need no per-element work at runtime */
1712 4846 : 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 5282 : scratch.opcode = EEOP_ARRAYCOERCE;
1724 5282 : scratch.d.arraycoerce.elemexprstate = elemstate;
1725 5282 : scratch.d.arraycoerce.resultelemtype = resultelemtype;
1726 :
1727 5282 : 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 4846 : scratch.d.arraycoerce.amstate = NULL;
1737 : }
1738 :
1739 5282 : ExprEvalPushStep(state, &scratch);
1740 5282 : 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 101548 : case T_CaseExpr:
1771 : {
1772 101548 : CaseExpr *caseExpr = (CaseExpr *) node;
1773 101548 : List *adjust_jumps = NIL;
1774 101548 : Datum *caseval = NULL;
1775 101548 : 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 101548 : if (caseExpr->arg != NULL)
1784 : {
1785 : /* Evaluate testexpr into caseval/casenull workspace */
1786 4050 : caseval = palloc(sizeof(Datum));
1787 4050 : casenull = palloc(sizeof(bool));
1788 :
1789 4050 : 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 4050 : 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 279316 : foreach(lc, caseExpr->args)
1818 : {
1819 177768 : 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 177768 : save_innermost_caseval = state->innermost_caseval;
1835 177768 : save_innermost_casenull = state->innermost_casenull;
1836 177768 : state->innermost_caseval = caseval;
1837 177768 : state->innermost_casenull = casenull;
1838 :
1839 : /* evaluate condition into CASE's result variables */
1840 177768 : ExecInitExprRec(when->expr, state, resv, resnull);
1841 :
1842 177768 : state->innermost_caseval = save_innermost_caseval;
1843 177768 : state->innermost_casenull = save_innermost_casenull;
1844 :
1845 : /* If WHEN result isn't true, jump to next CASE arm */
1846 177768 : scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
1847 177768 : scratch.d.jump.jumpdone = -1; /* computed later */
1848 177768 : ExprEvalPushStep(state, &scratch);
1849 177768 : 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 177768 : ExecInitExprRec(when->result, state, resv, resnull);
1856 :
1857 : /* Emit JUMP step to jump to end of CASE's code */
1858 177768 : scratch.opcode = EEOP_JUMP;
1859 177768 : scratch.d.jump.jumpdone = -1; /* computed later */
1860 177768 : 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 177768 : adjust_jumps = lappend_int(adjust_jumps,
1867 177768 : 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 177768 : 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 101548 : ExecInitExprRec(caseExpr->defresult, state,
1881 : resv, resnull);
1882 :
1883 : /* adjust jump targets */
1884 279316 : foreach(lc, adjust_jumps)
1885 : {
1886 177768 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
1887 :
1888 : Assert(as->opcode == EEOP_JUMP);
1889 : Assert(as->d.jump.jumpdone == -1);
1890 177768 : as->d.jump.jumpdone = state->steps_len;
1891 : }
1892 :
1893 101548 : break;
1894 : }
1895 :
1896 23558 : 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
1905 : * scenario at runtime.
1906 : */
1907 23558 : scratch.opcode = EEOP_CASE_TESTVAL;
1908 23558 : scratch.d.casetest.value = state->innermost_caseval;
1909 23558 : scratch.d.casetest.isnull = state->innermost_casenull;
1910 :
1911 23558 : ExprEvalPushStep(state, &scratch);
1912 23558 : break;
1913 : }
1914 :
1915 25718 : case T_ArrayExpr:
1916 : {
1917 25718 : ArrayExpr *arrayexpr = (ArrayExpr *) node;
1918 25718 : int nelems = list_length(arrayexpr->elements);
1919 : ListCell *lc;
1920 : int elemoff;
1921 :
1922 : /*
1923 : * Evaluate by computing each element, and then forming the
1924 : * array. Elements are computed into scratch arrays
1925 : * associated with the ARRAYEXPR step.
1926 : */
1927 25718 : scratch.opcode = EEOP_ARRAYEXPR;
1928 25718 : scratch.d.arrayexpr.elemvalues =
1929 25718 : (Datum *) palloc(sizeof(Datum) * nelems);
1930 25718 : scratch.d.arrayexpr.elemnulls =
1931 25718 : (bool *) palloc(sizeof(bool) * nelems);
1932 25718 : scratch.d.arrayexpr.nelems = nelems;
1933 :
1934 : /* fill remaining fields of step */
1935 25718 : scratch.d.arrayexpr.multidims = arrayexpr->multidims;
1936 25718 : scratch.d.arrayexpr.elemtype = arrayexpr->element_typeid;
1937 :
1938 : /* do one-time catalog lookup for type info */
1939 25718 : get_typlenbyvalalign(arrayexpr->element_typeid,
1940 : &scratch.d.arrayexpr.elemlength,
1941 : &scratch.d.arrayexpr.elembyval,
1942 : &scratch.d.arrayexpr.elemalign);
1943 :
1944 : /* prepare to evaluate all arguments */
1945 25718 : elemoff = 0;
1946 95822 : foreach(lc, arrayexpr->elements)
1947 : {
1948 70104 : Expr *e = (Expr *) lfirst(lc);
1949 :
1950 70104 : ExecInitExprRec(e, state,
1951 70104 : &scratch.d.arrayexpr.elemvalues[elemoff],
1952 70104 : &scratch.d.arrayexpr.elemnulls[elemoff]);
1953 70104 : elemoff++;
1954 : }
1955 :
1956 : /* and then collect all into an array */
1957 25718 : ExprEvalPushStep(state, &scratch);
1958 25718 : break;
1959 : }
1960 :
1961 5474 : case T_RowExpr:
1962 : {
1963 5474 : RowExpr *rowexpr = (RowExpr *) node;
1964 5474 : int nelems = list_length(rowexpr->args);
1965 : TupleDesc tupdesc;
1966 : int i;
1967 : ListCell *l;
1968 :
1969 : /* Build tupdesc to describe result tuples */
1970 5474 : if (rowexpr->row_typeid == RECORDOID)
1971 : {
1972 : /* generic record, use types of given expressions */
1973 2882 : tupdesc = ExecTypeFromExprList(rowexpr->args);
1974 : /* ... but adopt RowExpr's column aliases */
1975 2882 : ExecTypeSetColNames(tupdesc, rowexpr->colnames);
1976 : /* Bless the tupdesc so it can be looked up later */
1977 2882 : BlessTupleDesc(tupdesc);
1978 : }
1979 : else
1980 : {
1981 : /* it's been cast to a named type, use that */
1982 2592 : tupdesc = lookup_rowtype_tupdesc_copy(rowexpr->row_typeid, -1);
1983 : }
1984 :
1985 : /*
1986 : * In the named-type case, the tupdesc could have more columns
1987 : * than are in the args list, since the type might have had
1988 : * columns added since the ROW() was parsed. We want those
1989 : * extra columns to go to nulls, so we make sure that the
1990 : * workspace arrays are large enough and then initialize any
1991 : * extra columns to read as NULLs.
1992 : */
1993 : Assert(nelems <= tupdesc->natts);
1994 5474 : nelems = Max(nelems, tupdesc->natts);
1995 :
1996 : /*
1997 : * Evaluate by first building datums for each field, and then
1998 : * a final step forming the composite datum.
1999 : */
2000 5474 : scratch.opcode = EEOP_ROW;
2001 5474 : scratch.d.row.tupdesc = tupdesc;
2002 :
2003 : /* space for the individual field datums */
2004 5474 : scratch.d.row.elemvalues =
2005 5474 : (Datum *) palloc(sizeof(Datum) * nelems);
2006 5474 : scratch.d.row.elemnulls =
2007 5474 : (bool *) palloc(sizeof(bool) * nelems);
2008 : /* as explained above, make sure any extra columns are null */
2009 5474 : memset(scratch.d.row.elemnulls, true, sizeof(bool) * nelems);
2010 :
2011 : /* Set up evaluation, skipping any deleted columns */
2012 5474 : i = 0;
2013 19864 : foreach(l, rowexpr->args)
2014 : {
2015 14396 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2016 14396 : Expr *e = (Expr *) lfirst(l);
2017 :
2018 14396 : if (!att->attisdropped)
2019 : {
2020 : /*
2021 : * Guard against ALTER COLUMN TYPE on rowtype since
2022 : * the RowExpr was created. XXX should we check
2023 : * typmod too? Not sure we can be sure it'll be the
2024 : * same.
2025 : */
2026 14378 : if (exprType((Node *) e) != att->atttypid)
2027 6 : ereport(ERROR,
2028 : (errcode(ERRCODE_DATATYPE_MISMATCH),
2029 : errmsg("ROW() column has type %s instead of type %s",
2030 : format_type_be(exprType((Node *) e)),
2031 : format_type_be(att->atttypid))));
2032 : }
2033 : else
2034 : {
2035 : /*
2036 : * Ignore original expression and insert a NULL. We
2037 : * don't really care what type of NULL it is, so
2038 : * always make an int4 NULL.
2039 : */
2040 18 : e = (Expr *) makeNullConst(INT4OID, -1, InvalidOid);
2041 : }
2042 :
2043 : /* Evaluate column expr into appropriate workspace slot */
2044 14390 : ExecInitExprRec(e, state,
2045 14390 : &scratch.d.row.elemvalues[i],
2046 14390 : &scratch.d.row.elemnulls[i]);
2047 14390 : i++;
2048 : }
2049 :
2050 : /* And finally build the row value */
2051 5468 : ExprEvalPushStep(state, &scratch);
2052 5468 : break;
2053 : }
2054 :
2055 228 : case T_RowCompareExpr:
2056 : {
2057 228 : RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2058 228 : int nopers = list_length(rcexpr->opnos);
2059 228 : List *adjust_jumps = NIL;
2060 : ListCell *l_left_expr,
2061 : *l_right_expr,
2062 : *l_opno,
2063 : *l_opfamily,
2064 : *l_inputcollid;
2065 : ListCell *lc;
2066 :
2067 : /*
2068 : * Iterate over each field, prepare comparisons. To handle
2069 : * NULL results, prepare jumps to after the expression. If a
2070 : * comparison yields a != 0 result, jump to the final step.
2071 : */
2072 : Assert(list_length(rcexpr->largs) == nopers);
2073 : Assert(list_length(rcexpr->rargs) == nopers);
2074 : Assert(list_length(rcexpr->opfamilies) == nopers);
2075 : Assert(list_length(rcexpr->inputcollids) == nopers);
2076 :
2077 738 : forfive(l_left_expr, rcexpr->largs,
2078 : l_right_expr, rcexpr->rargs,
2079 : l_opno, rcexpr->opnos,
2080 : l_opfamily, rcexpr->opfamilies,
2081 : l_inputcollid, rcexpr->inputcollids)
2082 : {
2083 510 : Expr *left_expr = (Expr *) lfirst(l_left_expr);
2084 510 : Expr *right_expr = (Expr *) lfirst(l_right_expr);
2085 510 : Oid opno = lfirst_oid(l_opno);
2086 510 : Oid opfamily = lfirst_oid(l_opfamily);
2087 510 : Oid inputcollid = lfirst_oid(l_inputcollid);
2088 : int strategy;
2089 : Oid lefttype;
2090 : Oid righttype;
2091 : Oid proc;
2092 : FmgrInfo *finfo;
2093 : FunctionCallInfo fcinfo;
2094 :
2095 510 : get_op_opfamily_properties(opno, opfamily, false,
2096 : &strategy,
2097 : &lefttype,
2098 : &righttype);
2099 510 : proc = get_opfamily_proc(opfamily,
2100 : lefttype,
2101 : righttype,
2102 : BTORDER_PROC);
2103 510 : if (!OidIsValid(proc))
2104 0 : elog(ERROR, "missing support function %d(%u,%u) in opfamily %u",
2105 : BTORDER_PROC, lefttype, righttype, opfamily);
2106 :
2107 : /* Set up the primary fmgr lookup information */
2108 510 : finfo = palloc0(sizeof(FmgrInfo));
2109 510 : fcinfo = palloc0(SizeForFunctionCallInfo(2));
2110 510 : fmgr_info(proc, finfo);
2111 510 : fmgr_info_set_expr((Node *) node, finfo);
2112 510 : InitFunctionCallInfoData(*fcinfo, finfo, 2,
2113 : inputcollid, NULL, NULL);
2114 :
2115 : /*
2116 : * If we enforced permissions checks on index support
2117 : * functions, we'd need to make a check here. But the
2118 : * index support machinery doesn't do that, and thus
2119 : * neither does this code.
2120 : */
2121 :
2122 : /* evaluate left and right args directly into fcinfo */
2123 510 : ExecInitExprRec(left_expr, state,
2124 : &fcinfo->args[0].value, &fcinfo->args[0].isnull);
2125 510 : ExecInitExprRec(right_expr, state,
2126 : &fcinfo->args[1].value, &fcinfo->args[1].isnull);
2127 :
2128 510 : scratch.opcode = EEOP_ROWCOMPARE_STEP;
2129 510 : scratch.d.rowcompare_step.finfo = finfo;
2130 510 : scratch.d.rowcompare_step.fcinfo_data = fcinfo;
2131 510 : scratch.d.rowcompare_step.fn_addr = finfo->fn_addr;
2132 : /* jump targets filled below */
2133 510 : scratch.d.rowcompare_step.jumpnull = -1;
2134 510 : scratch.d.rowcompare_step.jumpdone = -1;
2135 :
2136 510 : ExprEvalPushStep(state, &scratch);
2137 510 : adjust_jumps = lappend_int(adjust_jumps,
2138 510 : state->steps_len - 1);
2139 : }
2140 :
2141 : /*
2142 : * We could have a zero-column rowtype, in which case the rows
2143 : * necessarily compare equal.
2144 : */
2145 228 : if (nopers == 0)
2146 : {
2147 0 : scratch.opcode = EEOP_CONST;
2148 0 : scratch.d.constval.value = Int32GetDatum(0);
2149 0 : scratch.d.constval.isnull = false;
2150 0 : ExprEvalPushStep(state, &scratch);
2151 : }
2152 :
2153 : /* Finally, examine the last comparison result */
2154 228 : scratch.opcode = EEOP_ROWCOMPARE_FINAL;
2155 228 : scratch.d.rowcompare_final.cmptype = rcexpr->cmptype;
2156 228 : ExprEvalPushStep(state, &scratch);
2157 :
2158 : /* adjust jump targets */
2159 738 : foreach(lc, adjust_jumps)
2160 : {
2161 510 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
2162 :
2163 : Assert(as->opcode == EEOP_ROWCOMPARE_STEP);
2164 : Assert(as->d.rowcompare_step.jumpdone == -1);
2165 : Assert(as->d.rowcompare_step.jumpnull == -1);
2166 :
2167 : /* jump to comparison evaluation */
2168 510 : as->d.rowcompare_step.jumpdone = state->steps_len - 1;
2169 : /* jump to the following expression */
2170 510 : as->d.rowcompare_step.jumpnull = state->steps_len;
2171 : }
2172 :
2173 228 : break;
2174 : }
2175 :
2176 3304 : case T_CoalesceExpr:
2177 : {
2178 3304 : CoalesceExpr *coalesce = (CoalesceExpr *) node;
2179 3304 : List *adjust_jumps = NIL;
2180 : ListCell *lc;
2181 :
2182 : /* We assume there's at least one arg */
2183 : Assert(coalesce->args != NIL);
2184 :
2185 : /*
2186 : * Prepare evaluation of all coalesced arguments, after each
2187 : * one push a step that short-circuits if not null.
2188 : */
2189 9870 : foreach(lc, coalesce->args)
2190 : {
2191 6566 : Expr *e = (Expr *) lfirst(lc);
2192 :
2193 : /* evaluate argument, directly into result datum */
2194 6566 : ExecInitExprRec(e, state, resv, resnull);
2195 :
2196 : /* if it's not null, skip to end of COALESCE expr */
2197 6566 : scratch.opcode = EEOP_JUMP_IF_NOT_NULL;
2198 6566 : scratch.d.jump.jumpdone = -1; /* adjust later */
2199 6566 : ExprEvalPushStep(state, &scratch);
2200 :
2201 6566 : adjust_jumps = lappend_int(adjust_jumps,
2202 6566 : state->steps_len - 1);
2203 : }
2204 :
2205 : /*
2206 : * No need to add a constant NULL return - we only can get to
2207 : * the end of the expression if a NULL already is being
2208 : * returned.
2209 : */
2210 :
2211 : /* adjust jump targets */
2212 9870 : foreach(lc, adjust_jumps)
2213 : {
2214 6566 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
2215 :
2216 : Assert(as->opcode == EEOP_JUMP_IF_NOT_NULL);
2217 : Assert(as->d.jump.jumpdone == -1);
2218 6566 : as->d.jump.jumpdone = state->steps_len;
2219 : }
2220 :
2221 3304 : break;
2222 : }
2223 :
2224 2446 : case T_MinMaxExpr:
2225 : {
2226 2446 : MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
2227 2446 : int nelems = list_length(minmaxexpr->args);
2228 : TypeCacheEntry *typentry;
2229 : FmgrInfo *finfo;
2230 : FunctionCallInfo fcinfo;
2231 : ListCell *lc;
2232 : int off;
2233 :
2234 : /* Look up the btree comparison function for the datatype */
2235 2446 : typentry = lookup_type_cache(minmaxexpr->minmaxtype,
2236 : TYPECACHE_CMP_PROC);
2237 2446 : if (!OidIsValid(typentry->cmp_proc))
2238 0 : ereport(ERROR,
2239 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2240 : errmsg("could not identify a comparison function for type %s",
2241 : format_type_be(minmaxexpr->minmaxtype))));
2242 :
2243 : /*
2244 : * If we enforced permissions checks on index support
2245 : * functions, we'd need to make a check here. But the index
2246 : * support machinery doesn't do that, and thus neither does
2247 : * this code.
2248 : */
2249 :
2250 : /* Perform function lookup */
2251 2446 : finfo = palloc0(sizeof(FmgrInfo));
2252 2446 : fcinfo = palloc0(SizeForFunctionCallInfo(2));
2253 2446 : fmgr_info(typentry->cmp_proc, finfo);
2254 2446 : fmgr_info_set_expr((Node *) node, finfo);
2255 2446 : InitFunctionCallInfoData(*fcinfo, finfo, 2,
2256 : minmaxexpr->inputcollid, NULL, NULL);
2257 :
2258 2446 : scratch.opcode = EEOP_MINMAX;
2259 : /* allocate space to store arguments */
2260 2446 : scratch.d.minmax.values =
2261 2446 : (Datum *) palloc(sizeof(Datum) * nelems);
2262 2446 : scratch.d.minmax.nulls =
2263 2446 : (bool *) palloc(sizeof(bool) * nelems);
2264 2446 : scratch.d.minmax.nelems = nelems;
2265 :
2266 2446 : scratch.d.minmax.op = minmaxexpr->op;
2267 2446 : scratch.d.minmax.finfo = finfo;
2268 2446 : scratch.d.minmax.fcinfo_data = fcinfo;
2269 :
2270 : /* evaluate expressions into minmax->values/nulls */
2271 2446 : off = 0;
2272 7446 : foreach(lc, minmaxexpr->args)
2273 : {
2274 5000 : Expr *e = (Expr *) lfirst(lc);
2275 :
2276 5000 : ExecInitExprRec(e, state,
2277 5000 : &scratch.d.minmax.values[off],
2278 5000 : &scratch.d.minmax.nulls[off]);
2279 5000 : off++;
2280 : }
2281 :
2282 : /* and push the final comparison */
2283 2446 : ExprEvalPushStep(state, &scratch);
2284 2446 : break;
2285 : }
2286 :
2287 5130 : case T_SQLValueFunction:
2288 : {
2289 5130 : SQLValueFunction *svf = (SQLValueFunction *) node;
2290 :
2291 5130 : scratch.opcode = EEOP_SQLVALUEFUNCTION;
2292 5130 : scratch.d.sqlvaluefunction.svf = svf;
2293 :
2294 5130 : ExprEvalPushStep(state, &scratch);
2295 5130 : break;
2296 : }
2297 :
2298 702 : case T_XmlExpr:
2299 : {
2300 702 : XmlExpr *xexpr = (XmlExpr *) node;
2301 702 : int nnamed = list_length(xexpr->named_args);
2302 702 : int nargs = list_length(xexpr->args);
2303 : int off;
2304 : ListCell *arg;
2305 :
2306 702 : scratch.opcode = EEOP_XMLEXPR;
2307 702 : scratch.d.xmlexpr.xexpr = xexpr;
2308 :
2309 : /* allocate space for storing all the arguments */
2310 702 : if (nnamed)
2311 : {
2312 60 : scratch.d.xmlexpr.named_argvalue =
2313 60 : (Datum *) palloc(sizeof(Datum) * nnamed);
2314 60 : scratch.d.xmlexpr.named_argnull =
2315 60 : (bool *) palloc(sizeof(bool) * nnamed);
2316 : }
2317 : else
2318 : {
2319 642 : scratch.d.xmlexpr.named_argvalue = NULL;
2320 642 : scratch.d.xmlexpr.named_argnull = NULL;
2321 : }
2322 :
2323 702 : if (nargs)
2324 : {
2325 618 : scratch.d.xmlexpr.argvalue =
2326 618 : (Datum *) palloc(sizeof(Datum) * nargs);
2327 618 : scratch.d.xmlexpr.argnull =
2328 618 : (bool *) palloc(sizeof(bool) * nargs);
2329 : }
2330 : else
2331 : {
2332 84 : scratch.d.xmlexpr.argvalue = NULL;
2333 84 : scratch.d.xmlexpr.argnull = NULL;
2334 : }
2335 :
2336 : /* prepare argument execution */
2337 702 : off = 0;
2338 870 : foreach(arg, xexpr->named_args)
2339 : {
2340 168 : Expr *e = (Expr *) lfirst(arg);
2341 :
2342 168 : ExecInitExprRec(e, state,
2343 168 : &scratch.d.xmlexpr.named_argvalue[off],
2344 168 : &scratch.d.xmlexpr.named_argnull[off]);
2345 168 : off++;
2346 : }
2347 :
2348 702 : off = 0;
2349 1638 : foreach(arg, xexpr->args)
2350 : {
2351 936 : Expr *e = (Expr *) lfirst(arg);
2352 :
2353 936 : ExecInitExprRec(e, state,
2354 936 : &scratch.d.xmlexpr.argvalue[off],
2355 936 : &scratch.d.xmlexpr.argnull[off]);
2356 936 : off++;
2357 : }
2358 :
2359 : /* and evaluate the actual XML expression */
2360 702 : ExprEvalPushStep(state, &scratch);
2361 702 : break;
2362 : }
2363 :
2364 228 : case T_JsonValueExpr:
2365 : {
2366 228 : JsonValueExpr *jve = (JsonValueExpr *) node;
2367 :
2368 : Assert(jve->raw_expr != NULL);
2369 228 : ExecInitExprRec(jve->raw_expr, state, resv, resnull);
2370 : Assert(jve->formatted_expr != NULL);
2371 228 : ExecInitExprRec(jve->formatted_expr, state, resv, resnull);
2372 228 : break;
2373 : }
2374 :
2375 1342 : case T_JsonConstructorExpr:
2376 : {
2377 1342 : JsonConstructorExpr *ctor = (JsonConstructorExpr *) node;
2378 1342 : List *args = ctor->args;
2379 : ListCell *lc;
2380 1342 : int nargs = list_length(args);
2381 1342 : int argno = 0;
2382 :
2383 1342 : if (ctor->func)
2384 : {
2385 414 : ExecInitExprRec(ctor->func, state, resv, resnull);
2386 : }
2387 928 : else if ((ctor->type == JSCTOR_JSON_PARSE && !ctor->unique) ||
2388 806 : ctor->type == JSCTOR_JSON_SERIALIZE)
2389 : {
2390 : /* Use the value of the first argument as result */
2391 220 : ExecInitExprRec(linitial(args), state, resv, resnull);
2392 : }
2393 : else
2394 : {
2395 : JsonConstructorExprState *jcstate;
2396 :
2397 708 : jcstate = palloc0(sizeof(JsonConstructorExprState));
2398 :
2399 708 : scratch.opcode = EEOP_JSON_CONSTRUCTOR;
2400 708 : scratch.d.json_constructor.jcstate = jcstate;
2401 :
2402 708 : jcstate->constructor = ctor;
2403 708 : jcstate->arg_values = (Datum *) palloc(sizeof(Datum) * nargs);
2404 708 : jcstate->arg_nulls = (bool *) palloc(sizeof(bool) * nargs);
2405 708 : jcstate->arg_types = (Oid *) palloc(sizeof(Oid) * nargs);
2406 708 : jcstate->nargs = nargs;
2407 :
2408 2224 : foreach(lc, args)
2409 : {
2410 1516 : Expr *arg = (Expr *) lfirst(lc);
2411 :
2412 1516 : jcstate->arg_types[argno] = exprType((Node *) arg);
2413 :
2414 1516 : if (IsA(arg, Const))
2415 : {
2416 : /* Don't evaluate const arguments every round */
2417 1390 : Const *con = (Const *) arg;
2418 :
2419 1390 : jcstate->arg_values[argno] = con->constvalue;
2420 1390 : jcstate->arg_nulls[argno] = con->constisnull;
2421 : }
2422 : else
2423 : {
2424 126 : ExecInitExprRec(arg, state,
2425 126 : &jcstate->arg_values[argno],
2426 126 : &jcstate->arg_nulls[argno]);
2427 : }
2428 1516 : argno++;
2429 : }
2430 :
2431 : /* prepare type cache for datum_to_json[b]() */
2432 708 : if (ctor->type == JSCTOR_JSON_SCALAR)
2433 : {
2434 112 : bool is_jsonb =
2435 112 : ctor->returning->format->format_type == JS_FORMAT_JSONB;
2436 :
2437 112 : jcstate->arg_type_cache =
2438 112 : palloc(sizeof(*jcstate->arg_type_cache) * nargs);
2439 :
2440 224 : for (int i = 0; i < nargs; i++)
2441 : {
2442 : JsonTypeCategory category;
2443 : Oid outfuncid;
2444 112 : Oid typid = jcstate->arg_types[i];
2445 :
2446 112 : json_categorize_type(typid, is_jsonb,
2447 : &category, &outfuncid);
2448 :
2449 112 : jcstate->arg_type_cache[i].outfuncid = outfuncid;
2450 112 : jcstate->arg_type_cache[i].category = (int) category;
2451 : }
2452 : }
2453 :
2454 708 : ExprEvalPushStep(state, &scratch);
2455 : }
2456 :
2457 1342 : if (ctor->coercion)
2458 : {
2459 374 : Datum *innermost_caseval = state->innermost_caseval;
2460 374 : bool *innermost_isnull = state->innermost_casenull;
2461 :
2462 374 : state->innermost_caseval = resv;
2463 374 : state->innermost_casenull = resnull;
2464 :
2465 374 : ExecInitExprRec(ctor->coercion, state, resv, resnull);
2466 :
2467 374 : state->innermost_caseval = innermost_caseval;
2468 374 : state->innermost_casenull = innermost_isnull;
2469 : }
2470 : }
2471 1342 : break;
2472 :
2473 350 : case T_JsonIsPredicate:
2474 : {
2475 350 : JsonIsPredicate *pred = (JsonIsPredicate *) node;
2476 :
2477 350 : ExecInitExprRec((Expr *) pred->expr, state, resv, resnull);
2478 :
2479 350 : scratch.opcode = EEOP_IS_JSON;
2480 350 : scratch.d.is_json.pred = pred;
2481 :
2482 350 : ExprEvalPushStep(state, &scratch);
2483 350 : break;
2484 : }
2485 :
2486 2692 : case T_JsonExpr:
2487 : {
2488 2692 : JsonExpr *jsexpr = castNode(JsonExpr, node);
2489 :
2490 : /*
2491 : * No need to initialize a full JsonExprState For
2492 : * JSON_TABLE(), because the upstream caller tfuncFetchRows()
2493 : * is only interested in the value of formatted_expr.
2494 : */
2495 2692 : if (jsexpr->op == JSON_TABLE_OP)
2496 404 : ExecInitExprRec((Expr *) jsexpr->formatted_expr, state,
2497 : resv, resnull);
2498 : else
2499 2288 : ExecInitJsonExpr(jsexpr, state, resv, resnull, &scratch);
2500 2692 : break;
2501 : }
2502 :
2503 25152 : case T_NullTest:
2504 : {
2505 25152 : NullTest *ntest = (NullTest *) node;
2506 :
2507 25152 : if (ntest->nulltesttype == IS_NULL)
2508 : {
2509 7492 : if (ntest->argisrow)
2510 228 : scratch.opcode = EEOP_NULLTEST_ROWISNULL;
2511 : else
2512 7264 : scratch.opcode = EEOP_NULLTEST_ISNULL;
2513 : }
2514 17660 : else if (ntest->nulltesttype == IS_NOT_NULL)
2515 : {
2516 17660 : if (ntest->argisrow)
2517 222 : scratch.opcode = EEOP_NULLTEST_ROWISNOTNULL;
2518 : else
2519 17438 : scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
2520 : }
2521 : else
2522 : {
2523 0 : elog(ERROR, "unrecognized nulltesttype: %d",
2524 : (int) ntest->nulltesttype);
2525 : }
2526 : /* initialize cache in case it's a row test */
2527 25152 : scratch.d.nulltest_row.rowcache.cacheptr = NULL;
2528 :
2529 : /* first evaluate argument into result variable */
2530 25152 : ExecInitExprRec(ntest->arg, state,
2531 : resv, resnull);
2532 :
2533 : /* then push the test of that argument */
2534 25152 : ExprEvalPushStep(state, &scratch);
2535 25152 : break;
2536 : }
2537 :
2538 1256 : case T_BooleanTest:
2539 : {
2540 1256 : BooleanTest *btest = (BooleanTest *) node;
2541 :
2542 : /*
2543 : * Evaluate argument, directly into result datum. That's ok,
2544 : * because resv/resnull is definitely not used anywhere else,
2545 : * and will get overwritten by the below EEOP_BOOLTEST_IS_*
2546 : * step.
2547 : */
2548 1256 : ExecInitExprRec(btest->arg, state, resv, resnull);
2549 :
2550 1256 : switch (btest->booltesttype)
2551 : {
2552 432 : case IS_TRUE:
2553 432 : scratch.opcode = EEOP_BOOLTEST_IS_TRUE;
2554 432 : break;
2555 398 : case IS_NOT_TRUE:
2556 398 : scratch.opcode = EEOP_BOOLTEST_IS_NOT_TRUE;
2557 398 : break;
2558 84 : case IS_FALSE:
2559 84 : scratch.opcode = EEOP_BOOLTEST_IS_FALSE;
2560 84 : break;
2561 170 : case IS_NOT_FALSE:
2562 170 : scratch.opcode = EEOP_BOOLTEST_IS_NOT_FALSE;
2563 170 : break;
2564 58 : case IS_UNKNOWN:
2565 : /* Same as scalar IS NULL test */
2566 58 : scratch.opcode = EEOP_NULLTEST_ISNULL;
2567 58 : break;
2568 114 : case IS_NOT_UNKNOWN:
2569 : /* Same as scalar IS NOT NULL test */
2570 114 : scratch.opcode = EEOP_NULLTEST_ISNOTNULL;
2571 114 : break;
2572 0 : default:
2573 0 : elog(ERROR, "unrecognized booltesttype: %d",
2574 : (int) btest->booltesttype);
2575 : }
2576 :
2577 1256 : ExprEvalPushStep(state, &scratch);
2578 1256 : break;
2579 : }
2580 :
2581 8934 : case T_CoerceToDomain:
2582 : {
2583 8934 : CoerceToDomain *ctest = (CoerceToDomain *) node;
2584 :
2585 8934 : ExecInitCoerceToDomain(&scratch, ctest, state,
2586 : resv, resnull);
2587 8934 : break;
2588 : }
2589 :
2590 12844 : case T_CoerceToDomainValue:
2591 : {
2592 : /*
2593 : * Read from location identified by innermost_domainval. Note
2594 : * that innermost_domainval could be NULL, if we're compiling
2595 : * a standalone domain check rather than one embedded in a
2596 : * larger expression. In that case we must read from
2597 : * econtext->domainValue_datum. We'll take care of that
2598 : * scenario at runtime.
2599 : */
2600 12844 : scratch.opcode = EEOP_DOMAIN_TESTVAL;
2601 : /* we share instruction union variant with case testval */
2602 12844 : scratch.d.casetest.value = state->innermost_domainval;
2603 12844 : scratch.d.casetest.isnull = state->innermost_domainnull;
2604 :
2605 12844 : ExprEvalPushStep(state, &scratch);
2606 12844 : break;
2607 : }
2608 :
2609 2 : case T_CurrentOfExpr:
2610 : {
2611 2 : scratch.opcode = EEOP_CURRENTOFEXPR;
2612 2 : ExprEvalPushStep(state, &scratch);
2613 2 : break;
2614 : }
2615 :
2616 504 : case T_NextValueExpr:
2617 : {
2618 504 : NextValueExpr *nve = (NextValueExpr *) node;
2619 :
2620 504 : scratch.opcode = EEOP_NEXTVALUEEXPR;
2621 504 : scratch.d.nextvalueexpr.seqid = nve->seqid;
2622 504 : scratch.d.nextvalueexpr.seqtypid = nve->typeId;
2623 :
2624 504 : ExprEvalPushStep(state, &scratch);
2625 504 : break;
2626 : }
2627 :
2628 372 : case T_ReturningExpr:
2629 : {
2630 372 : ReturningExpr *rexpr = (ReturningExpr *) node;
2631 : int retstep;
2632 :
2633 : /* Skip expression evaluation if OLD/NEW row doesn't exist */
2634 372 : scratch.opcode = EEOP_RETURNINGEXPR;
2635 372 : scratch.d.returningexpr.nullflag = rexpr->retold ?
2636 : EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL;
2637 372 : scratch.d.returningexpr.jumpdone = -1; /* set below */
2638 372 : ExprEvalPushStep(state, &scratch);
2639 372 : retstep = state->steps_len - 1;
2640 :
2641 : /* Steps to evaluate expression to return */
2642 372 : ExecInitExprRec(rexpr->retexpr, state, resv, resnull);
2643 :
2644 : /* Jump target used if OLD/NEW row doesn't exist */
2645 372 : state->steps[retstep].d.returningexpr.jumpdone = state->steps_len;
2646 :
2647 : /* Update ExprState flags */
2648 372 : if (rexpr->retold)
2649 186 : state->flags |= EEO_FLAG_HAS_OLD;
2650 : else
2651 186 : state->flags |= EEO_FLAG_HAS_NEW;
2652 :
2653 372 : break;
2654 : }
2655 :
2656 0 : default:
2657 0 : elog(ERROR, "unrecognized node type: %d",
2658 : (int) nodeTag(node));
2659 : break;
2660 : }
2661 4979494 : }
2662 :
2663 : /*
2664 : * Add another expression evaluation step to ExprState->steps.
2665 : *
2666 : * Note that this potentially re-allocates es->steps, therefore no pointer
2667 : * into that array may be used while the expression is still being built.
2668 : */
2669 : void
2670 11222466 : ExprEvalPushStep(ExprState *es, const ExprEvalStep *s)
2671 : {
2672 11222466 : if (es->steps_alloc == 0)
2673 : {
2674 2279562 : es->steps_alloc = 16;
2675 2279562 : es->steps = palloc(sizeof(ExprEvalStep) * es->steps_alloc);
2676 : }
2677 8942904 : else if (es->steps_alloc == es->steps_len)
2678 : {
2679 85788 : es->steps_alloc *= 2;
2680 85788 : es->steps = repalloc(es->steps,
2681 85788 : sizeof(ExprEvalStep) * es->steps_alloc);
2682 : }
2683 :
2684 11222466 : memcpy(&es->steps[es->steps_len++], s, sizeof(ExprEvalStep));
2685 11222466 : }
2686 :
2687 : /*
2688 : * Perform setup necessary for the evaluation of a function-like expression,
2689 : * appending argument evaluation steps to the steps list in *state, and
2690 : * setting up *scratch so it is ready to be pushed.
2691 : *
2692 : * *scratch is not pushed here, so that callers may override the opcode,
2693 : * which is useful for function-like cases like DISTINCT.
2694 : */
2695 : static void
2696 1439634 : ExecInitFunc(ExprEvalStep *scratch, Expr *node, List *args, Oid funcid,
2697 : Oid inputcollid, ExprState *state)
2698 : {
2699 1439634 : int nargs = list_length(args);
2700 : AclResult aclresult;
2701 : FmgrInfo *flinfo;
2702 : FunctionCallInfo fcinfo;
2703 : int argno;
2704 : ListCell *lc;
2705 :
2706 : /* Check permission to call function */
2707 1439634 : aclresult = object_aclcheck(ProcedureRelationId, funcid, GetUserId(), ACL_EXECUTE);
2708 1439634 : if (aclresult != ACLCHECK_OK)
2709 74 : aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(funcid));
2710 1439560 : InvokeFunctionExecuteHook(funcid);
2711 :
2712 : /*
2713 : * Safety check on nargs. Under normal circumstances this should never
2714 : * fail, as parser should check sooner. But possibly it might fail if
2715 : * server has been compiled with FUNC_MAX_ARGS smaller than some functions
2716 : * declared in pg_proc?
2717 : */
2718 1439560 : if (nargs > FUNC_MAX_ARGS)
2719 0 : ereport(ERROR,
2720 : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2721 : errmsg_plural("cannot pass more than %d argument to a function",
2722 : "cannot pass more than %d arguments to a function",
2723 : FUNC_MAX_ARGS,
2724 : FUNC_MAX_ARGS)));
2725 :
2726 : /* Allocate function lookup data and parameter workspace for this call */
2727 1439560 : scratch->d.func.finfo = palloc0(sizeof(FmgrInfo));
2728 1439560 : scratch->d.func.fcinfo_data = palloc0(SizeForFunctionCallInfo(nargs));
2729 1439560 : flinfo = scratch->d.func.finfo;
2730 1439560 : fcinfo = scratch->d.func.fcinfo_data;
2731 :
2732 : /* Set up the primary fmgr lookup information */
2733 1439560 : fmgr_info(funcid, flinfo);
2734 1439560 : fmgr_info_set_expr((Node *) node, flinfo);
2735 :
2736 : /* Initialize function call parameter structure too */
2737 1439560 : InitFunctionCallInfoData(*fcinfo, flinfo,
2738 : nargs, inputcollid, NULL, NULL);
2739 :
2740 : /* Keep extra copies of this info to save an indirection at runtime */
2741 1439560 : scratch->d.func.fn_addr = flinfo->fn_addr;
2742 1439560 : scratch->d.func.nargs = nargs;
2743 :
2744 : /* We only support non-set functions here */
2745 1439560 : if (flinfo->fn_retset)
2746 0 : ereport(ERROR,
2747 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2748 : errmsg("set-valued function called in context that cannot accept a set"),
2749 : state->parent ?
2750 : executor_errposition(state->parent->state,
2751 : exprLocation((Node *) node)) : 0));
2752 :
2753 : /* Build code to evaluate arguments directly into the fcinfo struct */
2754 1439560 : argno = 0;
2755 3828676 : foreach(lc, args)
2756 : {
2757 2389116 : Expr *arg = (Expr *) lfirst(lc);
2758 :
2759 2389116 : if (IsA(arg, Const))
2760 : {
2761 : /*
2762 : * Don't evaluate const arguments every round; especially
2763 : * interesting for constants in comparisons.
2764 : */
2765 918732 : Const *con = (Const *) arg;
2766 :
2767 918732 : fcinfo->args[argno].value = con->constvalue;
2768 918732 : fcinfo->args[argno].isnull = con->constisnull;
2769 : }
2770 : else
2771 : {
2772 1470384 : ExecInitExprRec(arg, state,
2773 : &fcinfo->args[argno].value,
2774 : &fcinfo->args[argno].isnull);
2775 : }
2776 2389116 : argno++;
2777 : }
2778 :
2779 : /* Insert appropriate opcode depending on strictness and stats level */
2780 1439560 : if (pgstat_track_functions <= flinfo->fn_stats)
2781 : {
2782 1439346 : if (flinfo->fn_strict && nargs > 0)
2783 1287942 : scratch->opcode = EEOP_FUNCEXPR_STRICT;
2784 : else
2785 151404 : scratch->opcode = EEOP_FUNCEXPR;
2786 : }
2787 : else
2788 : {
2789 214 : if (flinfo->fn_strict && nargs > 0)
2790 6 : scratch->opcode = EEOP_FUNCEXPR_STRICT_FUSAGE;
2791 : else
2792 208 : scratch->opcode = EEOP_FUNCEXPR_FUSAGE;
2793 : }
2794 1439560 : }
2795 :
2796 : /*
2797 : * Append the steps necessary for the evaluation of a SubPlan node to
2798 : * ExprState->steps.
2799 : *
2800 : * subplan - SubPlan expression to evaluate
2801 : * state - ExprState to whose ->steps to append the necessary operations
2802 : * resv / resnull - where to store the result of the node into
2803 : */
2804 : static void
2805 26424 : ExecInitSubPlanExpr(SubPlan *subplan,
2806 : ExprState *state,
2807 : Datum *resv, bool *resnull)
2808 : {
2809 26424 : ExprEvalStep scratch = {0};
2810 : SubPlanState *sstate;
2811 : ListCell *pvar;
2812 : ListCell *l;
2813 :
2814 26424 : if (!state->parent)
2815 0 : elog(ERROR, "SubPlan found with no parent plan");
2816 :
2817 : /*
2818 : * Generate steps to evaluate input arguments for the subplan.
2819 : *
2820 : * We evaluate the argument expressions into ExprState's resvalue/resnull,
2821 : * and then use PARAM_SET to update the parameter. We do that, instead of
2822 : * evaluating directly into the param, to avoid depending on the pointer
2823 : * value remaining stable / being included in the generated expression. No
2824 : * danger of conflicts with other uses of resvalue/resnull as storing and
2825 : * using the value always is in subsequent steps.
2826 : *
2827 : * Any calculation we have to do can be done in the parent econtext, since
2828 : * the Param values don't need to have per-query lifetime.
2829 : */
2830 : Assert(list_length(subplan->parParam) == list_length(subplan->args));
2831 66922 : forboth(l, subplan->parParam, pvar, subplan->args)
2832 : {
2833 40498 : int paramid = lfirst_int(l);
2834 40498 : Expr *arg = (Expr *) lfirst(pvar);
2835 :
2836 40498 : ExecInitExprRec(arg, state,
2837 : &state->resvalue, &state->resnull);
2838 :
2839 40498 : scratch.opcode = EEOP_PARAM_SET;
2840 40498 : scratch.d.param.paramid = paramid;
2841 : /* paramtype's not actually used, but we might as well fill it */
2842 40498 : scratch.d.param.paramtype = exprType((Node *) arg);
2843 40498 : ExprEvalPushStep(state, &scratch);
2844 : }
2845 :
2846 26424 : sstate = ExecInitSubPlan(subplan, state->parent);
2847 :
2848 : /* add SubPlanState nodes to state->parent->subPlan */
2849 26424 : state->parent->subPlan = lappend(state->parent->subPlan,
2850 : sstate);
2851 :
2852 26424 : scratch.opcode = EEOP_SUBPLAN;
2853 26424 : scratch.resvalue = resv;
2854 26424 : scratch.resnull = resnull;
2855 26424 : scratch.d.subplan.sstate = sstate;
2856 :
2857 26424 : ExprEvalPushStep(state, &scratch);
2858 26424 : }
2859 :
2860 : /*
2861 : * Add expression steps performing setup that's needed before any of the
2862 : * main execution of the expression.
2863 : */
2864 : static void
2865 2188188 : ExecCreateExprSetupSteps(ExprState *state, Node *node)
2866 : {
2867 2188188 : ExprSetupInfo info = {0, 0, 0, 0, 0, NIL};
2868 :
2869 : /* Prescan to find out what we need. */
2870 2188188 : expr_setup_walker(node, &info);
2871 :
2872 : /* And generate those steps. */
2873 2188188 : ExecPushExprSetupSteps(state, &info);
2874 2188188 : }
2875 :
2876 : /*
2877 : * Add steps performing expression setup as indicated by "info".
2878 : * This is useful when building an ExprState covering more than one expression.
2879 : */
2880 : static void
2881 2248020 : ExecPushExprSetupSteps(ExprState *state, ExprSetupInfo *info)
2882 : {
2883 2248020 : ExprEvalStep scratch = {0};
2884 : ListCell *lc;
2885 :
2886 2248020 : scratch.resvalue = NULL;
2887 2248020 : scratch.resnull = NULL;
2888 :
2889 : /*
2890 : * Add steps deforming the ExprState's inner/outer/scan/old/new slots as
2891 : * much as required by any Vars appearing in the expression.
2892 : */
2893 2248020 : if (info->last_inner > 0)
2894 : {
2895 163718 : scratch.opcode = EEOP_INNER_FETCHSOME;
2896 163718 : scratch.d.fetch.last_var = info->last_inner;
2897 163718 : scratch.d.fetch.fixed = false;
2898 163718 : scratch.d.fetch.kind = NULL;
2899 163718 : scratch.d.fetch.known_desc = NULL;
2900 163718 : if (ExecComputeSlotInfo(state, &scratch))
2901 154166 : ExprEvalPushStep(state, &scratch);
2902 : }
2903 2248020 : if (info->last_outer > 0)
2904 : {
2905 295296 : scratch.opcode = EEOP_OUTER_FETCHSOME;
2906 295296 : scratch.d.fetch.last_var = info->last_outer;
2907 295296 : scratch.d.fetch.fixed = false;
2908 295296 : scratch.d.fetch.kind = NULL;
2909 295296 : scratch.d.fetch.known_desc = NULL;
2910 295296 : if (ExecComputeSlotInfo(state, &scratch))
2911 161792 : ExprEvalPushStep(state, &scratch);
2912 : }
2913 2248020 : if (info->last_scan > 0)
2914 : {
2915 557966 : scratch.opcode = EEOP_SCAN_FETCHSOME;
2916 557966 : scratch.d.fetch.last_var = info->last_scan;
2917 557966 : scratch.d.fetch.fixed = false;
2918 557966 : scratch.d.fetch.kind = NULL;
2919 557966 : scratch.d.fetch.known_desc = NULL;
2920 557966 : if (ExecComputeSlotInfo(state, &scratch))
2921 528520 : ExprEvalPushStep(state, &scratch);
2922 : }
2923 2248020 : if (info->last_old > 0)
2924 : {
2925 322 : scratch.opcode = EEOP_OLD_FETCHSOME;
2926 322 : scratch.d.fetch.last_var = info->last_old;
2927 322 : scratch.d.fetch.fixed = false;
2928 322 : scratch.d.fetch.kind = NULL;
2929 322 : scratch.d.fetch.known_desc = NULL;
2930 322 : if (ExecComputeSlotInfo(state, &scratch))
2931 322 : ExprEvalPushStep(state, &scratch);
2932 : }
2933 2248020 : if (info->last_new > 0)
2934 : {
2935 324 : scratch.opcode = EEOP_NEW_FETCHSOME;
2936 324 : scratch.d.fetch.last_var = info->last_new;
2937 324 : scratch.d.fetch.fixed = false;
2938 324 : scratch.d.fetch.kind = NULL;
2939 324 : scratch.d.fetch.known_desc = NULL;
2940 324 : if (ExecComputeSlotInfo(state, &scratch))
2941 324 : ExprEvalPushStep(state, &scratch);
2942 : }
2943 :
2944 : /*
2945 : * Add steps to execute any MULTIEXPR SubPlans appearing in the
2946 : * expression. We need to evaluate these before any of the Params
2947 : * referencing their outputs are used, but after we've prepared for any
2948 : * Var references they may contain. (There cannot be cross-references
2949 : * between MULTIEXPR SubPlans, so we needn't worry about their order.)
2950 : */
2951 2248146 : foreach(lc, info->multiexpr_subplans)
2952 : {
2953 126 : SubPlan *subplan = (SubPlan *) lfirst(lc);
2954 :
2955 : Assert(subplan->subLinkType == MULTIEXPR_SUBLINK);
2956 :
2957 : /* The result can be ignored, but we better put it somewhere */
2958 126 : ExecInitSubPlanExpr(subplan, state,
2959 : &state->resvalue, &state->resnull);
2960 : }
2961 2248020 : }
2962 :
2963 : /*
2964 : * expr_setup_walker: expression walker for ExecCreateExprSetupSteps
2965 : */
2966 : static bool
2967 10453292 : expr_setup_walker(Node *node, ExprSetupInfo *info)
2968 : {
2969 10453292 : if (node == NULL)
2970 388350 : return false;
2971 10064942 : if (IsA(node, Var))
2972 : {
2973 2151082 : Var *variable = (Var *) node;
2974 2151082 : AttrNumber attnum = variable->varattno;
2975 :
2976 2151082 : switch (variable->varno)
2977 : {
2978 309970 : case INNER_VAR:
2979 309970 : info->last_inner = Max(info->last_inner, attnum);
2980 309970 : break;
2981 :
2982 695058 : case OUTER_VAR:
2983 695058 : info->last_outer = Max(info->last_outer, attnum);
2984 695058 : break;
2985 :
2986 : /* INDEX_VAR is handled by default case */
2987 :
2988 1146054 : default:
2989 1146054 : switch (variable->varreturningtype)
2990 : {
2991 1143044 : case VAR_RETURNING_DEFAULT:
2992 1143044 : info->last_scan = Max(info->last_scan, attnum);
2993 1143044 : break;
2994 1504 : case VAR_RETURNING_OLD:
2995 1504 : info->last_old = Max(info->last_old, attnum);
2996 1504 : break;
2997 1506 : case VAR_RETURNING_NEW:
2998 1506 : info->last_new = Max(info->last_new, attnum);
2999 1506 : break;
3000 : }
3001 1146054 : break;
3002 : }
3003 2151082 : return false;
3004 : }
3005 :
3006 : /* Collect all MULTIEXPR SubPlans, too */
3007 7913860 : if (IsA(node, SubPlan))
3008 : {
3009 26424 : SubPlan *subplan = (SubPlan *) node;
3010 :
3011 26424 : if (subplan->subLinkType == MULTIEXPR_SUBLINK)
3012 126 : info->multiexpr_subplans = lappend(info->multiexpr_subplans,
3013 : subplan);
3014 : }
3015 :
3016 : /*
3017 : * Don't examine the arguments or filters of Aggrefs or WindowFuncs,
3018 : * because those do not represent expressions to be evaluated within the
3019 : * calling expression's econtext. GroupingFunc arguments are never
3020 : * evaluated at all.
3021 : */
3022 7913860 : if (IsA(node, Aggref))
3023 49914 : return false;
3024 7863946 : if (IsA(node, WindowFunc))
3025 3164 : return false;
3026 7860782 : if (IsA(node, GroupingFunc))
3027 350 : return false;
3028 7860432 : return expression_tree_walker(node, expr_setup_walker, info);
3029 : }
3030 :
3031 : /*
3032 : * Compute additional information for EEOP_*_FETCHSOME ops.
3033 : *
3034 : * The goal is to determine whether a slot is 'fixed', that is, every
3035 : * evaluation of the expression will have the same type of slot, with an
3036 : * equivalent descriptor.
3037 : *
3038 : * EEOP_OLD_FETCHSOME and EEOP_NEW_FETCHSOME are used to process RETURNING, if
3039 : * OLD/NEW columns are referred to explicitly. In both cases, the tuple
3040 : * descriptor comes from the parent scan node, so we treat them the same as
3041 : * EEOP_SCAN_FETCHSOME.
3042 : *
3043 : * Returns true if the deforming step is required, false otherwise.
3044 : */
3045 : static bool
3046 1063132 : ExecComputeSlotInfo(ExprState *state, ExprEvalStep *op)
3047 : {
3048 1063132 : PlanState *parent = state->parent;
3049 1063132 : TupleDesc desc = NULL;
3050 1063132 : const TupleTableSlotOps *tts_ops = NULL;
3051 1063132 : bool isfixed = false;
3052 1063132 : ExprEvalOp opcode = op->opcode;
3053 :
3054 : Assert(opcode == EEOP_INNER_FETCHSOME ||
3055 : opcode == EEOP_OUTER_FETCHSOME ||
3056 : opcode == EEOP_SCAN_FETCHSOME ||
3057 : opcode == EEOP_OLD_FETCHSOME ||
3058 : opcode == EEOP_NEW_FETCHSOME);
3059 :
3060 1063132 : if (op->d.fetch.known_desc != NULL)
3061 : {
3062 45506 : desc = op->d.fetch.known_desc;
3063 45506 : tts_ops = op->d.fetch.kind;
3064 45506 : isfixed = op->d.fetch.kind != NULL;
3065 : }
3066 1017626 : else if (!parent)
3067 : {
3068 15058 : isfixed = false;
3069 : }
3070 1002568 : else if (opcode == EEOP_INNER_FETCHSOME)
3071 : {
3072 163630 : PlanState *is = innerPlanState(parent);
3073 :
3074 163630 : if (parent->inneropsset && !parent->inneropsfixed)
3075 : {
3076 0 : isfixed = false;
3077 : }
3078 163630 : else if (parent->inneropsset && parent->innerops)
3079 : {
3080 0 : isfixed = true;
3081 0 : tts_ops = parent->innerops;
3082 0 : desc = ExecGetResultType(is);
3083 : }
3084 163630 : else if (is)
3085 : {
3086 161082 : tts_ops = ExecGetResultSlotOps(is, &isfixed);
3087 161082 : desc = ExecGetResultType(is);
3088 : }
3089 : }
3090 838938 : else if (opcode == EEOP_OUTER_FETCHSOME)
3091 : {
3092 295118 : PlanState *os = outerPlanState(parent);
3093 :
3094 295118 : if (parent->outeropsset && !parent->outeropsfixed)
3095 : {
3096 1106 : isfixed = false;
3097 : }
3098 294012 : else if (parent->outeropsset && parent->outerops)
3099 : {
3100 40944 : isfixed = true;
3101 40944 : tts_ops = parent->outerops;
3102 40944 : desc = ExecGetResultType(os);
3103 : }
3104 253068 : else if (os)
3105 : {
3106 253056 : tts_ops = ExecGetResultSlotOps(os, &isfixed);
3107 253056 : desc = ExecGetResultType(os);
3108 : }
3109 : }
3110 543820 : else if (opcode == EEOP_SCAN_FETCHSOME ||
3111 324 : opcode == EEOP_OLD_FETCHSOME ||
3112 : opcode == EEOP_NEW_FETCHSOME)
3113 : {
3114 543820 : desc = parent->scandesc;
3115 :
3116 543820 : if (parent->scanops)
3117 522224 : tts_ops = parent->scanops;
3118 :
3119 543820 : if (parent->scanopsset)
3120 522224 : isfixed = parent->scanopsfixed;
3121 : }
3122 :
3123 1063132 : if (isfixed && desc != NULL && tts_ops != NULL)
3124 : {
3125 998040 : op->d.fetch.fixed = true;
3126 998040 : op->d.fetch.kind = tts_ops;
3127 998040 : op->d.fetch.known_desc = desc;
3128 : }
3129 : else
3130 : {
3131 65092 : op->d.fetch.fixed = false;
3132 65092 : op->d.fetch.kind = NULL;
3133 65092 : op->d.fetch.known_desc = NULL;
3134 : }
3135 :
3136 : /* if the slot is known to always virtual we never need to deform */
3137 1063132 : if (op->d.fetch.fixed && op->d.fetch.kind == &TTSOpsVirtual)
3138 178628 : return false;
3139 :
3140 884504 : return true;
3141 : }
3142 :
3143 : /*
3144 : * Prepare step for the evaluation of a whole-row variable.
3145 : * The caller still has to push the step.
3146 : */
3147 : static void
3148 4246 : ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state)
3149 : {
3150 4246 : PlanState *parent = state->parent;
3151 :
3152 : /* fill in all but the target */
3153 4246 : scratch->opcode = EEOP_WHOLEROW;
3154 4246 : scratch->d.wholerow.var = variable;
3155 4246 : scratch->d.wholerow.first = true;
3156 4246 : scratch->d.wholerow.slow = false;
3157 4246 : scratch->d.wholerow.tupdesc = NULL; /* filled at runtime */
3158 4246 : scratch->d.wholerow.junkFilter = NULL;
3159 :
3160 : /* update ExprState flags if Var refers to OLD/NEW */
3161 4246 : if (variable->varreturningtype == VAR_RETURNING_OLD)
3162 108 : state->flags |= EEO_FLAG_HAS_OLD;
3163 4138 : else if (variable->varreturningtype == VAR_RETURNING_NEW)
3164 108 : state->flags |= EEO_FLAG_HAS_NEW;
3165 :
3166 : /*
3167 : * If the input tuple came from a subquery, it might contain "resjunk"
3168 : * columns (such as GROUP BY or ORDER BY columns), which we don't want to
3169 : * keep in the whole-row result. We can get rid of such columns by
3170 : * passing the tuple through a JunkFilter --- but to make one, we have to
3171 : * lay our hands on the subquery's targetlist. Fortunately, there are not
3172 : * very many cases where this can happen, and we can identify all of them
3173 : * by examining our parent PlanState. We assume this is not an issue in
3174 : * standalone expressions that don't have parent plans. (Whole-row Vars
3175 : * can occur in such expressions, but they will always be referencing
3176 : * table rows.)
3177 : */
3178 4246 : if (parent)
3179 : {
3180 4214 : PlanState *subplan = NULL;
3181 :
3182 4214 : switch (nodeTag(parent))
3183 : {
3184 310 : case T_SubqueryScanState:
3185 310 : subplan = ((SubqueryScanState *) parent)->subplan;
3186 310 : break;
3187 172 : case T_CteScanState:
3188 172 : subplan = ((CteScanState *) parent)->cteplanstate;
3189 172 : break;
3190 3732 : default:
3191 3732 : break;
3192 : }
3193 :
3194 4214 : if (subplan)
3195 : {
3196 482 : bool junk_filter_needed = false;
3197 : ListCell *tlist;
3198 :
3199 : /* Detect whether subplan tlist actually has any junk columns */
3200 1458 : foreach(tlist, subplan->plan->targetlist)
3201 : {
3202 988 : TargetEntry *tle = (TargetEntry *) lfirst(tlist);
3203 :
3204 988 : if (tle->resjunk)
3205 : {
3206 12 : junk_filter_needed = true;
3207 12 : break;
3208 : }
3209 : }
3210 :
3211 : /* If so, build the junkfilter now */
3212 482 : if (junk_filter_needed)
3213 : {
3214 12 : scratch->d.wholerow.junkFilter =
3215 12 : ExecInitJunkFilter(subplan->plan->targetlist,
3216 : ExecInitExtraTupleSlot(parent->state, NULL,
3217 : &TTSOpsVirtual));
3218 : }
3219 : }
3220 : }
3221 4246 : }
3222 :
3223 : /*
3224 : * Prepare evaluation of a SubscriptingRef expression.
3225 : */
3226 : static void
3227 24618 : ExecInitSubscriptingRef(ExprEvalStep *scratch, SubscriptingRef *sbsref,
3228 : ExprState *state, Datum *resv, bool *resnull)
3229 : {
3230 24618 : bool isAssignment = (sbsref->refassgnexpr != NULL);
3231 24618 : int nupper = list_length(sbsref->refupperindexpr);
3232 24618 : int nlower = list_length(sbsref->reflowerindexpr);
3233 : const SubscriptRoutines *sbsroutines;
3234 : SubscriptingRefState *sbsrefstate;
3235 : SubscriptExecSteps methods;
3236 : char *ptr;
3237 24618 : List *adjust_jumps = NIL;
3238 : ListCell *lc;
3239 : int i;
3240 :
3241 : /* Look up the subscripting support methods */
3242 24618 : sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
3243 24618 : if (!sbsroutines)
3244 0 : ereport(ERROR,
3245 : (errcode(ERRCODE_DATATYPE_MISMATCH),
3246 : errmsg("cannot subscript type %s because it does not support subscripting",
3247 : format_type_be(sbsref->refcontainertype)),
3248 : state->parent ?
3249 : executor_errposition(state->parent->state,
3250 : exprLocation((Node *) sbsref)) : 0));
3251 :
3252 : /* Allocate sbsrefstate, with enough space for per-subscript arrays too */
3253 24618 : sbsrefstate = palloc0(MAXALIGN(sizeof(SubscriptingRefState)) +
3254 24618 : (nupper + nlower) * (sizeof(Datum) +
3255 : 2 * sizeof(bool)));
3256 :
3257 : /* Fill constant fields of SubscriptingRefState */
3258 24618 : sbsrefstate->isassignment = isAssignment;
3259 24618 : sbsrefstate->numupper = nupper;
3260 24618 : sbsrefstate->numlower = nlower;
3261 : /* Set up per-subscript arrays */
3262 24618 : ptr = ((char *) sbsrefstate) + MAXALIGN(sizeof(SubscriptingRefState));
3263 24618 : sbsrefstate->upperindex = (Datum *) ptr;
3264 24618 : ptr += nupper * sizeof(Datum);
3265 24618 : sbsrefstate->lowerindex = (Datum *) ptr;
3266 24618 : ptr += nlower * sizeof(Datum);
3267 24618 : sbsrefstate->upperprovided = (bool *) ptr;
3268 24618 : ptr += nupper * sizeof(bool);
3269 24618 : sbsrefstate->lowerprovided = (bool *) ptr;
3270 24618 : ptr += nlower * sizeof(bool);
3271 24618 : sbsrefstate->upperindexnull = (bool *) ptr;
3272 24618 : ptr += nupper * sizeof(bool);
3273 24618 : sbsrefstate->lowerindexnull = (bool *) ptr;
3274 : /* ptr += nlower * sizeof(bool); */
3275 :
3276 : /*
3277 : * Let the container-type-specific code have a chance. It must fill the
3278 : * "methods" struct with function pointers for us to possibly use in
3279 : * execution steps below; and it can optionally set up some data pointed
3280 : * to by the workspace field.
3281 : */
3282 24618 : memset(&methods, 0, sizeof(methods));
3283 24618 : sbsroutines->exec_setup(sbsref, sbsrefstate, &methods);
3284 :
3285 : /*
3286 : * Evaluate array input. It's safe to do so into resv/resnull, because we
3287 : * won't use that as target for any of the other subexpressions, and it'll
3288 : * be overwritten by the final EEOP_SBSREF_FETCH/ASSIGN step, which is
3289 : * pushed last.
3290 : */
3291 24618 : ExecInitExprRec(sbsref->refexpr, state, resv, resnull);
3292 :
3293 : /*
3294 : * If refexpr yields NULL, and the operation should be strict, then result
3295 : * is NULL. We can implement this with just JUMP_IF_NULL, since we
3296 : * evaluated the array into the desired target location.
3297 : */
3298 24618 : if (!isAssignment && sbsroutines->fetch_strict)
3299 : {
3300 23298 : scratch->opcode = EEOP_JUMP_IF_NULL;
3301 23298 : scratch->d.jump.jumpdone = -1; /* adjust later */
3302 23298 : ExprEvalPushStep(state, scratch);
3303 23298 : adjust_jumps = lappend_int(adjust_jumps,
3304 23298 : state->steps_len - 1);
3305 : }
3306 :
3307 : /* Evaluate upper subscripts */
3308 24618 : i = 0;
3309 49820 : foreach(lc, sbsref->refupperindexpr)
3310 : {
3311 25202 : Expr *e = (Expr *) lfirst(lc);
3312 :
3313 : /* When slicing, individual subscript bounds can be omitted */
3314 25202 : if (!e)
3315 : {
3316 78 : sbsrefstate->upperprovided[i] = false;
3317 78 : sbsrefstate->upperindexnull[i] = true;
3318 : }
3319 : else
3320 : {
3321 25124 : sbsrefstate->upperprovided[i] = true;
3322 : /* Each subscript is evaluated into appropriate array entry */
3323 25124 : ExecInitExprRec(e, state,
3324 25124 : &sbsrefstate->upperindex[i],
3325 25124 : &sbsrefstate->upperindexnull[i]);
3326 : }
3327 25202 : i++;
3328 : }
3329 :
3330 : /* Evaluate lower subscripts similarly */
3331 24618 : i = 0;
3332 25194 : foreach(lc, sbsref->reflowerindexpr)
3333 : {
3334 576 : Expr *e = (Expr *) lfirst(lc);
3335 :
3336 : /* When slicing, individual subscript bounds can be omitted */
3337 576 : if (!e)
3338 : {
3339 78 : sbsrefstate->lowerprovided[i] = false;
3340 78 : sbsrefstate->lowerindexnull[i] = true;
3341 : }
3342 : else
3343 : {
3344 498 : sbsrefstate->lowerprovided[i] = true;
3345 : /* Each subscript is evaluated into appropriate array entry */
3346 498 : ExecInitExprRec(e, state,
3347 498 : &sbsrefstate->lowerindex[i],
3348 498 : &sbsrefstate->lowerindexnull[i]);
3349 : }
3350 576 : i++;
3351 : }
3352 :
3353 : /* SBSREF_SUBSCRIPTS checks and converts all the subscripts at once */
3354 24618 : if (methods.sbs_check_subscripts)
3355 : {
3356 24604 : scratch->opcode = EEOP_SBSREF_SUBSCRIPTS;
3357 24604 : scratch->d.sbsref_subscript.subscriptfunc = methods.sbs_check_subscripts;
3358 24604 : scratch->d.sbsref_subscript.state = sbsrefstate;
3359 24604 : scratch->d.sbsref_subscript.jumpdone = -1; /* adjust later */
3360 24604 : ExprEvalPushStep(state, scratch);
3361 24604 : adjust_jumps = lappend_int(adjust_jumps,
3362 24604 : state->steps_len - 1);
3363 : }
3364 :
3365 24618 : if (isAssignment)
3366 : {
3367 : Datum *save_innermost_caseval;
3368 : bool *save_innermost_casenull;
3369 :
3370 : /* Check for unimplemented methods */
3371 1320 : if (!methods.sbs_assign)
3372 0 : ereport(ERROR,
3373 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3374 : errmsg("type %s does not support subscripted assignment",
3375 : format_type_be(sbsref->refcontainertype))));
3376 :
3377 : /*
3378 : * We might have a nested-assignment situation, in which the
3379 : * refassgnexpr is itself a FieldStore or SubscriptingRef that needs
3380 : * to obtain and modify the previous value of the array element or
3381 : * slice being replaced. If so, we have to extract that value from
3382 : * the array and pass it down via the CaseTestExpr mechanism. It's
3383 : * safe to reuse the CASE mechanism because there cannot be a CASE
3384 : * between here and where the value would be needed, and an array
3385 : * assignment can't be within a CASE either. (So saving and restoring
3386 : * innermost_caseval is just paranoia, but let's do it anyway.)
3387 : *
3388 : * Since fetching the old element might be a nontrivial expense, do it
3389 : * only if the argument actually needs it.
3390 : */
3391 1320 : if (isAssignmentIndirectionExpr(sbsref->refassgnexpr))
3392 : {
3393 186 : if (!methods.sbs_fetch_old)
3394 0 : ereport(ERROR,
3395 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3396 : errmsg("type %s does not support subscripted assignment",
3397 : format_type_be(sbsref->refcontainertype))));
3398 186 : scratch->opcode = EEOP_SBSREF_OLD;
3399 186 : scratch->d.sbsref.subscriptfunc = methods.sbs_fetch_old;
3400 186 : scratch->d.sbsref.state = sbsrefstate;
3401 186 : ExprEvalPushStep(state, scratch);
3402 : }
3403 :
3404 : /* SBSREF_OLD puts extracted value into prevvalue/prevnull */
3405 1320 : save_innermost_caseval = state->innermost_caseval;
3406 1320 : save_innermost_casenull = state->innermost_casenull;
3407 1320 : state->innermost_caseval = &sbsrefstate->prevvalue;
3408 1320 : state->innermost_casenull = &sbsrefstate->prevnull;
3409 :
3410 : /* evaluate replacement value into replacevalue/replacenull */
3411 1320 : ExecInitExprRec(sbsref->refassgnexpr, state,
3412 : &sbsrefstate->replacevalue, &sbsrefstate->replacenull);
3413 :
3414 1320 : state->innermost_caseval = save_innermost_caseval;
3415 1320 : state->innermost_casenull = save_innermost_casenull;
3416 :
3417 : /* and perform the assignment */
3418 1320 : scratch->opcode = EEOP_SBSREF_ASSIGN;
3419 1320 : scratch->d.sbsref.subscriptfunc = methods.sbs_assign;
3420 1320 : scratch->d.sbsref.state = sbsrefstate;
3421 1320 : ExprEvalPushStep(state, scratch);
3422 : }
3423 : else
3424 : {
3425 : /* array fetch is much simpler */
3426 23298 : scratch->opcode = EEOP_SBSREF_FETCH;
3427 23298 : scratch->d.sbsref.subscriptfunc = methods.sbs_fetch;
3428 23298 : scratch->d.sbsref.state = sbsrefstate;
3429 23298 : ExprEvalPushStep(state, scratch);
3430 : }
3431 :
3432 : /* adjust jump targets */
3433 72520 : foreach(lc, adjust_jumps)
3434 : {
3435 47902 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
3436 :
3437 47902 : if (as->opcode == EEOP_SBSREF_SUBSCRIPTS)
3438 : {
3439 : Assert(as->d.sbsref_subscript.jumpdone == -1);
3440 24604 : as->d.sbsref_subscript.jumpdone = state->steps_len;
3441 : }
3442 : else
3443 : {
3444 : Assert(as->opcode == EEOP_JUMP_IF_NULL);
3445 : Assert(as->d.jump.jumpdone == -1);
3446 23298 : as->d.jump.jumpdone = state->steps_len;
3447 : }
3448 : }
3449 24618 : }
3450 :
3451 : /*
3452 : * Helper for preparing SubscriptingRef expressions for evaluation: is expr
3453 : * a nested FieldStore or SubscriptingRef that needs the old element value
3454 : * passed down?
3455 : *
3456 : * (We could use this in FieldStore too, but in that case passing the old
3457 : * value is so cheap there's no need.)
3458 : *
3459 : * Note: it might seem that this needs to recurse, but in most cases it does
3460 : * not; the CaseTestExpr, if any, will be directly the arg or refexpr of the
3461 : * top-level node. Nested-assignment situations give rise to expression
3462 : * trees in which each level of assignment has its own CaseTestExpr, and the
3463 : * recursive structure appears within the newvals or refassgnexpr field.
3464 : * There is an exception, though: if the array is an array-of-domain, we will
3465 : * have a CoerceToDomain or RelabelType as the refassgnexpr, and we need to
3466 : * be able to look through that.
3467 : */
3468 : static bool
3469 1404 : isAssignmentIndirectionExpr(Expr *expr)
3470 : {
3471 1404 : if (expr == NULL)
3472 0 : return false; /* just paranoia */
3473 1404 : if (IsA(expr, FieldStore))
3474 : {
3475 186 : FieldStore *fstore = (FieldStore *) expr;
3476 :
3477 186 : if (fstore->arg && IsA(fstore->arg, CaseTestExpr))
3478 186 : return true;
3479 : }
3480 1218 : else if (IsA(expr, SubscriptingRef))
3481 : {
3482 32 : SubscriptingRef *sbsRef = (SubscriptingRef *) expr;
3483 :
3484 32 : if (sbsRef->refexpr && IsA(sbsRef->refexpr, CaseTestExpr))
3485 0 : return true;
3486 : }
3487 1186 : else if (IsA(expr, CoerceToDomain))
3488 : {
3489 66 : CoerceToDomain *cd = (CoerceToDomain *) expr;
3490 :
3491 66 : return isAssignmentIndirectionExpr(cd->arg);
3492 : }
3493 1120 : else if (IsA(expr, RelabelType))
3494 : {
3495 18 : RelabelType *r = (RelabelType *) expr;
3496 :
3497 18 : return isAssignmentIndirectionExpr(r->arg);
3498 : }
3499 1134 : return false;
3500 : }
3501 :
3502 : /*
3503 : * Prepare evaluation of a CoerceToDomain expression.
3504 : */
3505 : static void
3506 8934 : ExecInitCoerceToDomain(ExprEvalStep *scratch, CoerceToDomain *ctest,
3507 : ExprState *state, Datum *resv, bool *resnull)
3508 : {
3509 : DomainConstraintRef *constraint_ref;
3510 8934 : Datum *domainval = NULL;
3511 8934 : bool *domainnull = NULL;
3512 : ListCell *l;
3513 :
3514 8934 : scratch->d.domaincheck.resulttype = ctest->resulttype;
3515 : /* we'll allocate workspace only if needed */
3516 8934 : scratch->d.domaincheck.checkvalue = NULL;
3517 8934 : scratch->d.domaincheck.checknull = NULL;
3518 8934 : scratch->d.domaincheck.escontext = state->escontext;
3519 :
3520 : /*
3521 : * Evaluate argument - it's fine to directly store it into resv/resnull,
3522 : * if there's constraint failures there'll be errors, otherwise it's what
3523 : * needs to be returned.
3524 : */
3525 8934 : ExecInitExprRec(ctest->arg, state, resv, resnull);
3526 :
3527 : /*
3528 : * Note: if the argument is of varlena type, it could be a R/W expanded
3529 : * object. We want to return the R/W pointer as the final result, but we
3530 : * have to pass a R/O pointer as the value to be tested by any functions
3531 : * in check expressions. We don't bother to emit a MAKE_READONLY step
3532 : * unless there's actually at least one check expression, though. Until
3533 : * we've tested that, domainval/domainnull are NULL.
3534 : */
3535 :
3536 : /*
3537 : * Collect the constraints associated with the domain.
3538 : *
3539 : * Note: before PG v10 we'd recheck the set of constraints during each
3540 : * evaluation of the expression. Now we bake them into the ExprState
3541 : * during executor initialization. That means we don't need typcache.c to
3542 : * provide compiled exprs.
3543 : */
3544 : constraint_ref = (DomainConstraintRef *)
3545 8934 : palloc(sizeof(DomainConstraintRef));
3546 8934 : InitDomainConstraintRef(ctest->resulttype,
3547 : constraint_ref,
3548 : CurrentMemoryContext,
3549 : false);
3550 :
3551 : /*
3552 : * Compile code to check each domain constraint. NOTNULL constraints can
3553 : * just be applied on the resv/resnull value, but for CHECK constraints we
3554 : * need more pushups.
3555 : */
3556 18820 : foreach(l, constraint_ref->constraints)
3557 : {
3558 9886 : DomainConstraintState *con = (DomainConstraintState *) lfirst(l);
3559 : Datum *save_innermost_domainval;
3560 : bool *save_innermost_domainnull;
3561 :
3562 9886 : scratch->d.domaincheck.constraintname = con->name;
3563 :
3564 9886 : switch (con->constrainttype)
3565 : {
3566 396 : case DOM_CONSTRAINT_NOTNULL:
3567 396 : scratch->opcode = EEOP_DOMAIN_NOTNULL;
3568 396 : ExprEvalPushStep(state, scratch);
3569 396 : break;
3570 9490 : case DOM_CONSTRAINT_CHECK:
3571 : /* Allocate workspace for CHECK output if we didn't yet */
3572 9490 : if (scratch->d.domaincheck.checkvalue == NULL)
3573 : {
3574 8630 : scratch->d.domaincheck.checkvalue =
3575 8630 : (Datum *) palloc(sizeof(Datum));
3576 8630 : scratch->d.domaincheck.checknull =
3577 8630 : (bool *) palloc(sizeof(bool));
3578 : }
3579 :
3580 : /*
3581 : * If first time through, determine where CoerceToDomainValue
3582 : * nodes should read from.
3583 : */
3584 9490 : if (domainval == NULL)
3585 : {
3586 : /*
3587 : * Since value might be read multiple times, force to R/O
3588 : * - but only if it could be an expanded datum.
3589 : */
3590 8630 : if (get_typlen(ctest->resulttype) == -1)
3591 : {
3592 2940 : ExprEvalStep scratch2 = {0};
3593 :
3594 : /* Yes, so make output workspace for MAKE_READONLY */
3595 2940 : domainval = (Datum *) palloc(sizeof(Datum));
3596 2940 : domainnull = (bool *) palloc(sizeof(bool));
3597 :
3598 : /* Emit MAKE_READONLY */
3599 2940 : scratch2.opcode = EEOP_MAKE_READONLY;
3600 2940 : scratch2.resvalue = domainval;
3601 2940 : scratch2.resnull = domainnull;
3602 2940 : scratch2.d.make_readonly.value = resv;
3603 2940 : scratch2.d.make_readonly.isnull = resnull;
3604 2940 : ExprEvalPushStep(state, &scratch2);
3605 : }
3606 : else
3607 : {
3608 : /* No, so it's fine to read from resv/resnull */
3609 5690 : domainval = resv;
3610 5690 : domainnull = resnull;
3611 : }
3612 : }
3613 :
3614 : /*
3615 : * Set up value to be returned by CoerceToDomainValue nodes.
3616 : * We must save and restore innermost_domainval/null fields,
3617 : * in case this node is itself within a check expression for
3618 : * another domain.
3619 : */
3620 9490 : save_innermost_domainval = state->innermost_domainval;
3621 9490 : save_innermost_domainnull = state->innermost_domainnull;
3622 9490 : state->innermost_domainval = domainval;
3623 9490 : state->innermost_domainnull = domainnull;
3624 :
3625 : /* evaluate check expression value */
3626 9490 : ExecInitExprRec(con->check_expr, state,
3627 : scratch->d.domaincheck.checkvalue,
3628 : scratch->d.domaincheck.checknull);
3629 :
3630 9490 : state->innermost_domainval = save_innermost_domainval;
3631 9490 : state->innermost_domainnull = save_innermost_domainnull;
3632 :
3633 : /* now test result */
3634 9490 : scratch->opcode = EEOP_DOMAIN_CHECK;
3635 9490 : ExprEvalPushStep(state, scratch);
3636 :
3637 9490 : break;
3638 0 : default:
3639 0 : elog(ERROR, "unrecognized constraint type: %d",
3640 : (int) con->constrainttype);
3641 : break;
3642 : }
3643 : }
3644 8934 : }
3645 :
3646 : /*
3647 : * Build transition/combine function invocations for all aggregate transition
3648 : * / combination function invocations in a grouping sets phase. This has to
3649 : * invoke all sort based transitions in a phase (if doSort is true), all hash
3650 : * based transitions (if doHash is true), or both (both true).
3651 : *
3652 : * The resulting expression will, for each set of transition values, first
3653 : * check for filters, evaluate aggregate input, check that that input is not
3654 : * NULL for a strict transition function, and then finally invoke the
3655 : * transition for each of the concurrently computed grouping sets.
3656 : *
3657 : * If nullcheck is true, the generated code will check for a NULL pointer to
3658 : * the array of AggStatePerGroup, and skip evaluation if so.
3659 : */
3660 : ExprState *
3661 44644 : ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase,
3662 : bool doSort, bool doHash, bool nullcheck)
3663 : {
3664 44644 : ExprState *state = makeNode(ExprState);
3665 44644 : PlanState *parent = &aggstate->ss.ps;
3666 44644 : ExprEvalStep scratch = {0};
3667 44644 : bool isCombine = DO_AGGSPLIT_COMBINE(aggstate->aggsplit);
3668 44644 : ExprSetupInfo deform = {0, 0, 0, 0, 0, NIL};
3669 :
3670 44644 : state->expr = (Expr *) aggstate;
3671 44644 : state->parent = parent;
3672 :
3673 44644 : scratch.resvalue = &state->resvalue;
3674 44644 : scratch.resnull = &state->resnull;
3675 :
3676 : /*
3677 : * First figure out which slots, and how many columns from each, we're
3678 : * going to need.
3679 : */
3680 94380 : for (int transno = 0; transno < aggstate->numtrans; transno++)
3681 : {
3682 49736 : AggStatePerTrans pertrans = &aggstate->pertrans[transno];
3683 :
3684 49736 : expr_setup_walker((Node *) pertrans->aggref->aggdirectargs,
3685 : &deform);
3686 49736 : expr_setup_walker((Node *) pertrans->aggref->args,
3687 : &deform);
3688 49736 : expr_setup_walker((Node *) pertrans->aggref->aggorder,
3689 : &deform);
3690 49736 : expr_setup_walker((Node *) pertrans->aggref->aggdistinct,
3691 : &deform);
3692 49736 : expr_setup_walker((Node *) pertrans->aggref->aggfilter,
3693 : &deform);
3694 : }
3695 44644 : ExecPushExprSetupSteps(state, &deform);
3696 :
3697 : /*
3698 : * Emit instructions for each transition value / grouping set combination.
3699 : */
3700 94380 : for (int transno = 0; transno < aggstate->numtrans; transno++)
3701 : {
3702 49736 : AggStatePerTrans pertrans = &aggstate->pertrans[transno];
3703 49736 : FunctionCallInfo trans_fcinfo = pertrans->transfn_fcinfo;
3704 49736 : List *adjust_bailout = NIL;
3705 49736 : NullableDatum *strictargs = NULL;
3706 49736 : bool *strictnulls = NULL;
3707 : int argno;
3708 : ListCell *bail;
3709 :
3710 : /*
3711 : * If filter present, emit. Do so before evaluating the input, to
3712 : * avoid potentially unneeded computations, or even worse, unintended
3713 : * side-effects. When combining, all the necessary filtering has
3714 : * already been done.
3715 : */
3716 49736 : if (pertrans->aggref->aggfilter && !isCombine)
3717 : {
3718 : /* evaluate filter expression */
3719 734 : ExecInitExprRec(pertrans->aggref->aggfilter, state,
3720 : &state->resvalue, &state->resnull);
3721 : /* and jump out if false */
3722 734 : scratch.opcode = EEOP_JUMP_IF_NOT_TRUE;
3723 734 : scratch.d.jump.jumpdone = -1; /* adjust later */
3724 734 : ExprEvalPushStep(state, &scratch);
3725 734 : adjust_bailout = lappend_int(adjust_bailout,
3726 734 : state->steps_len - 1);
3727 : }
3728 :
3729 : /*
3730 : * Evaluate arguments to aggregate/combine function.
3731 : */
3732 49736 : argno = 0;
3733 49736 : if (isCombine)
3734 : {
3735 : /*
3736 : * Combining two aggregate transition values. Instead of directly
3737 : * coming from a tuple the input is a, potentially deserialized,
3738 : * transition value.
3739 : */
3740 : TargetEntry *source_tle;
3741 :
3742 : Assert(pertrans->numSortCols == 0);
3743 : Assert(list_length(pertrans->aggref->args) == 1);
3744 :
3745 1354 : strictargs = trans_fcinfo->args + 1;
3746 1354 : source_tle = (TargetEntry *) linitial(pertrans->aggref->args);
3747 :
3748 : /*
3749 : * deserialfn_oid will be set if we must deserialize the input
3750 : * state before calling the combine function.
3751 : */
3752 1354 : if (!OidIsValid(pertrans->deserialfn_oid))
3753 : {
3754 : /*
3755 : * Start from 1, since the 0th arg will be the transition
3756 : * value
3757 : */
3758 1234 : ExecInitExprRec(source_tle->expr, state,
3759 1234 : &trans_fcinfo->args[argno + 1].value,
3760 1234 : &trans_fcinfo->args[argno + 1].isnull);
3761 : }
3762 : else
3763 : {
3764 120 : FunctionCallInfo ds_fcinfo = pertrans->deserialfn_fcinfo;
3765 :
3766 : /* evaluate argument */
3767 120 : ExecInitExprRec(source_tle->expr, state,
3768 : &ds_fcinfo->args[0].value,
3769 : &ds_fcinfo->args[0].isnull);
3770 :
3771 : /* Dummy second argument for type-safety reasons */
3772 120 : ds_fcinfo->args[1].value = PointerGetDatum(NULL);
3773 120 : ds_fcinfo->args[1].isnull = false;
3774 :
3775 : /*
3776 : * Don't call a strict deserialization function with NULL
3777 : * input
3778 : */
3779 120 : if (pertrans->deserialfn.fn_strict)
3780 120 : scratch.opcode = EEOP_AGG_STRICT_DESERIALIZE;
3781 : else
3782 0 : scratch.opcode = EEOP_AGG_DESERIALIZE;
3783 :
3784 120 : scratch.d.agg_deserialize.fcinfo_data = ds_fcinfo;
3785 120 : scratch.d.agg_deserialize.jumpnull = -1; /* adjust later */
3786 120 : scratch.resvalue = &trans_fcinfo->args[argno + 1].value;
3787 120 : scratch.resnull = &trans_fcinfo->args[argno + 1].isnull;
3788 :
3789 120 : ExprEvalPushStep(state, &scratch);
3790 : /* don't add an adjustment unless the function is strict */
3791 120 : if (pertrans->deserialfn.fn_strict)
3792 120 : adjust_bailout = lappend_int(adjust_bailout,
3793 120 : state->steps_len - 1);
3794 :
3795 : /* restore normal settings of scratch fields */
3796 120 : scratch.resvalue = &state->resvalue;
3797 120 : scratch.resnull = &state->resnull;
3798 : }
3799 1354 : argno++;
3800 :
3801 : Assert(pertrans->numInputs == argno);
3802 : }
3803 48382 : else if (!pertrans->aggsortrequired)
3804 : {
3805 : ListCell *arg;
3806 :
3807 : /*
3808 : * Normal transition function without ORDER BY / DISTINCT or with
3809 : * ORDER BY / DISTINCT but the planner has given us pre-sorted
3810 : * input.
3811 : */
3812 48106 : strictargs = trans_fcinfo->args + 1;
3813 :
3814 86850 : foreach(arg, pertrans->aggref->args)
3815 : {
3816 39812 : TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
3817 :
3818 : /*
3819 : * Don't initialize args for any ORDER BY clause that might
3820 : * exist in a presorted aggregate.
3821 : */
3822 39812 : if (argno == pertrans->numTransInputs)
3823 1068 : break;
3824 :
3825 : /*
3826 : * Start from 1, since the 0th arg will be the transition
3827 : * value
3828 : */
3829 38744 : ExecInitExprRec(source_tle->expr, state,
3830 38744 : &trans_fcinfo->args[argno + 1].value,
3831 38744 : &trans_fcinfo->args[argno + 1].isnull);
3832 38744 : argno++;
3833 : }
3834 : Assert(pertrans->numTransInputs == argno);
3835 : }
3836 276 : else if (pertrans->numInputs == 1)
3837 : {
3838 : /*
3839 : * Non-presorted DISTINCT and/or ORDER BY case, with a single
3840 : * column sorted on.
3841 : */
3842 246 : TargetEntry *source_tle =
3843 246 : (TargetEntry *) linitial(pertrans->aggref->args);
3844 :
3845 : Assert(list_length(pertrans->aggref->args) == 1);
3846 :
3847 246 : ExecInitExprRec(source_tle->expr, state,
3848 : &state->resvalue,
3849 : &state->resnull);
3850 246 : strictnulls = &state->resnull;
3851 246 : argno++;
3852 :
3853 : Assert(pertrans->numInputs == argno);
3854 : }
3855 : else
3856 : {
3857 : /*
3858 : * Non-presorted DISTINCT and/or ORDER BY case, with multiple
3859 : * columns sorted on.
3860 : */
3861 30 : Datum *values = pertrans->sortslot->tts_values;
3862 30 : bool *nulls = pertrans->sortslot->tts_isnull;
3863 : ListCell *arg;
3864 :
3865 30 : strictnulls = nulls;
3866 :
3867 114 : foreach(arg, pertrans->aggref->args)
3868 : {
3869 84 : TargetEntry *source_tle = (TargetEntry *) lfirst(arg);
3870 :
3871 84 : ExecInitExprRec(source_tle->expr, state,
3872 84 : &values[argno], &nulls[argno]);
3873 84 : argno++;
3874 : }
3875 : Assert(pertrans->numInputs == argno);
3876 : }
3877 :
3878 : /*
3879 : * For a strict transfn, nothing happens when there's a NULL input; we
3880 : * just keep the prior transValue. This is true for both plain and
3881 : * sorted/distinct aggregates.
3882 : */
3883 49736 : if (trans_fcinfo->flinfo->fn_strict && pertrans->numTransInputs > 0)
3884 : {
3885 10896 : if (strictnulls)
3886 162 : scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_NULLS;
3887 : else
3888 10734 : scratch.opcode = EEOP_AGG_STRICT_INPUT_CHECK_ARGS;
3889 10896 : scratch.d.agg_strict_input_check.nulls = strictnulls;
3890 10896 : scratch.d.agg_strict_input_check.args = strictargs;
3891 10896 : scratch.d.agg_strict_input_check.jumpnull = -1; /* adjust later */
3892 10896 : scratch.d.agg_strict_input_check.nargs = pertrans->numTransInputs;
3893 10896 : ExprEvalPushStep(state, &scratch);
3894 10896 : adjust_bailout = lappend_int(adjust_bailout,
3895 10896 : state->steps_len - 1);
3896 : }
3897 :
3898 : /* Handle DISTINCT aggregates which have pre-sorted input */
3899 49736 : if (pertrans->numDistinctCols > 0 && !pertrans->aggsortrequired)
3900 : {
3901 426 : if (pertrans->numDistinctCols > 1)
3902 96 : scratch.opcode = EEOP_AGG_PRESORTED_DISTINCT_MULTI;
3903 : else
3904 330 : scratch.opcode = EEOP_AGG_PRESORTED_DISTINCT_SINGLE;
3905 :
3906 426 : scratch.d.agg_presorted_distinctcheck.pertrans = pertrans;
3907 426 : scratch.d.agg_presorted_distinctcheck.jumpdistinct = -1; /* adjust later */
3908 426 : ExprEvalPushStep(state, &scratch);
3909 426 : adjust_bailout = lappend_int(adjust_bailout,
3910 426 : state->steps_len - 1);
3911 : }
3912 :
3913 : /*
3914 : * Call transition function (once for each concurrently evaluated
3915 : * grouping set). Do so for both sort and hash based computations, as
3916 : * applicable.
3917 : */
3918 49736 : if (doSort)
3919 : {
3920 43442 : int processGroupingSets = Max(phase->numsets, 1);
3921 43442 : int setoff = 0;
3922 :
3923 88006 : for (int setno = 0; setno < processGroupingSets; setno++)
3924 : {
3925 44564 : ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
3926 : pertrans, transno, setno, setoff, false,
3927 : nullcheck);
3928 44564 : setoff++;
3929 : }
3930 : }
3931 :
3932 49736 : if (doHash)
3933 : {
3934 6668 : int numHashes = aggstate->num_hashes;
3935 : int setoff;
3936 :
3937 : /* in MIXED mode, there'll be preceding transition values */
3938 6668 : if (aggstate->aggstrategy != AGG_HASHED)
3939 398 : setoff = aggstate->maxsets;
3940 : else
3941 6270 : setoff = 0;
3942 :
3943 14546 : for (int setno = 0; setno < numHashes; setno++)
3944 : {
3945 7878 : ExecBuildAggTransCall(state, aggstate, &scratch, trans_fcinfo,
3946 : pertrans, transno, setno, setoff, true,
3947 : nullcheck);
3948 7878 : setoff++;
3949 : }
3950 : }
3951 :
3952 : /* adjust early bail out jump target(s) */
3953 61912 : foreach(bail, adjust_bailout)
3954 : {
3955 12176 : ExprEvalStep *as = &state->steps[lfirst_int(bail)];
3956 :
3957 12176 : if (as->opcode == EEOP_JUMP_IF_NOT_TRUE)
3958 : {
3959 : Assert(as->d.jump.jumpdone == -1);
3960 734 : as->d.jump.jumpdone = state->steps_len;
3961 : }
3962 11442 : else if (as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_ARGS ||
3963 708 : as->opcode == EEOP_AGG_STRICT_INPUT_CHECK_NULLS)
3964 : {
3965 : Assert(as->d.agg_strict_input_check.jumpnull == -1);
3966 10896 : as->d.agg_strict_input_check.jumpnull = state->steps_len;
3967 : }
3968 546 : else if (as->opcode == EEOP_AGG_STRICT_DESERIALIZE)
3969 : {
3970 : Assert(as->d.agg_deserialize.jumpnull == -1);
3971 120 : as->d.agg_deserialize.jumpnull = state->steps_len;
3972 : }
3973 426 : else if (as->opcode == EEOP_AGG_PRESORTED_DISTINCT_SINGLE ||
3974 96 : as->opcode == EEOP_AGG_PRESORTED_DISTINCT_MULTI)
3975 : {
3976 : Assert(as->d.agg_presorted_distinctcheck.jumpdistinct == -1);
3977 426 : as->d.agg_presorted_distinctcheck.jumpdistinct = state->steps_len;
3978 : }
3979 : else
3980 : Assert(false);
3981 : }
3982 : }
3983 :
3984 44644 : scratch.resvalue = NULL;
3985 44644 : scratch.resnull = NULL;
3986 44644 : scratch.opcode = EEOP_DONE;
3987 44644 : ExprEvalPushStep(state, &scratch);
3988 :
3989 44644 : ExecReadyExpr(state);
3990 :
3991 44644 : return state;
3992 : }
3993 :
3994 : /*
3995 : * Build transition/combine function invocation for a single transition
3996 : * value. This is separated from ExecBuildAggTrans() because there are
3997 : * multiple callsites (hash and sort in some grouping set cases).
3998 : */
3999 : static void
4000 52442 : ExecBuildAggTransCall(ExprState *state, AggState *aggstate,
4001 : ExprEvalStep *scratch,
4002 : FunctionCallInfo fcinfo, AggStatePerTrans pertrans,
4003 : int transno, int setno, int setoff, bool ishash,
4004 : bool nullcheck)
4005 : {
4006 : ExprContext *aggcontext;
4007 52442 : int adjust_jumpnull = -1;
4008 :
4009 52442 : if (ishash)
4010 7878 : aggcontext = aggstate->hashcontext;
4011 : else
4012 44564 : aggcontext = aggstate->aggcontexts[setno];
4013 :
4014 : /* add check for NULL pointer? */
4015 52442 : if (nullcheck)
4016 : {
4017 408 : scratch->opcode = EEOP_AGG_PLAIN_PERGROUP_NULLCHECK;
4018 408 : scratch->d.agg_plain_pergroup_nullcheck.setoff = setoff;
4019 : /* adjust later */
4020 408 : scratch->d.agg_plain_pergroup_nullcheck.jumpnull = -1;
4021 408 : ExprEvalPushStep(state, scratch);
4022 408 : adjust_jumpnull = state->steps_len - 1;
4023 : }
4024 :
4025 : /*
4026 : * Determine appropriate transition implementation.
4027 : *
4028 : * For non-ordered aggregates and ORDER BY / DISTINCT aggregates with
4029 : * presorted input:
4030 : *
4031 : * If the initial value for the transition state doesn't exist in the
4032 : * pg_aggregate table then we will let the first non-NULL value returned
4033 : * from the outer procNode become the initial value. (This is useful for
4034 : * aggregates like max() and min().) The noTransValue flag signals that we
4035 : * need to do so. If true, generate a
4036 : * EEOP_AGG_INIT_STRICT_PLAIN_TRANS{,_BYVAL} step. This step also needs to
4037 : * do the work described next:
4038 : *
4039 : * If the function is strict, but does have an initial value, choose
4040 : * EEOP_AGG_STRICT_PLAIN_TRANS{,_BYVAL}, which skips the transition
4041 : * function if the transition value has become NULL (because a previous
4042 : * transition function returned NULL). This step also needs to do the work
4043 : * described next:
4044 : *
4045 : * Otherwise we call EEOP_AGG_PLAIN_TRANS{,_BYVAL}, which does not have to
4046 : * perform either of the above checks.
4047 : *
4048 : * Having steps with overlapping responsibilities is not nice, but
4049 : * aggregations are very performance sensitive, making this worthwhile.
4050 : *
4051 : * For ordered aggregates:
4052 : *
4053 : * Only need to choose between the faster path for a single ordered
4054 : * column, and the one between multiple columns. Checking strictness etc
4055 : * is done when finalizing the aggregate. See
4056 : * process_ordered_aggregate_{single, multi} and
4057 : * advance_transition_function.
4058 : */
4059 52442 : if (!pertrans->aggsortrequired)
4060 : {
4061 52118 : if (pertrans->transtypeByVal)
4062 : {
4063 48336 : if (fcinfo->flinfo->fn_strict &&
4064 23156 : pertrans->initValueIsNull)
4065 4770 : scratch->opcode = EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL;
4066 43566 : else if (fcinfo->flinfo->fn_strict)
4067 18386 : scratch->opcode = EEOP_AGG_PLAIN_TRANS_STRICT_BYVAL;
4068 : else
4069 25180 : scratch->opcode = EEOP_AGG_PLAIN_TRANS_BYVAL;
4070 : }
4071 : else
4072 : {
4073 3782 : if (fcinfo->flinfo->fn_strict &&
4074 3410 : pertrans->initValueIsNull)
4075 1002 : scratch->opcode = EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYREF;
4076 2780 : else if (fcinfo->flinfo->fn_strict)
4077 2408 : scratch->opcode = EEOP_AGG_PLAIN_TRANS_STRICT_BYREF;
4078 : else
4079 372 : scratch->opcode = EEOP_AGG_PLAIN_TRANS_BYREF;
4080 : }
4081 : }
4082 324 : else if (pertrans->numInputs == 1)
4083 282 : scratch->opcode = EEOP_AGG_ORDERED_TRANS_DATUM;
4084 : else
4085 42 : scratch->opcode = EEOP_AGG_ORDERED_TRANS_TUPLE;
4086 :
4087 52442 : scratch->d.agg_trans.pertrans = pertrans;
4088 52442 : scratch->d.agg_trans.setno = setno;
4089 52442 : scratch->d.agg_trans.setoff = setoff;
4090 52442 : scratch->d.agg_trans.transno = transno;
4091 52442 : scratch->d.agg_trans.aggcontext = aggcontext;
4092 52442 : ExprEvalPushStep(state, scratch);
4093 :
4094 : /* fix up jumpnull */
4095 52442 : if (adjust_jumpnull != -1)
4096 : {
4097 408 : ExprEvalStep *as = &state->steps[adjust_jumpnull];
4098 :
4099 : Assert(as->opcode == EEOP_AGG_PLAIN_PERGROUP_NULLCHECK);
4100 : Assert(as->d.agg_plain_pergroup_nullcheck.jumpnull == -1);
4101 408 : as->d.agg_plain_pergroup_nullcheck.jumpnull = state->steps_len;
4102 : }
4103 52442 : }
4104 :
4105 : /*
4106 : * Build an ExprState that calls the given hash function(s) on the attnums
4107 : * given by 'keyColIdx' . When numCols > 1, the hash values returned by each
4108 : * hash function are combined to produce a single hash value.
4109 : *
4110 : * desc: tuple descriptor for the to-be-hashed columns
4111 : * ops: TupleTableSlotOps to use for the give TupleDesc
4112 : * hashfunctions: FmgrInfos for each hash function to call, one per numCols.
4113 : * These are used directly in the returned ExprState so must remain allocated.
4114 : * collations: collation to use when calling the hash function.
4115 : * numCols: array length of hashfunctions, collations and keyColIdx.
4116 : * parent: PlanState node that the resulting ExprState will be evaluated at
4117 : * init_value: Normally 0, but can be set to other values to seed the hash
4118 : * with. Non-zero is marginally slower, so best to only use if it's provably
4119 : * worthwhile.
4120 : */
4121 : ExprState *
4122 7150 : ExecBuildHash32FromAttrs(TupleDesc desc, const TupleTableSlotOps *ops,
4123 : FmgrInfo *hashfunctions, Oid *collations,
4124 : int numCols, AttrNumber *keyColIdx,
4125 : PlanState *parent, uint32 init_value)
4126 : {
4127 7150 : ExprState *state = makeNode(ExprState);
4128 7150 : ExprEvalStep scratch = {0};
4129 7150 : NullableDatum *iresult = NULL;
4130 : intptr_t opcode;
4131 7150 : AttrNumber last_attnum = 0;
4132 :
4133 : Assert(numCols >= 0);
4134 :
4135 7150 : state->parent = parent;
4136 :
4137 : /*
4138 : * Make a place to store intermediate hash values between subsequent
4139 : * hashing of individual columns. We only need this if there is more than
4140 : * one column to hash or an initial value plus one column.
4141 : */
4142 7150 : if ((int64) numCols + (init_value != 0) > 1)
4143 2820 : iresult = palloc(sizeof(NullableDatum));
4144 :
4145 : /* find the highest attnum so we deform the tuple to that point */
4146 18484 : for (int i = 0; i < numCols; i++)
4147 11334 : last_attnum = Max(last_attnum, keyColIdx[i]);
4148 :
4149 7150 : scratch.opcode = EEOP_INNER_FETCHSOME;
4150 7150 : scratch.d.fetch.last_var = last_attnum;
4151 7150 : scratch.d.fetch.fixed = false;
4152 7150 : scratch.d.fetch.kind = ops;
4153 7150 : scratch.d.fetch.known_desc = desc;
4154 7150 : if (ExecComputeSlotInfo(state, &scratch))
4155 4780 : ExprEvalPushStep(state, &scratch);
4156 :
4157 7150 : if (init_value == 0)
4158 : {
4159 : /*
4160 : * No initial value, so we can assign the result of the hash function
4161 : * for the first attribute without having to concern ourselves with
4162 : * combining the result with any initial value.
4163 : */
4164 6616 : opcode = EEOP_HASHDATUM_FIRST;
4165 : }
4166 : else
4167 : {
4168 : /*
4169 : * Set up operation to set the initial value. Normally we store this
4170 : * in the intermediate hash value location, but if there are no
4171 : * columns to hash, store it in the ExprState's result field.
4172 : */
4173 534 : scratch.opcode = EEOP_HASHDATUM_SET_INITVAL;
4174 534 : scratch.d.hashdatum_initvalue.init_value = UInt32GetDatum(init_value);
4175 534 : scratch.resvalue = numCols > 0 ? &iresult->value : &state->resvalue;
4176 534 : scratch.resnull = numCols > 0 ? &iresult->isnull : &state->resnull;
4177 :
4178 534 : ExprEvalPushStep(state, &scratch);
4179 :
4180 : /*
4181 : * When using an initial value use the NEXT32 ops as the FIRST ops
4182 : * would overwrite the stored initial value.
4183 : */
4184 534 : opcode = EEOP_HASHDATUM_NEXT32;
4185 : }
4186 :
4187 18484 : for (int i = 0; i < numCols; i++)
4188 : {
4189 : FmgrInfo *finfo;
4190 : FunctionCallInfo fcinfo;
4191 11334 : Oid inputcollid = collations[i];
4192 11334 : AttrNumber attnum = keyColIdx[i] - 1;
4193 :
4194 11334 : finfo = &hashfunctions[i];
4195 11334 : fcinfo = palloc0(SizeForFunctionCallInfo(1));
4196 :
4197 : /* Initialize function call parameter structure too */
4198 11334 : InitFunctionCallInfoData(*fcinfo, finfo, 1, inputcollid, NULL, NULL);
4199 :
4200 : /*
4201 : * Fetch inner Var for this attnum and store it in the 1st arg of the
4202 : * hash func.
4203 : */
4204 11334 : scratch.opcode = EEOP_INNER_VAR;
4205 11334 : scratch.resvalue = &fcinfo->args[0].value;
4206 11334 : scratch.resnull = &fcinfo->args[0].isnull;
4207 11334 : scratch.d.var.attnum = attnum;
4208 11334 : scratch.d.var.vartype = TupleDescAttr(desc, attnum)->atttypid;
4209 11334 : scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
4210 :
4211 11334 : ExprEvalPushStep(state, &scratch);
4212 :
4213 : /* Call the hash function */
4214 11334 : scratch.opcode = opcode;
4215 :
4216 11334 : if (i == numCols - 1)
4217 : {
4218 : /*
4219 : * The result for hashing the final column is stored in the
4220 : * ExprState.
4221 : */
4222 7150 : scratch.resvalue = &state->resvalue;
4223 7150 : scratch.resnull = &state->resnull;
4224 : }
4225 : else
4226 : {
4227 : Assert(iresult != NULL);
4228 :
4229 : /* intermediate values are stored in an intermediate result */
4230 4184 : scratch.resvalue = &iresult->value;
4231 4184 : scratch.resnull = &iresult->isnull;
4232 : }
4233 :
4234 : /*
4235 : * NEXT32 opcodes need to look at the intermediate result. We might
4236 : * as well just set this for all ops. FIRSTs won't look at it.
4237 : */
4238 11334 : scratch.d.hashdatum.iresult = iresult;
4239 :
4240 11334 : scratch.d.hashdatum.finfo = finfo;
4241 11334 : scratch.d.hashdatum.fcinfo_data = fcinfo;
4242 11334 : scratch.d.hashdatum.fn_addr = finfo->fn_addr;
4243 11334 : scratch.d.hashdatum.jumpdone = -1;
4244 :
4245 11334 : ExprEvalPushStep(state, &scratch);
4246 :
4247 : /* subsequent attnums must be combined with the previous */
4248 11334 : opcode = EEOP_HASHDATUM_NEXT32;
4249 : }
4250 :
4251 7150 : scratch.resvalue = NULL;
4252 7150 : scratch.resnull = NULL;
4253 7150 : scratch.opcode = EEOP_DONE;
4254 7150 : ExprEvalPushStep(state, &scratch);
4255 :
4256 7150 : ExecReadyExpr(state);
4257 :
4258 7150 : return state;
4259 : }
4260 :
4261 : /*
4262 : * Build an ExprState that calls the given hash function(s) on the given
4263 : * 'hash_exprs'. When multiple expressions are present, the hash values
4264 : * returned by each hash function are combined to produce a single hash value.
4265 : *
4266 : * desc: tuple descriptor for the to-be-hashed expressions
4267 : * ops: TupleTableSlotOps for the TupleDesc
4268 : * hashfunc_oids: Oid for each hash function to call, one for each 'hash_expr'
4269 : * collations: collation to use when calling the hash function.
4270 : * hash_expr: list of expressions to hash the value of
4271 : * opstrict: array corresponding to the 'hashfunc_oids' to store op_strict()
4272 : * parent: PlanState node that the 'hash_exprs' will be evaluated at
4273 : * init_value: Normally 0, but can be set to other values to seed the hash
4274 : * with some other value. Using non-zero is slightly less efficient but can
4275 : * be useful.
4276 : * keep_nulls: if true, evaluation of the returned ExprState will abort early
4277 : * returning NULL if the given hash function is strict and the Datum to hash
4278 : * is null. When set to false, any NULL input Datums are skipped.
4279 : */
4280 : ExprState *
4281 58824 : ExecBuildHash32Expr(TupleDesc desc, const TupleTableSlotOps *ops,
4282 : const Oid *hashfunc_oids, const List *collations,
4283 : const List *hash_exprs, const bool *opstrict,
4284 : PlanState *parent, uint32 init_value, bool keep_nulls)
4285 : {
4286 58824 : ExprState *state = makeNode(ExprState);
4287 58824 : ExprEvalStep scratch = {0};
4288 58824 : NullableDatum *iresult = NULL;
4289 58824 : List *adjust_jumps = NIL;
4290 : ListCell *lc;
4291 : ListCell *lc2;
4292 : intptr_t strict_opcode;
4293 : intptr_t opcode;
4294 58824 : int num_exprs = list_length(hash_exprs);
4295 :
4296 : Assert(num_exprs == list_length(collations));
4297 :
4298 58824 : state->parent = parent;
4299 :
4300 : /* Insert setup steps as needed. */
4301 58824 : ExecCreateExprSetupSteps(state, (Node *) hash_exprs);
4302 :
4303 : /*
4304 : * Make a place to store intermediate hash values between subsequent
4305 : * hashing of individual expressions. We only need this if there is more
4306 : * than one expression to hash or an initial value plus one expression.
4307 : */
4308 58824 : if ((int64) num_exprs + (init_value != 0) > 1)
4309 4636 : iresult = palloc(sizeof(NullableDatum));
4310 :
4311 58824 : if (init_value == 0)
4312 : {
4313 : /*
4314 : * No initial value, so we can assign the result of the hash function
4315 : * for the first hash_expr without having to concern ourselves with
4316 : * combining the result with any initial value.
4317 : */
4318 58824 : strict_opcode = EEOP_HASHDATUM_FIRST_STRICT;
4319 58824 : opcode = EEOP_HASHDATUM_FIRST;
4320 : }
4321 : else
4322 : {
4323 : /*
4324 : * Set up operation to set the initial value. Normally we store this
4325 : * in the intermediate hash value location, but if there are no exprs
4326 : * to hash, store it in the ExprState's result field.
4327 : */
4328 0 : scratch.opcode = EEOP_HASHDATUM_SET_INITVAL;
4329 0 : scratch.d.hashdatum_initvalue.init_value = UInt32GetDatum(init_value);
4330 0 : scratch.resvalue = num_exprs > 0 ? &iresult->value : &state->resvalue;
4331 0 : scratch.resnull = num_exprs > 0 ? &iresult->isnull : &state->resnull;
4332 :
4333 0 : ExprEvalPushStep(state, &scratch);
4334 :
4335 : /*
4336 : * When using an initial value use the NEXT32/NEXT32_STRICT ops as the
4337 : * FIRST/FIRST_STRICT ops would overwrite the stored initial value.
4338 : */
4339 0 : strict_opcode = EEOP_HASHDATUM_NEXT32_STRICT;
4340 0 : opcode = EEOP_HASHDATUM_NEXT32;
4341 : }
4342 :
4343 122452 : forboth(lc, hash_exprs, lc2, collations)
4344 : {
4345 63628 : Expr *expr = (Expr *) lfirst(lc);
4346 : FmgrInfo *finfo;
4347 : FunctionCallInfo fcinfo;
4348 63628 : int i = foreach_current_index(lc);
4349 : Oid funcid;
4350 63628 : Oid inputcollid = lfirst_oid(lc2);
4351 :
4352 63628 : funcid = hashfunc_oids[i];
4353 :
4354 : /* Allocate hash function lookup data. */
4355 63628 : finfo = palloc0(sizeof(FmgrInfo));
4356 63628 : fcinfo = palloc0(SizeForFunctionCallInfo(1));
4357 :
4358 63628 : fmgr_info(funcid, finfo);
4359 :
4360 : /*
4361 : * Build the steps to evaluate the hash function's argument have it so
4362 : * the value of that is stored in the 0th argument of the hash func.
4363 : */
4364 63628 : ExecInitExprRec(expr,
4365 : state,
4366 : &fcinfo->args[0].value,
4367 : &fcinfo->args[0].isnull);
4368 :
4369 63628 : if (i == num_exprs - 1)
4370 : {
4371 : /* the result for hashing the final expr is stored in the state */
4372 58824 : scratch.resvalue = &state->resvalue;
4373 58824 : scratch.resnull = &state->resnull;
4374 : }
4375 : else
4376 : {
4377 : Assert(iresult != NULL);
4378 :
4379 : /* intermediate values are stored in an intermediate result */
4380 4804 : scratch.resvalue = &iresult->value;
4381 4804 : scratch.resnull = &iresult->isnull;
4382 : }
4383 :
4384 : /*
4385 : * NEXT32 opcodes need to look at the intermediate result. We might
4386 : * as well just set this for all ops. FIRSTs won't look at it.
4387 : */
4388 63628 : scratch.d.hashdatum.iresult = iresult;
4389 :
4390 : /* Initialize function call parameter structure too */
4391 63628 : InitFunctionCallInfoData(*fcinfo, finfo, 1, inputcollid, NULL, NULL);
4392 :
4393 63628 : scratch.d.hashdatum.finfo = finfo;
4394 63628 : scratch.d.hashdatum.fcinfo_data = fcinfo;
4395 63628 : scratch.d.hashdatum.fn_addr = finfo->fn_addr;
4396 :
4397 63628 : scratch.opcode = opstrict[i] && !keep_nulls ? strict_opcode : opcode;
4398 63628 : scratch.d.hashdatum.jumpdone = -1;
4399 :
4400 63628 : ExprEvalPushStep(state, &scratch);
4401 63628 : adjust_jumps = lappend_int(adjust_jumps, state->steps_len - 1);
4402 :
4403 : /*
4404 : * For subsequent keys we must combine the hash value with the
4405 : * previous hashes.
4406 : */
4407 63628 : strict_opcode = EEOP_HASHDATUM_NEXT32_STRICT;
4408 63628 : opcode = EEOP_HASHDATUM_NEXT32;
4409 : }
4410 :
4411 : /* adjust jump targets */
4412 122452 : foreach(lc, adjust_jumps)
4413 : {
4414 63628 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
4415 :
4416 : Assert(as->opcode == EEOP_HASHDATUM_FIRST ||
4417 : as->opcode == EEOP_HASHDATUM_FIRST_STRICT ||
4418 : as->opcode == EEOP_HASHDATUM_NEXT32 ||
4419 : as->opcode == EEOP_HASHDATUM_NEXT32_STRICT);
4420 : Assert(as->d.hashdatum.jumpdone == -1);
4421 63628 : as->d.hashdatum.jumpdone = state->steps_len;
4422 : }
4423 :
4424 58824 : scratch.resvalue = NULL;
4425 58824 : scratch.resnull = NULL;
4426 58824 : scratch.opcode = EEOP_DONE;
4427 58824 : ExprEvalPushStep(state, &scratch);
4428 :
4429 58824 : ExecReadyExpr(state);
4430 :
4431 58824 : return state;
4432 : }
4433 :
4434 : /*
4435 : * Build equality expression that can be evaluated using ExecQual(), returning
4436 : * true if the expression context's inner/outer tuple are NOT DISTINCT. I.e
4437 : * two nulls match, a null and a not-null don't match.
4438 : *
4439 : * desc: tuple descriptor of the to-be-compared tuples
4440 : * numCols: the number of attributes to be examined
4441 : * keyColIdx: array of attribute column numbers
4442 : * eqFunctions: array of function oids of the equality functions to use
4443 : * parent: parent executor node
4444 : */
4445 : ExprState *
4446 17792 : ExecBuildGroupingEqual(TupleDesc ldesc, TupleDesc rdesc,
4447 : const TupleTableSlotOps *lops, const TupleTableSlotOps *rops,
4448 : int numCols,
4449 : const AttrNumber *keyColIdx,
4450 : const Oid *eqfunctions,
4451 : const Oid *collations,
4452 : PlanState *parent)
4453 : {
4454 17792 : ExprState *state = makeNode(ExprState);
4455 17792 : ExprEvalStep scratch = {0};
4456 17792 : int maxatt = -1;
4457 17792 : List *adjust_jumps = NIL;
4458 : ListCell *lc;
4459 :
4460 : /*
4461 : * When no columns are actually compared, the result's always true. See
4462 : * special case in ExecQual().
4463 : */
4464 17792 : if (numCols == 0)
4465 0 : return NULL;
4466 :
4467 17792 : state->expr = NULL;
4468 17792 : state->flags = EEO_FLAG_IS_QUAL;
4469 17792 : state->parent = parent;
4470 :
4471 17792 : scratch.resvalue = &state->resvalue;
4472 17792 : scratch.resnull = &state->resnull;
4473 :
4474 : /* compute max needed attribute */
4475 47604 : for (int natt = 0; natt < numCols; natt++)
4476 : {
4477 29812 : int attno = keyColIdx[natt];
4478 :
4479 29812 : if (attno > maxatt)
4480 29444 : maxatt = attno;
4481 : }
4482 : Assert(maxatt >= 0);
4483 :
4484 : /* push deform steps */
4485 17792 : scratch.opcode = EEOP_INNER_FETCHSOME;
4486 17792 : scratch.d.fetch.last_var = maxatt;
4487 17792 : scratch.d.fetch.fixed = false;
4488 17792 : scratch.d.fetch.known_desc = ldesc;
4489 17792 : scratch.d.fetch.kind = lops;
4490 17792 : if (ExecComputeSlotInfo(state, &scratch))
4491 15422 : ExprEvalPushStep(state, &scratch);
4492 :
4493 17792 : scratch.opcode = EEOP_OUTER_FETCHSOME;
4494 17792 : scratch.d.fetch.last_var = maxatt;
4495 17792 : scratch.d.fetch.fixed = false;
4496 17792 : scratch.d.fetch.known_desc = rdesc;
4497 17792 : scratch.d.fetch.kind = rops;
4498 17792 : if (ExecComputeSlotInfo(state, &scratch))
4499 17792 : ExprEvalPushStep(state, &scratch);
4500 :
4501 : /*
4502 : * Start comparing at the last field (least significant sort key). That's
4503 : * the most likely to be different if we are dealing with sorted input.
4504 : */
4505 47604 : for (int natt = numCols; --natt >= 0;)
4506 : {
4507 29812 : int attno = keyColIdx[natt];
4508 29812 : Form_pg_attribute latt = TupleDescAttr(ldesc, attno - 1);
4509 29812 : Form_pg_attribute ratt = TupleDescAttr(rdesc, attno - 1);
4510 29812 : Oid foid = eqfunctions[natt];
4511 29812 : Oid collid = collations[natt];
4512 : FmgrInfo *finfo;
4513 : FunctionCallInfo fcinfo;
4514 : AclResult aclresult;
4515 :
4516 : /* Check permission to call function */
4517 29812 : aclresult = object_aclcheck(ProcedureRelationId, foid, GetUserId(), ACL_EXECUTE);
4518 29812 : if (aclresult != ACLCHECK_OK)
4519 0 : aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
4520 :
4521 29812 : InvokeFunctionExecuteHook(foid);
4522 :
4523 : /* Set up the primary fmgr lookup information */
4524 29812 : finfo = palloc0(sizeof(FmgrInfo));
4525 29812 : fcinfo = palloc0(SizeForFunctionCallInfo(2));
4526 29812 : fmgr_info(foid, finfo);
4527 29812 : fmgr_info_set_expr(NULL, finfo);
4528 29812 : InitFunctionCallInfoData(*fcinfo, finfo, 2,
4529 : collid, NULL, NULL);
4530 :
4531 : /* left arg */
4532 29812 : scratch.opcode = EEOP_INNER_VAR;
4533 29812 : scratch.d.var.attnum = attno - 1;
4534 29812 : scratch.d.var.vartype = latt->atttypid;
4535 29812 : scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
4536 29812 : scratch.resvalue = &fcinfo->args[0].value;
4537 29812 : scratch.resnull = &fcinfo->args[0].isnull;
4538 29812 : ExprEvalPushStep(state, &scratch);
4539 :
4540 : /* right arg */
4541 29812 : scratch.opcode = EEOP_OUTER_VAR;
4542 29812 : scratch.d.var.attnum = attno - 1;
4543 29812 : scratch.d.var.vartype = ratt->atttypid;
4544 29812 : scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
4545 29812 : scratch.resvalue = &fcinfo->args[1].value;
4546 29812 : scratch.resnull = &fcinfo->args[1].isnull;
4547 29812 : ExprEvalPushStep(state, &scratch);
4548 :
4549 : /* evaluate distinctness */
4550 29812 : scratch.opcode = EEOP_NOT_DISTINCT;
4551 29812 : scratch.d.func.finfo = finfo;
4552 29812 : scratch.d.func.fcinfo_data = fcinfo;
4553 29812 : scratch.d.func.fn_addr = finfo->fn_addr;
4554 29812 : scratch.d.func.nargs = 2;
4555 29812 : scratch.resvalue = &state->resvalue;
4556 29812 : scratch.resnull = &state->resnull;
4557 29812 : ExprEvalPushStep(state, &scratch);
4558 :
4559 : /* then emit EEOP_QUAL to detect if result is false (or null) */
4560 29812 : scratch.opcode = EEOP_QUAL;
4561 29812 : scratch.d.qualexpr.jumpdone = -1;
4562 29812 : scratch.resvalue = &state->resvalue;
4563 29812 : scratch.resnull = &state->resnull;
4564 29812 : ExprEvalPushStep(state, &scratch);
4565 29812 : adjust_jumps = lappend_int(adjust_jumps,
4566 29812 : state->steps_len - 1);
4567 : }
4568 :
4569 : /* adjust jump targets */
4570 47604 : foreach(lc, adjust_jumps)
4571 : {
4572 29812 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
4573 :
4574 : Assert(as->opcode == EEOP_QUAL);
4575 : Assert(as->d.qualexpr.jumpdone == -1);
4576 29812 : as->d.qualexpr.jumpdone = state->steps_len;
4577 : }
4578 :
4579 17792 : scratch.resvalue = NULL;
4580 17792 : scratch.resnull = NULL;
4581 17792 : scratch.opcode = EEOP_DONE;
4582 17792 : ExprEvalPushStep(state, &scratch);
4583 :
4584 17792 : ExecReadyExpr(state);
4585 :
4586 17792 : return state;
4587 : }
4588 :
4589 : /*
4590 : * Build equality expression that can be evaluated using ExecQual(), returning
4591 : * true if the expression context's inner/outer tuples are equal. Datums in
4592 : * the inner/outer slots are assumed to be in the same order and quantity as
4593 : * the 'eqfunctions' parameter. NULLs are treated as equal.
4594 : *
4595 : * desc: tuple descriptor of the to-be-compared tuples
4596 : * lops: the slot ops for the inner tuple slots
4597 : * rops: the slot ops for the outer tuple slots
4598 : * eqFunctions: array of function oids of the equality functions to use
4599 : * this must be the same length as the 'param_exprs' list.
4600 : * collations: collation Oids to use for equality comparison. Must be the
4601 : * same length as the 'param_exprs' list.
4602 : * parent: parent executor node
4603 : */
4604 : ExprState *
4605 1386 : ExecBuildParamSetEqual(TupleDesc desc,
4606 : const TupleTableSlotOps *lops,
4607 : const TupleTableSlotOps *rops,
4608 : const Oid *eqfunctions,
4609 : const Oid *collations,
4610 : const List *param_exprs,
4611 : PlanState *parent)
4612 : {
4613 1386 : ExprState *state = makeNode(ExprState);
4614 1386 : ExprEvalStep scratch = {0};
4615 1386 : int maxatt = list_length(param_exprs);
4616 1386 : List *adjust_jumps = NIL;
4617 : ListCell *lc;
4618 :
4619 1386 : state->expr = NULL;
4620 1386 : state->flags = EEO_FLAG_IS_QUAL;
4621 1386 : state->parent = parent;
4622 :
4623 1386 : scratch.resvalue = &state->resvalue;
4624 1386 : scratch.resnull = &state->resnull;
4625 :
4626 : /* push deform steps */
4627 1386 : scratch.opcode = EEOP_INNER_FETCHSOME;
4628 1386 : scratch.d.fetch.last_var = maxatt;
4629 1386 : scratch.d.fetch.fixed = false;
4630 1386 : scratch.d.fetch.known_desc = desc;
4631 1386 : scratch.d.fetch.kind = lops;
4632 1386 : if (ExecComputeSlotInfo(state, &scratch))
4633 1386 : ExprEvalPushStep(state, &scratch);
4634 :
4635 1386 : scratch.opcode = EEOP_OUTER_FETCHSOME;
4636 1386 : scratch.d.fetch.last_var = maxatt;
4637 1386 : scratch.d.fetch.fixed = false;
4638 1386 : scratch.d.fetch.known_desc = desc;
4639 1386 : scratch.d.fetch.kind = rops;
4640 1386 : if (ExecComputeSlotInfo(state, &scratch))
4641 0 : ExprEvalPushStep(state, &scratch);
4642 :
4643 2814 : for (int attno = 0; attno < maxatt; attno++)
4644 : {
4645 1428 : Form_pg_attribute att = TupleDescAttr(desc, attno);
4646 1428 : Oid foid = eqfunctions[attno];
4647 1428 : Oid collid = collations[attno];
4648 : FmgrInfo *finfo;
4649 : FunctionCallInfo fcinfo;
4650 : AclResult aclresult;
4651 :
4652 : /* Check permission to call function */
4653 1428 : aclresult = object_aclcheck(ProcedureRelationId, foid, GetUserId(), ACL_EXECUTE);
4654 1428 : if (aclresult != ACLCHECK_OK)
4655 0 : aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
4656 :
4657 1428 : InvokeFunctionExecuteHook(foid);
4658 :
4659 : /* Set up the primary fmgr lookup information */
4660 1428 : finfo = palloc0(sizeof(FmgrInfo));
4661 1428 : fcinfo = palloc0(SizeForFunctionCallInfo(2));
4662 1428 : fmgr_info(foid, finfo);
4663 1428 : fmgr_info_set_expr(NULL, finfo);
4664 1428 : InitFunctionCallInfoData(*fcinfo, finfo, 2,
4665 : collid, NULL, NULL);
4666 :
4667 : /* left arg */
4668 1428 : scratch.opcode = EEOP_INNER_VAR;
4669 1428 : scratch.d.var.attnum = attno;
4670 1428 : scratch.d.var.vartype = att->atttypid;
4671 1428 : scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
4672 1428 : scratch.resvalue = &fcinfo->args[0].value;
4673 1428 : scratch.resnull = &fcinfo->args[0].isnull;
4674 1428 : ExprEvalPushStep(state, &scratch);
4675 :
4676 : /* right arg */
4677 1428 : scratch.opcode = EEOP_OUTER_VAR;
4678 1428 : scratch.d.var.attnum = attno;
4679 1428 : scratch.d.var.vartype = att->atttypid;
4680 1428 : scratch.d.var.varreturningtype = VAR_RETURNING_DEFAULT;
4681 1428 : scratch.resvalue = &fcinfo->args[1].value;
4682 1428 : scratch.resnull = &fcinfo->args[1].isnull;
4683 1428 : ExprEvalPushStep(state, &scratch);
4684 :
4685 : /* evaluate distinctness */
4686 1428 : scratch.opcode = EEOP_NOT_DISTINCT;
4687 1428 : scratch.d.func.finfo = finfo;
4688 1428 : scratch.d.func.fcinfo_data = fcinfo;
4689 1428 : scratch.d.func.fn_addr = finfo->fn_addr;
4690 1428 : scratch.d.func.nargs = 2;
4691 1428 : scratch.resvalue = &state->resvalue;
4692 1428 : scratch.resnull = &state->resnull;
4693 1428 : ExprEvalPushStep(state, &scratch);
4694 :
4695 : /* then emit EEOP_QUAL to detect if result is false (or null) */
4696 1428 : scratch.opcode = EEOP_QUAL;
4697 1428 : scratch.d.qualexpr.jumpdone = -1;
4698 1428 : scratch.resvalue = &state->resvalue;
4699 1428 : scratch.resnull = &state->resnull;
4700 1428 : ExprEvalPushStep(state, &scratch);
4701 1428 : adjust_jumps = lappend_int(adjust_jumps,
4702 1428 : state->steps_len - 1);
4703 : }
4704 :
4705 : /* adjust jump targets */
4706 2814 : foreach(lc, adjust_jumps)
4707 : {
4708 1428 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
4709 :
4710 : Assert(as->opcode == EEOP_QUAL);
4711 : Assert(as->d.qualexpr.jumpdone == -1);
4712 1428 : as->d.qualexpr.jumpdone = state->steps_len;
4713 : }
4714 :
4715 1386 : scratch.resvalue = NULL;
4716 1386 : scratch.resnull = NULL;
4717 1386 : scratch.opcode = EEOP_DONE;
4718 1386 : ExprEvalPushStep(state, &scratch);
4719 :
4720 1386 : ExecReadyExpr(state);
4721 :
4722 1386 : return state;
4723 : }
4724 :
4725 : /*
4726 : * Push steps to evaluate a JsonExpr and its various subsidiary expressions.
4727 : */
4728 : static void
4729 2288 : ExecInitJsonExpr(JsonExpr *jsexpr, ExprState *state,
4730 : Datum *resv, bool *resnull,
4731 : ExprEvalStep *scratch)
4732 : {
4733 2288 : JsonExprState *jsestate = palloc0(sizeof(JsonExprState));
4734 : ListCell *argexprlc;
4735 : ListCell *argnamelc;
4736 2288 : List *jumps_return_null = NIL;
4737 2288 : List *jumps_to_end = NIL;
4738 : ListCell *lc;
4739 : ErrorSaveContext *escontext;
4740 2288 : bool returning_domain =
4741 2288 : get_typtype(jsexpr->returning->typid) == TYPTYPE_DOMAIN;
4742 :
4743 : Assert(jsexpr->on_error != NULL);
4744 :
4745 2288 : jsestate->jsexpr = jsexpr;
4746 :
4747 : /*
4748 : * Evaluate formatted_expr storing the result into
4749 : * jsestate->formatted_expr.
4750 : */
4751 2288 : ExecInitExprRec((Expr *) jsexpr->formatted_expr, state,
4752 : &jsestate->formatted_expr.value,
4753 : &jsestate->formatted_expr.isnull);
4754 :
4755 : /* JUMP to return NULL if formatted_expr evaluates to NULL */
4756 2288 : jumps_return_null = lappend_int(jumps_return_null, state->steps_len);
4757 2288 : scratch->opcode = EEOP_JUMP_IF_NULL;
4758 2288 : scratch->resnull = &jsestate->formatted_expr.isnull;
4759 2288 : scratch->d.jump.jumpdone = -1; /* set below */
4760 2288 : ExprEvalPushStep(state, scratch);
4761 :
4762 : /*
4763 : * Evaluate pathspec expression storing the result into
4764 : * jsestate->pathspec.
4765 : */
4766 2288 : ExecInitExprRec((Expr *) jsexpr->path_spec, state,
4767 : &jsestate->pathspec.value,
4768 : &jsestate->pathspec.isnull);
4769 :
4770 : /* JUMP to return NULL if path_spec evaluates to NULL */
4771 2288 : jumps_return_null = lappend_int(jumps_return_null, state->steps_len);
4772 2288 : scratch->opcode = EEOP_JUMP_IF_NULL;
4773 2288 : scratch->resnull = &jsestate->pathspec.isnull;
4774 2288 : scratch->d.jump.jumpdone = -1; /* set below */
4775 2288 : ExprEvalPushStep(state, scratch);
4776 :
4777 : /* Steps to compute PASSING args. */
4778 2288 : jsestate->args = NIL;
4779 3194 : forboth(argexprlc, jsexpr->passing_values,
4780 : argnamelc, jsexpr->passing_names)
4781 : {
4782 906 : Expr *argexpr = (Expr *) lfirst(argexprlc);
4783 906 : String *argname = lfirst_node(String, argnamelc);
4784 906 : JsonPathVariable *var = palloc(sizeof(*var));
4785 :
4786 906 : var->name = argname->sval;
4787 906 : var->namelen = strlen(var->name);
4788 906 : var->typid = exprType((Node *) argexpr);
4789 906 : var->typmod = exprTypmod((Node *) argexpr);
4790 :
4791 906 : ExecInitExprRec((Expr *) argexpr, state, &var->value, &var->isnull);
4792 :
4793 906 : jsestate->args = lappend(jsestate->args, var);
4794 : }
4795 :
4796 : /* Step for jsonpath evaluation; see ExecEvalJsonExprPath(). */
4797 2288 : scratch->opcode = EEOP_JSONEXPR_PATH;
4798 2288 : scratch->resvalue = resv;
4799 2288 : scratch->resnull = resnull;
4800 2288 : scratch->d.jsonexpr.jsestate = jsestate;
4801 2288 : ExprEvalPushStep(state, scratch);
4802 :
4803 : /*
4804 : * Step to return NULL after jumping to skip the EEOP_JSONEXPR_PATH step
4805 : * when either formatted_expr or pathspec is NULL. Adjust jump target
4806 : * addresses of JUMPs that we added above.
4807 : */
4808 6864 : foreach(lc, jumps_return_null)
4809 : {
4810 4576 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
4811 :
4812 4576 : as->d.jump.jumpdone = state->steps_len;
4813 : }
4814 2288 : scratch->opcode = EEOP_CONST;
4815 2288 : scratch->resvalue = resv;
4816 2288 : scratch->resnull = resnull;
4817 2288 : scratch->d.constval.value = (Datum) 0;
4818 2288 : scratch->d.constval.isnull = true;
4819 2288 : ExprEvalPushStep(state, scratch);
4820 :
4821 4576 : escontext = jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR ?
4822 2288 : &jsestate->escontext : NULL;
4823 :
4824 : /*
4825 : * To handle coercion errors softly, use the following ErrorSaveContext to
4826 : * pass to ExecInitExprRec() when initializing the coercion expressions
4827 : * and in the EEOP_JSONEXPR_COERCION step.
4828 : */
4829 2288 : jsestate->escontext.type = T_ErrorSaveContext;
4830 :
4831 : /*
4832 : * Steps to coerce the result value computed by EEOP_JSONEXPR_PATH or the
4833 : * NULL returned on NULL input as described above.
4834 : */
4835 2288 : jsestate->jump_eval_coercion = -1;
4836 2288 : if (jsexpr->use_json_coercion)
4837 : {
4838 888 : jsestate->jump_eval_coercion = state->steps_len;
4839 :
4840 888 : ExecInitJsonCoercion(state, jsexpr->returning, escontext,
4841 888 : jsexpr->omit_quotes,
4842 888 : jsexpr->op == JSON_EXISTS_OP,
4843 : resv, resnull);
4844 : }
4845 1400 : else if (jsexpr->use_io_coercion)
4846 : {
4847 : /*
4848 : * Here we only need to initialize the FunctionCallInfo for the target
4849 : * type's input function, which is called by ExecEvalJsonExprPath()
4850 : * itself, so no additional step is necessary.
4851 : */
4852 : Oid typinput;
4853 : Oid typioparam;
4854 : FmgrInfo *finfo;
4855 : FunctionCallInfo fcinfo;
4856 :
4857 626 : getTypeInputInfo(jsexpr->returning->typid, &typinput, &typioparam);
4858 626 : finfo = palloc0(sizeof(FmgrInfo));
4859 626 : fcinfo = palloc0(SizeForFunctionCallInfo(3));
4860 626 : fmgr_info(typinput, finfo);
4861 626 : fmgr_info_set_expr((Node *) jsexpr->returning, finfo);
4862 626 : InitFunctionCallInfoData(*fcinfo, finfo, 3, InvalidOid, NULL, NULL);
4863 :
4864 : /*
4865 : * We can preload the second and third arguments for the input
4866 : * function, since they're constants.
4867 : */
4868 626 : fcinfo->args[1].value = ObjectIdGetDatum(typioparam);
4869 626 : fcinfo->args[1].isnull = false;
4870 626 : fcinfo->args[2].value = Int32GetDatum(jsexpr->returning->typmod);
4871 626 : fcinfo->args[2].isnull = false;
4872 626 : fcinfo->context = (Node *) escontext;
4873 :
4874 626 : jsestate->input_fcinfo = fcinfo;
4875 : }
4876 :
4877 : /*
4878 : * Add a special step, if needed, to check if the coercion evaluation ran
4879 : * into an error but was not thrown because the ON ERROR behavior is not
4880 : * ERROR. It will set jsestate->error if an error did occur.
4881 : */
4882 2288 : if (jsestate->jump_eval_coercion >= 0 && escontext != NULL)
4883 : {
4884 666 : scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
4885 666 : scratch->d.jsonexpr.jsestate = jsestate;
4886 666 : ExprEvalPushStep(state, scratch);
4887 : }
4888 :
4889 2288 : jsestate->jump_empty = jsestate->jump_error = -1;
4890 :
4891 : /*
4892 : * Step to check jsestate->error and return the ON ERROR expression if
4893 : * there is one. This handles both the errors that occur during jsonpath
4894 : * evaluation in EEOP_JSONEXPR_PATH and subsequent coercion evaluation.
4895 : *
4896 : * Speed up common cases by avoiding extra steps for a NULL-valued ON
4897 : * ERROR expression unless RETURNING a domain type, where constraints must
4898 : * be checked. ExecEvalJsonExprPath() already returns NULL on error,
4899 : * making additional steps unnecessary in typical scenarios. Note that the
4900 : * default ON ERROR behavior for JSON_VALUE() and JSON_QUERY() is to
4901 : * return NULL.
4902 : */
4903 2288 : if (jsexpr->on_error->btype != JSON_BEHAVIOR_ERROR &&
4904 1862 : (!(IsA(jsexpr->on_error->expr, Const) &&
4905 1814 : ((Const *) jsexpr->on_error->expr)->constisnull) ||
4906 : returning_domain))
4907 : {
4908 : ErrorSaveContext *saved_escontext;
4909 :
4910 570 : jsestate->jump_error = state->steps_len;
4911 :
4912 : /* JUMP to end if false, that is, skip the ON ERROR expression. */
4913 570 : jumps_to_end = lappend_int(jumps_to_end, state->steps_len);
4914 570 : scratch->opcode = EEOP_JUMP_IF_NOT_TRUE;
4915 570 : scratch->resvalue = &jsestate->error.value;
4916 570 : scratch->resnull = &jsestate->error.isnull;
4917 570 : scratch->d.jump.jumpdone = -1; /* set below */
4918 570 : ExprEvalPushStep(state, scratch);
4919 :
4920 : /*
4921 : * Steps to evaluate the ON ERROR expression; handle errors softly to
4922 : * rethrow them in COERCION_FINISH step that will be added later.
4923 : */
4924 570 : saved_escontext = state->escontext;
4925 570 : state->escontext = escontext;
4926 570 : ExecInitExprRec((Expr *) jsexpr->on_error->expr,
4927 : state, resv, resnull);
4928 570 : state->escontext = saved_escontext;
4929 :
4930 : /* Step to coerce the ON ERROR expression if needed */
4931 570 : if (jsexpr->on_error->coerce)
4932 150 : ExecInitJsonCoercion(state, jsexpr->returning, escontext,
4933 150 : jsexpr->omit_quotes, false,
4934 : resv, resnull);
4935 :
4936 : /*
4937 : * Add a COERCION_FINISH step to check for errors that may occur when
4938 : * coercing and rethrow them.
4939 : */
4940 570 : if (jsexpr->on_error->coerce ||
4941 420 : IsA(jsexpr->on_error->expr, CoerceViaIO) ||
4942 420 : IsA(jsexpr->on_error->expr, CoerceToDomain))
4943 : {
4944 198 : scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
4945 198 : scratch->resvalue = resv;
4946 198 : scratch->resnull = resnull;
4947 198 : scratch->d.jsonexpr.jsestate = jsestate;
4948 198 : ExprEvalPushStep(state, scratch);
4949 : }
4950 :
4951 : /* JUMP to end to skip the ON EMPTY steps added below. */
4952 570 : jumps_to_end = lappend_int(jumps_to_end, state->steps_len);
4953 570 : scratch->opcode = EEOP_JUMP;
4954 570 : scratch->d.jump.jumpdone = -1;
4955 570 : ExprEvalPushStep(state, scratch);
4956 : }
4957 :
4958 : /*
4959 : * Step to check jsestate->empty and return the ON EMPTY expression if
4960 : * there is one.
4961 : *
4962 : * See the comment above for details on the optimization for NULL-valued
4963 : * expressions.
4964 : */
4965 2288 : if (jsexpr->on_empty != NULL &&
4966 1964 : jsexpr->on_empty->btype != JSON_BEHAVIOR_ERROR &&
4967 1898 : (!(IsA(jsexpr->on_empty->expr, Const) &&
4968 1844 : ((Const *) jsexpr->on_empty->expr)->constisnull) ||
4969 : returning_domain))
4970 : {
4971 : ErrorSaveContext *saved_escontext;
4972 :
4973 360 : jsestate->jump_empty = state->steps_len;
4974 :
4975 : /* JUMP to end if false, that is, skip the ON EMPTY expression. */
4976 360 : jumps_to_end = lappend_int(jumps_to_end, state->steps_len);
4977 360 : scratch->opcode = EEOP_JUMP_IF_NOT_TRUE;
4978 360 : scratch->resvalue = &jsestate->empty.value;
4979 360 : scratch->resnull = &jsestate->empty.isnull;
4980 360 : scratch->d.jump.jumpdone = -1; /* set below */
4981 360 : ExprEvalPushStep(state, scratch);
4982 :
4983 : /*
4984 : * Steps to evaluate the ON EMPTY expression; handle errors softly to
4985 : * rethrow them in COERCION_FINISH step that will be added later.
4986 : */
4987 360 : saved_escontext = state->escontext;
4988 360 : state->escontext = escontext;
4989 360 : ExecInitExprRec((Expr *) jsexpr->on_empty->expr,
4990 : state, resv, resnull);
4991 360 : state->escontext = saved_escontext;
4992 :
4993 : /* Step to coerce the ON EMPTY expression if needed */
4994 360 : if (jsexpr->on_empty->coerce)
4995 174 : ExecInitJsonCoercion(state, jsexpr->returning, escontext,
4996 174 : jsexpr->omit_quotes, false,
4997 : resv, resnull);
4998 :
4999 : /*
5000 : * Add a COERCION_FINISH step to check for errors that may occur when
5001 : * coercing and rethrow them.
5002 : */
5003 360 : if (jsexpr->on_empty->coerce ||
5004 186 : IsA(jsexpr->on_empty->expr, CoerceViaIO) ||
5005 186 : IsA(jsexpr->on_empty->expr, CoerceToDomain))
5006 : {
5007 :
5008 228 : scratch->opcode = EEOP_JSONEXPR_COERCION_FINISH;
5009 228 : scratch->resvalue = resv;
5010 228 : scratch->resnull = resnull;
5011 228 : scratch->d.jsonexpr.jsestate = jsestate;
5012 228 : ExprEvalPushStep(state, scratch);
5013 : }
5014 : }
5015 :
5016 3788 : foreach(lc, jumps_to_end)
5017 : {
5018 1500 : ExprEvalStep *as = &state->steps[lfirst_int(lc)];
5019 :
5020 1500 : as->d.jump.jumpdone = state->steps_len;
5021 : }
5022 :
5023 2288 : jsestate->jump_end = state->steps_len;
5024 2288 : }
5025 :
5026 : /*
5027 : * Initialize a EEOP_JSONEXPR_COERCION step to coerce the value given in resv
5028 : * to the given RETURNING type.
5029 : */
5030 : static void
5031 1212 : ExecInitJsonCoercion(ExprState *state, JsonReturning *returning,
5032 : ErrorSaveContext *escontext, bool omit_quotes,
5033 : bool exists_coerce,
5034 : Datum *resv, bool *resnull)
5035 : {
5036 1212 : ExprEvalStep scratch = {0};
5037 :
5038 : /* For json_populate_type() */
5039 1212 : scratch.opcode = EEOP_JSONEXPR_COERCION;
5040 1212 : scratch.resvalue = resv;
5041 1212 : scratch.resnull = resnull;
5042 1212 : scratch.d.jsonexpr_coercion.targettype = returning->typid;
5043 1212 : scratch.d.jsonexpr_coercion.targettypmod = returning->typmod;
5044 1212 : scratch.d.jsonexpr_coercion.json_coercion_cache = NULL;
5045 1212 : scratch.d.jsonexpr_coercion.escontext = escontext;
5046 1212 : scratch.d.jsonexpr_coercion.omit_quotes = omit_quotes;
5047 1212 : scratch.d.jsonexpr_coercion.exists_coerce = exists_coerce;
5048 1332 : scratch.d.jsonexpr_coercion.exists_cast_to_int = exists_coerce &&
5049 120 : getBaseType(returning->typid) == INT4OID;
5050 1332 : scratch.d.jsonexpr_coercion.exists_check_domain = exists_coerce &&
5051 120 : DomainHasConstraints(returning->typid);
5052 1212 : ExprEvalPushStep(state, &scratch);
5053 1212 : }
|