1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2015, 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/htup_details.h"
21 #include "access/transam.h"
22 #include "access/tupconvert.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/spi.h"
27 #include "miscadmin.h"
28 #include "nodes/nodeFuncs.h"
29 #include "optimizer/planner.h"
30 #include "parser/parse_coerce.h"
31 #include "parser/scansup.h"
32 #include "storage/proc.h"
33 #include "tcop/tcopprot.h"
34 #include "utils/array.h"
35 #include "utils/builtins.h"
36 #include "utils/datum.h"
37 #include "utils/lsyscache.h"
38 #include "utils/memutils.h"
39 #include "utils/rel.h"
40 #include "utils/snapmgr.h"
41 #include "utils/typcache.h"
44 static const char *const raise_skip_msg = "RAISE";
48 int nargs; /* number of arguments */
49 Oid *types; /* types of arguments */
50 Datum *values; /* evaluated argument values */
51 char *nulls; /* null markers (' '/'n' style) */
52 bool *freevals; /* which arguments are pfree-able */
57 /* NB: we assume this struct contains no padding bytes */
58 Oid srctype; /* source type for cast */
59 Oid dsttype; /* destination type for cast */
60 int32 dsttypmod; /* destination typmod for cast */
61 } plpgsql_CastHashKey;
65 plpgsql_CastHashKey key; /* hash key --- MUST BE FIRST */
66 ExprState *cast_exprstate; /* cast expression, or NULL if no-op cast */
67 } plpgsql_CastHashEntry;
70 * All plpgsql function executions within a single transaction share the same
71 * executor EState for evaluating "simple" expressions. Each function call
72 * creates its own "eval_econtext" ExprContext within this estate for
73 * per-evaluation workspace. eval_econtext is freed at normal function exit,
74 * and the EState is freed at transaction end (in case of error, we assume
75 * that the abort mechanisms clean it all up). Furthermore, any exception
76 * block within a function has to have its own eval_econtext separate from
77 * the containing function's, so that we can clean up ExprContext callbacks
78 * properly at subtransaction exit. We maintain a stack that tracks the
79 * individual econtexts so that we can clean up correctly at subxact exit.
81 * This arrangement is a bit tedious to maintain, but it's worth the trouble
82 * so that we don't have to re-prepare simple expressions on each trip through
83 * a function. (We assume the case to optimize is many repetitions of a
84 * function within a transaction.)
86 * However, there's no value in trying to amortize simple expression setup
87 * across multiple executions of a DO block (inline code block), since there
88 * can never be any. If we use the shared EState for a DO block, the expr
89 * state trees are effectively leaked till end of transaction, and that can
90 * add up if the user keeps on submitting DO blocks. Therefore, each DO block
91 * has its own simple-expression EState, which is cleaned up at exit from
92 * plpgsql_inline_handler(). DO blocks still use the simple_econtext_stack,
93 * though, so that subxact abort cleanup does the right thing.
95 typedef struct SimpleEcontextStackEntry
97 ExprContext *stack_econtext; /* a stacked econtext */
98 SubTransactionId xact_subxid; /* ID for current subxact */
99 struct SimpleEcontextStackEntry *next; /* next stack entry up */
100 } SimpleEcontextStackEntry;
102 static EState *shared_simple_eval_estate = NULL;
103 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
105 /************************************************************
106 * Local function forward declarations
107 ************************************************************/
108 static void plpgsql_exec_error_callback(void *arg);
109 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
111 static int exec_stmt_block(PLpgSQL_execstate *estate,
112 PLpgSQL_stmt_block *block);
113 static int exec_stmts(PLpgSQL_execstate *estate,
115 static int exec_stmt(PLpgSQL_execstate *estate,
117 static int exec_stmt_assign(PLpgSQL_execstate *estate,
118 PLpgSQL_stmt_assign *stmt);
119 static int exec_stmt_perform(PLpgSQL_execstate *estate,
120 PLpgSQL_stmt_perform *stmt);
121 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
122 PLpgSQL_stmt_getdiag *stmt);
123 static int exec_stmt_if(PLpgSQL_execstate *estate,
124 PLpgSQL_stmt_if *stmt);
125 static int exec_stmt_case(PLpgSQL_execstate *estate,
126 PLpgSQL_stmt_case *stmt);
127 static int exec_stmt_loop(PLpgSQL_execstate *estate,
128 PLpgSQL_stmt_loop *stmt);
129 static int exec_stmt_while(PLpgSQL_execstate *estate,
130 PLpgSQL_stmt_while *stmt);
131 static int exec_stmt_fori(PLpgSQL_execstate *estate,
132 PLpgSQL_stmt_fori *stmt);
133 static int exec_stmt_fors(PLpgSQL_execstate *estate,
134 PLpgSQL_stmt_fors *stmt);
135 static int exec_stmt_forc(PLpgSQL_execstate *estate,
136 PLpgSQL_stmt_forc *stmt);
137 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
138 PLpgSQL_stmt_foreach_a *stmt);
139 static int exec_stmt_open(PLpgSQL_execstate *estate,
140 PLpgSQL_stmt_open *stmt);
141 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
142 PLpgSQL_stmt_fetch *stmt);
143 static int exec_stmt_close(PLpgSQL_execstate *estate,
144 PLpgSQL_stmt_close *stmt);
145 static int exec_stmt_exit(PLpgSQL_execstate *estate,
146 PLpgSQL_stmt_exit *stmt);
147 static int exec_stmt_return(PLpgSQL_execstate *estate,
148 PLpgSQL_stmt_return *stmt);
149 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
150 PLpgSQL_stmt_return_next *stmt);
151 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
152 PLpgSQL_stmt_return_query *stmt);
153 static int exec_stmt_raise(PLpgSQL_execstate *estate,
154 PLpgSQL_stmt_raise *stmt);
155 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
156 PLpgSQL_stmt_execsql *stmt);
157 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
158 PLpgSQL_stmt_dynexecute *stmt);
159 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
160 PLpgSQL_stmt_dynfors *stmt);
162 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
163 PLpgSQL_function *func,
165 EState *simple_eval_estate);
166 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
168 static void exec_prepare_plan(PLpgSQL_execstate *estate,
169 PLpgSQL_expr *expr, int cursorOptions);
170 static bool exec_simple_check_node(Node *node);
171 static void exec_simple_check_plan(PLpgSQL_expr *expr);
172 static void exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan);
173 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
180 static void exec_assign_expr(PLpgSQL_execstate *estate,
181 PLpgSQL_datum *target,
183 static void exec_assign_c_string(PLpgSQL_execstate *estate,
184 PLpgSQL_datum *target,
186 static void exec_assign_value(PLpgSQL_execstate *estate,
187 PLpgSQL_datum *target,
188 Datum value, bool isNull,
189 Oid valtype, int32 valtypmod);
190 static void exec_eval_datum(PLpgSQL_execstate *estate,
191 PLpgSQL_datum *datum,
196 static int exec_eval_integer(PLpgSQL_execstate *estate,
199 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
202 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
207 static int exec_run_select(PLpgSQL_execstate *estate,
208 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
209 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
210 Portal portal, bool prefetch_ok);
211 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
213 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
214 static void exec_move_row(PLpgSQL_execstate *estate,
217 HeapTuple tup, TupleDesc tupdesc);
218 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
221 static HeapTuple get_tuple_from_datum(Datum value);
222 static TupleDesc get_tupdesc_from_datum(Datum value);
223 static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
227 static char *convert_value_to_string(PLpgSQL_execstate *estate,
228 Datum value, Oid valtype);
229 static Datum exec_cast_value(PLpgSQL_execstate *estate,
230 Datum value, bool *isnull,
231 Oid valtype, int32 valtypmod,
232 Oid reqtype, int32 reqtypmod);
233 static ExprState *get_cast_expression(PLpgSQL_execstate *estate,
234 Oid srctype, Oid dsttype, int32 dsttypmod);
235 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
236 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
237 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
238 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
239 static void free_var(PLpgSQL_var *var);
240 static void assign_text_var(PLpgSQL_var *var, const char *str);
241 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
243 static void free_params_data(PreparedParamsData *ppd);
244 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
245 PLpgSQL_expr *dynquery, List *params,
246 const char *portalname, int cursorOptions);
248 static char *format_expr_params(PLpgSQL_execstate *estate,
249 const PLpgSQL_expr *expr);
250 static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
251 const PreparedParamsData *ppd);
255 * plpgsql_exec_function Called by the call handler for
256 * function execution.
258 * This is also used to execute inline code blocks (DO blocks). The only
259 * difference that this code is aware of is that for a DO block, we want
260 * to use a private simple_eval_estate, which is created and passed in by
261 * the caller. For regular functions, pass NULL, which implies using
262 * shared_simple_eval_estate.
266 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
267 EState *simple_eval_estate)
269 PLpgSQL_execstate estate;
270 ErrorContextCallback plerrcontext;
275 * Setup the execution state
277 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
281 * Setup error traceback support for ereport()
283 plerrcontext.callback = plpgsql_exec_error_callback;
284 plerrcontext.arg = &estate;
285 plerrcontext.previous = error_context_stack;
286 error_context_stack = &plerrcontext;
289 * Make local execution copies of all the datums
291 estate.err_text = gettext_noop("during initialization of execution state");
292 for (i = 0; i < estate.ndatums; i++)
293 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
296 * Store the actual call argument values into the appropriate variables
298 estate.err_text = gettext_noop("while storing call arguments into local variables");
299 for (i = 0; i < func->fn_nargs; i++)
301 int n = func->fn_argvarnos[i];
303 switch (estate.datums[n]->dtype)
305 case PLPGSQL_DTYPE_VAR:
307 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
309 var->value = fcinfo->arg[i];
310 var->isnull = fcinfo->argnull[i];
311 var->freeval = false;
315 case PLPGSQL_DTYPE_ROW:
317 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
319 if (!fcinfo->argnull[i])
321 /* Assign row value from composite datum */
322 exec_move_row_from_datum(&estate, NULL, row,
327 /* If arg is null, treat it as an empty row */
328 exec_move_row(&estate, NULL, row, NULL, NULL);
330 /* clean up after exec_move_row() */
331 exec_eval_cleanup(&estate);
336 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
340 estate.err_text = gettext_noop("during function entry");
343 * Set the magic variable FOUND to false
345 exec_set_found(&estate, false);
348 * Let the instrumentation plugin peek at this function
350 if (*plugin_ptr && (*plugin_ptr)->func_beg)
351 ((*plugin_ptr)->func_beg) (&estate, func);
354 * Now call the toplevel block of statements
356 estate.err_text = NULL;
357 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
358 rc = exec_stmt_block(&estate, func->action);
359 if (rc != PLPGSQL_RC_RETURN)
361 estate.err_stmt = NULL;
362 estate.err_text = NULL;
365 * Provide a more helpful message if a CONTINUE or RAISE has been used
366 * outside the context it can work in.
368 if (rc == PLPGSQL_RC_CONTINUE)
370 (errcode(ERRCODE_SYNTAX_ERROR),
371 errmsg("CONTINUE cannot be used outside a loop")));
374 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
375 errmsg("control reached end of function without RETURN")));
379 * We got a return value - process it
381 estate.err_stmt = NULL;
382 estate.err_text = gettext_noop("while casting return value to function's return type");
384 fcinfo->isnull = estate.retisnull;
388 ReturnSetInfo *rsi = estate.rsi;
390 /* Check caller can handle a set result */
391 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
392 (rsi->allowedModes & SFRM_Materialize) == 0)
394 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
395 errmsg("set-valued function called in context that cannot accept a set")));
396 rsi->returnMode = SFRM_Materialize;
398 /* If we produced any tuples, send back the result */
399 if (estate.tuple_store)
401 rsi->setResult = estate.tuple_store;
402 if (estate.rettupdesc)
404 MemoryContext oldcxt;
406 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
407 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
408 MemoryContextSwitchTo(oldcxt);
411 estate.retval = (Datum) 0;
412 fcinfo->isnull = true;
414 else if (!estate.retisnull)
416 if (estate.retistuple)
419 * We have to check that the returned tuple actually matches the
420 * expected result type. XXX would be better to cache the tupdesc
421 * instead of repeating get_call_result_type()
423 HeapTuple rettup = (HeapTuple) DatumGetPointer(estate.retval);
425 TupleConversionMap *tupmap;
427 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
429 case TYPEFUNC_COMPOSITE:
430 /* got the expected result rowtype, now check it */
431 tupmap = convert_tuples_by_position(estate.rettupdesc,
433 gettext_noop("returned record type does not match expected record type"));
434 /* it might need conversion */
436 rettup = do_convert_tuple(rettup, tupmap);
437 /* no need to free map, we're about to return anyway */
439 case TYPEFUNC_RECORD:
442 * Failed to determine actual type of RECORD. We could
443 * raise an error here, but what this means in practice is
444 * that the caller is expecting any old generic rowtype,
445 * so we don't really need to be restrictive. Pass back
446 * the generated result type, instead.
448 tupdesc = estate.rettupdesc;
449 if (tupdesc == NULL) /* shouldn't happen */
450 elog(ERROR, "return type must be a row type");
453 /* shouldn't get here if retistuple is true ... */
454 elog(ERROR, "return type must be a row type");
459 * Copy tuple to upper executor memory, as a tuple Datum. Make
460 * sure it is labeled with the caller-supplied tuple type.
462 estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
466 /* Cast value to proper type */
467 estate.retval = exec_cast_value(&estate,
476 * If the function's return type isn't by value, copy the value
477 * into upper executor memory context.
479 if (!fcinfo->isnull && !func->fn_retbyval)
484 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
485 tmp = SPI_palloc(len);
486 memcpy(tmp, DatumGetPointer(estate.retval), len);
487 estate.retval = PointerGetDatum(tmp);
492 estate.err_text = gettext_noop("during function exit");
495 * Let the instrumentation plugin peek at this function
497 if (*plugin_ptr && (*plugin_ptr)->func_end)
498 ((*plugin_ptr)->func_end) (&estate, func);
500 /* Clean up any leftover temporary memory */
501 plpgsql_destroy_econtext(&estate);
502 exec_eval_cleanup(&estate);
505 * Pop the error context stack
507 error_context_stack = plerrcontext.previous;
510 * Return the function's result
512 return estate.retval;
517 * plpgsql_exec_trigger Called by the call handler for
522 plpgsql_exec_trigger(PLpgSQL_function *func,
523 TriggerData *trigdata)
525 PLpgSQL_execstate estate;
526 ErrorContextCallback plerrcontext;
530 PLpgSQL_rec *rec_new,
535 * Setup the execution state
537 plpgsql_estate_setup(&estate, func, NULL, NULL);
540 * Setup error traceback support for ereport()
542 plerrcontext.callback = plpgsql_exec_error_callback;
543 plerrcontext.arg = &estate;
544 plerrcontext.previous = error_context_stack;
545 error_context_stack = &plerrcontext;
548 * Make local execution copies of all the datums
550 estate.err_text = gettext_noop("during initialization of execution state");
551 for (i = 0; i < estate.ndatums; i++)
552 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
555 * Put the OLD and NEW tuples into record variables
557 * We make the tupdescs available in both records even though only one may
558 * have a value. This allows parsing of record references to succeed in
559 * functions that are used for multiple trigger types. For example, we
560 * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
561 * which should parse regardless of the current trigger type.
563 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
564 rec_new->freetup = false;
565 rec_new->tupdesc = trigdata->tg_relation->rd_att;
566 rec_new->freetupdesc = false;
567 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
568 rec_old->freetup = false;
569 rec_old->tupdesc = trigdata->tg_relation->rd_att;
570 rec_old->freetupdesc = false;
572 if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
575 * Per-statement triggers don't use OLD/NEW variables
580 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
582 rec_new->tup = trigdata->tg_trigtuple;
585 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
587 rec_new->tup = trigdata->tg_newtuple;
588 rec_old->tup = trigdata->tg_trigtuple;
590 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
593 rec_old->tup = trigdata->tg_trigtuple;
596 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
599 * Assign the special tg_ variables
602 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
603 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
604 var->value = CStringGetTextDatum("INSERT");
605 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
606 var->value = CStringGetTextDatum("UPDATE");
607 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
608 var->value = CStringGetTextDatum("DELETE");
609 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
610 var->value = CStringGetTextDatum("TRUNCATE");
612 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
616 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
617 var->value = DirectFunctionCall1(namein,
618 CStringGetDatum(trigdata->tg_trigger->tgname));
622 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
623 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
624 var->value = CStringGetTextDatum("BEFORE");
625 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
626 var->value = CStringGetTextDatum("AFTER");
627 else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
628 var->value = CStringGetTextDatum("INSTEAD OF");
630 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
634 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
635 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
636 var->value = CStringGetTextDatum("ROW");
637 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
638 var->value = CStringGetTextDatum("STATEMENT");
640 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
644 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
645 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
647 var->freeval = false;
649 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
650 var->value = DirectFunctionCall1(namein,
651 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
655 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
656 var->value = DirectFunctionCall1(namein,
657 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
661 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
662 var->value = DirectFunctionCall1(namein,
665 RelationGetNamespace(
666 trigdata->tg_relation))));
670 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
671 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
673 var->freeval = false;
675 var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
676 if (trigdata->tg_trigger->tgnargs > 0)
679 * For historical reasons, tg_argv[] subscripts start at zero not one.
680 * So we can't use construct_array().
682 int nelems = trigdata->tg_trigger->tgnargs;
687 elems = palloc(sizeof(Datum) * nelems);
688 for (i = 0; i < nelems; i++)
689 elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
693 var->value = PointerGetDatum(construct_md_array(elems, NULL,
702 var->value = (Datum) 0;
704 var->freeval = false;
707 estate.err_text = gettext_noop("during function entry");
710 * Set the magic variable FOUND to false
712 exec_set_found(&estate, false);
715 * Let the instrumentation plugin peek at this function
717 if (*plugin_ptr && (*plugin_ptr)->func_beg)
718 ((*plugin_ptr)->func_beg) (&estate, func);
721 * Now call the toplevel block of statements
723 estate.err_text = NULL;
724 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
725 rc = exec_stmt_block(&estate, func->action);
726 if (rc != PLPGSQL_RC_RETURN)
728 estate.err_stmt = NULL;
729 estate.err_text = NULL;
732 * Provide a more helpful message if a CONTINUE or RAISE has been used
733 * outside the context it can work in.
735 if (rc == PLPGSQL_RC_CONTINUE)
737 (errcode(ERRCODE_SYNTAX_ERROR),
738 errmsg("CONTINUE cannot be used outside a loop")));
741 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
742 errmsg("control reached end of trigger procedure without RETURN")));
745 estate.err_stmt = NULL;
746 estate.err_text = gettext_noop("during function exit");
750 (errcode(ERRCODE_DATATYPE_MISMATCH),
751 errmsg("trigger procedure cannot return a set")));
754 * Check that the returned tuple structure has the same attributes, the
755 * relation that fired the trigger has. A per-statement trigger always
756 * needs to return NULL, so we ignore any return value the function itself
757 * produces (XXX: is this a good idea?)
759 * XXX This way it is possible, that the trigger returns a tuple where
760 * attributes don't have the correct atttypmod's length. It's up to the
761 * trigger's programmer to ensure that this doesn't happen. Jan
763 if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
767 TupleConversionMap *tupmap;
769 rettup = (HeapTuple) DatumGetPointer(estate.retval);
770 /* check rowtype compatibility */
771 tupmap = convert_tuples_by_position(estate.rettupdesc,
772 trigdata->tg_relation->rd_att,
773 gettext_noop("returned row structure does not match the structure of the triggering table"));
774 /* it might need conversion */
776 rettup = do_convert_tuple(rettup, tupmap);
777 /* no need to free map, we're about to return anyway */
779 /* Copy tuple to upper executor memory */
780 rettup = SPI_copytuple(rettup);
784 * Let the instrumentation plugin peek at this function
786 if (*plugin_ptr && (*plugin_ptr)->func_end)
787 ((*plugin_ptr)->func_end) (&estate, func);
789 /* Clean up any leftover temporary memory */
790 plpgsql_destroy_econtext(&estate);
791 exec_eval_cleanup(&estate);
794 * Pop the error context stack
796 error_context_stack = plerrcontext.previous;
799 * Return the trigger's result
805 plpgsql_exec_event_trigger(PLpgSQL_function *func, EventTriggerData *trigdata)
807 PLpgSQL_execstate estate;
808 ErrorContextCallback plerrcontext;
814 * Setup the execution state
816 plpgsql_estate_setup(&estate, func, NULL, NULL);
819 * Setup error traceback support for ereport()
821 plerrcontext.callback = plpgsql_exec_error_callback;
822 plerrcontext.arg = &estate;
823 plerrcontext.previous = error_context_stack;
824 error_context_stack = &plerrcontext;
827 * Make local execution copies of all the datums
829 estate.err_text = gettext_noop("during initialization of execution state");
830 for (i = 0; i < estate.ndatums; i++)
831 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
834 * Assign the special tg_ variables
836 var = (PLpgSQL_var *) (estate.datums[func->tg_event_varno]);
837 var->value = CStringGetTextDatum(trigdata->event);
841 var = (PLpgSQL_var *) (estate.datums[func->tg_tag_varno]);
842 var->value = CStringGetTextDatum(trigdata->tag);
847 * Let the instrumentation plugin peek at this function
849 if (*plugin_ptr && (*plugin_ptr)->func_beg)
850 ((*plugin_ptr)->func_beg) (&estate, func);
853 * Now call the toplevel block of statements
855 estate.err_text = NULL;
856 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
857 rc = exec_stmt_block(&estate, func->action);
858 if (rc != PLPGSQL_RC_RETURN)
860 estate.err_stmt = NULL;
861 estate.err_text = NULL;
864 * Provide a more helpful message if a CONTINUE or RAISE has been used
865 * outside the context it can work in.
867 if (rc == PLPGSQL_RC_CONTINUE)
869 (errcode(ERRCODE_SYNTAX_ERROR),
870 errmsg("CONTINUE cannot be used outside a loop")));
873 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
874 errmsg("control reached end of trigger procedure without RETURN")));
877 estate.err_stmt = NULL;
878 estate.err_text = gettext_noop("during function exit");
881 * Let the instrumentation plugin peek at this function
883 if (*plugin_ptr && (*plugin_ptr)->func_end)
884 ((*plugin_ptr)->func_end) (&estate, func);
886 /* Clean up any leftover temporary memory */
887 plpgsql_destroy_econtext(&estate);
888 exec_eval_cleanup(&estate);
891 * Pop the error context stack
893 error_context_stack = plerrcontext.previous;
899 * error context callback to let us supply a call-stack traceback
902 plpgsql_exec_error_callback(void *arg)
904 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
906 /* if we are doing RAISE, don't report its location */
907 if (estate->err_text == raise_skip_msg)
910 if (estate->err_text != NULL)
913 * We don't expend the cycles to run gettext() on err_text unless we
914 * actually need it. Therefore, places that set up err_text should
915 * use gettext_noop() to ensure the strings get recorded in the
916 * message dictionary.
918 * If both err_text and err_stmt are set, use the err_text as
919 * description, but report the err_stmt's line number. When err_stmt
920 * is not set, we're in function entry/exit, or some such place not
921 * attached to a specific line number.
923 if (estate->err_stmt != NULL)
926 * translator: last %s is a phrase such as "during statement block
927 * local variable initialization"
929 errcontext("PL/pgSQL function %s line %d %s",
930 estate->func->fn_signature,
931 estate->err_stmt->lineno,
932 _(estate->err_text));
937 * translator: last %s is a phrase such as "while storing call
938 * arguments into local variables"
940 errcontext("PL/pgSQL function %s %s",
941 estate->func->fn_signature,
942 _(estate->err_text));
945 else if (estate->err_stmt != NULL)
947 /* translator: last %s is a plpgsql statement type name */
948 errcontext("PL/pgSQL function %s line %d at %s",
949 estate->func->fn_signature,
950 estate->err_stmt->lineno,
951 plpgsql_stmt_typename(estate->err_stmt));
954 errcontext("PL/pgSQL function %s",
955 estate->func->fn_signature);
960 * Support function for initializing local execution variables
963 static PLpgSQL_datum *
964 copy_plpgsql_datum(PLpgSQL_datum *datum)
966 PLpgSQL_datum *result;
968 switch (datum->dtype)
970 case PLPGSQL_DTYPE_VAR:
972 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
974 memcpy(new, datum, sizeof(PLpgSQL_var));
975 /* Ensure the value is null (possibly not needed?) */
978 new->freeval = false;
980 result = (PLpgSQL_datum *) new;
984 case PLPGSQL_DTYPE_REC:
986 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
988 memcpy(new, datum, sizeof(PLpgSQL_rec));
989 /* Ensure the value is null (possibly not needed?) */
992 new->freetup = false;
993 new->freetupdesc = false;
995 result = (PLpgSQL_datum *) new;
999 case PLPGSQL_DTYPE_ROW:
1000 case PLPGSQL_DTYPE_RECFIELD:
1001 case PLPGSQL_DTYPE_ARRAYELEM:
1004 * These datum records are read-only at runtime, so no need to
1005 * copy them (well, ARRAYELEM contains some cached type data, but
1006 * we'd just as soon centralize the caching anyway)
1012 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1013 result = NULL; /* keep compiler quiet */
1022 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
1024 for (; cond != NULL; cond = cond->next)
1026 int sqlerrstate = cond->sqlerrstate;
1029 * OTHERS matches everything *except* query-canceled; if you're
1030 * foolish enough, you can match that explicitly.
1032 if (sqlerrstate == 0)
1034 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
1038 else if (edata->sqlerrcode == sqlerrstate)
1040 /* Category match? */
1041 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1042 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1050 * exec_stmt_block Execute a block of statements
1054 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
1056 volatile int rc = -1;
1061 * First initialize all variables declared in this block
1063 estate->err_text = gettext_noop("during statement block local variable initialization");
1065 for (i = 0; i < block->n_initvars; i++)
1067 n = block->initvarnos[i];
1069 switch (estate->datums[n]->dtype)
1071 case PLPGSQL_DTYPE_VAR:
1073 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
1075 /* free any old value, in case re-entering block */
1078 /* Initially it contains a NULL */
1079 var->value = (Datum) 0;
1082 if (var->default_val == NULL)
1085 * If needed, give the datatype a chance to reject
1086 * NULLs, by assigning a NULL to the variable. We
1087 * claim the value is of type UNKNOWN, not the var's
1088 * datatype, else coercion will be skipped. (Do this
1089 * before the notnull check to be consistent with
1090 * exec_assign_value.)
1092 if (var->datatype->typtype == TYPTYPE_DOMAIN)
1093 exec_assign_value(estate,
1094 (PLpgSQL_datum *) var,
1102 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1103 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
1108 exec_assign_expr(estate, (PLpgSQL_datum *) var,
1114 case PLPGSQL_DTYPE_REC:
1116 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
1120 heap_freetuple(rec->tup);
1121 rec->freetup = false;
1123 if (rec->freetupdesc)
1125 FreeTupleDesc(rec->tupdesc);
1126 rec->freetupdesc = false;
1129 rec->tupdesc = NULL;
1133 case PLPGSQL_DTYPE_RECFIELD:
1134 case PLPGSQL_DTYPE_ARRAYELEM:
1138 elog(ERROR, "unrecognized dtype: %d",
1139 estate->datums[n]->dtype);
1143 if (block->exceptions)
1146 * Execute the statements in the block's body inside a sub-transaction
1148 MemoryContext oldcontext = CurrentMemoryContext;
1149 ResourceOwner oldowner = CurrentResourceOwner;
1150 ExprContext *old_eval_econtext = estate->eval_econtext;
1151 ErrorData *save_cur_error = estate->cur_error;
1153 estate->err_text = gettext_noop("during statement block entry");
1155 BeginInternalSubTransaction(NULL);
1156 /* Want to run statements inside function's memory context */
1157 MemoryContextSwitchTo(oldcontext);
1162 * We need to run the block's statements with a new eval_econtext
1163 * that belongs to the current subtransaction; if we try to use
1164 * the outer econtext then ExprContext shutdown callbacks will be
1165 * called at the wrong times.
1167 plpgsql_create_econtext(estate);
1169 estate->err_text = NULL;
1171 /* Run the block's statements */
1172 rc = exec_stmts(estate, block->body);
1174 estate->err_text = gettext_noop("during statement block exit");
1177 * If the block ended with RETURN, we may need to copy the return
1178 * value out of the subtransaction eval_context. This is
1179 * currently only needed for scalar result types --- rowtype
1180 * values will always exist in the function's own memory context.
1182 if (rc == PLPGSQL_RC_RETURN &&
1183 !estate->retisset &&
1184 !estate->retisnull &&
1185 estate->rettupdesc == NULL)
1190 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1191 estate->retval = datumCopy(estate->retval,
1192 resTypByVal, resTypLen);
1195 /* Commit the inner transaction, return to outer xact context */
1196 ReleaseCurrentSubTransaction();
1197 MemoryContextSwitchTo(oldcontext);
1198 CurrentResourceOwner = oldowner;
1201 * Revert to outer eval_econtext. (The inner one was
1202 * automatically cleaned up during subxact exit.)
1204 estate->eval_econtext = old_eval_econtext;
1207 * AtEOSubXact_SPI() should not have popped any SPI context, but
1208 * just in case it did, make sure we remain connected.
1210 SPI_restore_connection();
1217 estate->err_text = gettext_noop("during exception cleanup");
1219 /* Save error info */
1220 MemoryContextSwitchTo(oldcontext);
1221 edata = CopyErrorData();
1224 /* Abort the inner transaction */
1225 RollbackAndReleaseCurrentSubTransaction();
1226 MemoryContextSwitchTo(oldcontext);
1227 CurrentResourceOwner = oldowner;
1229 /* Revert to outer eval_econtext */
1230 estate->eval_econtext = old_eval_econtext;
1233 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1234 * will have left us in a disconnected state. We need this hack
1235 * to return to connected state.
1237 SPI_restore_connection();
1240 * Must clean up the econtext too. However, any tuple table made
1241 * in the subxact will have been thrown away by SPI during subxact
1242 * abort, so we don't need to (and mustn't try to) free the
1245 estate->eval_tuptable = NULL;
1246 exec_eval_cleanup(estate);
1248 /* Look for a matching exception handler */
1249 foreach(e, block->exceptions->exc_list)
1251 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1253 if (exception_matches_conditions(edata, exception->conditions))
1256 * Initialize the magic SQLSTATE and SQLERRM variables for
1257 * the exception block; this also frees values from any
1258 * prior use of the same exception. We needn't do this
1259 * until we have found a matching exception.
1261 PLpgSQL_var *state_var;
1262 PLpgSQL_var *errm_var;
1264 state_var = (PLpgSQL_var *)
1265 estate->datums[block->exceptions->sqlstate_varno];
1266 errm_var = (PLpgSQL_var *)
1267 estate->datums[block->exceptions->sqlerrm_varno];
1269 assign_text_var(state_var,
1270 unpack_sql_state(edata->sqlerrcode));
1271 assign_text_var(errm_var, edata->message);
1274 * Also set up cur_error so the error data is accessible
1275 * inside the handler.
1277 estate->cur_error = edata;
1279 estate->err_text = NULL;
1281 rc = exec_stmts(estate, exception->action);
1288 * Restore previous state of cur_error, whether or not we executed
1289 * a handler. This is needed in case an error got thrown from
1290 * some inner block's exception handler.
1292 estate->cur_error = save_cur_error;
1294 /* If no match found, re-throw the error */
1296 ReThrowError(edata);
1298 FreeErrorData(edata);
1302 Assert(save_cur_error == estate->cur_error);
1307 * Just execute the statements in the block's body
1309 estate->err_text = NULL;
1311 rc = exec_stmts(estate, block->body);
1314 estate->err_text = NULL;
1317 * Handle the return code.
1322 case PLPGSQL_RC_RETURN:
1323 case PLPGSQL_RC_CONTINUE:
1326 case PLPGSQL_RC_EXIT:
1329 * This is intentionally different from the handling of RC_EXIT
1330 * for loops: to match a block, we require a match by label.
1332 if (estate->exitlabel == NULL)
1333 return PLPGSQL_RC_EXIT;
1334 if (block->label == NULL)
1335 return PLPGSQL_RC_EXIT;
1336 if (strcmp(block->label, estate->exitlabel) != 0)
1337 return PLPGSQL_RC_EXIT;
1338 estate->exitlabel = NULL;
1339 return PLPGSQL_RC_OK;
1342 elog(ERROR, "unrecognized rc: %d", rc);
1345 return PLPGSQL_RC_OK;
1350 * exec_stmts Iterate over a list of statements
1351 * as long as their return code is OK
1355 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1362 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1363 * statement. This prevents hangup in a tight loop if, for instance,
1364 * there is a LOOP construct with an empty body.
1366 CHECK_FOR_INTERRUPTS();
1367 return PLPGSQL_RC_OK;
1372 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1373 int rc = exec_stmt(estate, stmt);
1375 if (rc != PLPGSQL_RC_OK)
1379 return PLPGSQL_RC_OK;
1384 * exec_stmt Distribute one statement to the statements
1385 * type specific execution function.
1389 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1391 PLpgSQL_stmt *save_estmt;
1394 save_estmt = estate->err_stmt;
1395 estate->err_stmt = stmt;
1397 /* Let the plugin know that we are about to execute this statement */
1398 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1399 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1401 CHECK_FOR_INTERRUPTS();
1403 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1405 case PLPGSQL_STMT_BLOCK:
1406 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1409 case PLPGSQL_STMT_ASSIGN:
1410 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1413 case PLPGSQL_STMT_PERFORM:
1414 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1417 case PLPGSQL_STMT_GETDIAG:
1418 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1421 case PLPGSQL_STMT_IF:
1422 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1425 case PLPGSQL_STMT_CASE:
1426 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1429 case PLPGSQL_STMT_LOOP:
1430 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1433 case PLPGSQL_STMT_WHILE:
1434 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1437 case PLPGSQL_STMT_FORI:
1438 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1441 case PLPGSQL_STMT_FORS:
1442 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1445 case PLPGSQL_STMT_FORC:
1446 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1449 case PLPGSQL_STMT_FOREACH_A:
1450 rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
1453 case PLPGSQL_STMT_EXIT:
1454 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1457 case PLPGSQL_STMT_RETURN:
1458 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1461 case PLPGSQL_STMT_RETURN_NEXT:
1462 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1465 case PLPGSQL_STMT_RETURN_QUERY:
1466 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1469 case PLPGSQL_STMT_RAISE:
1470 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1473 case PLPGSQL_STMT_EXECSQL:
1474 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1477 case PLPGSQL_STMT_DYNEXECUTE:
1478 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1481 case PLPGSQL_STMT_DYNFORS:
1482 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1485 case PLPGSQL_STMT_OPEN:
1486 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1489 case PLPGSQL_STMT_FETCH:
1490 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1493 case PLPGSQL_STMT_CLOSE:
1494 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1498 estate->err_stmt = save_estmt;
1499 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1502 /* Let the plugin know that we have finished executing this statement */
1503 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1504 ((*plugin_ptr)->stmt_end) (estate, stmt);
1506 estate->err_stmt = save_estmt;
1513 * exec_stmt_assign Evaluate an expression and
1514 * put the result into a variable.
1518 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1520 Assert(stmt->varno >= 0);
1522 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1524 return PLPGSQL_RC_OK;
1528 * exec_stmt_perform Evaluate query and discard result (but set
1529 * FOUND depending on whether at least one row
1534 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1536 PLpgSQL_expr *expr = stmt->expr;
1538 (void) exec_run_select(estate, expr, 0, NULL);
1539 exec_set_found(estate, (estate->eval_processed != 0));
1540 exec_eval_cleanup(estate);
1542 return PLPGSQL_RC_OK;
1546 * exec_stmt_getdiag Put internal PG information into
1547 * specified variables.
1551 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1556 * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
1558 * Note: we trust the grammar to have disallowed the relevant item kinds
1559 * if not is_stacked, otherwise we'd dump core below.
1561 if (stmt->is_stacked && estate->cur_error == NULL)
1563 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
1564 errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
1566 foreach(lc, stmt->diag_items)
1568 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1569 PLpgSQL_datum *var = estate->datums[diag_item->target];
1571 switch (diag_item->kind)
1573 case PLPGSQL_GETDIAG_ROW_COUNT:
1574 exec_assign_value(estate, var,
1575 UInt32GetDatum(estate->eval_processed),
1576 false, INT4OID, -1);
1579 case PLPGSQL_GETDIAG_RESULT_OID:
1580 exec_assign_value(estate, var,
1581 ObjectIdGetDatum(estate->eval_lastoid),
1585 case PLPGSQL_GETDIAG_ERROR_CONTEXT:
1586 exec_assign_c_string(estate, var,
1587 estate->cur_error->context);
1590 case PLPGSQL_GETDIAG_ERROR_DETAIL:
1591 exec_assign_c_string(estate, var,
1592 estate->cur_error->detail);
1595 case PLPGSQL_GETDIAG_ERROR_HINT:
1596 exec_assign_c_string(estate, var,
1597 estate->cur_error->hint);
1600 case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
1601 exec_assign_c_string(estate, var,
1602 unpack_sql_state(estate->cur_error->sqlerrcode));
1605 case PLPGSQL_GETDIAG_COLUMN_NAME:
1606 exec_assign_c_string(estate, var,
1607 estate->cur_error->column_name);
1610 case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
1611 exec_assign_c_string(estate, var,
1612 estate->cur_error->constraint_name);
1615 case PLPGSQL_GETDIAG_DATATYPE_NAME:
1616 exec_assign_c_string(estate, var,
1617 estate->cur_error->datatype_name);
1620 case PLPGSQL_GETDIAG_MESSAGE_TEXT:
1621 exec_assign_c_string(estate, var,
1622 estate->cur_error->message);
1625 case PLPGSQL_GETDIAG_TABLE_NAME:
1626 exec_assign_c_string(estate, var,
1627 estate->cur_error->table_name);
1630 case PLPGSQL_GETDIAG_SCHEMA_NAME:
1631 exec_assign_c_string(estate, var,
1632 estate->cur_error->schema_name);
1635 case PLPGSQL_GETDIAG_CONTEXT:
1637 char *contextstackstr = GetErrorContextStack();
1639 exec_assign_c_string(estate, var, contextstackstr);
1641 pfree(contextstackstr);
1646 elog(ERROR, "unrecognized diagnostic item kind: %d",
1651 return PLPGSQL_RC_OK;
1655 * exec_stmt_if Evaluate a bool expression and
1656 * execute the true or false body
1661 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1667 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1668 exec_eval_cleanup(estate);
1669 if (!isnull && value)
1670 return exec_stmts(estate, stmt->then_body);
1672 foreach(lc, stmt->elsif_list)
1674 PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
1676 value = exec_eval_boolean(estate, elif->cond, &isnull);
1677 exec_eval_cleanup(estate);
1678 if (!isnull && value)
1679 return exec_stmts(estate, elif->stmts);
1682 return exec_stmts(estate, stmt->else_body);
1691 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1693 PLpgSQL_var *t_var = NULL;
1697 if (stmt->t_expr != NULL)
1704 t_val = exec_eval_expr(estate, stmt->t_expr,
1705 &isnull, &t_typoid, &t_typmod);
1707 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1710 * When expected datatype is different from real, change it. Note that
1711 * what we're modifying here is an execution copy of the datum, so
1712 * this doesn't affect the originally stored function parse tree.
1714 if (t_var->datatype->typoid != t_typoid ||
1715 t_var->datatype->atttypmod != t_typmod)
1716 t_var->datatype = plpgsql_build_datatype(t_typoid,
1718 estate->func->fn_input_collation);
1720 /* now we can assign to the variable */
1721 exec_assign_value(estate,
1722 (PLpgSQL_datum *) t_var,
1728 exec_eval_cleanup(estate);
1731 /* Now search for a successful WHEN clause */
1732 foreach(l, stmt->case_when_list)
1734 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1737 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1738 exec_eval_cleanup(estate);
1739 if (!isnull && value)
1743 /* We can now discard any value we had for the temp variable */
1747 t_var->value = (Datum) 0;
1748 t_var->isnull = true;
1751 /* Evaluate the statement(s), and we're done */
1752 return exec_stmts(estate, cwt->stmts);
1756 /* We can now discard any value we had for the temp variable */
1760 t_var->value = (Datum) 0;
1761 t_var->isnull = true;
1764 /* SQL2003 mandates this error if there was no ELSE clause */
1765 if (!stmt->have_else)
1767 (errcode(ERRCODE_CASE_NOT_FOUND),
1768 errmsg("case not found"),
1769 errhint("CASE statement is missing ELSE part.")));
1771 /* Evaluate the ELSE statements, and we're done */
1772 return exec_stmts(estate, stmt->else_stmts);
1777 * exec_stmt_loop Loop over statements until
1782 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1786 int rc = exec_stmts(estate, stmt->body);
1793 case PLPGSQL_RC_EXIT:
1794 if (estate->exitlabel == NULL)
1795 return PLPGSQL_RC_OK;
1796 if (stmt->label == NULL)
1797 return PLPGSQL_RC_EXIT;
1798 if (strcmp(stmt->label, estate->exitlabel) != 0)
1799 return PLPGSQL_RC_EXIT;
1800 estate->exitlabel = NULL;
1801 return PLPGSQL_RC_OK;
1803 case PLPGSQL_RC_CONTINUE:
1804 if (estate->exitlabel == NULL)
1805 /* anonymous continue, so re-run the loop */
1807 else if (stmt->label != NULL &&
1808 strcmp(stmt->label, estate->exitlabel) == 0)
1809 /* label matches named continue, so re-run loop */
1810 estate->exitlabel = NULL;
1812 /* label doesn't match named continue, so propagate upward */
1813 return PLPGSQL_RC_CONTINUE;
1816 case PLPGSQL_RC_RETURN:
1820 elog(ERROR, "unrecognized rc: %d", rc);
1827 * exec_stmt_while Loop over statements as long
1828 * as an expression evaluates to
1829 * true or an exit occurs.
1833 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1841 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1842 exec_eval_cleanup(estate);
1844 if (isnull || !value)
1847 rc = exec_stmts(estate, stmt->body);
1854 case PLPGSQL_RC_EXIT:
1855 if (estate->exitlabel == NULL)
1856 return PLPGSQL_RC_OK;
1857 if (stmt->label == NULL)
1858 return PLPGSQL_RC_EXIT;
1859 if (strcmp(stmt->label, estate->exitlabel) != 0)
1860 return PLPGSQL_RC_EXIT;
1861 estate->exitlabel = NULL;
1862 return PLPGSQL_RC_OK;
1864 case PLPGSQL_RC_CONTINUE:
1865 if (estate->exitlabel == NULL)
1866 /* anonymous continue, so re-run loop */
1868 else if (stmt->label != NULL &&
1869 strcmp(stmt->label, estate->exitlabel) == 0)
1870 /* label matches named continue, so re-run loop */
1871 estate->exitlabel = NULL;
1873 /* label doesn't match named continue, propagate upward */
1874 return PLPGSQL_RC_CONTINUE;
1877 case PLPGSQL_RC_RETURN:
1881 elog(ERROR, "unrecognized rc: %d", rc);
1885 return PLPGSQL_RC_OK;
1890 * exec_stmt_fori Iterate an integer variable
1891 * from a lower to an upper value
1892 * incrementing or decrementing by the BY value
1896 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1907 int rc = PLPGSQL_RC_OK;
1909 var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1912 * Get the value of the lower bound
1914 value = exec_eval_expr(estate, stmt->lower,
1915 &isnull, &valtype, &valtypmod);
1916 value = exec_cast_value(estate, value, &isnull,
1918 var->datatype->typoid,
1919 var->datatype->atttypmod);
1922 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1923 errmsg("lower bound of FOR loop cannot be null")));
1924 loop_value = DatumGetInt32(value);
1925 exec_eval_cleanup(estate);
1928 * Get the value of the upper bound
1930 value = exec_eval_expr(estate, stmt->upper,
1931 &isnull, &valtype, &valtypmod);
1932 value = exec_cast_value(estate, value, &isnull,
1934 var->datatype->typoid,
1935 var->datatype->atttypmod);
1938 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1939 errmsg("upper bound of FOR loop cannot be null")));
1940 end_value = DatumGetInt32(value);
1941 exec_eval_cleanup(estate);
1944 * Get the step value
1948 value = exec_eval_expr(estate, stmt->step,
1949 &isnull, &valtype, &valtypmod);
1950 value = exec_cast_value(estate, value, &isnull,
1952 var->datatype->typoid,
1953 var->datatype->atttypmod);
1956 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1957 errmsg("BY value of FOR loop cannot be null")));
1958 step_value = DatumGetInt32(value);
1959 exec_eval_cleanup(estate);
1960 if (step_value <= 0)
1962 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1963 errmsg("BY value of FOR loop must be greater than zero")));
1974 * Check against upper bound
1978 if (loop_value < end_value)
1983 if (loop_value > end_value)
1987 found = true; /* looped at least once */
1990 * Assign current value to loop var
1992 var->value = Int32GetDatum(loop_value);
1993 var->isnull = false;
1996 * Execute the statements
1998 rc = exec_stmts(estate, stmt->body);
2000 if (rc == PLPGSQL_RC_RETURN)
2001 break; /* break out of the loop */
2002 else if (rc == PLPGSQL_RC_EXIT)
2004 if (estate->exitlabel == NULL)
2005 /* unlabelled exit, finish the current loop */
2007 else if (stmt->label != NULL &&
2008 strcmp(stmt->label, estate->exitlabel) == 0)
2010 /* labelled exit, matches the current stmt's label */
2011 estate->exitlabel = NULL;
2016 * otherwise, this is a labelled exit that does not match the
2017 * current statement's label, if any: return RC_EXIT so that the
2018 * EXIT continues to propagate up the stack.
2022 else if (rc == PLPGSQL_RC_CONTINUE)
2024 if (estate->exitlabel == NULL)
2025 /* unlabelled continue, so re-run the current loop */
2027 else if (stmt->label != NULL &&
2028 strcmp(stmt->label, estate->exitlabel) == 0)
2030 /* label matches named continue, so re-run loop */
2031 estate->exitlabel = NULL;
2037 * otherwise, this is a named continue that does not match the
2038 * current statement's label, if any: return RC_CONTINUE so
2039 * that the CONTINUE will propagate up the stack.
2046 * Increase/decrease loop value, unless it would overflow, in which
2047 * case exit the loop.
2051 if ((int32) (loop_value - step_value) > loop_value)
2053 loop_value -= step_value;
2057 if ((int32) (loop_value + step_value) < loop_value)
2059 loop_value += step_value;
2064 * Set the FOUND variable to indicate the result of executing the loop
2065 * (namely, whether we looped one or more times). This must be set here so
2066 * that it does not interfere with the value of the FOUND variable inside
2067 * the loop processing itself.
2069 exec_set_found(estate, found);
2076 * exec_stmt_fors Execute a query, assign each
2077 * tuple to a record or row and
2078 * execute a group of statements
2083 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
2089 * Open the implicit cursor for the statement using exec_run_select
2091 exec_run_select(estate, stmt->query, 0, &portal);
2096 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2099 * Close the implicit cursor
2101 SPI_cursor_close(portal);
2108 * exec_stmt_forc Execute a loop for each row from a cursor.
2112 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
2114 PLpgSQL_var *curvar;
2115 char *curname = NULL;
2116 PLpgSQL_expr *query;
2117 ParamListInfo paramLI;
2122 * Get the cursor variable and if it has an assigned name, check
2123 * that it's not in use currently.
2126 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2127 if (!curvar->isnull)
2129 curname = TextDatumGetCString(curvar->value);
2130 if (SPI_cursor_find(curname) != NULL)
2132 (errcode(ERRCODE_DUPLICATE_CURSOR),
2133 errmsg("cursor \"%s\" already in use", curname)));
2137 * Open the cursor just like an OPEN command
2139 * Note: parser should already have checked that statement supplies
2140 * args iff cursor needs them, but we check again to be safe.
2143 if (stmt->argquery != NULL)
2146 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
2147 * statement to evaluate the args and put 'em into the
2151 PLpgSQL_stmt_execsql set_args;
2153 if (curvar->cursor_explicit_argrow < 0)
2155 (errcode(ERRCODE_SYNTAX_ERROR),
2156 errmsg("arguments given for cursor without arguments")));
2158 memset(&set_args, 0, sizeof(set_args));
2159 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2160 set_args.lineno = stmt->lineno;
2161 set_args.sqlstmt = stmt->argquery;
2162 set_args.into = true;
2163 /* XXX historically this has not been STRICT */
2164 set_args.row = (PLpgSQL_row *)
2165 (estate->datums[curvar->cursor_explicit_argrow]);
2167 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2168 elog(ERROR, "open cursor failed during argument processing");
2172 if (curvar->cursor_explicit_argrow >= 0)
2174 (errcode(ERRCODE_SYNTAX_ERROR),
2175 errmsg("arguments required for cursor")));
2178 query = curvar->cursor_explicit_expr;
2181 if (query->plan == NULL)
2182 exec_prepare_plan(estate, query, curvar->cursor_options);
2185 * Set up ParamListInfo (hook function and possibly data values)
2187 paramLI = setup_param_list(estate, query);
2190 * Open the cursor (the paramlist will get copied into the portal)
2192 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2194 estate->readonly_func);
2196 elog(ERROR, "could not open cursor: %s",
2197 SPI_result_code_string(SPI_result));
2199 /* don't need paramlist any more */
2204 * If cursor variable was NULL, store the generated portal name in it
2206 if (curname == NULL)
2207 assign_text_var(curvar, portal->name);
2210 * Execute the loop. We can't prefetch because the cursor is accessible
2211 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2213 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2216 * Close portal, and restore cursor variable if it was initially NULL.
2219 SPI_cursor_close(portal);
2221 if (curname == NULL)
2224 curvar->value = (Datum) 0;
2225 curvar->isnull = true;
2236 * exec_stmt_foreach_a Loop over elements or slices of an array
2238 * When looping over elements, the loop variable is the same type that the
2239 * array stores (eg: integer), when looping through slices, the loop variable
2240 * is an array of size and dimensions to match the size of the slice.
2244 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2249 PLpgSQL_datum *loop_var;
2250 Oid loop_var_elem_type;
2252 int rc = PLPGSQL_RC_OK;
2253 ArrayIterator array_iterator;
2254 Oid iterator_result_type;
2255 int32 iterator_result_typmod;
2259 /* get the value of the array expression */
2260 value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype, &arrtypmod);
2263 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2264 errmsg("FOREACH expression must not be null")));
2266 /* check the type of the expression - must be an array */
2267 if (!OidIsValid(get_element_type(arrtype)))
2269 (errcode(ERRCODE_DATATYPE_MISMATCH),
2270 errmsg("FOREACH expression must yield an array, not type %s",
2271 format_type_be(arrtype))));
2274 * We must copy the array, else it will disappear in exec_eval_cleanup.
2275 * This is annoying, but cleanup will certainly happen while running the
2276 * loop body, so we have little choice.
2278 arr = DatumGetArrayTypePCopy(value);
2280 /* Clean up any leftover temporary memory */
2281 exec_eval_cleanup(estate);
2283 /* Slice dimension must be less than or equal to array dimension */
2284 if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2286 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2287 errmsg("slice dimension (%d) is out of the valid range 0..%d",
2288 stmt->slice, ARR_NDIM(arr))));
2290 /* Set up the loop variable and see if it is of an array type */
2291 loop_var = estate->datums[stmt->varno];
2292 if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
2293 loop_var->dtype == PLPGSQL_DTYPE_ROW)
2296 * Record/row variable is certainly not of array type, and might not
2297 * be initialized at all yet, so don't try to get its type
2299 loop_var_elem_type = InvalidOid;
2302 loop_var_elem_type = get_element_type(exec_get_datum_type(estate,
2306 * Sanity-check the loop variable type. We don't try very hard here, and
2307 * should not be too picky since it's possible that exec_assign_value can
2308 * coerce values of different types. But it seems worthwhile to complain
2309 * if the array-ness of the loop variable is not right.
2311 if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
2313 (errcode(ERRCODE_DATATYPE_MISMATCH),
2314 errmsg("FOREACH ... SLICE loop variable must be of an array type")));
2315 if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
2317 (errcode(ERRCODE_DATATYPE_MISMATCH),
2318 errmsg("FOREACH loop variable must not be of an array type")));
2320 /* Create an iterator to step through the array */
2321 array_iterator = array_create_iterator(arr, stmt->slice);
2323 /* Identify iterator result type */
2324 if (stmt->slice > 0)
2326 /* When slicing, nominal type of result is same as array type */
2327 iterator_result_type = arrtype;
2328 iterator_result_typmod = arrtypmod;
2332 /* Without slicing, results are individual array elements */
2333 iterator_result_type = ARR_ELEMTYPE(arr);
2334 iterator_result_typmod = arrtypmod;
2337 /* Iterate over the array elements or slices */
2338 while (array_iterate(array_iterator, &value, &isnull))
2340 found = true; /* looped at least once */
2342 /* Assign current element/slice to the loop variable */
2343 exec_assign_value(estate, loop_var, value, isnull,
2344 iterator_result_type, iterator_result_typmod);
2346 /* In slice case, value is temporary; must free it to avoid leakage */
2347 if (stmt->slice > 0)
2348 pfree(DatumGetPointer(value));
2351 * Execute the statements
2353 rc = exec_stmts(estate, stmt->body);
2355 /* Handle the return code */
2356 if (rc == PLPGSQL_RC_RETURN)
2357 break; /* break out of the loop */
2358 else if (rc == PLPGSQL_RC_EXIT)
2360 if (estate->exitlabel == NULL)
2361 /* unlabelled exit, finish the current loop */
2363 else if (stmt->label != NULL &&
2364 strcmp(stmt->label, estate->exitlabel) == 0)
2366 /* labelled exit, matches the current stmt's label */
2367 estate->exitlabel = NULL;
2372 * otherwise, this is a labelled exit that does not match the
2373 * current statement's label, if any: return RC_EXIT so that the
2374 * EXIT continues to propagate up the stack.
2378 else if (rc == PLPGSQL_RC_CONTINUE)
2380 if (estate->exitlabel == NULL)
2381 /* unlabelled continue, so re-run the current loop */
2383 else if (stmt->label != NULL &&
2384 strcmp(stmt->label, estate->exitlabel) == 0)
2386 /* label matches named continue, so re-run loop */
2387 estate->exitlabel = NULL;
2393 * otherwise, this is a named continue that does not match the
2394 * current statement's label, if any: return RC_CONTINUE so
2395 * that the CONTINUE will propagate up the stack.
2402 /* Release temporary memory, including the array value */
2403 array_free_iterator(array_iterator);
2407 * Set the FOUND variable to indicate the result of executing the loop
2408 * (namely, whether we looped one or more times). This must be set here so
2409 * that it does not interfere with the value of the FOUND variable inside
2410 * the loop processing itself.
2412 exec_set_found(estate, found);
2419 * exec_stmt_exit Implements EXIT and CONTINUE
2421 * This begins the process of exiting / restarting a loop.
2425 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2428 * If the exit / continue has a condition, evaluate it
2430 if (stmt->cond != NULL)
2435 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2436 exec_eval_cleanup(estate);
2437 if (isnull || value == false)
2438 return PLPGSQL_RC_OK;
2441 estate->exitlabel = stmt->label;
2443 return PLPGSQL_RC_EXIT;
2445 return PLPGSQL_RC_CONTINUE;
2450 * exec_stmt_return Evaluate an expression and start
2451 * returning from the function.
2455 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2458 * If processing a set-returning PL/pgSQL function, the final RETURN
2459 * indicates that the function is finished producing tuples. The rest of
2460 * the work will be done at the top level.
2462 if (estate->retisset)
2463 return PLPGSQL_RC_RETURN;
2465 /* initialize for null result (possibly a tuple) */
2466 estate->retval = (Datum) 0;
2467 estate->rettupdesc = NULL;
2468 estate->retisnull = true;
2471 * Special case path when the RETURN expression is a simple variable
2472 * reference; in particular, this path is always taken in functions with
2473 * one or more OUT parameters.
2475 if (stmt->retvarno >= 0)
2477 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2479 switch (retvar->dtype)
2481 case PLPGSQL_DTYPE_VAR:
2483 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2485 estate->retval = var->value;
2486 estate->retisnull = var->isnull;
2487 estate->rettype = var->datatype->typoid;
2491 case PLPGSQL_DTYPE_REC:
2493 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2495 if (HeapTupleIsValid(rec->tup))
2497 estate->retval = PointerGetDatum(rec->tup);
2498 estate->rettupdesc = rec->tupdesc;
2499 estate->retisnull = false;
2504 case PLPGSQL_DTYPE_ROW:
2506 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2508 Assert(row->rowtupdesc);
2510 PointerGetDatum(make_tuple_from_row(estate, row,
2512 if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
2513 elog(ERROR, "row not compatible with its own tupdesc");
2514 estate->rettupdesc = row->rowtupdesc;
2515 estate->retisnull = false;
2520 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2523 return PLPGSQL_RC_RETURN;
2526 if (stmt->expr != NULL)
2530 estate->retval = exec_eval_expr(estate, stmt->expr,
2531 &(estate->retisnull),
2535 if (estate->retistuple && !estate->retisnull)
2537 /* Convert composite datum to a HeapTuple and TupleDesc */
2541 /* Source must be of RECORD or composite type */
2542 if (!type_is_rowtype(estate->rettype))
2544 (errcode(ERRCODE_DATATYPE_MISMATCH),
2545 errmsg("cannot return non-composite value from function returning composite type")));
2546 tuple = get_tuple_from_datum(estate->retval);
2547 tupdesc = get_tupdesc_from_datum(estate->retval);
2548 estate->retval = PointerGetDatum(tuple);
2549 estate->rettupdesc = CreateTupleDescCopy(tupdesc);
2550 ReleaseTupleDesc(tupdesc);
2553 return PLPGSQL_RC_RETURN;
2557 * Special hack for function returning VOID: instead of NULL, return a
2558 * non-null VOID value. This is of dubious importance but is kept for
2559 * backwards compatibility.
2561 if (estate->fn_rettype == VOIDOID)
2563 estate->retval = (Datum) 0;
2564 estate->retisnull = false;
2565 estate->rettype = VOIDOID;
2568 return PLPGSQL_RC_RETURN;
2572 * exec_stmt_return_next Evaluate an expression and add it to the
2573 * list of tuples returned by the current
2578 exec_stmt_return_next(PLpgSQL_execstate *estate,
2579 PLpgSQL_stmt_return_next *stmt)
2583 HeapTuple tuple = NULL;
2584 bool free_tuple = false;
2586 if (!estate->retisset)
2588 (errcode(ERRCODE_SYNTAX_ERROR),
2589 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2591 if (estate->tuple_store == NULL)
2592 exec_init_tuple_store(estate);
2594 /* rettupdesc will be filled by exec_init_tuple_store */
2595 tupdesc = estate->rettupdesc;
2596 natts = tupdesc->natts;
2599 * Special case path when the RETURN NEXT expression is a simple variable
2600 * reference; in particular, this path is always taken in functions with
2601 * one or more OUT parameters.
2603 if (stmt->retvarno >= 0)
2605 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2607 switch (retvar->dtype)
2609 case PLPGSQL_DTYPE_VAR:
2611 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2612 Datum retval = var->value;
2613 bool isNull = var->isnull;
2617 (errcode(ERRCODE_DATATYPE_MISMATCH),
2618 errmsg("wrong result type supplied in RETURN NEXT")));
2620 /* coerce type if needed */
2621 retval = exec_cast_value(estate,
2624 var->datatype->typoid,
2625 var->datatype->atttypmod,
2626 tupdesc->attrs[0]->atttypid,
2627 tupdesc->attrs[0]->atttypmod);
2629 tuplestore_putvalues(estate->tuple_store, tupdesc,
2634 case PLPGSQL_DTYPE_REC:
2636 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2637 TupleConversionMap *tupmap;
2639 if (!HeapTupleIsValid(rec->tup))
2641 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2642 errmsg("record \"%s\" is not assigned yet",
2644 errdetail("The tuple structure of a not-yet-assigned"
2645 " record is indeterminate.")));
2646 tupmap = convert_tuples_by_position(rec->tupdesc,
2648 gettext_noop("wrong record type supplied in RETURN NEXT"));
2650 /* it might need conversion */
2653 tuple = do_convert_tuple(tuple, tupmap);
2654 free_conversion_map(tupmap);
2660 case PLPGSQL_DTYPE_ROW:
2662 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2664 tuple = make_tuple_from_row(estate, row, tupdesc);
2667 (errcode(ERRCODE_DATATYPE_MISMATCH),
2668 errmsg("wrong record type supplied in RETURN NEXT")));
2674 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2678 else if (stmt->expr)
2685 retval = exec_eval_expr(estate,
2691 if (estate->retistuple)
2693 /* Expression should be of RECORD or composite type */
2696 TupleDesc retvaldesc;
2697 TupleConversionMap *tupmap;
2699 if (!type_is_rowtype(rettype))
2701 (errcode(ERRCODE_DATATYPE_MISMATCH),
2702 errmsg("cannot return non-composite value from function returning composite type")));
2704 tuple = get_tuple_from_datum(retval);
2705 free_tuple = true; /* tuple is always freshly palloc'd */
2707 /* it might need conversion */
2708 retvaldesc = get_tupdesc_from_datum(retval);
2709 tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
2710 gettext_noop("returned record type does not match expected record type"));
2715 newtuple = do_convert_tuple(tuple, tupmap);
2716 free_conversion_map(tupmap);
2717 heap_freetuple(tuple);
2720 ReleaseTupleDesc(retvaldesc);
2721 /* tuple will be stored into tuplestore below */
2725 /* Composite NULL --- store a row of nulls */
2729 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
2730 nullflags = (bool *) palloc(natts * sizeof(bool));
2731 memset(nullflags, true, natts * sizeof(bool));
2732 tuplestore_putvalues(estate->tuple_store, tupdesc,
2733 nulldatums, nullflags);
2740 /* Simple scalar result */
2743 (errcode(ERRCODE_DATATYPE_MISMATCH),
2744 errmsg("wrong result type supplied in RETURN NEXT")));
2746 /* coerce type if needed */
2747 retval = exec_cast_value(estate,
2752 tupdesc->attrs[0]->atttypid,
2753 tupdesc->attrs[0]->atttypmod);
2755 tuplestore_putvalues(estate->tuple_store, tupdesc,
2762 (errcode(ERRCODE_SYNTAX_ERROR),
2763 errmsg("RETURN NEXT must have a parameter")));
2766 if (HeapTupleIsValid(tuple))
2768 tuplestore_puttuple(estate->tuple_store, tuple);
2771 heap_freetuple(tuple);
2774 exec_eval_cleanup(estate);
2776 return PLPGSQL_RC_OK;
2780 * exec_stmt_return_query Evaluate a query and add it to the
2781 * list of tuples returned by the current
2786 exec_stmt_return_query(PLpgSQL_execstate *estate,
2787 PLpgSQL_stmt_return_query *stmt)
2790 uint32 processed = 0;
2791 TupleConversionMap *tupmap;
2793 if (!estate->retisset)
2795 (errcode(ERRCODE_SYNTAX_ERROR),
2796 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2798 if (estate->tuple_store == NULL)
2799 exec_init_tuple_store(estate);
2801 if (stmt->query != NULL)
2804 exec_run_select(estate, stmt->query, 0, &portal);
2808 /* RETURN QUERY EXECUTE */
2809 Assert(stmt->dynquery != NULL);
2810 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2811 stmt->params, NULL, 0);
2814 tupmap = convert_tuples_by_position(portal->tupDesc,
2816 gettext_noop("structure of query does not match function result type"));
2822 SPI_cursor_fetch(portal, true, 50);
2823 if (SPI_processed == 0)
2826 for (i = 0; i < SPI_processed; i++)
2828 HeapTuple tuple = SPI_tuptable->vals[i];
2831 tuple = do_convert_tuple(tuple, tupmap);
2832 tuplestore_puttuple(estate->tuple_store, tuple);
2834 heap_freetuple(tuple);
2838 SPI_freetuptable(SPI_tuptable);
2842 free_conversion_map(tupmap);
2844 SPI_freetuptable(SPI_tuptable);
2845 SPI_cursor_close(portal);
2847 estate->eval_processed = processed;
2848 exec_set_found(estate, processed != 0);
2850 return PLPGSQL_RC_OK;
2854 exec_init_tuple_store(PLpgSQL_execstate *estate)
2856 ReturnSetInfo *rsi = estate->rsi;
2857 MemoryContext oldcxt;
2858 ResourceOwner oldowner;
2861 * Check caller can handle a set result in the way we want
2863 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2864 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2865 rsi->expectedDesc == NULL)
2867 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2868 errmsg("set-valued function called in context that cannot accept a set")));
2871 * Switch to the right memory context and resource owner for storing the
2872 * tuplestore for return set. If we're within a subtransaction opened for
2873 * an exception-block, for example, we must still create the tuplestore in
2874 * the resource owner that was active when this function was entered, and
2875 * not in the subtransaction resource owner.
2877 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2878 oldowner = CurrentResourceOwner;
2879 CurrentResourceOwner = estate->tuple_store_owner;
2881 estate->tuple_store =
2882 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2885 CurrentResourceOwner = oldowner;
2886 MemoryContextSwitchTo(oldcxt);
2888 estate->rettupdesc = rsi->expectedDesc;
2891 #define SET_RAISE_OPTION_TEXT(opt, name) \
2895 (errcode(ERRCODE_SYNTAX_ERROR), \
2896 errmsg("RAISE option already specified: %s", \
2898 opt = pstrdup(extval); \
2902 * exec_stmt_raise Build a message and throw it with elog()
2906 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2909 char *condname = NULL;
2910 char *err_message = NULL;
2911 char *err_detail = NULL;
2912 char *err_hint = NULL;
2913 char *err_column = NULL;
2914 char *err_constraint = NULL;
2915 char *err_datatype = NULL;
2916 char *err_table = NULL;
2917 char *err_schema = NULL;
2920 /* RAISE with no parameters: re-throw current exception */
2921 if (stmt->condname == NULL && stmt->message == NULL &&
2922 stmt->options == NIL)
2924 if (estate->cur_error != NULL)
2925 ReThrowError(estate->cur_error);
2926 /* oops, we're not inside a handler */
2928 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2929 errmsg("RAISE without parameters cannot be used outside an exception handler")));
2934 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2935 condname = pstrdup(stmt->condname);
2941 ListCell *current_param;
2944 initStringInfo(&ds);
2945 current_param = list_head(stmt->params);
2947 for (cp = stmt->message; *cp; cp++)
2950 * Occurrences of a single % are replaced by the next parameter's
2951 * external representation. Double %'s are converted to one %.
2963 appendStringInfoChar(&ds, '%');
2968 /* should have been checked at compile time */
2969 if (current_param == NULL)
2970 elog(ERROR, "unexpected RAISE parameter list length");
2972 paramvalue = exec_eval_expr(estate,
2973 (PLpgSQL_expr *) lfirst(current_param),
2981 extval = convert_value_to_string(estate,
2984 appendStringInfoString(&ds, extval);
2985 current_param = lnext(current_param);
2986 exec_eval_cleanup(estate);
2989 appendStringInfoChar(&ds, cp[0]);
2992 /* should have been checked at compile time */
2993 if (current_param != NULL)
2994 elog(ERROR, "unexpected RAISE parameter list length");
2996 err_message = ds.data;
2997 /* No pfree(ds.data), the pfree(err_message) does it */
3000 foreach(lc, stmt->options)
3002 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
3009 optionvalue = exec_eval_expr(estate, opt->expr,
3015 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3016 errmsg("RAISE statement option cannot be null")));
3018 extval = convert_value_to_string(estate, optionvalue, optiontypeid);
3020 switch (opt->opt_type)
3022 case PLPGSQL_RAISEOPTION_ERRCODE:
3025 (errcode(ERRCODE_SYNTAX_ERROR),
3026 errmsg("RAISE option already specified: %s",
3028 err_code = plpgsql_recognize_err_condition(extval, true);
3029 condname = pstrdup(extval);
3031 case PLPGSQL_RAISEOPTION_MESSAGE:
3032 SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3034 case PLPGSQL_RAISEOPTION_DETAIL:
3035 SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3037 case PLPGSQL_RAISEOPTION_HINT:
3038 SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3040 case PLPGSQL_RAISEOPTION_COLUMN:
3041 SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3043 case PLPGSQL_RAISEOPTION_CONSTRAINT:
3044 SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3046 case PLPGSQL_RAISEOPTION_DATATYPE:
3047 SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3049 case PLPGSQL_RAISEOPTION_TABLE:
3050 SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3052 case PLPGSQL_RAISEOPTION_SCHEMA:
3053 SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3056 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3059 exec_eval_cleanup(estate);
3062 /* Default code if nothing specified */
3063 if (err_code == 0 && stmt->elog_level >= ERROR)
3064 err_code = ERRCODE_RAISE_EXCEPTION;
3066 /* Default error message if nothing specified */
3067 if (err_message == NULL)
3071 err_message = condname;
3075 err_message = pstrdup(unpack_sql_state(err_code));
3079 * Throw the error (may or may not come back)
3081 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
3083 ereport(stmt->elog_level,
3084 (err_code ? errcode(err_code) : 0,
3085 errmsg_internal("%s", err_message),
3086 (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3087 (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3088 (err_column != NULL) ?
3089 err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3090 (err_constraint != NULL) ?
3091 err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3092 (err_datatype != NULL) ?
3093 err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3094 (err_table != NULL) ?
3095 err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3096 (err_schema != NULL) ?
3097 err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3099 estate->err_text = NULL; /* un-suppress... */
3101 if (condname != NULL)
3103 if (err_message != NULL)
3105 if (err_detail != NULL)
3107 if (err_hint != NULL)
3109 if (err_column != NULL)
3111 if (err_constraint != NULL)
3112 pfree(err_constraint);
3113 if (err_datatype != NULL)
3114 pfree(err_datatype);
3115 if (err_table != NULL)
3117 if (err_schema != NULL)
3120 return PLPGSQL_RC_OK;
3125 * Initialize a mostly empty execution state
3129 plpgsql_estate_setup(PLpgSQL_execstate *estate,
3130 PLpgSQL_function *func,
3132 EState *simple_eval_estate)
3134 /* this link will be restored at exit from plpgsql_call_handler */
3135 func->cur_estate = estate;
3137 estate->func = func;
3139 estate->retval = (Datum) 0;
3140 estate->retisnull = true;
3141 estate->rettype = InvalidOid;
3143 estate->fn_rettype = func->fn_rettype;
3144 estate->retistuple = func->fn_retistuple;
3145 estate->retisset = func->fn_retset;
3147 estate->readonly_func = func->fn_readonly;
3149 estate->rettupdesc = NULL;
3150 estate->exitlabel = NULL;
3151 estate->cur_error = NULL;
3153 estate->tuple_store = NULL;
3156 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
3157 estate->tuple_store_owner = CurrentResourceOwner;
3161 estate->tuple_store_cxt = NULL;
3162 estate->tuple_store_owner = NULL;
3166 estate->found_varno = func->found_varno;
3167 estate->ndatums = func->ndatums;
3168 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
3169 /* caller is expected to fill the datums array */
3171 /* set up for use of appropriate simple-expression EState */
3172 if (simple_eval_estate)
3173 estate->simple_eval_estate = simple_eval_estate;
3175 estate->simple_eval_estate = shared_simple_eval_estate;
3177 estate->eval_tuptable = NULL;
3178 estate->eval_processed = 0;
3179 estate->eval_lastoid = InvalidOid;
3180 estate->eval_econtext = NULL;
3181 estate->cur_expr = NULL;
3183 estate->err_stmt = NULL;
3184 estate->err_text = NULL;
3186 estate->plugin_info = NULL;
3189 * Create an EState and ExprContext for evaluation of simple expressions.
3191 plpgsql_create_econtext(estate);
3194 * Let the plugin see this function before we initialize any local
3195 * PL/pgSQL variables - note that we also give the plugin a few function
3196 * pointers so it can call back into PL/pgSQL for doing things like
3197 * variable assignments and stack traces
3201 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
3202 (*plugin_ptr)->assign_expr = exec_assign_expr;
3204 if ((*plugin_ptr)->func_setup)
3205 ((*plugin_ptr)->func_setup) (estate, func);
3210 * Release temporary memory used by expression/subselect evaluation
3212 * NB: the result of the evaluation is no longer valid after this is done,
3213 * unless it is a pass-by-value datatype.
3215 * NB: if you change this code, see also the hacks in exec_assign_value's
3216 * PLPGSQL_DTYPE_ARRAYELEM case.
3220 exec_eval_cleanup(PLpgSQL_execstate *estate)
3222 /* Clear result of a full SPI_execute */
3223 if (estate->eval_tuptable != NULL)
3224 SPI_freetuptable(estate->eval_tuptable);
3225 estate->eval_tuptable = NULL;
3227 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
3228 if (estate->eval_econtext != NULL)
3229 ResetExprContext(estate->eval_econtext);
3234 * Generate a prepared plan
3238 exec_prepare_plan(PLpgSQL_execstate *estate,
3239 PLpgSQL_expr *expr, int cursorOptions)
3244 * The grammar can't conveniently set expr->func while building the parse
3245 * tree, so make sure it's set before parser hooks need it.
3247 expr->func = estate->func;
3250 * Generate and save the plan
3252 plan = SPI_prepare_params(expr->query,
3253 (ParserSetupHook) plpgsql_parser_setup,
3258 /* Some SPI errors deserve specific error messages */
3261 case SPI_ERROR_COPY:
3263 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3264 errmsg("cannot COPY to/from client in PL/pgSQL")));
3265 case SPI_ERROR_TRANSACTION:
3267 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3268 errmsg("cannot begin/end transactions in PL/pgSQL"),
3269 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3271 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
3272 expr->query, SPI_result_code_string(SPI_result));
3278 /* Check to see if it's a simple expression */
3279 exec_simple_check_plan(expr);
3284 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
3288 exec_stmt_execsql(PLpgSQL_execstate *estate,
3289 PLpgSQL_stmt_execsql *stmt)
3291 ParamListInfo paramLI;
3294 PLpgSQL_expr *expr = stmt->sqlstmt;
3297 * On the first call for this statement generate the plan, and detect
3298 * whether the statement is INSERT/UPDATE/DELETE
3300 if (expr->plan == NULL)
3304 exec_prepare_plan(estate, expr, 0);
3305 stmt->mod_stmt = false;
3306 foreach(l, SPI_plan_get_plan_sources(expr->plan))
3308 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
3311 foreach(l2, plansource->query_list)
3313 Query *q = (Query *) lfirst(l2);
3315 Assert(IsA(q, Query));
3318 if (q->commandType == CMD_INSERT ||
3319 q->commandType == CMD_UPDATE ||
3320 q->commandType == CMD_DELETE)
3321 stmt->mod_stmt = true;
3328 * Set up ParamListInfo (hook function and possibly data values)
3330 paramLI = setup_param_list(estate, expr);
3333 * If we have INTO, then we only need one row back ... but if we have INTO
3334 * STRICT, ask for two rows, so that we can verify the statement returns
3335 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
3336 * INTO, just run the statement to completion (tcount = 0).
3338 * We could just ask for two rows always when using INTO, but there are
3339 * some cases where demanding the extra row costs significant time, eg by
3340 * forcing completion of a sequential scan. So don't do it unless we need
3341 * to enforce strictness.
3345 if (stmt->strict || stmt->mod_stmt)
3356 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
3357 estate->readonly_func, tcount);
3360 * Check for error, and set FOUND if appropriate (for historical reasons
3361 * we set FOUND only for certain query types). Also Assert that we
3362 * identified the statement type the same as SPI did.
3367 Assert(!stmt->mod_stmt);
3368 exec_set_found(estate, (SPI_processed != 0));
3374 case SPI_OK_INSERT_RETURNING:
3375 case SPI_OK_UPDATE_RETURNING:
3376 case SPI_OK_DELETE_RETURNING:
3377 Assert(stmt->mod_stmt);
3378 exec_set_found(estate, (SPI_processed != 0));
3381 case SPI_OK_SELINTO:
3382 case SPI_OK_UTILITY:
3383 Assert(!stmt->mod_stmt);
3386 case SPI_OK_REWRITTEN:
3387 Assert(!stmt->mod_stmt);
3390 * The command was rewritten into another kind of command. It's
3391 * not clear what FOUND would mean in that case (and SPI doesn't
3392 * return the row count either), so just set it to false.
3394 exec_set_found(estate, false);
3397 /* Some SPI errors deserve specific error messages */
3398 case SPI_ERROR_COPY:
3400 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3401 errmsg("cannot COPY to/from client in PL/pgSQL")));
3402 case SPI_ERROR_TRANSACTION:
3404 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3405 errmsg("cannot begin/end transactions in PL/pgSQL"),
3406 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3409 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
3410 expr->query, SPI_result_code_string(rc));
3413 /* All variants should save result info for GET DIAGNOSTICS */
3414 estate->eval_processed = SPI_processed;
3415 estate->eval_lastoid = SPI_lastoid;
3417 /* Process INTO if present */
3420 SPITupleTable *tuptab = SPI_tuptable;
3421 uint32 n = SPI_processed;
3422 PLpgSQL_rec *rec = NULL;
3423 PLpgSQL_row *row = NULL;
3425 /* If the statement did not return a tuple table, complain */
3428 (errcode(ERRCODE_SYNTAX_ERROR),
3429 errmsg("INTO used with a command that cannot return data")));
3431 /* Determine if we assign to a record or a row */
3432 if (stmt->rec != NULL)
3433 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3434 else if (stmt->row != NULL)
3435 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3437 elog(ERROR, "unsupported target");
3440 * If SELECT ... INTO specified STRICT, and the query didn't find
3441 * exactly one row, throw an error. If STRICT was not specified, then
3442 * allow the query to find any number of rows.
3450 if (estate->func->print_strict_params)
3451 errdetail = format_expr_params(estate, expr);
3456 (errcode(ERRCODE_NO_DATA_FOUND),
3457 errmsg("query returned no rows"),
3458 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3460 /* set the target to NULL(s) */
3461 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3465 if (n > 1 && (stmt->strict || stmt->mod_stmt))
3469 if (estate->func->print_strict_params)
3470 errdetail = format_expr_params(estate, expr);
3475 (errcode(ERRCODE_TOO_MANY_ROWS),
3476 errmsg("query returned more than one row"),
3477 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3479 /* Put the first result row into the target */
3480 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3484 exec_eval_cleanup(estate);
3485 SPI_freetuptable(SPI_tuptable);
3489 /* If the statement returned a tuple table, complain */
3490 if (SPI_tuptable != NULL)
3492 (errcode(ERRCODE_SYNTAX_ERROR),
3493 errmsg("query has no destination for result data"),
3494 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
3500 return PLPGSQL_RC_OK;
3505 * exec_stmt_dynexecute Execute a dynamic SQL query
3506 * (possibly with INTO).
3510 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
3511 PLpgSQL_stmt_dynexecute *stmt)
3519 PreparedParamsData *ppd = NULL;
3522 * First we evaluate the string expression after the EXECUTE keyword. Its
3523 * result is the querystring we have to execute.
3525 query = exec_eval_expr(estate, stmt->query, &isnull, &restype, &restypmod);
3528 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3529 errmsg("query string argument of EXECUTE is null")));
3531 /* Get the C-String representation */
3532 querystr = convert_value_to_string(estate, query, restype);
3534 /* copy it out of the temporary context before we clean up */
3535 querystr = pstrdup(querystr);
3537 exec_eval_cleanup(estate);
3540 * Execute the query without preparing a saved plan.
3544 ppd = exec_eval_using_params(estate, stmt->params);
3545 exec_res = SPI_execute_with_args(querystr,
3546 ppd->nargs, ppd->types,
3547 ppd->values, ppd->nulls,
3548 estate->readonly_func, 0);
3551 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
3559 case SPI_OK_INSERT_RETURNING:
3560 case SPI_OK_UPDATE_RETURNING:
3561 case SPI_OK_DELETE_RETURNING:
3562 case SPI_OK_UTILITY:
3563 case SPI_OK_REWRITTEN:
3569 * Also allow a zero return, which implies the querystring
3570 * contained no commands.
3574 case SPI_OK_SELINTO:
3577 * We want to disallow SELECT INTO for now, because its behavior
3578 * is not consistent with SELECT INTO in a normal plpgsql context.
3579 * (We need to reimplement EXECUTE to parse the string as a
3580 * plpgsql command, not just feed it to SPI_execute.) This is not
3581 * a functional limitation because CREATE TABLE AS is allowed.
3584 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3585 errmsg("EXECUTE of SELECT ... INTO is not implemented"),
3586 errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
3589 /* Some SPI errors deserve specific error messages */
3590 case SPI_ERROR_COPY:
3592 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3593 errmsg("cannot COPY to/from client in PL/pgSQL")));
3594 case SPI_ERROR_TRANSACTION:
3596 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3597 errmsg("cannot begin/end transactions in PL/pgSQL"),
3598 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3601 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3602 querystr, SPI_result_code_string(exec_res));
3606 /* Save result info for GET DIAGNOSTICS */
3607 estate->eval_processed = SPI_processed;
3608 estate->eval_lastoid = SPI_lastoid;
3610 /* Process INTO if present */
3613 SPITupleTable *tuptab = SPI_tuptable;
3614 uint32 n = SPI_processed;
3615 PLpgSQL_rec *rec = NULL;
3616 PLpgSQL_row *row = NULL;
3618 /* If the statement did not return a tuple table, complain */
3621 (errcode(ERRCODE_SYNTAX_ERROR),
3622 errmsg("INTO used with a command that cannot return data")));
3624 /* Determine if we assign to a record or a row */
3625 if (stmt->rec != NULL)
3626 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3627 else if (stmt->row != NULL)
3628 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3630 elog(ERROR, "unsupported target");
3633 * If SELECT ... INTO specified STRICT, and the query didn't find
3634 * exactly one row, throw an error. If STRICT was not specified, then
3635 * allow the query to find any number of rows.
3643 if (estate->func->print_strict_params)
3644 errdetail = format_preparedparamsdata(estate, ppd);
3649 (errcode(ERRCODE_NO_DATA_FOUND),
3650 errmsg("query returned no rows"),
3651 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3653 /* set the target to NULL(s) */
3654 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3658 if (n > 1 && stmt->strict)
3662 if (estate->func->print_strict_params)
3663 errdetail = format_preparedparamsdata(estate, ppd);
3668 (errcode(ERRCODE_TOO_MANY_ROWS),
3669 errmsg("query returned more than one row"),
3670 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3673 /* Put the first result row into the target */
3674 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3676 /* clean up after exec_move_row() */
3677 exec_eval_cleanup(estate);
3682 * It might be a good idea to raise an error if the query returned
3683 * tuples that are being ignored, but historically we have not done
3689 free_params_data(ppd);
3691 /* Release any result from SPI_execute, as well as the querystring */
3692 SPI_freetuptable(SPI_tuptable);
3695 return PLPGSQL_RC_OK;
3700 * exec_stmt_dynfors Execute a dynamic query, assign each
3701 * tuple to a record or row and
3702 * execute a group of statements
3707 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3712 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
3718 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3721 * Close the implicit cursor
3723 SPI_cursor_close(portal);
3730 * exec_stmt_open Execute an OPEN cursor statement
3734 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3736 PLpgSQL_var *curvar;
3737 char *curname = NULL;
3738 PLpgSQL_expr *query;
3740 ParamListInfo paramLI;
3743 * Get the cursor variable and if it has an assigned name, check
3744 * that it's not in use currently.
3747 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3748 if (!curvar->isnull)
3750 curname = TextDatumGetCString(curvar->value);
3751 if (SPI_cursor_find(curname) != NULL)
3753 (errcode(ERRCODE_DUPLICATE_CURSOR),
3754 errmsg("cursor \"%s\" already in use", curname)));
3758 * Process the OPEN according to it's type.
3761 if (stmt->query != NULL)
3764 * This is an OPEN refcursor FOR SELECT ...
3766 * We just make sure the query is planned. The real work is
3770 query = stmt->query;
3771 if (query->plan == NULL)
3772 exec_prepare_plan(estate, query, stmt->cursor_options);
3774 else if (stmt->dynquery != NULL)
3777 * This is an OPEN refcursor FOR EXECUTE ...
3780 portal = exec_dynquery_with_params(estate,
3784 stmt->cursor_options);
3787 * If cursor variable was NULL, store the generated portal name in it
3789 if (curname == NULL)
3790 assign_text_var(curvar, portal->name);
3792 return PLPGSQL_RC_OK;
3797 * This is an OPEN cursor
3799 * Note: parser should already have checked that statement supplies
3800 * args iff cursor needs them, but we check again to be safe.
3803 if (stmt->argquery != NULL)
3806 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3807 * statement to evaluate the args and put 'em into the
3811 PLpgSQL_stmt_execsql set_args;
3813 if (curvar->cursor_explicit_argrow < 0)
3815 (errcode(ERRCODE_SYNTAX_ERROR),
3816 errmsg("arguments given for cursor without arguments")));
3818 memset(&set_args, 0, sizeof(set_args));
3819 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3820 set_args.lineno = stmt->lineno;
3821 set_args.sqlstmt = stmt->argquery;
3822 set_args.into = true;
3823 /* XXX historically this has not been STRICT */
3824 set_args.row = (PLpgSQL_row *)
3825 (estate->datums[curvar->cursor_explicit_argrow]);
3827 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3828 elog(ERROR, "open cursor failed during argument processing");
3832 if (curvar->cursor_explicit_argrow >= 0)
3834 (errcode(ERRCODE_SYNTAX_ERROR),
3835 errmsg("arguments required for cursor")));
3838 query = curvar->cursor_explicit_expr;
3839 if (query->plan == NULL)
3840 exec_prepare_plan(estate, query, curvar->cursor_options);
3844 * Set up ParamListInfo (hook function and possibly data values)
3846 paramLI = setup_param_list(estate, query);
3851 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3853 estate->readonly_func);
3855 elog(ERROR, "could not open cursor: %s",
3856 SPI_result_code_string(SPI_result));
3859 * If cursor variable was NULL, store the generated portal name in it
3861 if (curname == NULL)
3862 assign_text_var(curvar, portal->name);
3869 return PLPGSQL_RC_OK;
3874 * exec_stmt_fetch Fetch from a cursor into a target, or just
3875 * move the current position of the cursor
3879 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3881 PLpgSQL_var *curvar = NULL;
3882 PLpgSQL_rec *rec = NULL;
3883 PLpgSQL_row *row = NULL;
3884 long how_many = stmt->how_many;
3885 SPITupleTable *tuptab;
3891 * Get the portal of the cursor by name
3894 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3897 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3898 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3899 curname = TextDatumGetCString(curvar->value);
3901 portal = SPI_cursor_find(curname);
3904 (errcode(ERRCODE_UNDEFINED_CURSOR),
3905 errmsg("cursor \"%s\" does not exist", curname)));
3908 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3913 /* XXX should be doing this in LONG not INT width */
3914 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3918 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3919 errmsg("relative or absolute cursor position is null")));
3921 exec_eval_cleanup(estate);
3927 * Determine if we fetch into a record or a row
3930 if (stmt->rec != NULL)
3931 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3932 else if (stmt->row != NULL)
3933 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3935 elog(ERROR, "unsupported target");
3938 * Fetch 1 tuple from the cursor
3941 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3942 tuptab = SPI_tuptable;
3946 * Set the target appropriately.
3950 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3952 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3954 exec_eval_cleanup(estate);
3955 SPI_freetuptable(tuptab);
3959 /* Move the cursor */
3960 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3964 /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3965 estate->eval_processed = n;
3966 exec_set_found(estate, n != 0);
3968 return PLPGSQL_RC_OK;
3972 * exec_stmt_close Close a cursor
3976 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3978 PLpgSQL_var *curvar = NULL;
3983 * Get the portal of the cursor by name
3986 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3989 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3990 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3991 curname = TextDatumGetCString(curvar->value);
3993 portal = SPI_cursor_find(curname);
3996 (errcode(ERRCODE_UNDEFINED_CURSOR),
3997 errmsg("cursor \"%s\" does not exist", curname)));
4004 SPI_cursor_close(portal);
4006 return PLPGSQL_RC_OK;
4011 * exec_assign_expr Put an expression's result into a variable.
4015 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4023 value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4024 exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4025 exec_eval_cleanup(estate);
4030 * exec_assign_c_string Put a C string into a text variable.
4032 * We take a NULL pointer as signifying empty string, not SQL null.
4036 exec_assign_c_string(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4042 value = cstring_to_text(str);
4044 value = cstring_to_text("");
4045 exec_assign_value(estate, target, PointerGetDatum(value), false,
4052 * exec_assign_value Put a value into a target field
4054 * Note: in some code paths, this will leak memory in the eval_econtext;
4055 * we assume that will be cleaned up later by exec_eval_cleanup. We cannot
4056 * call exec_eval_cleanup here for fear of destroying the input Datum value.
4060 exec_assign_value(PLpgSQL_execstate *estate,
4061 PLpgSQL_datum *target,
4062 Datum value, bool isNull,
4063 Oid valtype, int32 valtypmod)
4065 switch (target->dtype)
4067 case PLPGSQL_DTYPE_VAR:
4070 * Target is a variable
4072 PLpgSQL_var *var = (PLpgSQL_var *) target;
4075 newvalue = exec_cast_value(estate,
4080 var->datatype->typoid,
4081 var->datatype->atttypmod);
4083 if (isNull && var->notnull)
4085 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4086 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4090 * If type is by-reference, copy the new value (which is
4091 * probably in the eval_econtext) into the procedure's memory
4094 if (!var->datatype->typbyval && !isNull)
4095 newvalue = datumCopy(newvalue,
4097 var->datatype->typlen);
4100 * Now free the old value. (We can't do this any earlier
4101 * because of the possibility that we are assigning the var's
4102 * old value to it, eg "foo := foo". We could optimize out
4103 * the assignment altogether in such cases, but it's too
4104 * infrequent to be worth testing for.)
4108 var->value = newvalue;
4109 var->isnull = isNull;
4110 if (!var->datatype->typbyval && !isNull)
4111 var->freeval = true;
4115 case PLPGSQL_DTYPE_ROW:
4118 * Target is a row variable
4120 PLpgSQL_row *row = (PLpgSQL_row *) target;
4124 /* If source is null, just assign nulls to the row */
4125 exec_move_row(estate, NULL, row, NULL, NULL);
4129 /* Source must be of RECORD or composite type */
4130 if (!type_is_rowtype(valtype))
4132 (errcode(ERRCODE_DATATYPE_MISMATCH),
4133 errmsg("cannot assign non-composite value to a row variable")));
4134 exec_move_row_from_datum(estate, NULL, row, value);
4139 case PLPGSQL_DTYPE_REC:
4142 * Target is a record variable
4144 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
4148 /* If source is null, just assign nulls to the record */
4149 exec_move_row(estate, rec, NULL, NULL, NULL);
4153 /* Source must be of RECORD or composite type */
4154 if (!type_is_rowtype(valtype))
4156 (errcode(ERRCODE_DATATYPE_MISMATCH),
4157 errmsg("cannot assign non-composite value to a record variable")));
4158 exec_move_row_from_datum(estate, rec, NULL, value);
4163 case PLPGSQL_DTYPE_RECFIELD:
4166 * Target is a field of a record
4168 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
4179 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4182 * Check that there is already a tuple in the record. We need
4183 * that because records don't have any predefined field
4186 if (!HeapTupleIsValid(rec->tup))
4188 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4189 errmsg("record \"%s\" is not assigned yet",
4191 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4194 * Get the number of the records field to change and the
4195 * number of attributes in the tuple. Note: disallow system
4196 * column names because the code below won't cope.
4198 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4201 (errcode(ERRCODE_UNDEFINED_COLUMN),
4202 errmsg("record \"%s\" has no field \"%s\"",
4203 rec->refname, recfield->fieldname)));
4205 natts = rec->tupdesc->natts;
4208 * Set up values/control arrays for heap_modify_tuple. For all
4209 * the attributes except the one we want to replace, use the
4210 * value that's in the old tuple.
4212 values = palloc(sizeof(Datum) * natts);
4213 nulls = palloc(sizeof(bool) * natts);
4214 replaces = palloc(sizeof(bool) * natts);
4216 memset(replaces, false, sizeof(bool) * natts);
4217 replaces[fno] = true;
4220 * Now insert the new value, being careful to cast it to the
4223 atttype = rec->tupdesc->attrs[fno]->atttypid;
4224 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
4225 values[fno] = exec_cast_value(estate,
4232 nulls[fno] = isNull;
4235 * Now call heap_modify_tuple() to create a new tuple that
4236 * replaces the old one in the record.
4238 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
4239 values, nulls, replaces);
4242 heap_freetuple(rec->tup);
4245 rec->freetup = true;
4254 case PLPGSQL_DTYPE_ARRAYELEM:
4257 * Target is an element of an array
4259 PLpgSQL_arrayelem *arrayelem;
4262 PLpgSQL_expr *subscripts[MAXDIM];
4263 int subscriptvals[MAXDIM];
4264 Datum oldarraydatum,
4267 bool oldarrayisnull;
4270 SPITupleTable *save_eval_tuptable;
4271 MemoryContext oldcontext;
4274 * We need to do subscript evaluation, which might require
4275 * evaluating general expressions; and the caller might have
4276 * done that too in order to prepare the input Datum. We have
4277 * to save and restore the caller's SPI_execute result, if
4280 save_eval_tuptable = estate->eval_tuptable;
4281 estate->eval_tuptable = NULL;
4284 * To handle constructs like x[1][2] := something, we have to
4285 * be prepared to deal with a chain of arrayelem datums. Chase
4286 * back to find the base array datum, and save the subscript
4287 * expressions as we go. (We are scanning right to left here,
4288 * but want to evaluate the subscripts left-to-right to
4289 * minimize surprises.) Note that arrayelem is left pointing
4290 * to the leftmost arrayelem datum, where we will cache the
4291 * array element type data.
4296 arrayelem = (PLpgSQL_arrayelem *) target;
4297 if (nsubscripts >= MAXDIM)
4299 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4300 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
4301 nsubscripts + 1, MAXDIM)));
4302 subscripts[nsubscripts++] = arrayelem->subscript;
4303 target = estate->datums[arrayelem->arrayparentno];
4304 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
4306 /* Fetch current value of array datum */
4307 exec_eval_datum(estate, target,
4308 &parenttypoid, &parenttypmod,
4309 &oldarraydatum, &oldarrayisnull);
4311 /* Update cached type data if necessary */
4312 if (arrayelem->parenttypoid != parenttypoid ||
4313 arrayelem->parenttypmod != parenttypmod)
4316 int32 arraytypmod = parenttypmod;
4323 /* If target is domain over array, reduce to base type */
4324 arraytypoid = getBaseTypeAndTypmod(parenttypoid,
4327 /* ... and identify the element type */
4328 elemtypoid = get_element_type(arraytypoid);
4329 if (!OidIsValid(elemtypoid))
4331 (errcode(ERRCODE_DATATYPE_MISMATCH),
4332 errmsg("subscripted object is not an array")));
4334 /* Collect needed data about the types */
4335 arraytyplen = get_typlen(arraytypoid);
4337 get_typlenbyvalalign(elemtypoid,
4342 /* Now safe to update the cached data */
4343 arrayelem->parenttypoid = parenttypoid;
4344 arrayelem->parenttypmod = parenttypmod;
4345 arrayelem->arraytypoid = arraytypoid;
4346 arrayelem->arraytypmod = arraytypmod;
4347 arrayelem->arraytyplen = arraytyplen;
4348 arrayelem->elemtypoid = elemtypoid;
4349 arrayelem->elemtyplen = elemtyplen;
4350 arrayelem->elemtypbyval = elemtypbyval;
4351 arrayelem->elemtypalign = elemtypalign;
4355 * Evaluate the subscripts, switch into left-to-right order.
4356 * Like ExecEvalArrayRef(), complain if any subscript is null.
4358 for (i = 0; i < nsubscripts; i++)
4363 exec_eval_integer(estate,
4364 subscripts[nsubscripts - 1 - i],
4368 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4369 errmsg("array subscript in assignment must not be null")));
4372 * Clean up in case the subscript expression wasn't
4373 * simple. We can't do exec_eval_cleanup, but we can do
4374 * this much (which is safe because the integer subscript
4375 * value is surely pass-by-value), and we must do it in
4376 * case the next subscript expression isn't simple either.
4378 if (estate->eval_tuptable != NULL)
4379 SPI_freetuptable(estate->eval_tuptable);
4380 estate->eval_tuptable = NULL;
4383 /* Now we can restore caller's SPI_execute result if any. */
4384 Assert(estate->eval_tuptable == NULL);
4385 estate->eval_tuptable = save_eval_tuptable;
4387 /* Coerce source value to match array element type. */
4388 coerced_value = exec_cast_value(estate,
4393 arrayelem->elemtypoid,
4394 arrayelem->arraytypmod);
4397 * If the original array is null, cons up an empty array so
4398 * that the assignment can proceed; we'll end with a
4399 * one-element array containing just the assigned-to
4400 * subscript. This only works for varlena arrays, though; for
4401 * fixed-length array types we skip the assignment. We can't
4402 * support assignment of a null entry into a fixed-length
4403 * array, either, so that's a no-op too. This is all ugly but
4404 * corresponds to the current behavior of ExecEvalArrayRef().
4406 if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
4407 (oldarrayisnull || isNull))
4410 /* empty array, if any, and newarraydatum are short-lived */
4411 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4414 oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
4417 * Build the modified array value.
4419 newarraydatum = array_set_element(oldarraydatum,
4424 arrayelem->arraytyplen,
4425 arrayelem->elemtyplen,
4426 arrayelem->elemtypbyval,
4427 arrayelem->elemtypalign);
4429 MemoryContextSwitchTo(oldcontext);
4432 * Assign the new array to the base variable. It's never NULL
4433 * at this point. Note that if the target is a domain,
4434 * coercing the base array type back up to the domain will
4435 * happen within exec_assign_value.
4437 exec_assign_value(estate, target,
4440 arrayelem->arraytypoid,
4441 arrayelem->arraytypmod);
4446 elog(ERROR, "unrecognized dtype: %d", target->dtype);
4451 * exec_eval_datum Get current value of a PLpgSQL_datum
4453 * The type oid, typmod, value in Datum format, and null flag are returned.
4455 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
4457 * NOTE: caller must not modify the returned value, since it points right
4458 * at the stored value in the case of pass-by-reference datatypes. In some
4459 * cases we have to palloc a return value, and in such cases we put it into
4460 * the estate's short-term memory context.
4463 exec_eval_datum(PLpgSQL_execstate *estate,
4464 PLpgSQL_datum *datum,
4470 MemoryContext oldcontext;
4472 switch (datum->dtype)
4474 case PLPGSQL_DTYPE_VAR:
4476 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4478 *typeid = var->datatype->typoid;
4479 *typetypmod = var->datatype->atttypmod;
4480 *value = var->value;
4481 *isnull = var->isnull;
4485 case PLPGSQL_DTYPE_ROW:
4487 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4490 if (!row->rowtupdesc) /* should not happen */
4491 elog(ERROR, "row variable has no tupdesc");
4492 /* Make sure we have a valid type/typmod setting */
4493 BlessTupleDesc(row->rowtupdesc);
4494 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4495 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
4496 if (tup == NULL) /* should not happen */
4497 elog(ERROR, "row not compatible with its own tupdesc");
4498 *typeid = row->rowtupdesc->tdtypeid;
4499 *typetypmod = row->rowtupdesc->tdtypmod;
4500 *value = HeapTupleGetDatum(tup);
4502 MemoryContextSwitchTo(oldcontext);
4506 case PLPGSQL_DTYPE_REC:
4508 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4510 if (!HeapTupleIsValid(rec->tup))
4512 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4513 errmsg("record \"%s\" is not assigned yet",
4515 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4516 Assert(rec->tupdesc != NULL);
4517 /* Make sure we have a valid type/typmod setting */
4518 BlessTupleDesc(rec->tupdesc);
4520 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4521 *typeid = rec->tupdesc->tdtypeid;
4522 *typetypmod = rec->tupdesc->tdtypmod;
4523 *value = heap_copy_tuple_as_datum(rec->tup, rec->tupdesc);
4525 MemoryContextSwitchTo(oldcontext);
4529 case PLPGSQL_DTYPE_RECFIELD:
4531 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4535 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4536 if (!HeapTupleIsValid(rec->tup))
4538 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4539 errmsg("record \"%s\" is not assigned yet",
4541 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4542 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4543 if (fno == SPI_ERROR_NOATTRIBUTE)
4545 (errcode(ERRCODE_UNDEFINED_COLUMN),
4546 errmsg("record \"%s\" has no field \"%s\"",
4547 rec->refname, recfield->fieldname)));
4548 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4550 *typetypmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4553 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
4558 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4563 * exec_get_datum_type Get datatype of a PLpgSQL_datum
4565 * This is the same logic as in exec_eval_datum, except that it can handle
4566 * some cases where exec_eval_datum has to fail; specifically, we may have
4567 * a tupdesc but no row value for a record variable. (This currently can
4568 * happen only for a trigger's NEW/OLD records.)
4571 exec_get_datum_type(PLpgSQL_execstate *estate,
4572 PLpgSQL_datum *datum)
4576 switch (datum->dtype)
4578 case PLPGSQL_DTYPE_VAR:
4580 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4582 typeid = var->datatype->typoid;
4586 case PLPGSQL_DTYPE_ROW:
4588 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4590 if (!row->rowtupdesc) /* should not happen */
4591 elog(ERROR, "row variable has no tupdesc");
4592 /* Make sure we have a valid type/typmod setting */
4593 BlessTupleDesc(row->rowtupdesc);
4594 typeid = row->rowtupdesc->tdtypeid;
4598 case PLPGSQL_DTYPE_REC:
4600 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4602 if (rec->tupdesc == NULL)
4604 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4605 errmsg("record \"%s\" is not assigned yet",
4607 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4608 /* Make sure we have a valid type/typmod setting */
4609 BlessTupleDesc(rec->tupdesc);
4610 typeid = rec->tupdesc->tdtypeid;
4614 case PLPGSQL_DTYPE_RECFIELD:
4616 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4620 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4621 if (rec->tupdesc == NULL)
4623 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4624 errmsg("record \"%s\" is not assigned yet",
4626 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4627 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4628 if (fno == SPI_ERROR_NOATTRIBUTE)
4630 (errcode(ERRCODE_UNDEFINED_COLUMN),
4631 errmsg("record \"%s\" has no field \"%s\"",
4632 rec->refname, recfield->fieldname)));
4633 typeid = SPI_gettypeid(rec->tupdesc, fno);
4638 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4639 typeid = InvalidOid; /* keep compiler quiet */
4647 * exec_get_datum_type_info Get datatype etc of a PLpgSQL_datum
4649 * An extended version of exec_get_datum_type, which also retrieves the
4650 * typmod and collation of the datum.
4653 exec_get_datum_type_info(PLpgSQL_execstate *estate,
4654 PLpgSQL_datum *datum,
4655 Oid *typeid, int32 *typmod, Oid *collation)
4657 switch (datum->dtype)
4659 case PLPGSQL_DTYPE_VAR:
4661 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4663 *typeid = var->datatype->typoid;
4664 *typmod = var->datatype->atttypmod;
4665 *collation = var->datatype->collation;
4669 case PLPGSQL_DTYPE_ROW:
4671 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4673 if (!row->rowtupdesc) /* should not happen */
4674 elog(ERROR, "row variable has no tupdesc");
4675 /* Make sure we have a valid type/typmod setting */
4676 BlessTupleDesc(row->rowtupdesc);
4677 *typeid = row->rowtupdesc->tdtypeid;
4678 /* do NOT return the mutable typmod of a RECORD variable */
4680 /* composite types are never collatable */
4681 *collation = InvalidOid;
4685 case PLPGSQL_DTYPE_REC:
4687 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4689 if (rec->tupdesc == NULL)
4691 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4692 errmsg("record \"%s\" is not assigned yet",
4694 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4695 /* Make sure we have a valid type/typmod setting */
4696 BlessTupleDesc(rec->tupdesc);
4697 *typeid = rec->tupdesc->tdtypeid;
4698 /* do NOT return the mutable typmod of a RECORD variable */
4700 /* composite types are never collatable */
4701 *collation = InvalidOid;
4705 case PLPGSQL_DTYPE_RECFIELD:
4707 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4711 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4712 if (rec->tupdesc == NULL)
4714 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4715 errmsg("record \"%s\" is not assigned yet",
4717 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4718 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4719 if (fno == SPI_ERROR_NOATTRIBUTE)
4721 (errcode(ERRCODE_UNDEFINED_COLUMN),
4722 errmsg("record \"%s\" has no field \"%s\"",
4723 rec->refname, recfield->fieldname)));
4724 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4726 *typmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4730 *collation = rec->tupdesc->attrs[fno - 1]->attcollation;
4731 else /* no system column types have collation */
4732 *collation = InvalidOid;
4737 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4738 *typeid = InvalidOid; /* keep compiler quiet */
4740 *collation = InvalidOid;
4746 * exec_eval_integer Evaluate an expression, coerce result to int4
4748 * Note we do not do exec_eval_cleanup here; the caller must do it at
4749 * some later point. (We do this because the caller may be holding the
4750 * results of other, pass-by-reference, expression evaluations, such as
4751 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
4752 * about allocation of the parameter array.)
4756 exec_eval_integer(PLpgSQL_execstate *estate,
4764 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
4765 exprdatum = exec_cast_value(estate, exprdatum, isNull,
4766 exprtypeid, exprtypmod,
4768 return DatumGetInt32(exprdatum);
4772 * exec_eval_boolean Evaluate an expression, coerce result to bool
4774 * Note we do not do exec_eval_cleanup here; the caller must do it at
4779 exec_eval_boolean(PLpgSQL_execstate *estate,
4787 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
4788 exprdatum = exec_cast_value(estate, exprdatum, isNull,
4789 exprtypeid, exprtypmod,
4791 return DatumGetBool(exprdatum);
4795 * exec_eval_expr Evaluate an expression and return
4796 * the result Datum, along with data type/typmod.
4798 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4802 exec_eval_expr(PLpgSQL_execstate *estate,
4812 * If first time through, create a plan for this expression.
4814 if (expr->plan == NULL)
4815 exec_prepare_plan(estate, expr, 0);
4818 * If this is a simple expression, bypass SPI and use the executor
4821 if (exec_eval_simple_expr(estate, expr,
4822 &result, isNull, rettype, rettypmod))
4826 * Else do it the hard way via exec_run_select
4828 rc = exec_run_select(estate, expr, 2, NULL);
4829 if (rc != SPI_OK_SELECT)
4831 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4832 errmsg("query \"%s\" did not return data", expr->query)));
4835 * Check that the expression returns exactly one column...
4837 if (estate->eval_tuptable->tupdesc->natts != 1)
4839 (errcode(ERRCODE_SYNTAX_ERROR),
4840 errmsg_plural("query \"%s\" returned %d column",
4841 "query \"%s\" returned %d columns",
4842 estate->eval_tuptable->tupdesc->natts,
4844 estate->eval_tuptable->tupdesc->natts)));
4847 * ... and get the column's datatype.
4849 *rettype = estate->eval_tuptable->tupdesc->attrs[0]->atttypid;
4850 *rettypmod = estate->eval_tuptable->tupdesc->attrs[0]->atttypmod;
4853 * If there are no rows selected, the result is a NULL of that type.
4855 if (estate->eval_processed == 0)
4862 * Check that the expression returned no more than one row.
4864 if (estate->eval_processed != 1)
4866 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4867 errmsg("query \"%s\" returned more than one row",
4871 * Return the single result Datum.
4873 return SPI_getbinval(estate->eval_tuptable->vals[0],
4874 estate->eval_tuptable->tupdesc, 1, isNull);
4879 * exec_run_select Execute a select query
4883 exec_run_select(PLpgSQL_execstate *estate,
4884 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4886 ParamListInfo paramLI;
4890 * On the first call for this expression generate the plan
4892 if (expr->plan == NULL)
4893 exec_prepare_plan(estate, expr, 0);
4896 * Set up ParamListInfo (hook function and possibly data values)
4898 paramLI = setup_param_list(estate, expr);
4901 * If a portal was requested, put the query into the portal
4903 if (portalP != NULL)
4905 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4907 estate->readonly_func);
4908 if (*portalP == NULL)
4909 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4910 expr->query, SPI_result_code_string(SPI_result));
4913 return SPI_OK_CURSOR;
4919 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4920 estate->readonly_func, maxtuples);
4921 if (rc != SPI_OK_SELECT)
4923 (errcode(ERRCODE_SYNTAX_ERROR),
4924 errmsg("query \"%s\" is not a SELECT", expr->query)));
4926 /* Save query results for eventual cleanup */
4927 Assert(estate->eval_tuptable == NULL);
4928 estate->eval_tuptable = SPI_tuptable;
4929 estate->eval_processed = SPI_processed;
4930 estate->eval_lastoid = SPI_lastoid;
4940 * exec_for_query --- execute body of FOR loop for each row from a portal
4942 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4945 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4946 Portal portal, bool prefetch_ok)
4948 PLpgSQL_rec *rec = NULL;
4949 PLpgSQL_row *row = NULL;
4950 SPITupleTable *tuptab;
4952 int rc = PLPGSQL_RC_OK;
4956 * Determine if we assign to a record or a row
4958 if (stmt->rec != NULL)
4959 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4960 else if (stmt->row != NULL)
4961 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4963 elog(ERROR, "unsupported target");
4966 * Make sure the portal doesn't get closed by the user statements we
4972 * Fetch the initial tuple(s). If prefetching is allowed then we grab a
4973 * few more rows to avoid multiple trips through executor startup
4976 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4977 tuptab = SPI_tuptable;
4981 * If the query didn't return any rows, set the target to NULL and fall
4982 * through with found = false.
4986 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4987 exec_eval_cleanup(estate);
4990 found = true; /* processed at least one tuple */
4999 for (i = 0; i < n; i++)
5002 * Assign the tuple to the target
5004 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
5005 exec_eval_cleanup(estate);
5008 * Execute the statements
5010 rc = exec_stmts(estate, stmt->body);
5012 if (rc != PLPGSQL_RC_OK)
5014 if (rc == PLPGSQL_RC_EXIT)
5016 if (estate->exitlabel == NULL)
5018 /* unlabelled exit, so exit the current loop */
5021 else if (stmt->label != NULL &&
5022 strcmp(stmt->label, estate->exitlabel) == 0)
5024 /* label matches this loop, so exit loop */
5025 estate->exitlabel = NULL;
5030 * otherwise, we processed a labelled exit that does not
5031 * match the current statement's label, if any; return
5032 * RC_EXIT so that the EXIT continues to recurse upward.
5035 else if (rc == PLPGSQL_RC_CONTINUE)
5037 if (estate->exitlabel == NULL)
5039 /* unlabelled continue, so re-run the current loop */
5043 else if (stmt->label != NULL &&
5044 strcmp(stmt->label, estate->exitlabel) == 0)
5046 /* label matches this loop, so re-run loop */
5047 estate->exitlabel = NULL;
5053 * otherwise, we process a labelled continue that does not
5054 * match the current statement's label, if any; return
5055 * RC_CONTINUE so that the CONTINUE will propagate up the
5061 * We're aborting the loop. Need a goto to get out of two
5068 SPI_freetuptable(tuptab);
5071 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
5073 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
5074 tuptab = SPI_tuptable;
5081 * Release last group of tuples (if any)
5083 SPI_freetuptable(tuptab);
5085 UnpinPortal(portal);
5088 * Set the FOUND variable to indicate the result of executing the loop
5089 * (namely, whether we looped one or more times). This must be set last so
5090 * that it does not interfere with the value of the FOUND variable inside
5091 * the loop processing itself.
5093 exec_set_found(estate, found);
5100 * exec_eval_simple_expr - Evaluate a simple expression returning
5101 * a Datum by directly calling ExecEvalExpr().
5103 * If successful, store results into *result, *isNull, *rettype, *rettypmod
5104 * and return TRUE. If the expression cannot be handled by simple evaluation,
5107 * Because we only store one execution tree for a simple expression, we
5108 * can't handle recursion cases. So, if we see the tree is already busy
5109 * with an evaluation in the current xact, we just return FALSE and let the
5110 * caller run the expression the hard way. (Other alternatives such as
5111 * creating a new tree for a recursive call either introduce memory leaks,
5112 * or add enough bookkeeping to be doubtful wins anyway.) Another case that
5113 * is covered by the expr_simple_in_use test is where a previous execution
5114 * of the tree was aborted by an error: the tree may contain bogus state
5115 * so we dare not re-use it.
5117 * It is possible though unlikely for a simple expression to become non-simple
5118 * (consider for example redefining a trivial view). We must handle that for
5119 * correctness; fortunately it's normally inexpensive to call
5120 * SPI_plan_get_cached_plan for a simple expression. We do not consider the
5121 * other direction (non-simple expression becoming simple) because we'll still
5122 * give correct results if that happens, and it's unlikely to be worth the
5125 * Note: if pass-by-reference, the result is in the eval_econtext's
5126 * temporary memory context. It will be freed when exec_eval_cleanup
5131 exec_eval_simple_expr(PLpgSQL_execstate *estate,
5138 ExprContext *econtext = estate->eval_econtext;
5139 LocalTransactionId curlxid = MyProc->lxid;
5141 ParamListInfo paramLI;
5142 PLpgSQL_expr *save_cur_expr;
5143 MemoryContext oldcontext;
5146 * Forget it if expression wasn't simple before.
5148 if (expr->expr_simple_expr == NULL)
5152 * If expression is in use in current xact, don't touch it.
5154 if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
5158 * Revalidate cached plan, so that we will notice if it became stale. (We
5159 * need to hold a refcount while using the plan, anyway.)
5161 cplan = SPI_plan_get_cached_plan(expr->plan);
5164 * We can't get a failure here, because the number of CachedPlanSources in
5165 * the SPI plan can't change from what exec_simple_check_plan saw; it's a
5166 * property of the raw parsetree generated from the query text.
5168 Assert(cplan != NULL);
5170 if (cplan->generation != expr->expr_simple_generation)
5172 /* It got replanned ... is it still simple? */
5173 exec_simple_recheck_plan(expr, cplan);
5174 if (expr->expr_simple_expr == NULL)
5176 /* Ooops, release refcount and fail */
5177 ReleaseCachedPlan(cplan, true);
5183 * Pass back previously-determined result type.
5185 *rettype = expr->expr_simple_type;
5186 *rettypmod = expr->expr_simple_typmod;
5189 * Prepare the expression for execution, if it's not been done already in
5190 * the current transaction. (This will be forced to happen if we called
5191 * exec_simple_recheck_plan above.)
5193 if (expr->expr_simple_lxid != curlxid)
5195 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
5196 expr->expr_simple_state = ExecInitExpr(expr->expr_simple_expr, NULL);
5197 expr->expr_simple_in_use = false;
5198 expr->expr_simple_lxid = curlxid;
5199 MemoryContextSwitchTo(oldcontext);
5203 * We have to do some of the things SPI_execute_plan would do, in
5204 * particular advance the snapshot if we are in a non-read-only function.
5205 * Without this, stable functions within the expression would fail to see
5206 * updates made so far by our own function.
5210 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
5211 if (!estate->readonly_func)
5213 CommandCounterIncrement();
5214 PushActiveSnapshot(GetTransactionSnapshot());
5218 * Create the param list in econtext's temporary memory context. We won't
5219 * need to free it explicitly, since it will go away at the next reset of
5222 * Just for paranoia's sake, save and restore the prior value of
5223 * estate->cur_expr, which setup_param_list() sets.
5225 save_cur_expr = estate->cur_expr;
5227 paramLI = setup_param_list(estate, expr);
5228 econtext->ecxt_param_list_info = paramLI;
5231 * Mark expression as busy for the duration of the ExecEvalExpr call.
5233 expr->expr_simple_in_use = true;
5236 * Finally we can call the executor to evaluate the expression
5238 *result = ExecEvalExpr(expr->expr_simple_state,
5243 /* Assorted cleanup */
5244 expr->expr_simple_in_use = false;
5246 estate->cur_expr = save_cur_expr;
5248 if (!estate->readonly_func)
5249 PopActiveSnapshot();
5251 MemoryContextSwitchTo(oldcontext);
5256 * Now we can release our refcount on the cached plan.
5258 ReleaseCachedPlan(cplan, true);
5268 * Create a ParamListInfo to pass to SPI
5270 * We fill in the values for any expression parameters that are plain
5271 * PLpgSQL_var datums; these are cheap and safe to evaluate, and by setting
5272 * them with PARAM_FLAG_CONST flags, we allow the planner to use those values
5273 * in custom plans. However, parameters that are not plain PLpgSQL_vars
5274 * should not be evaluated here, because they could throw errors (for example
5275 * "no such record field") and we do not want that to happen in a part of
5276 * the expression that might never be evaluated at runtime. To handle those
5277 * parameters, we set up a paramFetch hook for the executor to call when it
5278 * wants a not-presupplied value.
5280 * The result is a locally palloc'd array that should be pfree'd after use;
5281 * but note it can be NULL.
5283 static ParamListInfo
5284 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
5286 ParamListInfo paramLI;
5289 * We must have created the SPIPlan already (hence, query text has been
5290 * parsed/analyzed at least once); else we cannot rely on expr->paramnos.
5292 Assert(expr->plan != NULL);
5295 * Could we re-use these arrays instead of palloc'ing a new one each time?
5296 * However, we'd have to re-fill the array each time anyway, since new
5297 * values might have been assigned to the variables.
5299 if (!bms_is_empty(expr->paramnos))
5303 paramLI = (ParamListInfo)
5304 palloc0(offsetof(ParamListInfoData, params) +
5305 estate->ndatums * sizeof(ParamExternData));
5306 paramLI->paramFetch = plpgsql_param_fetch;
5307 paramLI->paramFetchArg = (void *) estate;
5308 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
5309 paramLI->parserSetupArg = (void *) expr;
5310 paramLI->numParams = estate->ndatums;
5312 /* Instantiate values for "safe" parameters of the expression */
5314 while ((dno = bms_next_member(expr->paramnos, dno)) >= 0)
5316 PLpgSQL_datum *datum = estate->datums[dno];
5318 if (datum->dtype == PLPGSQL_DTYPE_VAR)
5320 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5321 ParamExternData *prm = ¶mLI->params[dno];
5323 prm->value = var->value;
5324 prm->isnull = var->isnull;
5325 prm->pflags = PARAM_FLAG_CONST;
5326 prm->ptype = var->datatype->typoid;
5331 * Set up link to active expr where the hook functions can find it.
5332 * Callers must save and restore cur_expr if there is any chance that
5333 * they are interrupting an active use of parameters.
5335 estate->cur_expr = expr;
5338 * Also make sure this is set before parser hooks need it. There is
5339 * no need to save and restore, since the value is always correct once
5340 * set. (Should be set already, but let's be sure.)
5342 expr->func = estate->func;
5347 * Expression requires no parameters. Be sure we represent this case
5348 * as a NULL ParamListInfo, so that plancache.c knows there is no
5349 * point in a custom plan.
5357 * plpgsql_param_fetch paramFetch callback for dynamic parameter fetch
5360 plpgsql_param_fetch(ParamListInfo params, int paramid)
5363 PLpgSQL_execstate *estate;
5365 PLpgSQL_datum *datum;
5366 ParamExternData *prm;
5369 /* paramid's are 1-based, but dnos are 0-based */
5371 Assert(dno >= 0 && dno < params->numParams);
5373 /* fetch back the hook data */
5374 estate = (PLpgSQL_execstate *) params->paramFetchArg;
5375 expr = estate->cur_expr;
5376 Assert(params->numParams == estate->ndatums);
5379 * Do nothing if asked for a value that's not supposed to be used by this
5380 * SQL expression. This avoids unwanted evaluations when functions such
5381 * as copyParamList try to materialize all the values.
5383 if (!bms_is_member(dno, expr->paramnos))
5386 /* OK, evaluate the value and store into the appropriate paramlist slot */
5387 datum = estate->datums[dno];
5388 prm = ¶ms->params[dno];
5389 exec_eval_datum(estate, datum,
5390 &prm->ptype, &prmtypmod,
5391 &prm->value, &prm->isnull);
5396 * exec_move_row Move one tuple's values into a record or row
5398 * Since this uses exec_assign_value, caller should eventually call
5399 * exec_eval_cleanup to prevent long-term memory leaks.
5403 exec_move_row(PLpgSQL_execstate *estate,
5406 HeapTuple tup, TupleDesc tupdesc)
5409 * Record is simple - just copy the tuple and its descriptor into the
5415 * Copy input first, just in case it is pointing at variable's value
5417 if (HeapTupleIsValid(tup))
5418 tup = heap_copytuple(tup);
5421 /* If we have a tupdesc but no data, form an all-nulls tuple */
5424 nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
5425 memset(nulls, true, tupdesc->natts * sizeof(bool));
5427 tup = heap_form_tuple(tupdesc, NULL, nulls);
5433 tupdesc = CreateTupleDescCopy(tupdesc);
5435 /* Free the old value ... */
5438 heap_freetuple(rec->tup);
5439 rec->freetup = false;
5441 if (rec->freetupdesc)
5443 FreeTupleDesc(rec->tupdesc);
5444 rec->freetupdesc = false;
5447 /* ... and install the new */
5448 if (HeapTupleIsValid(tup))
5451 rec->freetup = true;
5458 rec->tupdesc = tupdesc;
5459 rec->freetupdesc = true;
5462 rec->tupdesc = NULL;
5468 * Row is a bit more complicated in that we assign the individual
5469 * attributes of the tuple to the variables the row points to.
5471 * NOTE: this code used to demand row->nfields ==
5472 * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong. The tuple
5473 * might have more fields than we expected if it's from an
5474 * inheritance-child table of the current table, or it might have fewer if
5475 * the table has had columns added by ALTER TABLE. Ignore extra columns
5476 * and assume NULL for missing columns, the same as heap_getattr would do.
5477 * We also have to skip over dropped columns in either the source or
5480 * If we have no tuple data at all, we'll assign NULL to all columns of
5485 int td_natts = tupdesc ? tupdesc->natts : 0;
5490 if (HeapTupleIsValid(tup))
5491 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
5496 for (fnum = 0; fnum < row->nfields; fnum++)
5504 if (row->varnos[fnum] < 0)
5505 continue; /* skip dropped column in row struct */
5507 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
5509 while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
5510 anum++; /* skip dropped column in tuple */
5512 if (anum < td_natts)
5515 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
5521 valtype = tupdesc->attrs[anum]->atttypid;
5522 valtypmod = tupdesc->attrs[anum]->atttypmod;
5529 valtype = UNKNOWNOID;
5533 exec_assign_value(estate, (PLpgSQL_datum *) var,
5534 value, isnull, valtype, valtypmod);
5540 elog(ERROR, "unsupported target");
5544 * make_tuple_from_row Make a tuple from the values of a row object
5546 * A NULL return indicates rowtype mismatch; caller must raise suitable error
5550 make_tuple_from_row(PLpgSQL_execstate *estate,
5554 int natts = tupdesc->natts;
5560 if (natts != row->nfields)
5563 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
5564 nulls = (bool *) palloc(natts * sizeof(bool));
5566 for (i = 0; i < natts; i++)
5571 if (tupdesc->attrs[i]->attisdropped)
5573 nulls[i] = true; /* leave the column as null */
5576 if (row->varnos[i] < 0) /* should not happen */
5577 elog(ERROR, "dropped rowtype entry for non-dropped column");
5579 exec_eval_datum(estate, estate->datums[row->varnos[i]],
5580 &fieldtypeid, &fieldtypmod,
5581 &dvalues[i], &nulls[i]);
5582 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
5584 /* XXX should we insist on typmod match, too? */
5587 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
5596 * get_tuple_from_datum extract a tuple from a composite Datum
5598 * Returns a freshly palloc'd HeapTuple.
5600 * Note: it's caller's responsibility to be sure value is of composite type.
5604 get_tuple_from_datum(Datum value)
5606 HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5607 HeapTupleData tmptup;
5609 /* Build a temporary HeapTuple control structure */
5610 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5611 ItemPointerSetInvalid(&(tmptup.t_self));
5612 tmptup.t_tableOid = InvalidOid;
5615 /* Build a copy and return it */
5616 return heap_copytuple(&tmptup);
5620 * get_tupdesc_from_datum get a tuple descriptor for a composite Datum
5622 * Returns a pointer to the TupleDesc of the tuple's rowtype.
5623 * Caller is responsible for calling ReleaseTupleDesc when done with it.
5625 * Note: it's caller's responsibility to be sure value is of composite type.
5629 get_tupdesc_from_datum(Datum value)
5631 HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5635 /* Extract rowtype info and find a tupdesc */
5636 tupType = HeapTupleHeaderGetTypeId(td);
5637 tupTypmod = HeapTupleHeaderGetTypMod(td);
5638 return lookup_rowtype_tupdesc(tupType, tupTypmod);
5642 * exec_move_row_from_datum Move a composite Datum into a record or row
5644 * This is equivalent to get_tuple_from_datum() followed by exec_move_row(),
5645 * but we avoid constructing an intermediate physical copy of the tuple.
5649 exec_move_row_from_datum(PLpgSQL_execstate *estate,
5654 HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5658 HeapTupleData tmptup;
5660 /* Extract rowtype info and find a tupdesc */
5661 tupType = HeapTupleHeaderGetTypeId(td);
5662 tupTypmod = HeapTupleHeaderGetTypMod(td);
5663 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
5665 /* Build a temporary HeapTuple control structure */
5666 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5667 ItemPointerSetInvalid(&(tmptup.t_self));
5668 tmptup.t_tableOid = InvalidOid;
5672 exec_move_row(estate, rec, row, &tmptup, tupdesc);
5674 /* Release tupdesc usage count */
5675 ReleaseTupleDesc(tupdesc);
5679 * convert_value_to_string Convert a non-null Datum to C string
5681 * Note: the result is in the estate's eval_econtext, and will be cleared
5682 * by the next exec_eval_cleanup() call. The invoked output function might
5683 * leave additional cruft there as well, so just pfree'ing the result string
5684 * would not be enough to avoid memory leaks if we did not do it like this.
5685 * In most usages the Datum being passed in is also in that context (if
5686 * pass-by-reference) and so an exec_eval_cleanup() call is needed anyway.
5688 * Note: not caching the conversion function lookup is bad for performance.
5689 * However, this function isn't currently used in any places where an extra
5690 * catalog lookup or two seems like a big deal.
5694 convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
5697 MemoryContext oldcontext;
5701 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
5702 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
5703 result = OidOutputFunctionCall(typoutput, value);
5704 MemoryContextSwitchTo(oldcontext);
5710 * exec_cast_value Cast a value if required
5712 * Note that *isnull is an input and also an output parameter. While it's
5713 * unlikely that a cast operation would produce null from non-null or vice
5714 * versa, that could happen in principle.
5716 * Note: the estate's eval_econtext is used for temporary storage, and may
5717 * also contain the result Datum if we have to do a conversion to a pass-
5718 * by-reference data type. Be sure to do an exec_eval_cleanup() call when
5719 * done with the result.
5723 exec_cast_value(PLpgSQL_execstate *estate,
5724 Datum value, bool *isnull,
5725 Oid valtype, int32 valtypmod,
5726 Oid reqtype, int32 reqtypmod)
5729 * If the type of the given value isn't what's requested, convert it.
5731 if (valtype != reqtype ||
5732 (valtypmod != reqtypmod && reqtypmod != -1))
5734 ExprState *cast_expr;
5736 cast_expr = get_cast_expression(estate, valtype, reqtype, reqtypmod);
5739 ExprContext *econtext = estate->eval_econtext;
5740 MemoryContext oldcontext;
5742 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
5744 econtext->caseValue_datum = value;
5745 econtext->caseValue_isNull = *isnull;
5747 value = ExecEvalExpr(cast_expr, econtext, isnull, NULL);
5749 MemoryContextSwitchTo(oldcontext);
5757 * get_cast_expression Look up how to perform a type cast
5759 * Returns an expression evaluation tree based on a CaseTestExpr input,
5760 * or NULL if the cast is a mere no-op relabeling.
5762 * We cache the results of the lookup in a per-function hash table.
5763 * It's tempting to consider using a session-wide hash table instead,
5764 * but that introduces some corner-case questions that probably aren't
5765 * worth dealing with; in particular that re-entrant use of an evaluation
5766 * tree might occur. That would also set in stone the assumption that
5767 * collation isn't important to a cast function.
5771 get_cast_expression(PLpgSQL_execstate *estate,
5772 Oid srctype, Oid dsttype, int32 dsttypmod)
5774 HTAB *cast_hash = estate->func->cast_hash;
5775 plpgsql_CastHashKey cast_key;
5776 plpgsql_CastHashEntry *cast_entry;
5778 CaseTestExpr *placeholder;
5780 ExprState *cast_exprstate;
5781 MemoryContext oldcontext;
5783 /* Create the cast-info hash table if we didn't already */
5784 if (cast_hash == NULL)
5788 memset(&ctl, 0, sizeof(ctl));
5789 ctl.keysize = sizeof(plpgsql_CastHashKey);
5790 ctl.entrysize = sizeof(plpgsql_CastHashEntry);
5791 ctl.hcxt = estate->func->fn_cxt;
5792 cast_hash = hash_create("PLpgSQL cast cache",
5793 16, /* start small and extend */
5795 HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
5796 estate->func->cast_hash = cast_hash;
5799 /* Look for existing entry */
5800 cast_key.srctype = srctype;
5801 cast_key.dsttype = dsttype;
5802 cast_key.dsttypmod = dsttypmod;
5803 cast_entry = (plpgsql_CastHashEntry *) hash_search(cast_hash,
5807 return cast_entry->cast_exprstate;
5809 /* Construct expression tree for coercion in function's context */
5810 oldcontext = MemoryContextSwitchTo(estate->func->fn_cxt);
5813 * We use a CaseTestExpr as the base of the coercion tree, since it's very
5814 * cheap to insert the source value for that.
5816 placeholder = makeNode(CaseTestExpr);
5817 placeholder->typeId = srctype;
5818 placeholder->typeMod = -1;
5819 placeholder->collation = get_typcollation(srctype);
5820 if (OidIsValid(estate->func->fn_input_collation) &&
5821 OidIsValid(placeholder->collation))
5822 placeholder->collation = estate->func->fn_input_collation;
5825 * Apply coercion. We use ASSIGNMENT coercion because that's the closest
5826 * match to plpgsql's historical behavior; in particular, EXPLICIT
5827 * coercion would allow silent truncation to a destination
5828 * varchar/bpchar's length, which we do not want.
5830 * If source type is UNKNOWN, coerce_to_target_type will fail (it only
5831 * expects to see that for Const input nodes), so don't call it; we'll
5832 * apply CoerceViaIO instead.
5834 if (srctype != UNKNOWNOID)
5835 cast_expr = coerce_to_target_type(NULL,
5836 (Node *) placeholder, srctype,
5838 COERCION_ASSIGNMENT,
5839 COERCE_IMPLICIT_CAST,
5845 * If there's no cast path according to the parser, fall back to using an
5846 * I/O coercion; this is semantically dubious but matches plpgsql's
5847 * historical behavior. We would need something of the sort for UNKNOWN
5848 * literals in any case.
5850 if (cast_expr == NULL)
5852 CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
5854 iocoerce->arg = (Expr *) placeholder;
5855 iocoerce->resulttype = dsttype;
5856 iocoerce->resultcollid = InvalidOid;
5857 iocoerce->coerceformat = COERCE_IMPLICIT_CAST;
5858 iocoerce->location = -1;
5859 cast_expr = (Node *) iocoerce;
5860 if (dsttypmod != -1)
5861 cast_expr = coerce_to_target_type(NULL,
5864 COERCION_ASSIGNMENT,
5865 COERCE_IMPLICIT_CAST,
5869 /* Note: we don't bother labeling the expression tree with collation */
5871 /* Detect whether we have a no-op (RelabelType) coercion */
5872 if (IsA(cast_expr, RelabelType) &&
5873 ((RelabelType *) cast_expr)->arg == (Expr *) placeholder)
5878 /* ExecInitExpr assumes we've planned the expression */
5879 cast_expr = (Node *) expression_planner((Expr *) cast_expr);
5880 /* Create an expression eval state tree for it */
5881 cast_exprstate = ExecInitExpr((Expr *) cast_expr, NULL);
5884 cast_exprstate = NULL;
5886 MemoryContextSwitchTo(oldcontext);
5889 * Now fill in a hashtable entry. If we fail anywhere up to/including
5890 * this step, we've only leaked some memory in the function context, which
5891 * isn't great but isn't disastrous either.
5893 cast_entry = (plpgsql_CastHashEntry *) hash_search(cast_hash,
5895 HASH_ENTER, &found);
5896 Assert(!found); /* wasn't there a moment ago */
5898 cast_entry->cast_exprstate = cast_exprstate;
5900 return cast_exprstate;
5904 * exec_simple_check_node - Recursively check if an expression
5905 * is made only of simple things we can
5906 * hand out directly to ExecEvalExpr()
5907 * instead of calling SPI.
5911 exec_simple_check_node(Node *node)
5916 switch (nodeTag(node))
5926 ArrayRef *expr = (ArrayRef *) node;
5928 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
5930 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
5932 if (!exec_simple_check_node((Node *) expr->refexpr))
5934 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
5942 FuncExpr *expr = (FuncExpr *) node;
5944 if (expr->funcretset)
5946 if (!exec_simple_check_node((Node *) expr->args))
5954 OpExpr *expr = (OpExpr *) node;
5958 if (!exec_simple_check_node((Node *) expr->args))
5964 case T_DistinctExpr:
5966 DistinctExpr *expr = (DistinctExpr *) node;
5970 if (!exec_simple_check_node((Node *) expr->args))
5978 NullIfExpr *expr = (NullIfExpr *) node;
5982 if (!exec_simple_check_node((Node *) expr->args))
5988 case T_ScalarArrayOpExpr:
5990 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5992 if (!exec_simple_check_node((Node *) expr->args))
6000 BoolExpr *expr = (BoolExpr *) node;
6002 if (!exec_simple_check_node((Node *) expr->args))
6009 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
6013 FieldStore *expr = (FieldStore *) node;
6015 if (!exec_simple_check_node((Node *) expr->arg))
6017 if (!exec_simple_check_node((Node *) expr->newvals))
6024 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
6027 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
6029 case T_ArrayCoerceExpr:
6030 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
6032 case T_ConvertRowtypeExpr:
6033 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
6037 CaseExpr *expr = (CaseExpr *) node;
6039 if (!exec_simple_check_node((Node *) expr->arg))
6041 if (!exec_simple_check_node((Node *) expr->args))
6043 if (!exec_simple_check_node((Node *) expr->defresult))
6051 CaseWhen *when = (CaseWhen *) node;
6053 if (!exec_simple_check_node((Node *) when->expr))
6055 if (!exec_simple_check_node((Node *) when->result))
6061 case T_CaseTestExpr:
6066 ArrayExpr *expr = (ArrayExpr *) node;
6068 if (!exec_simple_check_node((Node *) expr->elements))
6076 RowExpr *expr = (RowExpr *) node;
6078 if (!exec_simple_check_node((Node *) expr->args))
6084 case T_RowCompareExpr:
6086 RowCompareExpr *expr = (RowCompareExpr *) node;
6088 if (!exec_simple_check_node((Node *) expr->largs))
6090 if (!exec_simple_check_node((Node *) expr->rargs))
6096 case T_CoalesceExpr:
6098 CoalesceExpr *expr = (CoalesceExpr *) node;
6100 if (!exec_simple_check_node((Node *) expr->args))
6108 MinMaxExpr *expr = (MinMaxExpr *) node;
6110 if (!exec_simple_check_node((Node *) expr->args))
6118 XmlExpr *expr = (XmlExpr *) node;
6120 if (!exec_simple_check_node((Node *) expr->named_args))
6122 if (!exec_simple_check_node((Node *) expr->args))
6129 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
6132 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
6134 case T_CoerceToDomain:
6135 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
6137 case T_CoerceToDomainValue:
6142 List *expr = (List *) node;
6147 if (!exec_simple_check_node(lfirst(l)))
6161 * exec_simple_check_plan - Check if a plan is simple enough to
6162 * be evaluated by ExecEvalExpr() instead
6167 exec_simple_check_plan(PLpgSQL_expr *expr)
6170 CachedPlanSource *plansource;
6175 * Initialize to "not simple", and remember the plan generation number we
6176 * last checked. (If we don't get as far as obtaining a plan to check, we
6177 * just leave expr_simple_generation set to 0.)
6179 expr->expr_simple_expr = NULL;
6180 expr->expr_simple_generation = 0;
6183 * We can only test queries that resulted in exactly one CachedPlanSource
6185 plansources = SPI_plan_get_plan_sources(expr->plan);
6186 if (list_length(plansources) != 1)
6188 plansource = (CachedPlanSource *) linitial(plansources);
6191 * Do some checking on the analyzed-and-rewritten form of the query. These
6192 * checks are basically redundant with the tests in
6193 * exec_simple_recheck_plan, but the point is to avoid building a plan if
6194 * possible. Since this function is only called immediately after
6195 * creating the CachedPlanSource, we need not worry about the query being
6200 * 1. There must be one single querytree.
6202 if (list_length(plansource->query_list) != 1)
6204 query = (Query *) linitial(plansource->query_list);
6207 * 2. It must be a plain SELECT query without any input tables
6209 if (!IsA(query, Query))
6211 if (query->commandType != CMD_SELECT)
6213 if (query->rtable != NIL)
6217 * 3. Can't have any subplans, aggregates, qual clauses either
6219 if (query->hasAggs ||
6220 query->hasWindowFuncs ||
6221 query->hasSubLinks ||
6222 query->hasForUpdate ||
6224 query->jointree->quals ||
6225 query->groupClause ||
6226 query->havingQual ||
6227 query->windowClause ||
6228 query->distinctClause ||
6229 query->sortClause ||
6230 query->limitOffset ||
6231 query->limitCount ||
6232 query->setOperations)
6236 * 4. The query must have a single attribute as result
6238 if (list_length(query->targetList) != 1)
6242 * OK, it seems worth constructing a plan for more careful checking.
6245 /* Get the generic plan for the query */
6246 cplan = SPI_plan_get_cached_plan(expr->plan);
6248 /* Can't fail, because we checked for a single CachedPlanSource above */
6249 Assert(cplan != NULL);
6251 /* Share the remaining work with recheck code path */
6252 exec_simple_recheck_plan(expr, cplan);
6254 /* Release our plan refcount */
6255 ReleaseCachedPlan(cplan, true);
6259 * exec_simple_recheck_plan --- check for simple plan once we have CachedPlan
6262 exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan)
6269 * Initialize to "not simple", and remember the plan generation number we
6272 expr->expr_simple_expr = NULL;
6273 expr->expr_simple_generation = cplan->generation;
6276 * 1. There must be one single plantree
6278 if (list_length(cplan->stmt_list) != 1)
6280 stmt = (PlannedStmt *) linitial(cplan->stmt_list);
6283 * 2. It must be a RESULT plan --> no scan's required
6285 if (!IsA(stmt, PlannedStmt))
6287 if (stmt->commandType != CMD_SELECT)
6289 plan = stmt->planTree;
6290 if (!IsA(plan, Result))
6294 * 3. Can't have any subplan or qual clause, either
6296 if (plan->lefttree != NULL ||
6297 plan->righttree != NULL ||
6298 plan->initPlan != NULL ||
6299 plan->qual != NULL ||
6300 ((Result *) plan)->resconstantqual != NULL)
6304 * 4. The plan must have a single attribute as result
6306 if (list_length(plan->targetlist) != 1)
6309 tle = (TargetEntry *) linitial(plan->targetlist);
6312 * 5. Check that all the nodes in the expression are non-scary.
6314 if (!exec_simple_check_node((Node *) tle->expr))
6318 * Yes - this is a simple expression. Mark it as such, and initialize
6319 * state to "not valid in current transaction".
6321 expr->expr_simple_expr = tle->expr;
6322 expr->expr_simple_state = NULL;
6323 expr->expr_simple_in_use = false;
6324 expr->expr_simple_lxid = InvalidLocalTransactionId;
6325 /* Also stash away the expression result type */
6326 expr->expr_simple_type = exprType((Node *) tle->expr);
6327 expr->expr_simple_typmod = exprTypmod((Node *) tle->expr);
6331 * exec_set_found Set the global found variable to true/false
6335 exec_set_found(PLpgSQL_execstate *estate, bool state)
6339 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
6340 var->value = BoolGetDatum(state);
6341 var->isnull = false;
6345 * plpgsql_create_econtext --- create an eval_econtext for the current function
6347 * We may need to create a new shared_simple_eval_estate too, if there's not
6348 * one already for the current transaction. The EState will be cleaned up at
6352 plpgsql_create_econtext(PLpgSQL_execstate *estate)
6354 SimpleEcontextStackEntry *entry;
6357 * Create an EState for evaluation of simple expressions, if there's not
6358 * one already in the current transaction. The EState is made a child of
6359 * TopTransactionContext so it will have the right lifespan.
6361 * Note that this path is never taken when executing a DO block; the
6362 * required EState was already made by plpgsql_inline_handler.
6364 if (estate->simple_eval_estate == NULL)
6366 MemoryContext oldcontext;
6368 Assert(shared_simple_eval_estate == NULL);
6369 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
6370 shared_simple_eval_estate = CreateExecutorState();
6371 estate->simple_eval_estate = shared_simple_eval_estate;
6372 MemoryContextSwitchTo(oldcontext);
6376 * Create a child econtext for the current function.
6378 estate->eval_econtext = CreateExprContext(estate->simple_eval_estate);
6381 * Make a stack entry so we can clean up the econtext at subxact end.
6382 * Stack entries are kept in TopTransactionContext for simplicity.
6384 entry = (SimpleEcontextStackEntry *)
6385 MemoryContextAlloc(TopTransactionContext,
6386 sizeof(SimpleEcontextStackEntry));
6388 entry->stack_econtext = estate->eval_econtext;
6389 entry->xact_subxid = GetCurrentSubTransactionId();
6391 entry->next = simple_econtext_stack;
6392 simple_econtext_stack = entry;
6396 * plpgsql_destroy_econtext --- destroy function's econtext
6398 * We check that it matches the top stack entry, and destroy the stack
6399 * entry along with the context.
6402 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
6404 SimpleEcontextStackEntry *next;
6406 Assert(simple_econtext_stack != NULL);
6407 Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
6409 next = simple_econtext_stack->next;
6410 pfree(simple_econtext_stack);
6411 simple_econtext_stack = next;
6413 FreeExprContext(estate->eval_econtext, true);
6414 estate->eval_econtext = NULL;
6418 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
6420 * If a simple-expression EState was created in the current transaction,
6421 * it has to be cleaned up.
6424 plpgsql_xact_cb(XactEvent event, void *arg)
6427 * If we are doing a clean transaction shutdown, free the EState (so that
6428 * any remaining resources will be released correctly). In an abort, we
6429 * expect the regular abort recovery procedures to release everything of
6432 if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_PREPARE)
6434 /* Shouldn't be any econtext stack entries left at commit */
6435 Assert(simple_econtext_stack == NULL);
6437 if (shared_simple_eval_estate)
6438 FreeExecutorState(shared_simple_eval_estate);
6439 shared_simple_eval_estate = NULL;
6441 else if (event == XACT_EVENT_ABORT)
6443 simple_econtext_stack = NULL;
6444 shared_simple_eval_estate = NULL;
6449 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
6451 * Make sure any simple-expression econtexts created in the current
6452 * subtransaction get cleaned up. We have to do this explicitly because
6453 * no other code knows which econtexts belong to which level of subxact.
6456 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
6457 SubTransactionId parentSubid, void *arg)
6459 if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)
6461 while (simple_econtext_stack != NULL &&
6462 simple_econtext_stack->xact_subxid == mySubid)
6464 SimpleEcontextStackEntry *next;
6466 FreeExprContext(simple_econtext_stack->stack_econtext,
6467 (event == SUBXACT_EVENT_COMMIT_SUB));
6468 next = simple_econtext_stack->next;
6469 pfree(simple_econtext_stack);
6470 simple_econtext_stack = next;
6476 * free_var --- pfree any pass-by-reference value of the variable.
6478 * This should always be followed by some assignment to var->value,
6479 * as it leaves a dangling pointer.
6482 free_var(PLpgSQL_var *var)
6486 pfree(DatumGetPointer(var->value));
6487 var->freeval = false;
6492 * free old value of a text variable and assign new value from C string
6495 assign_text_var(PLpgSQL_var *var, const char *str)
6498 var->value = CStringGetTextDatum(str);
6499 var->isnull = false;
6500 var->freeval = true;
6504 * exec_eval_using_params --- evaluate params of USING clause
6506 static PreparedParamsData *
6507 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
6509 PreparedParamsData *ppd;
6514 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
6515 nargs = list_length(params);
6518 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
6519 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
6520 ppd->nulls = (char *) palloc(nargs * sizeof(char));
6521 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
6526 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
6530 ppd->values[i] = exec_eval_expr(estate, param,
6534 ppd->nulls[i] = isnull ? 'n' : ' ';
6535 ppd->freevals[i] = false;
6537 if (ppd->types[i] == UNKNOWNOID)
6540 * Treat 'unknown' parameters as text, since that's what most
6541 * people would expect. SPI_execute_with_args can coerce unknown
6542 * constants in a more intelligent way, but not unknown Params.
6543 * This code also takes care of copying into the right context.
6544 * Note we assume 'unknown' has the representation of C-string.
6546 ppd->types[i] = TEXTOID;
6549 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
6550 ppd->freevals[i] = true;
6553 /* pass-by-ref non null values must be copied into plpgsql context */
6559 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
6562 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
6563 ppd->freevals[i] = true;
6567 exec_eval_cleanup(estate);
6576 * free_params_data --- pfree all pass-by-reference values used in USING clause
6579 free_params_data(PreparedParamsData *ppd)
6583 for (i = 0; i < ppd->nargs; i++)
6585 if (ppd->freevals[i])
6586 pfree(DatumGetPointer(ppd->values[i]));
6592 pfree(ppd->freevals);
6598 * Open portal for dynamic query
6601 exec_dynquery_with_params(PLpgSQL_execstate *estate,
6602 PLpgSQL_expr *dynquery,
6604 const char *portalname,
6615 * Evaluate the string expression after the EXECUTE keyword. Its result is
6616 * the querystring we have to execute.
6618 query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
6621 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6622 errmsg("query string argument of EXECUTE is null")));
6624 /* Get the C-String representation */
6625 querystr = convert_value_to_string(estate, query, restype);
6627 /* copy it out of the temporary context before we clean up */
6628 querystr = pstrdup(querystr);
6630 exec_eval_cleanup(estate);
6633 * Open an implicit cursor for the query. We use
6634 * SPI_cursor_open_with_args even when there are no params, because this
6635 * avoids making and freeing one copy of the plan.
6639 PreparedParamsData *ppd;
6641 ppd = exec_eval_using_params(estate, params);
6642 portal = SPI_cursor_open_with_args(portalname,
6644 ppd->nargs, ppd->types,
6645 ppd->values, ppd->nulls,
6646 estate->readonly_func,
6648 free_params_data(ppd);
6652 portal = SPI_cursor_open_with_args(portalname,
6656 estate->readonly_func,
6661 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
6662 querystr, SPI_result_code_string(SPI_result));
6669 * Return a formatted string with information about an expression's parameters,
6670 * or NULL if the expression does not take any parameters.
6673 format_expr_params(PLpgSQL_execstate *estate,
6674 const PLpgSQL_expr *expr)
6678 StringInfoData paramstr;
6680 if (!expr->paramnos)
6683 initStringInfo(¶mstr);
6686 while ((dno = bms_next_member(expr->paramnos, dno)) >= 0)
6692 PLpgSQL_var *curvar;
6694 curvar = (PLpgSQL_var *) estate->datums[dno];
6696 exec_eval_datum(estate, (PLpgSQL_datum *) curvar, ¶mtypeid,
6697 ¶mtypmod, ¶mdatum, ¶misnull);
6699 appendStringInfo(¶mstr, "%s%s = ",
6700 paramno > 0 ? ", " : "",
6704 appendStringInfoString(¶mstr, "NULL");
6707 char *value = convert_value_to_string(estate, paramdatum, paramtypeid);
6710 appendStringInfoCharMacro(¶mstr, '\'');
6711 for (p = value; *p; p++)
6713 if (*p == '\'') /* double single quotes */
6714 appendStringInfoCharMacro(¶mstr, *p);
6715 appendStringInfoCharMacro(¶mstr, *p);
6717 appendStringInfoCharMacro(¶mstr, '\'');
6723 return paramstr.data;
6727 * Return a formatted string with information about PreparedParamsData, or NULL
6728 * if there are no parameters.
6731 format_preparedparamsdata(PLpgSQL_execstate *estate,
6732 const PreparedParamsData *ppd)
6735 StringInfoData paramstr;
6740 initStringInfo(¶mstr);
6741 for (paramno = 0; paramno < ppd->nargs; paramno++)
6743 appendStringInfo(¶mstr, "%s$%d = ",
6744 paramno > 0 ? ", " : "",
6747 if (ppd->nulls[paramno] == 'n')
6748 appendStringInfoString(¶mstr, "NULL");
6751 char *value = convert_value_to_string(estate, ppd->values[paramno], ppd->types[paramno]);
6754 appendStringInfoCharMacro(¶mstr, '\'');
6755 for (p = value; *p; p++)
6757 if (*p == '\'') /* double single quotes */
6758 appendStringInfoCharMacro(¶mstr, *p);
6759 appendStringInfoCharMacro(¶mstr, *p);
6761 appendStringInfoCharMacro(¶mstr, '\'');
6765 return paramstr.data;