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;
3369 * exec_stmt_close Close a cursor
3373 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3375 PLpgSQL_var *curvar = NULL;
3380 * Get the portal of the cursor by name
3383 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3386 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3387 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3388 curname = TextDatumGetCString(curvar->value);
3390 portal = SPI_cursor_find(curname);
3393 (errcode(ERRCODE_UNDEFINED_CURSOR),
3394 errmsg("cursor \"%s\" does not exist", curname)));
3401 SPI_cursor_close(portal);
3403 return PLPGSQL_RC_OK;
3408 * exec_assign_expr Put an expression's result into
3413 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3418 bool isnull = false;
3420 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3421 exec_assign_value(estate, target, value, valtype, &isnull);
3422 exec_eval_cleanup(estate);
3427 * exec_assign_value Put a value into a target field
3431 exec_assign_value(PLpgSQL_execstate *estate,
3432 PLpgSQL_datum *target,
3433 Datum value, Oid valtype, bool *isNull)
3435 switch (target->dtype)
3437 case PLPGSQL_DTYPE_VAR:
3440 * Target is a variable
3442 PLpgSQL_var *var = (PLpgSQL_var *) target;
3445 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3446 &(var->datatype->typinput),
3447 var->datatype->typioparam,
3448 var->datatype->atttypmod,
3451 if (*isNull && var->notnull)
3453 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3454 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3458 * If type is by-reference, make sure we have a freshly
3459 * palloc'd copy; the originally passed value may not live as
3460 * long as the variable! But we don't need to re-copy if
3461 * exec_cast_value performed a conversion; its output must
3462 * already be palloc'd.
3464 if (!var->datatype->typbyval && !*isNull)
3466 if (newvalue == value)
3467 newvalue = datumCopy(newvalue,
3469 var->datatype->typlen);
3473 * Now free the old value. (We can't do this any earlier
3474 * because of the possibility that we are assigning the var's
3475 * old value to it, eg "foo := foo". We could optimize out
3476 * the assignment altogether in such cases, but it's too
3477 * infrequent to be worth testing for.)
3481 var->value = newvalue;
3482 var->isnull = *isNull;
3483 if (!var->datatype->typbyval && !*isNull)
3484 var->freeval = true;
3488 case PLPGSQL_DTYPE_ROW:
3491 * Target is a row variable
3493 PLpgSQL_row *row = (PLpgSQL_row *) target;
3495 /* Source must be of RECORD or composite type */
3496 if (!type_is_rowtype(valtype))
3498 (errcode(ERRCODE_DATATYPE_MISMATCH),
3499 errmsg("cannot assign non-composite value to a row variable")));
3502 /* If source is null, just assign nulls to the row */
3503 exec_move_row(estate, NULL, row, NULL, NULL);
3511 HeapTupleData tmptup;
3513 /* Else source is a tuple Datum, safe to do this: */
3514 td = DatumGetHeapTupleHeader(value);
3515 /* Extract rowtype info and find a tupdesc */
3516 tupType = HeapTupleHeaderGetTypeId(td);
3517 tupTypmod = HeapTupleHeaderGetTypMod(td);
3518 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3519 /* Build a temporary HeapTuple control structure */
3520 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3521 ItemPointerSetInvalid(&(tmptup.t_self));
3522 tmptup.t_tableOid = InvalidOid;
3524 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3525 ReleaseTupleDesc(tupdesc);
3530 case PLPGSQL_DTYPE_REC:
3533 * Target is a record variable
3535 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3537 /* Source must be of RECORD or composite type */
3538 if (!type_is_rowtype(valtype))
3540 (errcode(ERRCODE_DATATYPE_MISMATCH),
3541 errmsg("cannot assign non-composite value to a record variable")));
3544 /* If source is null, just assign nulls to the record */
3545 exec_move_row(estate, rec, NULL, NULL, NULL);
3553 HeapTupleData tmptup;
3555 /* Else source is a tuple Datum, safe to do this: */
3556 td = DatumGetHeapTupleHeader(value);
3557 /* Extract rowtype info and find a tupdesc */
3558 tupType = HeapTupleHeaderGetTypeId(td);
3559 tupTypmod = HeapTupleHeaderGetTypMod(td);
3560 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3561 /* Build a temporary HeapTuple control structure */
3562 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3563 ItemPointerSetInvalid(&(tmptup.t_self));
3564 tmptup.t_tableOid = InvalidOid;
3566 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3567 ReleaseTupleDesc(tupdesc);
3572 case PLPGSQL_DTYPE_RECFIELD:
3575 * Target is a field of a record
3577 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3590 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3593 * Check that there is already a tuple in the record. We need
3594 * that because records don't have any predefined field
3597 if (!HeapTupleIsValid(rec->tup))
3599 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3600 errmsg("record \"%s\" is not assigned yet",
3602 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3605 * Get the number of the records field to change and the
3606 * number of attributes in the tuple.
3608 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3609 if (fno == SPI_ERROR_NOATTRIBUTE)
3611 (errcode(ERRCODE_UNDEFINED_COLUMN),
3612 errmsg("record \"%s\" has no field \"%s\"",
3613 rec->refname, recfield->fieldname)));
3615 natts = rec->tupdesc->natts;
3618 * Set up values/datums arrays for heap_formtuple. For all
3619 * the attributes except the one we want to replace, use the
3620 * value that's in the old tuple.
3622 values = palloc(sizeof(Datum) * natts);
3623 nulls = palloc(natts);
3625 for (i = 0; i < natts; i++)
3629 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3638 * Now insert the new value, being careful to cast it to the
3641 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3642 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3643 attisnull = *isNull;
3644 values[fno] = exec_simple_cast_value(value,
3655 * Avoid leaking the result of exec_simple_cast_value, if it
3656 * performed a conversion to a pass-by-ref type.
3658 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3659 mustfree = DatumGetPointer(values[fno]);
3664 * Now call heap_formtuple() to create a new tuple that
3665 * replaces the old one in the record.
3667 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3670 heap_freetuple(rec->tup);
3673 rec->freetup = true;
3683 case PLPGSQL_DTYPE_ARRAYELEM:
3687 PLpgSQL_expr *subscripts[MAXDIM];
3688 int subscriptvals[MAXDIM];
3689 bool oldarrayisnull;
3696 Datum oldarraydatum,
3698 ArrayType *oldarrayval;
3699 ArrayType *newarrayval;
3702 * Target is an element of an array
3704 * To handle constructs like x[1][2] := something, we have to
3705 * be prepared to deal with a chain of arrayelem datums. Chase
3706 * back to find the base array datum, and save the subscript
3707 * expressions as we go. (We are scanning right to left here,
3708 * but want to evaluate the subscripts left-to-right to
3709 * minimize surprises.)
3714 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3716 if (nsubscripts >= MAXDIM)
3718 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3719 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3721 subscripts[nsubscripts++] = arrayelem->subscript;
3722 target = estate->datums[arrayelem->arrayparentno];
3723 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3725 /* Fetch current value of array datum */
3726 exec_eval_datum(estate, target, InvalidOid,
3727 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3729 arrayelemtypeid = get_element_type(arraytypeid);
3730 if (!OidIsValid(arrayelemtypeid))
3732 (errcode(ERRCODE_DATATYPE_MISMATCH),
3733 errmsg("subscripted object is not an array")));
3735 get_typlenbyvalalign(arrayelemtypeid,
3739 arraytyplen = get_typlen(arraytypeid);
3742 * Evaluate the subscripts, switch into left-to-right order.
3743 * Like ExecEvalArrayRef(), complain if any subscript is null.
3745 for (i = 0; i < nsubscripts; i++)
3750 exec_eval_integer(estate,
3751 subscripts[nsubscripts - 1 - i],
3755 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3756 errmsg("array subscript in assignment must not be NULL")));
3759 /* Coerce source value to match array element type. */
3760 coerced_value = exec_simple_cast_value(value,
3767 * If the original array is null, cons up an empty array so
3768 * that the assignment can proceed; we'll end with a
3769 * one-element array containing just the assigned-to
3770 * subscript. This only works for varlena arrays, though; for
3771 * fixed-length array types we skip the assignment. We can't
3772 * support assignment of a null entry into a fixed-length
3773 * array, either, so that's a no-op too. This is all ugly but
3774 * corresponds to the current behavior of ExecEvalArrayRef().
3776 if (arraytyplen > 0 && /* fixed-length array? */
3777 (oldarrayisnull || *isNull))
3781 oldarrayval = construct_empty_array(arrayelemtypeid);
3783 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3786 * Build the modified array value.
3788 newarrayval = array_set(oldarrayval,
3799 * Avoid leaking the result of exec_simple_cast_value, if it
3800 * performed a conversion to a pass-by-ref type.
3802 if (!*isNull && coerced_value != value && !elemtypbyval)
3803 pfree(DatumGetPointer(coerced_value));
3806 * Assign the new array to the base variable. It's never NULL
3810 exec_assign_value(estate, target,
3811 PointerGetDatum(newarrayval),
3812 arraytypeid, isNull);
3815 * Avoid leaking the modified array value, too.
3822 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3827 * exec_eval_datum Get current value of a PLpgSQL_datum
3829 * The type oid, value in Datum format, and null flag are returned.
3831 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3833 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3835 * NOTE: caller must not modify the returned value, since it points right
3836 * at the stored value in the case of pass-by-reference datatypes. In some
3837 * cases we have to palloc a return value, and in such cases we put it into
3838 * the estate's short-term memory context.
3841 exec_eval_datum(PLpgSQL_execstate *estate,
3842 PLpgSQL_datum *datum,
3848 MemoryContext oldcontext;
3850 switch (datum->dtype)
3852 case PLPGSQL_DTYPE_VAR:
3854 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3856 *typeid = var->datatype->typoid;
3857 *value = var->value;
3858 *isnull = var->isnull;
3859 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3861 (errcode(ERRCODE_DATATYPE_MISMATCH),
3862 errmsg("type of \"%s\" does not match that when preparing the plan",
3867 case PLPGSQL_DTYPE_ROW:
3869 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3872 if (!row->rowtupdesc) /* should not happen */
3873 elog(ERROR, "row variable has no tupdesc");
3874 /* Make sure we have a valid type/typmod setting */
3875 BlessTupleDesc(row->rowtupdesc);
3876 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3877 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3878 if (tup == NULL) /* should not happen */
3879 elog(ERROR, "row not compatible with its own tupdesc");
3880 MemoryContextSwitchTo(oldcontext);
3881 *typeid = row->rowtupdesc->tdtypeid;
3882 *value = HeapTupleGetDatum(tup);
3884 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3886 (errcode(ERRCODE_DATATYPE_MISMATCH),
3887 errmsg("type of \"%s\" does not match that when preparing the plan",
3892 case PLPGSQL_DTYPE_REC:
3894 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3895 HeapTupleData worktup;
3897 if (!HeapTupleIsValid(rec->tup))
3899 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3900 errmsg("record \"%s\" is not assigned yet",
3902 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3903 Assert(rec->tupdesc != NULL);
3904 /* Make sure we have a valid type/typmod setting */
3905 BlessTupleDesc(rec->tupdesc);
3908 * In a trigger, the NEW and OLD parameters are likely to be
3909 * on-disk tuples that don't have the desired Datum fields.
3910 * Copy the tuple body and insert the right values.
3912 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3913 heap_copytuple_with_tuple(rec->tup, &worktup);
3914 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3915 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3916 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3917 MemoryContextSwitchTo(oldcontext);
3918 *typeid = rec->tupdesc->tdtypeid;
3919 *value = HeapTupleGetDatum(&worktup);
3921 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3923 (errcode(ERRCODE_DATATYPE_MISMATCH),
3924 errmsg("type of \"%s\" does not match that when preparing the plan",
3929 case PLPGSQL_DTYPE_RECFIELD:
3931 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3935 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3936 if (!HeapTupleIsValid(rec->tup))
3938 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3939 errmsg("record \"%s\" is not assigned yet",
3941 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3942 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3943 if (fno == SPI_ERROR_NOATTRIBUTE)
3945 (errcode(ERRCODE_UNDEFINED_COLUMN),
3946 errmsg("record \"%s\" has no field \"%s\"",
3947 rec->refname, recfield->fieldname)));
3948 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3949 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3950 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3952 (errcode(ERRCODE_DATATYPE_MISMATCH),
3953 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3954 rec->refname, recfield->fieldname)));
3958 case PLPGSQL_DTYPE_TRIGARG:
3960 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3964 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3965 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3972 *value = estate->trig_argv[tgargno];
3975 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3977 (errcode(ERRCODE_DATATYPE_MISMATCH),
3978 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3984 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3989 * exec_eval_integer Evaluate an expression, coerce result to int4
3991 * Note we do not do exec_eval_cleanup here; the caller must do it at
3992 * some later point. (We do this because the caller may be holding the
3993 * results of other, pass-by-reference, expression evaluations, such as
3994 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3995 * about allocation of the parameter array.)
3999 exec_eval_integer(PLpgSQL_execstate *estate,
4006 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4007 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4010 return DatumGetInt32(exprdatum);
4014 * exec_eval_boolean Evaluate an expression, coerce result to bool
4016 * Note we do not do exec_eval_cleanup here; the caller must do it at
4021 exec_eval_boolean(PLpgSQL_execstate *estate,
4028 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4029 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4032 return DatumGetBool(exprdatum);
4036 * exec_eval_expr Evaluate an expression and return
4039 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4043 exec_eval_expr(PLpgSQL_execstate *estate,
4052 * If first time through, create a plan for this expression.
4054 if (expr->plan == NULL)
4055 exec_prepare_plan(estate, expr, 0);
4058 * If this is a simple expression, bypass SPI and use the executor
4061 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4065 * Else do it the hard way via exec_run_select
4067 rc = exec_run_select(estate, expr, 2, NULL);
4068 if (rc != SPI_OK_SELECT)
4070 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4071 errmsg("query \"%s\" did not return data", expr->query)));
4074 * If there are no rows selected, the result is NULL.
4076 if (estate->eval_processed == 0)
4083 * Check that the expression returned one single Datum
4085 if (estate->eval_processed > 1)
4087 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4088 errmsg("query \"%s\" returned more than one row",
4090 if (estate->eval_tuptable->tupdesc->natts != 1)
4092 (errcode(ERRCODE_SYNTAX_ERROR),
4093 errmsg("query \"%s\" returned %d columns", expr->query,
4094 estate->eval_tuptable->tupdesc->natts)));
4097 * Return the result and its type
4099 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4100 return SPI_getbinval(estate->eval_tuptable->vals[0],
4101 estate->eval_tuptable->tupdesc, 1, isNull);
4106 * exec_run_select Execute a select query
4110 exec_run_select(PLpgSQL_execstate *estate,
4111 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4118 * On the first call for this expression generate the plan
4120 if (expr->plan == NULL)
4121 exec_prepare_plan(estate, expr, 0);
4124 * Now build up the values and nulls arguments for SPI_execute_plan()
4126 eval_expr_params(estate, expr, &values, &nulls);
4129 * If a portal was requested, put the query into the portal
4131 if (portalP != NULL)
4133 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
4134 estate->readonly_func);
4135 if (*portalP == NULL)
4136 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4137 expr->query, SPI_result_code_string(SPI_result));
4140 return SPI_OK_CURSOR;
4146 rc = SPI_execute_plan(expr->plan, values, nulls,
4147 estate->readonly_func, maxtuples);
4148 if (rc != SPI_OK_SELECT)
4150 (errcode(ERRCODE_SYNTAX_ERROR),
4151 errmsg("query \"%s\" is not a SELECT", expr->query)));
4153 /* Save query results for eventual cleanup */
4154 Assert(estate->eval_tuptable == NULL);
4155 estate->eval_tuptable = SPI_tuptable;
4156 estate->eval_processed = SPI_processed;
4157 estate->eval_lastoid = SPI_lastoid;
4167 * exec_for_query --- execute body of FOR loop for each row from a portal
4169 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4172 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4173 Portal portal, bool prefetch_ok)
4175 PLpgSQL_rec *rec = NULL;
4176 PLpgSQL_row *row = NULL;
4177 SPITupleTable *tuptab;
4179 int rc = PLPGSQL_RC_OK;
4183 * Determine if we assign to a record or a row
4185 if (stmt->rec != NULL)
4186 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
4187 else if (stmt->row != NULL)
4188 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
4190 elog(ERROR, "unsupported target");
4193 * Fetch the initial tuple(s). If prefetching is allowed then we grab
4194 * a few more rows to avoid multiple trips through executor startup
4197 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4198 tuptab = SPI_tuptable;
4202 * If the query didn't return any rows, set the target to NULL and
4203 * fall through with found = false.
4206 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4208 found = true; /* processed at least one tuple */
4217 for (i = 0; i < n; i++)
4220 * Assign the tuple to the target
4222 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4225 * Execute the statements
4227 rc = exec_stmts(estate, stmt->body);
4229 if (rc != PLPGSQL_RC_OK)
4231 if (rc == PLPGSQL_RC_EXIT)
4233 if (estate->exitlabel == NULL)
4235 /* unlabelled exit, so exit the current loop */
4238 else if (stmt->label != NULL &&
4239 strcmp(stmt->label, estate->exitlabel) == 0)
4241 /* label matches this loop, so exit loop */
4242 estate->exitlabel = NULL;
4247 * otherwise, we processed a labelled exit that does not
4248 * match the current statement's label, if any; return
4249 * RC_EXIT so that the EXIT continues to recurse upward.
4252 else if (rc == PLPGSQL_RC_CONTINUE)
4254 if (estate->exitlabel == NULL)
4256 /* unlabelled continue, so re-run the current loop */
4260 else if (stmt->label != NULL &&
4261 strcmp(stmt->label, estate->exitlabel) == 0)
4263 /* label matches this loop, so re-run loop */
4264 estate->exitlabel = NULL;
4270 * otherwise, we process a labelled continue that does not
4271 * match the current statement's label, if any; return
4272 * RC_CONTINUE so that the CONTINUE will propagate up the
4278 * We're aborting the loop. Need a goto to get out of two
4285 SPI_freetuptable(tuptab);
4288 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
4290 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
4291 tuptab = SPI_tuptable;
4298 * Release last group of tuples (if any)
4300 SPI_freetuptable(tuptab);
4303 * Set the FOUND variable to indicate the result of executing the loop
4304 * (namely, whether we looped one or more times). This must be set last so
4305 * that it does not interfere with the value of the FOUND variable inside
4306 * the loop processing itself.
4308 exec_set_found(estate, found);
4315 * exec_eval_simple_expr - Evaluate a simple expression returning
4316 * a Datum by directly calling ExecEvalExpr().
4318 * If successful, store results into *result, *isNull, *rettype and return
4319 * TRUE. If the expression is not simple (any more), return FALSE.
4321 * It is possible though unlikely for a simple expression to become non-simple
4322 * (consider for example redefining a trivial view). We must handle that for
4323 * correctness; fortunately it's normally inexpensive to do
4324 * RevalidateCachedPlan on a simple expression. We do not consider the other
4325 * direction (non-simple expression becoming simple) because we'll still give
4326 * correct results if that happens, and it's unlikely to be worth the cycles
4329 * Note: if pass-by-reference, the result is in the eval_econtext's
4330 * temporary memory context. It will be freed when exec_eval_cleanup
4335 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4341 ExprContext *econtext = estate->eval_econtext;
4342 CachedPlanSource *plansource;
4344 ParamListInfo paramLI;
4346 MemoryContext oldcontext;
4349 * Forget it if expression wasn't simple before.
4351 if (expr->expr_simple_expr == NULL)
4355 * Revalidate cached plan, so that we will notice if it became stale. (We
4356 * also need to hold a refcount while using the plan.) Note that even if
4357 * replanning occurs, the length of plancache_list can't change, since it
4358 * is a property of the raw parsetree generated from the query text.
4360 Assert(list_length(expr->plan->plancache_list) == 1);
4361 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4362 cplan = RevalidateCachedPlan(plansource, true);
4363 if (cplan->generation != expr->expr_simple_generation)
4365 /* It got replanned ... is it still simple? */
4366 exec_simple_check_plan(expr);
4367 if (expr->expr_simple_expr == NULL)
4369 /* Ooops, release refcount and fail */
4370 ReleaseCachedPlan(cplan, true);
4376 * Pass back previously-determined result type.
4378 *rettype = expr->expr_simple_type;
4381 * Prepare the expression for execution, if it's not been done already in
4382 * the current eval_estate. (This will be forced to happen if we called
4383 * exec_simple_check_plan above.)
4385 if (expr->expr_simple_id != estate->eval_estate_simple_id)
4387 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4388 estate->eval_estate);
4389 expr->expr_simple_id = estate->eval_estate_simple_id;
4393 * Param list can live in econtext's temporary memory context.
4395 * XXX think about avoiding repeated palloc's for param lists? Beware
4396 * however that this routine is re-entrant: exec_eval_datum() can call it
4397 * back for subscript evaluation, and so there can be a need to have more
4398 * than one active param list.
4400 if (expr->nparams > 0)
4402 /* sizeof(ParamListInfoData) includes the first array element */
4403 paramLI = (ParamListInfo)
4404 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
4405 sizeof(ParamListInfoData) +
4406 (expr->nparams - 1) *sizeof(ParamExternData));
4407 paramLI->numParams = expr->nparams;
4409 for (i = 0; i < expr->nparams; i++)
4411 ParamExternData *prm = ¶mLI->params[i];
4412 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4415 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4417 &prm->value, &prm->isnull);
4424 * Now we can safely make the econtext point to the param list.
4426 econtext->ecxt_param_list_info = paramLI;
4429 * We have to do some of the things SPI_execute_plan would do, in
4430 * particular advance the snapshot if we are in a non-read-only function.
4431 * Without this, stable functions within the expression would fail to see
4432 * updates made so far by our own function.
4436 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4437 if (!estate->readonly_func)
4439 CommandCounterIncrement();
4440 PushActiveSnapshot(GetTransactionSnapshot());
4444 * Finally we can call the executor to evaluate the expression
4446 *result = ExecEvalExpr(expr->expr_simple_state,
4450 MemoryContextSwitchTo(oldcontext);
4452 if (!estate->readonly_func)
4453 PopActiveSnapshot();
4458 * Now we can release our refcount on the cached plan.
4460 ReleaseCachedPlan(cplan, true);
4470 * Build up the values and nulls arguments for SPI_execute_plan()
4473 eval_expr_params(PLpgSQL_execstate *estate,
4474 PLpgSQL_expr *expr, Datum **p_values, char **p_nulls)
4480 *p_values = values = (Datum *) palloc(expr->nparams * sizeof(Datum));
4481 *p_nulls = nulls = (char *) palloc(expr->nparams * sizeof(char));
4483 for (i = 0; i < expr->nparams; i++)
4485 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4489 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4490 ¶mtypeid, &values[i], ¶misnull);
4500 * exec_move_row Move one tuple's values into a record or row
4504 exec_move_row(PLpgSQL_execstate *estate,
4507 HeapTuple tup, TupleDesc tupdesc)
4510 * Record is simple - just copy the tuple and its descriptor into the
4516 * copy input first, just in case it is pointing at variable's value
4518 if (HeapTupleIsValid(tup))
4519 tup = heap_copytuple(tup);
4521 tupdesc = CreateTupleDescCopy(tupdesc);
4525 heap_freetuple(rec->tup);
4526 rec->freetup = false;
4528 if (rec->freetupdesc)
4530 FreeTupleDesc(rec->tupdesc);
4531 rec->freetupdesc = false;
4534 if (HeapTupleIsValid(tup))
4537 rec->freetup = true;
4541 /* If we have a tupdesc but no data, form an all-nulls tuple */
4544 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
4545 memset(nulls, 'n', tupdesc->natts * sizeof(char));
4547 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
4548 rec->freetup = true;
4557 rec->tupdesc = tupdesc;
4558 rec->freetupdesc = true;
4561 rec->tupdesc = NULL;
4567 * Row is a bit more complicated in that we assign the individual
4568 * attributes of the tuple to the variables the row points to.
4570 * NOTE: this code used to demand row->nfields ==
4571 * HeapTupleHeaderGetNatts(tup->t_data, but that's wrong. The tuple might
4572 * have more fields than we expected if it's from an inheritance-child
4573 * table of the current table, or it might have fewer if the table has had
4574 * columns added by ALTER TABLE. Ignore extra columns and assume NULL for
4575 * missing columns, the same as heap_getattr would do. We also have to
4576 * skip over dropped columns in either the source or destination.
4578 * If we have no tuple data at all, we'll assign NULL to all columns of
4587 if (HeapTupleIsValid(tup))
4588 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4593 for (fnum = 0; fnum < row->nfields; fnum++)
4600 if (row->varnos[fnum] < 0)
4601 continue; /* skip dropped column in row struct */
4603 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4605 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
4606 anum++; /* skip dropped column in tuple */
4610 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4611 valtype = SPI_gettypeid(tupdesc, anum + 1);
4618 valtype = InvalidOid;
4621 exec_assign_value(estate, (PLpgSQL_datum *) var,
4622 value, valtype, &isnull);
4628 elog(ERROR, "unsupported target");
4632 * make_tuple_from_row Make a tuple from the values of a row object
4634 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4638 make_tuple_from_row(PLpgSQL_execstate *estate,
4642 int natts = tupdesc->natts;
4648 if (natts != row->nfields)
4651 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4652 nulls = (bool *) palloc(natts * sizeof(bool));
4654 for (i = 0; i < natts; i++)
4658 if (tupdesc->attrs[i]->attisdropped)
4660 nulls[i] = true; /* leave the column as null */
4663 if (row->varnos[i] < 0) /* should not happen */
4664 elog(ERROR, "dropped rowtype entry for non-dropped column");
4666 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4667 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4668 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4672 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4681 * convert_value_to_string Convert a non-null Datum to C string
4683 * Note: callers generally assume that the result is a palloc'd string and
4684 * should be pfree'd. This is not all that safe an assumption ...
4686 * Note: not caching the conversion function lookup is bad for performance.
4690 convert_value_to_string(Datum value, Oid valtype)
4696 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4699 * We do SPI_push to allow the datatype output function to use SPI.
4700 * However we do not mess around with CommandCounterIncrement or advancing
4701 * the snapshot, which means that a stable output function would not see
4702 * updates made so far by our own function. The use-case for such
4703 * scenarios seems too narrow to justify the cycles that would be
4708 str = OidOutputFunctionCall(typoutput, value);
4716 * exec_cast_value Cast a value if required
4720 exec_cast_value(Datum value, Oid valtype,
4728 * If the type of the queries return value isn't that of the variable,
4731 if (valtype != reqtype || reqtypmod != -1)
4737 extval = convert_value_to_string(value, valtype);
4739 /* Allow input function to use SPI ... see notes above */
4742 value = InputFunctionCall(reqinput, extval,
4743 reqtypioparam, reqtypmod);
4753 value = InputFunctionCall(reqinput, NULL,
4754 reqtypioparam, reqtypmod);
4764 * exec_simple_cast_value Cast a value if required
4766 * As above, but need not supply details about target type. Note that this
4767 * is slower than exec_cast_value with cached type info, and so should be
4768 * avoided in heavily used code paths.
4772 exec_simple_cast_value(Datum value, Oid valtype,
4773 Oid reqtype, int32 reqtypmod,
4778 if (valtype != reqtype || reqtypmod != -1)
4782 FmgrInfo finfo_input;
4784 getTypeInputInfo(reqtype, &typinput, &typioparam);
4786 fmgr_info(typinput, &finfo_input);
4788 value = exec_cast_value(value,
4803 * exec_simple_check_node - Recursively check if an expression
4804 * is made only of simple things we can
4805 * hand out directly to ExecEvalExpr()
4806 * instead of calling SPI.
4810 exec_simple_check_node(Node *node)
4815 switch (nodeTag(node))
4825 ArrayRef *expr = (ArrayRef *) node;
4827 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4829 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4831 if (!exec_simple_check_node((Node *) expr->refexpr))
4833 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4841 FuncExpr *expr = (FuncExpr *) node;
4843 if (expr->funcretset)
4845 if (!exec_simple_check_node((Node *) expr->args))
4853 OpExpr *expr = (OpExpr *) node;
4857 if (!exec_simple_check_node((Node *) expr->args))
4863 case T_DistinctExpr:
4865 DistinctExpr *expr = (DistinctExpr *) node;
4869 if (!exec_simple_check_node((Node *) expr->args))
4875 case T_ScalarArrayOpExpr:
4877 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4879 if (!exec_simple_check_node((Node *) expr->args))
4887 BoolExpr *expr = (BoolExpr *) node;
4889 if (!exec_simple_check_node((Node *) expr->args))
4896 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4900 FieldStore *expr = (FieldStore *) node;
4902 if (!exec_simple_check_node((Node *) expr->arg))
4904 if (!exec_simple_check_node((Node *) expr->newvals))
4911 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4914 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
4916 case T_ArrayCoerceExpr:
4917 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
4919 case T_ConvertRowtypeExpr:
4920 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4924 CaseExpr *expr = (CaseExpr *) node;
4926 if (!exec_simple_check_node((Node *) expr->arg))
4928 if (!exec_simple_check_node((Node *) expr->args))
4930 if (!exec_simple_check_node((Node *) expr->defresult))
4938 CaseWhen *when = (CaseWhen *) node;
4940 if (!exec_simple_check_node((Node *) when->expr))
4942 if (!exec_simple_check_node((Node *) when->result))
4948 case T_CaseTestExpr:
4953 ArrayExpr *expr = (ArrayExpr *) node;
4955 if (!exec_simple_check_node((Node *) expr->elements))
4963 RowExpr *expr = (RowExpr *) node;
4965 if (!exec_simple_check_node((Node *) expr->args))
4971 case T_RowCompareExpr:
4973 RowCompareExpr *expr = (RowCompareExpr *) node;
4975 if (!exec_simple_check_node((Node *) expr->largs))
4977 if (!exec_simple_check_node((Node *) expr->rargs))
4983 case T_CoalesceExpr:
4985 CoalesceExpr *expr = (CoalesceExpr *) node;
4987 if (!exec_simple_check_node((Node *) expr->args))
4995 MinMaxExpr *expr = (MinMaxExpr *) node;
4997 if (!exec_simple_check_node((Node *) expr->args))
5005 XmlExpr *expr = (XmlExpr *) node;
5007 if (!exec_simple_check_node((Node *) expr->named_args))
5009 if (!exec_simple_check_node((Node *) expr->args))
5017 NullIfExpr *expr = (NullIfExpr *) node;
5021 if (!exec_simple_check_node((Node *) expr->args))
5028 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5031 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5033 case T_CoerceToDomain:
5034 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5036 case T_CoerceToDomainValue:
5041 List *expr = (List *) node;
5046 if (!exec_simple_check_node(lfirst(l)))
5060 * exec_simple_check_plan - Check if a plan is simple enough to
5061 * be evaluated by ExecEvalExpr() instead
5066 exec_simple_check_plan(PLpgSQL_expr *expr)
5068 CachedPlanSource *plansource;
5074 * Initialize to "not simple", and remember the plan generation number we
5075 * last checked. (If the query produces more or less than one parsetree
5076 * we just leave expr_simple_generation set to 0.)
5078 expr->expr_simple_expr = NULL;
5079 expr->expr_simple_generation = 0;
5082 * 1. We can only evaluate queries that resulted in one single execution
5085 if (list_length(expr->plan->plancache_list) != 1)
5087 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
5088 expr->expr_simple_generation = plansource->generation;
5089 if (list_length(plansource->plan->stmt_list) != 1)
5092 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
5095 * 2. It must be a RESULT plan --> no scan's required
5097 if (!IsA(stmt, PlannedStmt))
5099 plan = stmt->planTree;
5100 if (!IsA(plan, Result))
5104 * 3. Can't have any subplan or qual clause, either
5106 if (plan->lefttree != NULL ||
5107 plan->righttree != NULL ||
5108 plan->initPlan != NULL ||
5109 plan->qual != NULL ||
5110 ((Result *) plan)->resconstantqual != NULL)
5114 * 4. The plan must have a single attribute as result
5116 if (list_length(plan->targetlist) != 1)
5119 tle = (TargetEntry *) linitial(plan->targetlist);
5122 * 5. Check that all the nodes in the expression are non-scary.
5124 if (!exec_simple_check_node((Node *) tle->expr))
5128 * Yes - this is a simple expression. Mark it as such, and initialize
5129 * state to "not valid in current transaction".
5131 expr->expr_simple_expr = tle->expr;
5132 expr->expr_simple_state = NULL;
5133 expr->expr_simple_id = -1;
5134 /* Also stash away the expression result type */
5135 expr->expr_simple_type = exprType((Node *) tle->expr);
5139 * Check two tupledescs have matching number and types of attributes
5142 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
5146 if (td1->natts != td2->natts)
5149 for (i = 0; i < td1->natts; i++)
5151 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
5159 * exec_set_found Set the global found variable
5164 exec_set_found(PLpgSQL_execstate *estate, bool state)
5168 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
5169 var->value = PointerGetDatum(state);
5170 var->isnull = false;
5174 * plpgsql_create_econtext --- create an eval_econtext for the current function
5176 * We may need to create a new eval_estate too, if there's not one already
5177 * for the current (sub) transaction. The EState will be cleaned up at
5178 * (sub) transaction end.
5181 plpgsql_create_econtext(PLpgSQL_execstate *estate)
5183 SubTransactionId my_subxid = GetCurrentSubTransactionId();
5184 SimpleEstateStackEntry *entry = simple_estate_stack;
5186 /* Create new EState if not one for current subxact */
5187 if (entry == NULL ||
5188 entry->xact_subxid != my_subxid)
5190 MemoryContext oldcontext;
5192 /* Stack entries are kept in TopTransactionContext for simplicity */
5193 entry = (SimpleEstateStackEntry *)
5194 MemoryContextAlloc(TopTransactionContext,
5195 sizeof(SimpleEstateStackEntry));
5197 /* But each EState should be a child of its CurTransactionContext */
5198 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
5199 entry->xact_eval_estate = CreateExecutorState();
5200 MemoryContextSwitchTo(oldcontext);
5202 /* Assign a reasonably-unique ID to this EState */
5203 entry->xact_estate_simple_id = simple_estate_id_counter++;
5204 entry->xact_subxid = my_subxid;
5206 entry->next = simple_estate_stack;
5207 simple_estate_stack = entry;
5210 /* Link plpgsql estate to it */
5211 estate->eval_estate = entry->xact_eval_estate;
5212 estate->eval_estate_simple_id = entry->xact_estate_simple_id;
5214 /* And create a child econtext for the current function */
5215 estate->eval_econtext = CreateExprContext(estate->eval_estate);
5219 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5221 * If a simple-expression EState was created in the current transaction,
5222 * it has to be cleaned up.
5225 plpgsql_xact_cb(XactEvent event, void *arg)
5228 * If we are doing a clean transaction shutdown, free the EState (so that
5229 * any remaining resources will be released correctly). In an abort, we
5230 * expect the regular abort recovery procedures to release everything of
5231 * interest. We don't need to free the individual stack entries since
5232 * TopTransactionContext is about to go away anyway.
5234 * Note: if plpgsql_subxact_cb is doing its job, there should be at most
5235 * one stack entry, but we may as well code this as a loop.
5237 if (event != XACT_EVENT_ABORT)
5239 while (simple_estate_stack != NULL)
5241 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5242 simple_estate_stack = simple_estate_stack->next;
5246 simple_estate_stack = NULL;
5250 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5252 * If a simple-expression EState was created in the current subtransaction,
5253 * it has to be cleaned up.
5256 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5257 SubTransactionId parentSubid, void *arg)
5259 if (event == SUBXACT_EVENT_START_SUB)
5262 if (simple_estate_stack != NULL &&
5263 simple_estate_stack->xact_subxid == mySubid)
5265 SimpleEstateStackEntry *next;
5267 if (event == SUBXACT_EVENT_COMMIT_SUB)
5268 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5269 next = simple_estate_stack->next;
5270 pfree(simple_estate_stack);
5271 simple_estate_stack = next;
5276 * free_var --- pfree any pass-by-reference value of the variable.
5278 * This should always be followed by some assignment to var->value,
5279 * as it leaves a dangling pointer.
5282 free_var(PLpgSQL_var *var)
5286 pfree(DatumGetPointer(var->value));
5287 var->freeval = false;
5292 * free old value of a text variable and assign new value from C string
5295 assign_text_var(PLpgSQL_var *var, const char *str)
5298 var->value = CStringGetTextDatum(str);
5299 var->isnull = false;
5300 var->freeval = true;
5304 * exec_eval_using_params --- evaluate params of USING clause
5306 static PreparedParamsData *
5307 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
5309 PreparedParamsData *ppd;
5314 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
5315 nargs = list_length(params);
5318 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
5319 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
5320 ppd->nulls = (char *) palloc(nargs * sizeof(char));
5321 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
5326 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
5329 ppd->values[i] = exec_eval_expr(estate, param,
5332 ppd->nulls[i] = isnull ? 'n' : ' ';
5333 ppd->freevals[i] = false;
5335 /* pass-by-ref non null values must be copied into plpgsql context */
5341 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
5344 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
5345 ppd->freevals[i] = true;
5349 exec_eval_cleanup(estate);
5358 * free_params_data --- pfree all pass-by-reference values used in USING clause
5361 free_params_data(PreparedParamsData *ppd)
5365 for (i = 0; i < ppd->nargs; i++)
5367 if (ppd->freevals[i])
5368 pfree(DatumGetPointer(ppd->values[i]));
5374 pfree(ppd->freevals);
5380 * Open portal for dynamic query
5383 exec_dynquery_with_params(PLpgSQL_execstate *estate, PLpgSQL_expr *dynquery,
5393 * Evaluate the string expression after the EXECUTE keyword. Its result
5394 * is the querystring we have to execute.
5396 query = exec_eval_expr(estate, dynquery, &isnull, &restype);
5399 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5400 errmsg("cannot EXECUTE a null querystring")));
5402 /* Get the C-String representation */
5403 querystr = convert_value_to_string(query, restype);
5405 exec_eval_cleanup(estate);
5408 * Open an implicit cursor for the query. We use SPI_cursor_open_with_args
5409 * even when there are no params, because this avoids making and freeing
5410 * one copy of the plan.
5414 PreparedParamsData *ppd;
5416 ppd = exec_eval_using_params(estate, params);
5417 portal = SPI_cursor_open_with_args(NULL,
5419 ppd->nargs, ppd->types,
5420 ppd->values, ppd->nulls,
5421 estate->readonly_func, 0);
5422 free_params_data(ppd);
5426 portal = SPI_cursor_open_with_args(NULL,
5430 estate->readonly_func, 0);
5434 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5435 querystr, SPI_result_code_string(SPI_result));