1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.218 2008/08/29 13:02:33 petere Exp $
13 *-------------------------------------------------------------------------
20 #include "access/transam.h"
21 #include "catalog/pg_proc.h"
22 #include "catalog/pg_type.h"
23 #include "executor/spi_priv.h"
25 #include "nodes/nodeFuncs.h"
26 #include "parser/scansup.h"
27 #include "tcop/tcopprot.h"
28 #include "utils/array.h"
29 #include "utils/builtins.h"
30 #include "utils/lsyscache.h"
31 #include "utils/memutils.h"
32 #include "utils/snapmgr.h"
33 #include "utils/typcache.h"
36 static const char *const raise_skip_msg = "RAISE";
40 int nargs; /* number of arguments */
41 Oid *types; /* types of arguments */
42 Datum *values; /* evaluated argument values */
43 char *nulls; /* null markers (' '/'n' style) */
44 bool *freevals; /* which arguments are pfree-able */
48 * All plpgsql function executions within a single transaction share the same
49 * executor EState for evaluating "simple" expressions. Each function call
50 * creates its own "eval_econtext" ExprContext within this estate for
51 * per-evaluation workspace. eval_econtext is freed at normal function exit,
52 * and the EState is freed at transaction end (in case of error, we assume
53 * that the abort mechanisms clean it all up). In order to be sure
54 * ExprContext callbacks are handled properly, each subtransaction has to have
55 * its own such EState; hence we need a stack. We use a simple counter to
56 * distinguish different instantiations of the EState, so that we can tell
57 * whether we have a current copy of a prepared expression.
59 * This arrangement is a bit tedious to maintain, but it's worth the trouble
60 * so that we don't have to re-prepare simple expressions on each trip through
61 * a function. (We assume the case to optimize is many repetitions of a
62 * function within a transaction.)
64 typedef struct SimpleEstateStackEntry
66 EState *xact_eval_estate; /* EState for current xact level */
67 long int xact_estate_simple_id; /* ID for xact_eval_estate */
68 SubTransactionId xact_subxid; /* ID for current subxact */
69 struct SimpleEstateStackEntry *next; /* next stack entry up */
70 } SimpleEstateStackEntry;
72 static SimpleEstateStackEntry *simple_estate_stack = NULL;
73 static long int simple_estate_id_counter = 0;
75 /************************************************************
76 * Local function forward declarations
77 ************************************************************/
78 static void plpgsql_exec_error_callback(void *arg);
79 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
81 static int exec_stmt_block(PLpgSQL_execstate *estate,
82 PLpgSQL_stmt_block *block);
83 static int exec_stmts(PLpgSQL_execstate *estate,
85 static int exec_stmt(PLpgSQL_execstate *estate,
87 static int exec_stmt_assign(PLpgSQL_execstate *estate,
88 PLpgSQL_stmt_assign *stmt);
89 static int exec_stmt_perform(PLpgSQL_execstate *estate,
90 PLpgSQL_stmt_perform *stmt);
91 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
92 PLpgSQL_stmt_getdiag *stmt);
93 static int exec_stmt_if(PLpgSQL_execstate *estate,
94 PLpgSQL_stmt_if *stmt);
95 static int exec_stmt_case(PLpgSQL_execstate *estate,
96 PLpgSQL_stmt_case *stmt);
97 static int exec_stmt_loop(PLpgSQL_execstate *estate,
98 PLpgSQL_stmt_loop *stmt);
99 static int exec_stmt_while(PLpgSQL_execstate *estate,
100 PLpgSQL_stmt_while *stmt);
101 static int exec_stmt_fori(PLpgSQL_execstate *estate,
102 PLpgSQL_stmt_fori *stmt);
103 static int exec_stmt_fors(PLpgSQL_execstate *estate,
104 PLpgSQL_stmt_fors *stmt);
105 static int exec_stmt_forc(PLpgSQL_execstate *estate,
106 PLpgSQL_stmt_forc *stmt);
107 static int exec_stmt_open(PLpgSQL_execstate *estate,
108 PLpgSQL_stmt_open *stmt);
109 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
110 PLpgSQL_stmt_fetch *stmt);
111 static int exec_stmt_close(PLpgSQL_execstate *estate,
112 PLpgSQL_stmt_close *stmt);
113 static int exec_stmt_exit(PLpgSQL_execstate *estate,
114 PLpgSQL_stmt_exit *stmt);
115 static int exec_stmt_return(PLpgSQL_execstate *estate,
116 PLpgSQL_stmt_return *stmt);
117 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
118 PLpgSQL_stmt_return_next *stmt);
119 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
120 PLpgSQL_stmt_return_query *stmt);
121 static int exec_stmt_raise(PLpgSQL_execstate *estate,
122 PLpgSQL_stmt_raise *stmt);
123 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
124 PLpgSQL_stmt_execsql *stmt);
125 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
126 PLpgSQL_stmt_dynexecute *stmt);
127 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
128 PLpgSQL_stmt_dynfors *stmt);
130 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
131 PLpgSQL_function *func,
133 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
135 static void exec_prepare_plan(PLpgSQL_execstate *estate,
136 PLpgSQL_expr *expr, int cursorOptions);
137 static bool exec_simple_check_node(Node *node);
138 static void exec_simple_check_plan(PLpgSQL_expr *expr);
139 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
145 static void exec_assign_expr(PLpgSQL_execstate *estate,
146 PLpgSQL_datum *target,
148 static void exec_assign_value(PLpgSQL_execstate *estate,
149 PLpgSQL_datum *target,
150 Datum value, Oid valtype, bool *isNull);
151 static void exec_eval_datum(PLpgSQL_execstate *estate,
152 PLpgSQL_datum *datum,
157 static int exec_eval_integer(PLpgSQL_execstate *estate,
160 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
163 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
167 static int exec_run_select(PLpgSQL_execstate *estate,
168 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
169 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
170 Portal portal, bool prefetch_ok);
171 static void eval_expr_params(PLpgSQL_execstate *estate,
172 PLpgSQL_expr *expr, Datum **p_values, char **p_nulls);
173 static void exec_move_row(PLpgSQL_execstate *estate,
176 HeapTuple tup, TupleDesc tupdesc);
177 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
180 static char *convert_value_to_string(Datum value, Oid valtype);
181 static Datum exec_cast_value(Datum value, Oid valtype,
187 static Datum exec_simple_cast_value(Datum value, Oid valtype,
188 Oid reqtype, int32 reqtypmod,
190 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
191 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
192 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
193 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
194 static void free_var(PLpgSQL_var *var);
195 static void assign_text_var(PLpgSQL_var *var, const char *str);
196 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
198 static void free_params_data(PreparedParamsData *ppd);
199 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
200 PLpgSQL_expr *query, List *params);
204 * plpgsql_exec_function Called by the call handler for
205 * function execution.
209 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
211 PLpgSQL_execstate estate;
212 ErrorContextCallback plerrcontext;
217 * Setup the execution state
219 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
222 * Setup error traceback support for ereport()
224 plerrcontext.callback = plpgsql_exec_error_callback;
225 plerrcontext.arg = &estate;
226 plerrcontext.previous = error_context_stack;
227 error_context_stack = &plerrcontext;
230 * Make local execution copies of all the datums
232 estate.err_text = gettext_noop("during initialization of execution state");
233 for (i = 0; i < estate.ndatums; i++)
234 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
237 * Store the actual call argument values into the appropriate variables
239 estate.err_text = gettext_noop("while storing call arguments into local variables");
240 for (i = 0; i < func->fn_nargs; i++)
242 int n = func->fn_argvarnos[i];
244 switch (estate.datums[n]->dtype)
246 case PLPGSQL_DTYPE_VAR:
248 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
250 var->value = fcinfo->arg[i];
251 var->isnull = fcinfo->argnull[i];
252 var->freeval = false;
256 case PLPGSQL_DTYPE_ROW:
258 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
260 if (!fcinfo->argnull[i])
266 HeapTupleData tmptup;
268 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
269 /* Extract rowtype info and find a tupdesc */
270 tupType = HeapTupleHeaderGetTypeId(td);
271 tupTypmod = HeapTupleHeaderGetTypMod(td);
272 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
273 /* Build a temporary HeapTuple control structure */
274 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
275 ItemPointerSetInvalid(&(tmptup.t_self));
276 tmptup.t_tableOid = InvalidOid;
278 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
279 ReleaseTupleDesc(tupdesc);
283 /* If arg is null, treat it as an empty row */
284 exec_move_row(&estate, NULL, row, NULL, NULL);
290 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
294 estate.err_text = gettext_noop("during function entry");
297 * Set the magic variable FOUND to false
299 exec_set_found(&estate, false);
302 * Let the instrumentation plugin peek at this function
304 if (*plugin_ptr && (*plugin_ptr)->func_beg)
305 ((*plugin_ptr)->func_beg) (&estate, func);
308 * Now call the toplevel block of statements
310 estate.err_text = NULL;
311 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
312 rc = exec_stmt_block(&estate, func->action);
313 if (rc != PLPGSQL_RC_RETURN)
315 estate.err_stmt = NULL;
316 estate.err_text = NULL;
319 * Provide a more helpful message if a CONTINUE or RAISE has been used
320 * outside the context it can work in.
322 if (rc == PLPGSQL_RC_CONTINUE)
324 (errcode(ERRCODE_SYNTAX_ERROR),
325 errmsg("CONTINUE cannot be used outside a loop")));
326 else if (rc == PLPGSQL_RC_RERAISE)
328 (errcode(ERRCODE_SYNTAX_ERROR),
329 errmsg("RAISE without parameters cannot be used outside an exception handler")));
332 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
333 errmsg("control reached end of function without RETURN")));
337 * We got a return value - process it
339 estate.err_stmt = NULL;
340 estate.err_text = gettext_noop("while casting return value to function's return type");
342 fcinfo->isnull = estate.retisnull;
346 ReturnSetInfo *rsi = estate.rsi;
348 /* Check caller can handle a set result */
349 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
350 (rsi->allowedModes & SFRM_Materialize) == 0)
352 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
353 errmsg("set-valued function called in context that cannot accept a set")));
354 rsi->returnMode = SFRM_Materialize;
356 /* If we produced any tuples, send back the result */
357 if (estate.tuple_store)
359 rsi->setResult = estate.tuple_store;
360 if (estate.rettupdesc)
362 MemoryContext oldcxt;
364 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
365 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
366 MemoryContextSwitchTo(oldcxt);
369 estate.retval = (Datum) 0;
370 fcinfo->isnull = true;
372 else if (!estate.retisnull)
374 if (estate.retistuple)
377 * We have to check that the returned tuple actually matches the
378 * expected result type. XXX would be better to cache the tupdesc
379 * instead of repeating get_call_result_type()
383 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
385 case TYPEFUNC_COMPOSITE:
386 /* got the expected result rowtype, now check it */
387 if (estate.rettupdesc == NULL ||
388 !compatible_tupdesc(estate.rettupdesc, tupdesc))
390 (errcode(ERRCODE_DATATYPE_MISMATCH),
391 errmsg("returned record type does not match expected record type")));
393 case TYPEFUNC_RECORD:
396 * Failed to determine actual type of RECORD. We could
397 * raise an error here, but what this means in practice is
398 * that the caller is expecting any old generic rowtype,
399 * so we don't really need to be restrictive. Pass back
400 * the generated result type, instead.
402 tupdesc = estate.rettupdesc;
403 if (tupdesc == NULL) /* shouldn't happen */
404 elog(ERROR, "return type must be a row type");
407 /* shouldn't get here if retistuple is true ... */
408 elog(ERROR, "return type must be a row type");
413 * Copy tuple to upper executor memory, as a tuple Datum. Make
414 * sure it is labeled with the caller-supplied tuple type.
417 PointerGetDatum(SPI_returntuple((HeapTuple)DatumGetPointer(estate.retval),
422 /* Cast value to proper type */
423 estate.retval = exec_cast_value(estate.retval, estate.rettype,
425 &(func->fn_retinput),
426 func->fn_rettypioparam,
431 * If the function's return type isn't by value, copy the value
432 * into upper executor memory context.
434 if (!fcinfo->isnull && !func->fn_retbyval)
439 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
440 tmp = SPI_palloc(len);
441 memcpy(tmp, DatumGetPointer(estate.retval), len);
442 estate.retval = PointerGetDatum(tmp);
447 estate.err_text = gettext_noop("during function exit");
450 * Let the instrumentation plugin peek at this function
452 if (*plugin_ptr && (*plugin_ptr)->func_end)
453 ((*plugin_ptr)->func_end) (&estate, func);
455 /* Clean up any leftover temporary memory */
456 FreeExprContext(estate.eval_econtext);
457 estate.eval_econtext = NULL;
458 exec_eval_cleanup(&estate);
461 * Pop the error context stack
463 error_context_stack = plerrcontext.previous;
466 * Return the function's result
468 return estate.retval;
473 * plpgsql_exec_trigger Called by the call handler for
478 plpgsql_exec_trigger(PLpgSQL_function *func,
479 TriggerData *trigdata)
481 PLpgSQL_execstate estate;
482 ErrorContextCallback plerrcontext;
486 PLpgSQL_rec *rec_new,
491 * Setup the execution state
493 plpgsql_estate_setup(&estate, func, NULL);
496 * Setup error traceback support for ereport()
498 plerrcontext.callback = plpgsql_exec_error_callback;
499 plerrcontext.arg = &estate;
500 plerrcontext.previous = error_context_stack;
501 error_context_stack = &plerrcontext;
504 * Make local execution copies of all the datums
506 estate.err_text = gettext_noop("during initialization of execution state");
507 for (i = 0; i < estate.ndatums; i++)
508 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
511 * Put the OLD and NEW tuples into record variables
513 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
514 rec_new->freetup = false;
515 rec_new->freetupdesc = false;
516 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
517 rec_old->freetup = false;
518 rec_old->freetupdesc = false;
520 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
523 * Per-statement triggers don't use OLD/NEW variables
526 rec_new->tupdesc = NULL;
528 rec_old->tupdesc = NULL;
530 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
532 rec_new->tup = trigdata->tg_trigtuple;
533 rec_new->tupdesc = trigdata->tg_relation->rd_att;
535 rec_old->tupdesc = NULL;
537 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
539 rec_new->tup = trigdata->tg_newtuple;
540 rec_new->tupdesc = trigdata->tg_relation->rd_att;
541 rec_old->tup = trigdata->tg_trigtuple;
542 rec_old->tupdesc = trigdata->tg_relation->rd_att;
544 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
547 rec_new->tupdesc = NULL;
548 rec_old->tup = trigdata->tg_trigtuple;
549 rec_old->tupdesc = trigdata->tg_relation->rd_att;
552 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
555 * Assign the special tg_ variables
558 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
559 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
560 var->value = CStringGetTextDatum("INSERT");
561 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
562 var->value = CStringGetTextDatum("UPDATE");
563 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
564 var->value = CStringGetTextDatum("DELETE");
565 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
566 var->value = CStringGetTextDatum("TRUNCATE");
568 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
572 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
573 var->value = DirectFunctionCall1(namein,
574 CStringGetDatum(trigdata->tg_trigger->tgname));
578 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
579 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
580 var->value = CStringGetTextDatum("BEFORE");
581 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
582 var->value = CStringGetTextDatum("AFTER");
584 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
588 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
589 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
590 var->value = CStringGetTextDatum("ROW");
591 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
592 var->value = CStringGetTextDatum("STATEMENT");
594 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
598 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
599 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
601 var->freeval = false;
603 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
604 var->value = DirectFunctionCall1(namein,
605 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
609 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
610 var->value = DirectFunctionCall1(namein,
611 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
615 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
616 var->value = DirectFunctionCall1(namein,
619 RelationGetNamespace(
620 trigdata->tg_relation))));
624 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
625 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
627 var->freeval = false;
630 * Store the trigger argument values into the special execution state
633 estate.err_text = gettext_noop("while storing call arguments into local variables");
634 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
635 if (estate.trig_nargs == 0)
636 estate.trig_argv = NULL;
639 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
640 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
641 estate.trig_argv[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
644 estate.err_text = gettext_noop("during function entry");
647 * Set the magic variable FOUND to false
649 exec_set_found(&estate, false);
652 * Let the instrumentation plugin peek at this function
654 if (*plugin_ptr && (*plugin_ptr)->func_beg)
655 ((*plugin_ptr)->func_beg) (&estate, func);
658 * Now call the toplevel block of statements
660 estate.err_text = NULL;
661 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
662 rc = exec_stmt_block(&estate, func->action);
663 if (rc != PLPGSQL_RC_RETURN)
665 estate.err_stmt = NULL;
666 estate.err_text = NULL;
669 * Provide a more helpful message if a CONTINUE or RAISE has been used
670 * outside the context it can work in.
672 if (rc == PLPGSQL_RC_CONTINUE)
674 (errcode(ERRCODE_SYNTAX_ERROR),
675 errmsg("CONTINUE cannot be used outside a loop")));
676 else if (rc == PLPGSQL_RC_RERAISE)
678 (errcode(ERRCODE_SYNTAX_ERROR),
679 errmsg("RAISE without parameters cannot be used outside an exception handler")));
682 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
683 errmsg("control reached end of trigger procedure without RETURN")));
686 estate.err_stmt = NULL;
687 estate.err_text = gettext_noop("during function exit");
691 (errcode(ERRCODE_DATATYPE_MISMATCH),
692 errmsg("trigger procedure cannot return a set")));
695 * Check that the returned tuple structure has the same attributes, the
696 * relation that fired the trigger has. A per-statement trigger always
697 * needs to return NULL, so we ignore any return value the function itself
698 * produces (XXX: is this a good idea?)
700 * XXX This way it is possible, that the trigger returns a tuple where
701 * attributes don't have the correct atttypmod's length. It's up to the
702 * trigger's programmer to ensure that this doesn't happen. Jan
704 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
708 if (!compatible_tupdesc(estate.rettupdesc,
709 trigdata->tg_relation->rd_att))
711 (errcode(ERRCODE_DATATYPE_MISMATCH),
712 errmsg("returned tuple structure does not match table of trigger event")));
713 /* Copy tuple to upper executor memory */
714 rettup = SPI_copytuple((HeapTuple) DatumGetPointer(estate.retval));
718 * Let the instrumentation plugin peek at this function
720 if (*plugin_ptr && (*plugin_ptr)->func_end)
721 ((*plugin_ptr)->func_end) (&estate, func);
723 /* Clean up any leftover temporary memory */
724 FreeExprContext(estate.eval_econtext);
725 estate.eval_econtext = NULL;
726 exec_eval_cleanup(&estate);
729 * Pop the error context stack
731 error_context_stack = plerrcontext.previous;
734 * Return the trigger's result
741 * error context callback to let us supply a call-stack traceback
744 plpgsql_exec_error_callback(void *arg)
746 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
748 /* safety check, shouldn't happen */
749 if (estate->err_func == NULL)
752 /* if we are doing RAISE, don't report its location */
753 if (estate->err_text == raise_skip_msg)
756 if (estate->err_text != NULL)
759 * We don't expend the cycles to run gettext() on err_text unless we
760 * actually need it. Therefore, places that set up err_text should
761 * use gettext_noop() to ensure the strings get recorded in the
762 * message dictionary.
764 * If both err_text and err_stmt are set, use the err_text as
765 * description, but report the err_stmt's line number. When err_stmt
766 * is not set, we're in function entry/exit, or some such place not
767 * attached to a specific line number.
769 if (estate->err_stmt != NULL)
772 * translator: last %s is a phrase such as "during statement block
773 * local variable initialization"
775 errcontext("PL/pgSQL function \"%s\" line %d %s",
776 estate->err_func->fn_name,
777 estate->err_stmt->lineno,
778 gettext(estate->err_text));
783 * translator: last %s is a phrase such as "while storing call
784 * arguments into local variables"
786 errcontext("PL/pgSQL function \"%s\" %s",
787 estate->err_func->fn_name,
788 gettext(estate->err_text));
791 else if (estate->err_stmt != NULL)
793 /* translator: last %s is a plpgsql statement type name */
794 errcontext("PL/pgSQL function \"%s\" line %d at %s",
795 estate->err_func->fn_name,
796 estate->err_stmt->lineno,
797 plpgsql_stmt_typename(estate->err_stmt));
800 errcontext("PL/pgSQL function \"%s\"",
801 estate->err_func->fn_name);
806 * Support function for initializing local execution variables
809 static PLpgSQL_datum *
810 copy_plpgsql_datum(PLpgSQL_datum *datum)
812 PLpgSQL_datum *result;
814 switch (datum->dtype)
816 case PLPGSQL_DTYPE_VAR:
818 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
820 memcpy(new, datum, sizeof(PLpgSQL_var));
821 /* Ensure the value is null (possibly not needed?) */
824 new->freeval = false;
826 result = (PLpgSQL_datum *) new;
830 case PLPGSQL_DTYPE_REC:
832 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
834 memcpy(new, datum, sizeof(PLpgSQL_rec));
835 /* Ensure the value is null (possibly not needed?) */
838 new->freetup = false;
839 new->freetupdesc = false;
841 result = (PLpgSQL_datum *) new;
845 case PLPGSQL_DTYPE_ROW:
846 case PLPGSQL_DTYPE_RECFIELD:
847 case PLPGSQL_DTYPE_ARRAYELEM:
848 case PLPGSQL_DTYPE_TRIGARG:
851 * These datum records are read-only at runtime, so no need to
858 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
859 result = NULL; /* keep compiler quiet */
868 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
870 for (; cond != NULL; cond = cond->next)
872 int sqlerrstate = cond->sqlerrstate;
875 * OTHERS matches everything *except* query-canceled; if you're
876 * foolish enough, you can match that explicitly.
878 if (sqlerrstate == 0)
880 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
884 else if (edata->sqlerrcode == sqlerrstate)
886 /* Category match? */
887 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
888 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
896 * exec_stmt_block Execute a block of statements
900 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
902 volatile int rc = -1;
907 * First initialize all variables declared in this block
909 estate->err_text = gettext_noop("during statement block local variable initialization");
911 for (i = 0; i < block->n_initvars; i++)
913 n = block->initvarnos[i];
915 switch (estate->datums[n]->dtype)
917 case PLPGSQL_DTYPE_VAR:
919 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
921 /* free any old value, in case re-entering block */
924 /* Initially it contains a NULL */
925 var->value = (Datum) 0;
928 if (var->default_val == NULL)
931 * If needed, give the datatype a chance to reject
932 * NULLs, by assigning a NULL to the variable. We
933 * claim the value is of type UNKNOWN, not the var's
934 * datatype, else coercion will be skipped. (Do this
935 * before the notnull check to be consistent with
936 * exec_assign_value.)
938 if (!var->datatype->typinput.fn_strict)
940 bool valIsNull = true;
942 exec_assign_value(estate,
943 (PLpgSQL_datum *) var,
950 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
951 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
956 exec_assign_expr(estate, (PLpgSQL_datum *) var,
962 case PLPGSQL_DTYPE_REC:
964 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
968 heap_freetuple(rec->tup);
969 FreeTupleDesc(rec->tupdesc);
970 rec->freetup = false;
978 case PLPGSQL_DTYPE_RECFIELD:
979 case PLPGSQL_DTYPE_ARRAYELEM:
983 elog(ERROR, "unrecognized dtype: %d",
984 estate->datums[n]->dtype);
988 if (block->exceptions)
991 * Execute the statements in the block's body inside a sub-transaction
993 MemoryContext oldcontext = CurrentMemoryContext;
994 ResourceOwner oldowner = CurrentResourceOwner;
995 ExprContext *old_eval_econtext = estate->eval_econtext;
996 EState *old_eval_estate = estate->eval_estate;
997 long int old_eval_estate_simple_id = estate->eval_estate_simple_id;
999 estate->err_text = gettext_noop("during statement block entry");
1001 BeginInternalSubTransaction(NULL);
1002 /* Want to run statements inside function's memory context */
1003 MemoryContextSwitchTo(oldcontext);
1008 * We need to run the block's statements with a new eval_econtext
1009 * that belongs to the current subtransaction; if we try to use
1010 * the outer econtext then ExprContext shutdown callbacks will be
1011 * called at the wrong times.
1013 plpgsql_create_econtext(estate);
1015 estate->err_text = NULL;
1017 /* Run the block's statements */
1018 rc = exec_stmts(estate, block->body);
1020 estate->err_text = gettext_noop("during statement block exit");
1023 * If the block ended with RETURN, we may need to copy the return
1024 * value out of the subtransaction eval_context. This is
1025 * currently only needed for scalar result types --- rowtype
1026 * values will always exist in the function's own memory context.
1028 if (rc == PLPGSQL_RC_RETURN &&
1029 !estate->retisset &&
1030 !estate->retisnull &&
1031 estate->rettupdesc == NULL)
1036 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1037 estate->retval = datumCopy(estate->retval,
1038 resTypByVal, resTypLen);
1041 /* Commit the inner transaction, return to outer xact context */
1042 ReleaseCurrentSubTransaction();
1043 MemoryContextSwitchTo(oldcontext);
1044 CurrentResourceOwner = oldowner;
1046 /* Revert to outer eval_econtext */
1047 estate->eval_econtext = old_eval_econtext;
1048 estate->eval_estate = old_eval_estate;
1049 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1052 * AtEOSubXact_SPI() should not have popped any SPI context, but
1053 * just in case it did, make sure we remain connected.
1055 SPI_restore_connection();
1062 estate->err_text = gettext_noop("during exception cleanup");
1064 /* Save error info */
1065 MemoryContextSwitchTo(oldcontext);
1066 edata = CopyErrorData();
1069 /* Abort the inner transaction */
1070 RollbackAndReleaseCurrentSubTransaction();
1071 MemoryContextSwitchTo(oldcontext);
1072 CurrentResourceOwner = oldowner;
1074 /* Revert to outer eval_econtext */
1075 estate->eval_econtext = old_eval_econtext;
1076 estate->eval_estate = old_eval_estate;
1077 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1080 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1081 * will have left us in a disconnected state. We need this hack
1082 * to return to connected state.
1084 SPI_restore_connection();
1086 /* Look for a matching exception handler */
1087 foreach(e, block->exceptions->exc_list)
1089 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1091 if (exception_matches_conditions(edata, exception->conditions))
1094 * Initialize the magic SQLSTATE and SQLERRM variables for
1095 * the exception block. We needn't do this until we have
1096 * found a matching exception.
1098 PLpgSQL_var *state_var;
1099 PLpgSQL_var *errm_var;
1101 state_var = (PLpgSQL_var *)
1102 estate->datums[block->exceptions->sqlstate_varno];
1103 errm_var = (PLpgSQL_var *)
1104 estate->datums[block->exceptions->sqlerrm_varno];
1106 assign_text_var(state_var,
1107 unpack_sql_state(edata->sqlerrcode));
1108 assign_text_var(errm_var, edata->message);
1110 estate->err_text = NULL;
1112 rc = exec_stmts(estate, exception->action);
1114 free_var(state_var);
1115 state_var->value = (Datum) 0;
1116 state_var->isnull = true;
1118 errm_var->value = (Datum) 0;
1119 errm_var->isnull = true;
1121 /* re-throw error if requested by handler */
1122 if (rc == PLPGSQL_RC_RERAISE)
1123 ReThrowError(edata);
1129 /* If no match found, re-throw the error */
1131 ReThrowError(edata);
1133 FreeErrorData(edata);
1140 * Just execute the statements in the block's body
1142 estate->err_text = NULL;
1144 rc = exec_stmts(estate, block->body);
1147 estate->err_text = NULL;
1150 * Handle the return code.
1155 case PLPGSQL_RC_RETURN:
1156 case PLPGSQL_RC_CONTINUE:
1157 case PLPGSQL_RC_RERAISE:
1160 case PLPGSQL_RC_EXIT:
1161 if (estate->exitlabel == NULL)
1162 return PLPGSQL_RC_OK;
1163 if (block->label == NULL)
1164 return PLPGSQL_RC_EXIT;
1165 if (strcmp(block->label, estate->exitlabel))
1166 return PLPGSQL_RC_EXIT;
1167 estate->exitlabel = NULL;
1168 return PLPGSQL_RC_OK;
1171 elog(ERROR, "unrecognized rc: %d", rc);
1174 return PLPGSQL_RC_OK;
1179 * exec_stmts Iterate over a list of statements
1180 * as long as their return code is OK
1184 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1191 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1192 * statement. This prevents hangup in a tight loop if, for instance,
1193 * there is a LOOP construct with an empty body.
1195 CHECK_FOR_INTERRUPTS();
1196 return PLPGSQL_RC_OK;
1201 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1202 int rc = exec_stmt(estate, stmt);
1204 if (rc != PLPGSQL_RC_OK)
1208 return PLPGSQL_RC_OK;
1213 * exec_stmt Distribute one statement to the statements
1214 * type specific execution function.
1218 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1220 PLpgSQL_stmt *save_estmt;
1223 save_estmt = estate->err_stmt;
1224 estate->err_stmt = stmt;
1226 /* Let the plugin know that we are about to execute this statement */
1227 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1228 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1230 CHECK_FOR_INTERRUPTS();
1232 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1234 case PLPGSQL_STMT_BLOCK:
1235 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1238 case PLPGSQL_STMT_ASSIGN:
1239 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1242 case PLPGSQL_STMT_PERFORM:
1243 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1246 case PLPGSQL_STMT_GETDIAG:
1247 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1250 case PLPGSQL_STMT_IF:
1251 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1254 case PLPGSQL_STMT_CASE:
1255 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1258 case PLPGSQL_STMT_LOOP:
1259 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1262 case PLPGSQL_STMT_WHILE:
1263 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1266 case PLPGSQL_STMT_FORI:
1267 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1270 case PLPGSQL_STMT_FORS:
1271 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1274 case PLPGSQL_STMT_FORC:
1275 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1278 case PLPGSQL_STMT_EXIT:
1279 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1282 case PLPGSQL_STMT_RETURN:
1283 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1286 case PLPGSQL_STMT_RETURN_NEXT:
1287 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1290 case PLPGSQL_STMT_RETURN_QUERY:
1291 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1294 case PLPGSQL_STMT_RAISE:
1295 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1298 case PLPGSQL_STMT_EXECSQL:
1299 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1302 case PLPGSQL_STMT_DYNEXECUTE:
1303 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1306 case PLPGSQL_STMT_DYNFORS:
1307 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1310 case PLPGSQL_STMT_OPEN:
1311 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1314 case PLPGSQL_STMT_FETCH:
1315 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1318 case PLPGSQL_STMT_CLOSE:
1319 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1323 estate->err_stmt = save_estmt;
1324 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1327 /* Let the plugin know that we have finished executing this statement */
1328 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1329 ((*plugin_ptr)->stmt_end) (estate, stmt);
1331 estate->err_stmt = save_estmt;
1338 * exec_stmt_assign Evaluate an expression and
1339 * put the result into a variable.
1343 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1345 Assert(stmt->varno >= 0);
1347 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1349 return PLPGSQL_RC_OK;
1353 * exec_stmt_perform Evaluate query and discard result (but set
1354 * FOUND depending on whether at least one row
1359 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1361 PLpgSQL_expr *expr = stmt->expr;
1363 (void) exec_run_select(estate, expr, 0, NULL);
1364 exec_set_found(estate, (estate->eval_processed != 0));
1365 exec_eval_cleanup(estate);
1367 return PLPGSQL_RC_OK;
1371 * exec_stmt_getdiag Put internal PG information into
1372 * specified variables.
1376 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1380 foreach(lc, stmt->diag_items)
1382 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1384 bool isnull = false;
1386 if (diag_item->target <= 0)
1389 var = estate->datums[diag_item->target];
1394 switch (diag_item->kind)
1396 case PLPGSQL_GETDIAG_ROW_COUNT:
1398 exec_assign_value(estate, var,
1399 UInt32GetDatum(estate->eval_processed),
1403 case PLPGSQL_GETDIAG_RESULT_OID:
1405 exec_assign_value(estate, var,
1406 ObjectIdGetDatum(estate->eval_lastoid),
1411 elog(ERROR, "unrecognized attribute request: %d",
1416 return PLPGSQL_RC_OK;
1420 * exec_stmt_if Evaluate a bool expression and
1421 * execute the true or false body
1426 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1431 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1432 exec_eval_cleanup(estate);
1434 if (!isnull && value)
1436 if (stmt->true_body != NIL)
1437 return exec_stmts(estate, stmt->true_body);
1441 if (stmt->false_body != NIL)
1442 return exec_stmts(estate, stmt->false_body);
1445 return PLPGSQL_RC_OK;
1454 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1456 PLpgSQL_var *t_var = NULL;
1460 if (stmt->t_expr != NULL)
1466 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1468 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1471 * When expected datatype is different from real, change it.
1472 * Note that what we're modifying here is an execution copy
1473 * of the datum, so this doesn't affect the originally stored
1474 * function parse tree.
1476 if (t_var->datatype->typoid != t_oid)
1477 t_var->datatype = plpgsql_build_datatype(t_oid, -1);
1479 /* now we can assign to the variable */
1480 exec_assign_value(estate,
1481 (PLpgSQL_datum *) t_var,
1486 exec_eval_cleanup(estate);
1489 /* Now search for a successful WHEN clause */
1490 foreach(l, stmt->case_when_list)
1492 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1495 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1496 exec_eval_cleanup(estate);
1497 if (!isnull && value)
1501 /* We can now discard any value we had for the temp variable */
1505 t_var->value = (Datum) 0;
1506 t_var->isnull = true;
1509 /* Evaluate the statement(s), and we're done */
1510 return exec_stmts(estate, cwt->stmts);
1514 /* We can now discard any value we had for the temp variable */
1518 t_var->value = (Datum) 0;
1519 t_var->isnull = true;
1522 /* SQL2003 mandates this error if there was no ELSE clause */
1523 if (!stmt->have_else)
1525 (errcode(ERRCODE_CASE_NOT_FOUND),
1526 errmsg("case not found"),
1527 errhint("CASE statement is missing ELSE part.")));
1529 /* Evaluate the ELSE statements, and we're done */
1530 return exec_stmts(estate, stmt->else_stmts);
1535 * exec_stmt_loop Loop over statements until
1540 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1544 int rc = exec_stmts(estate, stmt->body);
1551 case PLPGSQL_RC_EXIT:
1552 if (estate->exitlabel == NULL)
1553 return PLPGSQL_RC_OK;
1554 if (stmt->label == NULL)
1555 return PLPGSQL_RC_EXIT;
1556 if (strcmp(stmt->label, estate->exitlabel) != 0)
1557 return PLPGSQL_RC_EXIT;
1558 estate->exitlabel = NULL;
1559 return PLPGSQL_RC_OK;
1561 case PLPGSQL_RC_CONTINUE:
1562 if (estate->exitlabel == NULL)
1563 /* anonymous continue, so re-run the loop */
1565 else if (stmt->label != NULL &&
1566 strcmp(stmt->label, estate->exitlabel) == 0)
1567 /* label matches named continue, so re-run loop */
1568 estate->exitlabel = NULL;
1570 /* label doesn't match named continue, so propagate upward */
1571 return PLPGSQL_RC_CONTINUE;
1574 case PLPGSQL_RC_RETURN:
1575 case PLPGSQL_RC_RERAISE:
1579 elog(ERROR, "unrecognized rc: %d", rc);
1583 return PLPGSQL_RC_OK;
1588 * exec_stmt_while Loop over statements as long
1589 * as an expression evaluates to
1590 * true or an exit occurs.
1594 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1602 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1603 exec_eval_cleanup(estate);
1605 if (isnull || !value)
1608 rc = exec_stmts(estate, stmt->body);
1615 case PLPGSQL_RC_EXIT:
1616 if (estate->exitlabel == NULL)
1617 return PLPGSQL_RC_OK;
1618 if (stmt->label == NULL)
1619 return PLPGSQL_RC_EXIT;
1620 if (strcmp(stmt->label, estate->exitlabel))
1621 return PLPGSQL_RC_EXIT;
1622 estate->exitlabel = NULL;
1623 return PLPGSQL_RC_OK;
1625 case PLPGSQL_RC_CONTINUE:
1626 if (estate->exitlabel == NULL)
1627 /* anonymous continue, so re-run loop */
1629 else if (stmt->label != NULL &&
1630 strcmp(stmt->label, estate->exitlabel) == 0)
1631 /* label matches named continue, so re-run loop */
1632 estate->exitlabel = NULL;
1634 /* label doesn't match named continue, propagate upward */
1635 return PLPGSQL_RC_CONTINUE;
1638 case PLPGSQL_RC_RETURN:
1639 case PLPGSQL_RC_RERAISE:
1643 elog(ERROR, "unrecognized rc: %d", rc);
1647 return PLPGSQL_RC_OK;
1652 * exec_stmt_fori Iterate an integer variable
1653 * from a lower to an upper value
1654 * incrementing or decrementing by the BY value
1658 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1668 int rc = PLPGSQL_RC_OK;
1670 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1673 * Get the value of the lower bound
1675 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1676 value = exec_cast_value(value, valtype, var->datatype->typoid,
1677 &(var->datatype->typinput),
1678 var->datatype->typioparam,
1679 var->datatype->atttypmod, isnull);
1682 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1683 errmsg("lower bound of FOR loop cannot be NULL")));
1684 loop_value = DatumGetInt32(value);
1685 exec_eval_cleanup(estate);
1688 * Get the value of the upper bound
1690 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1691 value = exec_cast_value(value, valtype, var->datatype->typoid,
1692 &(var->datatype->typinput),
1693 var->datatype->typioparam,
1694 var->datatype->atttypmod, isnull);
1697 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1698 errmsg("upper bound of FOR loop cannot be NULL")));
1699 end_value = DatumGetInt32(value);
1700 exec_eval_cleanup(estate);
1703 * Get the step value
1707 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1708 value = exec_cast_value(value, valtype, var->datatype->typoid,
1709 &(var->datatype->typinput),
1710 var->datatype->typioparam,
1711 var->datatype->atttypmod, isnull);
1714 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1715 errmsg("BY value of FOR loop cannot be NULL")));
1716 step_value = DatumGetInt32(value);
1717 exec_eval_cleanup(estate);
1718 if (step_value <= 0)
1720 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1721 errmsg("BY value of FOR loop must be greater than zero")));
1732 * Check against upper bound
1736 if (loop_value < end_value)
1741 if (loop_value > end_value)
1745 found = true; /* looped at least once */
1748 * Assign current value to loop var
1750 var->value = Int32GetDatum(loop_value);
1751 var->isnull = false;
1754 * Execute the statements
1756 rc = exec_stmts(estate, stmt->body);
1758 if (rc == PLPGSQL_RC_RETURN ||
1759 rc == PLPGSQL_RC_RERAISE)
1760 break; /* break out of the loop */
1761 else if (rc == PLPGSQL_RC_EXIT)
1763 if (estate->exitlabel == NULL)
1764 /* unlabelled exit, finish the current loop */
1766 else if (stmt->label != NULL &&
1767 strcmp(stmt->label, estate->exitlabel) == 0)
1769 /* labelled exit, matches the current stmt's label */
1770 estate->exitlabel = NULL;
1775 * otherwise, this is a labelled exit that does not match the
1776 * current statement's label, if any: return RC_EXIT so that the
1777 * EXIT continues to propagate up the stack.
1781 else if (rc == PLPGSQL_RC_CONTINUE)
1783 if (estate->exitlabel == NULL)
1784 /* unlabelled continue, so re-run the current loop */
1786 else if (stmt->label != NULL &&
1787 strcmp(stmt->label, estate->exitlabel) == 0)
1789 /* label matches named continue, so re-run loop */
1790 estate->exitlabel = NULL;
1796 * otherwise, this is a named continue that does not match the
1797 * current statement's label, if any: return RC_CONTINUE so
1798 * that the CONTINUE will propagate up the stack.
1805 * Increase/decrease loop value, unless it would overflow, in which
1806 * case exit the loop.
1810 if ((int32) (loop_value - step_value) > loop_value)
1812 loop_value -= step_value;
1816 if ((int32) (loop_value + step_value) < loop_value)
1818 loop_value += step_value;
1823 * Set the FOUND variable to indicate the result of executing the loop
1824 * (namely, whether we looped one or more times). This must be set here so
1825 * that it does not interfere with the value of the FOUND variable inside
1826 * the loop processing itself.
1828 exec_set_found(estate, found);
1835 * exec_stmt_fors Execute a query, assign each
1836 * tuple to a record or row and
1837 * execute a group of statements
1842 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1848 * Open the implicit cursor for the statement using exec_run_select
1850 exec_run_select(estate, stmt->query, 0, &portal);
1855 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1858 * Close the implicit cursor
1860 SPI_cursor_close(portal);
1867 * exec_stmt_forc Execute a loop for each row from a cursor.
1871 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1873 PLpgSQL_var *curvar;
1874 char *curname = NULL;
1875 PLpgSQL_expr *query;
1882 * Get the cursor variable and if it has an assigned name, check
1883 * that it's not in use currently.
1886 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1887 if (!curvar->isnull)
1889 curname = TextDatumGetCString(curvar->value);
1890 if (SPI_cursor_find(curname) != NULL)
1892 (errcode(ERRCODE_DUPLICATE_CURSOR),
1893 errmsg("cursor \"%s\" already in use", curname)));
1897 * Open the cursor just like an OPEN command
1899 * Note: parser should already have checked that statement supplies
1900 * args iff cursor needs them, but we check again to be safe.
1903 if (stmt->argquery != NULL)
1906 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
1907 * statement to evaluate the args and put 'em into the
1911 PLpgSQL_stmt_execsql set_args;
1913 if (curvar->cursor_explicit_argrow < 0)
1915 (errcode(ERRCODE_SYNTAX_ERROR),
1916 errmsg("arguments given for cursor without arguments")));
1918 memset(&set_args, 0, sizeof(set_args));
1919 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1920 set_args.lineno = stmt->lineno;
1921 set_args.sqlstmt = stmt->argquery;
1922 set_args.into = true;
1923 /* XXX historically this has not been STRICT */
1924 set_args.row = (PLpgSQL_row *)
1925 (estate->datums[curvar->cursor_explicit_argrow]);
1927 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1928 elog(ERROR, "open cursor failed during argument processing");
1932 if (curvar->cursor_explicit_argrow >= 0)
1934 (errcode(ERRCODE_SYNTAX_ERROR),
1935 errmsg("arguments required for cursor")));
1938 query = curvar->cursor_explicit_expr;
1941 if (query->plan == NULL)
1942 exec_prepare_plan(estate, query, curvar->cursor_options);
1945 * Now build up the values and nulls arguments for SPI_execute_plan()
1947 eval_expr_params(estate, query, &values, &nulls);
1952 portal = SPI_cursor_open(curname, query->plan, values, nulls,
1953 estate->readonly_func);
1955 elog(ERROR, "could not open cursor: %s",
1956 SPI_result_code_string(SPI_result));
1959 * If cursor variable was NULL, store the generated portal name in it
1961 if (curname == NULL)
1962 assign_text_var(curvar, portal->name);
1965 * Execute the loop. We can't prefetch because the cursor is accessible
1966 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
1968 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
1971 * Close portal, and restore cursor variable if it was initially NULL.
1974 SPI_cursor_close(portal);
1976 if (curname == NULL)
1979 curvar->value = (Datum) 0;
1980 curvar->isnull = true;
1993 * exec_stmt_exit Implements EXIT and CONTINUE
1995 * This begins the process of exiting / restarting a loop.
1999 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2002 * If the exit / continue has a condition, evaluate it
2004 if (stmt->cond != NULL)
2009 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2010 exec_eval_cleanup(estate);
2011 if (isnull || value == false)
2012 return PLPGSQL_RC_OK;
2015 estate->exitlabel = stmt->label;
2017 return PLPGSQL_RC_EXIT;
2019 return PLPGSQL_RC_CONTINUE;
2024 * exec_stmt_return Evaluate an expression and start
2025 * returning from the function.
2029 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2032 * If processing a set-returning PL/PgSQL function, the final RETURN
2033 * indicates that the function is finished producing tuples. The rest of
2034 * the work will be done at the top level.
2036 if (estate->retisset)
2037 return PLPGSQL_RC_RETURN;
2039 /* initialize for null result (possibly a tuple) */
2040 estate->retval = (Datum) 0;
2041 estate->rettupdesc = NULL;
2042 estate->retisnull = true;
2044 if (stmt->retvarno >= 0)
2046 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2048 switch (retvar->dtype)
2050 case PLPGSQL_DTYPE_VAR:
2052 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2054 estate->retval = var->value;
2055 estate->retisnull = var->isnull;
2056 estate->rettype = var->datatype->typoid;
2060 case PLPGSQL_DTYPE_REC:
2062 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2064 if (HeapTupleIsValid(rec->tup))
2066 estate->retval = PointerGetDatum(rec->tup);
2067 estate->rettupdesc = rec->tupdesc;
2068 estate->retisnull = false;
2073 case PLPGSQL_DTYPE_ROW:
2075 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2077 Assert(row->rowtupdesc);
2079 PointerGetDatum(make_tuple_from_row(estate, row,
2081 if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
2082 elog(ERROR, "row not compatible with its own tupdesc");
2083 estate->rettupdesc = row->rowtupdesc;
2084 estate->retisnull = false;
2089 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2092 return PLPGSQL_RC_RETURN;
2095 if (stmt->expr != NULL)
2097 if (estate->retistuple)
2099 exec_run_select(estate, stmt->expr, 1, NULL);
2100 if (estate->eval_processed > 0)
2102 estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
2103 estate->rettupdesc = estate->eval_tuptable->tupdesc;
2104 estate->retisnull = false;
2109 /* Normal case for scalar results */
2110 estate->retval = exec_eval_expr(estate, stmt->expr,
2111 &(estate->retisnull),
2112 &(estate->rettype));
2115 return PLPGSQL_RC_RETURN;
2119 * Special hack for function returning VOID: instead of NULL, return a
2120 * non-null VOID value. This is of dubious importance but is kept for
2121 * backwards compatibility. Note that the only other way to get here is
2122 * to have written "RETURN NULL" in a function returning tuple.
2124 if (estate->fn_rettype == VOIDOID)
2126 estate->retval = (Datum) 0;
2127 estate->retisnull = false;
2128 estate->rettype = VOIDOID;
2131 return PLPGSQL_RC_RETURN;
2135 * exec_stmt_return_next Evaluate an expression and add it to the
2136 * list of tuples returned by the current
2141 exec_stmt_return_next(PLpgSQL_execstate *estate,
2142 PLpgSQL_stmt_return_next *stmt)
2146 MemoryContext oldcxt;
2147 HeapTuple tuple = NULL;
2148 bool free_tuple = false;
2150 if (!estate->retisset)
2152 (errcode(ERRCODE_SYNTAX_ERROR),
2153 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2155 if (estate->tuple_store == NULL)
2156 exec_init_tuple_store(estate);
2158 /* rettupdesc will be filled by exec_init_tuple_store */
2159 tupdesc = estate->rettupdesc;
2160 natts = tupdesc->natts;
2162 if (stmt->retvarno >= 0)
2164 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2166 switch (retvar->dtype)
2168 case PLPGSQL_DTYPE_VAR:
2170 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2171 Datum retval = var->value;
2172 bool isNull = var->isnull;
2176 (errcode(ERRCODE_DATATYPE_MISMATCH),
2177 errmsg("wrong result type supplied in RETURN NEXT")));
2179 /* coerce type if needed */
2180 retval = exec_simple_cast_value(retval,
2181 var->datatype->typoid,
2182 tupdesc->attrs[0]->atttypid,
2183 tupdesc->attrs[0]->atttypmod,
2186 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2187 tuplestore_putvalues(estate->tuple_store, tupdesc,
2189 MemoryContextSwitchTo(oldcxt);
2193 case PLPGSQL_DTYPE_REC:
2195 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2197 if (!HeapTupleIsValid(rec->tup))
2199 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2200 errmsg("record \"%s\" is not assigned yet",
2202 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
2203 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
2205 (errcode(ERRCODE_DATATYPE_MISMATCH),
2206 errmsg("wrong record type supplied in RETURN NEXT")));
2211 case PLPGSQL_DTYPE_ROW:
2213 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2215 tuple = make_tuple_from_row(estate, row, tupdesc);
2218 (errcode(ERRCODE_DATATYPE_MISMATCH),
2219 errmsg("wrong record type supplied in RETURN NEXT")));
2225 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2229 else if (stmt->expr)
2237 (errcode(ERRCODE_DATATYPE_MISMATCH),
2238 errmsg("wrong result type supplied in RETURN NEXT")));
2240 retval = exec_eval_expr(estate,
2245 /* coerce type if needed */
2246 retval = exec_simple_cast_value(retval,
2248 tupdesc->attrs[0]->atttypid,
2249 tupdesc->attrs[0]->atttypmod,
2252 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2253 tuplestore_putvalues(estate->tuple_store, tupdesc,
2255 MemoryContextSwitchTo(oldcxt);
2257 exec_eval_cleanup(estate);
2262 (errcode(ERRCODE_SYNTAX_ERROR),
2263 errmsg("RETURN NEXT must have a parameter")));
2266 if (HeapTupleIsValid(tuple))
2268 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2269 tuplestore_puttuple(estate->tuple_store, tuple);
2270 MemoryContextSwitchTo(oldcxt);
2273 heap_freetuple(tuple);
2276 return PLPGSQL_RC_OK;
2280 * exec_stmt_return_query Evaluate a query and add it to the
2281 * list of tuples returned by the current
2286 exec_stmt_return_query(PLpgSQL_execstate *estate,
2287 PLpgSQL_stmt_return_query *stmt)
2291 if (!estate->retisset)
2293 (errcode(ERRCODE_SYNTAX_ERROR),
2294 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2296 if (estate->tuple_store == NULL)
2297 exec_init_tuple_store(estate);
2299 if (stmt->query != NULL)
2302 exec_run_select(estate, stmt->query, 0, &portal);
2306 /* RETURN QUERY EXECUTE */
2307 Assert(stmt->dynquery != NULL);
2308 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2312 if (!compatible_tupdesc(estate->rettupdesc, portal->tupDesc))
2314 (errcode(ERRCODE_DATATYPE_MISMATCH),
2315 errmsg("structure of query does not match function result type")));
2319 MemoryContext old_cxt;
2322 SPI_cursor_fetch(portal, true, 50);
2323 if (SPI_processed == 0)
2326 old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2327 for (i = 0; i < SPI_processed; i++)
2329 HeapTuple tuple = SPI_tuptable->vals[i];
2331 tuplestore_puttuple(estate->tuple_store, tuple);
2333 MemoryContextSwitchTo(old_cxt);
2335 SPI_freetuptable(SPI_tuptable);
2338 SPI_freetuptable(SPI_tuptable);
2339 SPI_cursor_close(portal);
2341 return PLPGSQL_RC_OK;
2345 exec_init_tuple_store(PLpgSQL_execstate *estate)
2347 ReturnSetInfo *rsi = estate->rsi;
2348 MemoryContext oldcxt;
2351 * Check caller can handle a set result in the way we want
2353 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2354 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2355 rsi->expectedDesc == NULL)
2357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2358 errmsg("set-valued function called in context that cannot accept a set")));
2360 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2362 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2363 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2364 MemoryContextSwitchTo(oldcxt);
2366 estate->rettupdesc = rsi->expectedDesc;
2370 * exec_stmt_raise Build a message and throw it with elog()
2374 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2377 char *condname = NULL;
2378 char *err_message = NULL;
2379 char *err_detail = NULL;
2380 char *err_hint = NULL;
2383 /* RAISE with no parameters: re-throw current exception */
2384 if (stmt->condname == NULL && stmt->message == NULL &&
2385 stmt->options == NIL)
2386 return PLPGSQL_RC_RERAISE;
2390 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2391 condname = pstrdup(stmt->condname);
2397 ListCell *current_param;
2400 plpgsql_dstring_init(&ds);
2401 current_param = list_head(stmt->params);
2403 for (cp = stmt->message; *cp; cp++)
2406 * Occurrences of a single % are replaced by the next parameter's
2407 * external representation. Double %'s are converted to one %.
2418 plpgsql_dstring_append_char(&ds, cp[1]);
2423 if (current_param == NULL)
2425 (errcode(ERRCODE_SYNTAX_ERROR),
2426 errmsg("too few parameters specified for RAISE")));
2428 paramvalue = exec_eval_expr(estate,
2429 (PLpgSQL_expr *) lfirst(current_param),
2436 extval = convert_value_to_string(paramvalue, paramtypeid);
2437 plpgsql_dstring_append(&ds, extval);
2438 current_param = lnext(current_param);
2439 exec_eval_cleanup(estate);
2442 plpgsql_dstring_append_char(&ds, cp[0]);
2446 * If more parameters were specified than were required to process the
2447 * format string, throw an error
2449 if (current_param != NULL)
2451 (errcode(ERRCODE_SYNTAX_ERROR),
2452 errmsg("too many parameters specified for RAISE")));
2454 err_message = plpgsql_dstring_get(&ds);
2455 /* No dstring_free here, the pfree(err_message) does it */
2458 foreach(lc, stmt->options)
2460 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2466 optionvalue = exec_eval_expr(estate, opt->expr,
2471 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2472 errmsg("RAISE statement option cannot be NULL")));
2474 extval = convert_value_to_string(optionvalue, optiontypeid);
2476 switch (opt->opt_type)
2478 case PLPGSQL_RAISEOPTION_ERRCODE:
2481 (errcode(ERRCODE_SYNTAX_ERROR),
2482 errmsg("RAISE option already specified: %s",
2484 err_code = plpgsql_recognize_err_condition(extval, true);
2485 condname = pstrdup(extval);
2487 case PLPGSQL_RAISEOPTION_MESSAGE:
2490 (errcode(ERRCODE_SYNTAX_ERROR),
2491 errmsg("RAISE option already specified: %s",
2493 err_message = pstrdup(extval);
2495 case PLPGSQL_RAISEOPTION_DETAIL:
2498 (errcode(ERRCODE_SYNTAX_ERROR),
2499 errmsg("RAISE option already specified: %s",
2501 err_detail = pstrdup(extval);
2503 case PLPGSQL_RAISEOPTION_HINT:
2506 (errcode(ERRCODE_SYNTAX_ERROR),
2507 errmsg("RAISE option already specified: %s",
2509 err_hint = pstrdup(extval);
2512 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
2515 exec_eval_cleanup(estate);
2518 /* Default code if nothing specified */
2519 if (err_code == 0 && stmt->elog_level >= ERROR)
2520 err_code = ERRCODE_RAISE_EXCEPTION;
2522 /* Default error message if nothing specified */
2523 if (err_message == NULL)
2527 err_message = condname;
2531 err_message = pstrdup(unpack_sql_state(err_code));
2535 * Throw the error (may or may not come back)
2537 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2539 ereport(stmt->elog_level,
2540 (err_code ? errcode(err_code) : 0,
2541 errmsg_internal("%s", err_message),
2542 (err_detail != NULL) ? errdetail(err_detail) : 0,
2543 (err_hint != NULL) ? errhint(err_hint) : 0));
2545 estate->err_text = NULL; /* un-suppress... */
2547 if (condname != NULL)
2549 if (err_message != NULL)
2551 if (err_detail != NULL)
2553 if (err_hint != NULL)
2556 return PLPGSQL_RC_OK;
2561 * Initialize a mostly empty execution state
2565 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2566 PLpgSQL_function *func,
2569 estate->retval = (Datum) 0;
2570 estate->retisnull = true;
2571 estate->rettype = InvalidOid;
2573 estate->fn_rettype = func->fn_rettype;
2574 estate->retistuple = func->fn_retistuple;
2575 estate->retisset = func->fn_retset;
2577 estate->readonly_func = func->fn_readonly;
2579 estate->rettupdesc = NULL;
2580 estate->exitlabel = NULL;
2582 estate->tuple_store = NULL;
2583 estate->tuple_store_cxt = NULL;
2586 estate->trig_nargs = 0;
2587 estate->trig_argv = NULL;
2589 estate->found_varno = func->found_varno;
2590 estate->ndatums = func->ndatums;
2591 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2592 /* caller is expected to fill the datums array */
2594 estate->eval_tuptable = NULL;
2595 estate->eval_processed = 0;
2596 estate->eval_lastoid = InvalidOid;
2598 estate->err_func = func;
2599 estate->err_stmt = NULL;
2600 estate->err_text = NULL;
2603 * Create an EState and ExprContext for evaluation of simple expressions.
2605 plpgsql_create_econtext(estate);
2608 * Let the plugin see this function before we initialize any local
2609 * PL/pgSQL variables - note that we also give the plugin a few function
2610 * pointers so it can call back into PL/pgSQL for doing things like
2611 * variable assignments and stack traces
2615 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2616 (*plugin_ptr)->assign_expr = exec_assign_expr;
2618 if ((*plugin_ptr)->func_setup)
2619 ((*plugin_ptr)->func_setup) (estate, func);
2624 * Release temporary memory used by expression/subselect evaluation
2626 * NB: the result of the evaluation is no longer valid after this is done,
2627 * unless it is a pass-by-value datatype.
2631 exec_eval_cleanup(PLpgSQL_execstate *estate)
2633 /* Clear result of a full SPI_execute */
2634 if (estate->eval_tuptable != NULL)
2635 SPI_freetuptable(estate->eval_tuptable);
2636 estate->eval_tuptable = NULL;
2638 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2639 if (estate->eval_econtext != NULL)
2640 ResetExprContext(estate->eval_econtext);
2645 * Generate a prepared plan
2649 exec_prepare_plan(PLpgSQL_execstate *estate,
2650 PLpgSQL_expr *expr, int cursorOptions)
2657 * We need a temporary argtypes array to load with data. (The finished
2658 * plan structure will contain a copy of it.)
2660 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2662 for (i = 0; i < expr->nparams; i++)
2667 exec_eval_datum(estate, estate->datums[expr->params[i]],
2669 &argtypes[i], ¶mval, ¶misnull);
2673 * Generate and save the plan
2675 plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
2679 /* Some SPI errors deserve specific error messages */
2682 case SPI_ERROR_COPY:
2684 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2685 errmsg("cannot COPY to/from client in PL/pgSQL")));
2686 case SPI_ERROR_TRANSACTION:
2688 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2689 errmsg("cannot begin/end transactions in PL/pgSQL"),
2690 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2692 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2693 expr->query, SPI_result_code_string(SPI_result));
2696 expr->plan = SPI_saveplan(plan);
2699 expr->plan_argtypes = plan->argtypes;
2700 exec_simple_check_plan(expr);
2707 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2711 exec_stmt_execsql(PLpgSQL_execstate *estate,
2712 PLpgSQL_stmt_execsql *stmt)
2718 PLpgSQL_expr *expr = stmt->sqlstmt;
2721 * On the first call for this statement generate the plan, and detect
2722 * whether the statement is INSERT/UPDATE/DELETE
2724 if (expr->plan == NULL)
2728 exec_prepare_plan(estate, expr, 0);
2729 stmt->mod_stmt = false;
2730 foreach(l, expr->plan->plancache_list)
2732 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2735 foreach(l2, plansource->plan->stmt_list)
2737 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2739 if (IsA(p, PlannedStmt) &&
2742 if (p->commandType == CMD_INSERT ||
2743 p->commandType == CMD_UPDATE ||
2744 p->commandType == CMD_DELETE)
2745 stmt->mod_stmt = true;
2752 * Now build up the values and nulls arguments for SPI_execute_plan()
2754 eval_expr_params(estate, expr, &values, &nulls);
2757 * If we have INTO, then we only need one row back ... but if we have INTO
2758 * STRICT, ask for two rows, so that we can verify the statement returns
2759 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2760 * INTO, just run the statement to completion (tcount = 0).
2762 * We could just ask for two rows always when using INTO, but there are
2763 * some cases where demanding the extra row costs significant time, eg by
2764 * forcing completion of a sequential scan. So don't do it unless we need
2765 * to enforce strictness.
2769 if (stmt->strict || stmt->mod_stmt)
2780 rc = SPI_execute_plan(expr->plan, values, nulls,
2781 estate->readonly_func, tcount);
2784 * Check for error, and set FOUND if appropriate (for historical reasons
2785 * we set FOUND only for certain query types). Also Assert that we
2786 * identified the statement type the same as SPI did.
2791 Assert(!stmt->mod_stmt);
2792 exec_set_found(estate, (SPI_processed != 0));
2798 case SPI_OK_INSERT_RETURNING:
2799 case SPI_OK_UPDATE_RETURNING:
2800 case SPI_OK_DELETE_RETURNING:
2801 Assert(stmt->mod_stmt);
2802 exec_set_found(estate, (SPI_processed != 0));
2805 case SPI_OK_SELINTO:
2806 case SPI_OK_UTILITY:
2807 Assert(!stmt->mod_stmt);
2811 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2812 expr->query, SPI_result_code_string(rc));
2815 /* All variants should save result info for GET DIAGNOSTICS */
2816 estate->eval_processed = SPI_processed;
2817 estate->eval_lastoid = SPI_lastoid;
2819 /* Process INTO if present */
2822 SPITupleTable *tuptab = SPI_tuptable;
2823 uint32 n = SPI_processed;
2824 PLpgSQL_rec *rec = NULL;
2825 PLpgSQL_row *row = NULL;
2827 /* If the statement did not return a tuple table, complain */
2830 (errcode(ERRCODE_SYNTAX_ERROR),
2831 errmsg("INTO used with a command that cannot return data")));
2833 /* Determine if we assign to a record or a row */
2834 if (stmt->rec != NULL)
2835 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2836 else if (stmt->row != NULL)
2837 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2839 elog(ERROR, "unsupported target");
2842 * If SELECT ... INTO specified STRICT, and the query didn't find
2843 * exactly one row, throw an error. If STRICT was not specified, then
2844 * allow the query to find any number of rows.
2850 (errcode(ERRCODE_NO_DATA_FOUND),
2851 errmsg("query returned no rows")));
2852 /* set the target to NULL(s) */
2853 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2857 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2859 (errcode(ERRCODE_TOO_MANY_ROWS),
2860 errmsg("query returned more than one row")));
2861 /* Put the first result row into the target */
2862 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2866 SPI_freetuptable(SPI_tuptable);
2870 /* If the statement returned a tuple table, complain */
2871 if (SPI_tuptable != NULL)
2873 (errcode(ERRCODE_SYNTAX_ERROR),
2874 errmsg("query has no destination for result data"),
2875 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2881 return PLPGSQL_RC_OK;
2886 * exec_stmt_dynexecute Execute a dynamic SQL query
2887 * (possibly with INTO).
2891 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2892 PLpgSQL_stmt_dynexecute *stmt)
2895 bool isnull = false;
2901 * First we evaluate the string expression after the EXECUTE keyword. Its
2902 * result is the querystring we have to execute.
2904 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2907 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2908 errmsg("cannot EXECUTE a null querystring")));
2910 /* Get the C-String representation */
2911 querystr = convert_value_to_string(query, restype);
2913 exec_eval_cleanup(estate);
2916 * Execute the query without preparing a saved plan.
2920 PreparedParamsData *ppd;
2922 ppd = exec_eval_using_params(estate, stmt->params);
2923 exec_res = SPI_execute_with_args(querystr,
2924 ppd->nargs, ppd->types,
2925 ppd->values, ppd->nulls,
2926 estate->readonly_func, 0);
2927 free_params_data(ppd);
2930 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2938 case SPI_OK_INSERT_RETURNING:
2939 case SPI_OK_UPDATE_RETURNING:
2940 case SPI_OK_DELETE_RETURNING:
2941 case SPI_OK_UTILITY:
2947 * Also allow a zero return, which implies the querystring
2948 * contained no commands.
2952 case SPI_OK_SELINTO:
2955 * We want to disallow SELECT INTO for now, because its behavior
2956 * is not consistent with SELECT INTO in a normal plpgsql context.
2957 * (We need to reimplement EXECUTE to parse the string as a
2958 * plpgsql command, not just feed it to SPI_execute.) However,
2959 * CREATE AS should be allowed ... and since it produces the same
2960 * parsetree as SELECT INTO, there's no way to tell the difference
2961 * except to look at the source text. Wotta kluge!
2966 for (ptr = querystr; *ptr; ptr++)
2967 if (!scanner_isspace(*ptr))
2969 if (*ptr == 'S' || *ptr == 's')
2971 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2972 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2976 /* Some SPI errors deserve specific error messages */
2977 case SPI_ERROR_COPY:
2979 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2980 errmsg("cannot COPY to/from client in PL/pgSQL")));
2981 case SPI_ERROR_TRANSACTION:
2983 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2984 errmsg("cannot begin/end transactions in PL/pgSQL"),
2985 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2988 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2989 querystr, SPI_result_code_string(exec_res));
2993 /* Save result info for GET DIAGNOSTICS */
2994 estate->eval_processed = SPI_processed;
2995 estate->eval_lastoid = SPI_lastoid;
2997 /* Process INTO if present */
3000 SPITupleTable *tuptab = SPI_tuptable;
3001 uint32 n = SPI_processed;
3002 PLpgSQL_rec *rec = NULL;
3003 PLpgSQL_row *row = NULL;
3005 /* If the statement did not return a tuple table, complain */
3008 (errcode(ERRCODE_SYNTAX_ERROR),
3009 errmsg("INTO used with a command that cannot return data")));
3011 /* Determine if we assign to a record or a row */
3012 if (stmt->rec != NULL)
3013 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3014 else if (stmt->row != NULL)
3015 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3017 elog(ERROR, "unsupported target");
3020 * If SELECT ... INTO specified STRICT, and the query didn't find
3021 * exactly one row, throw an error. If STRICT was not specified, then
3022 * allow the query to find any number of rows.
3028 (errcode(ERRCODE_NO_DATA_FOUND),
3029 errmsg("query returned no rows")));
3030 /* set the target to NULL(s) */
3031 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3035 if (n > 1 && stmt->strict)
3037 (errcode(ERRCODE_TOO_MANY_ROWS),
3038 errmsg("query returned more than one row")));
3039 /* Put the first result row into the target */
3040 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3046 * It might be a good idea to raise an error if the query returned
3047 * tuples that are being ignored, but historically we have not done
3052 /* Release any result from SPI_execute, as well as the querystring */
3053 SPI_freetuptable(SPI_tuptable);
3056 return PLPGSQL_RC_OK;
3061 * exec_stmt_dynfors Execute a dynamic query, assign each
3062 * tuple to a record or row and
3063 * execute a group of statements
3068 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3073 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params);
3078 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3081 * Close the implicit cursor
3083 SPI_cursor_close(portal);
3090 * exec_stmt_open Execute an OPEN cursor statement
3094 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3096 PLpgSQL_var *curvar;
3097 char *curname = NULL;
3098 PLpgSQL_expr *query;
3105 * Get the cursor variable and if it has an assigned name, check
3106 * that it's not in use currently.
3109 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3110 if (!curvar->isnull)
3112 curname = TextDatumGetCString(curvar->value);
3113 if (SPI_cursor_find(curname) != NULL)
3115 (errcode(ERRCODE_DUPLICATE_CURSOR),
3116 errmsg("cursor \"%s\" already in use", curname)));
3120 * Process the OPEN according to it's type.
3123 if (stmt->query != NULL)
3126 * This is an OPEN refcursor FOR SELECT ...
3128 * We just make sure the query is planned. The real work is
3132 query = stmt->query;
3133 if (query->plan == NULL)
3134 exec_prepare_plan(estate, query, stmt->cursor_options);
3136 else if (stmt->dynquery != NULL)
3139 * This is an OPEN refcursor FOR EXECUTE ...
3148 * We evaluate the string expression after the
3149 * EXECUTE keyword. It's result is the querystring we have
3153 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
3156 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3157 errmsg("cannot EXECUTE a null querystring")));
3159 /* Get the C-String representation */
3160 querystr = convert_value_to_string(queryD, restype);
3162 exec_eval_cleanup(estate);
3165 * Now we prepare a query plan for it and open a cursor
3168 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
3169 if (curplan == NULL)
3170 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
3171 querystr, SPI_result_code_string(SPI_result));
3172 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
3173 estate->readonly_func);
3175 elog(ERROR, "could not open cursor for query \"%s\": %s",
3176 querystr, SPI_result_code_string(SPI_result));
3178 SPI_freeplan(curplan);
3181 * If cursor variable was NULL, store the generated portal name in it
3183 if (curname == NULL)
3184 assign_text_var(curvar, portal->name);
3186 return PLPGSQL_RC_OK;
3191 * This is an OPEN cursor
3193 * Note: parser should already have checked that statement supplies
3194 * args iff cursor needs them, but we check again to be safe.
3197 if (stmt->argquery != NULL)
3200 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3201 * statement to evaluate the args and put 'em into the
3205 PLpgSQL_stmt_execsql set_args;
3207 if (curvar->cursor_explicit_argrow < 0)
3209 (errcode(ERRCODE_SYNTAX_ERROR),
3210 errmsg("arguments given for cursor without arguments")));
3212 memset(&set_args, 0, sizeof(set_args));
3213 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3214 set_args.lineno = stmt->lineno;
3215 set_args.sqlstmt = stmt->argquery;
3216 set_args.into = true;
3217 /* XXX historically this has not been STRICT */
3218 set_args.row = (PLpgSQL_row *)
3219 (estate->datums[curvar->cursor_explicit_argrow]);
3221 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3222 elog(ERROR, "open cursor failed during argument processing");
3226 if (curvar->cursor_explicit_argrow >= 0)
3228 (errcode(ERRCODE_SYNTAX_ERROR),
3229 errmsg("arguments required for cursor")));
3232 query = curvar->cursor_explicit_expr;
3233 if (query->plan == NULL)
3234 exec_prepare_plan(estate, query, curvar->cursor_options);
3238 * Now build up the values and nulls arguments for SPI_execute_plan()
3240 eval_expr_params(estate, query, &values, &nulls);
3245 portal = SPI_cursor_open(curname, query->plan, values, nulls,
3246 estate->readonly_func);
3248 elog(ERROR, "could not open cursor: %s",
3249 SPI_result_code_string(SPI_result));
3252 * If cursor variable was NULL, store the generated portal name in it
3254 if (curname == NULL)
3255 assign_text_var(curvar, portal->name);
3262 return PLPGSQL_RC_OK;
3267 * exec_stmt_fetch Fetch from a cursor into a target, or just
3268 * move the current position of the cursor
3272 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3274 PLpgSQL_var *curvar = NULL;
3275 PLpgSQL_rec *rec = NULL;
3276 PLpgSQL_row *row = NULL;
3277 long how_many = stmt->how_many;
3278 SPITupleTable *tuptab;
3284 * Get the portal of the cursor by name
3287 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3290 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3291 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3292 curname = TextDatumGetCString(curvar->value);
3294 portal = SPI_cursor_find(curname);
3297 (errcode(ERRCODE_UNDEFINED_CURSOR),
3298 errmsg("cursor \"%s\" does not exist", curname)));
3301 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3306 /* XXX should be doing this in LONG not INT width */
3307 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3311 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3312 errmsg("relative or absolute cursor position is NULL")));
3314 exec_eval_cleanup(estate);
3320 * Determine if we fetch into a record or a row
3323 if (stmt->rec != NULL)
3324 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3325 else if (stmt->row != NULL)
3326 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3328 elog(ERROR, "unsupported target");
3331 * Fetch 1 tuple from the cursor
3334 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3335 tuptab = SPI_tuptable;
3339 * Set the target and the global FOUND variable appropriately.
3344 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3345 exec_set_found(estate, false);
3349 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3350 exec_set_found(estate, true);
3353 SPI_freetuptable(tuptab);
3357 /* Move the cursor */
3358 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3361 /* Set the global FOUND variable appropriately. */
3362 exec_set_found(estate, n != 0);
3365 return PLPGSQL_RC_OK;