1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2011, 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/transam.h"
21 #include "access/tupconvert.h"
22 #include "catalog/pg_proc.h"
23 #include "catalog/pg_type.h"
24 #include "executor/spi_priv.h"
26 #include "miscadmin.h"
27 #include "nodes/nodeFuncs.h"
28 #include "parser/scansup.h"
29 #include "storage/proc.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/array.h"
32 #include "utils/builtins.h"
33 #include "utils/datum.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/snapmgr.h"
37 #include "utils/typcache.h"
40 static const char *const raise_skip_msg = "RAISE";
44 int nargs; /* number of arguments */
45 Oid *types; /* types of arguments */
46 Datum *values; /* evaluated argument values */
47 char *nulls; /* null markers (' '/'n' style) */
48 bool *freevals; /* which arguments are pfree-able */
52 * All plpgsql function executions within a single transaction share the same
53 * executor EState for evaluating "simple" expressions. Each function call
54 * creates its own "eval_econtext" ExprContext within this estate for
55 * per-evaluation workspace. eval_econtext is freed at normal function exit,
56 * and the EState is freed at transaction end (in case of error, we assume
57 * that the abort mechanisms clean it all up). Furthermore, any exception
58 * block within a function has to have its own eval_econtext separate from
59 * the containing function's, so that we can clean up ExprContext callbacks
60 * properly at subtransaction exit. We maintain a stack that tracks the
61 * individual econtexts so that we can clean up correctly at subxact exit.
63 * This arrangement is a bit tedious to maintain, but it's worth the trouble
64 * so that we don't have to re-prepare simple expressions on each trip through
65 * a function. (We assume the case to optimize is many repetitions of a
66 * function within a transaction.)
68 typedef struct SimpleEcontextStackEntry
70 ExprContext *stack_econtext; /* a stacked econtext */
71 SubTransactionId xact_subxid; /* ID for current subxact */
72 struct SimpleEcontextStackEntry *next; /* next stack entry up */
73 } SimpleEcontextStackEntry;
75 static EState *simple_eval_estate = NULL;
76 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
78 /************************************************************
79 * Local function forward declarations
80 ************************************************************/
81 static void plpgsql_exec_error_callback(void *arg);
82 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
84 static int exec_stmt_block(PLpgSQL_execstate *estate,
85 PLpgSQL_stmt_block *block);
86 static int exec_stmts(PLpgSQL_execstate *estate,
88 static int exec_stmt(PLpgSQL_execstate *estate,
90 static int exec_stmt_assign(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_assign *stmt);
92 static int exec_stmt_perform(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_perform *stmt);
94 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_getdiag *stmt);
96 static int exec_stmt_if(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_if *stmt);
98 static int exec_stmt_case(PLpgSQL_execstate *estate,
99 PLpgSQL_stmt_case *stmt);
100 static int exec_stmt_loop(PLpgSQL_execstate *estate,
101 PLpgSQL_stmt_loop *stmt);
102 static int exec_stmt_while(PLpgSQL_execstate *estate,
103 PLpgSQL_stmt_while *stmt);
104 static int exec_stmt_fori(PLpgSQL_execstate *estate,
105 PLpgSQL_stmt_fori *stmt);
106 static int exec_stmt_fors(PLpgSQL_execstate *estate,
107 PLpgSQL_stmt_fors *stmt);
108 static int exec_stmt_forc(PLpgSQL_execstate *estate,
109 PLpgSQL_stmt_forc *stmt);
110 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
111 PLpgSQL_stmt_foreach_a *stmt);
112 static int exec_stmt_open(PLpgSQL_execstate *estate,
113 PLpgSQL_stmt_open *stmt);
114 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
115 PLpgSQL_stmt_fetch *stmt);
116 static int exec_stmt_close(PLpgSQL_execstate *estate,
117 PLpgSQL_stmt_close *stmt);
118 static int exec_stmt_exit(PLpgSQL_execstate *estate,
119 PLpgSQL_stmt_exit *stmt);
120 static int exec_stmt_return(PLpgSQL_execstate *estate,
121 PLpgSQL_stmt_return *stmt);
122 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
123 PLpgSQL_stmt_return_next *stmt);
124 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
125 PLpgSQL_stmt_return_query *stmt);
126 static int exec_stmt_raise(PLpgSQL_execstate *estate,
127 PLpgSQL_stmt_raise *stmt);
128 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
129 PLpgSQL_stmt_execsql *stmt);
130 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
131 PLpgSQL_stmt_dynexecute *stmt);
132 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
133 PLpgSQL_stmt_dynfors *stmt);
135 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
136 PLpgSQL_function *func,
138 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
140 static void exec_prepare_plan(PLpgSQL_execstate *estate,
141 PLpgSQL_expr *expr, int cursorOptions);
142 static bool exec_simple_check_node(Node *node);
143 static void exec_simple_check_plan(PLpgSQL_expr *expr);
144 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
150 static void exec_assign_expr(PLpgSQL_execstate *estate,
151 PLpgSQL_datum *target,
153 static void exec_assign_value(PLpgSQL_execstate *estate,
154 PLpgSQL_datum *target,
155 Datum value, Oid valtype, bool *isNull);
156 static void exec_eval_datum(PLpgSQL_execstate *estate,
157 PLpgSQL_datum *datum,
162 static int exec_eval_integer(PLpgSQL_execstate *estate,
165 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
168 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
172 static int exec_run_select(PLpgSQL_execstate *estate,
173 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
174 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
175 Portal portal, bool prefetch_ok);
176 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
178 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
179 static void exec_move_row(PLpgSQL_execstate *estate,
182 HeapTuple tup, TupleDesc tupdesc);
183 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
186 static char *convert_value_to_string(Datum value, Oid valtype);
187 static Datum exec_cast_value(Datum value, Oid valtype,
193 static Datum exec_simple_cast_value(Datum value, Oid valtype,
194 Oid reqtype, int32 reqtypmod,
196 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
197 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
198 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
199 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
200 static void free_var(PLpgSQL_var *var);
201 static void assign_text_var(PLpgSQL_var *var, const char *str);
202 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
204 static void free_params_data(PreparedParamsData *ppd);
205 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
206 PLpgSQL_expr *dynquery, List *params,
207 const char *portalname, int cursorOptions);
211 * plpgsql_exec_function Called by the call handler for
212 * function execution.
216 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
218 PLpgSQL_execstate estate;
219 ErrorContextCallback plerrcontext;
224 * Setup the execution state
226 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
229 * Setup error traceback support for ereport()
231 plerrcontext.callback = plpgsql_exec_error_callback;
232 plerrcontext.arg = &estate;
233 plerrcontext.previous = error_context_stack;
234 error_context_stack = &plerrcontext;
237 * Make local execution copies of all the datums
239 estate.err_text = gettext_noop("during initialization of execution state");
240 for (i = 0; i < estate.ndatums; i++)
241 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
244 * Store the actual call argument values into the appropriate variables
246 estate.err_text = gettext_noop("while storing call arguments into local variables");
247 for (i = 0; i < func->fn_nargs; i++)
249 int n = func->fn_argvarnos[i];
251 switch (estate.datums[n]->dtype)
253 case PLPGSQL_DTYPE_VAR:
255 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
257 var->value = fcinfo->arg[i];
258 var->isnull = fcinfo->argnull[i];
259 var->freeval = false;
263 case PLPGSQL_DTYPE_ROW:
265 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
267 if (!fcinfo->argnull[i])
273 HeapTupleData tmptup;
275 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
276 /* Extract rowtype info and find a tupdesc */
277 tupType = HeapTupleHeaderGetTypeId(td);
278 tupTypmod = HeapTupleHeaderGetTypMod(td);
279 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
280 /* Build a temporary HeapTuple control structure */
281 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
282 ItemPointerSetInvalid(&(tmptup.t_self));
283 tmptup.t_tableOid = InvalidOid;
285 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
286 ReleaseTupleDesc(tupdesc);
290 /* If arg is null, treat it as an empty row */
291 exec_move_row(&estate, NULL, row, NULL, NULL);
297 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
301 estate.err_text = gettext_noop("during function entry");
304 * Set the magic variable FOUND to false
306 exec_set_found(&estate, false);
309 * Let the instrumentation plugin peek at this function
311 if (*plugin_ptr && (*plugin_ptr)->func_beg)
312 ((*plugin_ptr)->func_beg) (&estate, func);
315 * Now call the toplevel block of statements
317 estate.err_text = NULL;
318 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
319 rc = exec_stmt_block(&estate, func->action);
320 if (rc != PLPGSQL_RC_RETURN)
322 estate.err_stmt = NULL;
323 estate.err_text = NULL;
326 * Provide a more helpful message if a CONTINUE or RAISE has been used
327 * outside the context it can work in.
329 if (rc == PLPGSQL_RC_CONTINUE)
331 (errcode(ERRCODE_SYNTAX_ERROR),
332 errmsg("CONTINUE cannot be used outside a loop")));
335 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
336 errmsg("control reached end of function without RETURN")));
340 * We got a return value - process it
342 estate.err_stmt = NULL;
343 estate.err_text = gettext_noop("while casting return value to function's return type");
345 fcinfo->isnull = estate.retisnull;
349 ReturnSetInfo *rsi = estate.rsi;
351 /* Check caller can handle a set result */
352 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
353 (rsi->allowedModes & SFRM_Materialize) == 0)
355 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
356 errmsg("set-valued function called in context that cannot accept a set")));
357 rsi->returnMode = SFRM_Materialize;
359 /* If we produced any tuples, send back the result */
360 if (estate.tuple_store)
362 rsi->setResult = estate.tuple_store;
363 if (estate.rettupdesc)
365 MemoryContext oldcxt;
367 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
368 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
369 MemoryContextSwitchTo(oldcxt);
372 estate.retval = (Datum) 0;
373 fcinfo->isnull = true;
375 else if (!estate.retisnull)
377 if (estate.retistuple)
380 * We have to check that the returned tuple actually matches the
381 * expected result type. XXX would be better to cache the tupdesc
382 * instead of repeating get_call_result_type()
384 HeapTuple rettup = (HeapTuple) DatumGetPointer(estate.retval);
386 TupleConversionMap *tupmap;
388 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
390 case TYPEFUNC_COMPOSITE:
391 /* got the expected result rowtype, now check it */
392 tupmap = convert_tuples_by_position(estate.rettupdesc,
394 gettext_noop("returned record type does not match expected record type"));
395 /* it might need conversion */
397 rettup = do_convert_tuple(rettup, tupmap);
398 /* no need to free map, we're about to return anyway */
400 case TYPEFUNC_RECORD:
403 * Failed to determine actual type of RECORD. We could
404 * raise an error here, but what this means in practice is
405 * that the caller is expecting any old generic rowtype,
406 * so we don't really need to be restrictive. Pass back
407 * the generated result type, instead.
409 tupdesc = estate.rettupdesc;
410 if (tupdesc == NULL) /* shouldn't happen */
411 elog(ERROR, "return type must be a row type");
414 /* shouldn't get here if retistuple is true ... */
415 elog(ERROR, "return type must be a row type");
420 * Copy tuple to upper executor memory, as a tuple Datum. Make
421 * sure it is labeled with the caller-supplied tuple type.
423 estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
427 /* Cast value to proper type */
428 estate.retval = exec_cast_value(estate.retval, estate.rettype,
430 &(func->fn_retinput),
431 func->fn_rettypioparam,
436 * If the function's return type isn't by value, copy the value
437 * into upper executor memory context.
439 if (!fcinfo->isnull && !func->fn_retbyval)
444 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
445 tmp = SPI_palloc(len);
446 memcpy(tmp, DatumGetPointer(estate.retval), len);
447 estate.retval = PointerGetDatum(tmp);
452 estate.err_text = gettext_noop("during function exit");
455 * Let the instrumentation plugin peek at this function
457 if (*plugin_ptr && (*plugin_ptr)->func_end)
458 ((*plugin_ptr)->func_end) (&estate, func);
460 /* Clean up any leftover temporary memory */
461 plpgsql_destroy_econtext(&estate);
462 exec_eval_cleanup(&estate);
465 * Pop the error context stack
467 error_context_stack = plerrcontext.previous;
470 * Return the function's result
472 return estate.retval;
477 * plpgsql_exec_trigger Called by the call handler for
482 plpgsql_exec_trigger(PLpgSQL_function *func,
483 TriggerData *trigdata)
485 PLpgSQL_execstate estate;
486 ErrorContextCallback plerrcontext;
490 PLpgSQL_rec *rec_new,
495 * Setup the execution state
497 plpgsql_estate_setup(&estate, func, NULL);
500 * Setup error traceback support for ereport()
502 plerrcontext.callback = plpgsql_exec_error_callback;
503 plerrcontext.arg = &estate;
504 plerrcontext.previous = error_context_stack;
505 error_context_stack = &plerrcontext;
508 * Make local execution copies of all the datums
510 estate.err_text = gettext_noop("during initialization of execution state");
511 for (i = 0; i < estate.ndatums; i++)
512 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
515 * Put the OLD and NEW tuples into record variables
517 * We make the tupdescs available in both records even though only one may
518 * have a value. This allows parsing of record references to succeed in
519 * functions that are used for multiple trigger types. For example, we
520 * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
521 * which should parse regardless of the current trigger type.
523 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
524 rec_new->freetup = false;
525 rec_new->tupdesc = trigdata->tg_relation->rd_att;
526 rec_new->freetupdesc = false;
527 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
528 rec_old->freetup = false;
529 rec_old->tupdesc = trigdata->tg_relation->rd_att;
530 rec_old->freetupdesc = false;
532 if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
535 * Per-statement triggers don't use OLD/NEW variables
540 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
542 rec_new->tup = trigdata->tg_trigtuple;
545 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
547 rec_new->tup = trigdata->tg_newtuple;
548 rec_old->tup = trigdata->tg_trigtuple;
550 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
553 rec_old->tup = trigdata->tg_trigtuple;
556 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
559 * Assign the special tg_ variables
562 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
563 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
564 var->value = CStringGetTextDatum("INSERT");
565 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
566 var->value = CStringGetTextDatum("UPDATE");
567 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
568 var->value = CStringGetTextDatum("DELETE");
569 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
570 var->value = CStringGetTextDatum("TRUNCATE");
572 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
576 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
577 var->value = DirectFunctionCall1(namein,
578 CStringGetDatum(trigdata->tg_trigger->tgname));
582 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
583 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
584 var->value = CStringGetTextDatum("BEFORE");
585 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
586 var->value = CStringGetTextDatum("AFTER");
587 else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
588 var->value = CStringGetTextDatum("INSTEAD OF");
590 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
594 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
595 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
596 var->value = CStringGetTextDatum("ROW");
597 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
598 var->value = CStringGetTextDatum("STATEMENT");
600 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
604 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
605 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
607 var->freeval = false;
609 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
610 var->value = DirectFunctionCall1(namein,
611 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
615 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
616 var->value = DirectFunctionCall1(namein,
617 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
621 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
622 var->value = DirectFunctionCall1(namein,
625 RelationGetNamespace(
626 trigdata->tg_relation))));
630 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
631 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
633 var->freeval = false;
635 var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
636 if (trigdata->tg_trigger->tgnargs > 0)
639 * For historical reasons, tg_argv[] subscripts start at zero not one.
640 * So we can't use construct_array().
642 int nelems = trigdata->tg_trigger->tgnargs;
647 elems = palloc(sizeof(Datum) * nelems);
648 for (i = 0; i < nelems; i++)
649 elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
653 var->value = PointerGetDatum(construct_md_array(elems, NULL,
662 var->value = (Datum) 0;
664 var->freeval = false;
667 estate.err_text = gettext_noop("during function entry");
670 * Set the magic variable FOUND to false
672 exec_set_found(&estate, false);
675 * Let the instrumentation plugin peek at this function
677 if (*plugin_ptr && (*plugin_ptr)->func_beg)
678 ((*plugin_ptr)->func_beg) (&estate, func);
681 * Now call the toplevel block of statements
683 estate.err_text = NULL;
684 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
685 rc = exec_stmt_block(&estate, func->action);
686 if (rc != PLPGSQL_RC_RETURN)
688 estate.err_stmt = NULL;
689 estate.err_text = NULL;
692 * Provide a more helpful message if a CONTINUE or RAISE has been used
693 * outside the context it can work in.
695 if (rc == PLPGSQL_RC_CONTINUE)
697 (errcode(ERRCODE_SYNTAX_ERROR),
698 errmsg("CONTINUE cannot be used outside a loop")));
701 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
702 errmsg("control reached end of trigger procedure without RETURN")));
705 estate.err_stmt = NULL;
706 estate.err_text = gettext_noop("during function exit");
710 (errcode(ERRCODE_DATATYPE_MISMATCH),
711 errmsg("trigger procedure cannot return a set")));
714 * Check that the returned tuple structure has the same attributes, the
715 * relation that fired the trigger has. A per-statement trigger always
716 * needs to return NULL, so we ignore any return value the function itself
717 * produces (XXX: is this a good idea?)
719 * XXX This way it is possible, that the trigger returns a tuple where
720 * attributes don't have the correct atttypmod's length. It's up to the
721 * trigger's programmer to ensure that this doesn't happen. Jan
723 if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
727 TupleConversionMap *tupmap;
729 rettup = (HeapTuple) DatumGetPointer(estate.retval);
730 /* check rowtype compatibility */
731 tupmap = convert_tuples_by_position(estate.rettupdesc,
732 trigdata->tg_relation->rd_att,
733 gettext_noop("returned row structure does not match the structure of the triggering table"));
734 /* it might need conversion */
736 rettup = do_convert_tuple(rettup, tupmap);
737 /* no need to free map, we're about to return anyway */
739 /* Copy tuple to upper executor memory */
740 rettup = SPI_copytuple(rettup);
744 * Let the instrumentation plugin peek at this function
746 if (*plugin_ptr && (*plugin_ptr)->func_end)
747 ((*plugin_ptr)->func_end) (&estate, func);
749 /* Clean up any leftover temporary memory */
750 plpgsql_destroy_econtext(&estate);
751 exec_eval_cleanup(&estate);
754 * Pop the error context stack
756 error_context_stack = plerrcontext.previous;
759 * Return the trigger's result
766 * error context callback to let us supply a call-stack traceback
769 plpgsql_exec_error_callback(void *arg)
771 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
773 /* if we are doing RAISE, don't report its location */
774 if (estate->err_text == raise_skip_msg)
777 if (estate->err_text != NULL)
780 * We don't expend the cycles to run gettext() on err_text unless we
781 * actually need it. Therefore, places that set up err_text should
782 * use gettext_noop() to ensure the strings get recorded in the
783 * message dictionary.
785 * If both err_text and err_stmt are set, use the err_text as
786 * description, but report the err_stmt's line number. When err_stmt
787 * is not set, we're in function entry/exit, or some such place not
788 * attached to a specific line number.
790 if (estate->err_stmt != NULL)
793 * translator: last %s is a phrase such as "during statement block
794 * local variable initialization"
796 errcontext("PL/pgSQL function \"%s\" line %d %s",
797 estate->func->fn_name,
798 estate->err_stmt->lineno,
799 _(estate->err_text));
804 * translator: last %s is a phrase such as "while storing call
805 * arguments into local variables"
807 errcontext("PL/pgSQL function \"%s\" %s",
808 estate->func->fn_name,
809 _(estate->err_text));
812 else if (estate->err_stmt != NULL)
814 /* translator: last %s is a plpgsql statement type name */
815 errcontext("PL/pgSQL function \"%s\" line %d at %s",
816 estate->func->fn_name,
817 estate->err_stmt->lineno,
818 plpgsql_stmt_typename(estate->err_stmt));
821 errcontext("PL/pgSQL function \"%s\"",
822 estate->func->fn_name);
827 * Support function for initializing local execution variables
830 static PLpgSQL_datum *
831 copy_plpgsql_datum(PLpgSQL_datum *datum)
833 PLpgSQL_datum *result;
835 switch (datum->dtype)
837 case PLPGSQL_DTYPE_VAR:
839 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
841 memcpy(new, datum, sizeof(PLpgSQL_var));
842 /* Ensure the value is null (possibly not needed?) */
845 new->freeval = false;
847 result = (PLpgSQL_datum *) new;
851 case PLPGSQL_DTYPE_REC:
853 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
855 memcpy(new, datum, sizeof(PLpgSQL_rec));
856 /* Ensure the value is null (possibly not needed?) */
859 new->freetup = false;
860 new->freetupdesc = false;
862 result = (PLpgSQL_datum *) new;
866 case PLPGSQL_DTYPE_ROW:
867 case PLPGSQL_DTYPE_RECFIELD:
868 case PLPGSQL_DTYPE_ARRAYELEM:
871 * These datum records are read-only at runtime, so no need to
878 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
879 result = NULL; /* keep compiler quiet */
888 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
890 for (; cond != NULL; cond = cond->next)
892 int sqlerrstate = cond->sqlerrstate;
895 * OTHERS matches everything *except* query-canceled; if you're
896 * foolish enough, you can match that explicitly.
898 if (sqlerrstate == 0)
900 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
904 else if (edata->sqlerrcode == sqlerrstate)
906 /* Category match? */
907 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
908 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
916 * exec_stmt_block Execute a block of statements
920 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
922 volatile int rc = -1;
927 * First initialize all variables declared in this block
929 estate->err_text = gettext_noop("during statement block local variable initialization");
931 for (i = 0; i < block->n_initvars; i++)
933 n = block->initvarnos[i];
935 switch (estate->datums[n]->dtype)
937 case PLPGSQL_DTYPE_VAR:
939 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
941 /* free any old value, in case re-entering block */
944 /* Initially it contains a NULL */
945 var->value = (Datum) 0;
948 if (var->default_val == NULL)
951 * If needed, give the datatype a chance to reject
952 * NULLs, by assigning a NULL to the variable. We
953 * claim the value is of type UNKNOWN, not the var's
954 * datatype, else coercion will be skipped. (Do this
955 * before the notnull check to be consistent with
956 * exec_assign_value.)
958 if (!var->datatype->typinput.fn_strict)
960 bool valIsNull = true;
962 exec_assign_value(estate,
963 (PLpgSQL_datum *) var,
970 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
971 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
976 exec_assign_expr(estate, (PLpgSQL_datum *) var,
982 case PLPGSQL_DTYPE_REC:
984 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
988 heap_freetuple(rec->tup);
989 rec->freetup = false;
991 if (rec->freetupdesc)
993 FreeTupleDesc(rec->tupdesc);
994 rec->freetupdesc = false;
1001 case PLPGSQL_DTYPE_RECFIELD:
1002 case PLPGSQL_DTYPE_ARRAYELEM:
1006 elog(ERROR, "unrecognized dtype: %d",
1007 estate->datums[n]->dtype);
1011 if (block->exceptions)
1014 * Execute the statements in the block's body inside a sub-transaction
1016 MemoryContext oldcontext = CurrentMemoryContext;
1017 ResourceOwner oldowner = CurrentResourceOwner;
1018 ExprContext *old_eval_econtext = estate->eval_econtext;
1019 ErrorData *save_cur_error = estate->cur_error;
1021 estate->err_text = gettext_noop("during statement block entry");
1023 BeginInternalSubTransaction(NULL);
1024 /* Want to run statements inside function's memory context */
1025 MemoryContextSwitchTo(oldcontext);
1030 * We need to run the block's statements with a new eval_econtext
1031 * that belongs to the current subtransaction; if we try to use
1032 * the outer econtext then ExprContext shutdown callbacks will be
1033 * called at the wrong times.
1035 plpgsql_create_econtext(estate);
1037 estate->err_text = NULL;
1039 /* Run the block's statements */
1040 rc = exec_stmts(estate, block->body);
1042 estate->err_text = gettext_noop("during statement block exit");
1045 * If the block ended with RETURN, we may need to copy the return
1046 * value out of the subtransaction eval_context. This is
1047 * currently only needed for scalar result types --- rowtype
1048 * values will always exist in the function's own memory context.
1050 if (rc == PLPGSQL_RC_RETURN &&
1051 !estate->retisset &&
1052 !estate->retisnull &&
1053 estate->rettupdesc == NULL)
1058 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1059 estate->retval = datumCopy(estate->retval,
1060 resTypByVal, resTypLen);
1063 /* Commit the inner transaction, return to outer xact context */
1064 ReleaseCurrentSubTransaction();
1065 MemoryContextSwitchTo(oldcontext);
1066 CurrentResourceOwner = oldowner;
1069 * Revert to outer eval_econtext. (The inner one was
1070 * automatically cleaned up during subxact exit.)
1072 estate->eval_econtext = old_eval_econtext;
1075 * AtEOSubXact_SPI() should not have popped any SPI context, but
1076 * just in case it did, make sure we remain connected.
1078 SPI_restore_connection();
1085 estate->err_text = gettext_noop("during exception cleanup");
1087 /* Save error info */
1088 MemoryContextSwitchTo(oldcontext);
1089 edata = CopyErrorData();
1092 /* Abort the inner transaction */
1093 RollbackAndReleaseCurrentSubTransaction();
1094 MemoryContextSwitchTo(oldcontext);
1095 CurrentResourceOwner = oldowner;
1097 /* Revert to outer eval_econtext */
1098 estate->eval_econtext = old_eval_econtext;
1101 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1102 * will have left us in a disconnected state. We need this hack
1103 * to return to connected state.
1105 SPI_restore_connection();
1107 /* Must clean up the econtext too */
1108 exec_eval_cleanup(estate);
1110 /* Look for a matching exception handler */
1111 foreach(e, block->exceptions->exc_list)
1113 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1115 if (exception_matches_conditions(edata, exception->conditions))
1118 * Initialize the magic SQLSTATE and SQLERRM variables for
1119 * the exception block. We needn't do this until we have
1120 * found a matching exception.
1122 PLpgSQL_var *state_var;
1123 PLpgSQL_var *errm_var;
1125 state_var = (PLpgSQL_var *)
1126 estate->datums[block->exceptions->sqlstate_varno];
1127 errm_var = (PLpgSQL_var *)
1128 estate->datums[block->exceptions->sqlerrm_varno];
1130 assign_text_var(state_var,
1131 unpack_sql_state(edata->sqlerrcode));
1132 assign_text_var(errm_var, edata->message);
1135 * Also set up cur_error so the error data is accessible
1136 * inside the handler.
1138 estate->cur_error = edata;
1140 estate->err_text = NULL;
1142 rc = exec_stmts(estate, exception->action);
1144 free_var(state_var);
1145 state_var->value = (Datum) 0;
1146 state_var->isnull = true;
1148 errm_var->value = (Datum) 0;
1149 errm_var->isnull = true;
1156 * Restore previous state of cur_error, whether or not we executed
1157 * a handler. This is needed in case an error got thrown from
1158 * some inner block's exception handler.
1160 estate->cur_error = save_cur_error;
1162 /* If no match found, re-throw the error */
1164 ReThrowError(edata);
1166 FreeErrorData(edata);
1170 Assert(save_cur_error == estate->cur_error);
1175 * Just execute the statements in the block's body
1177 estate->err_text = NULL;
1179 rc = exec_stmts(estate, block->body);
1182 estate->err_text = NULL;
1185 * Handle the return code.
1190 case PLPGSQL_RC_RETURN:
1191 case PLPGSQL_RC_CONTINUE:
1194 case PLPGSQL_RC_EXIT:
1197 * This is intentionally different from the handling of RC_EXIT
1198 * for loops: to match a block, we require a match by label.
1200 if (estate->exitlabel == NULL)
1201 return PLPGSQL_RC_EXIT;
1202 if (block->label == NULL)
1203 return PLPGSQL_RC_EXIT;
1204 if (strcmp(block->label, estate->exitlabel) != 0)
1205 return PLPGSQL_RC_EXIT;
1206 estate->exitlabel = NULL;
1207 return PLPGSQL_RC_OK;
1210 elog(ERROR, "unrecognized rc: %d", rc);
1213 return PLPGSQL_RC_OK;
1218 * exec_stmts Iterate over a list of statements
1219 * as long as their return code is OK
1223 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1230 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1231 * statement. This prevents hangup in a tight loop if, for instance,
1232 * there is a LOOP construct with an empty body.
1234 CHECK_FOR_INTERRUPTS();
1235 return PLPGSQL_RC_OK;
1240 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1241 int rc = exec_stmt(estate, stmt);
1243 if (rc != PLPGSQL_RC_OK)
1247 return PLPGSQL_RC_OK;
1252 * exec_stmt Distribute one statement to the statements
1253 * type specific execution function.
1257 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1259 PLpgSQL_stmt *save_estmt;
1262 save_estmt = estate->err_stmt;
1263 estate->err_stmt = stmt;
1265 /* Let the plugin know that we are about to execute this statement */
1266 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1267 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1269 CHECK_FOR_INTERRUPTS();
1271 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1273 case PLPGSQL_STMT_BLOCK:
1274 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1277 case PLPGSQL_STMT_ASSIGN:
1278 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1281 case PLPGSQL_STMT_PERFORM:
1282 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1285 case PLPGSQL_STMT_GETDIAG:
1286 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1289 case PLPGSQL_STMT_IF:
1290 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1293 case PLPGSQL_STMT_CASE:
1294 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1297 case PLPGSQL_STMT_LOOP:
1298 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1301 case PLPGSQL_STMT_WHILE:
1302 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1305 case PLPGSQL_STMT_FORI:
1306 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1309 case PLPGSQL_STMT_FORS:
1310 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1313 case PLPGSQL_STMT_FORC:
1314 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1317 case PLPGSQL_STMT_FOREACH_A:
1318 rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
1321 case PLPGSQL_STMT_EXIT:
1322 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1325 case PLPGSQL_STMT_RETURN:
1326 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1329 case PLPGSQL_STMT_RETURN_NEXT:
1330 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1333 case PLPGSQL_STMT_RETURN_QUERY:
1334 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1337 case PLPGSQL_STMT_RAISE:
1338 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1341 case PLPGSQL_STMT_EXECSQL:
1342 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1345 case PLPGSQL_STMT_DYNEXECUTE:
1346 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1349 case PLPGSQL_STMT_DYNFORS:
1350 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1353 case PLPGSQL_STMT_OPEN:
1354 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1357 case PLPGSQL_STMT_FETCH:
1358 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1361 case PLPGSQL_STMT_CLOSE:
1362 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1366 estate->err_stmt = save_estmt;
1367 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1370 /* Let the plugin know that we have finished executing this statement */
1371 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1372 ((*plugin_ptr)->stmt_end) (estate, stmt);
1374 estate->err_stmt = save_estmt;
1381 * exec_stmt_assign Evaluate an expression and
1382 * put the result into a variable.
1386 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1388 Assert(stmt->varno >= 0);
1390 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1392 return PLPGSQL_RC_OK;
1396 * exec_stmt_perform Evaluate query and discard result (but set
1397 * FOUND depending on whether at least one row
1402 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1404 PLpgSQL_expr *expr = stmt->expr;
1406 (void) exec_run_select(estate, expr, 0, NULL);
1407 exec_set_found(estate, (estate->eval_processed != 0));
1408 exec_eval_cleanup(estate);
1410 return PLPGSQL_RC_OK;
1414 * exec_stmt_getdiag Put internal PG information into
1415 * specified variables.
1419 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1423 foreach(lc, stmt->diag_items)
1425 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1427 bool isnull = false;
1429 if (diag_item->target <= 0)
1432 var = estate->datums[diag_item->target];
1437 switch (diag_item->kind)
1439 case PLPGSQL_GETDIAG_ROW_COUNT:
1441 exec_assign_value(estate, var,
1442 UInt32GetDatum(estate->eval_processed),
1446 case PLPGSQL_GETDIAG_RESULT_OID:
1448 exec_assign_value(estate, var,
1449 ObjectIdGetDatum(estate->eval_lastoid),
1454 elog(ERROR, "unrecognized attribute request: %d",
1459 return PLPGSQL_RC_OK;
1463 * exec_stmt_if Evaluate a bool expression and
1464 * execute the true or false body
1469 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1474 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1475 exec_eval_cleanup(estate);
1477 if (!isnull && value)
1479 if (stmt->true_body != NIL)
1480 return exec_stmts(estate, stmt->true_body);
1484 if (stmt->false_body != NIL)
1485 return exec_stmts(estate, stmt->false_body);
1488 return PLPGSQL_RC_OK;
1497 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1499 PLpgSQL_var *t_var = NULL;
1503 if (stmt->t_expr != NULL)
1509 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1511 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1514 * When expected datatype is different from real, change it. Note that
1515 * what we're modifying here is an execution copy of the datum, so
1516 * this doesn't affect the originally stored function parse tree.
1518 if (t_var->datatype->typoid != t_oid)
1519 t_var->datatype = plpgsql_build_datatype(t_oid, -1);
1521 /* now we can assign to the variable */
1522 exec_assign_value(estate,
1523 (PLpgSQL_datum *) t_var,
1528 exec_eval_cleanup(estate);
1531 /* Now search for a successful WHEN clause */
1532 foreach(l, stmt->case_when_list)
1534 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1537 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1538 exec_eval_cleanup(estate);
1539 if (!isnull && value)
1543 /* We can now discard any value we had for the temp variable */
1547 t_var->value = (Datum) 0;
1548 t_var->isnull = true;
1551 /* Evaluate the statement(s), and we're done */
1552 return exec_stmts(estate, cwt->stmts);
1556 /* We can now discard any value we had for the temp variable */
1560 t_var->value = (Datum) 0;
1561 t_var->isnull = true;
1564 /* SQL2003 mandates this error if there was no ELSE clause */
1565 if (!stmt->have_else)
1567 (errcode(ERRCODE_CASE_NOT_FOUND),
1568 errmsg("case not found"),
1569 errhint("CASE statement is missing ELSE part.")));
1571 /* Evaluate the ELSE statements, and we're done */
1572 return exec_stmts(estate, stmt->else_stmts);
1577 * exec_stmt_loop Loop over statements until
1582 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1586 int rc = exec_stmts(estate, stmt->body);
1593 case PLPGSQL_RC_EXIT:
1594 if (estate->exitlabel == NULL)
1595 return PLPGSQL_RC_OK;
1596 if (stmt->label == NULL)
1597 return PLPGSQL_RC_EXIT;
1598 if (strcmp(stmt->label, estate->exitlabel) != 0)
1599 return PLPGSQL_RC_EXIT;
1600 estate->exitlabel = NULL;
1601 return PLPGSQL_RC_OK;
1603 case PLPGSQL_RC_CONTINUE:
1604 if (estate->exitlabel == NULL)
1605 /* anonymous continue, so re-run the loop */
1607 else if (stmt->label != NULL &&
1608 strcmp(stmt->label, estate->exitlabel) == 0)
1609 /* label matches named continue, so re-run loop */
1610 estate->exitlabel = NULL;
1612 /* label doesn't match named continue, so propagate upward */
1613 return PLPGSQL_RC_CONTINUE;
1616 case PLPGSQL_RC_RETURN:
1620 elog(ERROR, "unrecognized rc: %d", rc);
1624 return PLPGSQL_RC_OK;
1629 * exec_stmt_while Loop over statements as long
1630 * as an expression evaluates to
1631 * true or an exit occurs.
1635 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1643 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1644 exec_eval_cleanup(estate);
1646 if (isnull || !value)
1649 rc = exec_stmts(estate, stmt->body);
1656 case PLPGSQL_RC_EXIT:
1657 if (estate->exitlabel == NULL)
1658 return PLPGSQL_RC_OK;
1659 if (stmt->label == NULL)
1660 return PLPGSQL_RC_EXIT;
1661 if (strcmp(stmt->label, estate->exitlabel) != 0)
1662 return PLPGSQL_RC_EXIT;
1663 estate->exitlabel = NULL;
1664 return PLPGSQL_RC_OK;
1666 case PLPGSQL_RC_CONTINUE:
1667 if (estate->exitlabel == NULL)
1668 /* anonymous continue, so re-run loop */
1670 else if (stmt->label != NULL &&
1671 strcmp(stmt->label, estate->exitlabel) == 0)
1672 /* label matches named continue, so re-run loop */
1673 estate->exitlabel = NULL;
1675 /* label doesn't match named continue, propagate upward */
1676 return PLPGSQL_RC_CONTINUE;
1679 case PLPGSQL_RC_RETURN:
1683 elog(ERROR, "unrecognized rc: %d", rc);
1687 return PLPGSQL_RC_OK;
1692 * exec_stmt_fori Iterate an integer variable
1693 * from a lower to an upper value
1694 * incrementing or decrementing by the BY value
1698 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1708 int rc = PLPGSQL_RC_OK;
1710 var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1713 * Get the value of the lower bound
1715 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1716 value = exec_cast_value(value, valtype, var->datatype->typoid,
1717 &(var->datatype->typinput),
1718 var->datatype->typioparam,
1719 var->datatype->atttypmod, isnull);
1722 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1723 errmsg("lower bound of FOR loop cannot be null")));
1724 loop_value = DatumGetInt32(value);
1725 exec_eval_cleanup(estate);
1728 * Get the value of the upper bound
1730 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1731 value = exec_cast_value(value, valtype, var->datatype->typoid,
1732 &(var->datatype->typinput),
1733 var->datatype->typioparam,
1734 var->datatype->atttypmod, isnull);
1737 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1738 errmsg("upper bound of FOR loop cannot be null")));
1739 end_value = DatumGetInt32(value);
1740 exec_eval_cleanup(estate);
1743 * Get the step value
1747 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1748 value = exec_cast_value(value, valtype, var->datatype->typoid,
1749 &(var->datatype->typinput),
1750 var->datatype->typioparam,
1751 var->datatype->atttypmod, isnull);
1754 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1755 errmsg("BY value of FOR loop cannot be null")));
1756 step_value = DatumGetInt32(value);
1757 exec_eval_cleanup(estate);
1758 if (step_value <= 0)
1760 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1761 errmsg("BY value of FOR loop must be greater than zero")));
1772 * Check against upper bound
1776 if (loop_value < end_value)
1781 if (loop_value > end_value)
1785 found = true; /* looped at least once */
1788 * Assign current value to loop var
1790 var->value = Int32GetDatum(loop_value);
1791 var->isnull = false;
1794 * Execute the statements
1796 rc = exec_stmts(estate, stmt->body);
1798 if (rc == PLPGSQL_RC_RETURN)
1799 break; /* break out of the loop */
1800 else if (rc == PLPGSQL_RC_EXIT)
1802 if (estate->exitlabel == NULL)
1803 /* unlabelled exit, finish the current loop */
1805 else if (stmt->label != NULL &&
1806 strcmp(stmt->label, estate->exitlabel) == 0)
1808 /* labelled exit, matches the current stmt's label */
1809 estate->exitlabel = NULL;
1814 * otherwise, this is a labelled exit that does not match the
1815 * current statement's label, if any: return RC_EXIT so that the
1816 * EXIT continues to propagate up the stack.
1820 else if (rc == PLPGSQL_RC_CONTINUE)
1822 if (estate->exitlabel == NULL)
1823 /* unlabelled continue, so re-run the current loop */
1825 else if (stmt->label != NULL &&
1826 strcmp(stmt->label, estate->exitlabel) == 0)
1828 /* label matches named continue, so re-run loop */
1829 estate->exitlabel = NULL;
1835 * otherwise, this is a named continue that does not match the
1836 * current statement's label, if any: return RC_CONTINUE so
1837 * that the CONTINUE will propagate up the stack.
1844 * Increase/decrease loop value, unless it would overflow, in which
1845 * case exit the loop.
1849 if ((int32) (loop_value - step_value) > loop_value)
1851 loop_value -= step_value;
1855 if ((int32) (loop_value + step_value) < loop_value)
1857 loop_value += step_value;
1862 * Set the FOUND variable to indicate the result of executing the loop
1863 * (namely, whether we looped one or more times). This must be set here so
1864 * that it does not interfere with the value of the FOUND variable inside
1865 * the loop processing itself.
1867 exec_set_found(estate, found);
1874 * exec_stmt_fors Execute a query, assign each
1875 * tuple to a record or row and
1876 * execute a group of statements
1881 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1887 * Open the implicit cursor for the statement using exec_run_select
1889 exec_run_select(estate, stmt->query, 0, &portal);
1894 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1897 * Close the implicit cursor
1899 SPI_cursor_close(portal);
1906 * exec_stmt_forc Execute a loop for each row from a cursor.
1910 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1912 PLpgSQL_var *curvar;
1913 char *curname = NULL;
1914 const char *portalname;
1915 PLpgSQL_expr *query;
1916 ParamListInfo paramLI;
1921 * Get the cursor variable and if it has an assigned name, check
1922 * that it's not in use currently.
1925 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1926 if (!curvar->isnull)
1928 curname = TextDatumGetCString(curvar->value);
1929 if (SPI_cursor_find(curname) != NULL)
1931 (errcode(ERRCODE_DUPLICATE_CURSOR),
1932 errmsg("cursor \"%s\" already in use", curname)));
1936 * Open the cursor just like an OPEN command
1938 * Note: parser should already have checked that statement supplies
1939 * args iff cursor needs them, but we check again to be safe.
1942 if (stmt->argquery != NULL)
1945 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
1946 * statement to evaluate the args and put 'em into the
1950 PLpgSQL_stmt_execsql set_args;
1952 if (curvar->cursor_explicit_argrow < 0)
1954 (errcode(ERRCODE_SYNTAX_ERROR),
1955 errmsg("arguments given for cursor without arguments")));
1957 memset(&set_args, 0, sizeof(set_args));
1958 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1959 set_args.lineno = stmt->lineno;
1960 set_args.sqlstmt = stmt->argquery;
1961 set_args.into = true;
1962 /* XXX historically this has not been STRICT */
1963 set_args.row = (PLpgSQL_row *)
1964 (estate->datums[curvar->cursor_explicit_argrow]);
1966 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1967 elog(ERROR, "open cursor failed during argument processing");
1971 if (curvar->cursor_explicit_argrow >= 0)
1973 (errcode(ERRCODE_SYNTAX_ERROR),
1974 errmsg("arguments required for cursor")));
1977 query = curvar->cursor_explicit_expr;
1980 if (query->plan == NULL)
1981 exec_prepare_plan(estate, query, curvar->cursor_options);
1984 * Set up ParamListInfo (note this is only carrying a hook function, not
1985 * any actual data values, at this point)
1987 paramLI = setup_param_list(estate, query);
1990 * Open the cursor (the paramlist will get copied into the portal)
1992 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
1994 estate->readonly_func);
1996 elog(ERROR, "could not open cursor: %s",
1997 SPI_result_code_string(SPI_result));
1998 portalname = portal->name;
2000 /* don't need paramlist any more */
2005 * If cursor variable was NULL, store the generated portal name in it
2007 if (curname == NULL)
2008 assign_text_var(curvar, portal->name);
2011 * Execute the loop. We can't prefetch because the cursor is accessible
2012 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2014 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2017 * Close portal, and restore cursor variable if it was initially NULL.
2020 SPI_cursor_close(portal);
2022 if (curname == NULL)
2025 curvar->value = (Datum) 0;
2026 curvar->isnull = true;
2037 * exec_stmt_foreach_a Loop over elements or slices of an array
2039 * When looping over elements, the loop variable is the same type that the
2040 * array stores (eg: integer), when looping through slices, the loop variable
2041 * is an array of size and dimensions to match the size of the slice.
2045 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2049 PLpgSQL_datum *loop_var;
2050 Oid loop_var_elem_type;
2052 int rc = PLPGSQL_RC_OK;
2053 ArrayIterator array_iterator;
2054 Oid iterator_result_type;
2058 /* get the value of the array expression */
2059 value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype);
2062 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2063 errmsg("FOREACH expression must not be NULL")));
2065 /* check the type of the expression - must be an array */
2066 if (!OidIsValid(get_element_type(arrtype)))
2068 (errcode(ERRCODE_DATATYPE_MISMATCH),
2069 errmsg("FOREACH expression must yield an array, not type %s",
2070 format_type_be(arrtype))));
2073 * We must copy the array, else it will disappear in exec_eval_cleanup.
2074 * This is annoying, but cleanup will certainly happen while running the
2075 * loop body, so we have little choice.
2077 arr = DatumGetArrayTypePCopy(value);
2079 /* Clean up any leftover temporary memory */
2080 exec_eval_cleanup(estate);
2082 /* Slice dimension must be less than or equal to array dimension */
2083 if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2085 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2086 errmsg("slice dimension (%d) is out of the valid range 0..%d",
2087 stmt->slice, ARR_NDIM(arr))));
2089 /* Set up the loop variable and see if it is of an array type */
2090 loop_var = estate->datums[stmt->varno];
2091 if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
2092 loop_var->dtype == PLPGSQL_DTYPE_ROW)
2095 * Record/row variable is certainly not of array type, and might not
2096 * be initialized at all yet, so don't try to get its type
2098 loop_var_elem_type = InvalidOid;
2101 loop_var_elem_type = get_element_type(exec_get_datum_type(estate,
2105 * Sanity-check the loop variable type. We don't try very hard here,
2106 * and should not be too picky since it's possible that exec_assign_value
2107 * can coerce values of different types. But it seems worthwhile to
2108 * complain if the array-ness of the loop variable is not right.
2110 if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
2112 (errcode(ERRCODE_DATATYPE_MISMATCH),
2113 errmsg("FOREACH ... SLICE loop variable must be of an array type")));
2114 if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
2116 (errcode(ERRCODE_DATATYPE_MISMATCH),
2117 errmsg("FOREACH loop variable must not be of an array type")));
2119 /* Create an iterator to step through the array */
2120 array_iterator = array_create_iterator(arr, stmt->slice);
2122 /* Identify iterator result type */
2123 if (stmt->slice > 0)
2125 /* When slicing, nominal type of result is same as array type */
2126 iterator_result_type = arrtype;
2130 /* Without slicing, results are individual array elements */
2131 iterator_result_type = ARR_ELEMTYPE(arr);
2134 /* Iterate over the array elements or slices */
2135 while (array_iterate(array_iterator, &value, &isnull))
2137 found = true; /* looped at least once */
2139 /* Assign current element/slice to the loop variable */
2140 exec_assign_value(estate, loop_var, value, iterator_result_type,
2143 /* In slice case, value is temporary; must free it to avoid leakage */
2144 if (stmt->slice > 0)
2145 pfree(DatumGetPointer(value));
2148 * Execute the statements
2150 rc = exec_stmts(estate, stmt->body);
2152 /* Handle the return code */
2153 if (rc == PLPGSQL_RC_RETURN)
2154 break; /* break out of the loop */
2155 else if (rc == PLPGSQL_RC_EXIT)
2157 if (estate->exitlabel == NULL)
2158 /* unlabelled exit, finish the current loop */
2160 else if (stmt->label != NULL &&
2161 strcmp(stmt->label, estate->exitlabel) == 0)
2163 /* labelled exit, matches the current stmt's label */
2164 estate->exitlabel = NULL;
2169 * otherwise, this is a labelled exit that does not match the
2170 * current statement's label, if any: return RC_EXIT so that the
2171 * EXIT continues to propagate up the stack.
2175 else if (rc == PLPGSQL_RC_CONTINUE)
2177 if (estate->exitlabel == NULL)
2178 /* unlabelled continue, so re-run the current loop */
2180 else if (stmt->label != NULL &&
2181 strcmp(stmt->label, estate->exitlabel) == 0)
2183 /* label matches named continue, so re-run loop */
2184 estate->exitlabel = NULL;
2190 * otherwise, this is a named continue that does not match the
2191 * current statement's label, if any: return RC_CONTINUE so
2192 * that the CONTINUE will propagate up the stack.
2199 /* Release temporary memory, including the array value */
2200 array_free_iterator(array_iterator);
2204 * Set the FOUND variable to indicate the result of executing the loop
2205 * (namely, whether we looped one or more times). This must be set here so
2206 * that it does not interfere with the value of the FOUND variable inside
2207 * the loop processing itself.
2209 exec_set_found(estate, found);
2216 * exec_stmt_exit Implements EXIT and CONTINUE
2218 * This begins the process of exiting / restarting a loop.
2222 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2225 * If the exit / continue has a condition, evaluate it
2227 if (stmt->cond != NULL)
2232 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2233 exec_eval_cleanup(estate);
2234 if (isnull || value == false)
2235 return PLPGSQL_RC_OK;
2238 estate->exitlabel = stmt->label;
2240 return PLPGSQL_RC_EXIT;
2242 return PLPGSQL_RC_CONTINUE;
2247 * exec_stmt_return Evaluate an expression and start
2248 * returning from the function.
2252 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2255 * If processing a set-returning PL/pgSQL function, the final RETURN
2256 * indicates that the function is finished producing tuples. The rest of
2257 * the work will be done at the top level.
2259 if (estate->retisset)
2260 return PLPGSQL_RC_RETURN;
2262 /* initialize for null result (possibly a tuple) */
2263 estate->retval = (Datum) 0;
2264 estate->rettupdesc = NULL;
2265 estate->retisnull = true;
2267 if (stmt->retvarno >= 0)
2269 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2271 switch (retvar->dtype)
2273 case PLPGSQL_DTYPE_VAR:
2275 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2277 estate->retval = var->value;
2278 estate->retisnull = var->isnull;
2279 estate->rettype = var->datatype->typoid;
2283 case PLPGSQL_DTYPE_REC:
2285 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2287 if (HeapTupleIsValid(rec->tup))
2289 estate->retval = PointerGetDatum(rec->tup);
2290 estate->rettupdesc = rec->tupdesc;
2291 estate->retisnull = false;
2296 case PLPGSQL_DTYPE_ROW:
2298 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2300 Assert(row->rowtupdesc);
2302 PointerGetDatum(make_tuple_from_row(estate, row,
2304 if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
2305 elog(ERROR, "row not compatible with its own tupdesc");
2306 estate->rettupdesc = row->rowtupdesc;
2307 estate->retisnull = false;
2312 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2315 return PLPGSQL_RC_RETURN;
2318 if (stmt->expr != NULL)
2320 if (estate->retistuple)
2322 exec_run_select(estate, stmt->expr, 1, NULL);
2323 if (estate->eval_processed > 0)
2325 estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
2326 estate->rettupdesc = estate->eval_tuptable->tupdesc;
2327 estate->retisnull = false;
2332 /* Normal case for scalar results */
2333 estate->retval = exec_eval_expr(estate, stmt->expr,
2334 &(estate->retisnull),
2335 &(estate->rettype));
2338 return PLPGSQL_RC_RETURN;
2342 * Special hack for function returning VOID: instead of NULL, return a
2343 * non-null VOID value. This is of dubious importance but is kept for
2344 * backwards compatibility. Note that the only other way to get here is
2345 * to have written "RETURN NULL" in a function returning tuple.
2347 if (estate->fn_rettype == VOIDOID)
2349 estate->retval = (Datum) 0;
2350 estate->retisnull = false;
2351 estate->rettype = VOIDOID;
2354 return PLPGSQL_RC_RETURN;
2358 * exec_stmt_return_next Evaluate an expression and add it to the
2359 * list of tuples returned by the current
2364 exec_stmt_return_next(PLpgSQL_execstate *estate,
2365 PLpgSQL_stmt_return_next *stmt)
2369 HeapTuple tuple = NULL;
2370 bool free_tuple = false;
2372 if (!estate->retisset)
2374 (errcode(ERRCODE_SYNTAX_ERROR),
2375 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2377 if (estate->tuple_store == NULL)
2378 exec_init_tuple_store(estate);
2380 /* rettupdesc will be filled by exec_init_tuple_store */
2381 tupdesc = estate->rettupdesc;
2382 natts = tupdesc->natts;
2384 if (stmt->retvarno >= 0)
2386 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2388 switch (retvar->dtype)
2390 case PLPGSQL_DTYPE_VAR:
2392 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2393 Datum retval = var->value;
2394 bool isNull = var->isnull;
2398 (errcode(ERRCODE_DATATYPE_MISMATCH),
2399 errmsg("wrong result type supplied in RETURN NEXT")));
2401 /* coerce type if needed */
2402 retval = exec_simple_cast_value(retval,
2403 var->datatype->typoid,
2404 tupdesc->attrs[0]->atttypid,
2405 tupdesc->attrs[0]->atttypmod,
2408 tuplestore_putvalues(estate->tuple_store, tupdesc,
2413 case PLPGSQL_DTYPE_REC:
2415 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2416 TupleConversionMap *tupmap;
2418 if (!HeapTupleIsValid(rec->tup))
2420 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2421 errmsg("record \"%s\" is not assigned yet",
2423 errdetail("The tuple structure of a not-yet-assigned"
2424 " record is indeterminate.")));
2425 tupmap = convert_tuples_by_position(rec->tupdesc,
2427 gettext_noop("wrong record type supplied in RETURN NEXT"));
2429 /* it might need conversion */
2432 tuple = do_convert_tuple(tuple, tupmap);
2433 free_conversion_map(tupmap);
2438 case PLPGSQL_DTYPE_ROW:
2440 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2442 tuple = make_tuple_from_row(estate, row, tupdesc);
2445 (errcode(ERRCODE_DATATYPE_MISMATCH),
2446 errmsg("wrong record type supplied in RETURN NEXT")));
2452 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2456 else if (stmt->expr)
2464 (errcode(ERRCODE_DATATYPE_MISMATCH),
2465 errmsg("wrong result type supplied in RETURN NEXT")));
2467 retval = exec_eval_expr(estate,
2472 /* coerce type if needed */
2473 retval = exec_simple_cast_value(retval,
2475 tupdesc->attrs[0]->atttypid,
2476 tupdesc->attrs[0]->atttypmod,
2479 tuplestore_putvalues(estate->tuple_store, tupdesc,
2482 exec_eval_cleanup(estate);
2487 (errcode(ERRCODE_SYNTAX_ERROR),
2488 errmsg("RETURN NEXT must have a parameter")));
2491 if (HeapTupleIsValid(tuple))
2493 tuplestore_puttuple(estate->tuple_store, tuple);
2496 heap_freetuple(tuple);
2499 return PLPGSQL_RC_OK;
2503 * exec_stmt_return_query Evaluate a query and add it to the
2504 * list of tuples returned by the current
2509 exec_stmt_return_query(PLpgSQL_execstate *estate,
2510 PLpgSQL_stmt_return_query *stmt)
2513 uint32 processed = 0;
2514 TupleConversionMap *tupmap;
2516 if (!estate->retisset)
2518 (errcode(ERRCODE_SYNTAX_ERROR),
2519 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2521 if (estate->tuple_store == NULL)
2522 exec_init_tuple_store(estate);
2524 if (stmt->query != NULL)
2527 exec_run_select(estate, stmt->query, 0, &portal);
2531 /* RETURN QUERY EXECUTE */
2532 Assert(stmt->dynquery != NULL);
2533 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2534 stmt->params, NULL, 0);
2537 tupmap = convert_tuples_by_position(portal->tupDesc,
2539 gettext_noop("structure of query does not match function result type"));
2545 SPI_cursor_fetch(portal, true, 50);
2546 if (SPI_processed == 0)
2549 for (i = 0; i < SPI_processed; i++)
2551 HeapTuple tuple = SPI_tuptable->vals[i];
2554 tuple = do_convert_tuple(tuple, tupmap);
2555 tuplestore_puttuple(estate->tuple_store, tuple);
2557 heap_freetuple(tuple);
2561 SPI_freetuptable(SPI_tuptable);
2565 free_conversion_map(tupmap);
2567 SPI_freetuptable(SPI_tuptable);
2568 SPI_cursor_close(portal);
2570 estate->eval_processed = processed;
2571 exec_set_found(estate, processed != 0);
2573 return PLPGSQL_RC_OK;
2577 exec_init_tuple_store(PLpgSQL_execstate *estate)
2579 ReturnSetInfo *rsi = estate->rsi;
2580 MemoryContext oldcxt;
2581 ResourceOwner oldowner;
2584 * Check caller can handle a set result in the way we want
2586 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2587 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2588 rsi->expectedDesc == NULL)
2590 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2591 errmsg("set-valued function called in context that cannot accept a set")));
2594 * Switch to the right memory context and resource owner for storing the
2595 * tuplestore for return set. If we're within a subtransaction opened for
2596 * an exception-block, for example, we must still create the tuplestore in
2597 * the resource owner that was active when this function was entered, and
2598 * not in the subtransaction resource owner.
2600 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2601 oldowner = CurrentResourceOwner;
2602 CurrentResourceOwner = estate->tuple_store_owner;
2604 estate->tuple_store =
2605 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2608 CurrentResourceOwner = oldowner;
2609 MemoryContextSwitchTo(oldcxt);
2611 estate->rettupdesc = rsi->expectedDesc;
2615 * exec_stmt_raise Build a message and throw it with elog()
2619 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2622 char *condname = NULL;
2623 char *err_message = NULL;
2624 char *err_detail = NULL;
2625 char *err_hint = NULL;
2628 /* RAISE with no parameters: re-throw current exception */
2629 if (stmt->condname == NULL && stmt->message == NULL &&
2630 stmt->options == NIL)
2632 if (estate->cur_error != NULL)
2633 ReThrowError(estate->cur_error);
2634 /* oops, we're not inside a handler */
2636 (errcode(ERRCODE_SYNTAX_ERROR),
2637 errmsg("RAISE without parameters cannot be used outside an exception handler")));
2642 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2643 condname = pstrdup(stmt->condname);
2649 ListCell *current_param;
2652 initStringInfo(&ds);
2653 current_param = list_head(stmt->params);
2655 for (cp = stmt->message; *cp; cp++)
2658 * Occurrences of a single % are replaced by the next parameter's
2659 * external representation. Double %'s are converted to one %.
2670 appendStringInfoChar(&ds, '%');
2675 if (current_param == NULL)
2677 (errcode(ERRCODE_SYNTAX_ERROR),
2678 errmsg("too few parameters specified for RAISE")));
2680 paramvalue = exec_eval_expr(estate,
2681 (PLpgSQL_expr *) lfirst(current_param),
2688 extval = convert_value_to_string(paramvalue, paramtypeid);
2689 appendStringInfoString(&ds, extval);
2690 current_param = lnext(current_param);
2691 exec_eval_cleanup(estate);
2694 appendStringInfoChar(&ds, cp[0]);
2698 * If more parameters were specified than were required to process the
2699 * format string, throw an error
2701 if (current_param != NULL)
2703 (errcode(ERRCODE_SYNTAX_ERROR),
2704 errmsg("too many parameters specified for RAISE")));
2706 err_message = ds.data;
2707 /* No pfree(ds.data), the pfree(err_message) does it */
2710 foreach(lc, stmt->options)
2712 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2718 optionvalue = exec_eval_expr(estate, opt->expr,
2723 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2724 errmsg("RAISE statement option cannot be null")));
2726 extval = convert_value_to_string(optionvalue, optiontypeid);
2728 switch (opt->opt_type)
2730 case PLPGSQL_RAISEOPTION_ERRCODE:
2733 (errcode(ERRCODE_SYNTAX_ERROR),
2734 errmsg("RAISE option already specified: %s",
2736 err_code = plpgsql_recognize_err_condition(extval, true);
2737 condname = pstrdup(extval);
2739 case PLPGSQL_RAISEOPTION_MESSAGE:
2742 (errcode(ERRCODE_SYNTAX_ERROR),
2743 errmsg("RAISE option already specified: %s",
2745 err_message = pstrdup(extval);
2747 case PLPGSQL_RAISEOPTION_DETAIL:
2750 (errcode(ERRCODE_SYNTAX_ERROR),
2751 errmsg("RAISE option already specified: %s",
2753 err_detail = pstrdup(extval);
2755 case PLPGSQL_RAISEOPTION_HINT:
2758 (errcode(ERRCODE_SYNTAX_ERROR),
2759 errmsg("RAISE option already specified: %s",
2761 err_hint = pstrdup(extval);
2764 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
2767 exec_eval_cleanup(estate);
2770 /* Default code if nothing specified */
2771 if (err_code == 0 && stmt->elog_level >= ERROR)
2772 err_code = ERRCODE_RAISE_EXCEPTION;
2774 /* Default error message if nothing specified */
2775 if (err_message == NULL)
2779 err_message = condname;
2783 err_message = pstrdup(unpack_sql_state(err_code));
2787 * Throw the error (may or may not come back)
2789 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2791 ereport(stmt->elog_level,
2792 (err_code ? errcode(err_code) : 0,
2793 errmsg_internal("%s", err_message),
2794 (err_detail != NULL) ? errdetail("%s", err_detail) : 0,
2795 (err_hint != NULL) ? errhint("%s", err_hint) : 0));
2797 estate->err_text = NULL; /* un-suppress... */
2799 if (condname != NULL)
2801 if (err_message != NULL)
2803 if (err_detail != NULL)
2805 if (err_hint != NULL)
2808 return PLPGSQL_RC_OK;
2813 * Initialize a mostly empty execution state
2817 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2818 PLpgSQL_function *func,
2821 /* this link will be restored at exit from plpgsql_call_handler */
2822 func->cur_estate = estate;
2824 estate->func = func;
2826 estate->retval = (Datum) 0;
2827 estate->retisnull = true;
2828 estate->rettype = InvalidOid;
2830 estate->fn_rettype = func->fn_rettype;
2831 estate->retistuple = func->fn_retistuple;
2832 estate->retisset = func->fn_retset;
2834 estate->readonly_func = func->fn_readonly;
2836 estate->rettupdesc = NULL;
2837 estate->exitlabel = NULL;
2838 estate->cur_error = NULL;
2840 estate->tuple_store = NULL;
2843 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2844 estate->tuple_store_owner = CurrentResourceOwner;
2848 estate->tuple_store_cxt = NULL;
2849 estate->tuple_store_owner = NULL;
2853 estate->found_varno = func->found_varno;
2854 estate->ndatums = func->ndatums;
2855 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2856 /* caller is expected to fill the datums array */
2858 estate->eval_tuptable = NULL;
2859 estate->eval_processed = 0;
2860 estate->eval_lastoid = InvalidOid;
2861 estate->eval_econtext = NULL;
2862 estate->cur_expr = NULL;
2864 estate->err_stmt = NULL;
2865 estate->err_text = NULL;
2867 estate->plugin_info = NULL;
2870 * Create an EState and ExprContext for evaluation of simple expressions.
2872 plpgsql_create_econtext(estate);
2875 * Let the plugin see this function before we initialize any local
2876 * PL/pgSQL variables - note that we also give the plugin a few function
2877 * pointers so it can call back into PL/pgSQL for doing things like
2878 * variable assignments and stack traces
2882 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2883 (*plugin_ptr)->assign_expr = exec_assign_expr;
2885 if ((*plugin_ptr)->func_setup)
2886 ((*plugin_ptr)->func_setup) (estate, func);
2891 * Release temporary memory used by expression/subselect evaluation
2893 * NB: the result of the evaluation is no longer valid after this is done,
2894 * unless it is a pass-by-value datatype.
2896 * NB: if you change this code, see also the hacks in exec_assign_value's
2897 * PLPGSQL_DTYPE_ARRAYELEM case.
2901 exec_eval_cleanup(PLpgSQL_execstate *estate)
2903 /* Clear result of a full SPI_execute */
2904 if (estate->eval_tuptable != NULL)
2905 SPI_freetuptable(estate->eval_tuptable);
2906 estate->eval_tuptable = NULL;
2908 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2909 if (estate->eval_econtext != NULL)
2910 ResetExprContext(estate->eval_econtext);
2915 * Generate a prepared plan
2919 exec_prepare_plan(PLpgSQL_execstate *estate,
2920 PLpgSQL_expr *expr, int cursorOptions)
2925 * The grammar can't conveniently set expr->func while building the parse
2926 * tree, so make sure it's set before parser hooks need it.
2928 expr->func = estate->func;
2931 * Generate and save the plan
2933 plan = SPI_prepare_params(expr->query,
2934 (ParserSetupHook) plpgsql_parser_setup,
2939 /* Some SPI errors deserve specific error messages */
2942 case SPI_ERROR_COPY:
2944 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2945 errmsg("cannot COPY to/from client in PL/pgSQL")));
2946 case SPI_ERROR_TRANSACTION:
2948 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2949 errmsg("cannot begin/end transactions in PL/pgSQL"),
2950 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2952 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
2953 expr->query, SPI_result_code_string(SPI_result));
2956 expr->plan = SPI_saveplan(plan);
2958 exec_simple_check_plan(expr);
2963 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2967 exec_stmt_execsql(PLpgSQL_execstate *estate,
2968 PLpgSQL_stmt_execsql *stmt)
2970 ParamListInfo paramLI;
2973 PLpgSQL_expr *expr = stmt->sqlstmt;
2976 * On the first call for this statement generate the plan, and detect
2977 * whether the statement is INSERT/UPDATE/DELETE
2979 if (expr->plan == NULL)
2983 exec_prepare_plan(estate, expr, 0);
2984 stmt->mod_stmt = false;
2985 foreach(l, expr->plan->plancache_list)
2987 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2990 foreach(l2, plansource->plan->stmt_list)
2992 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2994 if (IsA(p, PlannedStmt) &&
2997 if (p->commandType == CMD_INSERT ||
2998 p->commandType == CMD_UPDATE ||
2999 p->commandType == CMD_DELETE)
3000 stmt->mod_stmt = true;
3007 * Set up ParamListInfo (note this is only carrying a hook function, not
3008 * any actual data values, at this point)
3010 paramLI = setup_param_list(estate, expr);
3013 * If we have INTO, then we only need one row back ... but if we have INTO
3014 * STRICT, ask for two rows, so that we can verify the statement returns
3015 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
3016 * INTO, just run the statement to completion (tcount = 0).
3018 * We could just ask for two rows always when using INTO, but there are
3019 * some cases where demanding the extra row costs significant time, eg by
3020 * forcing completion of a sequential scan. So don't do it unless we need
3021 * to enforce strictness.
3025 if (stmt->strict || stmt->mod_stmt)
3036 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
3037 estate->readonly_func, tcount);
3040 * Check for error, and set FOUND if appropriate (for historical reasons
3041 * we set FOUND only for certain query types). Also Assert that we
3042 * identified the statement type the same as SPI did.
3047 Assert(!stmt->mod_stmt);
3048 exec_set_found(estate, (SPI_processed != 0));
3054 case SPI_OK_INSERT_RETURNING:
3055 case SPI_OK_UPDATE_RETURNING:
3056 case SPI_OK_DELETE_RETURNING:
3057 Assert(stmt->mod_stmt);
3058 exec_set_found(estate, (SPI_processed != 0));
3061 case SPI_OK_SELINTO:
3062 case SPI_OK_UTILITY:
3063 Assert(!stmt->mod_stmt);
3066 case SPI_OK_REWRITTEN:
3067 Assert(!stmt->mod_stmt);
3070 * The command was rewritten into another kind of command. It's
3071 * not clear what FOUND would mean in that case (and SPI doesn't
3072 * return the row count either), so just set it to false.
3074 exec_set_found(estate, false);
3077 /* Some SPI errors deserve specific error messages */
3078 case SPI_ERROR_COPY:
3080 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3081 errmsg("cannot COPY to/from client in PL/pgSQL")));
3082 case SPI_ERROR_TRANSACTION:
3084 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3085 errmsg("cannot begin/end transactions in PL/pgSQL"),
3086 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3089 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
3090 expr->query, SPI_result_code_string(rc));
3093 /* All variants should save result info for GET DIAGNOSTICS */
3094 estate->eval_processed = SPI_processed;
3095 estate->eval_lastoid = SPI_lastoid;
3097 /* Process INTO if present */
3100 SPITupleTable *tuptab = SPI_tuptable;
3101 uint32 n = SPI_processed;
3102 PLpgSQL_rec *rec = NULL;
3103 PLpgSQL_row *row = NULL;
3105 /* If the statement did not return a tuple table, complain */
3108 (errcode(ERRCODE_SYNTAX_ERROR),
3109 errmsg("INTO used with a command that cannot return data")));
3111 /* Determine if we assign to a record or a row */
3112 if (stmt->rec != NULL)
3113 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3114 else if (stmt->row != NULL)
3115 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3117 elog(ERROR, "unsupported target");
3120 * If SELECT ... INTO specified STRICT, and the query didn't find
3121 * exactly one row, throw an error. If STRICT was not specified, then
3122 * allow the query to find any number of rows.
3128 (errcode(ERRCODE_NO_DATA_FOUND),
3129 errmsg("query returned no rows")));
3130 /* set the target to NULL(s) */
3131 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3135 if (n > 1 && (stmt->strict || stmt->mod_stmt))
3137 (errcode(ERRCODE_TOO_MANY_ROWS),
3138 errmsg("query returned more than one row")));
3139 /* Put the first result row into the target */
3140 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3144 SPI_freetuptable(SPI_tuptable);
3148 /* If the statement returned a tuple table, complain */
3149 if (SPI_tuptable != NULL)
3151 (errcode(ERRCODE_SYNTAX_ERROR),
3152 errmsg("query has no destination for result data"),
3153 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
3159 return PLPGSQL_RC_OK;
3164 * exec_stmt_dynexecute Execute a dynamic SQL query
3165 * (possibly with INTO).
3169 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
3170 PLpgSQL_stmt_dynexecute *stmt)
3173 bool isnull = false;
3179 * First we evaluate the string expression after the EXECUTE keyword. Its
3180 * result is the querystring we have to execute.
3182 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
3185 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3186 errmsg("query string argument of EXECUTE is null")));
3188 /* Get the C-String representation */
3189 querystr = convert_value_to_string(query, restype);
3191 exec_eval_cleanup(estate);
3194 * Execute the query without preparing a saved plan.
3198 PreparedParamsData *ppd;
3200 ppd = exec_eval_using_params(estate, stmt->params);
3201 exec_res = SPI_execute_with_args(querystr,
3202 ppd->nargs, ppd->types,
3203 ppd->values, ppd->nulls,
3204 estate->readonly_func, 0);
3205 free_params_data(ppd);
3208 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
3216 case SPI_OK_INSERT_RETURNING:
3217 case SPI_OK_UPDATE_RETURNING:
3218 case SPI_OK_DELETE_RETURNING:
3219 case SPI_OK_UTILITY:
3220 case SPI_OK_REWRITTEN:
3226 * Also allow a zero return, which implies the querystring
3227 * contained no commands.
3231 case SPI_OK_SELINTO:
3234 * We want to disallow SELECT INTO for now, because its behavior
3235 * is not consistent with SELECT INTO in a normal plpgsql context.
3236 * (We need to reimplement EXECUTE to parse the string as a
3237 * plpgsql command, not just feed it to SPI_execute.) However,
3238 * CREATE AS should be allowed ... and since it produces the same
3239 * parsetree as SELECT INTO, there's no way to tell the difference
3240 * except to look at the source text. Wotta kluge!
3245 for (ptr = querystr; *ptr; ptr++)
3246 if (!scanner_isspace(*ptr))
3248 if (*ptr == 'S' || *ptr == 's')
3250 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3251 errmsg("EXECUTE of SELECT ... INTO is not implemented"),
3252 errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
3256 /* Some SPI errors deserve specific error messages */
3257 case SPI_ERROR_COPY:
3259 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260 errmsg("cannot COPY to/from client in PL/pgSQL")));
3261 case SPI_ERROR_TRANSACTION:
3263 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3264 errmsg("cannot begin/end transactions in PL/pgSQL"),
3265 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3268 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3269 querystr, SPI_result_code_string(exec_res));
3273 /* Save result info for GET DIAGNOSTICS */
3274 estate->eval_processed = SPI_processed;
3275 estate->eval_lastoid = SPI_lastoid;
3277 /* Process INTO if present */
3280 SPITupleTable *tuptab = SPI_tuptable;
3281 uint32 n = SPI_processed;
3282 PLpgSQL_rec *rec = NULL;
3283 PLpgSQL_row *row = NULL;
3285 /* If the statement did not return a tuple table, complain */
3288 (errcode(ERRCODE_SYNTAX_ERROR),
3289 errmsg("INTO used with a command that cannot return data")));
3291 /* Determine if we assign to a record or a row */
3292 if (stmt->rec != NULL)
3293 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3294 else if (stmt->row != NULL)
3295 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3297 elog(ERROR, "unsupported target");
3300 * If SELECT ... INTO specified STRICT, and the query didn't find
3301 * exactly one row, throw an error. If STRICT was not specified, then
3302 * allow the query to find any number of rows.
3308 (errcode(ERRCODE_NO_DATA_FOUND),
3309 errmsg("query returned no rows")));
3310 /* set the target to NULL(s) */
3311 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3315 if (n > 1 && stmt->strict)
3317 (errcode(ERRCODE_TOO_MANY_ROWS),
3318 errmsg("query returned more than one row")));
3319 /* Put the first result row into the target */
3320 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3326 * It might be a good idea to raise an error if the query returned
3327 * tuples that are being ignored, but historically we have not done
3332 /* Release any result from SPI_execute, as well as the querystring */
3333 SPI_freetuptable(SPI_tuptable);
3336 return PLPGSQL_RC_OK;
3341 * exec_stmt_dynfors Execute a dynamic query, assign each
3342 * tuple to a record or row and
3343 * execute a group of statements
3348 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3353 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
3359 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3362 * Close the implicit cursor
3364 SPI_cursor_close(portal);
3371 * exec_stmt_open Execute an OPEN cursor statement
3375 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3377 PLpgSQL_var *curvar;
3378 char *curname = NULL;
3379 PLpgSQL_expr *query;
3381 ParamListInfo paramLI;
3384 * Get the cursor variable and if it has an assigned name, check
3385 * that it's not in use currently.
3388 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3389 if (!curvar->isnull)
3391 curname = TextDatumGetCString(curvar->value);
3392 if (SPI_cursor_find(curname) != NULL)
3394 (errcode(ERRCODE_DUPLICATE_CURSOR),
3395 errmsg("cursor \"%s\" already in use", curname)));
3399 * Process the OPEN according to it's type.
3402 if (stmt->query != NULL)
3405 * This is an OPEN refcursor FOR SELECT ...
3407 * We just make sure the query is planned. The real work is
3411 query = stmt->query;
3412 if (query->plan == NULL)
3413 exec_prepare_plan(estate, query, stmt->cursor_options);
3415 else if (stmt->dynquery != NULL)
3418 * This is an OPEN refcursor FOR EXECUTE ...
3421 portal = exec_dynquery_with_params(estate,
3425 stmt->cursor_options);
3428 * If cursor variable was NULL, store the generated portal name in it
3430 if (curname == NULL)
3431 assign_text_var(curvar, portal->name);
3433 return PLPGSQL_RC_OK;
3438 * This is an OPEN cursor
3440 * Note: parser should already have checked that statement supplies
3441 * args iff cursor needs them, but we check again to be safe.
3444 if (stmt->argquery != NULL)
3447 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3448 * statement to evaluate the args and put 'em into the
3452 PLpgSQL_stmt_execsql set_args;
3454 if (curvar->cursor_explicit_argrow < 0)
3456 (errcode(ERRCODE_SYNTAX_ERROR),
3457 errmsg("arguments given for cursor without arguments")));
3459 memset(&set_args, 0, sizeof(set_args));
3460 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3461 set_args.lineno = stmt->lineno;
3462 set_args.sqlstmt = stmt->argquery;
3463 set_args.into = true;
3464 /* XXX historically this has not been STRICT */
3465 set_args.row = (PLpgSQL_row *)
3466 (estate->datums[curvar->cursor_explicit_argrow]);
3468 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3469 elog(ERROR, "open cursor failed during argument processing");
3473 if (curvar->cursor_explicit_argrow >= 0)
3475 (errcode(ERRCODE_SYNTAX_ERROR),
3476 errmsg("arguments required for cursor")));
3479 query = curvar->cursor_explicit_expr;
3480 if (query->plan == NULL)
3481 exec_prepare_plan(estate, query, curvar->cursor_options);
3485 * Set up ParamListInfo (note this is only carrying a hook function, not
3486 * any actual data values, at this point)
3488 paramLI = setup_param_list(estate, query);
3493 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3495 estate->readonly_func);
3497 elog(ERROR, "could not open cursor: %s",
3498 SPI_result_code_string(SPI_result));
3501 * If cursor variable was NULL, store the generated portal name in it
3503 if (curname == NULL)
3504 assign_text_var(curvar, portal->name);
3511 return PLPGSQL_RC_OK;
3516 * exec_stmt_fetch Fetch from a cursor into a target, or just
3517 * move the current position of the cursor
3521 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3523 PLpgSQL_var *curvar = NULL;
3524 PLpgSQL_rec *rec = NULL;
3525 PLpgSQL_row *row = NULL;
3526 long how_many = stmt->how_many;
3527 SPITupleTable *tuptab;
3533 * Get the portal of the cursor by name
3536 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3539 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3540 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3541 curname = TextDatumGetCString(curvar->value);
3543 portal = SPI_cursor_find(curname);
3546 (errcode(ERRCODE_UNDEFINED_CURSOR),
3547 errmsg("cursor \"%s\" does not exist", curname)));
3550 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3555 /* XXX should be doing this in LONG not INT width */
3556 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3560 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3561 errmsg("relative or absolute cursor position is null")));
3563 exec_eval_cleanup(estate);
3569 * Determine if we fetch into a record or a row
3572 if (stmt->rec != NULL)
3573 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3574 else if (stmt->row != NULL)
3575 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3577 elog(ERROR, "unsupported target");
3580 * Fetch 1 tuple from the cursor
3583 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3584 tuptab = SPI_tuptable;
3588 * Set the target appropriately.
3592 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3594 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3596 SPI_freetuptable(tuptab);
3600 /* Move the cursor */
3601 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3605 /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3606 estate->eval_processed = n;
3607 exec_set_found(estate, n != 0);
3609 return PLPGSQL_RC_OK;
3613 * exec_stmt_close Close a cursor
3617 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3619 PLpgSQL_var *curvar = NULL;
3624 * Get the portal of the cursor by name
3627 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3630 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3631 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3632 curname = TextDatumGetCString(curvar->value);
3634 portal = SPI_cursor_find(curname);
3637 (errcode(ERRCODE_UNDEFINED_CURSOR),
3638 errmsg("cursor \"%s\" does not exist", curname)));
3645 SPI_cursor_close(portal);
3647 return PLPGSQL_RC_OK;
3652 * exec_assign_expr Put an expression's result into
3657 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3662 bool isnull = false;
3664 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3665 exec_assign_value(estate, target, value, valtype, &isnull);
3666 exec_eval_cleanup(estate);
3671 * exec_assign_value Put a value into a target field
3673 * Note: in some code paths, this may leak memory in the eval_econtext;
3674 * we assume that will be cleaned up later by exec_eval_cleanup. We cannot
3675 * call exec_eval_cleanup here for fear of destroying the input Datum value.
3679 exec_assign_value(PLpgSQL_execstate *estate,
3680 PLpgSQL_datum *target,
3681 Datum value, Oid valtype, bool *isNull)
3683 switch (target->dtype)
3685 case PLPGSQL_DTYPE_VAR:
3688 * Target is a variable
3690 PLpgSQL_var *var = (PLpgSQL_var *) target;
3693 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3694 &(var->datatype->typinput),
3695 var->datatype->typioparam,
3696 var->datatype->atttypmod,
3699 if (*isNull && var->notnull)
3701 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3702 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
3706 * If type is by-reference, make sure we have a freshly
3707 * palloc'd copy; the originally passed value may not live as
3708 * long as the variable! But we don't need to re-copy if
3709 * exec_cast_value performed a conversion; its output must
3710 * already be palloc'd.
3712 if (!var->datatype->typbyval && !*isNull)
3714 if (newvalue == value)
3715 newvalue = datumCopy(newvalue,
3717 var->datatype->typlen);
3721 * Now free the old value. (We can't do this any earlier
3722 * because of the possibility that we are assigning the var's
3723 * old value to it, eg "foo := foo". We could optimize out
3724 * the assignment altogether in such cases, but it's too
3725 * infrequent to be worth testing for.)
3729 var->value = newvalue;
3730 var->isnull = *isNull;
3731 if (!var->datatype->typbyval && !*isNull)
3732 var->freeval = true;
3736 case PLPGSQL_DTYPE_ROW:
3739 * Target is a row variable
3741 PLpgSQL_row *row = (PLpgSQL_row *) target;
3745 /* If source is null, just assign nulls to the row */
3746 exec_move_row(estate, NULL, row, NULL, NULL);
3754 HeapTupleData tmptup;
3756 /* Source must be of RECORD or composite type */
3757 if (!type_is_rowtype(valtype))
3759 (errcode(ERRCODE_DATATYPE_MISMATCH),
3760 errmsg("cannot assign non-composite value to a row variable")));
3761 /* Source is a tuple Datum, so safe to do this: */
3762 td = DatumGetHeapTupleHeader(value);
3763 /* Extract rowtype info and find a tupdesc */
3764 tupType = HeapTupleHeaderGetTypeId(td);
3765 tupTypmod = HeapTupleHeaderGetTypMod(td);
3766 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3767 /* Build a temporary HeapTuple control structure */
3768 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3769 ItemPointerSetInvalid(&(tmptup.t_self));
3770 tmptup.t_tableOid = InvalidOid;
3772 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3773 ReleaseTupleDesc(tupdesc);
3778 case PLPGSQL_DTYPE_REC:
3781 * Target is a record variable
3783 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3787 /* If source is null, just assign nulls to the record */
3788 exec_move_row(estate, rec, NULL, NULL, NULL);
3796 HeapTupleData tmptup;
3798 /* Source must be of RECORD or composite type */
3799 if (!type_is_rowtype(valtype))
3801 (errcode(ERRCODE_DATATYPE_MISMATCH),
3802 errmsg("cannot assign non-composite value to a record variable")));
3804 /* Source is a tuple Datum, so safe to do this: */
3805 td = DatumGetHeapTupleHeader(value);
3806 /* Extract rowtype info and find a tupdesc */
3807 tupType = HeapTupleHeaderGetTypeId(td);
3808 tupTypmod = HeapTupleHeaderGetTypMod(td);
3809 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3810 /* Build a temporary HeapTuple control structure */
3811 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3812 ItemPointerSetInvalid(&(tmptup.t_self));
3813 tmptup.t_tableOid = InvalidOid;
3815 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3816 ReleaseTupleDesc(tupdesc);
3821 case PLPGSQL_DTYPE_RECFIELD:
3824 * Target is a field of a record
3826 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3839 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3842 * Check that there is already a tuple in the record. We need
3843 * that because records don't have any predefined field
3846 if (!HeapTupleIsValid(rec->tup))
3848 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3849 errmsg("record \"%s\" is not assigned yet",
3851 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3854 * Get the number of the records field to change and the
3855 * number of attributes in the tuple. Note: disallow system
3856 * column names because the code below won't cope.
3858 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3861 (errcode(ERRCODE_UNDEFINED_COLUMN),
3862 errmsg("record \"%s\" has no field \"%s\"",
3863 rec->refname, recfield->fieldname)));
3865 natts = rec->tupdesc->natts;
3868 * Set up values/control arrays for heap_modify_tuple. For all
3869 * the attributes except the one we want to replace, use the
3870 * value that's in the old tuple.
3872 values = palloc(sizeof(Datum) * natts);
3873 nulls = palloc(sizeof(bool) * natts);
3874 replaces = palloc(sizeof(bool) * natts);
3876 memset(replaces, false, sizeof(bool) * natts);
3877 replaces[fno] = true;
3880 * Now insert the new value, being careful to cast it to the
3883 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3884 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3885 attisnull = *isNull;
3886 values[fno] = exec_simple_cast_value(value,
3891 nulls[fno] = attisnull;
3894 * Avoid leaking the result of exec_simple_cast_value, if it
3895 * performed a conversion to a pass-by-ref type.
3897 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3898 mustfree = DatumGetPointer(values[fno]);
3903 * Now call heap_modify_tuple() to create a new tuple that
3904 * replaces the old one in the record.
3906 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
3907 values, nulls, replaces);
3910 heap_freetuple(rec->tup);
3913 rec->freetup = true;
3924 case PLPGSQL_DTYPE_ARRAYELEM:
3927 * Target is an element of an array
3931 PLpgSQL_expr *subscripts[MAXDIM];
3932 int subscriptvals[MAXDIM];
3933 bool oldarrayisnull;
3941 Datum oldarraydatum,
3943 ArrayType *oldarrayval;
3944 ArrayType *newarrayval;
3945 SPITupleTable *save_eval_tuptable;
3948 * We need to do subscript evaluation, which might require
3949 * evaluating general expressions; and the caller might have
3950 * done that too in order to prepare the input Datum. We
3951 * have to save and restore the caller's SPI_execute result,
3954 save_eval_tuptable = estate->eval_tuptable;
3955 estate->eval_tuptable = NULL;
3958 * To handle constructs like x[1][2] := something, we have to
3959 * be prepared to deal with a chain of arrayelem datums. Chase
3960 * back to find the base array datum, and save the subscript
3961 * expressions as we go. (We are scanning right to left here,
3962 * but want to evaluate the subscripts left-to-right to
3963 * minimize surprises.)
3968 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3970 if (nsubscripts >= MAXDIM)
3972 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3973 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
3974 nsubscripts + 1, MAXDIM)));
3975 subscripts[nsubscripts++] = arrayelem->subscript;
3976 target = estate->datums[arrayelem->arrayparentno];
3977 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3979 /* Fetch current value of array datum */
3980 exec_eval_datum(estate, target,
3981 &arraytypeid, &arraytypmod,
3982 &oldarraydatum, &oldarrayisnull);
3984 /* If target is domain over array, reduce to base type */
3985 arraytypeid = getBaseTypeAndTypmod(arraytypeid, &arraytypmod);
3987 /* ... and identify the element type */
3988 arrayelemtypeid = get_element_type(arraytypeid);
3989 if (!OidIsValid(arrayelemtypeid))
3991 (errcode(ERRCODE_DATATYPE_MISMATCH),
3992 errmsg("subscripted object is not an array")));
3994 get_typlenbyvalalign(arrayelemtypeid,
3998 arraytyplen = get_typlen(arraytypeid);
4001 * Evaluate the subscripts, switch into left-to-right order.
4002 * Like ExecEvalArrayRef(), complain if any subscript is null.
4004 for (i = 0; i < nsubscripts; i++)
4009 exec_eval_integer(estate,
4010 subscripts[nsubscripts - 1 - i],
4014 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4015 errmsg("array subscript in assignment must not be null")));
4018 * Clean up in case the subscript expression wasn't simple.
4019 * We can't do exec_eval_cleanup, but we can do this much
4020 * (which is safe because the integer subscript value is
4021 * surely pass-by-value), and we must do it in case the
4022 * next subscript expression isn't simple either.
4024 if (estate->eval_tuptable != NULL)
4025 SPI_freetuptable(estate->eval_tuptable);
4026 estate->eval_tuptable = NULL;
4029 /* Now we can restore caller's SPI_execute result if any. */
4030 Assert(estate->eval_tuptable == NULL);
4031 estate->eval_tuptable = save_eval_tuptable;
4033 /* Coerce source value to match array element type. */
4034 coerced_value = exec_simple_cast_value(value,
4041 * If the original array is null, cons up an empty array so
4042 * that the assignment can proceed; we'll end with a
4043 * one-element array containing just the assigned-to
4044 * subscript. This only works for varlena arrays, though; for
4045 * fixed-length array types we skip the assignment. We can't
4046 * support assignment of a null entry into a fixed-length
4047 * array, either, so that's a no-op too. This is all ugly but
4048 * corresponds to the current behavior of ExecEvalArrayRef().
4050 if (arraytyplen > 0 && /* fixed-length array? */
4051 (oldarrayisnull || *isNull))
4055 oldarrayval = construct_empty_array(arrayelemtypeid);
4057 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
4060 * Build the modified array value.
4062 newarrayval = array_set(oldarrayval,
4073 * Avoid leaking the result of exec_simple_cast_value, if it
4074 * performed a conversion to a pass-by-ref type.
4076 if (!*isNull && coerced_value != value && !elemtypbyval)
4077 pfree(DatumGetPointer(coerced_value));
4080 * Assign the new array to the base variable. It's never NULL
4081 * at this point. Note that if the target is a domain,
4082 * coercing the base array type back up to the domain will
4083 * happen within exec_assign_value.
4086 exec_assign_value(estate, target,
4087 PointerGetDatum(newarrayval),
4088 arraytypeid, isNull);
4091 * Avoid leaking the modified array value, too.
4098 elog(ERROR, "unrecognized dtype: %d", target->dtype);
4103 * exec_eval_datum Get current value of a PLpgSQL_datum
4105 * The type oid, typmod, value in Datum format, and null flag are returned.
4107 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
4109 * NOTE: caller must not modify the returned value, since it points right
4110 * at the stored value in the case of pass-by-reference datatypes. In some
4111 * cases we have to palloc a return value, and in such cases we put it into
4112 * the estate's short-term memory context.
4115 exec_eval_datum(PLpgSQL_execstate *estate,
4116 PLpgSQL_datum *datum,
4122 MemoryContext oldcontext;
4124 switch (datum->dtype)
4126 case PLPGSQL_DTYPE_VAR:
4128 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4130 *typeid = var->datatype->typoid;
4131 *typetypmod = var->datatype->atttypmod;
4132 *value = var->value;
4133 *isnull = var->isnull;
4137 case PLPGSQL_DTYPE_ROW:
4139 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4142 if (!row->rowtupdesc) /* should not happen */
4143 elog(ERROR, "row variable has no tupdesc");
4144 /* Make sure we have a valid type/typmod setting */
4145 BlessTupleDesc(row->rowtupdesc);
4146 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4147 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
4148 if (tup == NULL) /* should not happen */
4149 elog(ERROR, "row not compatible with its own tupdesc");
4150 MemoryContextSwitchTo(oldcontext);
4151 *typeid = row->rowtupdesc->tdtypeid;
4152 *typetypmod = row->rowtupdesc->tdtypmod;
4153 *value = HeapTupleGetDatum(tup);
4158 case PLPGSQL_DTYPE_REC:
4160 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4161 HeapTupleData worktup;
4163 if (!HeapTupleIsValid(rec->tup))
4165 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4166 errmsg("record \"%s\" is not assigned yet",
4168 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4169 Assert(rec->tupdesc != NULL);
4170 /* Make sure we have a valid type/typmod setting */
4171 BlessTupleDesc(rec->tupdesc);
4174 * In a trigger, the NEW and OLD parameters are likely to be
4175 * on-disk tuples that don't have the desired Datum fields.
4176 * Copy the tuple body and insert the right values.
4178 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4179 heap_copytuple_with_tuple(rec->tup, &worktup);
4180 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
4181 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
4182 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
4183 MemoryContextSwitchTo(oldcontext);
4184 *typeid = rec->tupdesc->tdtypeid;
4185 *typetypmod = rec->tupdesc->tdtypmod;
4186 *value = HeapTupleGetDatum(&worktup);
4191 case PLPGSQL_DTYPE_RECFIELD:
4193 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4197 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4198 if (!HeapTupleIsValid(rec->tup))
4200 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4201 errmsg("record \"%s\" is not assigned yet",
4203 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4204 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4205 if (fno == SPI_ERROR_NOATTRIBUTE)
4207 (errcode(ERRCODE_UNDEFINED_COLUMN),
4208 errmsg("record \"%s\" has no field \"%s\"",
4209 rec->refname, recfield->fieldname)));
4210 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4211 /* XXX there's no SPI_gettypmod, for some reason */
4213 *typetypmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4216 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
4221 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4226 * exec_get_datum_type Get datatype of a PLpgSQL_datum
4228 * This is the same logic as in exec_eval_datum, except that it can handle
4229 * some cases where exec_eval_datum has to fail; specifically, we may have
4230 * a tupdesc but no row value for a record variable. (This currently can
4231 * happen only for a trigger's NEW/OLD records.)
4234 exec_get_datum_type(PLpgSQL_execstate *estate,
4235 PLpgSQL_datum *datum)
4239 switch (datum->dtype)
4241 case PLPGSQL_DTYPE_VAR:
4243 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4245 typeid = var->datatype->typoid;
4249 case PLPGSQL_DTYPE_ROW:
4251 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4253 if (!row->rowtupdesc) /* should not happen */
4254 elog(ERROR, "row variable has no tupdesc");
4255 /* Make sure we have a valid type/typmod setting */
4256 BlessTupleDesc(row->rowtupdesc);
4257 typeid = row->rowtupdesc->tdtypeid;
4261 case PLPGSQL_DTYPE_REC:
4263 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4265 if (rec->tupdesc == NULL)
4267 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4268 errmsg("record \"%s\" is not assigned yet",
4270 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4271 /* Make sure we have a valid type/typmod setting */
4272 BlessTupleDesc(rec->tupdesc);
4273 typeid = rec->tupdesc->tdtypeid;
4277 case PLPGSQL_DTYPE_RECFIELD:
4279 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4283 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4284 if (rec->tupdesc == NULL)
4286 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4287 errmsg("record \"%s\" is not assigned yet",
4289 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4290 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4291 if (fno == SPI_ERROR_NOATTRIBUTE)
4293 (errcode(ERRCODE_UNDEFINED_COLUMN),
4294 errmsg("record \"%s\" has no field \"%s\"",
4295 rec->refname, recfield->fieldname)));
4296 typeid = SPI_gettypeid(rec->tupdesc, fno);
4301 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4302 typeid = InvalidOid; /* keep compiler quiet */
4310 * exec_get_rec_fieldtype Get datatype of a PLpgSQL record field
4312 * Also returns the field number to *fieldno.
4315 exec_get_rec_fieldtype(PLpgSQL_rec *rec, const char *fieldname,
4321 if (rec->tupdesc == NULL)
4323 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4324 errmsg("record \"%s\" is not assigned yet",
4326 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4327 fno = SPI_fnumber(rec->tupdesc, fieldname);
4328 if (fno == SPI_ERROR_NOATTRIBUTE)
4330 (errcode(ERRCODE_UNDEFINED_COLUMN),
4331 errmsg("record \"%s\" has no field \"%s\"",
4332 rec->refname, fieldname)));
4333 typeid = SPI_gettypeid(rec->tupdesc, fno);
4340 * exec_eval_integer Evaluate an expression, coerce result to int4
4342 * Note we do not do exec_eval_cleanup here; the caller must do it at
4343 * some later point. (We do this because the caller may be holding the
4344 * results of other, pass-by-reference, expression evaluations, such as
4345 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
4346 * about allocation of the parameter array.)
4350 exec_eval_integer(PLpgSQL_execstate *estate,
4357 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4358 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4361 return DatumGetInt32(exprdatum);
4365 * exec_eval_boolean Evaluate an expression, coerce result to bool
4367 * Note we do not do exec_eval_cleanup here; the caller must do it at
4372 exec_eval_boolean(PLpgSQL_execstate *estate,
4379 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4380 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4383 return DatumGetBool(exprdatum);
4387 * exec_eval_expr Evaluate an expression and return
4390 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4394 exec_eval_expr(PLpgSQL_execstate *estate,
4403 * If first time through, create a plan for this expression.
4405 if (expr->plan == NULL)
4406 exec_prepare_plan(estate, expr, 0);
4409 * If this is a simple expression, bypass SPI and use the executor
4412 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4416 * Else do it the hard way via exec_run_select
4418 rc = exec_run_select(estate, expr, 2, NULL);
4419 if (rc != SPI_OK_SELECT)
4421 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4422 errmsg("query \"%s\" did not return data", expr->query)));
4425 * Check that the expression returns exactly one column...
4427 if (estate->eval_tuptable->tupdesc->natts != 1)
4429 (errcode(ERRCODE_SYNTAX_ERROR),
4430 errmsg_plural("query \"%s\" returned %d column",
4431 "query \"%s\" returned %d columns",
4432 estate->eval_tuptable->tupdesc->natts,
4434 estate->eval_tuptable->tupdesc->natts)));
4437 * ... and get the column's datatype.
4439 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4442 * If there are no rows selected, the result is a NULL of that type.
4444 if (estate->eval_processed == 0)
4451 * Check that the expression returned no more than one row.
4453 if (estate->eval_processed != 1)
4455 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4456 errmsg("query \"%s\" returned more than one row",
4460 * Return the single result Datum.
4462 return SPI_getbinval(estate->eval_tuptable->vals[0],
4463 estate->eval_tuptable->tupdesc, 1, isNull);
4468 * exec_run_select Execute a select query
4472 exec_run_select(PLpgSQL_execstate *estate,
4473 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4475 ParamListInfo paramLI;
4479 * On the first call for this expression generate the plan
4481 if (expr->plan == NULL)
4482 exec_prepare_plan(estate, expr, 0);
4485 * Set up ParamListInfo (note this is only carrying a hook function, not
4486 * any actual data values, at this point)
4488 paramLI = setup_param_list(estate, expr);
4491 * If a portal was requested, put the query into the portal
4493 if (portalP != NULL)
4495 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4497 estate->readonly_func);
4498 if (*portalP == NULL)
4499 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4500 expr->query, SPI_result_code_string(SPI_result));
4503 return SPI_OK_CURSOR;
4509 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4510 estate->readonly_func, maxtuples);
4511 if (rc != SPI_OK_SELECT)
4513 (errcode(ERRCODE_SYNTAX_ERROR),
4514 errmsg("query \"%s\" is not a SELECT", expr->query)));
4516 /* Save query results for eventual cleanup */
4517 Assert(estate->eval_tuptable == NULL);
4518 estate->eval_tuptable = SPI_tuptable;
4519 estate->eval_processed = SPI_processed;
4520 estate->eval_lastoid = SPI_lastoid;
4530 * exec_for_query --- execute body of FOR loop for each row from a portal
4532 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4535 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4536 Portal portal, bool prefetch_ok)
4538 PLpgSQL_rec *rec = NULL;
4539 PLpgSQL_row *row = NULL;
4540 SPITupleTable *tuptab;
4542 int rc = PLPGSQL_RC_OK;
4546 * Determine if we assign to a record or a row
4548 if (stmt->rec != NULL)
4549 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4550 else if (stmt->row != NULL)
4551 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4553 elog(ERROR, "unsupported target");
4556 * Make sure the portal doesn't get closed by the user statements we
4562 * Fetch the initial tuple(s). If prefetching is allowed then we grab a
4563 * few more rows to avoid multiple trips through executor startup
4566 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4567 tuptab = SPI_tuptable;
4571 * If the query didn't return any rows, set the target to NULL and fall
4572 * through with found = false.
4575 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4577 found = true; /* processed at least one tuple */
4586 for (i = 0; i < n; i++)
4589 * Assign the tuple to the target
4591 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4594 * Execute the statements
4596 rc = exec_stmts(estate, stmt->body);
4598 if (rc != PLPGSQL_RC_OK)
4600 if (rc == PLPGSQL_RC_EXIT)
4602 if (estate->exitlabel == NULL)
4604 /* unlabelled exit, so exit the current loop */
4607 else if (stmt->label != NULL &&
4608 strcmp(stmt->label, estate->exitlabel) == 0)
4610 /* label matches this loop, so exit loop */
4611 estate->exitlabel = NULL;
4616 * otherwise, we processed a labelled exit that does not
4617 * match the current statement's label, if any; return
4618 * RC_EXIT so that the EXIT continues to recurse upward.
4621 else if (rc == PLPGSQL_RC_CONTINUE)
4623 if (estate->exitlabel == NULL)
4625 /* unlabelled continue, so re-run the current loop */
4629 else if (stmt->label != NULL &&
4630 strcmp(stmt->label, estate->exitlabel) == 0)
4632 /* label matches this loop, so re-run loop */
4633 estate->exitlabel = NULL;
4639 * otherwise, we process a labelled continue that does not
4640 * match the current statement's label, if any; return
4641 * RC_CONTINUE so that the CONTINUE will propagate up the
4647 * We're aborting the loop. Need a goto to get out of two
4654 SPI_freetuptable(tuptab);
4657 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
4659 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
4660 tuptab = SPI_tuptable;
4667 * Release last group of tuples (if any)
4669 SPI_freetuptable(tuptab);
4671 UnpinPortal(portal);
4674 * Set the FOUND variable to indicate the result of executing the loop
4675 * (namely, whether we looped one or more times). This must be set last so
4676 * that it does not interfere with the value of the FOUND variable inside
4677 * the loop processing itself.
4679 exec_set_found(estate, found);
4686 * exec_eval_simple_expr - Evaluate a simple expression returning
4687 * a Datum by directly calling ExecEvalExpr().
4689 * If successful, store results into *result, *isNull, *rettype and return
4690 * TRUE. If the expression cannot be handled by simple evaluation,
4693 * Because we only store one execution tree for a simple expression, we
4694 * can't handle recursion cases. So, if we see the tree is already busy
4695 * with an evaluation in the current xact, we just return FALSE and let the
4696 * caller run the expression the hard way. (Other alternatives such as
4697 * creating a new tree for a recursive call either introduce memory leaks,
4698 * or add enough bookkeeping to be doubtful wins anyway.) Another case that
4699 * is covered by the expr_simple_in_use test is where a previous execution
4700 * of the tree was aborted by an error: the tree may contain bogus state
4701 * so we dare not re-use it.
4703 * It is possible though unlikely for a simple expression to become non-simple
4704 * (consider for example redefining a trivial view). We must handle that for
4705 * correctness; fortunately it's normally inexpensive to do
4706 * RevalidateCachedPlan on a simple expression. We do not consider the other
4707 * direction (non-simple expression becoming simple) because we'll still give
4708 * correct results if that happens, and it's unlikely to be worth the cycles
4711 * Note: if pass-by-reference, the result is in the eval_econtext's
4712 * temporary memory context. It will be freed when exec_eval_cleanup
4717 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4723 ExprContext *econtext = estate->eval_econtext;
4724 LocalTransactionId curlxid = MyProc->lxid;
4725 CachedPlanSource *plansource;
4727 ParamListInfo paramLI;
4728 PLpgSQL_expr *save_cur_expr;
4729 MemoryContext oldcontext;
4732 * Forget it if expression wasn't simple before.
4734 if (expr->expr_simple_expr == NULL)
4738 * If expression is in use in current xact, don't touch it.
4740 if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
4744 * Revalidate cached plan, so that we will notice if it became stale. (We
4745 * also need to hold a refcount while using the plan.) Note that even if
4746 * replanning occurs, the length of plancache_list can't change, since it
4747 * is a property of the raw parsetree generated from the query text.
4749 Assert(list_length(expr->plan->plancache_list) == 1);
4750 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4751 cplan = RevalidateCachedPlan(plansource, true);
4752 if (cplan->generation != expr->expr_simple_generation)
4754 /* It got replanned ... is it still simple? */
4755 exec_simple_check_plan(expr);
4756 if (expr->expr_simple_expr == NULL)
4758 /* Ooops, release refcount and fail */
4759 ReleaseCachedPlan(cplan, true);
4765 * Pass back previously-determined result type.
4767 *rettype = expr->expr_simple_type;
4770 * Prepare the expression for execution, if it's not been done already in
4771 * the current transaction. (This will be forced to happen if we called
4772 * exec_simple_check_plan above.)
4774 if (expr->expr_simple_lxid != curlxid)
4776 oldcontext = MemoryContextSwitchTo(simple_eval_estate->es_query_cxt);
4777 expr->expr_simple_state = ExecInitExpr(expr->expr_simple_expr, NULL);
4778 expr->expr_simple_in_use = false;
4779 expr->expr_simple_lxid = curlxid;
4780 MemoryContextSwitchTo(oldcontext);
4784 * We have to do some of the things SPI_execute_plan would do, in
4785 * particular advance the snapshot if we are in a non-read-only function.
4786 * Without this, stable functions within the expression would fail to see
4787 * updates made so far by our own function.
4791 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4792 if (!estate->readonly_func)
4794 CommandCounterIncrement();
4795 PushActiveSnapshot(GetTransactionSnapshot());
4799 * Create the param list in econtext's temporary memory context. We won't
4800 * need to free it explicitly, since it will go away at the next reset of
4803 * XXX think about avoiding repeated palloc's for param lists? It should
4804 * be possible --- this routine isn't re-entrant anymore.
4806 * Just for paranoia's sake, save and restore the prior value of
4807 * estate->cur_expr, which setup_param_list() sets.
4809 save_cur_expr = estate->cur_expr;
4811 paramLI = setup_param_list(estate, expr);
4812 econtext->ecxt_param_list_info = paramLI;
4815 * Mark expression as busy for the duration of the ExecEvalExpr call.
4817 expr->expr_simple_in_use = true;
4820 * Finally we can call the executor to evaluate the expression
4822 *result = ExecEvalExpr(expr->expr_simple_state,
4827 /* Assorted cleanup */
4828 expr->expr_simple_in_use = false;
4830 estate->cur_expr = save_cur_expr;
4832 if (!estate->readonly_func)
4833 PopActiveSnapshot();
4835 MemoryContextSwitchTo(oldcontext);
4840 * Now we can release our refcount on the cached plan.
4842 ReleaseCachedPlan(cplan, true);
4852 * Create a ParamListInfo to pass to SPI
4854 * The ParamListInfo array is initially all zeroes, in particular the
4855 * ptype values are all InvalidOid. This causes the executor to call the
4856 * paramFetch hook each time it wants a value. We thus evaluate only the
4857 * parameters actually demanded.
4859 * The result is a locally palloc'd array that should be pfree'd after use;
4860 * but note it can be NULL.
4862 static ParamListInfo
4863 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
4865 ParamListInfo paramLI;
4868 * Could we re-use these arrays instead of palloc'ing a new one each time?
4869 * However, we'd have to zero the array each time anyway, since new values
4870 * might have been assigned to the variables.
4872 if (estate->ndatums > 0)
4874 /* sizeof(ParamListInfoData) includes the first array element */
4875 paramLI = (ParamListInfo)
4876 palloc0(sizeof(ParamListInfoData) +
4877 (estate->ndatums - 1) *sizeof(ParamExternData));
4878 paramLI->paramFetch = plpgsql_param_fetch;
4879 paramLI->paramFetchArg = (void *) estate;
4880 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
4881 paramLI->parserSetupArg = (void *) expr;
4882 paramLI->numParams = estate->ndatums;
4885 * Set up link to active expr where the hook functions can find it.
4886 * Callers must save and restore cur_expr if there is any chance that
4887 * they are interrupting an active use of parameters.
4889 estate->cur_expr = expr;
4892 * Also make sure this is set before parser hooks need it. There is
4893 * no need to save and restore, since the value is always correct once
4896 expr->func = estate->func;
4904 * plpgsql_param_fetch paramFetch callback for dynamic parameter fetch
4907 plpgsql_param_fetch(ParamListInfo params, int paramid)
4910 PLpgSQL_execstate *estate;
4912 PLpgSQL_datum *datum;
4913 ParamExternData *prm;
4916 /* paramid's are 1-based, but dnos are 0-based */
4918 Assert(dno >= 0 && dno < params->numParams);
4920 /* fetch back the hook data */
4921 estate = (PLpgSQL_execstate *) params->paramFetchArg;
4922 expr = estate->cur_expr;
4923 Assert(params->numParams == estate->ndatums);
4926 * Do nothing if asked for a value that's not supposed to be used by this
4927 * SQL expression. This avoids unwanted evaluations when functions such
4928 * as copyParamList try to materialize all the values.
4930 if (!bms_is_member(dno, expr->paramnos))
4933 /* OK, evaluate the value and store into the appropriate paramlist slot */
4934 datum = estate->datums[dno];
4935 prm = ¶ms->params[dno];
4936 exec_eval_datum(estate, datum,
4937 &prm->ptype, &prmtypmod,
4938 &prm->value, &prm->isnull);
4943 * exec_move_row Move one tuple's values into a record or row
4947 exec_move_row(PLpgSQL_execstate *estate,
4950 HeapTuple tup, TupleDesc tupdesc)
4953 * Record is simple - just copy the tuple and its descriptor into the
4959 * Copy input first, just in case it is pointing at variable's value
4961 if (HeapTupleIsValid(tup))
4962 tup = heap_copytuple(tup);
4965 /* If we have a tupdesc but no data, form an all-nulls tuple */
4968 nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
4969 memset(nulls, true, tupdesc->natts * sizeof(bool));
4971 tup = heap_form_tuple(tupdesc, NULL, nulls);
4977 tupdesc = CreateTupleDescCopy(tupdesc);
4979 /* Free the old value ... */
4982 heap_freetuple(rec->tup);
4983 rec->freetup = false;
4985 if (rec->freetupdesc)
4987 FreeTupleDesc(rec->tupdesc);
4988 rec->freetupdesc = false;
4991 /* ... and install the new */
4992 if (HeapTupleIsValid(tup))
4995 rec->freetup = true;
5002 rec->tupdesc = tupdesc;
5003 rec->freetupdesc = true;
5006 rec->tupdesc = NULL;
5012 * Row is a bit more complicated in that we assign the individual
5013 * attributes of the tuple to the variables the row points to.
5015 * NOTE: this code used to demand row->nfields ==
5016 * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong. The tuple
5017 * might have more fields than we expected if it's from an
5018 * inheritance-child table of the current table, or it might have fewer if
5019 * the table has had columns added by ALTER TABLE. Ignore extra columns
5020 * and assume NULL for missing columns, the same as heap_getattr would do.
5021 * We also have to skip over dropped columns in either the source or
5024 * If we have no tuple data at all, we'll assign NULL to all columns of
5029 int td_natts = tupdesc ? tupdesc->natts : 0;
5034 if (HeapTupleIsValid(tup))
5035 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
5040 for (fnum = 0; fnum < row->nfields; fnum++)
5047 if (row->varnos[fnum] < 0)
5048 continue; /* skip dropped column in row struct */
5050 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
5052 while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
5053 anum++; /* skip dropped column in tuple */
5055 if (anum < td_natts)
5058 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
5064 valtype = SPI_gettypeid(tupdesc, anum + 1);
5073 * InvalidOid is OK because exec_assign_value doesn't care
5074 * about the type of a source NULL
5076 valtype = InvalidOid;
5079 exec_assign_value(estate, (PLpgSQL_datum *) var,
5080 value, valtype, &isnull);
5086 elog(ERROR, "unsupported target");
5090 * make_tuple_from_row Make a tuple from the values of a row object
5092 * A NULL return indicates rowtype mismatch; caller must raise suitable error
5096 make_tuple_from_row(PLpgSQL_execstate *estate,
5100 int natts = tupdesc->natts;
5106 if (natts != row->nfields)
5109 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
5110 nulls = (bool *) palloc(natts * sizeof(bool));
5112 for (i = 0; i < natts; i++)
5117 if (tupdesc->attrs[i]->attisdropped)
5119 nulls[i] = true; /* leave the column as null */
5122 if (row->varnos[i] < 0) /* should not happen */
5123 elog(ERROR, "dropped rowtype entry for non-dropped column");
5125 exec_eval_datum(estate, estate->datums[row->varnos[i]],
5126 &fieldtypeid, &fieldtypmod,
5127 &dvalues[i], &nulls[i]);
5128 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
5130 /* XXX should we insist on typmod match, too? */
5133 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
5142 * convert_value_to_string Convert a non-null Datum to C string
5144 * Note: callers generally assume that the result is a palloc'd string and
5145 * should be pfree'd. This is not all that safe an assumption ...
5147 * Note: not caching the conversion function lookup is bad for performance.
5151 convert_value_to_string(Datum value, Oid valtype)
5156 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
5157 return OidOutputFunctionCall(typoutput, value);
5161 * exec_cast_value Cast a value if required
5165 exec_cast_value(Datum value, Oid valtype,
5173 * If the type of the queries return value isn't that of the variable,
5176 if (valtype != reqtype || reqtypmod != -1)
5182 extval = convert_value_to_string(value, valtype);
5183 value = InputFunctionCall(reqinput, extval,
5184 reqtypioparam, reqtypmod);
5189 value = InputFunctionCall(reqinput, NULL,
5190 reqtypioparam, reqtypmod);
5198 * exec_simple_cast_value Cast a value if required
5200 * As above, but need not supply details about target type. Note that this
5201 * is slower than exec_cast_value with cached type info, and so should be
5202 * avoided in heavily used code paths.
5206 exec_simple_cast_value(Datum value, Oid valtype,
5207 Oid reqtype, int32 reqtypmod,
5210 if (valtype != reqtype || reqtypmod != -1)
5214 FmgrInfo finfo_input;
5216 getTypeInputInfo(reqtype, &typinput, &typioparam);
5218 fmgr_info(typinput, &finfo_input);
5220 value = exec_cast_value(value,
5234 * exec_simple_check_node - Recursively check if an expression
5235 * is made only of simple things we can
5236 * hand out directly to ExecEvalExpr()
5237 * instead of calling SPI.
5241 exec_simple_check_node(Node *node)
5246 switch (nodeTag(node))
5256 ArrayRef *expr = (ArrayRef *) node;
5258 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
5260 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
5262 if (!exec_simple_check_node((Node *) expr->refexpr))
5264 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
5272 FuncExpr *expr = (FuncExpr *) node;
5274 if (expr->funcretset)
5276 if (!exec_simple_check_node((Node *) expr->args))
5284 OpExpr *expr = (OpExpr *) node;
5288 if (!exec_simple_check_node((Node *) expr->args))
5294 case T_DistinctExpr:
5296 DistinctExpr *expr = (DistinctExpr *) node;
5300 if (!exec_simple_check_node((Node *) expr->args))
5306 case T_ScalarArrayOpExpr:
5308 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5310 if (!exec_simple_check_node((Node *) expr->args))
5318 BoolExpr *expr = (BoolExpr *) node;
5320 if (!exec_simple_check_node((Node *) expr->args))
5327 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
5331 FieldStore *expr = (FieldStore *) node;
5333 if (!exec_simple_check_node((Node *) expr->arg))
5335 if (!exec_simple_check_node((Node *) expr->newvals))
5342 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
5345 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
5347 case T_ArrayCoerceExpr:
5348 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
5350 case T_ConvertRowtypeExpr:
5351 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
5354 return exec_simple_check_node((Node *) ((CollateExpr *) node)->arg);
5358 CaseExpr *expr = (CaseExpr *) node;
5360 if (!exec_simple_check_node((Node *) expr->arg))
5362 if (!exec_simple_check_node((Node *) expr->args))
5364 if (!exec_simple_check_node((Node *) expr->defresult))
5372 CaseWhen *when = (CaseWhen *) node;
5374 if (!exec_simple_check_node((Node *) when->expr))
5376 if (!exec_simple_check_node((Node *) when->result))
5382 case T_CaseTestExpr:
5387 ArrayExpr *expr = (ArrayExpr *) node;
5389 if (!exec_simple_check_node((Node *) expr->elements))
5397 RowExpr *expr = (RowExpr *) node;
5399 if (!exec_simple_check_node((Node *) expr->args))
5405 case T_RowCompareExpr:
5407 RowCompareExpr *expr = (RowCompareExpr *) node;
5409 if (!exec_simple_check_node((Node *) expr->largs))
5411 if (!exec_simple_check_node((Node *) expr->rargs))
5417 case T_CoalesceExpr:
5419 CoalesceExpr *expr = (CoalesceExpr *) node;
5421 if (!exec_simple_check_node((Node *) expr->args))
5429 MinMaxExpr *expr = (MinMaxExpr *) node;
5431 if (!exec_simple_check_node((Node *) expr->args))
5439 XmlExpr *expr = (XmlExpr *) node;
5441 if (!exec_simple_check_node((Node *) expr->named_args))
5443 if (!exec_simple_check_node((Node *) expr->args))
5451 NullIfExpr *expr = (NullIfExpr *) node;
5455 if (!exec_simple_check_node((Node *) expr->args))
5462 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5465 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5467 case T_CoerceToDomain:
5468 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5470 case T_CoerceToDomainValue:
5475 List *expr = (List *) node;
5480 if (!exec_simple_check_node(lfirst(l)))
5494 * exec_simple_check_plan - Check if a plan is simple enough to
5495 * be evaluated by ExecEvalExpr() instead
5500 exec_simple_check_plan(PLpgSQL_expr *expr)
5502 CachedPlanSource *plansource;
5508 * Initialize to "not simple", and remember the plan generation number we
5509 * last checked. (If the query produces more or less than one parsetree
5510 * we just leave expr_simple_generation set to 0.)
5512 expr->expr_simple_expr = NULL;
5513 expr->expr_simple_generation = 0;
5516 * 1. We can only evaluate queries that resulted in one single execution
5519 if (list_length(expr->plan->plancache_list) != 1)
5521 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
5522 expr->expr_simple_generation = plansource->generation;
5523 if (list_length(plansource->plan->stmt_list) != 1)
5526 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
5529 * 2. It must be a RESULT plan --> no scan's required
5531 if (!IsA(stmt, PlannedStmt))
5533 if (stmt->commandType != CMD_SELECT || stmt->intoClause)
5535 plan = stmt->planTree;
5536 if (!IsA(plan, Result))
5540 * 3. Can't have any subplan or qual clause, either
5542 if (plan->lefttree != NULL ||
5543 plan->righttree != NULL ||
5544 plan->initPlan != NULL ||
5545 plan->qual != NULL ||
5546 ((Result *) plan)->resconstantqual != NULL)
5550 * 4. The plan must have a single attribute as result
5552 if (list_length(plan->targetlist) != 1)
5555 tle = (TargetEntry *) linitial(plan->targetlist);
5558 * 5. Check that all the nodes in the expression are non-scary.
5560 if (!exec_simple_check_node((Node *) tle->expr))
5564 * Yes - this is a simple expression. Mark it as such, and initialize
5565 * state to "not valid in current transaction".
5567 expr->expr_simple_expr = tle->expr;
5568 expr->expr_simple_state = NULL;
5569 expr->expr_simple_in_use = false;
5570 expr->expr_simple_lxid = InvalidLocalTransactionId;
5571 /* Also stash away the expression result type */
5572 expr->expr_simple_type = exprType((Node *) tle->expr);
5576 * exec_set_found Set the global found variable
5581 exec_set_found(PLpgSQL_execstate *estate, bool state)
5585 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
5586 var->value = PointerGetDatum(state);
5587 var->isnull = false;
5591 * plpgsql_create_econtext --- create an eval_econtext for the current function
5593 * We may need to create a new simple_eval_estate too, if there's not one
5594 * already for the current transaction. The EState will be cleaned up at
5598 plpgsql_create_econtext(PLpgSQL_execstate *estate)
5600 SimpleEcontextStackEntry *entry;
5603 * Create an EState for evaluation of simple expressions, if there's not
5604 * one already in the current transaction. The EState is made a child of
5605 * TopTransactionContext so it will have the right lifespan.
5607 if (simple_eval_estate == NULL)
5609 MemoryContext oldcontext;
5611 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
5612 simple_eval_estate = CreateExecutorState();
5613 MemoryContextSwitchTo(oldcontext);
5617 * Create a child econtext for the current function.
5619 estate->eval_econtext = CreateExprContext(simple_eval_estate);
5622 * Make a stack entry so we can clean up the econtext at subxact end.
5623 * Stack entries are kept in TopTransactionContext for simplicity.
5625 entry = (SimpleEcontextStackEntry *)
5626 MemoryContextAlloc(TopTransactionContext,
5627 sizeof(SimpleEcontextStackEntry));
5629 entry->stack_econtext = estate->eval_econtext;
5630 entry->xact_subxid = GetCurrentSubTransactionId();
5632 entry->next = simple_econtext_stack;
5633 simple_econtext_stack = entry;
5637 * plpgsql_destroy_econtext --- destroy function's econtext
5639 * We check that it matches the top stack entry, and destroy the stack
5640 * entry along with the context.
5643 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
5645 SimpleEcontextStackEntry *next;
5647 Assert(simple_econtext_stack != NULL);
5648 Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
5650 next = simple_econtext_stack->next;
5651 pfree(simple_econtext_stack);
5652 simple_econtext_stack = next;
5654 FreeExprContext(estate->eval_econtext, true);
5655 estate->eval_econtext = NULL;
5659 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5661 * If a simple-expression EState was created in the current transaction,
5662 * it has to be cleaned up.
5665 plpgsql_xact_cb(XactEvent event, void *arg)
5668 * If we are doing a clean transaction shutdown, free the EState (so that
5669 * any remaining resources will be released correctly). In an abort, we
5670 * expect the regular abort recovery procedures to release everything of
5673 if (event != XACT_EVENT_ABORT)
5675 /* Shouldn't be any econtext stack entries left at commit */
5676 Assert(simple_econtext_stack == NULL);
5678 if (simple_eval_estate)
5679 FreeExecutorState(simple_eval_estate);
5680 simple_eval_estate = NULL;
5684 simple_econtext_stack = NULL;
5685 simple_eval_estate = NULL;
5690 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5692 * Make sure any simple-expression econtexts created in the current
5693 * subtransaction get cleaned up. We have to do this explicitly because
5694 * no other code knows which child econtexts of simple_eval_estate belong
5695 * to which level of subxact.
5698 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5699 SubTransactionId parentSubid, void *arg)
5701 if (event == SUBXACT_EVENT_START_SUB)
5704 while (simple_econtext_stack != NULL &&
5705 simple_econtext_stack->xact_subxid == mySubid)
5707 SimpleEcontextStackEntry *next;
5709 FreeExprContext(simple_econtext_stack->stack_econtext,
5710 (event == SUBXACT_EVENT_COMMIT_SUB));
5711 next = simple_econtext_stack->next;
5712 pfree(simple_econtext_stack);
5713 simple_econtext_stack = next;
5718 * free_var --- pfree any pass-by-reference value of the variable.
5720 * This should always be followed by some assignment to var->value,
5721 * as it leaves a dangling pointer.
5724 free_var(PLpgSQL_var *var)
5728 pfree(DatumGetPointer(var->value));
5729 var->freeval = false;
5734 * free old value of a text variable and assign new value from C string
5737 assign_text_var(PLpgSQL_var *var, const char *str)
5740 var->value = CStringGetTextDatum(str);
5741 var->isnull = false;
5742 var->freeval = true;
5746 * exec_eval_using_params --- evaluate params of USING clause
5748 static PreparedParamsData *
5749 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
5751 PreparedParamsData *ppd;
5756 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
5757 nargs = list_length(params);
5760 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
5761 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
5762 ppd->nulls = (char *) palloc(nargs * sizeof(char));
5763 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
5768 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
5771 ppd->values[i] = exec_eval_expr(estate, param,
5774 ppd->nulls[i] = isnull ? 'n' : ' ';
5775 ppd->freevals[i] = false;
5777 if (ppd->types[i] == UNKNOWNOID)
5780 * Treat 'unknown' parameters as text, since that's what most
5781 * people would expect. SPI_execute_with_args can coerce unknown
5782 * constants in a more intelligent way, but not unknown Params.
5783 * This code also takes care of copying into the right context.
5784 * Note we assume 'unknown' has the representation of C-string.
5786 ppd->types[i] = TEXTOID;
5789 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
5790 ppd->freevals[i] = true;
5793 /* pass-by-ref non null values must be copied into plpgsql context */
5799 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
5802 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
5803 ppd->freevals[i] = true;
5807 exec_eval_cleanup(estate);
5816 * free_params_data --- pfree all pass-by-reference values used in USING clause
5819 free_params_data(PreparedParamsData *ppd)
5823 for (i = 0; i < ppd->nargs; i++)
5825 if (ppd->freevals[i])
5826 pfree(DatumGetPointer(ppd->values[i]));
5832 pfree(ppd->freevals);
5838 * Open portal for dynamic query
5841 exec_dynquery_with_params(PLpgSQL_execstate *estate,
5842 PLpgSQL_expr *dynquery,
5844 const char *portalname,
5854 * Evaluate the string expression after the EXECUTE keyword. Its result is
5855 * the querystring we have to execute.
5857 query = exec_eval_expr(estate, dynquery, &isnull, &restype);
5860 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5861 errmsg("query string argument of EXECUTE is null")));
5863 /* Get the C-String representation */
5864 querystr = convert_value_to_string(query, restype);
5866 exec_eval_cleanup(estate);
5869 * Open an implicit cursor for the query. We use
5870 * SPI_cursor_open_with_args even when there are no params, because this
5871 * avoids making and freeing one copy of the plan.
5875 PreparedParamsData *ppd;
5877 ppd = exec_eval_using_params(estate, params);
5878 portal = SPI_cursor_open_with_args(portalname,
5880 ppd->nargs, ppd->types,
5881 ppd->values, ppd->nulls,
5882 estate->readonly_func,
5884 free_params_data(ppd);
5888 portal = SPI_cursor_open_with_args(portalname,
5892 estate->readonly_func,
5897 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5898 querystr, SPI_result_code_string(SPI_result));