1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/pl/plpgsql/src/pl_exec.c
13 *-------------------------------------------------------------------------
20 #include "access/detoast.h"
21 #include "access/htup_details.h"
22 #include "access/transam.h"
23 #include "access/tupconvert.h"
24 #include "catalog/pg_proc.h"
25 #include "catalog/pg_type.h"
26 #include "commands/defrem.h"
27 #include "executor/execExpr.h"
28 #include "executor/spi.h"
29 #include "executor/spi_priv.h"
31 #include "miscadmin.h"
32 #include "nodes/nodeFuncs.h"
33 #include "optimizer/optimizer.h"
34 #include "parser/parse_coerce.h"
35 #include "parser/parse_type.h"
36 #include "parser/scansup.h"
38 #include "storage/proc.h"
39 #include "tcop/tcopprot.h"
40 #include "tcop/utility.h"
41 #include "utils/array.h"
42 #include "utils/builtins.h"
43 #include "utils/datum.h"
44 #include "utils/fmgroids.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/rel.h"
48 #include "utils/snapmgr.h"
49 #include "utils/syscache.h"
50 #include "utils/typcache.h"
54 int nargs; /* number of arguments */
55 Oid *types; /* types of arguments */
56 Datum *values; /* evaluated argument values */
57 char *nulls; /* null markers (' '/'n' style) */
61 * All plpgsql function executions within a single transaction share the same
62 * executor EState for evaluating "simple" expressions. Each function call
63 * creates its own "eval_econtext" ExprContext within this estate for
64 * per-evaluation workspace. eval_econtext is freed at normal function exit,
65 * and the EState is freed at transaction end (in case of error, we assume
66 * that the abort mechanisms clean it all up). Furthermore, any exception
67 * block within a function has to have its own eval_econtext separate from
68 * the containing function's, so that we can clean up ExprContext callbacks
69 * properly at subtransaction exit. We maintain a stack that tracks the
70 * individual econtexts so that we can clean up correctly at subxact exit.
72 * This arrangement is a bit tedious to maintain, but it's worth the trouble
73 * so that we don't have to re-prepare simple expressions on each trip through
74 * a function. (We assume the case to optimize is many repetitions of a
75 * function within a transaction.)
77 * However, there's no value in trying to amortize simple expression setup
78 * across multiple executions of a DO block (inline code block), since there
79 * can never be any. If we use the shared EState for a DO block, the expr
80 * state trees are effectively leaked till end of transaction, and that can
81 * add up if the user keeps on submitting DO blocks. Therefore, each DO block
82 * has its own simple-expression EState, which is cleaned up at exit from
83 * plpgsql_inline_handler(). DO blocks still use the simple_econtext_stack,
84 * though, so that subxact abort cleanup does the right thing.
86 typedef struct SimpleEcontextStackEntry
88 ExprContext *stack_econtext; /* a stacked econtext */
89 SubTransactionId xact_subxid; /* ID for current subxact */
90 struct SimpleEcontextStackEntry *next; /* next stack entry up */
91 } SimpleEcontextStackEntry;
93 static EState *shared_simple_eval_estate = NULL;
94 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
97 * Memory management within a plpgsql function generally works with three
100 * 1. Function-call-lifespan data, such as variable values, is kept in the
101 * "main" context, a/k/a the "SPI Proc" context established by SPI_connect().
102 * This is usually the CurrentMemoryContext while running code in this module
103 * (which is not good, because careless coding can easily cause
104 * function-lifespan memory leaks, but we live with it for now).
106 * 2. Some statement-execution routines need statement-lifespan workspace.
107 * A suitable context is created on-demand by get_stmt_mcontext(), and must
108 * be reset at the end of the requesting routine. Error recovery will clean
109 * it up automatically. Nested statements requiring statement-lifespan
110 * workspace will result in a stack of such contexts, see push_stmt_mcontext().
112 * 3. We use the eval_econtext's per-tuple memory context for expression
113 * evaluation, and as a general-purpose workspace for short-lived allocations.
114 * Such allocations usually aren't explicitly freed, but are left to be
115 * cleaned up by a context reset, typically done by exec_eval_cleanup().
117 * These macros are for use in making short-lived allocations:
119 #define get_eval_mcontext(estate) \
120 ((estate)->eval_econtext->ecxt_per_tuple_memory)
121 #define eval_mcontext_alloc(estate, sz) \
122 MemoryContextAlloc(get_eval_mcontext(estate), sz)
123 #define eval_mcontext_alloc0(estate, sz) \
124 MemoryContextAllocZero(get_eval_mcontext(estate), sz)
127 * We use a session-wide hash table for caching cast information.
129 * Once built, the compiled expression trees (cast_expr fields) survive for
130 * the life of the session. At some point it might be worth invalidating
131 * those after pg_cast changes, but for the moment we don't bother.
133 * The evaluation state trees (cast_exprstate) are managed in the same way as
134 * simple expressions (i.e., we assume cast expressions are always simple).
136 * As with simple expressions, DO blocks don't use the shared hash table but
137 * must have their own. This isn't ideal, but we don't want to deal with
138 * multiple simple_eval_estates within a DO block.
140 typedef struct /* lookup key for cast info */
142 /* NB: we assume this struct contains no padding bytes */
143 Oid srctype; /* source type for cast */
144 Oid dsttype; /* destination type for cast */
145 int32 srctypmod; /* source typmod for cast */
146 int32 dsttypmod; /* destination typmod for cast */
147 } plpgsql_CastHashKey;
149 typedef struct /* cast_hash table entry */
151 plpgsql_CastHashKey key; /* hash key --- MUST BE FIRST */
152 Expr *cast_expr; /* cast expression, or NULL if no-op cast */
153 CachedExpression *cast_cexpr; /* cached expression backing the above */
154 /* ExprState is valid only when cast_lxid matches current LXID */
155 ExprState *cast_exprstate; /* expression's eval tree */
156 bool cast_in_use; /* true while we're executing eval tree */
157 LocalTransactionId cast_lxid;
158 } plpgsql_CastHashEntry;
160 static MemoryContext shared_cast_context = NULL;
161 static HTAB *shared_cast_hash = NULL;
164 * LOOP_RC_PROCESSING encapsulates common logic for looping statements to
165 * handle return/exit/continue result codes from the loop body statement(s).
166 * It's meant to be used like this:
168 * int rc = PLPGSQL_RC_OK;
172 * rc = exec_stmts(estate, stmt->body);
173 * LOOP_RC_PROCESSING(stmt->label, break);
178 * If execution of the loop should terminate, LOOP_RC_PROCESSING will execute
179 * "exit_action" (typically a "break" or "goto"), after updating "rc" to the
180 * value the current statement should return. If execution should continue,
181 * LOOP_RC_PROCESSING will do nothing except reset "rc" to PLPGSQL_RC_OK.
183 * estate and rc are implicit arguments to the macro.
184 * estate->exitlabel is examined and possibly updated.
186 #define LOOP_RC_PROCESSING(looplabel, exit_action) \
187 if (rc == PLPGSQL_RC_RETURN) \
189 /* RETURN, so propagate RC_RETURN out */ \
192 else if (rc == PLPGSQL_RC_EXIT) \
194 if (estate->exitlabel == NULL) \
196 /* unlabelled EXIT terminates this loop */ \
197 rc = PLPGSQL_RC_OK; \
200 else if ((looplabel) != NULL && \
201 strcmp(looplabel, estate->exitlabel) == 0) \
203 /* labelled EXIT matching this loop, so terminate loop */ \
204 estate->exitlabel = NULL; \
205 rc = PLPGSQL_RC_OK; \
210 /* non-matching labelled EXIT, propagate RC_EXIT out */ \
214 else if (rc == PLPGSQL_RC_CONTINUE) \
216 if (estate->exitlabel == NULL) \
218 /* unlabelled CONTINUE matches this loop, so continue in loop */ \
219 rc = PLPGSQL_RC_OK; \
221 else if ((looplabel) != NULL && \
222 strcmp(looplabel, estate->exitlabel) == 0) \
224 /* labelled CONTINUE matching this loop, so continue in loop */ \
225 estate->exitlabel = NULL; \
226 rc = PLPGSQL_RC_OK; \
230 /* non-matching labelled CONTINUE, propagate RC_CONTINUE out */ \
235 Assert(rc == PLPGSQL_RC_OK)
237 /************************************************************
238 * Local function forward declarations
239 ************************************************************/
240 static void coerce_function_result_tuple(PLpgSQL_execstate *estate,
242 static void plpgsql_exec_error_callback(void *arg);
243 static void copy_plpgsql_datums(PLpgSQL_execstate *estate,
244 PLpgSQL_function *func);
245 static void plpgsql_fulfill_promise(PLpgSQL_execstate *estate,
247 static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate);
248 static void push_stmt_mcontext(PLpgSQL_execstate *estate);
249 static void pop_stmt_mcontext(PLpgSQL_execstate *estate);
251 static int exec_stmt_block(PLpgSQL_execstate *estate,
252 PLpgSQL_stmt_block *block);
253 static int exec_stmts(PLpgSQL_execstate *estate,
255 static int exec_stmt(PLpgSQL_execstate *estate,
257 static int exec_stmt_assign(PLpgSQL_execstate *estate,
258 PLpgSQL_stmt_assign *stmt);
259 static int exec_stmt_perform(PLpgSQL_execstate *estate,
260 PLpgSQL_stmt_perform *stmt);
261 static int exec_stmt_call(PLpgSQL_execstate *estate,
262 PLpgSQL_stmt_call *stmt);
263 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
264 PLpgSQL_stmt_getdiag *stmt);
265 static int exec_stmt_if(PLpgSQL_execstate *estate,
266 PLpgSQL_stmt_if *stmt);
267 static int exec_stmt_case(PLpgSQL_execstate *estate,
268 PLpgSQL_stmt_case *stmt);
269 static int exec_stmt_loop(PLpgSQL_execstate *estate,
270 PLpgSQL_stmt_loop *stmt);
271 static int exec_stmt_while(PLpgSQL_execstate *estate,
272 PLpgSQL_stmt_while *stmt);
273 static int exec_stmt_fori(PLpgSQL_execstate *estate,
274 PLpgSQL_stmt_fori *stmt);
275 static int exec_stmt_fors(PLpgSQL_execstate *estate,
276 PLpgSQL_stmt_fors *stmt);
277 static int exec_stmt_forc(PLpgSQL_execstate *estate,
278 PLpgSQL_stmt_forc *stmt);
279 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
280 PLpgSQL_stmt_foreach_a *stmt);
281 static int exec_stmt_open(PLpgSQL_execstate *estate,
282 PLpgSQL_stmt_open *stmt);
283 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
284 PLpgSQL_stmt_fetch *stmt);
285 static int exec_stmt_close(PLpgSQL_execstate *estate,
286 PLpgSQL_stmt_close *stmt);
287 static int exec_stmt_exit(PLpgSQL_execstate *estate,
288 PLpgSQL_stmt_exit *stmt);
289 static int exec_stmt_return(PLpgSQL_execstate *estate,
290 PLpgSQL_stmt_return *stmt);
291 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
292 PLpgSQL_stmt_return_next *stmt);
293 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
294 PLpgSQL_stmt_return_query *stmt);
295 static int exec_stmt_raise(PLpgSQL_execstate *estate,
296 PLpgSQL_stmt_raise *stmt);
297 static int exec_stmt_assert(PLpgSQL_execstate *estate,
298 PLpgSQL_stmt_assert *stmt);
299 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
300 PLpgSQL_stmt_execsql *stmt);
301 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
302 PLpgSQL_stmt_dynexecute *stmt);
303 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
304 PLpgSQL_stmt_dynfors *stmt);
305 static int exec_stmt_commit(PLpgSQL_execstate *estate,
306 PLpgSQL_stmt_commit *stmt);
307 static int exec_stmt_rollback(PLpgSQL_execstate *estate,
308 PLpgSQL_stmt_rollback *stmt);
309 static int exec_stmt_set(PLpgSQL_execstate *estate,
310 PLpgSQL_stmt_set *stmt);
312 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
313 PLpgSQL_function *func,
315 EState *simple_eval_estate);
316 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
318 static void exec_prepare_plan(PLpgSQL_execstate *estate,
319 PLpgSQL_expr *expr, int cursorOptions,
321 static void exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr);
322 static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan);
323 static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno);
324 static bool contains_target_param(Node *node, int *target_dno);
325 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
332 static void exec_assign_expr(PLpgSQL_execstate *estate,
333 PLpgSQL_datum *target,
335 static void exec_assign_c_string(PLpgSQL_execstate *estate,
336 PLpgSQL_datum *target,
338 static void exec_assign_value(PLpgSQL_execstate *estate,
339 PLpgSQL_datum *target,
340 Datum value, bool isNull,
341 Oid valtype, int32 valtypmod);
342 static void exec_eval_datum(PLpgSQL_execstate *estate,
343 PLpgSQL_datum *datum,
348 static int exec_eval_integer(PLpgSQL_execstate *estate,
351 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
354 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
359 static int exec_run_select(PLpgSQL_execstate *estate,
360 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
361 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
362 Portal portal, bool prefetch_ok);
363 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
365 static ParamExternData *plpgsql_param_fetch(ParamListInfo params,
366 int paramid, bool speculative,
367 ParamExternData *workspace);
368 static void plpgsql_param_compile(ParamListInfo params, Param *param,
370 Datum *resv, bool *resnull);
371 static void plpgsql_param_eval_var(ExprState *state, ExprEvalStep *op,
372 ExprContext *econtext);
373 static void plpgsql_param_eval_var_ro(ExprState *state, ExprEvalStep *op,
374 ExprContext *econtext);
375 static void plpgsql_param_eval_recfield(ExprState *state, ExprEvalStep *op,
376 ExprContext *econtext);
377 static void plpgsql_param_eval_generic(ExprState *state, ExprEvalStep *op,
378 ExprContext *econtext);
379 static void plpgsql_param_eval_generic_ro(ExprState *state, ExprEvalStep *op,
380 ExprContext *econtext);
381 static void exec_move_row(PLpgSQL_execstate *estate,
382 PLpgSQL_variable *target,
383 HeapTuple tup, TupleDesc tupdesc);
384 static void revalidate_rectypeid(PLpgSQL_rec *rec);
385 static ExpandedRecordHeader *make_expanded_record_for_rec(PLpgSQL_execstate *estate,
387 TupleDesc srctupdesc,
388 ExpandedRecordHeader *srcerh);
389 static void exec_move_row_from_fields(PLpgSQL_execstate *estate,
390 PLpgSQL_variable *target,
391 ExpandedRecordHeader *newerh,
392 Datum *values, bool *nulls,
394 static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc);
395 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
398 static TupleDesc deconstruct_composite_datum(Datum value,
399 HeapTupleData *tmptup);
400 static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
401 PLpgSQL_variable *target,
403 static void instantiate_empty_record_variable(PLpgSQL_execstate *estate,
405 static char *convert_value_to_string(PLpgSQL_execstate *estate,
406 Datum value, Oid valtype);
407 static Datum exec_cast_value(PLpgSQL_execstate *estate,
408 Datum value, bool *isnull,
409 Oid valtype, int32 valtypmod,
410 Oid reqtype, int32 reqtypmod);
411 static plpgsql_CastHashEntry *get_cast_hashentry(PLpgSQL_execstate *estate,
412 Oid srctype, int32 srctypmod,
413 Oid dsttype, int32 dsttypmod);
414 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
415 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
416 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
417 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
418 static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
419 Datum newvalue, bool isnull, bool freeable);
420 static void assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
422 static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec,
423 ExpandedRecordHeader *erh);
424 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
426 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
427 PLpgSQL_expr *dynquery, List *params,
428 const char *portalname, int cursorOptions);
429 static char *format_expr_params(PLpgSQL_execstate *estate,
430 const PLpgSQL_expr *expr);
431 static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
432 const PreparedParamsData *ppd);
436 * plpgsql_exec_function Called by the call handler for
437 * function execution.
439 * This is also used to execute inline code blocks (DO blocks). The only
440 * difference that this code is aware of is that for a DO block, we want
441 * to use a private simple_eval_estate, which is created and passed in by
442 * the caller. For regular functions, pass NULL, which implies using
443 * shared_simple_eval_estate. (When using a private simple_eval_estate,
444 * we must also use a private cast hashtable, but that's taken care of
445 * within plpgsql_estate_setup.)
449 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
450 EState *simple_eval_estate, bool atomic)
452 PLpgSQL_execstate estate;
453 ErrorContextCallback plerrcontext;
458 * Setup the execution state
460 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
462 estate.atomic = atomic;
465 * Setup error traceback support for ereport()
467 plerrcontext.callback = plpgsql_exec_error_callback;
468 plerrcontext.arg = &estate;
469 plerrcontext.previous = error_context_stack;
470 error_context_stack = &plerrcontext;
473 * Make local execution copies of all the datums
475 estate.err_text = gettext_noop("during initialization of execution state");
476 copy_plpgsql_datums(&estate, func);
479 * Store the actual call argument values into the appropriate variables
481 estate.err_text = gettext_noop("while storing call arguments into local variables");
482 for (i = 0; i < func->fn_nargs; i++)
484 int n = func->fn_argvarnos[i];
486 switch (estate.datums[n]->dtype)
488 case PLPGSQL_DTYPE_VAR:
490 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
492 assign_simple_var(&estate, var,
493 fcinfo->args[i].value,
494 fcinfo->args[i].isnull,
498 * Force any array-valued parameter to be stored in
499 * expanded form in our local variable, in hopes of
500 * improving efficiency of uses of the variable. (This is
501 * a hack, really: why only arrays? Need more thought
502 * about which cases are likely to win. See also
503 * typisarray-specific heuristic in exec_assign_value.)
505 * Special cases: If passed a R/W expanded pointer, assume
506 * we can commandeer the object rather than having to copy
507 * it. If passed a R/O expanded pointer, just keep it as
508 * the value of the variable for the moment. (We'll force
509 * it to R/W if the variable gets modified, but that may
510 * very well never happen.)
512 if (!var->isnull && var->datatype->typisarray)
514 if (VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(var->value)))
516 /* take ownership of R/W object */
517 assign_simple_var(&estate, var,
518 TransferExpandedObject(var->value,
519 estate.datum_context),
523 else if (VARATT_IS_EXTERNAL_EXPANDED_RO(DatumGetPointer(var->value)))
525 /* R/O pointer, keep it as-is until assigned to */
529 /* flat array, so force to expanded form */
530 assign_simple_var(&estate, var,
531 expand_array(var->value,
532 estate.datum_context,
541 case PLPGSQL_DTYPE_REC:
543 PLpgSQL_rec *rec = (PLpgSQL_rec *) estate.datums[n];
545 if (!fcinfo->args[i].isnull)
547 /* Assign row value from composite datum */
548 exec_move_row_from_datum(&estate,
549 (PLpgSQL_variable *) rec,
550 fcinfo->args[i].value);
554 /* If arg is null, set variable to null */
555 exec_move_row(&estate, (PLpgSQL_variable *) rec,
558 /* clean up after exec_move_row() */
559 exec_eval_cleanup(&estate);
564 /* Anything else should not be an argument variable */
565 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
569 estate.err_text = gettext_noop("during function entry");
572 * Set the magic variable FOUND to false
574 exec_set_found(&estate, false);
577 * Let the instrumentation plugin peek at this function
579 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
580 ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
583 * Now call the toplevel block of statements
585 estate.err_text = NULL;
586 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
587 rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
588 if (rc != PLPGSQL_RC_RETURN)
590 estate.err_stmt = NULL;
591 estate.err_text = NULL;
593 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
594 errmsg("control reached end of function without RETURN")));
598 * We got a return value - process it
600 estate.err_stmt = NULL;
601 estate.err_text = gettext_noop("while casting return value to function's return type");
603 fcinfo->isnull = estate.retisnull;
607 ReturnSetInfo *rsi = estate.rsi;
609 /* Check caller can handle a set result */
610 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
611 (rsi->allowedModes & SFRM_Materialize) == 0)
613 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
614 errmsg("set-valued function called in context that cannot accept a set")));
615 rsi->returnMode = SFRM_Materialize;
617 /* If we produced any tuples, send back the result */
618 if (estate.tuple_store)
620 MemoryContext oldcxt;
622 rsi->setResult = estate.tuple_store;
623 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
624 rsi->setDesc = CreateTupleDescCopy(estate.tuple_store_desc);
625 MemoryContextSwitchTo(oldcxt);
627 estate.retval = (Datum) 0;
628 fcinfo->isnull = true;
630 else if (!estate.retisnull)
633 * Cast result value to function's declared result type, and copy it
634 * out to the upper executor memory context. We must treat tuple
635 * results specially in order to deal with cases like rowtypes
636 * involving dropped columns.
638 if (estate.retistuple)
640 /* Don't need coercion if rowtype is known to match */
641 if (func->fn_rettype == estate.rettype &&
642 func->fn_rettype != RECORDOID)
645 * Copy the tuple result into upper executor memory context.
646 * However, if we have a R/W expanded datum, we can just
647 * transfer its ownership out to the upper context.
649 estate.retval = SPI_datumTransfer(estate.retval,
656 * Need to look up the expected result type. XXX would be
657 * better to cache the tupdesc instead of repeating
658 * get_call_result_type(), but the only easy place to save it
659 * is in the PLpgSQL_function struct, and that's too
660 * long-lived: composite types could change during the
661 * existence of a PLpgSQL_function.
666 switch (get_call_result_type(fcinfo, &resultTypeId, &tupdesc))
668 case TYPEFUNC_COMPOSITE:
669 /* got the expected result rowtype, now coerce it */
670 coerce_function_result_tuple(&estate, tupdesc);
672 case TYPEFUNC_COMPOSITE_DOMAIN:
673 /* got the expected result rowtype, now coerce it */
674 coerce_function_result_tuple(&estate, tupdesc);
675 /* and check domain constraints */
676 /* XXX allowing caching here would be good, too */
677 domain_check(estate.retval, false, resultTypeId,
680 case TYPEFUNC_RECORD:
683 * Failed to determine actual type of RECORD. We
684 * could raise an error here, but what this means in
685 * practice is that the caller is expecting any old
686 * generic rowtype, so we don't really need to be
687 * restrictive. Pass back the generated result as-is.
689 estate.retval = SPI_datumTransfer(estate.retval,
694 /* shouldn't get here if retistuple is true ... */
695 elog(ERROR, "return type must be a row type");
702 /* Scalar case: use exec_cast_value */
703 estate.retval = exec_cast_value(&estate,
712 * If the function's return type isn't by value, copy the value
713 * into upper executor memory context. However, if we have a R/W
714 * expanded datum, we can just transfer its ownership out to the
715 * upper executor context.
717 if (!fcinfo->isnull && !func->fn_retbyval)
718 estate.retval = SPI_datumTransfer(estate.retval,
726 * We're returning a NULL, which normally requires no conversion work
727 * regardless of datatypes. But, if we are casting it to a domain
728 * return type, we'd better check that the domain's constraints pass.
730 if (func->fn_retisdomain)
731 estate.retval = exec_cast_value(&estate,
740 estate.err_text = gettext_noop("during function exit");
743 * Let the instrumentation plugin peek at this function
745 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
746 ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
748 /* Clean up any leftover temporary memory */
749 plpgsql_destroy_econtext(&estate);
750 exec_eval_cleanup(&estate);
751 /* stmt_mcontext will be destroyed when function's main context is */
754 * Pop the error context stack
756 error_context_stack = plerrcontext.previous;
759 * Return the function's result
761 return estate.retval;
765 * Helper for plpgsql_exec_function: coerce composite result to the specified
766 * tuple descriptor, and copy it out to upper executor memory. This is split
767 * out mostly for cosmetic reasons --- the logic would be very deeply nested
770 * estate->retval is updated in-place.
773 coerce_function_result_tuple(PLpgSQL_execstate *estate, TupleDesc tupdesc)
777 TupleConversionMap *tupmap;
779 /* We assume exec_stmt_return verified that result is composite */
780 Assert(type_is_rowtype(estate->rettype));
782 /* We can special-case expanded records for speed */
783 if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(estate->retval)))
785 ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(estate->retval);
787 Assert(erh->er_magic == ER_MAGIC);
789 /* Extract record's TupleDesc */
790 retdesc = expanded_record_get_tupdesc(erh);
792 /* check rowtype compatibility */
793 tupmap = convert_tuples_by_position(retdesc,
795 gettext_noop("returned record type does not match expected record type"));
797 /* it might need conversion */
800 rettup = expanded_record_get_tuple(erh);
802 rettup = execute_attr_map_tuple(rettup, tupmap);
805 * Copy tuple to upper executor memory, as a tuple Datum. Make
806 * sure it is labeled with the caller-supplied tuple type.
808 estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
809 /* no need to free map, we're about to return anyway */
811 else if (!(tupdesc->tdtypeid == erh->er_decltypeid ||
812 (tupdesc->tdtypeid == RECORDOID &&
813 !ExpandedRecordIsDomain(erh))))
816 * The expanded record has the right physical tupdesc, but the
817 * wrong type ID. (Typically, the expanded record is RECORDOID
818 * but the function is declared to return a named composite type.
819 * As in exec_move_row_from_datum, we don't allow returning a
820 * composite-domain record from a function declared to return
821 * RECORD.) So we must flatten the record to a tuple datum and
822 * overwrite its type fields with the right thing. spi.c doesn't
823 * provide any easy way to deal with this case, so we end up
824 * duplicating the guts of datumCopy() :-(
827 HeapTupleHeader tuphdr;
829 resultsize = EOH_get_flat_size(&erh->hdr);
830 tuphdr = (HeapTupleHeader) SPI_palloc(resultsize);
831 EOH_flatten_into(&erh->hdr, (void *) tuphdr, resultsize);
832 HeapTupleHeaderSetTypeId(tuphdr, tupdesc->tdtypeid);
833 HeapTupleHeaderSetTypMod(tuphdr, tupdesc->tdtypmod);
834 estate->retval = PointerGetDatum(tuphdr);
839 * We need only copy result into upper executor memory context.
840 * However, if we have a R/W expanded datum, we can just transfer
841 * its ownership out to the upper executor context.
843 estate->retval = SPI_datumTransfer(estate->retval,
850 /* Convert composite datum to a HeapTuple and TupleDesc */
851 HeapTupleData tmptup;
853 retdesc = deconstruct_composite_datum(estate->retval, &tmptup);
856 /* check rowtype compatibility */
857 tupmap = convert_tuples_by_position(retdesc,
859 gettext_noop("returned record type does not match expected record type"));
861 /* it might need conversion */
863 rettup = execute_attr_map_tuple(rettup, tupmap);
866 * Copy tuple to upper executor memory, as a tuple Datum. Make sure
867 * it is labeled with the caller-supplied tuple type.
869 estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
871 /* no need to free map, we're about to return anyway */
873 ReleaseTupleDesc(retdesc);
879 * plpgsql_exec_trigger Called by the call handler for
884 plpgsql_exec_trigger(PLpgSQL_function *func,
885 TriggerData *trigdata)
887 PLpgSQL_execstate estate;
888 ErrorContextCallback plerrcontext;
891 PLpgSQL_rec *rec_new,
896 * Setup the execution state
898 plpgsql_estate_setup(&estate, func, NULL, NULL);
899 estate.trigdata = trigdata;
902 * Setup error traceback support for ereport()
904 plerrcontext.callback = plpgsql_exec_error_callback;
905 plerrcontext.arg = &estate;
906 plerrcontext.previous = error_context_stack;
907 error_context_stack = &plerrcontext;
910 * Make local execution copies of all the datums
912 estate.err_text = gettext_noop("during initialization of execution state");
913 copy_plpgsql_datums(&estate, func);
916 * Put the OLD and NEW tuples into record variables
918 * We set up expanded records for both variables even though only one may
919 * have a value. This allows record references to succeed in functions
920 * that are used for multiple trigger types. For example, we might have a
921 * test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')", which should
922 * work regardless of the current trigger type. If a value is actually
923 * fetched from an unsupplied tuple, it will read as NULL.
925 tupdesc = RelationGetDescr(trigdata->tg_relation);
927 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
928 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
930 rec_new->erh = make_expanded_record_from_tupdesc(tupdesc,
931 estate.datum_context);
932 rec_old->erh = make_expanded_record_from_exprecord(rec_new->erh,
933 estate.datum_context);
935 if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
938 * Per-statement triggers don't use OLD/NEW variables
941 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
943 expanded_record_set_tuple(rec_new->erh, trigdata->tg_trigtuple,
946 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
948 expanded_record_set_tuple(rec_new->erh, trigdata->tg_newtuple,
950 expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
954 * In BEFORE trigger, stored generated columns are not computed yet,
955 * so make them null in the NEW row. (Only needed in UPDATE branch;
956 * in the INSERT case, they are already null, but in UPDATE, the field
957 * still contains the old value.) Alternatively, we could construct a
958 * whole new row structure without the generated columns, but this way
959 * seems more efficient and potentially less confusing.
961 if (tupdesc->constr && tupdesc->constr->has_generated_stored &&
962 TRIGGER_FIRED_BEFORE(trigdata->tg_event))
964 for (int i = 0; i < tupdesc->natts; i++)
965 if (TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED)
966 expanded_record_set_field_internal(rec_new->erh,
973 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
975 expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
979 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
981 /* Make transition tables visible to this SPI connection */
982 rc = SPI_register_trigger_data(trigdata);
985 estate.err_text = gettext_noop("during function entry");
988 * Set the magic variable FOUND to false
990 exec_set_found(&estate, false);
993 * Let the instrumentation plugin peek at this function
995 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
996 ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
999 * Now call the toplevel block of statements
1001 estate.err_text = NULL;
1002 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
1003 rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
1004 if (rc != PLPGSQL_RC_RETURN)
1006 estate.err_stmt = NULL;
1007 estate.err_text = NULL;
1009 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
1010 errmsg("control reached end of trigger procedure without RETURN")));
1013 estate.err_stmt = NULL;
1014 estate.err_text = gettext_noop("during function exit");
1016 if (estate.retisset)
1018 (errcode(ERRCODE_DATATYPE_MISMATCH),
1019 errmsg("trigger procedure cannot return a set")));
1022 * Check that the returned tuple structure has the same attributes, the
1023 * relation that fired the trigger has. A per-statement trigger always
1024 * needs to return NULL, so we ignore any return value the function itself
1025 * produces (XXX: is this a good idea?)
1027 * XXX This way it is possible, that the trigger returns a tuple where
1028 * attributes don't have the correct atttypmod's length. It's up to the
1029 * trigger's programmer to ensure that this doesn't happen. Jan
1031 if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
1036 TupleConversionMap *tupmap;
1038 /* We assume exec_stmt_return verified that result is composite */
1039 Assert(type_is_rowtype(estate.rettype));
1041 /* We can special-case expanded records for speed */
1042 if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(estate.retval)))
1044 ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(estate.retval);
1046 Assert(erh->er_magic == ER_MAGIC);
1048 /* Extract HeapTuple and TupleDesc */
1049 rettup = expanded_record_get_tuple(erh);
1051 retdesc = expanded_record_get_tupdesc(erh);
1053 if (retdesc != RelationGetDescr(trigdata->tg_relation))
1055 /* check rowtype compatibility */
1056 tupmap = convert_tuples_by_position(retdesc,
1057 RelationGetDescr(trigdata->tg_relation),
1058 gettext_noop("returned row structure does not match the structure of the triggering table"));
1059 /* it might need conversion */
1061 rettup = execute_attr_map_tuple(rettup, tupmap);
1062 /* no need to free map, we're about to return anyway */
1066 * Copy tuple to upper executor memory. But if user just did
1067 * "return new" or "return old" without changing anything, there's
1068 * no need to copy; we can return the original tuple (which will
1069 * save a few cycles in trigger.c as well as here).
1071 if (rettup != trigdata->tg_newtuple &&
1072 rettup != trigdata->tg_trigtuple)
1073 rettup = SPI_copytuple(rettup);
1077 /* Convert composite datum to a HeapTuple and TupleDesc */
1078 HeapTupleData tmptup;
1080 retdesc = deconstruct_composite_datum(estate.retval, &tmptup);
1083 /* check rowtype compatibility */
1084 tupmap = convert_tuples_by_position(retdesc,
1085 RelationGetDescr(trigdata->tg_relation),
1086 gettext_noop("returned row structure does not match the structure of the triggering table"));
1087 /* it might need conversion */
1089 rettup = execute_attr_map_tuple(rettup, tupmap);
1091 ReleaseTupleDesc(retdesc);
1092 /* no need to free map, we're about to return anyway */
1094 /* Copy tuple to upper executor memory */
1095 rettup = SPI_copytuple(rettup);
1100 * Let the instrumentation plugin peek at this function
1102 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
1103 ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
1105 /* Clean up any leftover temporary memory */
1106 plpgsql_destroy_econtext(&estate);
1107 exec_eval_cleanup(&estate);
1108 /* stmt_mcontext will be destroyed when function's main context is */
1111 * Pop the error context stack
1113 error_context_stack = plerrcontext.previous;
1116 * Return the trigger's result
1122 * plpgsql_exec_event_trigger Called by the call handler for
1123 * event trigger execution.
1127 plpgsql_exec_event_trigger(PLpgSQL_function *func, EventTriggerData *trigdata)
1129 PLpgSQL_execstate estate;
1130 ErrorContextCallback plerrcontext;
1134 * Setup the execution state
1136 plpgsql_estate_setup(&estate, func, NULL, NULL);
1137 estate.evtrigdata = trigdata;
1140 * Setup error traceback support for ereport()
1142 plerrcontext.callback = plpgsql_exec_error_callback;
1143 plerrcontext.arg = &estate;
1144 plerrcontext.previous = error_context_stack;
1145 error_context_stack = &plerrcontext;
1148 * Make local execution copies of all the datums
1150 estate.err_text = gettext_noop("during initialization of execution state");
1151 copy_plpgsql_datums(&estate, func);
1154 * Let the instrumentation plugin peek at this function
1156 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
1157 ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
1160 * Now call the toplevel block of statements
1162 estate.err_text = NULL;
1163 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
1164 rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
1165 if (rc != PLPGSQL_RC_RETURN)
1167 estate.err_stmt = NULL;
1168 estate.err_text = NULL;
1170 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
1171 errmsg("control reached end of trigger procedure without RETURN")));
1174 estate.err_stmt = NULL;
1175 estate.err_text = gettext_noop("during function exit");
1178 * Let the instrumentation plugin peek at this function
1180 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
1181 ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
1183 /* Clean up any leftover temporary memory */
1184 plpgsql_destroy_econtext(&estate);
1185 exec_eval_cleanup(&estate);
1186 /* stmt_mcontext will be destroyed when function's main context is */
1189 * Pop the error context stack
1191 error_context_stack = plerrcontext.previous;
1197 * error context callback to let us supply a call-stack traceback
1200 plpgsql_exec_error_callback(void *arg)
1202 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
1204 if (estate->err_text != NULL)
1207 * We don't expend the cycles to run gettext() on err_text unless we
1208 * actually need it. Therefore, places that set up err_text should
1209 * use gettext_noop() to ensure the strings get recorded in the
1210 * message dictionary.
1212 * If both err_text and err_stmt are set, use the err_text as
1213 * description, but report the err_stmt's line number. When err_stmt
1214 * is not set, we're in function entry/exit, or some such place not
1215 * attached to a specific line number.
1217 if (estate->err_stmt != NULL)
1220 * translator: last %s is a phrase such as "during statement block
1221 * local variable initialization"
1223 errcontext("PL/pgSQL function %s line %d %s",
1224 estate->func->fn_signature,
1225 estate->err_stmt->lineno,
1226 _(estate->err_text));
1231 * translator: last %s is a phrase such as "while storing call
1232 * arguments into local variables"
1234 errcontext("PL/pgSQL function %s %s",
1235 estate->func->fn_signature,
1236 _(estate->err_text));
1239 else if (estate->err_stmt != NULL)
1241 /* translator: last %s is a plpgsql statement type name */
1242 errcontext("PL/pgSQL function %s line %d at %s",
1243 estate->func->fn_signature,
1244 estate->err_stmt->lineno,
1245 plpgsql_stmt_typename(estate->err_stmt));
1248 errcontext("PL/pgSQL function %s",
1249 estate->func->fn_signature);
1254 * Support function for initializing local execution variables
1258 copy_plpgsql_datums(PLpgSQL_execstate *estate,
1259 PLpgSQL_function *func)
1261 int ndatums = estate->ndatums;
1262 PLpgSQL_datum **indatums;
1263 PLpgSQL_datum **outdatums;
1268 /* Allocate local datum-pointer array */
1269 estate->datums = (PLpgSQL_datum **)
1270 palloc(sizeof(PLpgSQL_datum *) * ndatums);
1273 * To reduce palloc overhead, we make a single palloc request for all the
1274 * space needed for locally-instantiated datums.
1276 workspace = palloc(func->copiable_size);
1277 ws_next = workspace;
1279 /* Fill datum-pointer array, copying datums into workspace as needed */
1280 indatums = func->datums;
1281 outdatums = estate->datums;
1282 for (i = 0; i < ndatums; i++)
1284 PLpgSQL_datum *indatum = indatums[i];
1285 PLpgSQL_datum *outdatum;
1287 /* This must agree with plpgsql_finish_datums on what is copiable */
1288 switch (indatum->dtype)
1290 case PLPGSQL_DTYPE_VAR:
1291 case PLPGSQL_DTYPE_PROMISE:
1292 outdatum = (PLpgSQL_datum *) ws_next;
1293 memcpy(outdatum, indatum, sizeof(PLpgSQL_var));
1294 ws_next += MAXALIGN(sizeof(PLpgSQL_var));
1297 case PLPGSQL_DTYPE_REC:
1298 outdatum = (PLpgSQL_datum *) ws_next;
1299 memcpy(outdatum, indatum, sizeof(PLpgSQL_rec));
1300 ws_next += MAXALIGN(sizeof(PLpgSQL_rec));
1303 case PLPGSQL_DTYPE_ROW:
1304 case PLPGSQL_DTYPE_RECFIELD:
1305 case PLPGSQL_DTYPE_ARRAYELEM:
1308 * These datum records are read-only at runtime, so no need to
1309 * copy them (well, RECFIELD and ARRAYELEM contain cached
1310 * data, but we'd just as soon centralize the caching anyway).
1316 elog(ERROR, "unrecognized dtype: %d", indatum->dtype);
1317 outdatum = NULL; /* keep compiler quiet */
1321 outdatums[i] = outdatum;
1324 Assert(ws_next == workspace + func->copiable_size);
1328 * If the variable has an armed "promise", compute the promised value
1329 * and assign it to the variable.
1330 * The assignment automatically disarms the promise.
1333 plpgsql_fulfill_promise(PLpgSQL_execstate *estate,
1336 MemoryContext oldcontext;
1338 if (var->promise == PLPGSQL_PROMISE_NONE)
1339 return; /* nothing to do */
1342 * This will typically be invoked in a short-lived context such as the
1343 * mcontext. We must create variable values in the estate's datum
1344 * context. This quick-and-dirty solution risks leaking some additional
1345 * cruft there, but since any one promise is honored at most once per
1346 * function call, it's probably not worth being more careful.
1348 oldcontext = MemoryContextSwitchTo(estate->datum_context);
1350 switch (var->promise)
1352 case PLPGSQL_PROMISE_TG_NAME:
1353 if (estate->trigdata == NULL)
1354 elog(ERROR, "trigger promise is not in a trigger function");
1355 assign_simple_var(estate, var,
1356 DirectFunctionCall1(namein,
1357 CStringGetDatum(estate->trigdata->tg_trigger->tgname)),
1361 case PLPGSQL_PROMISE_TG_WHEN:
1362 if (estate->trigdata == NULL)
1363 elog(ERROR, "trigger promise is not in a trigger function");
1364 if (TRIGGER_FIRED_BEFORE(estate->trigdata->tg_event))
1365 assign_text_var(estate, var, "BEFORE");
1366 else if (TRIGGER_FIRED_AFTER(estate->trigdata->tg_event))
1367 assign_text_var(estate, var, "AFTER");
1368 else if (TRIGGER_FIRED_INSTEAD(estate->trigdata->tg_event))
1369 assign_text_var(estate, var, "INSTEAD OF");
1371 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
1374 case PLPGSQL_PROMISE_TG_LEVEL:
1375 if (estate->trigdata == NULL)
1376 elog(ERROR, "trigger promise is not in a trigger function");
1377 if (TRIGGER_FIRED_FOR_ROW(estate->trigdata->tg_event))
1378 assign_text_var(estate, var, "ROW");
1379 else if (TRIGGER_FIRED_FOR_STATEMENT(estate->trigdata->tg_event))
1380 assign_text_var(estate, var, "STATEMENT");
1382 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
1385 case PLPGSQL_PROMISE_TG_OP:
1386 if (estate->trigdata == NULL)
1387 elog(ERROR, "trigger promise is not in a trigger function");
1388 if (TRIGGER_FIRED_BY_INSERT(estate->trigdata->tg_event))
1389 assign_text_var(estate, var, "INSERT");
1390 else if (TRIGGER_FIRED_BY_UPDATE(estate->trigdata->tg_event))
1391 assign_text_var(estate, var, "UPDATE");
1392 else if (TRIGGER_FIRED_BY_DELETE(estate->trigdata->tg_event))
1393 assign_text_var(estate, var, "DELETE");
1394 else if (TRIGGER_FIRED_BY_TRUNCATE(estate->trigdata->tg_event))
1395 assign_text_var(estate, var, "TRUNCATE");
1397 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
1400 case PLPGSQL_PROMISE_TG_RELID:
1401 if (estate->trigdata == NULL)
1402 elog(ERROR, "trigger promise is not in a trigger function");
1403 assign_simple_var(estate, var,
1404 ObjectIdGetDatum(estate->trigdata->tg_relation->rd_id),
1408 case PLPGSQL_PROMISE_TG_TABLE_NAME:
1409 if (estate->trigdata == NULL)
1410 elog(ERROR, "trigger promise is not in a trigger function");
1411 assign_simple_var(estate, var,
1412 DirectFunctionCall1(namein,
1413 CStringGetDatum(RelationGetRelationName(estate->trigdata->tg_relation))),
1417 case PLPGSQL_PROMISE_TG_TABLE_SCHEMA:
1418 if (estate->trigdata == NULL)
1419 elog(ERROR, "trigger promise is not in a trigger function");
1420 assign_simple_var(estate, var,
1421 DirectFunctionCall1(namein,
1422 CStringGetDatum(get_namespace_name(RelationGetNamespace(estate->trigdata->tg_relation)))),
1426 case PLPGSQL_PROMISE_TG_NARGS:
1427 if (estate->trigdata == NULL)
1428 elog(ERROR, "trigger promise is not in a trigger function");
1429 assign_simple_var(estate, var,
1430 Int16GetDatum(estate->trigdata->tg_trigger->tgnargs),
1434 case PLPGSQL_PROMISE_TG_ARGV:
1435 if (estate->trigdata == NULL)
1436 elog(ERROR, "trigger promise is not in a trigger function");
1437 if (estate->trigdata->tg_trigger->tgnargs > 0)
1440 * For historical reasons, tg_argv[] subscripts start at zero
1441 * not one. So we can't use construct_array().
1443 int nelems = estate->trigdata->tg_trigger->tgnargs;
1449 elems = palloc(sizeof(Datum) * nelems);
1450 for (i = 0; i < nelems; i++)
1451 elems[i] = CStringGetTextDatum(estate->trigdata->tg_trigger->tgargs[i]);
1455 assign_simple_var(estate, var,
1456 PointerGetDatum(construct_md_array(elems, NULL,
1464 assign_simple_var(estate, var, (Datum) 0, true, false);
1468 case PLPGSQL_PROMISE_TG_EVENT:
1469 if (estate->evtrigdata == NULL)
1470 elog(ERROR, "event trigger promise is not in an event trigger function");
1471 assign_text_var(estate, var, estate->evtrigdata->event);
1474 case PLPGSQL_PROMISE_TG_TAG:
1475 if (estate->evtrigdata == NULL)
1476 elog(ERROR, "event trigger promise is not in an event trigger function");
1477 assign_text_var(estate, var, estate->evtrigdata->tag);
1481 elog(ERROR, "unrecognized promise type: %d", var->promise);
1484 MemoryContextSwitchTo(oldcontext);
1488 * Create a memory context for statement-lifespan variables, if we don't
1489 * have one already. It will be a child of stmt_mcontext_parent, which is
1490 * either the function's main context or a pushed-down outer stmt_mcontext.
1492 static MemoryContext
1493 get_stmt_mcontext(PLpgSQL_execstate *estate)
1495 if (estate->stmt_mcontext == NULL)
1497 estate->stmt_mcontext =
1498 AllocSetContextCreate(estate->stmt_mcontext_parent,
1499 "PLpgSQL per-statement data",
1500 ALLOCSET_DEFAULT_SIZES);
1502 return estate->stmt_mcontext;
1506 * Push down the current stmt_mcontext so that called statements won't use it.
1507 * This is needed by statements that have statement-lifespan data and need to
1508 * preserve it across some inner statements. The caller should eventually do
1509 * pop_stmt_mcontext().
1512 push_stmt_mcontext(PLpgSQL_execstate *estate)
1514 /* Should have done get_stmt_mcontext() first */
1515 Assert(estate->stmt_mcontext != NULL);
1516 /* Assert we've not messed up the stack linkage */
1517 Assert(MemoryContextGetParent(estate->stmt_mcontext) == estate->stmt_mcontext_parent);
1518 /* Push it down to become the parent of any nested stmt mcontext */
1519 estate->stmt_mcontext_parent = estate->stmt_mcontext;
1520 /* And make it not available for use directly */
1521 estate->stmt_mcontext = NULL;
1525 * Undo push_stmt_mcontext(). We assume this is done just before or after
1526 * resetting the caller's stmt_mcontext; since that action will also delete
1527 * any child contexts, there's no need to explicitly delete whatever context
1528 * might currently be estate->stmt_mcontext.
1531 pop_stmt_mcontext(PLpgSQL_execstate *estate)
1533 /* We need only pop the stack */
1534 estate->stmt_mcontext = estate->stmt_mcontext_parent;
1535 estate->stmt_mcontext_parent = MemoryContextGetParent(estate->stmt_mcontext);
1540 * Subroutine for exec_stmt_block: does any condition in the condition list
1541 * match the current exception?
1544 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
1546 for (; cond != NULL; cond = cond->next)
1548 int sqlerrstate = cond->sqlerrstate;
1551 * OTHERS matches everything *except* query-canceled and
1552 * assert-failure. If you're foolish enough, you can match those
1555 if (sqlerrstate == 0)
1557 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED &&
1558 edata->sqlerrcode != ERRCODE_ASSERT_FAILURE)
1562 else if (edata->sqlerrcode == sqlerrstate)
1564 /* Category match? */
1565 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1566 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1574 * exec_stmt_block Execute a block of statements
1578 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
1580 volatile int rc = -1;
1584 * First initialize all variables declared in this block
1586 estate->err_text = gettext_noop("during statement block local variable initialization");
1588 for (i = 0; i < block->n_initvars; i++)
1590 int n = block->initvarnos[i];
1591 PLpgSQL_datum *datum = estate->datums[n];
1594 * The set of dtypes handled here must match plpgsql_add_initdatums().
1596 * Note that we currently don't support promise datums within blocks,
1597 * only at a function's outermost scope, so we needn't handle those
1600 switch (datum->dtype)
1602 case PLPGSQL_DTYPE_VAR:
1604 PLpgSQL_var *var = (PLpgSQL_var *) datum;
1607 * Free any old value, in case re-entering block, and
1608 * initialize to NULL
1610 assign_simple_var(estate, var, (Datum) 0, true, false);
1612 if (var->default_val == NULL)
1615 * If needed, give the datatype a chance to reject
1616 * NULLs, by assigning a NULL to the variable. We
1617 * claim the value is of type UNKNOWN, not the var's
1618 * datatype, else coercion will be skipped.
1620 if (var->datatype->typtype == TYPTYPE_DOMAIN)
1621 exec_assign_value(estate,
1622 (PLpgSQL_datum *) var,
1628 /* parser should have rejected NOT NULL */
1629 Assert(!var->notnull);
1633 exec_assign_expr(estate, (PLpgSQL_datum *) var,
1639 case PLPGSQL_DTYPE_REC:
1641 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
1644 * Deletion of any existing object will be handled during
1645 * the assignments below, and in some cases it's more
1646 * efficient for us not to get rid of it beforehand.
1648 if (rec->default_val == NULL)
1651 * If needed, give the datatype a chance to reject
1652 * NULLs, by assigning a NULL to the variable.
1654 exec_move_row(estate, (PLpgSQL_variable *) rec,
1657 /* parser should have rejected NOT NULL */
1658 Assert(!rec->notnull);
1662 exec_assign_expr(estate, (PLpgSQL_datum *) rec,
1669 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1673 if (block->exceptions)
1676 * Execute the statements in the block's body inside a sub-transaction
1678 MemoryContext oldcontext = CurrentMemoryContext;
1679 ResourceOwner oldowner = CurrentResourceOwner;
1680 ExprContext *old_eval_econtext = estate->eval_econtext;
1681 ErrorData *save_cur_error = estate->cur_error;
1682 MemoryContext stmt_mcontext;
1684 estate->err_text = gettext_noop("during statement block entry");
1687 * We will need a stmt_mcontext to hold the error data if an error
1688 * occurs. It seems best to force it to exist before entering the
1689 * subtransaction, so that we reduce the risk of out-of-memory during
1690 * error recovery, and because this greatly simplifies restoring the
1691 * stmt_mcontext stack to the correct state after an error. We can
1692 * ameliorate the cost of this by allowing the called statements to
1693 * use this mcontext too; so we don't push it down here.
1695 stmt_mcontext = get_stmt_mcontext(estate);
1697 BeginInternalSubTransaction(NULL);
1698 /* Want to run statements inside function's memory context */
1699 MemoryContextSwitchTo(oldcontext);
1704 * We need to run the block's statements with a new eval_econtext
1705 * that belongs to the current subtransaction; if we try to use
1706 * the outer econtext then ExprContext shutdown callbacks will be
1707 * called at the wrong times.
1709 plpgsql_create_econtext(estate);
1711 estate->err_text = NULL;
1713 /* Run the block's statements */
1714 rc = exec_stmts(estate, block->body);
1716 estate->err_text = gettext_noop("during statement block exit");
1719 * If the block ended with RETURN, we may need to copy the return
1720 * value out of the subtransaction eval_context. We can avoid a
1721 * physical copy if the value happens to be a R/W expanded object.
1723 if (rc == PLPGSQL_RC_RETURN &&
1724 !estate->retisset &&
1730 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1731 estate->retval = datumTransfer(estate->retval,
1732 resTypByVal, resTypLen);
1735 /* Commit the inner transaction, return to outer xact context */
1736 ReleaseCurrentSubTransaction();
1737 MemoryContextSwitchTo(oldcontext);
1738 CurrentResourceOwner = oldowner;
1740 /* Assert that the stmt_mcontext stack is unchanged */
1741 Assert(stmt_mcontext == estate->stmt_mcontext);
1744 * Revert to outer eval_econtext. (The inner one was
1745 * automatically cleaned up during subxact exit.)
1747 estate->eval_econtext = old_eval_econtext;
1754 estate->err_text = gettext_noop("during exception cleanup");
1756 /* Save error info in our stmt_mcontext */
1757 MemoryContextSwitchTo(stmt_mcontext);
1758 edata = CopyErrorData();
1761 /* Abort the inner transaction */
1762 RollbackAndReleaseCurrentSubTransaction();
1763 MemoryContextSwitchTo(oldcontext);
1764 CurrentResourceOwner = oldowner;
1767 * Set up the stmt_mcontext stack as though we had restored our
1768 * previous state and then done push_stmt_mcontext(). The push is
1769 * needed so that statements in the exception handler won't
1770 * clobber the error data that's in our stmt_mcontext.
1772 estate->stmt_mcontext_parent = stmt_mcontext;
1773 estate->stmt_mcontext = NULL;
1776 * Now we can delete any nested stmt_mcontexts that might have
1777 * been created as children of ours. (Note: we do not immediately
1778 * release any statement-lifespan data that might have been left
1779 * behind in stmt_mcontext itself. We could attempt that by doing
1780 * a MemoryContextReset on it before collecting the error data
1781 * above, but it seems too risky to do any significant amount of
1782 * work before collecting the error.)
1784 MemoryContextDeleteChildren(stmt_mcontext);
1786 /* Revert to outer eval_econtext */
1787 estate->eval_econtext = old_eval_econtext;
1790 * Must clean up the econtext too. However, any tuple table made
1791 * in the subxact will have been thrown away by SPI during subxact
1792 * abort, so we don't need to (and mustn't try to) free the
1795 estate->eval_tuptable = NULL;
1796 exec_eval_cleanup(estate);
1798 /* Look for a matching exception handler */
1799 foreach(e, block->exceptions->exc_list)
1801 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1803 if (exception_matches_conditions(edata, exception->conditions))
1806 * Initialize the magic SQLSTATE and SQLERRM variables for
1807 * the exception block; this also frees values from any
1808 * prior use of the same exception. We needn't do this
1809 * until we have found a matching exception.
1811 PLpgSQL_var *state_var;
1812 PLpgSQL_var *errm_var;
1814 state_var = (PLpgSQL_var *)
1815 estate->datums[block->exceptions->sqlstate_varno];
1816 errm_var = (PLpgSQL_var *)
1817 estate->datums[block->exceptions->sqlerrm_varno];
1819 assign_text_var(estate, state_var,
1820 unpack_sql_state(edata->sqlerrcode));
1821 assign_text_var(estate, errm_var, edata->message);
1824 * Also set up cur_error so the error data is accessible
1825 * inside the handler.
1827 estate->cur_error = edata;
1829 estate->err_text = NULL;
1831 rc = exec_stmts(estate, exception->action);
1838 * Restore previous state of cur_error, whether or not we executed
1839 * a handler. This is needed in case an error got thrown from
1840 * some inner block's exception handler.
1842 estate->cur_error = save_cur_error;
1844 /* If no match found, re-throw the error */
1846 ReThrowError(edata);
1848 /* Restore stmt_mcontext stack and release the error data */
1849 pop_stmt_mcontext(estate);
1850 MemoryContextReset(stmt_mcontext);
1854 Assert(save_cur_error == estate->cur_error);
1859 * Just execute the statements in the block's body
1861 estate->err_text = NULL;
1863 rc = exec_stmts(estate, block->body);
1866 estate->err_text = NULL;
1869 * Handle the return code. This is intentionally different from
1870 * LOOP_RC_PROCESSING(): CONTINUE never matches a block, and EXIT matches
1871 * a block only if there is a label match.
1876 case PLPGSQL_RC_RETURN:
1877 case PLPGSQL_RC_CONTINUE:
1880 case PLPGSQL_RC_EXIT:
1881 if (estate->exitlabel == NULL)
1882 return PLPGSQL_RC_EXIT;
1883 if (block->label == NULL)
1884 return PLPGSQL_RC_EXIT;
1885 if (strcmp(block->label, estate->exitlabel) != 0)
1886 return PLPGSQL_RC_EXIT;
1887 estate->exitlabel = NULL;
1888 return PLPGSQL_RC_OK;
1891 elog(ERROR, "unrecognized rc: %d", rc);
1894 return PLPGSQL_RC_OK;
1899 * exec_stmts Iterate over a list of statements
1900 * as long as their return code is OK
1904 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1911 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1912 * statement. This prevents hangup in a tight loop if, for instance,
1913 * there is a LOOP construct with an empty body.
1915 CHECK_FOR_INTERRUPTS();
1916 return PLPGSQL_RC_OK;
1921 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1922 int rc = exec_stmt(estate, stmt);
1924 if (rc != PLPGSQL_RC_OK)
1928 return PLPGSQL_RC_OK;
1933 * exec_stmt Distribute one statement to the statements
1934 * type specific execution function.
1938 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1940 PLpgSQL_stmt *save_estmt;
1943 save_estmt = estate->err_stmt;
1944 estate->err_stmt = stmt;
1946 /* Let the plugin know that we are about to execute this statement */
1947 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_beg)
1948 ((*plpgsql_plugin_ptr)->stmt_beg) (estate, stmt);
1950 CHECK_FOR_INTERRUPTS();
1952 switch (stmt->cmd_type)
1954 case PLPGSQL_STMT_BLOCK:
1955 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1958 case PLPGSQL_STMT_ASSIGN:
1959 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1962 case PLPGSQL_STMT_PERFORM:
1963 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1966 case PLPGSQL_STMT_CALL:
1967 rc = exec_stmt_call(estate, (PLpgSQL_stmt_call *) stmt);
1970 case PLPGSQL_STMT_GETDIAG:
1971 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1974 case PLPGSQL_STMT_IF:
1975 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1978 case PLPGSQL_STMT_CASE:
1979 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1982 case PLPGSQL_STMT_LOOP:
1983 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1986 case PLPGSQL_STMT_WHILE:
1987 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1990 case PLPGSQL_STMT_FORI:
1991 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1994 case PLPGSQL_STMT_FORS:
1995 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1998 case PLPGSQL_STMT_FORC:
1999 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
2002 case PLPGSQL_STMT_FOREACH_A:
2003 rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
2006 case PLPGSQL_STMT_EXIT:
2007 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
2010 case PLPGSQL_STMT_RETURN:
2011 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
2014 case PLPGSQL_STMT_RETURN_NEXT:
2015 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
2018 case PLPGSQL_STMT_RETURN_QUERY:
2019 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
2022 case PLPGSQL_STMT_RAISE:
2023 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
2026 case PLPGSQL_STMT_ASSERT:
2027 rc = exec_stmt_assert(estate, (PLpgSQL_stmt_assert *) stmt);
2030 case PLPGSQL_STMT_EXECSQL:
2031 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
2034 case PLPGSQL_STMT_DYNEXECUTE:
2035 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
2038 case PLPGSQL_STMT_DYNFORS:
2039 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
2042 case PLPGSQL_STMT_OPEN:
2043 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
2046 case PLPGSQL_STMT_FETCH:
2047 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
2050 case PLPGSQL_STMT_CLOSE:
2051 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
2054 case PLPGSQL_STMT_COMMIT:
2055 rc = exec_stmt_commit(estate, (PLpgSQL_stmt_commit *) stmt);
2058 case PLPGSQL_STMT_ROLLBACK:
2059 rc = exec_stmt_rollback(estate, (PLpgSQL_stmt_rollback *) stmt);
2062 case PLPGSQL_STMT_SET:
2063 rc = exec_stmt_set(estate, (PLpgSQL_stmt_set *) stmt);
2067 estate->err_stmt = save_estmt;
2068 elog(ERROR, "unrecognized cmd_type: %d", stmt->cmd_type);
2071 /* Let the plugin know that we have finished executing this statement */
2072 if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_end)
2073 ((*plpgsql_plugin_ptr)->stmt_end) (estate, stmt);
2075 estate->err_stmt = save_estmt;
2082 * exec_stmt_assign Evaluate an expression and
2083 * put the result into a variable.
2087 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
2089 Assert(stmt->varno >= 0);
2091 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
2093 return PLPGSQL_RC_OK;
2097 * exec_stmt_perform Evaluate query and discard result (but set
2098 * FOUND depending on whether at least one row
2103 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
2105 PLpgSQL_expr *expr = stmt->expr;
2107 (void) exec_run_select(estate, expr, 0, NULL);
2108 exec_set_found(estate, (estate->eval_processed != 0));
2109 exec_eval_cleanup(estate);
2111 return PLPGSQL_RC_OK;
2118 exec_stmt_call(PLpgSQL_execstate *estate, PLpgSQL_stmt_call *stmt)
2120 PLpgSQL_expr *expr = stmt->expr;
2121 volatile LocalTransactionId before_lxid;
2122 LocalTransactionId after_lxid;
2123 volatile bool pushed_active_snap = false;
2126 /* PG_TRY to ensure we clear the plan link, if needed, on failure */
2129 SPIPlanPtr plan = expr->plan;
2130 ParamListInfo paramLI;
2136 * Don't save the plan if not in atomic context. Otherwise,
2137 * transaction ends would cause errors about plancache leaks.
2139 * XXX This would be fixable with some plancache/resowner surgery
2140 * elsewhere, but for now we'll just work around this here.
2142 exec_prepare_plan(estate, expr, 0, estate->atomic);
2145 * The procedure call could end transactions, which would upset
2146 * the snapshot management in SPI_execute*, so don't let it do it.
2147 * Instead, we set the snapshots ourselves below.
2150 plan->no_snapshots = true;
2153 * Force target to be recalculated whenever the plan changes, in
2154 * case the procedure's argument list has changed.
2156 stmt->target = NULL;
2160 * We construct a DTYPE_ROW datum representing the plpgsql variables
2161 * associated with the procedure's output arguments. Then we can use
2162 * exec_move_row() to do the assignments.
2164 if (stmt->is_call && stmt->target == NULL)
2168 HeapTuple func_tuple;
2173 MemoryContext oldcontext;
2180 * Get the parsed CallStmt, and look up the called procedure
2182 node = linitial_node(Query,
2183 ((CachedPlanSource *) linitial(plan->plancache_list))->query_list)->utilityStmt;
2184 if (node == NULL || !IsA(node, CallStmt))
2185 elog(ERROR, "query for CALL statement is not a CallStmt");
2187 funcexpr = ((CallStmt *) node)->funcexpr;
2189 func_tuple = SearchSysCache1(PROCOID,
2190 ObjectIdGetDatum(funcexpr->funcid));
2191 if (!HeapTupleIsValid(func_tuple))
2192 elog(ERROR, "cache lookup failed for function %u",
2196 * Extract function arguments, and expand any named-arg notation
2198 funcargs = expand_function_arguments(funcexpr->args,
2199 funcexpr->funcresulttype,
2203 * Get the argument names and modes, too
2205 get_func_arg_info(func_tuple, &argtypes, &argnames, &argmodes);
2207 ReleaseSysCache(func_tuple);
2210 * Begin constructing row Datum
2212 oldcontext = MemoryContextSwitchTo(estate->func->fn_cxt);
2214 row = (PLpgSQL_row *) palloc0(sizeof(PLpgSQL_row));
2215 row->dtype = PLPGSQL_DTYPE_ROW;
2216 row->refname = "(unnamed row)";
2218 row->varnos = (int *) palloc(sizeof(int) * list_length(funcargs));
2220 MemoryContextSwitchTo(oldcontext);
2223 * Examine procedure's argument list. Each output arg position
2224 * should be an unadorned plpgsql variable (Datum), which we can
2225 * insert into the row Datum.
2229 foreach(lc, funcargs)
2231 Node *n = lfirst(lc);
2234 (argmodes[i] == PROARGMODE_INOUT ||
2235 argmodes[i] == PROARGMODE_OUT))
2239 Param *param = (Param *) n;
2241 /* paramid is offset by 1 (see make_datum_param()) */
2242 row->varnos[nfields++] = param->paramid - 1;
2246 /* report error using parameter name, if available */
2247 if (argnames && argnames[i] && argnames[i][0])
2249 (errcode(ERRCODE_SYNTAX_ERROR),
2250 errmsg("procedure parameter \"%s\" is an output parameter but corresponding argument is not writable",
2254 (errcode(ERRCODE_SYNTAX_ERROR),
2255 errmsg("procedure parameter %d is an output parameter but corresponding argument is not writable",
2262 row->nfields = nfields;
2264 stmt->target = (PLpgSQL_variable *) row;
2267 paramLI = setup_param_list(estate, expr);
2269 before_lxid = MyProc->lxid;
2272 * Set snapshot only for non-read-only procedures, similar to SPI
2275 if (!estate->readonly_func)
2277 PushActiveSnapshot(GetTransactionSnapshot());
2278 pushed_active_snap = true;
2281 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
2282 estate->readonly_func, 0);
2287 * If we aren't saving the plan, unset the pointer. Note that it
2288 * could have been unset already, in case of a recursive call.
2290 if (expr->plan && !expr->plan->saved)
2296 if (expr->plan && !expr->plan->saved)
2300 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
2301 expr->query, SPI_result_code_string(rc));
2303 after_lxid = MyProc->lxid;
2305 if (before_lxid == after_lxid)
2308 * If we are still in the same transaction after the call, pop the
2309 * snapshot that we might have pushed. (If it's a new transaction,
2310 * then all the snapshots are gone already.)
2312 if (pushed_active_snap)
2313 PopActiveSnapshot();
2318 * If we are in a new transaction after the call, we need to reset
2319 * some internal state.
2321 estate->simple_eval_estate = NULL;
2322 plpgsql_create_econtext(estate);
2326 * Check result rowcount; if there's one row, assign procedure's output
2327 * values back to the appropriate variables.
2329 if (SPI_processed == 1)
2331 SPITupleTable *tuptab = SPI_tuptable;
2334 elog(ERROR, "DO statement returned a row");
2336 exec_move_row(estate, stmt->target, tuptab->vals[0], tuptab->tupdesc);
2338 else if (SPI_processed > 1)
2339 elog(ERROR, "procedure call returned more than one row");
2341 exec_eval_cleanup(estate);
2342 SPI_freetuptable(SPI_tuptable);
2344 return PLPGSQL_RC_OK;
2348 * exec_stmt_getdiag Put internal PG information into
2349 * specified variables.
2353 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
2358 * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
2360 * Note: we trust the grammar to have disallowed the relevant item kinds
2361 * if not is_stacked, otherwise we'd dump core below.
2363 if (stmt->is_stacked && estate->cur_error == NULL)
2365 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2366 errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
2368 foreach(lc, stmt->diag_items)
2370 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
2371 PLpgSQL_datum *var = estate->datums[diag_item->target];
2373 switch (diag_item->kind)
2375 case PLPGSQL_GETDIAG_ROW_COUNT:
2376 exec_assign_value(estate, var,
2377 UInt64GetDatum(estate->eval_processed),
2378 false, INT8OID, -1);
2381 case PLPGSQL_GETDIAG_ERROR_CONTEXT:
2382 exec_assign_c_string(estate, var,
2383 estate->cur_error->context);
2386 case PLPGSQL_GETDIAG_ERROR_DETAIL:
2387 exec_assign_c_string(estate, var,
2388 estate->cur_error->detail);
2391 case PLPGSQL_GETDIAG_ERROR_HINT:
2392 exec_assign_c_string(estate, var,
2393 estate->cur_error->hint);
2396 case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
2397 exec_assign_c_string(estate, var,
2398 unpack_sql_state(estate->cur_error->sqlerrcode));
2401 case PLPGSQL_GETDIAG_COLUMN_NAME:
2402 exec_assign_c_string(estate, var,
2403 estate->cur_error->column_name);
2406 case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
2407 exec_assign_c_string(estate, var,
2408 estate->cur_error->constraint_name);
2411 case PLPGSQL_GETDIAG_DATATYPE_NAME:
2412 exec_assign_c_string(estate, var,
2413 estate->cur_error->datatype_name);
2416 case PLPGSQL_GETDIAG_MESSAGE_TEXT:
2417 exec_assign_c_string(estate, var,
2418 estate->cur_error->message);
2421 case PLPGSQL_GETDIAG_TABLE_NAME:
2422 exec_assign_c_string(estate, var,
2423 estate->cur_error->table_name);
2426 case PLPGSQL_GETDIAG_SCHEMA_NAME:
2427 exec_assign_c_string(estate, var,
2428 estate->cur_error->schema_name);
2431 case PLPGSQL_GETDIAG_CONTEXT:
2433 char *contextstackstr;
2434 MemoryContext oldcontext;
2436 /* Use eval_mcontext for short-lived string */
2437 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
2438 contextstackstr = GetErrorContextStack();
2439 MemoryContextSwitchTo(oldcontext);
2441 exec_assign_c_string(estate, var, contextstackstr);
2446 elog(ERROR, "unrecognized diagnostic item kind: %d",
2451 exec_eval_cleanup(estate);
2453 return PLPGSQL_RC_OK;
2457 * exec_stmt_if Evaluate a bool expression and
2458 * execute the true or false body
2463 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
2469 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2470 exec_eval_cleanup(estate);
2471 if (!isnull && value)
2472 return exec_stmts(estate, stmt->then_body);
2474 foreach(lc, stmt->elsif_list)
2476 PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
2478 value = exec_eval_boolean(estate, elif->cond, &isnull);
2479 exec_eval_cleanup(estate);
2480 if (!isnull && value)
2481 return exec_stmts(estate, elif->stmts);
2484 return exec_stmts(estate, stmt->else_body);
2493 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
2495 PLpgSQL_var *t_var = NULL;
2499 if (stmt->t_expr != NULL)
2506 t_val = exec_eval_expr(estate, stmt->t_expr,
2507 &isnull, &t_typoid, &t_typmod);
2509 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
2512 * When expected datatype is different from real, change it. Note that
2513 * what we're modifying here is an execution copy of the datum, so
2514 * this doesn't affect the originally stored function parse tree. (In
2515 * theory, if the expression datatype keeps changing during execution,
2516 * this could cause a function-lifespan memory leak. Doesn't seem
2517 * worth worrying about though.)
2519 if (t_var->datatype->typoid != t_typoid ||
2520 t_var->datatype->atttypmod != t_typmod)
2521 t_var->datatype = plpgsql_build_datatype(t_typoid,
2523 estate->func->fn_input_collation,
2526 /* now we can assign to the variable */
2527 exec_assign_value(estate,
2528 (PLpgSQL_datum *) t_var,
2534 exec_eval_cleanup(estate);
2537 /* Now search for a successful WHEN clause */
2538 foreach(l, stmt->case_when_list)
2540 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
2543 value = exec_eval_boolean(estate, cwt->expr, &isnull);
2544 exec_eval_cleanup(estate);
2545 if (!isnull && value)
2549 /* We can now discard any value we had for the temp variable */
2551 assign_simple_var(estate, t_var, (Datum) 0, true, false);
2553 /* Evaluate the statement(s), and we're done */
2554 return exec_stmts(estate, cwt->stmts);
2558 /* We can now discard any value we had for the temp variable */
2560 assign_simple_var(estate, t_var, (Datum) 0, true, false);
2562 /* SQL2003 mandates this error if there was no ELSE clause */
2563 if (!stmt->have_else)
2565 (errcode(ERRCODE_CASE_NOT_FOUND),
2566 errmsg("case not found"),
2567 errhint("CASE statement is missing ELSE part.")));
2569 /* Evaluate the ELSE statements, and we're done */
2570 return exec_stmts(estate, stmt->else_stmts);
2575 * exec_stmt_loop Loop over statements until
2580 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
2582 int rc = PLPGSQL_RC_OK;
2586 rc = exec_stmts(estate, stmt->body);
2588 LOOP_RC_PROCESSING(stmt->label, break);
2596 * exec_stmt_while Loop over statements as long
2597 * as an expression evaluates to
2598 * true or an exit occurs.
2602 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
2604 int rc = PLPGSQL_RC_OK;
2611 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2612 exec_eval_cleanup(estate);
2614 if (isnull || !value)
2617 rc = exec_stmts(estate, stmt->body);
2619 LOOP_RC_PROCESSING(stmt->label, break);
2627 * exec_stmt_fori Iterate an integer variable
2628 * from a lower to an upper value
2629 * incrementing or decrementing by the BY value
2633 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
2644 int rc = PLPGSQL_RC_OK;
2646 var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
2649 * Get the value of the lower bound
2651 value = exec_eval_expr(estate, stmt->lower,
2652 &isnull, &valtype, &valtypmod);
2653 value = exec_cast_value(estate, value, &isnull,
2655 var->datatype->typoid,
2656 var->datatype->atttypmod);
2659 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2660 errmsg("lower bound of FOR loop cannot be null")));
2661 loop_value = DatumGetInt32(value);
2662 exec_eval_cleanup(estate);
2665 * Get the value of the upper bound
2667 value = exec_eval_expr(estate, stmt->upper,
2668 &isnull, &valtype, &valtypmod);
2669 value = exec_cast_value(estate, value, &isnull,
2671 var->datatype->typoid,
2672 var->datatype->atttypmod);
2675 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2676 errmsg("upper bound of FOR loop cannot be null")));
2677 end_value = DatumGetInt32(value);
2678 exec_eval_cleanup(estate);
2681 * Get the step value
2685 value = exec_eval_expr(estate, stmt->step,
2686 &isnull, &valtype, &valtypmod);
2687 value = exec_cast_value(estate, value, &isnull,
2689 var->datatype->typoid,
2690 var->datatype->atttypmod);
2693 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2694 errmsg("BY value of FOR loop cannot be null")));
2695 step_value = DatumGetInt32(value);
2696 exec_eval_cleanup(estate);
2697 if (step_value <= 0)
2699 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2700 errmsg("BY value of FOR loop must be greater than zero")));
2711 * Check against upper bound
2715 if (loop_value < end_value)
2720 if (loop_value > end_value)
2724 found = true; /* looped at least once */
2727 * Assign current value to loop var
2729 assign_simple_var(estate, var, Int32GetDatum(loop_value), false, false);
2732 * Execute the statements
2734 rc = exec_stmts(estate, stmt->body);
2736 LOOP_RC_PROCESSING(stmt->label, break);
2739 * Increase/decrease loop value, unless it would overflow, in which
2740 * case exit the loop.
2744 if (loop_value < (PG_INT32_MIN + step_value))
2746 loop_value -= step_value;
2750 if (loop_value > (PG_INT32_MAX - step_value))
2752 loop_value += step_value;
2757 * Set the FOUND variable to indicate the result of executing the loop
2758 * (namely, whether we looped one or more times). This must be set here so
2759 * that it does not interfere with the value of the FOUND variable inside
2760 * the loop processing itself.
2762 exec_set_found(estate, found);
2769 * exec_stmt_fors Execute a query, assign each
2770 * tuple to a record or row and
2771 * execute a group of statements
2776 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
2782 * Open the implicit cursor for the statement using exec_run_select
2784 exec_run_select(estate, stmt->query, 0, &portal);
2789 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2792 * Close the implicit cursor
2794 SPI_cursor_close(portal);
2801 * exec_stmt_forc Execute a loop for each row from a cursor.
2805 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
2807 PLpgSQL_var *curvar;
2808 MemoryContext stmt_mcontext = NULL;
2809 char *curname = NULL;
2810 PLpgSQL_expr *query;
2811 ParamListInfo paramLI;
2816 * Get the cursor variable and if it has an assigned name, check
2817 * that it's not in use currently.
2820 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2821 if (!curvar->isnull)
2823 MemoryContext oldcontext;
2825 /* We only need stmt_mcontext to hold the cursor name string */
2826 stmt_mcontext = get_stmt_mcontext(estate);
2827 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
2828 curname = TextDatumGetCString(curvar->value);
2829 MemoryContextSwitchTo(oldcontext);
2831 if (SPI_cursor_find(curname) != NULL)
2833 (errcode(ERRCODE_DUPLICATE_CURSOR),
2834 errmsg("cursor \"%s\" already in use", curname)));
2838 * Open the cursor just like an OPEN command
2840 * Note: parser should already have checked that statement supplies
2841 * args iff cursor needs them, but we check again to be safe.
2844 if (stmt->argquery != NULL)
2847 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
2848 * statement to evaluate the args and put 'em into the
2852 PLpgSQL_stmt_execsql set_args;
2854 if (curvar->cursor_explicit_argrow < 0)
2856 (errcode(ERRCODE_SYNTAX_ERROR),
2857 errmsg("arguments given for cursor without arguments")));
2859 memset(&set_args, 0, sizeof(set_args));
2860 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2861 set_args.lineno = stmt->lineno;
2862 set_args.sqlstmt = stmt->argquery;
2863 set_args.into = true;
2864 /* XXX historically this has not been STRICT */
2865 set_args.target = (PLpgSQL_variable *)
2866 (estate->datums[curvar->cursor_explicit_argrow]);
2868 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2869 elog(ERROR, "open cursor failed during argument processing");
2873 if (curvar->cursor_explicit_argrow >= 0)
2875 (errcode(ERRCODE_SYNTAX_ERROR),
2876 errmsg("arguments required for cursor")));
2879 query = curvar->cursor_explicit_expr;
2882 if (query->plan == NULL)
2883 exec_prepare_plan(estate, query, curvar->cursor_options, true);
2886 * Set up ParamListInfo for this query
2888 paramLI = setup_param_list(estate, query);
2891 * Open the cursor (the paramlist will get copied into the portal)
2893 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2895 estate->readonly_func);
2897 elog(ERROR, "could not open cursor: %s",
2898 SPI_result_code_string(SPI_result));
2901 * If cursor variable was NULL, store the generated portal name in it
2903 if (curname == NULL)
2904 assign_text_var(estate, curvar, portal->name);
2907 * Clean up before entering exec_for_query
2909 exec_eval_cleanup(estate);
2911 MemoryContextReset(stmt_mcontext);
2914 * Execute the loop. We can't prefetch because the cursor is accessible
2915 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2917 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2920 * Close portal, and restore cursor variable if it was initially NULL.
2923 SPI_cursor_close(portal);
2925 if (curname == NULL)
2926 assign_simple_var(estate, curvar, (Datum) 0, true, false);
2933 * exec_stmt_foreach_a Loop over elements or slices of an array
2935 * When looping over elements, the loop variable is the same type that the
2936 * array stores (eg: integer), when looping through slices, the loop variable
2937 * is an array of size and dimensions to match the size of the slice.
2941 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2946 PLpgSQL_datum *loop_var;
2947 Oid loop_var_elem_type;
2949 int rc = PLPGSQL_RC_OK;
2950 MemoryContext stmt_mcontext;
2951 MemoryContext oldcontext;
2952 ArrayIterator array_iterator;
2953 Oid iterator_result_type;
2954 int32 iterator_result_typmod;
2958 /* get the value of the array expression */
2959 value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype, &arrtypmod);
2962 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2963 errmsg("FOREACH expression must not be null")));
2966 * Do as much as possible of the code below in stmt_mcontext, to avoid any
2967 * leaks from called subroutines. We need a private stmt_mcontext since
2968 * we'll be calling arbitrary statement code.
2970 stmt_mcontext = get_stmt_mcontext(estate);
2971 push_stmt_mcontext(estate);
2972 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
2974 /* check the type of the expression - must be an array */
2975 if (!OidIsValid(get_element_type(arrtype)))
2977 (errcode(ERRCODE_DATATYPE_MISMATCH),
2978 errmsg("FOREACH expression must yield an array, not type %s",
2979 format_type_be(arrtype))));
2982 * We must copy the array into stmt_mcontext, else it will disappear in
2983 * exec_eval_cleanup. This is annoying, but cleanup will certainly happen
2984 * while running the loop body, so we have little choice.
2986 arr = DatumGetArrayTypePCopy(value);
2988 /* Clean up any leftover temporary memory */
2989 exec_eval_cleanup(estate);
2991 /* Slice dimension must be less than or equal to array dimension */
2992 if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2994 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2995 errmsg("slice dimension (%d) is out of the valid range 0..%d",
2996 stmt->slice, ARR_NDIM(arr))));
2998 /* Set up the loop variable and see if it is of an array type */
2999 loop_var = estate->datums[stmt->varno];
3000 if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
3001 loop_var->dtype == PLPGSQL_DTYPE_ROW)
3004 * Record/row variable is certainly not of array type, and might not
3005 * be initialized at all yet, so don't try to get its type
3007 loop_var_elem_type = InvalidOid;
3010 loop_var_elem_type = get_element_type(plpgsql_exec_get_datum_type(estate,
3014 * Sanity-check the loop variable type. We don't try very hard here, and
3015 * should not be too picky since it's possible that exec_assign_value can
3016 * coerce values of different types. But it seems worthwhile to complain
3017 * if the array-ness of the loop variable is not right.
3019 if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
3021 (errcode(ERRCODE_DATATYPE_MISMATCH),
3022 errmsg("FOREACH ... SLICE loop variable must be of an array type")));
3023 if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
3025 (errcode(ERRCODE_DATATYPE_MISMATCH),
3026 errmsg("FOREACH loop variable must not be of an array type")));
3028 /* Create an iterator to step through the array */
3029 array_iterator = array_create_iterator(arr, stmt->slice, NULL);
3031 /* Identify iterator result type */
3032 if (stmt->slice > 0)
3034 /* When slicing, nominal type of result is same as array type */
3035 iterator_result_type = arrtype;
3036 iterator_result_typmod = arrtypmod;
3040 /* Without slicing, results are individual array elements */
3041 iterator_result_type = ARR_ELEMTYPE(arr);
3042 iterator_result_typmod = arrtypmod;
3045 /* Iterate over the array elements or slices */
3046 while (array_iterate(array_iterator, &value, &isnull))
3048 found = true; /* looped at least once */
3050 /* exec_assign_value and exec_stmts must run in the main context */
3051 MemoryContextSwitchTo(oldcontext);
3053 /* Assign current element/slice to the loop variable */
3054 exec_assign_value(estate, loop_var, value, isnull,
3055 iterator_result_type, iterator_result_typmod);
3057 /* In slice case, value is temporary; must free it to avoid leakage */
3058 if (stmt->slice > 0)
3059 pfree(DatumGetPointer(value));
3062 * Execute the statements
3064 rc = exec_stmts(estate, stmt->body);
3066 LOOP_RC_PROCESSING(stmt->label, break);
3068 MemoryContextSwitchTo(stmt_mcontext);
3071 /* Restore memory context state */
3072 MemoryContextSwitchTo(oldcontext);
3073 pop_stmt_mcontext(estate);
3075 /* Release temporary memory, including the array value */
3076 MemoryContextReset(stmt_mcontext);
3079 * Set the FOUND variable to indicate the result of executing the loop
3080 * (namely, whether we looped one or more times). This must be set here so
3081 * that it does not interfere with the value of the FOUND variable inside
3082 * the loop processing itself.
3084 exec_set_found(estate, found);
3091 * exec_stmt_exit Implements EXIT and CONTINUE
3093 * This begins the process of exiting / restarting a loop.
3097 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
3100 * If the exit / continue has a condition, evaluate it
3102 if (stmt->cond != NULL)
3107 value = exec_eval_boolean(estate, stmt->cond, &isnull);
3108 exec_eval_cleanup(estate);
3109 if (isnull || value == false)
3110 return PLPGSQL_RC_OK;
3113 estate->exitlabel = stmt->label;
3115 return PLPGSQL_RC_EXIT;
3117 return PLPGSQL_RC_CONTINUE;
3122 * exec_stmt_return Evaluate an expression and start
3123 * returning from the function.
3125 * Note: The result may be in the eval_mcontext. Therefore, we must not
3126 * do exec_eval_cleanup while unwinding the control stack.
3130 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
3133 * If processing a set-returning PL/pgSQL function, the final RETURN
3134 * indicates that the function is finished producing tuples. The rest of
3135 * the work will be done at the top level.
3137 if (estate->retisset)
3138 return PLPGSQL_RC_RETURN;
3140 /* initialize for null result */
3141 estate->retval = (Datum) 0;
3142 estate->retisnull = true;
3143 estate->rettype = InvalidOid;
3146 * Special case path when the RETURN expression is a simple variable
3147 * reference; in particular, this path is always taken in functions with
3148 * one or more OUT parameters.
3150 * This special case is especially efficient for returning variables that
3151 * have R/W expanded values: we can put the R/W pointer directly into
3152 * estate->retval, leading to transferring the value to the caller's
3153 * context cheaply. If we went through exec_eval_expr we'd end up with a
3154 * R/O pointer. It's okay to skip MakeExpandedObjectReadOnly here since
3155 * we know we won't need the variable's value within the function anymore.
3157 if (stmt->retvarno >= 0)
3159 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3161 switch (retvar->dtype)
3163 case PLPGSQL_DTYPE_PROMISE:
3164 /* fulfill promise if needed, then handle like regular var */
3165 plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3169 case PLPGSQL_DTYPE_VAR:
3171 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3173 estate->retval = var->value;
3174 estate->retisnull = var->isnull;
3175 estate->rettype = var->datatype->typoid;
3178 * A PLpgSQL_var could not be of composite type, so
3179 * conversion must fail if retistuple. We throw a custom
3180 * error mainly for consistency with historical behavior.
3181 * For the same reason, we don't throw error if the result
3182 * is NULL. (Note that plpgsql_exec_trigger assumes that
3183 * any non-null result has been verified to be composite.)
3185 if (estate->retistuple && !estate->retisnull)
3187 (errcode(ERRCODE_DATATYPE_MISMATCH),
3188 errmsg("cannot return non-composite value from function returning composite type")));
3192 case PLPGSQL_DTYPE_REC:
3194 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3196 /* If record is empty, we return NULL not a row of nulls */
3197 if (rec->erh && !ExpandedRecordIsEmpty(rec->erh))
3199 estate->retval = ExpandedRecordGetDatum(rec->erh);
3200 estate->retisnull = false;
3201 estate->rettype = rec->rectypeid;
3206 case PLPGSQL_DTYPE_ROW:
3208 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3211 /* We get here if there are multiple OUT parameters */
3212 exec_eval_datum(estate,
3213 (PLpgSQL_datum *) row,
3217 &estate->retisnull);
3222 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3225 return PLPGSQL_RC_RETURN;
3228 if (stmt->expr != NULL)
3232 estate->retval = exec_eval_expr(estate, stmt->expr,
3233 &(estate->retisnull),
3238 * As in the DTYPE_VAR case above, throw a custom error if a non-null,
3239 * non-composite value is returned in a function returning tuple.
3241 if (estate->retistuple && !estate->retisnull &&
3242 !type_is_rowtype(estate->rettype))
3244 (errcode(ERRCODE_DATATYPE_MISMATCH),
3245 errmsg("cannot return non-composite value from function returning composite type")));
3247 return PLPGSQL_RC_RETURN;
3251 * Special hack for function returning VOID: instead of NULL, return a
3252 * non-null VOID value. This is of dubious importance but is kept for
3253 * backwards compatibility. We don't do it for procedures, though.
3255 if (estate->fn_rettype == VOIDOID &&
3256 estate->func->fn_prokind != PROKIND_PROCEDURE)
3258 estate->retval = (Datum) 0;
3259 estate->retisnull = false;
3260 estate->rettype = VOIDOID;
3263 return PLPGSQL_RC_RETURN;
3267 * exec_stmt_return_next Evaluate an expression and add it to the
3268 * list of tuples returned by the current
3273 exec_stmt_return_next(PLpgSQL_execstate *estate,
3274 PLpgSQL_stmt_return_next *stmt)
3279 MemoryContext oldcontext;
3281 if (!estate->retisset)
3283 (errcode(ERRCODE_SYNTAX_ERROR),
3284 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
3286 if (estate->tuple_store == NULL)
3287 exec_init_tuple_store(estate);
3289 /* tuple_store_desc will be filled by exec_init_tuple_store */
3290 tupdesc = estate->tuple_store_desc;
3291 natts = tupdesc->natts;
3294 * Special case path when the RETURN NEXT expression is a simple variable
3295 * reference; in particular, this path is always taken in functions with
3296 * one or more OUT parameters.
3298 * Unlike exec_stmt_return, there's no special win here for R/W expanded
3299 * values, since they'll have to get flattened to go into the tuplestore.
3300 * Indeed, we'd better make them R/O to avoid any risk of the casting step
3301 * changing them in-place.
3303 if (stmt->retvarno >= 0)
3305 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3307 switch (retvar->dtype)
3309 case PLPGSQL_DTYPE_PROMISE:
3310 /* fulfill promise if needed, then handle like regular var */
3311 plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3315 case PLPGSQL_DTYPE_VAR:
3317 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3318 Datum retval = var->value;
3319 bool isNull = var->isnull;
3320 Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3324 (errcode(ERRCODE_DATATYPE_MISMATCH),
3325 errmsg("wrong result type supplied in RETURN NEXT")));
3327 /* let's be very paranoid about the cast step */
3328 retval = MakeExpandedObjectReadOnly(retval,
3330 var->datatype->typlen);
3332 /* coerce type if needed */
3333 retval = exec_cast_value(estate,
3336 var->datatype->typoid,
3337 var->datatype->atttypmod,
3341 tuplestore_putvalues(estate->tuple_store, tupdesc,
3346 case PLPGSQL_DTYPE_REC:
3348 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3349 TupleDesc rec_tupdesc;
3350 TupleConversionMap *tupmap;
3352 /* If rec is null, try to convert it to a row of nulls */
3353 if (rec->erh == NULL)
3354 instantiate_empty_record_variable(estate, rec);
3355 if (ExpandedRecordIsEmpty(rec->erh))
3356 deconstruct_expanded_record(rec->erh);
3358 /* Use eval_mcontext for tuple conversion work */
3359 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3360 rec_tupdesc = expanded_record_get_tupdesc(rec->erh);
3361 tupmap = convert_tuples_by_position(rec_tupdesc,
3363 gettext_noop("wrong record type supplied in RETURN NEXT"));
3364 tuple = expanded_record_get_tuple(rec->erh);
3366 tuple = execute_attr_map_tuple(tuple, tupmap);
3367 tuplestore_puttuple(estate->tuple_store, tuple);
3368 MemoryContextSwitchTo(oldcontext);
3372 case PLPGSQL_DTYPE_ROW:
3374 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3376 /* We get here if there are multiple OUT parameters */
3378 /* Use eval_mcontext for tuple conversion work */
3379 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3380 tuple = make_tuple_from_row(estate, row, tupdesc);
3381 if (tuple == NULL) /* should not happen */
3383 (errcode(ERRCODE_DATATYPE_MISMATCH),
3384 errmsg("wrong record type supplied in RETURN NEXT")));
3385 tuplestore_puttuple(estate->tuple_store, tuple);
3386 MemoryContextSwitchTo(oldcontext);
3391 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3395 else if (stmt->expr)
3402 retval = exec_eval_expr(estate,
3408 if (estate->retistuple)
3410 /* Expression should be of RECORD or composite type */
3413 HeapTupleData tmptup;
3414 TupleDesc retvaldesc;
3415 TupleConversionMap *tupmap;
3417 if (!type_is_rowtype(rettype))
3419 (errcode(ERRCODE_DATATYPE_MISMATCH),
3420 errmsg("cannot return non-composite value from function returning composite type")));
3422 /* Use eval_mcontext for tuple conversion work */
3423 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3424 retvaldesc = deconstruct_composite_datum(retval, &tmptup);
3426 tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
3427 gettext_noop("returned record type does not match expected record type"));
3429 tuple = execute_attr_map_tuple(tuple, tupmap);
3430 tuplestore_puttuple(estate->tuple_store, tuple);
3431 ReleaseTupleDesc(retvaldesc);
3432 MemoryContextSwitchTo(oldcontext);
3436 /* Composite NULL --- store a row of nulls */
3440 nulldatums = (Datum *)
3441 eval_mcontext_alloc0(estate, natts * sizeof(Datum));
3442 nullflags = (bool *)
3443 eval_mcontext_alloc(estate, natts * sizeof(bool));
3444 memset(nullflags, true, natts * sizeof(bool));
3445 tuplestore_putvalues(estate->tuple_store, tupdesc,
3446 nulldatums, nullflags);
3451 Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3453 /* Simple scalar result */
3456 (errcode(ERRCODE_DATATYPE_MISMATCH),
3457 errmsg("wrong result type supplied in RETURN NEXT")));
3459 /* coerce type if needed */
3460 retval = exec_cast_value(estate,
3468 tuplestore_putvalues(estate->tuple_store, tupdesc,
3475 (errcode(ERRCODE_SYNTAX_ERROR),
3476 errmsg("RETURN NEXT must have a parameter")));
3479 exec_eval_cleanup(estate);
3481 return PLPGSQL_RC_OK;
3485 * exec_stmt_return_query Evaluate a query and add it to the
3486 * list of tuples returned by the current
3491 exec_stmt_return_query(PLpgSQL_execstate *estate,
3492 PLpgSQL_stmt_return_query *stmt)
3495 uint64 processed = 0;
3496 TupleConversionMap *tupmap;
3497 MemoryContext oldcontext;
3499 if (!estate->retisset)
3501 (errcode(ERRCODE_SYNTAX_ERROR),
3502 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
3504 if (estate->tuple_store == NULL)
3505 exec_init_tuple_store(estate);
3507 if (stmt->query != NULL)
3510 exec_run_select(estate, stmt->query, 0, &portal);
3514 /* RETURN QUERY EXECUTE */
3515 Assert(stmt->dynquery != NULL);
3516 portal = exec_dynquery_with_params(estate, stmt->dynquery,
3521 /* Use eval_mcontext for tuple conversion work */
3522 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3524 tupmap = convert_tuples_by_position(portal->tupDesc,
3525 estate->tuple_store_desc,
3526 gettext_noop("structure of query does not match function result type"));
3532 SPI_cursor_fetch(portal, true, 50);
3534 /* SPI will have changed CurrentMemoryContext */
3535 MemoryContextSwitchTo(get_eval_mcontext(estate));
3537 if (SPI_processed == 0)
3540 for (i = 0; i < SPI_processed; i++)
3542 HeapTuple tuple = SPI_tuptable->vals[i];
3545 tuple = execute_attr_map_tuple(tuple, tupmap);
3546 tuplestore_puttuple(estate->tuple_store, tuple);
3548 heap_freetuple(tuple);
3552 SPI_freetuptable(SPI_tuptable);
3555 SPI_freetuptable(SPI_tuptable);
3556 SPI_cursor_close(portal);
3558 MemoryContextSwitchTo(oldcontext);
3559 exec_eval_cleanup(estate);
3561 estate->eval_processed = processed;
3562 exec_set_found(estate, processed != 0);
3564 return PLPGSQL_RC_OK;
3568 exec_init_tuple_store(PLpgSQL_execstate *estate)
3570 ReturnSetInfo *rsi = estate->rsi;
3571 MemoryContext oldcxt;
3572 ResourceOwner oldowner;
3575 * Check caller can handle a set result in the way we want
3577 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
3578 (rsi->allowedModes & SFRM_Materialize) == 0 ||
3579 rsi->expectedDesc == NULL)
3581 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3582 errmsg("set-valued function called in context that cannot accept a set")));
3585 * Switch to the right memory context and resource owner for storing the
3586 * tuplestore for return set. If we're within a subtransaction opened for
3587 * an exception-block, for example, we must still create the tuplestore in
3588 * the resource owner that was active when this function was entered, and
3589 * not in the subtransaction resource owner.
3591 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
3592 oldowner = CurrentResourceOwner;
3593 CurrentResourceOwner = estate->tuple_store_owner;
3595 estate->tuple_store =
3596 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
3599 CurrentResourceOwner = oldowner;
3600 MemoryContextSwitchTo(oldcxt);
3602 estate->tuple_store_desc = rsi->expectedDesc;
3605 #define SET_RAISE_OPTION_TEXT(opt, name) \
3609 (errcode(ERRCODE_SYNTAX_ERROR), \
3610 errmsg("RAISE option already specified: %s", \
3612 opt = MemoryContextStrdup(stmt_mcontext, extval); \
3616 * exec_stmt_raise Build a message and throw it with elog()
3620 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
3623 char *condname = NULL;
3624 char *err_message = NULL;
3625 char *err_detail = NULL;
3626 char *err_hint = NULL;
3627 char *err_column = NULL;
3628 char *err_constraint = NULL;
3629 char *err_datatype = NULL;
3630 char *err_table = NULL;
3631 char *err_schema = NULL;
3632 MemoryContext stmt_mcontext;
3635 /* RAISE with no parameters: re-throw current exception */
3636 if (stmt->condname == NULL && stmt->message == NULL &&
3637 stmt->options == NIL)
3639 if (estate->cur_error != NULL)
3640 ReThrowError(estate->cur_error);
3641 /* oops, we're not inside a handler */
3643 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
3644 errmsg("RAISE without parameters cannot be used outside an exception handler")));
3647 /* We'll need to accumulate the various strings in stmt_mcontext */
3648 stmt_mcontext = get_stmt_mcontext(estate);
3652 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
3653 condname = MemoryContextStrdup(stmt_mcontext, stmt->condname);
3659 ListCell *current_param;
3661 MemoryContext oldcontext;
3663 /* build string in stmt_mcontext */
3664 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
3665 initStringInfo(&ds);
3666 MemoryContextSwitchTo(oldcontext);
3668 current_param = list_head(stmt->params);
3670 for (cp = stmt->message; *cp; cp++)
3673 * Occurrences of a single % are replaced by the next parameter's
3674 * external representation. Double %'s are converted to one %.
3686 appendStringInfoChar(&ds, '%');
3691 /* should have been checked at compile time */
3692 if (current_param == NULL)
3693 elog(ERROR, "unexpected RAISE parameter list length");
3695 paramvalue = exec_eval_expr(estate,
3696 (PLpgSQL_expr *) lfirst(current_param),
3704 extval = convert_value_to_string(estate,
3707 appendStringInfoString(&ds, extval);
3708 current_param = lnext(stmt->params, current_param);
3709 exec_eval_cleanup(estate);
3712 appendStringInfoChar(&ds, cp[0]);
3715 /* should have been checked at compile time */
3716 if (current_param != NULL)
3717 elog(ERROR, "unexpected RAISE parameter list length");
3719 err_message = ds.data;
3722 foreach(lc, stmt->options)
3724 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
3731 optionvalue = exec_eval_expr(estate, opt->expr,
3737 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3738 errmsg("RAISE statement option cannot be null")));
3740 extval = convert_value_to_string(estate, optionvalue, optiontypeid);
3742 switch (opt->opt_type)
3744 case PLPGSQL_RAISEOPTION_ERRCODE:
3747 (errcode(ERRCODE_SYNTAX_ERROR),
3748 errmsg("RAISE option already specified: %s",
3750 err_code = plpgsql_recognize_err_condition(extval, true);
3751 condname = MemoryContextStrdup(stmt_mcontext, extval);
3753 case PLPGSQL_RAISEOPTION_MESSAGE:
3754 SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3756 case PLPGSQL_RAISEOPTION_DETAIL:
3757 SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3759 case PLPGSQL_RAISEOPTION_HINT:
3760 SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3762 case PLPGSQL_RAISEOPTION_COLUMN:
3763 SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3765 case PLPGSQL_RAISEOPTION_CONSTRAINT:
3766 SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3768 case PLPGSQL_RAISEOPTION_DATATYPE:
3769 SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3771 case PLPGSQL_RAISEOPTION_TABLE:
3772 SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3774 case PLPGSQL_RAISEOPTION_SCHEMA:
3775 SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3778 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3781 exec_eval_cleanup(estate);
3784 /* Default code if nothing specified */
3785 if (err_code == 0 && stmt->elog_level >= ERROR)
3786 err_code = ERRCODE_RAISE_EXCEPTION;
3788 /* Default error message if nothing specified */
3789 if (err_message == NULL)
3793 err_message = condname;
3797 err_message = MemoryContextStrdup(stmt_mcontext,
3798 unpack_sql_state(err_code));
3802 * Throw the error (may or may not come back)
3804 ereport(stmt->elog_level,
3805 (err_code ? errcode(err_code) : 0,
3806 errmsg_internal("%s", err_message),
3807 (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3808 (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3809 (err_column != NULL) ?
3810 err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3811 (err_constraint != NULL) ?
3812 err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3813 (err_datatype != NULL) ?
3814 err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3815 (err_table != NULL) ?
3816 err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3817 (err_schema != NULL) ?
3818 err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3820 /* Clean up transient strings */
3821 MemoryContextReset(stmt_mcontext);
3823 return PLPGSQL_RC_OK;
3827 * exec_stmt_assert Assert statement
3831 exec_stmt_assert(PLpgSQL_execstate *estate, PLpgSQL_stmt_assert *stmt)
3836 /* do nothing when asserts are not enabled */
3837 if (!plpgsql_check_asserts)
3838 return PLPGSQL_RC_OK;
3840 value = exec_eval_boolean(estate, stmt->cond, &isnull);
3841 exec_eval_cleanup(estate);
3843 if (isnull || !value)
3845 char *message = NULL;
3847 if (stmt->message != NULL)
3853 val = exec_eval_expr(estate, stmt->message,
3854 &isnull, &typeid, &typmod);
3856 message = convert_value_to_string(estate, val, typeid);
3857 /* we mustn't do exec_eval_cleanup here */
3861 (errcode(ERRCODE_ASSERT_FAILURE),
3862 message ? errmsg_internal("%s", message) :
3863 errmsg("assertion failed")));
3866 return PLPGSQL_RC_OK;
3870 * Initialize a mostly empty execution state
3874 plpgsql_estate_setup(PLpgSQL_execstate *estate,
3875 PLpgSQL_function *func,
3877 EState *simple_eval_estate)
3881 /* this link will be restored at exit from plpgsql_call_handler */
3882 func->cur_estate = estate;
3884 estate->func = func;
3885 estate->trigdata = NULL;
3886 estate->evtrigdata = NULL;
3888 estate->retval = (Datum) 0;
3889 estate->retisnull = true;
3890 estate->rettype = InvalidOid;
3892 estate->fn_rettype = func->fn_rettype;
3893 estate->retistuple = func->fn_retistuple;
3894 estate->retisset = func->fn_retset;
3896 estate->readonly_func = func->fn_readonly;
3897 estate->atomic = true;
3899 estate->exitlabel = NULL;
3900 estate->cur_error = NULL;
3902 estate->tuple_store = NULL;
3903 estate->tuple_store_desc = NULL;
3906 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
3907 estate->tuple_store_owner = CurrentResourceOwner;
3911 estate->tuple_store_cxt = NULL;
3912 estate->tuple_store_owner = NULL;
3916 estate->found_varno = func->found_varno;
3917 estate->ndatums = func->ndatums;
3918 estate->datums = NULL;
3919 /* the datums array will be filled by copy_plpgsql_datums() */
3920 estate->datum_context = CurrentMemoryContext;
3922 /* initialize our ParamListInfo with appropriate hook functions */
3923 estate->paramLI = makeParamList(0);
3924 estate->paramLI->paramFetch = plpgsql_param_fetch;
3925 estate->paramLI->paramFetchArg = (void *) estate;
3926 estate->paramLI->paramCompile = plpgsql_param_compile;
3927 estate->paramLI->paramCompileArg = NULL; /* not needed */
3928 estate->paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
3929 estate->paramLI->parserSetupArg = NULL; /* filled during use */
3930 estate->paramLI->numParams = estate->ndatums;
3932 /* set up for use of appropriate simple-expression EState and cast hash */
3933 if (simple_eval_estate)
3935 estate->simple_eval_estate = simple_eval_estate;
3936 /* Private cast hash just lives in function's main context */
3937 memset(&ctl, 0, sizeof(ctl));
3938 ctl.keysize = sizeof(plpgsql_CastHashKey);
3939 ctl.entrysize = sizeof(plpgsql_CastHashEntry);
3940 ctl.hcxt = CurrentMemoryContext;
3941 estate->cast_hash = hash_create("PLpgSQL private cast cache",
3942 16, /* start small and extend */
3944 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
3945 estate->cast_hash_context = CurrentMemoryContext;
3949 estate->simple_eval_estate = shared_simple_eval_estate;
3950 /* Create the session-wide cast-info hash table if we didn't already */
3951 if (shared_cast_hash == NULL)
3953 shared_cast_context = AllocSetContextCreate(TopMemoryContext,
3954 "PLpgSQL cast info",
3955 ALLOCSET_DEFAULT_SIZES);
3956 memset(&ctl, 0, sizeof(ctl));
3957 ctl.keysize = sizeof(plpgsql_CastHashKey);
3958 ctl.entrysize = sizeof(plpgsql_CastHashEntry);
3959 ctl.hcxt = shared_cast_context;
3960 shared_cast_hash = hash_create("PLpgSQL cast cache",
3961 16, /* start small and extend */
3963 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
3965 estate->cast_hash = shared_cast_hash;
3966 estate->cast_hash_context = shared_cast_context;
3970 * We start with no stmt_mcontext; one will be created only if needed.
3971 * That context will be a direct child of the function's main execution
3972 * context. Additional stmt_mcontexts might be created as children of it.
3974 estate->stmt_mcontext = NULL;
3975 estate->stmt_mcontext_parent = CurrentMemoryContext;
3977 estate->eval_tuptable = NULL;
3978 estate->eval_processed = 0;
3979 estate->eval_econtext = NULL;
3981 estate->err_stmt = NULL;
3982 estate->err_text = NULL;
3984 estate->plugin_info = NULL;
3987 * Create an EState and ExprContext for evaluation of simple expressions.
3989 plpgsql_create_econtext(estate);
3992 * Let the plugin see this function before we initialize any local
3993 * PL/pgSQL variables - note that we also give the plugin a few function
3994 * pointers so it can call back into PL/pgSQL for doing things like
3995 * variable assignments and stack traces
3997 if (*plpgsql_plugin_ptr)
3999 (*plpgsql_plugin_ptr)->error_callback = plpgsql_exec_error_callback;
4000 (*plpgsql_plugin_ptr)->assign_expr = exec_assign_expr;
4002 if ((*plpgsql_plugin_ptr)->func_setup)
4003 ((*plpgsql_plugin_ptr)->func_setup) (estate, func);
4008 * Release temporary memory used by expression/subselect evaluation
4010 * NB: the result of the evaluation is no longer valid after this is done,
4011 * unless it is a pass-by-value datatype.
4013 * NB: if you change this code, see also the hacks in exec_assign_value's
4014 * PLPGSQL_DTYPE_ARRAYELEM case for partial cleanup after subscript evals.
4018 exec_eval_cleanup(PLpgSQL_execstate *estate)
4020 /* Clear result of a full SPI_execute */
4021 if (estate->eval_tuptable != NULL)
4022 SPI_freetuptable(estate->eval_tuptable);
4023 estate->eval_tuptable = NULL;
4026 * Clear result of exec_eval_simple_expr (but keep the econtext). This
4027 * also clears any short-lived allocations done via get_eval_mcontext.
4029 if (estate->eval_econtext != NULL)
4030 ResetExprContext(estate->eval_econtext);
4035 * Generate a prepared plan
4039 exec_prepare_plan(PLpgSQL_execstate *estate,
4040 PLpgSQL_expr *expr, int cursorOptions,
4046 * The grammar can't conveniently set expr->func while building the parse
4047 * tree, so make sure it's set before parser hooks need it.
4049 expr->func = estate->func;
4052 * Generate and save the plan
4054 plan = SPI_prepare_params(expr->query,
4055 (ParserSetupHook) plpgsql_parser_setup,
4059 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
4060 expr->query, SPI_result_code_string(SPI_result));
4065 /* Check to see if it's a simple expression */
4066 exec_simple_check_plan(estate, expr);
4069 * Mark expression as not using a read-write param. exec_assign_value has
4070 * to take steps to override this if appropriate; that seems cleaner than
4071 * adding parameters to all other callers.
4078 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
4080 * Note: some callers rely on this not touching stmt_mcontext. If it ever
4081 * needs to use that, fix those callers to push/pop stmt_mcontext.
4085 exec_stmt_execsql(PLpgSQL_execstate *estate,
4086 PLpgSQL_stmt_execsql *stmt)
4088 ParamListInfo paramLI;
4091 PLpgSQL_expr *expr = stmt->sqlstmt;
4092 int too_many_rows_level = 0;
4094 if (plpgsql_extra_errors & PLPGSQL_XCHECK_TOOMANYROWS)
4095 too_many_rows_level = ERROR;
4096 else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_TOOMANYROWS)
4097 too_many_rows_level = WARNING;
4100 * On the first call for this statement generate the plan, and detect
4101 * whether the statement is INSERT/UPDATE/DELETE
4103 if (expr->plan == NULL)
4107 exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
4108 stmt->mod_stmt = false;
4109 foreach(l, SPI_plan_get_plan_sources(expr->plan))
4111 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
4114 * We could look at the raw_parse_tree, but it seems simpler to
4115 * check the command tag. Note we should *not* look at the Query
4116 * tree(s), since those are the result of rewriting and could have
4117 * been transmogrified into something else entirely.
4119 if (plansource->commandTag &&
4120 (strcmp(plansource->commandTag, "INSERT") == 0 ||
4121 strcmp(plansource->commandTag, "UPDATE") == 0 ||
4122 strcmp(plansource->commandTag, "DELETE") == 0))
4124 stmt->mod_stmt = true;
4131 * Set up ParamListInfo to pass to executor
4133 paramLI = setup_param_list(estate, expr);
4136 * If we have INTO, then we only need one row back ... but if we have INTO
4137 * STRICT or extra check too_many_rows, ask for two rows, so that we can
4138 * verify the statement returns only one. INSERT/UPDATE/DELETE are always
4139 * treated strictly. Without INTO, just run the statement to completion
4142 * We could just ask for two rows always when using INTO, but there are
4143 * some cases where demanding the extra row costs significant time, eg by
4144 * forcing completion of a sequential scan. So don't do it unless we need
4145 * to enforce strictness.
4149 if (stmt->strict || stmt->mod_stmt || too_many_rows_level)
4160 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4161 estate->readonly_func, tcount);
4164 * Check for error, and set FOUND if appropriate (for historical reasons
4165 * we set FOUND only for certain query types). Also Assert that we
4166 * identified the statement type the same as SPI did.
4171 Assert(!stmt->mod_stmt);
4172 exec_set_found(estate, (SPI_processed != 0));
4178 case SPI_OK_INSERT_RETURNING:
4179 case SPI_OK_UPDATE_RETURNING:
4180 case SPI_OK_DELETE_RETURNING:
4181 Assert(stmt->mod_stmt);
4182 exec_set_found(estate, (SPI_processed != 0));
4185 case SPI_OK_SELINTO:
4186 case SPI_OK_UTILITY:
4187 Assert(!stmt->mod_stmt);
4190 case SPI_OK_REWRITTEN:
4193 * The command was rewritten into another kind of command. It's
4194 * not clear what FOUND would mean in that case (and SPI doesn't
4195 * return the row count either), so just set it to false. Note
4196 * that we can't assert anything about mod_stmt here.
4198 exec_set_found(estate, false);
4201 /* Some SPI errors deserve specific error messages */
4202 case SPI_ERROR_COPY:
4204 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4205 errmsg("cannot COPY to/from client in PL/pgSQL")));
4208 case SPI_ERROR_TRANSACTION:
4210 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4211 errmsg("unsupported transaction command in PL/pgSQL")));
4215 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
4216 expr->query, SPI_result_code_string(rc));
4220 /* All variants should save result info for GET DIAGNOSTICS */
4221 estate->eval_processed = SPI_processed;
4223 /* Process INTO if present */
4226 SPITupleTable *tuptab = SPI_tuptable;
4227 uint64 n = SPI_processed;
4228 PLpgSQL_variable *target;
4230 /* If the statement did not return a tuple table, complain */
4233 (errcode(ERRCODE_SYNTAX_ERROR),
4234 errmsg("INTO used with a command that cannot return data")));
4236 /* Fetch target's datum entry */
4237 target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4240 * If SELECT ... INTO specified STRICT, and the query didn't find
4241 * exactly one row, throw an error. If STRICT was not specified, then
4242 * allow the query to find any number of rows.
4250 if (estate->func->print_strict_params)
4251 errdetail = format_expr_params(estate, expr);
4256 (errcode(ERRCODE_NO_DATA_FOUND),
4257 errmsg("query returned no rows"),
4258 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4260 /* set the target to NULL(s) */
4261 exec_move_row(estate, target, NULL, tuptab->tupdesc);
4265 if (n > 1 && (stmt->strict || stmt->mod_stmt || too_many_rows_level))
4270 if (estate->func->print_strict_params)
4271 errdetail = format_expr_params(estate, expr);
4275 errlevel = (stmt->strict || stmt->mod_stmt) ? ERROR : too_many_rows_level;
4278 (errcode(ERRCODE_TOO_MANY_ROWS),
4279 errmsg("query returned more than one row"),
4280 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0,
4281 errhint("Make sure the query returns a single row, or use LIMIT 1.")));
4283 /* Put the first result row into the target */
4284 exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4288 exec_eval_cleanup(estate);
4289 SPI_freetuptable(SPI_tuptable);
4293 /* If the statement returned a tuple table, complain */
4294 if (SPI_tuptable != NULL)
4296 (errcode(ERRCODE_SYNTAX_ERROR),
4297 errmsg("query has no destination for result data"),
4298 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
4301 return PLPGSQL_RC_OK;
4306 * exec_stmt_dynexecute Execute a dynamic SQL query
4307 * (possibly with INTO).
4311 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
4312 PLpgSQL_stmt_dynexecute *stmt)
4320 PreparedParamsData *ppd = NULL;
4321 MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
4324 * First we evaluate the string expression after the EXECUTE keyword. Its
4325 * result is the querystring we have to execute.
4327 query = exec_eval_expr(estate, stmt->query, &isnull, &restype, &restypmod);
4330 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4331 errmsg("query string argument of EXECUTE is null")));
4333 /* Get the C-String representation */
4334 querystr = convert_value_to_string(estate, query, restype);
4336 /* copy it into the stmt_mcontext before we clean up */
4337 querystr = MemoryContextStrdup(stmt_mcontext, querystr);
4339 exec_eval_cleanup(estate);
4342 * Execute the query without preparing a saved plan.
4346 ppd = exec_eval_using_params(estate, stmt->params);
4347 exec_res = SPI_execute_with_args(querystr,
4348 ppd->nargs, ppd->types,
4349 ppd->values, ppd->nulls,
4350 estate->readonly_func, 0);
4353 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
4361 case SPI_OK_INSERT_RETURNING:
4362 case SPI_OK_UPDATE_RETURNING:
4363 case SPI_OK_DELETE_RETURNING:
4364 case SPI_OK_UTILITY:
4365 case SPI_OK_REWRITTEN:
4371 * Also allow a zero return, which implies the querystring
4372 * contained no commands.
4376 case SPI_OK_SELINTO:
4379 * We want to disallow SELECT INTO for now, because its behavior
4380 * is not consistent with SELECT INTO in a normal plpgsql context.
4381 * (We need to reimplement EXECUTE to parse the string as a
4382 * plpgsql command, not just feed it to SPI_execute.) This is not
4383 * a functional limitation because CREATE TABLE AS is allowed.
4386 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4387 errmsg("EXECUTE of SELECT ... INTO is not implemented"),
4388 errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
4391 /* Some SPI errors deserve specific error messages */
4392 case SPI_ERROR_COPY:
4394 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4395 errmsg("cannot COPY to/from client in PL/pgSQL")));
4398 case SPI_ERROR_TRANSACTION:
4400 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4401 errmsg("EXECUTE of transaction commands is not implemented")));
4405 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
4406 querystr, SPI_result_code_string(exec_res));
4410 /* Save result info for GET DIAGNOSTICS */
4411 estate->eval_processed = SPI_processed;
4413 /* Process INTO if present */
4416 SPITupleTable *tuptab = SPI_tuptable;
4417 uint64 n = SPI_processed;
4418 PLpgSQL_variable *target;
4420 /* If the statement did not return a tuple table, complain */
4423 (errcode(ERRCODE_SYNTAX_ERROR),
4424 errmsg("INTO used with a command that cannot return data")));
4426 /* Fetch target's datum entry */
4427 target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4430 * If SELECT ... INTO specified STRICT, and the query didn't find
4431 * exactly one row, throw an error. If STRICT was not specified, then
4432 * allow the query to find any number of rows.
4440 if (estate->func->print_strict_params)
4441 errdetail = format_preparedparamsdata(estate, ppd);
4446 (errcode(ERRCODE_NO_DATA_FOUND),
4447 errmsg("query returned no rows"),
4448 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4450 /* set the target to NULL(s) */
4451 exec_move_row(estate, target, NULL, tuptab->tupdesc);
4455 if (n > 1 && stmt->strict)
4459 if (estate->func->print_strict_params)
4460 errdetail = format_preparedparamsdata(estate, ppd);
4465 (errcode(ERRCODE_TOO_MANY_ROWS),
4466 errmsg("query returned more than one row"),
4467 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4470 /* Put the first result row into the target */
4471 exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4473 /* clean up after exec_move_row() */
4474 exec_eval_cleanup(estate);
4479 * It might be a good idea to raise an error if the query returned
4480 * tuples that are being ignored, but historically we have not done
4485 /* Release any result from SPI_execute, as well as transient data */
4486 SPI_freetuptable(SPI_tuptable);
4487 MemoryContextReset(stmt_mcontext);
4489 return PLPGSQL_RC_OK;
4494 * exec_stmt_dynfors Execute a dynamic query, assign each
4495 * tuple to a record or row and
4496 * execute a group of statements
4501 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
4506 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
4512 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
4515 * Close the implicit cursor
4517 SPI_cursor_close(portal);
4524 * exec_stmt_open Execute an OPEN cursor statement
4528 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
4530 PLpgSQL_var *curvar;
4531 MemoryContext stmt_mcontext = NULL;
4532 char *curname = NULL;
4533 PLpgSQL_expr *query;
4535 ParamListInfo paramLI;
4538 * Get the cursor variable and if it has an assigned name, check
4539 * that it's not in use currently.
4542 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4543 if (!curvar->isnull)
4545 MemoryContext oldcontext;
4547 /* We only need stmt_mcontext to hold the cursor name string */
4548 stmt_mcontext = get_stmt_mcontext(estate);
4549 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
4550 curname = TextDatumGetCString(curvar->value);
4551 MemoryContextSwitchTo(oldcontext);
4553 if (SPI_cursor_find(curname) != NULL)
4555 (errcode(ERRCODE_DUPLICATE_CURSOR),
4556 errmsg("cursor \"%s\" already in use", curname)));
4560 * Process the OPEN according to it's type.
4563 if (stmt->query != NULL)
4566 * This is an OPEN refcursor FOR SELECT ...
4568 * We just make sure the query is planned. The real work is
4572 query = stmt->query;
4573 if (query->plan == NULL)
4574 exec_prepare_plan(estate, query, stmt->cursor_options, true);
4576 else if (stmt->dynquery != NULL)
4579 * This is an OPEN refcursor FOR EXECUTE ...
4582 portal = exec_dynquery_with_params(estate,
4586 stmt->cursor_options);
4589 * If cursor variable was NULL, store the generated portal name in it.
4590 * Note: exec_dynquery_with_params already reset the stmt_mcontext, so
4591 * curname is a dangling pointer here; but testing it for nullness is
4594 if (curname == NULL)
4595 assign_text_var(estate, curvar, portal->name);
4597 return PLPGSQL_RC_OK;
4602 * This is an OPEN cursor
4604 * Note: parser should already have checked that statement supplies
4605 * args iff cursor needs them, but we check again to be safe.
4608 if (stmt->argquery != NULL)
4611 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
4612 * statement to evaluate the args and put 'em into the
4616 PLpgSQL_stmt_execsql set_args;
4618 if (curvar->cursor_explicit_argrow < 0)
4620 (errcode(ERRCODE_SYNTAX_ERROR),
4621 errmsg("arguments given for cursor without arguments")));
4623 memset(&set_args, 0, sizeof(set_args));
4624 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
4625 set_args.lineno = stmt->lineno;
4626 set_args.sqlstmt = stmt->argquery;
4627 set_args.into = true;
4628 /* XXX historically this has not been STRICT */
4629 set_args.target = (PLpgSQL_variable *)
4630 (estate->datums[curvar->cursor_explicit_argrow]);
4632 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
4633 elog(ERROR, "open cursor failed during argument processing");
4637 if (curvar->cursor_explicit_argrow >= 0)
4639 (errcode(ERRCODE_SYNTAX_ERROR),
4640 errmsg("arguments required for cursor")));
4643 query = curvar->cursor_explicit_expr;
4644 if (query->plan == NULL)
4645 exec_prepare_plan(estate, query, curvar->cursor_options, true);
4649 * Set up ParamListInfo for this query
4651 paramLI = setup_param_list(estate, query);
4654 * Open the cursor (the paramlist will get copied into the portal)
4656 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
4658 estate->readonly_func);
4660 elog(ERROR, "could not open cursor: %s",
4661 SPI_result_code_string(SPI_result));
4664 * If cursor variable was NULL, store the generated portal name in it
4666 if (curname == NULL)
4667 assign_text_var(estate, curvar, portal->name);
4669 /* If we had any transient data, clean it up */
4670 exec_eval_cleanup(estate);
4672 MemoryContextReset(stmt_mcontext);
4674 return PLPGSQL_RC_OK;
4679 * exec_stmt_fetch Fetch from a cursor into a target, or just
4680 * move the current position of the cursor
4684 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
4686 PLpgSQL_var *curvar;
4687 long how_many = stmt->how_many;
4688 SPITupleTable *tuptab;
4692 MemoryContext oldcontext;
4695 * Get the portal of the cursor by name
4698 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4701 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4702 errmsg("cursor variable \"%s\" is null", curvar->refname)));
4704 /* Use eval_mcontext for short-lived string */
4705 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4706 curname = TextDatumGetCString(curvar->value);
4707 MemoryContextSwitchTo(oldcontext);
4709 portal = SPI_cursor_find(curname);
4712 (errcode(ERRCODE_UNDEFINED_CURSOR),
4713 errmsg("cursor \"%s\" does not exist", curname)));
4715 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
4720 /* XXX should be doing this in LONG not INT width */
4721 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
4725 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4726 errmsg("relative or absolute cursor position is null")));
4728 exec_eval_cleanup(estate);
4733 PLpgSQL_variable *target;
4736 * Fetch 1 tuple from the cursor
4739 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
4740 tuptab = SPI_tuptable;
4744 * Set the target appropriately.
4747 target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4749 exec_move_row(estate, target, NULL, tuptab->tupdesc);
4751 exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4753 exec_eval_cleanup(estate);
4754 SPI_freetuptable(tuptab);
4758 /* Move the cursor */
4759 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
4763 /* Set the ROW_COUNT and the global FOUND variable appropriately. */
4764 estate->eval_processed = n;
4765 exec_set_found(estate, n != 0);
4767 return PLPGSQL_RC_OK;
4771 * exec_stmt_close Close a cursor
4775 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
4777 PLpgSQL_var *curvar;
4780 MemoryContext oldcontext;
4783 * Get the portal of the cursor by name
4786 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4789 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4790 errmsg("cursor variable \"%s\" is null", curvar->refname)));
4792 /* Use eval_mcontext for short-lived string */
4793 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4794 curname = TextDatumGetCString(curvar->value);
4795 MemoryContextSwitchTo(oldcontext);
4797 portal = SPI_cursor_find(curname);
4800 (errcode(ERRCODE_UNDEFINED_CURSOR),
4801 errmsg("cursor \"%s\" does not exist", curname)));
4807 SPI_cursor_close(portal);
4809 return PLPGSQL_RC_OK;
4815 * Commit the transaction.
4818 exec_stmt_commit(PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
4821 SPI_commit_and_chain();
4825 SPI_start_transaction();
4828 estate->simple_eval_estate = NULL;
4829 plpgsql_create_econtext(estate);
4831 return PLPGSQL_RC_OK;
4835 * exec_stmt_rollback
4837 * Abort the transaction.
4840 exec_stmt_rollback(PLpgSQL_execstate *estate, PLpgSQL_stmt_rollback *stmt)
4843 SPI_rollback_and_chain();
4847 SPI_start_transaction();
4850 estate->simple_eval_estate = NULL;
4851 plpgsql_create_econtext(estate);
4853 return PLPGSQL_RC_OK;
4859 * Execute SET/RESET statement.
4861 * We just parse and execute the statement normally, but we have to do it
4862 * without setting a snapshot, for things like SET TRANSACTION.
4865 exec_stmt_set(PLpgSQL_execstate *estate, PLpgSQL_stmt_set *stmt)
4867 PLpgSQL_expr *expr = stmt->expr;
4870 if (expr->plan == NULL)
4872 exec_prepare_plan(estate, expr, 0, true);
4873 expr->plan->no_snapshots = true;
4876 rc = SPI_execute_plan(expr->plan, NULL, NULL, estate->readonly_func, 0);
4878 if (rc != SPI_OK_UTILITY)
4879 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
4880 expr->query, SPI_result_code_string(rc));
4882 return PLPGSQL_RC_OK;
4886 * exec_assign_expr Put an expression's result into a variable.
4890 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4899 * If first time through, create a plan for this expression, and then see
4900 * if we can pass the target variable as a read-write parameter to the
4901 * expression. (This is a bit messy, but it seems cleaner than modifying
4902 * the API of exec_eval_expr for the purpose.)
4904 if (expr->plan == NULL)
4906 exec_prepare_plan(estate, expr, 0, true);
4907 if (target->dtype == PLPGSQL_DTYPE_VAR)
4908 exec_check_rw_parameter(expr, target->dno);
4911 value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4912 exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4913 exec_eval_cleanup(estate);
4918 * exec_assign_c_string Put a C string into a text variable.
4920 * We take a NULL pointer as signifying empty string, not SQL null.
4922 * As with the underlying exec_assign_value, caller is expected to do
4923 * exec_eval_cleanup later.
4927 exec_assign_c_string(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4931 MemoryContext oldcontext;
4933 /* Use eval_mcontext for short-lived text value */
4934 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4936 value = cstring_to_text(str);
4938 value = cstring_to_text("");
4939 MemoryContextSwitchTo(oldcontext);
4941 exec_assign_value(estate, target, PointerGetDatum(value), false,
4947 * exec_assign_value Put a value into a target datum
4949 * Note: in some code paths, this will leak memory in the eval_mcontext;
4950 * we assume that will be cleaned up later by exec_eval_cleanup. We cannot
4951 * call exec_eval_cleanup here for fear of destroying the input Datum value.
4955 exec_assign_value(PLpgSQL_execstate *estate,
4956 PLpgSQL_datum *target,
4957 Datum value, bool isNull,
4958 Oid valtype, int32 valtypmod)
4960 switch (target->dtype)
4962 case PLPGSQL_DTYPE_VAR:
4963 case PLPGSQL_DTYPE_PROMISE:
4966 * Target is a variable
4968 PLpgSQL_var *var = (PLpgSQL_var *) target;
4971 newvalue = exec_cast_value(estate,
4976 var->datatype->typoid,
4977 var->datatype->atttypmod);
4979 if (isNull && var->notnull)
4981 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4982 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4986 * If type is by-reference, copy the new value (which is
4987 * probably in the eval_mcontext) into the procedure's main
4988 * memory context. But if it's a read/write reference to an
4989 * expanded object, no physical copy needs to happen; at most
4990 * we need to reparent the object's memory context.
4992 * If it's an array, we force the value to be stored in R/W
4993 * expanded form. This wins if the function later does, say,
4994 * a lot of array subscripting operations on the variable, and
4995 * otherwise might lose. We might need to use a different
4996 * heuristic, but it's too soon to tell. Also, are there
4997 * cases where it'd be useful to force non-array values into
5000 if (!var->datatype->typbyval && !isNull)
5002 if (var->datatype->typisarray &&
5003 !VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(newvalue)))
5005 /* array and not already R/W, so apply expand_array */
5006 newvalue = expand_array(newvalue,
5007 estate->datum_context,
5012 /* else transfer value if R/W, else just datumCopy */
5013 newvalue = datumTransfer(newvalue,
5015 var->datatype->typlen);
5020 * Now free the old value, if any, and assign the new one. But
5021 * skip the assignment if old and new values are the same.
5022 * Note that for expanded objects, this test is necessary and
5023 * cannot reliably be made any earlier; we have to be looking
5024 * at the object's standard R/W pointer to be sure pointer
5025 * equality is meaningful.
5027 * Also, if it's a promise variable, we should disarm the
5028 * promise in any case --- otherwise, assigning null to an
5029 * armed promise variable would fail to disarm the promise.
5031 if (var->value != newvalue || var->isnull || isNull)
5032 assign_simple_var(estate, var, newvalue, isNull,
5033 (!var->datatype->typbyval && !isNull));
5035 var->promise = PLPGSQL_PROMISE_NONE;
5039 case PLPGSQL_DTYPE_ROW:
5042 * Target is a row variable
5044 PLpgSQL_row *row = (PLpgSQL_row *) target;
5048 /* If source is null, just assign nulls to the row */
5049 exec_move_row(estate, (PLpgSQL_variable *) row,
5054 /* Source must be of RECORD or composite type */
5055 if (!type_is_rowtype(valtype))
5057 (errcode(ERRCODE_DATATYPE_MISMATCH),
5058 errmsg("cannot assign non-composite value to a row variable")));
5059 exec_move_row_from_datum(estate, (PLpgSQL_variable *) row,
5065 case PLPGSQL_DTYPE_REC:
5068 * Target is a record variable
5070 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
5076 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5077 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5080 /* Set variable to a simple NULL */
5081 exec_move_row(estate, (PLpgSQL_variable *) rec,
5086 /* Source must be of RECORD or composite type */
5087 if (!type_is_rowtype(valtype))
5089 (errcode(ERRCODE_DATATYPE_MISMATCH),
5090 errmsg("cannot assign non-composite value to a record variable")));
5091 exec_move_row_from_datum(estate, (PLpgSQL_variable *) rec,
5097 case PLPGSQL_DTYPE_RECFIELD:
5100 * Target is a field of a record
5102 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
5104 ExpandedRecordHeader *erh;
5106 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5110 * If record variable is NULL, instantiate it if it has a
5111 * named composite type, else complain. (This won't change
5112 * the logical state of the record, but if we successfully
5113 * assign below, the unassigned fields will all become NULLs.)
5117 instantiate_empty_record_variable(estate, rec);
5122 * Look up the field's properties if we have not already, or
5123 * if the tuple descriptor ID changed since last time.
5125 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5127 if (!expanded_record_lookup_field(erh,
5128 recfield->fieldname,
5131 (errcode(ERRCODE_UNDEFINED_COLUMN),
5132 errmsg("record \"%s\" has no field \"%s\"",
5133 rec->refname, recfield->fieldname)));
5134 recfield->rectupledescid = erh->er_tupdesc_id;
5137 /* We don't support assignments to system columns. */
5138 if (recfield->finfo.fnumber <= 0)
5140 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5141 errmsg("cannot assign to system column \"%s\"",
5142 recfield->fieldname)));
5144 /* Cast the new value to the right type, if needed. */
5145 value = exec_cast_value(estate,
5150 recfield->finfo.ftypeid,
5151 recfield->finfo.ftypmod);
5153 /* And assign it. */
5154 expanded_record_set_field(erh, recfield->finfo.fnumber,
5155 value, isNull, !estate->atomic);
5159 case PLPGSQL_DTYPE_ARRAYELEM:
5162 * Target is an element of an array
5164 PLpgSQL_arrayelem *arrayelem;
5167 PLpgSQL_expr *subscripts[MAXDIM];
5168 int subscriptvals[MAXDIM];
5169 Datum oldarraydatum,
5172 bool oldarrayisnull;
5175 SPITupleTable *save_eval_tuptable;
5176 MemoryContext oldcontext;
5179 * We need to do subscript evaluation, which might require
5180 * evaluating general expressions; and the caller might have
5181 * done that too in order to prepare the input Datum. We have
5182 * to save and restore the caller's SPI_execute result, if
5185 save_eval_tuptable = estate->eval_tuptable;
5186 estate->eval_tuptable = NULL;
5189 * To handle constructs like x[1][2] := something, we have to
5190 * be prepared to deal with a chain of arrayelem datums. Chase
5191 * back to find the base array datum, and save the subscript
5192 * expressions as we go. (We are scanning right to left here,
5193 * but want to evaluate the subscripts left-to-right to
5194 * minimize surprises.) Note that arrayelem is left pointing
5195 * to the leftmost arrayelem datum, where we will cache the
5196 * array element type data.
5201 arrayelem = (PLpgSQL_arrayelem *) target;
5202 if (nsubscripts >= MAXDIM)
5204 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5205 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5206 nsubscripts + 1, MAXDIM)));
5207 subscripts[nsubscripts++] = arrayelem->subscript;
5208 target = estate->datums[arrayelem->arrayparentno];
5209 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
5211 /* Fetch current value of array datum */
5212 exec_eval_datum(estate, target,
5213 &parenttypoid, &parenttypmod,
5214 &oldarraydatum, &oldarrayisnull);
5216 /* Update cached type data if necessary */
5217 if (arrayelem->parenttypoid != parenttypoid ||
5218 arrayelem->parenttypmod != parenttypmod)
5221 int32 arraytypmod = parenttypmod;
5228 /* If target is domain over array, reduce to base type */
5229 arraytypoid = getBaseTypeAndTypmod(parenttypoid,
5232 /* ... and identify the element type */
5233 elemtypoid = get_element_type(arraytypoid);
5234 if (!OidIsValid(elemtypoid))
5236 (errcode(ERRCODE_DATATYPE_MISMATCH),
5237 errmsg("subscripted object is not an array")));
5239 /* Collect needed data about the types */
5240 arraytyplen = get_typlen(arraytypoid);
5242 get_typlenbyvalalign(elemtypoid,
5247 /* Now safe to update the cached data */
5248 arrayelem->parenttypoid = parenttypoid;
5249 arrayelem->parenttypmod = parenttypmod;
5250 arrayelem->arraytypoid = arraytypoid;
5251 arrayelem->arraytypmod = arraytypmod;
5252 arrayelem->arraytyplen = arraytyplen;
5253 arrayelem->elemtypoid = elemtypoid;
5254 arrayelem->elemtyplen = elemtyplen;
5255 arrayelem->elemtypbyval = elemtypbyval;
5256 arrayelem->elemtypalign = elemtypalign;
5260 * Evaluate the subscripts, switch into left-to-right order.
5261 * Like the expression built by ExecInitSubscriptingRef(),
5262 * complain if any subscript is null.
5264 for (i = 0; i < nsubscripts; i++)
5269 exec_eval_integer(estate,
5270 subscripts[nsubscripts - 1 - i],
5274 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5275 errmsg("array subscript in assignment must not be null")));
5278 * Clean up in case the subscript expression wasn't
5279 * simple. We can't do exec_eval_cleanup, but we can do
5280 * this much (which is safe because the integer subscript
5281 * value is surely pass-by-value), and we must do it in
5282 * case the next subscript expression isn't simple either.
5284 if (estate->eval_tuptable != NULL)
5285 SPI_freetuptable(estate->eval_tuptable);
5286 estate->eval_tuptable = NULL;
5289 /* Now we can restore caller's SPI_execute result if any. */
5290 Assert(estate->eval_tuptable == NULL);
5291 estate->eval_tuptable = save_eval_tuptable;
5293 /* Coerce source value to match array element type. */
5294 coerced_value = exec_cast_value(estate,
5299 arrayelem->elemtypoid,
5300 arrayelem->arraytypmod);
5303 * If the original array is null, cons up an empty array so
5304 * that the assignment can proceed; we'll end with a
5305 * one-element array containing just the assigned-to
5306 * subscript. This only works for varlena arrays, though; for
5307 * fixed-length array types we skip the assignment. We can't
5308 * support assignment of a null entry into a fixed-length
5309 * array, either, so that's a no-op too. This is all ugly but
5310 * corresponds to the current behavior of execExpr*.c.
5312 if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
5313 (oldarrayisnull || isNull))
5316 /* empty array, if any, and newarraydatum are short-lived */
5317 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5320 oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
5323 * Build the modified array value.
5325 newarraydatum = array_set_element(oldarraydatum,
5330 arrayelem->arraytyplen,
5331 arrayelem->elemtyplen,
5332 arrayelem->elemtypbyval,
5333 arrayelem->elemtypalign);
5335 MemoryContextSwitchTo(oldcontext);
5338 * Assign the new array to the base variable. It's never NULL
5339 * at this point. Note that if the target is a domain,
5340 * coercing the base array type back up to the domain will
5341 * happen within exec_assign_value.
5343 exec_assign_value(estate, target,
5346 arrayelem->arraytypoid,
5347 arrayelem->arraytypmod);
5352 elog(ERROR, "unrecognized dtype: %d", target->dtype);
5357 * exec_eval_datum Get current value of a PLpgSQL_datum
5359 * The type oid, typmod, value in Datum format, and null flag are returned.
5361 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums;
5362 * that's not needed because we never pass references to such datums to SPI.
5364 * NOTE: the returned Datum points right at the stored value in the case of
5365 * pass-by-reference datatypes. Generally callers should take care not to
5366 * modify the stored value. Some callers intentionally manipulate variables
5367 * referenced by R/W expanded pointers, though; it is those callers'
5368 * responsibility that the results are semantically OK.
5370 * In some cases we have to palloc a return value, and in such cases we put
5371 * it into the estate's eval_mcontext.
5374 exec_eval_datum(PLpgSQL_execstate *estate,
5375 PLpgSQL_datum *datum,
5381 MemoryContext oldcontext;
5383 switch (datum->dtype)
5385 case PLPGSQL_DTYPE_PROMISE:
5386 /* fulfill promise if needed, then handle like regular var */
5387 plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
5391 case PLPGSQL_DTYPE_VAR:
5393 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5395 *typeid = var->datatype->typoid;
5396 *typetypmod = var->datatype->atttypmod;
5397 *value = var->value;
5398 *isnull = var->isnull;
5402 case PLPGSQL_DTYPE_ROW:
5404 PLpgSQL_row *row = (PLpgSQL_row *) datum;
5407 /* We get here if there are multiple OUT parameters */
5408 if (!row->rowtupdesc) /* should not happen */
5409 elog(ERROR, "row variable has no tupdesc");
5410 /* Make sure we have a valid type/typmod setting */
5411 BlessTupleDesc(row->rowtupdesc);
5412 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5413 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
5414 if (tup == NULL) /* should not happen */
5415 elog(ERROR, "row not compatible with its own tupdesc");
5416 *typeid = row->rowtupdesc->tdtypeid;
5417 *typetypmod = row->rowtupdesc->tdtypmod;
5418 *value = HeapTupleGetDatum(tup);
5420 MemoryContextSwitchTo(oldcontext);
5424 case PLPGSQL_DTYPE_REC:
5426 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5428 if (rec->erh == NULL)
5430 /* Treat uninstantiated record as a simple NULL */
5433 /* Report variable's declared type */
5434 *typeid = rec->rectypeid;
5439 if (ExpandedRecordIsEmpty(rec->erh))
5441 /* Empty record is also a NULL */
5447 *value = ExpandedRecordGetDatum(rec->erh);
5450 if (rec->rectypeid != RECORDOID)
5452 /* Report variable's declared type, if not RECORD */
5453 *typeid = rec->rectypeid;
5458 /* Report record's actual type if declared RECORD */
5459 *typeid = rec->erh->er_typeid;
5460 *typetypmod = rec->erh->er_typmod;
5466 case PLPGSQL_DTYPE_RECFIELD:
5468 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5470 ExpandedRecordHeader *erh;
5472 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5476 * If record variable is NULL, instantiate it if it has a
5477 * named composite type, else complain. (This won't change
5478 * the logical state of the record: it's still NULL.)
5482 instantiate_empty_record_variable(estate, rec);
5487 * Look up the field's properties if we have not already, or
5488 * if the tuple descriptor ID changed since last time.
5490 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5492 if (!expanded_record_lookup_field(erh,
5493 recfield->fieldname,
5496 (errcode(ERRCODE_UNDEFINED_COLUMN),
5497 errmsg("record \"%s\" has no field \"%s\"",
5498 rec->refname, recfield->fieldname)));
5499 recfield->rectupledescid = erh->er_tupdesc_id;
5502 /* Report type data. */
5503 *typeid = recfield->finfo.ftypeid;
5504 *typetypmod = recfield->finfo.ftypmod;
5506 /* And fetch the field value. */
5507 *value = expanded_record_get_field(erh,
5508 recfield->finfo.fnumber,
5514 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5519 * plpgsql_exec_get_datum_type Get datatype of a PLpgSQL_datum
5521 * This is the same logic as in exec_eval_datum, but we skip acquiring
5522 * the actual value of the variable. Also, needn't support DTYPE_ROW.
5525 plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
5526 PLpgSQL_datum *datum)
5530 switch (datum->dtype)
5532 case PLPGSQL_DTYPE_VAR:
5533 case PLPGSQL_DTYPE_PROMISE:
5535 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5537 typeid = var->datatype->typoid;
5541 case PLPGSQL_DTYPE_REC:
5543 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5545 if (rec->erh == NULL || rec->rectypeid != RECORDOID)
5547 /* Report variable's declared type */
5548 typeid = rec->rectypeid;
5552 /* Report record's actual type if declared RECORD */
5553 typeid = rec->erh->er_typeid;
5558 case PLPGSQL_DTYPE_RECFIELD:
5560 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5563 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5566 * If record variable is NULL, instantiate it if it has a
5567 * named composite type, else complain. (This won't change
5568 * the logical state of the record: it's still NULL.)
5570 if (rec->erh == NULL)
5571 instantiate_empty_record_variable(estate, rec);
5574 * Look up the field's properties if we have not already, or
5575 * if the tuple descriptor ID changed since last time.
5577 if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
5579 if (!expanded_record_lookup_field(rec->erh,
5580 recfield->fieldname,
5583 (errcode(ERRCODE_UNDEFINED_COLUMN),
5584 errmsg("record \"%s\" has no field \"%s\"",
5585 rec->refname, recfield->fieldname)));
5586 recfield->rectupledescid = rec->erh->er_tupdesc_id;
5589 typeid = recfield->finfo.ftypeid;
5594 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5595 typeid = InvalidOid; /* keep compiler quiet */
5603 * plpgsql_exec_get_datum_type_info Get datatype etc of a PLpgSQL_datum
5605 * An extended version of plpgsql_exec_get_datum_type, which also retrieves the
5606 * typmod and collation of the datum. Note however that we don't report the
5607 * possibly-mutable typmod of RECORD values, but say -1 always.
5610 plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
5611 PLpgSQL_datum *datum,
5612 Oid *typeId, int32 *typMod, Oid *collation)
5614 switch (datum->dtype)
5616 case PLPGSQL_DTYPE_VAR:
5617 case PLPGSQL_DTYPE_PROMISE:
5619 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5621 *typeId = var->datatype->typoid;
5622 *typMod = var->datatype->atttypmod;
5623 *collation = var->datatype->collation;
5627 case PLPGSQL_DTYPE_REC:
5629 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5631 if (rec->erh == NULL || rec->rectypeid != RECORDOID)
5633 /* Report variable's declared type */
5634 *typeId = rec->rectypeid;
5639 /* Report record's actual type if declared RECORD */
5640 *typeId = rec->erh->er_typeid;
5641 /* do NOT return the mutable typmod of a RECORD variable */
5644 /* composite types are never collatable */
5645 *collation = InvalidOid;
5649 case PLPGSQL_DTYPE_RECFIELD:
5651 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5654 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5657 * If record variable is NULL, instantiate it if it has a
5658 * named composite type, else complain. (This won't change
5659 * the logical state of the record: it's still NULL.)
5661 if (rec->erh == NULL)
5662 instantiate_empty_record_variable(estate, rec);
5665 * Look up the field's properties if we have not already, or
5666 * if the tuple descriptor ID changed since last time.
5668 if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
5670 if (!expanded_record_lookup_field(rec->erh,
5671 recfield->fieldname,
5674 (errcode(ERRCODE_UNDEFINED_COLUMN),
5675 errmsg("record \"%s\" has no field \"%s\"",
5676 rec->refname, recfield->fieldname)));
5677 recfield->rectupledescid = rec->erh->er_tupdesc_id;
5680 *typeId = recfield->finfo.ftypeid;
5681 *typMod = recfield->finfo.ftypmod;
5682 *collation = recfield->finfo.fcollation;
5687 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5688 *typeId = InvalidOid; /* keep compiler quiet */
5690 *collation = InvalidOid;
5696 * exec_eval_integer Evaluate an expression, coerce result to int4
5698 * Note we do not do exec_eval_cleanup here; the caller must do it at
5699 * some later point. (We do this because the caller may be holding the
5700 * results of other, pass-by-reference, expression evaluations, such as
5701 * an array value to be subscripted.)
5705 exec_eval_integer(PLpgSQL_execstate *estate,
5713 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5714 exprdatum = exec_cast_value(estate, exprdatum, isNull,
5715 exprtypeid, exprtypmod,
5717 return DatumGetInt32(exprdatum);
5721 * exec_eval_boolean Evaluate an expression, coerce result to bool
5723 * Note we do not do exec_eval_cleanup here; the caller must do it at
5728 exec_eval_boolean(PLpgSQL_execstate *estate,
5736 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5737 exprdatum = exec_cast_value(estate, exprdatum, isNull,
5738 exprtypeid, exprtypmod,
5740 return DatumGetBool(exprdatum);
5744 * exec_eval_expr Evaluate an expression and return
5745 * the result Datum, along with data type/typmod.
5747 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
5751 exec_eval_expr(PLpgSQL_execstate *estate,
5759 Form_pg_attribute attr;
5762 * If first time through, create a plan for this expression.
5764 if (expr->plan == NULL)
5765 exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
5768 * If this is a simple expression, bypass SPI and use the executor
5771 if (exec_eval_simple_expr(estate, expr,
5772 &result, isNull, rettype, rettypmod))
5776 * Else do it the hard way via exec_run_select
5778 rc = exec_run_select(estate, expr, 2, NULL);
5779 if (rc != SPI_OK_SELECT)
5781 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5782 errmsg("query \"%s\" did not return data", expr->query)));
5785 * Check that the expression returns exactly one column...
5787 if (estate->eval_tuptable->tupdesc->natts != 1)
5789 (errcode(ERRCODE_SYNTAX_ERROR),
5790 errmsg_plural("query \"%s\" returned %d column",
5791 "query \"%s\" returned %d columns",
5792 estate->eval_tuptable->tupdesc->natts,
5794 estate->eval_tuptable->tupdesc->natts)));
5797 * ... and get the column's datatype.
5799 attr = TupleDescAttr(estate->eval_tuptable->tupdesc, 0);
5800 *rettype = attr->atttypid;
5801 *rettypmod = attr->atttypmod;
5804 * If there are no rows selected, the result is a NULL of that type.
5806 if (estate->eval_processed == 0)
5813 * Check that the expression returned no more than one row.
5815 if (estate->eval_processed != 1)
5817 (errcode(ERRCODE_CARDINALITY_VIOLATION),
5818 errmsg("query \"%s\" returned more than one row",
5822 * Return the single result Datum.
5824 return SPI_getbinval(estate->eval_tuptable->vals[0],
5825 estate->eval_tuptable->tupdesc, 1, isNull);
5830 * exec_run_select Execute a select query
5834 exec_run_select(PLpgSQL_execstate *estate,
5835 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
5837 ParamListInfo paramLI;
5841 * On the first call for this expression generate the plan.
5843 * If we don't need to return a portal, then we're just going to execute
5844 * the query once, which means it's OK to use a parallel plan, even if the
5845 * number of rows being fetched is limited. If we do need to return a
5846 * portal, the caller might do cursor operations, which parallel query
5849 if (expr->plan == NULL)
5850 exec_prepare_plan(estate, expr,
5851 portalP == NULL ? CURSOR_OPT_PARALLEL_OK : 0, true);
5854 * Set up ParamListInfo to pass to executor
5856 paramLI = setup_param_list(estate, expr);
5859 * If a portal was requested, put the query and paramlist into the portal
5861 if (portalP != NULL)
5863 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
5865 estate->readonly_func);
5866 if (*portalP == NULL)
5867 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5868 expr->query, SPI_result_code_string(SPI_result));
5869 exec_eval_cleanup(estate);
5870 return SPI_OK_CURSOR;
5876 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
5877 estate->readonly_func, maxtuples);
5878 if (rc != SPI_OK_SELECT)
5880 (errcode(ERRCODE_SYNTAX_ERROR),
5881 errmsg("query \"%s\" is not a SELECT", expr->query)));
5883 /* Save query results for eventual cleanup */
5884 Assert(estate->eval_tuptable == NULL);
5885 estate->eval_tuptable = SPI_tuptable;
5886 estate->eval_processed = SPI_processed;
5893 * exec_for_query --- execute body of FOR loop for each row from a portal
5895 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
5898 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
5899 Portal portal, bool prefetch_ok)
5901 PLpgSQL_variable *var;
5902 SPITupleTable *tuptab;
5904 int rc = PLPGSQL_RC_OK;
5905 uint64 previous_id = INVALID_TUPLEDESC_IDENTIFIER;
5906 bool tupdescs_match = true;
5909 /* Fetch loop variable's datum entry */
5910 var = (PLpgSQL_variable *) estate->datums[stmt->var->dno];
5913 * Make sure the portal doesn't get closed by the user statements we
5919 * Fetch the initial tuple(s). If prefetching is allowed then we grab a
5920 * few more rows to avoid multiple trips through executor startup
5923 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
5924 tuptab = SPI_tuptable;
5928 * If the query didn't return any rows, set the target to NULL and fall
5929 * through with found = false.
5933 exec_move_row(estate, var, NULL, tuptab->tupdesc);
5934 exec_eval_cleanup(estate);
5937 found = true; /* processed at least one tuple */
5946 for (i = 0; i < n; i++)
5949 * Assign the tuple to the target. Here, because we know that all
5950 * loop iterations should be assigning the same tupdesc, we can
5951 * optimize away repeated creations of expanded records with
5952 * identical tupdescs. Testing for changes of er_tupdesc_id is
5953 * reliable even if the loop body contains assignments that
5954 * replace the target's value entirely, because it's assigned from
5955 * a process-global counter. The case where the tupdescs don't
5956 * match could possibly be handled more efficiently than this
5957 * coding does, but it's not clear extra effort is worthwhile.
5959 if (var->dtype == PLPGSQL_DTYPE_REC)
5961 PLpgSQL_rec *rec = (PLpgSQL_rec *) var;
5964 rec->erh->er_tupdesc_id == previous_id &&
5967 /* Only need to assign a new tuple value */
5968 expanded_record_set_tuple(rec->erh, tuptab->vals[i],
5969 true, !estate->atomic);
5974 * First time through, or var's tupdesc changed in loop,
5975 * or we have to do it the hard way because type coercion
5978 exec_move_row(estate, var,
5979 tuptab->vals[i], tuptab->tupdesc);
5982 * Check to see if physical assignment is OK next time.
5983 * Once the tupdesc comparison has failed once, we don't
5984 * bother rechecking in subsequent loop iterations.
5989 (rec->rectypeid == RECORDOID ||
5990 rec->rectypeid == tuptab->tupdesc->tdtypeid ||
5991 compatible_tupdescs(tuptab->tupdesc,
5992 expanded_record_get_tupdesc(rec->erh)));
5994 previous_id = rec->erh->er_tupdesc_id;
5998 exec_move_row(estate, var, tuptab->vals[i], tuptab->tupdesc);
6000 exec_eval_cleanup(estate);
6003 * Execute the statements
6005 rc = exec_stmts(estate, stmt->body);
6007 LOOP_RC_PROCESSING(stmt->label, goto loop_exit);
6010 SPI_freetuptable(tuptab);
6013 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
6015 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
6016 tuptab = SPI_tuptable;
6023 * Release last group of tuples (if any)
6025 SPI_freetuptable(tuptab);
6027 UnpinPortal(portal);
6030 * Set the FOUND variable to indicate the result of executing the loop
6031 * (namely, whether we looped one or more times). This must be set last so
6032 * that it does not interfere with the value of the FOUND variable inside
6033 * the loop processing itself.
6035 exec_set_found(estate, found);
6042 * exec_eval_simple_expr - Evaluate a simple expression returning
6043 * a Datum by directly calling ExecEvalExpr().
6045 * If successful, store results into *result, *isNull, *rettype, *rettypmod
6046 * and return true. If the expression cannot be handled by simple evaluation,
6049 * Because we only store one execution tree for a simple expression, we
6050 * can't handle recursion cases. So, if we see the tree is already busy
6051 * with an evaluation in the current xact, we just return false and let the
6052 * caller run the expression the hard way. (Other alternatives such as
6053 * creating a new tree for a recursive call either introduce memory leaks,
6054 * or add enough bookkeeping to be doubtful wins anyway.) Another case that
6055 * is covered by the expr_simple_in_use test is where a previous execution
6056 * of the tree was aborted by an error: the tree may contain bogus state
6057 * so we dare not re-use it.
6059 * It is possible that we'd need to replan a simple expression; for example,
6060 * someone might redefine a SQL function that had been inlined into the simple
6061 * expression. That cannot cause a simple expression to become non-simple (or
6062 * vice versa), but we do have to handle replacing the expression tree.
6063 * Fortunately it's normally inexpensive to call SPI_plan_get_cached_plan for
6064 * a simple expression.
6066 * Note: if pass-by-reference, the result is in the eval_mcontext.
6067 * It will be freed when exec_eval_cleanup is done.
6071 exec_eval_simple_expr(PLpgSQL_execstate *estate,
6078 ExprContext *econtext = estate->eval_econtext;
6079 LocalTransactionId curlxid = MyProc->lxid;
6081 void *save_setup_arg;
6082 MemoryContext oldcontext;
6085 * Forget it if expression wasn't simple before.
6087 if (expr->expr_simple_expr == NULL)
6091 * If expression is in use in current xact, don't touch it.
6093 if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
6097 * Revalidate cached plan, so that we will notice if it became stale. (We
6098 * need to hold a refcount while using the plan, anyway.) If replanning
6099 * is needed, do that work in the eval_mcontext.
6101 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6102 cplan = SPI_plan_get_cached_plan(expr->plan);
6103 MemoryContextSwitchTo(oldcontext);
6106 * We can't get a failure here, because the number of CachedPlanSources in
6107 * the SPI plan can't change from what exec_simple_check_plan saw; it's a
6108 * property of the raw parsetree generated from the query text.
6110 Assert(cplan != NULL);
6112 /* If it got replanned, update our copy of the simple expression */
6113 if (cplan->generation != expr->expr_simple_generation)
6115 exec_save_simple_expr(expr, cplan);
6116 /* better recheck r/w safety, as it could change due to inlining */
6117 if (expr->rwparam >= 0)
6118 exec_check_rw_parameter(expr, expr->rwparam);
6122 * Pass back previously-determined result type.
6124 *rettype = expr->expr_simple_type;
6125 *rettypmod = expr->expr_simple_typmod;
6128 * Set up ParamListInfo to pass to executor. For safety, save and restore
6129 * estate->paramLI->parserSetupArg around our use of the param list.
6131 save_setup_arg = estate->paramLI->parserSetupArg;
6133 econtext->ecxt_param_list_info = setup_param_list(estate, expr);
6136 * Prepare the expression for execution, if it's not been done already in
6137 * the current transaction. (This will be forced to happen if we called
6138 * exec_save_simple_expr above.)
6140 if (expr->expr_simple_lxid != curlxid)
6142 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
6143 expr->expr_simple_state =
6144 ExecInitExprWithParams(expr->expr_simple_expr,
6145 econtext->ecxt_param_list_info);
6146 expr->expr_simple_in_use = false;
6147 expr->expr_simple_lxid = curlxid;
6148 MemoryContextSwitchTo(oldcontext);
6152 * We have to do some of the things SPI_execute_plan would do, in
6153 * particular advance the snapshot if we are in a non-read-only function.
6154 * Without this, stable functions within the expression would fail to see
6155 * updates made so far by our own function.
6157 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6158 if (!estate->readonly_func)
6160 CommandCounterIncrement();
6161 PushActiveSnapshot(GetTransactionSnapshot());
6165 * Mark expression as busy for the duration of the ExecEvalExpr call.
6167 expr->expr_simple_in_use = true;
6170 * Finally we can call the executor to evaluate the expression
6172 *result = ExecEvalExpr(expr->expr_simple_state,
6176 /* Assorted cleanup */
6177 expr->expr_simple_in_use = false;
6179 econtext->ecxt_param_list_info = NULL;
6181 estate->paramLI->parserSetupArg = save_setup_arg;
6183 if (!estate->readonly_func)
6184 PopActiveSnapshot();
6186 MemoryContextSwitchTo(oldcontext);
6189 * Now we can release our refcount on the cached plan.
6191 ReleaseCachedPlan(cplan, true);
6201 * Create a ParamListInfo to pass to SPI
6203 * We use a single ParamListInfo struct for all SPI calls made from this
6204 * estate; it contains no per-param data, just hook functions, so it's
6205 * effectively read-only for SPI.
6207 * An exception from pure read-only-ness is that the parserSetupArg points
6208 * to the specific PLpgSQL_expr being evaluated. This is not an issue for
6209 * statement-level callers, but lower-level callers must save and restore
6210 * estate->paramLI->parserSetupArg just in case there's an active evaluation
6211 * at an outer call level. (A plausible alternative design would be to
6212 * create a ParamListInfo struct for each PLpgSQL_expr, but for the moment
6213 * that seems like a waste of memory.)
6215 static ParamListInfo
6216 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
6218 ParamListInfo paramLI;
6221 * We must have created the SPIPlan already (hence, query text has been
6222 * parsed/analyzed at least once); else we cannot rely on expr->paramnos.
6224 Assert(expr->plan != NULL);
6227 * We only need a ParamListInfo if the expression has parameters. In
6228 * principle we should test with bms_is_empty(), but we use a not-null
6229 * test because it's faster. In current usage bits are never removed from
6230 * expr->paramnos, only added, so this test is correct anyway.
6234 /* Use the common ParamListInfo */
6235 paramLI = estate->paramLI;
6238 * Set up link to active expr where the hook functions can find it.
6239 * Callers must save and restore parserSetupArg if there is any chance
6240 * that they are interrupting an active use of parameters.
6242 paramLI->parserSetupArg = (void *) expr;
6245 * Also make sure this is set before parser hooks need it. There is
6246 * no need to save and restore, since the value is always correct once
6247 * set. (Should be set already, but let's be sure.)
6249 expr->func = estate->func;
6254 * Expression requires no parameters. Be sure we represent this case
6255 * as a NULL ParamListInfo, so that plancache.c knows there is no
6256 * point in a custom plan.
6264 * plpgsql_param_fetch paramFetch callback for dynamic parameter fetch
6266 * We always use the caller's workspace to construct the returned struct.
6268 * Note: this is no longer used during query execution. It is used during
6269 * planning (with speculative == true) and when the ParamListInfo we supply
6270 * to the executor is copied into a cursor portal or transferred to a
6271 * parallel child process.
6273 static ParamExternData *
6274 plpgsql_param_fetch(ParamListInfo params,
6275 int paramid, bool speculative,
6276 ParamExternData *prm)
6279 PLpgSQL_execstate *estate;
6281 PLpgSQL_datum *datum;
6285 /* paramid's are 1-based, but dnos are 0-based */
6287 Assert(dno >= 0 && dno < params->numParams);
6289 /* fetch back the hook data */
6290 estate = (PLpgSQL_execstate *) params->paramFetchArg;
6291 expr = (PLpgSQL_expr *) params->parserSetupArg;
6292 Assert(params->numParams == estate->ndatums);
6294 /* now we can access the target datum */
6295 datum = estate->datums[dno];
6298 * Since copyParamList() or SerializeParamList() will try to materialize
6299 * every single parameter slot, it's important to return a dummy param
6300 * when asked for a datum that's not supposed to be used by this SQL
6301 * expression. Otherwise we risk failures in exec_eval_datum(), or
6302 * copying a lot more data than necessary.
6304 if (!bms_is_member(dno, expr->paramnos))
6308 * If the access is speculative, we prefer to return no data rather than
6309 * to fail in exec_eval_datum(). Check the likely failure cases.
6311 else if (speculative)
6313 switch (datum->dtype)
6315 case PLPGSQL_DTYPE_VAR:
6316 case PLPGSQL_DTYPE_PROMISE:
6320 case PLPGSQL_DTYPE_ROW:
6321 /* should be safe in all interesting cases */
6324 case PLPGSQL_DTYPE_REC:
6325 /* always safe (might return NULL, that's fine) */
6328 case PLPGSQL_DTYPE_RECFIELD:
6330 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
6333 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
6336 * If record variable is NULL, don't risk anything.
6338 if (rec->erh == NULL)
6342 * Look up the field's properties if we have not already,
6343 * or if the tuple descriptor ID changed since last time.
6345 else if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
6347 if (expanded_record_lookup_field(rec->erh,
6348 recfield->fieldname,
6350 recfield->rectupledescid = rec->erh->er_tupdesc_id;
6363 /* Return "no such parameter" if not ok */
6366 prm->value = (Datum) 0;
6369 prm->ptype = InvalidOid;
6373 /* OK, evaluate the value and store into the return struct */
6374 exec_eval_datum(estate, datum,
6375 &prm->ptype, &prmtypmod,
6376 &prm->value, &prm->isnull);
6377 /* We can always mark params as "const" for executor's purposes */
6378 prm->pflags = PARAM_FLAG_CONST;
6381 * If it's a read/write expanded datum, convert reference to read-only,
6382 * unless it's safe to pass as read-write.
6384 if (dno != expr->rwparam)
6386 if (datum->dtype == PLPGSQL_DTYPE_VAR)
6387 prm->value = MakeExpandedObjectReadOnly(prm->value,
6389 ((PLpgSQL_var *) datum)->datatype->typlen);
6390 else if (datum->dtype == PLPGSQL_DTYPE_REC)
6391 prm->value = MakeExpandedObjectReadOnly(prm->value,
6400 * plpgsql_param_compile paramCompile callback for plpgsql parameters
6403 plpgsql_param_compile(ParamListInfo params, Param *param,
6405 Datum *resv, bool *resnull)
6407 PLpgSQL_execstate *estate;
6410 PLpgSQL_datum *datum;
6411 ExprEvalStep scratch;
6413 /* fetch back the hook data */
6414 estate = (PLpgSQL_execstate *) params->paramFetchArg;
6415 expr = (PLpgSQL_expr *) params->parserSetupArg;
6417 /* paramid's are 1-based, but dnos are 0-based */
6418 dno = param->paramid - 1;
6419 Assert(dno >= 0 && dno < estate->ndatums);
6421 /* now we can access the target datum */
6422 datum = estate->datums[dno];
6424 scratch.opcode = EEOP_PARAM_CALLBACK;
6425 scratch.resvalue = resv;
6426 scratch.resnull = resnull;
6429 * Select appropriate eval function. It seems worth special-casing
6430 * DTYPE_VAR and DTYPE_RECFIELD for performance. Also, we can determine
6431 * in advance whether MakeExpandedObjectReadOnly() will be required.
6432 * Currently, only VAR/PROMISE and REC datums could contain read/write
6435 if (datum->dtype == PLPGSQL_DTYPE_VAR)
6437 if (dno != expr->rwparam &&
6438 ((PLpgSQL_var *) datum)->datatype->typlen == -1)
6439 scratch.d.cparam.paramfunc = plpgsql_param_eval_var_ro;
6441 scratch.d.cparam.paramfunc = plpgsql_param_eval_var;
6443 else if (datum->dtype == PLPGSQL_DTYPE_RECFIELD)
6444 scratch.d.cparam.paramfunc = plpgsql_param_eval_recfield;
6445 else if (datum->dtype == PLPGSQL_DTYPE_PROMISE)
6447 if (dno != expr->rwparam &&
6448 ((PLpgSQL_var *) datum)->datatype->typlen == -1)
6449 scratch.d.cparam.paramfunc = plpgsql_param_eval_generic_ro;
6451 scratch.d.cparam.paramfunc = plpgsql_param_eval_generic;
6453 else if (datum->dtype == PLPGSQL_DTYPE_REC &&
6454 dno != expr->rwparam)
6455 scratch.d.cparam.paramfunc = plpgsql_param_eval_generic_ro;
6457 scratch.d.cparam.paramfunc = plpgsql_param_eval_generic;
6460 * Note: it's tempting to use paramarg to store the estate pointer and
6461 * thereby save an indirection or two in the eval functions. But that
6462 * doesn't work because the compiled expression might be used with
6463 * different estates for the same PL/pgSQL function.
6465 scratch.d.cparam.paramarg = NULL;
6466 scratch.d.cparam.paramid = param->paramid;
6467 scratch.d.cparam.paramtype = param->paramtype;
6468 ExprEvalPushStep(state, &scratch);
6472 * plpgsql_param_eval_var evaluation of EEOP_PARAM_CALLBACK step
6474 * This is specialized to the case of DTYPE_VAR variables for which
6475 * we do not need to invoke MakeExpandedObjectReadOnly.
6478 plpgsql_param_eval_var(ExprState *state, ExprEvalStep *op,
6479 ExprContext *econtext)
6481 ParamListInfo params;
6482 PLpgSQL_execstate *estate;
6483 int dno = op->d.cparam.paramid - 1;
6486 /* fetch back the hook data */
6487 params = econtext->ecxt_param_list_info;
6488 estate = (PLpgSQL_execstate *) params->paramFetchArg;
6489 Assert(dno >= 0 && dno < estate->ndatums);
6491 /* now we can access the target datum */
6492 var = (PLpgSQL_var *) estate->datums[dno];
6493 Assert(var->dtype == PLPGSQL_DTYPE_VAR);
6495 /* inlined version of exec_eval_datum() */
6496 *op->resvalue = var->value;
6497 *op->resnull = var->isnull;
6499 /* safety check -- an assertion should be sufficient */
6500 Assert(var->datatype->typoid == op->d.cparam.paramtype);
6504 * plpgsql_param_eval_var_ro evaluation of EEOP_PARAM_CALLBACK step
6506 * This is specialized to the case of DTYPE_VAR variables for which
6507 * we need to invoke MakeExpandedObjectReadOnly.
6510 plpgsql_param_eval_var_ro(ExprState *state, ExprEvalStep *op,
6511 ExprContext *econtext)
6513 ParamListInfo params;
6514 PLpgSQL_execstate *estate;
6515 int dno = op->d.cparam.paramid - 1;
6518 /* fetch back the hook data */
6519 params = econtext->ecxt_param_list_info;
6520 estate = (PLpgSQL_execstate *) params->paramFetchArg;
6521 Assert(dno >= 0 && dno < estate->ndatums);
6523 /* now we can access the target datum */
6524 var = (PLpgSQL_var *) estate->datums[dno];
6525 Assert(var->dtype == PLPGSQL_DTYPE_VAR);
6528 * Inlined version of exec_eval_datum() ... and while we're at it, force
6529 * expanded datums to read-only.
6531 *op->resvalue = MakeExpandedObjectReadOnly(var->value,
6534 *op->resnull = var->isnull;
6536 /* safety check -- an assertion should be sufficient */
6537 Assert(var->datatype->typoid == op->d.cparam.paramtype);
6541 * plpgsql_param_eval_recfield evaluation of EEOP_PARAM_CALLBACK step
6543 * This is specialized to the case of DTYPE_RECFIELD variables, for which
6544 * we never need to invoke MakeExpandedObjectReadOnly.
6547 plpgsql_param_eval_recfield(ExprState *state, ExprEvalStep *op,
6548 ExprContext *econtext)
6550 ParamListInfo params;
6551 PLpgSQL_execstate *estate;
6552 int dno = op->d.cparam.paramid - 1;
6553 PLpgSQL_recfield *recfield;
6555 ExpandedRecordHeader *erh;
6557 /* fetch back the hook data */
6558 params = econtext->ecxt_param_list_info;
6559 estate = (PLpgSQL_execstate *) params->paramFetchArg;
6560 Assert(dno >= 0 && dno < estate->ndatums);
6562 /* now we can access the target datum */
6563 recfield = (PLpgSQL_recfield *) estate->datums[dno];
6564 Assert(recfield->dtype == PLPGSQL_DTYPE_RECFIELD);
6566 /* inline the relevant part of exec_eval_datum */
6567 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
6571 * If record variable is NULL, instantiate it if it has a named composite
6572 * type, else complain. (This won't change the logical state of the
6573 * record: it's still NULL.)
6577 instantiate_empty_record_variable(estate, rec);
6582 * Look up the field's properties if we have not already, or if the tuple
6583 * descriptor ID changed since last time.
6585 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
6587 if (!expanded_record_lookup_field(erh,
6588 recfield->fieldname,
6591 (errcode(ERRCODE_UNDEFINED_COLUMN),
6592 errmsg("record \"%s\" has no field \"%s\"",
6593 rec->refname, recfield->fieldname)));
6594 recfield->rectupledescid = erh->er_tupdesc_id;
6597 /* OK to fetch the field value. */
6598 *op->resvalue = expanded_record_get_field(erh,
6599 recfield->finfo.fnumber,
6602 /* safety check -- needed for, eg, record fields */
6603 if (unlikely(recfield->finfo.ftypeid != op->d.cparam.paramtype))
6605 (errcode(ERRCODE_DATATYPE_MISMATCH),
6606 errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
6607 op->d.cparam.paramid,
6608 format_type_be(recfield->finfo.ftypeid),
6609 format_type_be(op->d.cparam.paramtype))));
6613 * plpgsql_param_eval_generic evaluation of EEOP_PARAM_CALLBACK step
6615 * This handles all variable types, but assumes we do not need to invoke
6616 * MakeExpandedObjectReadOnly.
6619 plpgsql_param_eval_generic(ExprState *state, ExprEvalStep *op,
6620 ExprContext *econtext)
6622 ParamListInfo params;
6623 PLpgSQL_execstate *estate;
6624 int dno = op->d.cparam.paramid - 1;
6625 PLpgSQL_datum *datum;
6629 /* fetch back the hook data */
6630 params = econtext->ecxt_param_list_info;
6631 estate = (PLpgSQL_execstate *) params->paramFetchArg;
6632 Assert(dno >= 0 && dno < estate->ndatums);
6634 /* now we can access the target datum */
6635 datum = estate->datums[dno];
6637 /* fetch datum's value */
6638 exec_eval_datum(estate, datum,
6639 &datumtype, &datumtypmod,
6640 op->resvalue, op->resnull);
6642 /* safety check -- needed for, eg, record fields */
6643 if (unlikely(datumtype != op->d.cparam.paramtype))
6645 (errcode(ERRCODE_DATATYPE_MISMATCH),
6646 errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
6647 op->d.cparam.paramid,
6648 format_type_be(datumtype),
6649 format_type_be(op->d.cparam.paramtype))));
6653 * plpgsql_param_eval_generic_ro evaluation of EEOP_PARAM_CALLBACK step
6655 * This handles all variable types, but assumes we need to invoke
6656 * MakeExpandedObjectReadOnly (hence, variable must be of a varlena type).
6659 plpgsql_param_eval_generic_ro(ExprState *state, ExprEvalStep *op,
6660 ExprContext *econtext)
6662 ParamListInfo params;
6663 PLpgSQL_execstate *estate;
6664 int dno = op->d.cparam.paramid - 1;
6665 PLpgSQL_datum *datum;
6669 /* fetch back the hook data */
6670 params = econtext->ecxt_param_list_info;
6671 estate = (PLpgSQL_execstate *) params->paramFetchArg;
6672 Assert(dno >= 0 && dno < estate->ndatums);
6674 /* now we can access the target datum */
6675 datum = estate->datums[dno];
6677 /* fetch datum's value */
6678 exec_eval_datum(estate, datum,
6679 &datumtype, &datumtypmod,
6680 op->resvalue, op->resnull);
6682 /* safety check -- needed for, eg, record fields */
6683 if (unlikely(datumtype != op->d.cparam.paramtype))
6685 (errcode(ERRCODE_DATATYPE_MISMATCH),
6686 errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
6687 op->d.cparam.paramid,
6688 format_type_be(datumtype),
6689 format_type_be(op->d.cparam.paramtype))));
6691 /* force the value to read-only */
6692 *op->resvalue = MakeExpandedObjectReadOnly(*op->resvalue,
6699 * exec_move_row Move one tuple's values into a record or row
6701 * tup and tupdesc may both be NULL if we're just assigning an indeterminate
6702 * composite NULL to the target. Alternatively, can have tup be NULL and
6703 * tupdesc not NULL, in which case we assign a row of NULLs to the target.
6705 * Since this uses the mcontext for workspace, caller should eventually call
6706 * exec_eval_cleanup to prevent long-term memory leaks.
6709 exec_move_row(PLpgSQL_execstate *estate,
6710 PLpgSQL_variable *target,
6711 HeapTuple tup, TupleDesc tupdesc)
6713 ExpandedRecordHeader *newerh = NULL;
6716 * If target is RECORD, we may be able to avoid field-by-field processing.
6718 if (target->dtype == PLPGSQL_DTYPE_REC)
6720 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
6723 * If we have no source tupdesc, just set the record variable to NULL.
6724 * (If we have a source tupdesc but not a tuple, we'll set the
6725 * variable to a row of nulls, instead. This is odd perhaps, but
6726 * backwards compatible.)
6728 if (tupdesc == NULL)
6730 if (rec->datatype &&
6731 rec->datatype->typtype == TYPTYPE_DOMAIN)
6734 * If it's a composite domain, NULL might not be a legal
6735 * value, so we instead need to make an empty expanded record
6736 * and ensure that domain type checking gets done. If there
6737 * is already an expanded record, piggyback on its lookups.
6739 newerh = make_expanded_record_for_rec(estate, rec,
6741 expanded_record_set_tuple(newerh, NULL, false, false);
6742 assign_record_var(estate, rec, newerh);
6746 /* Just clear it to NULL */
6748 DeleteExpandedObject(ExpandedRecordGetDatum(rec->erh));
6755 * Build a new expanded record with appropriate tupdesc.
6757 newerh = make_expanded_record_for_rec(estate, rec, tupdesc, NULL);
6760 * If the rowtypes match, or if we have no tuple anyway, we can
6761 * complete the assignment without field-by-field processing.
6763 * The tests here are ordered more or less in order of cheapness. We
6764 * can easily detect it will work if the target is declared RECORD or
6765 * has the same typeid as the source. But when assigning from a query
6766 * result, it's common to have a source tupdesc that's labeled RECORD
6767 * but is actually physically compatible with a named-composite-type
6768 * target, so it's worth spending extra cycles to check for that.
6770 if (rec->rectypeid == RECORDOID ||
6771 rec->rectypeid == tupdesc->tdtypeid ||
6772 !HeapTupleIsValid(tup) ||
6773 compatible_tupdescs(tupdesc, expanded_record_get_tupdesc(newerh)))
6775 if (!HeapTupleIsValid(tup))
6777 /* No data, so force the record into all-nulls state */
6778 deconstruct_expanded_record(newerh);
6782 /* No coercion is needed, so just assign the row value */
6783 expanded_record_set_tuple(newerh, tup, true, !estate->atomic);
6786 /* Complete the assignment */
6787 assign_record_var(estate, rec, newerh);
6794 * Otherwise, deconstruct the tuple and do field-by-field assignment,
6795 * using exec_move_row_from_fields.
6797 if (tupdesc && HeapTupleIsValid(tup))
6799 int td_natts = tupdesc->natts;
6802 Datum values_local[64];
6803 bool nulls_local[64];
6806 * Need workspace arrays. If td_natts is small enough, use local
6807 * arrays to save doing a palloc. Even if it's not small, we can
6808 * allocate both the Datum and isnull arrays in one palloc chunk.
6810 if (td_natts <= lengthof(values_local))
6812 values = values_local;
6813 nulls = nulls_local;
6819 chunk = eval_mcontext_alloc(estate,
6820 td_natts * (sizeof(Datum) + sizeof(bool)));
6821 values = (Datum *) chunk;
6822 nulls = (bool *) (chunk + td_natts * sizeof(Datum));
6825 heap_deform_tuple(tup, tupdesc, values, nulls);
6827 exec_move_row_from_fields(estate, target, newerh,
6828 values, nulls, tupdesc);
6835 exec_move_row_from_fields(estate, target, newerh,
6841 * Verify that a PLpgSQL_rec's rectypeid is up-to-date.
6844 revalidate_rectypeid(PLpgSQL_rec *rec)
6846 PLpgSQL_type *typ = rec->datatype;
6847 TypeCacheEntry *typentry;
6849 if (rec->rectypeid == RECORDOID)
6850 return; /* it's RECORD, so nothing to do */
6851 Assert(typ != NULL);
6853 typ->tcache->tupDesc_identifier == typ->tupdesc_id)
6854 return; /* known up-to-date */
6857 * typcache entry has suffered invalidation, so re-look-up the type name
6858 * if possible, and then recheck the type OID. If we don't have a
6859 * TypeName, then we just have to soldier on with the OID we've got.
6861 if (typ->origtypname != NULL)
6863 /* this bit should match parse_datatype() in pl_gram.y */
6864 typenameTypeIdAndMod(NULL, typ->origtypname,
6869 /* this bit should match build_datatype() in pl_comp.c */
6870 typentry = lookup_type_cache(typ->typoid,
6872 TYPECACHE_DOMAIN_BASE_INFO);
6873 if (typentry->typtype == TYPTYPE_DOMAIN)
6874 typentry = lookup_type_cache(typentry->domainBaseType,
6876 if (typentry->tupDesc == NULL)
6879 * If we get here, user tried to replace a composite type with a
6880 * non-composite one. We're not gonna support that.
6883 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
6884 errmsg("type %s is not composite",
6885 format_type_be(typ->typoid))));
6889 * Update tcache and tupdesc_id. Since we don't support changing to a
6890 * non-composite type, none of the rest of *typ needs to change.
6892 typ->tcache = typentry;
6893 typ->tupdesc_id = typentry->tupDesc_identifier;
6896 * Update *rec, too. (We'll deal with subsidiary RECFIELDs as needed.)
6898 rec->rectypeid = typ->typoid;
6902 * Build an expanded record object suitable for assignment to "rec".
6904 * Caller must supply either a source tuple descriptor or a source expanded
6905 * record (not both). If the record variable has declared type RECORD,
6906 * it'll adopt the source's rowtype. Even if it doesn't, we may be able to
6907 * piggyback on a source expanded record to save a typcache lookup.
6909 * Caller must fill the object with data, then do assign_record_var().
6911 * The new record is initially put into the mcontext, so it will be cleaned up
6912 * if we fail before reaching assign_record_var().
6914 static ExpandedRecordHeader *
6915 make_expanded_record_for_rec(PLpgSQL_execstate *estate,
6917 TupleDesc srctupdesc,
6918 ExpandedRecordHeader *srcerh)
6920 ExpandedRecordHeader *newerh;
6921 MemoryContext mcontext = get_eval_mcontext(estate);
6923 if (rec->rectypeid != RECORDOID)
6926 * Make sure rec->rectypeid is up-to-date before using it.
6928 revalidate_rectypeid(rec);
6931 * New record must be of desired type, but maybe srcerh has already
6932 * done all the same lookups.
6934 if (srcerh && rec->rectypeid == srcerh->er_decltypeid)
6935 newerh = make_expanded_record_from_exprecord(srcerh,
6938 newerh = make_expanded_record_from_typeid(rec->rectypeid, -1,
6944 * We'll adopt the input tupdesc. We can still use
6945 * make_expanded_record_from_exprecord, if srcerh isn't a composite
6946 * domain. (If it is, we effectively adopt its base type.)
6948 if (srcerh && !ExpandedRecordIsDomain(srcerh))
6949 newerh = make_expanded_record_from_exprecord(srcerh,
6954 srctupdesc = expanded_record_get_tupdesc(srcerh);
6955 newerh = make_expanded_record_from_tupdesc(srctupdesc,
6964 * exec_move_row_from_fields Move arrays of field values into a record or row
6966 * When assigning to a record, the caller must have already created a suitable
6967 * new expanded record object, newerh. Pass NULL when assigning to a row.
6969 * tupdesc describes the input row, which might have different column
6970 * types and/or different dropped-column positions than the target.
6971 * values/nulls/tupdesc can all be NULL if we just want to assign nulls to
6972 * all fields of the record or row.
6974 * Since this uses the mcontext for workspace, caller should eventually call
6975 * exec_eval_cleanup to prevent long-term memory leaks.
6978 exec_move_row_from_fields(PLpgSQL_execstate *estate,
6979 PLpgSQL_variable *target,
6980 ExpandedRecordHeader *newerh,
6981 Datum *values, bool *nulls,
6984 int td_natts = tupdesc ? tupdesc->natts : 0;
6987 int strict_multiassignment_level = 0;
6990 * The extra check strict strict_multi_assignment can be active, only when
6991 * input tupdesc is specified.
6993 if (tupdesc != NULL)
6995 if (plpgsql_extra_errors & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
6996 strict_multiassignment_level = ERROR;
6997 else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
6998 strict_multiassignment_level = WARNING;
7001 /* Handle RECORD-target case */
7002 if (target->dtype == PLPGSQL_DTYPE_REC)
7004 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7005 TupleDesc var_tupdesc;
7006 Datum newvalues_local[64];
7007 bool newnulls_local[64];
7009 Assert(newerh != NULL); /* caller must have built new object */
7011 var_tupdesc = expanded_record_get_tupdesc(newerh);
7014 * Coerce field values if needed. This might involve dealing with
7015 * different sets of dropped columns and/or coercing individual column
7016 * types. That's sort of a pain, but historically plpgsql has allowed
7017 * it, so we preserve the behavior. However, it's worth a quick check
7018 * to see if the tupdescs are identical. (Since expandedrecord.c
7019 * prefers to use refcounted tupdescs from the typcache, expanded
7020 * records with the same rowtype will have pointer-equal tupdescs.)
7022 if (var_tupdesc != tupdesc)
7024 int vtd_natts = var_tupdesc->natts;
7029 * Need workspace arrays. If vtd_natts is small enough, use local
7030 * arrays to save doing a palloc. Even if it's not small, we can
7031 * allocate both the Datum and isnull arrays in one palloc chunk.
7033 if (vtd_natts <= lengthof(newvalues_local))
7035 newvalues = newvalues_local;
7036 newnulls = newnulls_local;
7042 chunk = eval_mcontext_alloc(estate,
7043 vtd_natts * (sizeof(Datum) + sizeof(bool)));
7044 newvalues = (Datum *) chunk;
7045 newnulls = (bool *) (chunk + vtd_natts * sizeof(Datum));
7048 /* Walk over destination columns */
7050 for (fnum = 0; fnum < vtd_natts; fnum++)
7052 Form_pg_attribute attr = TupleDescAttr(var_tupdesc, fnum);
7058 if (attr->attisdropped)
7060 /* expanded_record_set_fields should ignore this column */
7061 continue; /* skip dropped column in record */
7064 while (anum < td_natts &&
7065 TupleDescAttr(tupdesc, anum)->attisdropped)
7066 anum++; /* skip dropped column in tuple */
7068 if (anum < td_natts)
7070 value = values[anum];
7071 isnull = nulls[anum];
7072 valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7073 valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7078 /* no source for destination column */
7081 valtype = UNKNOWNOID;
7084 /* When source value is missing */
7085 if (strict_multiassignment_level)
7086 ereport(strict_multiassignment_level,
7087 (errcode(ERRCODE_DATATYPE_MISMATCH),
7088 errmsg("number of source and target fields in assignment does not match"),
7089 /* translator: %s represents a name of an extra check */
7090 errdetail("%s check of %s is active.",
7091 "strict_multi_assignment",
7092 strict_multiassignment_level == ERROR ? "extra_errors" :
7094 errhint("Make sure the query returns the exact list of columns.")));
7097 /* Cast the new value to the right type, if needed. */
7098 newvalues[fnum] = exec_cast_value(estate,
7105 newnulls[fnum] = isnull;
7109 * When strict_multiassignment extra check is active, then ensure
7110 * there are no unassigned source attributes.
7112 if (strict_multiassignment_level && anum < td_natts)
7114 /* skip dropped columns in the source descriptor */
7115 while (anum < td_natts &&
7116 TupleDescAttr(tupdesc, anum)->attisdropped)
7119 if (anum < td_natts)
7120 ereport(strict_multiassignment_level,
7121 (errcode(ERRCODE_DATATYPE_MISMATCH),
7122 errmsg("number of source and target fields in assignment does not match"),
7123 /* translator: %s represents a name of an extra check */
7124 errdetail("%s check of %s is active.",
7125 "strict_multi_assignment",
7126 strict_multiassignment_level == ERROR ? "extra_errors" :
7128 errhint("Make sure the query returns the exact list of columns.")));
7135 /* Insert the coerced field values into the new expanded record */
7136 expanded_record_set_fields(newerh, values, nulls, !estate->atomic);
7138 /* Complete the assignment */
7139 assign_record_var(estate, rec, newerh);
7144 /* newerh should not have been passed in non-RECORD cases */
7145 Assert(newerh == NULL);
7148 * For a row, we assign the individual field values to the variables the
7151 * NOTE: both this code and the record code above silently ignore extra
7152 * columns in the source and assume NULL for missing columns. This is
7153 * pretty dubious but it's the historical behavior.
7155 * If we have no input data at all, we'll assign NULL to all columns of
7158 if (target->dtype == PLPGSQL_DTYPE_ROW)
7160 PLpgSQL_row *row = (PLpgSQL_row *) target;
7163 for (fnum = 0; fnum < row->nfields; fnum++)
7171 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
7173 while (anum < td_natts &&
7174 TupleDescAttr(tupdesc, anum)->attisdropped)
7175 anum++; /* skip dropped column in tuple */
7177 if (anum < td_natts)
7179 value = values[anum];
7180 isnull = nulls[anum];
7181 valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7182 valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7187 /* no source for destination column */
7190 valtype = UNKNOWNOID;
7193 if (strict_multiassignment_level)
7194 ereport(strict_multiassignment_level,
7195 (errcode(ERRCODE_DATATYPE_MISMATCH),
7196 errmsg("number of source and target fields in assignment does not match"),
7197 /* translator: %s represents a name of an extra check */
7198 errdetail("%s check of %s is active.",
7199 "strict_multi_assignment",
7200 strict_multiassignment_level == ERROR ? "extra_errors" :
7202 errhint("Make sure the query returns the exact list of columns.")));
7205 exec_assign_value(estate, (PLpgSQL_datum *) var,
7206 value, isnull, valtype, valtypmod);
7210 * When strict_multiassignment extra check is active, ensure there are
7211 * no unassigned source attributes.
7213 if (strict_multiassignment_level && anum < td_natts)
7215 while (anum < td_natts &&
7216 TupleDescAttr(tupdesc, anum)->attisdropped)
7217 anum++; /* skip dropped column in tuple */
7219 if (anum < td_natts)
7220 ereport(strict_multiassignment_level,
7221 (errcode(ERRCODE_DATATYPE_MISMATCH),
7222 errmsg("number of source and target fields in assignment does not match"),
7223 /* translator: %s represents a name of an extra check */
7224 errdetail("%s check of %s is active.",
7225 "strict_multi_assignment",
7226 strict_multiassignment_level == ERROR ? "extra_errors" :
7228 errhint("Make sure the query returns the exact list of columns.")));
7234 elog(ERROR, "unsupported target type: %d", target->dtype);
7238 * compatible_tupdescs: detect whether two tupdescs are physically compatible
7240 * TRUE indicates that a tuple satisfying src_tupdesc can be used directly as
7241 * a value for a composite variable using dst_tupdesc.
7244 compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
7248 /* Possibly we could allow src_tupdesc to have extra columns? */
7249 if (dst_tupdesc->natts != src_tupdesc->natts)
7252 for (i = 0; i < dst_tupdesc->natts; i++)
7254 Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
7255 Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
7257 if (dattr->attisdropped != sattr->attisdropped)
7259 if (!dattr->attisdropped)
7261 /* Normal columns must match by type and typmod */
7262 if (dattr->atttypid != sattr->atttypid ||
7263 (dattr->atttypmod >= 0 &&
7264 dattr->atttypmod != sattr->atttypmod))
7269 /* Dropped columns are OK as long as length/alignment match */
7270 if (dattr->attlen != sattr->attlen ||
7271 dattr->attalign != sattr->attalign)
7279 * make_tuple_from_row Make a tuple from the values of a row object
7281 * A NULL return indicates rowtype mismatch; caller must raise suitable error
7283 * The result tuple is freshly palloc'd in caller's context. Some junk
7284 * may be left behind in eval_mcontext, too.
7288 make_tuple_from_row(PLpgSQL_execstate *estate,
7292 int natts = tupdesc->natts;
7298 if (natts != row->nfields)
7301 dvalues = (Datum *) eval_mcontext_alloc0(estate, natts * sizeof(Datum));
7302 nulls = (bool *) eval_mcontext_alloc(estate, natts * sizeof(bool));
7304 for (i = 0; i < natts; i++)
7309 if (TupleDescAttr(tupdesc, i)->attisdropped)
7311 nulls[i] = true; /* leave the column as null */
7315 exec_eval_datum(estate, estate->datums[row->varnos[i]],
7316 &fieldtypeid, &fieldtypmod,
7317 &dvalues[i], &nulls[i]);
7318 if (fieldtypeid != TupleDescAttr(tupdesc, i)->atttypid)
7320 /* XXX should we insist on typmod match, too? */
7323 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
7329 * deconstruct_composite_datum extract tuple+tupdesc from composite Datum
7331 * The caller must supply a HeapTupleData variable, in which we set up a
7332 * tuple header pointing to the composite datum's body. To make the tuple
7333 * value outlive that variable, caller would need to apply heap_copytuple...
7334 * but current callers only need a short-lived tuple value anyway.
7336 * Returns a pointer to the TupleDesc of the datum's rowtype.
7337 * Caller is responsible for calling ReleaseTupleDesc when done with it.
7339 * Note: it's caller's responsibility to be sure value is of composite type.
7340 * Also, best to call this in a short-lived context, as it might leak memory.
7343 deconstruct_composite_datum(Datum value, HeapTupleData *tmptup)
7349 /* Get tuple body (note this could involve detoasting) */
7350 td = DatumGetHeapTupleHeader(value);
7352 /* Build a temporary HeapTuple control structure */
7353 tmptup->t_len = HeapTupleHeaderGetDatumLength(td);
7354 ItemPointerSetInvalid(&(tmptup->t_self));
7355 tmptup->t_tableOid = InvalidOid;
7356 tmptup->t_data = td;
7358 /* Extract rowtype info and find a tupdesc */
7359 tupType = HeapTupleHeaderGetTypeId(td);
7360 tupTypmod = HeapTupleHeaderGetTypMod(td);
7361 return lookup_rowtype_tupdesc(tupType, tupTypmod);
7365 * exec_move_row_from_datum Move a composite Datum into a record or row
7367 * This is equivalent to deconstruct_composite_datum() followed by
7368 * exec_move_row(), but we can optimize things if the Datum is an
7369 * expanded-record reference.
7371 * Note: it's caller's responsibility to be sure value is of composite type.
7374 exec_move_row_from_datum(PLpgSQL_execstate *estate,
7375 PLpgSQL_variable *target,
7378 /* Check to see if source is an expanded record */
7379 if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(value)))
7381 ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(value);
7382 ExpandedRecordHeader *newerh = NULL;
7384 Assert(erh->er_magic == ER_MAGIC);
7386 /* These cases apply if the target is record not row... */
7387 if (target->dtype == PLPGSQL_DTYPE_REC)
7389 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7392 * If it's the same record already stored in the variable, do
7393 * nothing. This would happen only in silly cases like "r := r",
7394 * but we need some check to avoid possibly freeing the variable's
7395 * live value below. Note that this applies even if what we have
7398 if (erh == rec->erh)
7402 * Make sure rec->rectypeid is up-to-date before using it.
7404 revalidate_rectypeid(rec);
7407 * If we have a R/W pointer, we're allowed to just commandeer
7408 * ownership of the expanded record. If it's of the right type to
7409 * put into the record variable, do that. (Note we don't accept
7410 * an expanded record of a composite-domain type as a RECORD
7411 * value. We'll treat it as the base composite type instead;
7412 * compare logic in make_expanded_record_for_rec.)
7414 if (VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(value)) &&
7415 (rec->rectypeid == erh->er_decltypeid ||
7416 (rec->rectypeid == RECORDOID &&
7417 !ExpandedRecordIsDomain(erh))))
7419 assign_record_var(estate, rec, erh);
7424 * If we already have an expanded record object in the target
7425 * variable, and the source record contains a valid tuple
7426 * representation with the right rowtype, then we can skip making
7427 * a new expanded record and just assign the tuple with
7428 * expanded_record_set_tuple. (We can't do the equivalent if we
7429 * have to do field-by-field assignment, since that wouldn't be
7430 * atomic if there's an error.) We consider that there's a
7431 * rowtype match only if it's the same named composite type or
7432 * same registered rowtype; checking for matches of anonymous
7433 * rowtypes would be more expensive than this is worth.
7436 (erh->flags & ER_FLAG_FVALUE_VALID) &&
7437 erh->er_typeid == rec->erh->er_typeid &&
7438 (erh->er_typeid != RECORDOID ||
7439 (erh->er_typmod == rec->erh->er_typmod &&
7440 erh->er_typmod >= 0)))
7442 expanded_record_set_tuple(rec->erh, erh->fvalue,
7443 true, !estate->atomic);
7448 * Otherwise we're gonna need a new expanded record object. Make
7449 * it here in hopes of piggybacking on the source object's
7450 * previous typcache lookup.
7452 newerh = make_expanded_record_for_rec(estate, rec, NULL, erh);
7455 * If the expanded record contains a valid tuple representation,
7456 * and we don't need rowtype conversion, then just copying the
7457 * tuple is probably faster than field-by-field processing. (This
7458 * isn't duplicative of the previous check, since here we will
7459 * catch the case where the record variable was previously empty.)
7461 if ((erh->flags & ER_FLAG_FVALUE_VALID) &&
7462 (rec->rectypeid == RECORDOID ||
7463 rec->rectypeid == erh->er_typeid))
7465 expanded_record_set_tuple(newerh, erh->fvalue,
7466 true, !estate->atomic);
7467 assign_record_var(estate, rec, newerh);
7472 * Need to special-case empty source record, else code below would
7475 if (ExpandedRecordIsEmpty(erh))
7477 /* Set newerh to a row of NULLs */
7478 deconstruct_expanded_record(newerh);
7479 assign_record_var(estate, rec, newerh);
7482 } /* end of record-target-only cases */
7485 * If the source expanded record is empty, we should treat that like a
7486 * NULL tuple value. (We're unlikely to see such a case, but we must
7487 * check this; deconstruct_expanded_record would cause a change of
7488 * logical state, which is not OK.)
7490 if (ExpandedRecordIsEmpty(erh))
7492 exec_move_row(estate, target, NULL,
7493 expanded_record_get_tupdesc(erh));
7498 * Otherwise, ensure that the source record is deconstructed, and
7499 * assign from its field values.
7501 deconstruct_expanded_record(erh);
7502 exec_move_row_from_fields(estate, target, newerh,
7503 erh->dvalues, erh->dnulls,
7504 expanded_record_get_tupdesc(erh));
7509 * Nope, we've got a plain composite Datum. Deconstruct it; but we
7510 * don't use deconstruct_composite_datum(), because we may be able to
7511 * skip calling lookup_rowtype_tupdesc().
7514 HeapTupleData tmptup;
7518 MemoryContext oldcontext;
7520 /* Ensure that any detoasted data winds up in the eval_mcontext */
7521 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7522 /* Get tuple body (note this could involve detoasting) */
7523 td = DatumGetHeapTupleHeader(value);
7524 MemoryContextSwitchTo(oldcontext);
7526 /* Build a temporary HeapTuple control structure */
7527 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
7528 ItemPointerSetInvalid(&(tmptup.t_self));
7529 tmptup.t_tableOid = InvalidOid;
7532 /* Extract rowtype info */
7533 tupType = HeapTupleHeaderGetTypeId(td);
7534 tupTypmod = HeapTupleHeaderGetTypMod(td);
7536 /* Now, if the target is record not row, maybe we can optimize ... */
7537 if (target->dtype == PLPGSQL_DTYPE_REC)
7539 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7542 * If we already have an expanded record object in the target
7543 * variable, and the source datum has a matching rowtype, then we
7544 * can skip making a new expanded record and just assign the tuple
7545 * with expanded_record_set_tuple. We consider that there's a
7546 * rowtype match only if it's the same named composite type or
7547 * same registered rowtype. (Checking to reject an anonymous
7548 * rowtype here should be redundant, but let's be safe.)
7551 tupType == rec->erh->er_typeid &&
7552 (tupType != RECORDOID ||
7553 (tupTypmod == rec->erh->er_typmod &&
7556 expanded_record_set_tuple(rec->erh, &tmptup,
7557 true, !estate->atomic);
7562 * If the source datum has a rowtype compatible with the target
7563 * variable, just build a new expanded record and assign the tuple
7564 * into it. Using make_expanded_record_from_typeid() here saves
7565 * one typcache lookup compared to the code below.
7567 if (rec->rectypeid == RECORDOID || rec->rectypeid == tupType)
7569 ExpandedRecordHeader *newerh;
7570 MemoryContext mcontext = get_eval_mcontext(estate);
7572 newerh = make_expanded_record_from_typeid(tupType, tupTypmod,
7574 expanded_record_set_tuple(newerh, &tmptup,
7575 true, !estate->atomic);
7576 assign_record_var(estate, rec, newerh);
7581 * Otherwise, we're going to need conversion, so fall through to
7582 * do it the hard way.
7587 * ROW target, or unoptimizable RECORD target, so we have to expend a
7588 * lookup to obtain the source datum's tupdesc.
7590 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
7593 exec_move_row(estate, target, &tmptup, tupdesc);
7595 /* Release tupdesc usage count */
7596 ReleaseTupleDesc(tupdesc);
7601 * If we have not created an expanded record to hold the record variable's
7602 * value, do so. The expanded record will be "empty", so this does not
7603 * change the logical state of the record variable: it's still NULL.
7604 * However, now we'll have a tupdesc with which we can e.g. look up fields.
7607 instantiate_empty_record_variable(PLpgSQL_execstate *estate, PLpgSQL_rec *rec)
7609 Assert(rec->erh == NULL); /* else caller error */
7611 /* If declared type is RECORD, we can't instantiate */
7612 if (rec->rectypeid == RECORDOID)
7614 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
7615 errmsg("record \"%s\" is not assigned yet", rec->refname),
7616 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
7618 /* Make sure rec->rectypeid is up-to-date before using it */
7619 revalidate_rectypeid(rec);
7622 rec->erh = make_expanded_record_from_typeid(rec->rectypeid, -1,
7623 estate->datum_context);
7627 * convert_value_to_string Convert a non-null Datum to C string
7629 * Note: the result is in the estate's eval_mcontext, and will be cleared
7630 * by the next exec_eval_cleanup() call. The invoked output function might
7631 * leave additional cruft there as well, so just pfree'ing the result string
7632 * would not be enough to avoid memory leaks if we did not do it like this.
7633 * In most usages the Datum being passed in is also in that context (if
7634 * pass-by-reference) and so an exec_eval_cleanup() call is needed anyway.
7636 * Note: not caching the conversion function lookup is bad for performance.
7637 * However, this function isn't currently used in any places where an extra
7638 * catalog lookup or two seems like a big deal.
7642 convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
7645 MemoryContext oldcontext;
7649 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7650 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
7651 result = OidOutputFunctionCall(typoutput, value);
7652 MemoryContextSwitchTo(oldcontext);
7658 * exec_cast_value Cast a value if required
7660 * Note that *isnull is an input and also an output parameter. While it's
7661 * unlikely that a cast operation would produce null from non-null or vice
7662 * versa, that could happen in principle.
7664 * Note: the estate's eval_mcontext is used for temporary storage, and may
7665 * also contain the result Datum if we have to do a conversion to a pass-
7666 * by-reference data type. Be sure to do an exec_eval_cleanup() call when
7667 * done with the result.
7671 exec_cast_value(PLpgSQL_execstate *estate,
7672 Datum value, bool *isnull,
7673 Oid valtype, int32 valtypmod,
7674 Oid reqtype, int32 reqtypmod)
7677 * If the type of the given value isn't what's requested, convert it.
7679 if (valtype != reqtype ||
7680 (valtypmod != reqtypmod && reqtypmod != -1))
7682 plpgsql_CastHashEntry *cast_entry;
7684 cast_entry = get_cast_hashentry(estate,
7686 reqtype, reqtypmod);
7689 ExprContext *econtext = estate->eval_econtext;
7690 MemoryContext oldcontext;
7692 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7694 econtext->caseValue_datum = value;
7695 econtext->caseValue_isNull = *isnull;
7697 cast_entry->cast_in_use = true;
7699 value = ExecEvalExpr(cast_entry->cast_exprstate, econtext,
7702 cast_entry->cast_in_use = false;
7704 MemoryContextSwitchTo(oldcontext);
7712 * get_cast_hashentry Look up how to perform a type cast
7714 * Returns a plpgsql_CastHashEntry if an expression has to be evaluated,
7715 * or NULL if the cast is a mere no-op relabeling. If there's work to be
7716 * done, the cast_exprstate field contains an expression evaluation tree
7717 * based on a CaseTestExpr input, and the cast_in_use field should be set
7718 * true while executing it.
7721 static plpgsql_CastHashEntry *
7722 get_cast_hashentry(PLpgSQL_execstate *estate,
7723 Oid srctype, int32 srctypmod,
7724 Oid dsttype, int32 dsttypmod)
7726 plpgsql_CastHashKey cast_key;
7727 plpgsql_CastHashEntry *cast_entry;
7729 LocalTransactionId curlxid;
7730 MemoryContext oldcontext;
7732 /* Look for existing entry */
7733 cast_key.srctype = srctype;
7734 cast_key.dsttype = dsttype;
7735 cast_key.srctypmod = srctypmod;
7736 cast_key.dsttypmod = dsttypmod;
7737 cast_entry = (plpgsql_CastHashEntry *) hash_search(estate->cast_hash,
7739 HASH_ENTER, &found);
7740 if (!found) /* initialize if new entry */
7741 cast_entry->cast_cexpr = NULL;
7743 if (cast_entry->cast_cexpr == NULL ||
7744 !cast_entry->cast_cexpr->is_valid)
7747 * We've not looked up this coercion before, or we have but the cached
7748 * expression has been invalidated.
7751 CachedExpression *cast_cexpr;
7752 CaseTestExpr *placeholder;
7755 * Drop old cached expression if there is one.
7757 if (cast_entry->cast_cexpr)
7759 FreeCachedExpression(cast_entry->cast_cexpr);
7760 cast_entry->cast_cexpr = NULL;
7764 * Since we could easily fail (no such coercion), construct a
7765 * temporary coercion expression tree in the short-lived
7766 * eval_mcontext, then if successful save it as a CachedExpression.
7768 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7771 * We use a CaseTestExpr as the base of the coercion tree, since it's
7772 * very cheap to insert the source value for that.
7774 placeholder = makeNode(CaseTestExpr);
7775 placeholder->typeId = srctype;
7776 placeholder->typeMod = srctypmod;
7777 placeholder->collation = get_typcollation(srctype);
7780 * Apply coercion. We use ASSIGNMENT coercion because that's the
7781 * closest match to plpgsql's historical behavior; in particular,
7782 * EXPLICIT coercion would allow silent truncation to a destination
7783 * varchar/bpchar's length, which we do not want.
7785 * If source type is UNKNOWN, coerce_to_target_type will fail (it only
7786 * expects to see that for Const input nodes), so don't call it; we'll
7787 * apply CoerceViaIO instead. Likewise, it doesn't currently work for
7788 * coercing RECORD to some other type, so skip for that too.
7790 if (srctype == UNKNOWNOID || srctype == RECORDOID)
7793 cast_expr = coerce_to_target_type(NULL,
7794 (Node *) placeholder, srctype,
7796 COERCION_ASSIGNMENT,
7797 COERCE_IMPLICIT_CAST,
7801 * If there's no cast path according to the parser, fall back to using
7802 * an I/O coercion; this is semantically dubious but matches plpgsql's
7803 * historical behavior. We would need something of the sort for
7804 * UNKNOWN literals in any case.
7806 if (cast_expr == NULL)
7808 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
7810 iocoerce->arg = (Expr *) placeholder;
7811 iocoerce->resulttype = dsttype;
7812 iocoerce->resultcollid = InvalidOid;
7813 iocoerce->coerceformat = COERCE_IMPLICIT_CAST;
7814 iocoerce->location = -1;
7815 cast_expr = (Node *) iocoerce;
7816 if (dsttypmod != -1)
7817 cast_expr = coerce_to_target_type(NULL,
7820 COERCION_ASSIGNMENT,
7821 COERCE_IMPLICIT_CAST,
7825 /* Note: we don't bother labeling the expression tree with collation */
7827 /* Plan the expression and build a CachedExpression */
7828 cast_cexpr = GetCachedExpression(cast_expr);
7829 cast_expr = cast_cexpr->expr;
7831 /* Detect whether we have a no-op (RelabelType) coercion */
7832 if (IsA(cast_expr, RelabelType) &&
7833 ((RelabelType *) cast_expr)->arg == (Expr *) placeholder)
7836 /* Now we can fill in the hashtable entry. */
7837 cast_entry->cast_cexpr = cast_cexpr;
7838 cast_entry->cast_expr = (Expr *) cast_expr;
7839 cast_entry->cast_exprstate = NULL;
7840 cast_entry->cast_in_use = false;
7841 cast_entry->cast_lxid = InvalidLocalTransactionId;
7843 MemoryContextSwitchTo(oldcontext);
7846 /* Done if we have determined that this is a no-op cast. */
7847 if (cast_entry->cast_expr == NULL)
7851 * Prepare the expression for execution, if it's not been done already in
7852 * the current transaction; also, if it's marked busy in the current
7853 * transaction, abandon that expression tree and build a new one, so as to
7854 * avoid potential problems with recursive cast expressions and failed
7855 * executions. (We will leak some memory intra-transaction if that
7856 * happens a lot, but we don't expect it to.) It's okay to update the
7857 * hash table with the new tree because all plpgsql functions within a
7858 * given transaction share the same simple_eval_estate. (Well, regular
7859 * functions do; DO blocks have private simple_eval_estates, and private
7860 * cast hash tables to go with them.)
7862 curlxid = MyProc->lxid;
7863 if (cast_entry->cast_lxid != curlxid || cast_entry->cast_in_use)
7865 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
7866 cast_entry->cast_exprstate = ExecInitExpr(cast_entry->cast_expr, NULL);
7867 cast_entry->cast_in_use = false;
7868 cast_entry->cast_lxid = curlxid;
7869 MemoryContextSwitchTo(oldcontext);
7877 * exec_simple_check_plan - Check if a plan is simple enough to
7878 * be evaluated by ExecEvalExpr() instead
7883 exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
7886 CachedPlanSource *plansource;
7889 MemoryContext oldcontext;
7892 * Initialize to "not simple".
7894 expr->expr_simple_expr = NULL;
7897 * Check the analyzed-and-rewritten form of the query to see if we will be
7898 * able to treat it as a simple expression. Since this function is only
7899 * called immediately after creating the CachedPlanSource, we need not
7900 * worry about the query being stale.
7904 * We can only test queries that resulted in exactly one CachedPlanSource
7906 plansources = SPI_plan_get_plan_sources(expr->plan);
7907 if (list_length(plansources) != 1)
7909 plansource = (CachedPlanSource *) linitial(plansources);
7912 * 1. There must be one single querytree.
7914 if (list_length(plansource->query_list) != 1)
7916 query = (Query *) linitial(plansource->query_list);
7919 * 2. It must be a plain SELECT query without any input tables
7921 if (!IsA(query, Query))
7923 if (query->commandType != CMD_SELECT)
7925 if (query->rtable != NIL)
7929 * 3. Can't have any subplans, aggregates, qual clauses either. (These
7930 * tests should generally match what inline_function() checks before
7931 * inlining a SQL function; otherwise, inlining could change our
7932 * conclusion about whether an expression is simple, which we don't want.)
7934 if (query->hasAggs ||
7935 query->hasWindowFuncs ||
7936 query->hasTargetSRFs ||
7937 query->hasSubLinks ||
7939 query->jointree->fromlist ||
7940 query->jointree->quals ||
7941 query->groupClause ||
7942 query->groupingSets ||
7943 query->havingQual ||
7944 query->windowClause ||
7945 query->distinctClause ||
7946 query->sortClause ||
7947 query->limitOffset ||
7948 query->limitCount ||
7949 query->setOperations)
7953 * 4. The query must have a single attribute as result
7955 if (list_length(query->targetList) != 1)
7959 * OK, we can treat it as a simple plan.
7961 * Get the generic plan for the query. If replanning is needed, do that
7962 * work in the eval_mcontext.
7964 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7965 cplan = SPI_plan_get_cached_plan(expr->plan);
7966 MemoryContextSwitchTo(oldcontext);
7968 /* Can't fail, because we checked for a single CachedPlanSource above */
7969 Assert(cplan != NULL);
7971 /* Share the remaining work with replan code path */
7972 exec_save_simple_expr(expr, cplan);
7974 /* Release our plan refcount */
7975 ReleaseCachedPlan(cplan, true);
7979 * exec_save_simple_expr --- extract simple expression from CachedPlan
7982 exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
7989 * Given the checks that exec_simple_check_plan did, none of the Asserts
7990 * here should ever fail.
7993 /* Extract the single PlannedStmt */
7994 Assert(list_length(cplan->stmt_list) == 1);
7995 stmt = linitial_node(PlannedStmt, cplan->stmt_list);
7996 Assert(stmt->commandType == CMD_SELECT);
7999 * Ordinarily, the plan node should be a simple Result. However, if
8000 * force_parallel_mode is on, the planner might've stuck a Gather node
8001 * atop that. The simplest way to deal with this is to look through the
8002 * Gather node. The Gather node's tlist would normally contain a Var
8003 * referencing the child node's output, but it could also be a Param, or
8004 * it could be a Const that setrefs.c copied as-is.
8006 plan = stmt->planTree;
8009 /* Extract the single tlist expression */
8010 Assert(list_length(plan->targetlist) == 1);
8011 tle_expr = castNode(TargetEntry, linitial(plan->targetlist))->expr;
8013 if (IsA(plan, Result))
8015 Assert(plan->lefttree == NULL &&
8016 plan->righttree == NULL &&
8017 plan->initPlan == NULL &&
8018 plan->qual == NULL &&
8019 ((Result *) plan)->resconstantqual == NULL);
8022 else if (IsA(plan, Gather))
8024 Assert(plan->lefttree != NULL &&
8025 plan->righttree == NULL &&
8026 plan->initPlan == NULL &&
8027 plan->qual == NULL);
8028 /* If setrefs.c copied up a Const, no need to look further */
8029 if (IsA(tle_expr, Const))
8031 /* Otherwise, it had better be a Param or an outer Var */
8032 Assert(IsA(tle_expr, Param) ||(IsA(tle_expr, Var) &&
8033 ((Var *) tle_expr)->varno == OUTER_VAR));
8034 /* Descend to the child node */
8035 plan = plan->lefttree;
8038 elog(ERROR, "unexpected plan node type: %d",
8039 (int) nodeTag(plan));
8043 * Save the simple expression, and initialize state to "not valid in
8044 * current transaction".
8046 expr->expr_simple_expr = tle_expr;
8047 expr->expr_simple_generation = cplan->generation;
8048 expr->expr_simple_state = NULL;
8049 expr->expr_simple_in_use = false;
8050 expr->expr_simple_lxid = InvalidLocalTransactionId;
8051 /* Also stash away the expression result type */
8052 expr->expr_simple_type = exprType((Node *) tle_expr);
8053 expr->expr_simple_typmod = exprTypmod((Node *) tle_expr);
8057 * exec_check_rw_parameter --- can we pass expanded object as read/write param?
8059 * If we have an assignment like "x := array_append(x, foo)" in which the
8060 * top-level function is trusted not to corrupt its argument in case of an
8061 * error, then when x has an expanded object as value, it is safe to pass the
8062 * value as a read/write pointer and let the function modify the value
8065 * This function checks for a safe expression, and sets expr->rwparam to the
8066 * dno of the target variable (x) if safe, or -1 if not safe.
8069 exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
8079 * If the expression isn't simple, there's no point in trying to optimize
8080 * (because the exec_run_select code path will flatten any expanded result
8081 * anyway). Even without that, this seems like a good safety restriction.
8083 if (expr->expr_simple_expr == NULL)
8087 * If target variable isn't referenced by expression, no need to look
8090 if (!bms_is_member(target_dno, expr->paramnos))
8094 * Top level of expression must be a simple FuncExpr or OpExpr.
8096 if (IsA(expr->expr_simple_expr, FuncExpr))
8098 FuncExpr *fexpr = (FuncExpr *) expr->expr_simple_expr;
8100 funcid = fexpr->funcid;
8101 fargs = fexpr->args;
8103 else if (IsA(expr->expr_simple_expr, OpExpr))
8105 OpExpr *opexpr = (OpExpr *) expr->expr_simple_expr;
8107 funcid = opexpr->opfuncid;
8108 fargs = opexpr->args;
8114 * The top-level function must be one that we trust to be "safe".
8115 * Currently we hard-wire the list, but it would be very desirable to
8116 * allow extensions to mark their functions as safe ...
8118 if (!(funcid == F_ARRAY_APPEND ||
8119 funcid == F_ARRAY_PREPEND))
8123 * The target variable (in the form of a Param) must only appear as a
8124 * direct argument of the top-level function.
8128 Node *arg = (Node *) lfirst(lc);
8130 /* A Param is OK, whether it's the target variable or not */
8131 if (arg && IsA(arg, Param))
8133 /* Otherwise, argument expression must not reference target */
8134 if (contains_target_param(arg, &target_dno))
8138 /* OK, we can pass target as a read-write parameter */
8139 expr->rwparam = target_dno;
8143 * Recursively check for a Param referencing the target variable
8146 contains_target_param(Node *node, int *target_dno)
8150 if (IsA(node, Param))
8152 Param *param = (Param *) node;
8154 if (param->paramkind == PARAM_EXTERN &&
8155 param->paramid == *target_dno + 1)
8159 return expression_tree_walker(node, contains_target_param,
8160 (void *) target_dno);
8164 * exec_set_found Set the global found variable to true/false
8168 exec_set_found(PLpgSQL_execstate *estate, bool state)
8172 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
8173 assign_simple_var(estate, var, BoolGetDatum(state), false, false);
8177 * plpgsql_create_econtext --- create an eval_econtext for the current function
8179 * We may need to create a new shared_simple_eval_estate too, if there's not
8180 * one already for the current transaction. The EState will be cleaned up at
8184 plpgsql_create_econtext(PLpgSQL_execstate *estate)
8186 SimpleEcontextStackEntry *entry;
8189 * Create an EState for evaluation of simple expressions, if there's not
8190 * one already in the current transaction. The EState is made a child of
8191 * TopTransactionContext so it will have the right lifespan.
8193 * Note that this path is never taken when executing a DO block; the
8194 * required EState was already made by plpgsql_inline_handler.
8196 if (estate->simple_eval_estate == NULL)
8198 MemoryContext oldcontext;
8200 if (shared_simple_eval_estate == NULL)
8202 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
8203 shared_simple_eval_estate = CreateExecutorState();
8204 MemoryContextSwitchTo(oldcontext);
8206 estate->simple_eval_estate = shared_simple_eval_estate;
8210 * Create a child econtext for the current function.
8212 estate->eval_econtext = CreateExprContext(estate->simple_eval_estate);
8215 * Make a stack entry so we can clean up the econtext at subxact end.
8216 * Stack entries are kept in TopTransactionContext for simplicity.
8218 entry = (SimpleEcontextStackEntry *)
8219 MemoryContextAlloc(TopTransactionContext,
8220 sizeof(SimpleEcontextStackEntry));
8222 entry->stack_econtext = estate->eval_econtext;
8223 entry->xact_subxid = GetCurrentSubTransactionId();
8225 entry->next = simple_econtext_stack;
8226 simple_econtext_stack = entry;
8230 * plpgsql_destroy_econtext --- destroy function's econtext
8232 * We check that it matches the top stack entry, and destroy the stack
8233 * entry along with the context.
8236 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
8238 SimpleEcontextStackEntry *next;
8240 Assert(simple_econtext_stack != NULL);
8241 Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
8243 next = simple_econtext_stack->next;
8244 pfree(simple_econtext_stack);
8245 simple_econtext_stack = next;
8247 FreeExprContext(estate->eval_econtext, true);
8248 estate->eval_econtext = NULL;
8252 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
8254 * If a simple-expression EState was created in the current transaction,
8255 * it has to be cleaned up.
8258 plpgsql_xact_cb(XactEvent event, void *arg)
8261 * If we are doing a clean transaction shutdown, free the EState (so that
8262 * any remaining resources will be released correctly). In an abort, we
8263 * expect the regular abort recovery procedures to release everything of
8266 if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_PREPARE)
8268 simple_econtext_stack = NULL;
8270 if (shared_simple_eval_estate)
8271 FreeExecutorState(shared_simple_eval_estate);
8272 shared_simple_eval_estate = NULL;
8274 else if (event == XACT_EVENT_ABORT)
8276 simple_econtext_stack = NULL;
8277 shared_simple_eval_estate = NULL;
8282 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
8284 * Make sure any simple-expression econtexts created in the current
8285 * subtransaction get cleaned up. We have to do this explicitly because
8286 * no other code knows which econtexts belong to which level of subxact.
8289 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
8290 SubTransactionId parentSubid, void *arg)
8292 if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)
8294 while (simple_econtext_stack != NULL &&
8295 simple_econtext_stack->xact_subxid == mySubid)
8297 SimpleEcontextStackEntry *next;
8299 FreeExprContext(simple_econtext_stack->stack_econtext,
8300 (event == SUBXACT_EVENT_COMMIT_SUB));
8301 next = simple_econtext_stack->next;
8302 pfree(simple_econtext_stack);
8303 simple_econtext_stack = next;
8309 * assign_simple_var --- assign a new value to any VAR datum.
8311 * This should be the only mechanism for assignment to simple variables,
8312 * lest we do the release of the old value incorrectly (not to mention
8313 * the detoasting business).
8316 assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
8317 Datum newvalue, bool isnull, bool freeable)
8319 Assert(var->dtype == PLPGSQL_DTYPE_VAR ||
8320 var->dtype == PLPGSQL_DTYPE_PROMISE);
8323 * In non-atomic contexts, we do not want to store TOAST pointers in
8324 * variables, because such pointers might become stale after a commit.
8325 * Forcibly detoast in such cases. We don't want to detoast (flatten)
8326 * expanded objects, however; those should be OK across a transaction
8327 * boundary since they're just memory-resident objects. (Elsewhere in
8328 * this module, operations on expanded records likewise need to request
8329 * detoasting of record fields when !estate->atomic. Expanded arrays are
8330 * not a problem since all array entries are always detoasted.)
8332 if (!estate->atomic && !isnull && var->datatype->typlen == -1 &&
8333 VARATT_IS_EXTERNAL_NON_EXPANDED(DatumGetPointer(newvalue)))
8335 MemoryContext oldcxt;
8339 * Do the detoasting in the eval_mcontext to avoid long-term leakage
8340 * of whatever memory toast fetching might leak. Then we have to copy
8341 * the detoasted datum to the function's main context, which is a
8342 * pain, but there's little choice.
8344 oldcxt = MemoryContextSwitchTo(get_eval_mcontext(estate));
8345 detoasted = PointerGetDatum(detoast_external_attr((struct varlena *) DatumGetPointer(newvalue)));
8346 MemoryContextSwitchTo(oldcxt);
8347 /* Now's a good time to not leak the input value if it's freeable */
8349 pfree(DatumGetPointer(newvalue));
8350 /* Once we copy the value, it's definitely freeable */
8351 newvalue = datumCopy(detoasted, false, -1);
8353 /* Can't clean up eval_mcontext here, but it'll happen before long */
8356 /* Free the old value if needed */
8359 if (DatumIsReadWriteExpandedObject(var->value,
8361 var->datatype->typlen))
8362 DeleteExpandedObject(var->value);
8364 pfree(DatumGetPointer(var->value));
8366 /* Assign new value to datum */
8367 var->value = newvalue;
8368 var->isnull = isnull;
8369 var->freeval = freeable;
8372 * If it's a promise variable, then either we just assigned the promised
8373 * value, or the user explicitly assigned an overriding value. Either
8374 * way, cancel the promise.
8376 var->promise = PLPGSQL_PROMISE_NONE;
8380 * free old value of a text variable and assign new value from C string
8383 assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, const char *str)
8385 assign_simple_var(estate, var, CStringGetTextDatum(str), false, true);
8389 * assign_record_var --- assign a new value to any REC datum.
8392 assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec,
8393 ExpandedRecordHeader *erh)
8395 Assert(rec->dtype == PLPGSQL_DTYPE_REC);
8397 /* Transfer new record object into datum_context */
8398 TransferExpandedRecord(erh, estate->datum_context);
8400 /* Free the old value ... */
8402 DeleteExpandedObject(ExpandedRecordGetDatum(rec->erh));
8404 /* ... and install the new */
8409 * exec_eval_using_params --- evaluate params of USING clause
8411 * The result data structure is created in the stmt_mcontext, and should
8412 * be freed by resetting that context.
8414 static PreparedParamsData *
8415 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
8417 PreparedParamsData *ppd;
8418 MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8423 ppd = (PreparedParamsData *)
8424 MemoryContextAlloc(stmt_mcontext, sizeof(PreparedParamsData));
8425 nargs = list_length(params);
8428 ppd->types = (Oid *)
8429 MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Oid));
8430 ppd->values = (Datum *)
8431 MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Datum));
8432 ppd->nulls = (char *)
8433 MemoryContextAlloc(stmt_mcontext, nargs * sizeof(char));
8438 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
8441 MemoryContext oldcontext;
8443 ppd->values[i] = exec_eval_expr(estate, param,
8447 ppd->nulls[i] = isnull ? 'n' : ' ';
8449 oldcontext = MemoryContextSwitchTo(stmt_mcontext);
8451 if (ppd->types[i] == UNKNOWNOID)
8454 * Treat 'unknown' parameters as text, since that's what most
8455 * people would expect. SPI_execute_with_args can coerce unknown
8456 * constants in a more intelligent way, but not unknown Params.
8457 * This code also takes care of copying into the right context.
8458 * Note we assume 'unknown' has the representation of C-string.
8460 ppd->types[i] = TEXTOID;
8462 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
8464 /* pass-by-ref non null values must be copied into stmt_mcontext */
8470 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
8472 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
8475 MemoryContextSwitchTo(oldcontext);
8477 exec_eval_cleanup(estate);
8486 * Open portal for dynamic query
8488 * Caution: this resets the stmt_mcontext at exit. We might eventually need
8489 * to move that responsibility to the callers, but currently no caller needs
8490 * to have statement-lifetime temp data that survives past this, so it's
8491 * simpler to do it here.
8494 exec_dynquery_with_params(PLpgSQL_execstate *estate,
8495 PLpgSQL_expr *dynquery,
8497 const char *portalname,
8506 MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8509 * Evaluate the string expression after the EXECUTE keyword. Its result is
8510 * the querystring we have to execute.
8512 query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
8515 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
8516 errmsg("query string argument of EXECUTE is null")));
8518 /* Get the C-String representation */
8519 querystr = convert_value_to_string(estate, query, restype);
8521 /* copy it into the stmt_mcontext before we clean up */
8522 querystr = MemoryContextStrdup(stmt_mcontext, querystr);
8524 exec_eval_cleanup(estate);
8527 * Open an implicit cursor for the query. We use
8528 * SPI_cursor_open_with_args even when there are no params, because this
8529 * avoids making and freeing one copy of the plan.
8533 PreparedParamsData *ppd;
8535 ppd = exec_eval_using_params(estate, params);
8536 portal = SPI_cursor_open_with_args(portalname,
8538 ppd->nargs, ppd->types,
8539 ppd->values, ppd->nulls,
8540 estate->readonly_func,
8545 portal = SPI_cursor_open_with_args(portalname,
8549 estate->readonly_func,
8554 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
8555 querystr, SPI_result_code_string(SPI_result));
8557 /* Release transient data */
8558 MemoryContextReset(stmt_mcontext);
8564 * Return a formatted string with information about an expression's parameters,
8565 * or NULL if the expression does not take any parameters.
8566 * The result is in the eval_mcontext.
8569 format_expr_params(PLpgSQL_execstate *estate,
8570 const PLpgSQL_expr *expr)
8574 StringInfoData paramstr;
8575 MemoryContext oldcontext;
8577 if (!expr->paramnos)
8580 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
8582 initStringInfo(¶mstr);
8585 while ((dno = bms_next_member(expr->paramnos, dno)) >= 0)
8591 PLpgSQL_var *curvar;
8593 curvar = (PLpgSQL_var *) estate->datums[dno];
8595 exec_eval_datum(estate, (PLpgSQL_datum *) curvar,
8596 ¶mtypeid, ¶mtypmod,
8597 ¶mdatum, ¶misnull);
8599 appendStringInfo(¶mstr, "%s%s = ",
8600 paramno > 0 ? ", " : "",
8604 appendStringInfoString(¶mstr, "NULL");
8607 char *value = convert_value_to_string(estate, paramdatum, paramtypeid);
8610 appendStringInfoCharMacro(¶mstr, '\'');
8611 for (p = value; *p; p++)
8613 if (*p == '\'') /* double single quotes */
8614 appendStringInfoCharMacro(¶mstr, *p);
8615 appendStringInfoCharMacro(¶mstr, *p);
8617 appendStringInfoCharMacro(¶mstr, '\'');
8623 MemoryContextSwitchTo(oldcontext);
8625 return paramstr.data;
8629 * Return a formatted string with information about PreparedParamsData, or NULL
8630 * if there are no parameters.
8631 * The result is in the eval_mcontext.
8634 format_preparedparamsdata(PLpgSQL_execstate *estate,
8635 const PreparedParamsData *ppd)
8638 StringInfoData paramstr;
8639 MemoryContext oldcontext;
8644 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
8646 initStringInfo(¶mstr);
8647 for (paramno = 0; paramno < ppd->nargs; paramno++)
8649 appendStringInfo(¶mstr, "%s$%d = ",
8650 paramno > 0 ? ", " : "",
8653 if (ppd->nulls[paramno] == 'n')
8654 appendStringInfoString(¶mstr, "NULL");
8657 char *value = convert_value_to_string(estate, ppd->values[paramno], ppd->types[paramno]);
8660 appendStringInfoCharMacro(¶mstr, '\'');
8661 for (p = value; *p; p++)
8663 if (*p == '\'') /* double single quotes */
8664 appendStringInfoCharMacro(¶mstr, *p);
8665 appendStringInfoCharMacro(¶mstr, *p);
8667 appendStringInfoCharMacro(¶mstr, '\'');
8671 MemoryContextSwitchTo(oldcontext);
8673 return paramstr.data;